answer
stringlengths
15
1.25M
<?php ?> <?php // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); ?> <?php echo FSS_Helper::PageStyle(); ?> <?php if (FSS_Helper::IsTests()) : ?> <?php echo FSS_Helper::PageTitle('COMMENT_MODERATION'); ?> <?php else: ?> <?php echo FSS_Helper::PageTitle('SUPPORT_ADMIN','COMMENT_MODERATION'); ?> <?php endif; ?> <?php //##NOT_TEST_START## ?> <?php include JPATH_SITE.DS.'components'.DS.'com_fss'.DS.'views'.DS.'admin'.DS.'snippet'.DS.'_tabbar.php'; //include "components/com_fss/views/admin/snippet/_tabbar.php" ?> <?php //##NOT_TEST_END## ?> <?php $this->comments->DisplayModerate(); ?> <?php include JPATH_SITE.DS.'components'.DS.'com_fss'.DS.'_powered.php'; ?> <?php echo FSS_Helper::PageStyleEnd(); ?>
#include "config.h" #include <stdlib.h> #include <gio/gio.h> #include <telepathy-glib/telepathy-glib.h> static GMainLoop *loop = NULL; static GList *channel_list = NULL; static void <API key> (TpChannel *channel, guint domain, gint code, gchar *message, gpointer user_data) { channel_list = g_list_remove (channel_list, channel); g_object_unref (channel); if (channel_list == NULL) g_main_loop_quit (loop); } static void session_complete (TpChannel *channel, const GError *error) { if (error != NULL) { g_debug ("Error for channel %p: %s", channel, error ? error->message : "No error message"); } <API key> (channel, NULL, NULL); } static void splice_cb (GObject *source_object, GAsyncResult *res, gpointer channel) { GError *error = NULL; <API key> (res, &error); session_complete (channel, error); g_clear_error (&error); } static void accept_tube_cb (GObject *object, GAsyncResult *res, gpointer user_data) { TpChannel *channel = TP_CHANNEL (object); <API key> *stc; GInetAddress *inet_address = NULL; GSocketAddress *socket_address = NULL; GSocket *socket = NULL; GSocketConnection *tube_connection = NULL; GSocketConnection *sshd_connection = NULL; GError *error = NULL; stc = <API key> (<API key> (channel), res, &error); if (stc == NULL) goto OUT; tube_connection = <API key> (stc); /* Connect to the sshd */ inet_address = <API key> (<API key>); socket_address = <API key> (inet_address, 22); socket = g_socket_new (<API key>, <API key>, <API key>, &error); if (socket == NULL) goto OUT; if (!g_socket_connect (socket, socket_address, NULL, &error)) goto OUT; sshd_connection = <API key> (socket); /* Splice tube and ssh connections */ <API key> (G_IO_STREAM (tube_connection), G_IO_STREAM (sshd_connection), <API key>, G_PRIORITY_DEFAULT, NULL, splice_cb, channel); OUT: if (error != NULL) session_complete (channel, error); tp_clear_object (&stc); tp_clear_object (&inet_address); tp_clear_object (&socket_address); tp_clear_object (&socket); tp_clear_object (&sshd_connection); g_clear_error (&error); } static void got_channel_cb (TpSimpleHandler *handler, TpAccount *account, TpConnection *connection, GList *channels, GList *requests_satisfied, gint64 user_action_time, <API key> *context, gpointer user_data) { GList *l; for (l = channels; l != NULL; l = l->next) { if (<API key> (l->data)) { TpStreamTubeChannel *channel = l->data; channel_list = g_list_prepend (channel_list, g_object_ref (channel)); g_signal_connect (channel, "invalidated", G_CALLBACK (<API key>), NULL); <API key> (channel, accept_tube_cb, NULL); } } <API key> (context); } int main (gint argc, gchar *argv[]) { TpDBusDaemon *dbus = NULL; <API key> *factory = NULL; TpBaseClient *client = NULL; gboolean success = TRUE; GError *error = NULL; g_type_init (); tp_debug_set_flags (g_getenv ("SSH_CONTACT_DEBUG")); dbus = tp_dbus_daemon_dup (&error); if (dbus == NULL) goto OUT; factory = (<API key> *) <API key> (dbus); client = <API key> (factory, FALSE, FALSE, "SSHContact", FALSE, got_channel_cb, NULL, NULL); <API key> (client, tp_asv_new ( <API key>, G_TYPE_STRING, <API key>, <API key>, G_TYPE_UINT, <API key>, <API key>, G_TYPE_STRING, TUBE_SERVICE, <API key>, G_TYPE_BOOLEAN, FALSE, NULL)); if (!<API key> (client, &error)) goto OUT; loop = g_main_loop_new (NULL, FALSE); g_main_loop_run (loop); OUT: if (error != NULL) { g_debug ("Error: %s", error->message); success = FALSE; } tp_clear_pointer (&loop, g_main_loop_unref); tp_clear_object (&dbus); tp_clear_object (&factory); tp_clear_object (&client); g_clear_error (&error); return success ? EXIT_SUCCESS : EXIT_FAILURE; }
var Behaviour = { list : new Array, register : function(sheet){ Behaviour.list.push(sheet); }, start : function(){ Behaviour.addLoadEvent(function(){ Behaviour.apply(); }); }, apply : function(){ for (h=0;sheet=Behaviour.list[h];h++){ for (selector in sheet){ var sels = selector.split(','); for (var n = 0; n < sels.length; n++) { list = document.<API key>(sels[n]); if (!list){ continue; } for (i=0;element=list[i];i++){ sheet[selector](element); } } } } }, addLoadEvent : function(func){ var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); } } } } Behaviour.start(); function getAllChildren(e) { // Returns all children of element. Workaround required for IE5/Windows. Ugh. return e.all ? e.all : e.<API key>('*'); } document.<API key> = function(selector) { // Attempt to fail gracefully in lesser browsers if (!document.<API key>) { return new Array(); } // Split selector in to tokens var tokens = selector.split(' '); var currentContext = new Array(document); for (var i = 0; i < tokens.length; i++) { token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');; if (token.indexOf(' // Token is an ID selector var bits = token.split(' var tagName = bits[0]; var id = bits[1]; var element = document.getElementById(id); if (tagName && element.nodeName.toLowerCase() != tagName) { // tag with that ID not found, return false return new Array(); } // Set currentContext to contain just this element currentContext = new Array(element); continue; // Skip to next token } if (token.indexOf('.') > -1) { // Token contains a class selector var bits = token.split('.'); var tagName = bits[0]; var className = bits[1]; if (!tagName) { tagName = '*'; } // Get elements matching tag, filter them for class selector var found = new Array; var foundCount = 0; for (var h = 0; h < currentContext.length; h++) { var elements; if (tagName == '*') { elements = getAllChildren(currentContext[h]); } else { elements = currentContext[h].<API key>(tagName); } for (var j = 0; j < elements.length; j++) { found[foundCount++] = elements[j]; } } currentContext = new Array; var currentContextIndex = 0; for (var k = 0; k < found.length; k++) { if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) { currentContext[currentContextIndex++] = found[k]; } } continue; // Skip to next token } // Code to deal with attribute selectors /* Original reg expression /^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/ was replaced by new RegExp() cuz compressor fault */ if (token.match(new RegExp('^(\\w*)\\[(\\w+)([=~\\|\\^\\$\\*]?)=?"?([^\\]"]*)"?\\]$'))) { var tagName = RegExp.$1; var attrName = RegExp.$2; var attrOperator = RegExp.$3; var attrValue = RegExp.$4; if (!tagName) { tagName = '*'; } // Grab all of the tagName elements within current context var found = new Array; var foundCount = 0; for (var h = 0; h < currentContext.length; h++) { var elements; if (tagName == '*') { elements = getAllChildren(currentContext[h]); } else { elements = currentContext[h].<API key>(tagName); } for (var j = 0; j < elements.length; j++) { found[foundCount++] = elements[j]; } } currentContext = new Array; var currentContextIndex = 0; var checkFunction; // This function will be used to filter the elements switch (attrOperator) { case '=': // Equality checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); }; break; case '~': // Match one of space seperated words checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.match(new RegExp('\\b'+attrValue+'\\b'))); }; break; case '|': // Match start with value followed by optional hyphen checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.match(new RegExp('^'+attrValue+'-?'))); }; break; case '^': // Match starts with value checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.indexOf(attrValue) == 0); }; break; case '$': // Match ends with value - fails with "Warning" in Opera 7 checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); }; break; case '*': // Match contains value checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.indexOf(attrValue) > -1); }; break; default : // Just test for existence of attribute checkFunction = function(e) { return e.getAttribute(attrName); }; } currentContext = new Array; var currentContextIndex = 0; for (var k = 0; k < found.length; k++) { if (checkFunction(found[k])) { currentContext[currentContextIndex++] = found[k]; } } // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue); continue; // Skip to next token } if (!currentContext[0]){ return; } // If we get here, token is JUST an element (not a class or ID selector) tagName = token; var found = new Array; var foundCount = 0; for (var h = 0; h < currentContext.length; h++) { var elements = currentContext[h].<API key>(tagName); for (var j = 0; j < elements.length; j++) { found[foundCount++] = elements[j]; } } currentContext = found; } return currentContext; }
#include "common/common.h" #include "macroblock.h" /* These chroma DC functions don't have assembly versions and are only used here. */ #define ZIG(i,y,x) level[i] = dct[x*2+y]; static inline void zigzag_scan_2x2_dc( dctcoef level[4], dctcoef dct[4] ) { ZIG(0,0,0) ZIG(1,0,1) ZIG(2,1,0) ZIG(3,1,1) } #undef ZIG static inline void zigzag_scan_2x4_dc( dctcoef level[8], dctcoef dct[8] ) { level[0] = dct[0]; level[1] = dct[2]; level[2] = dct[1]; level[3] = dct[4]; level[4] = dct[6]; level[5] = dct[3]; level[6] = dct[5]; level[7] = dct[7]; } #define <API key> \ int d0 = dct[0] + dct[1]; \ int d1 = dct[2] + dct[3]; \ int d2 = dct[0] - dct[1]; \ int d3 = dct[2] - dct[3]; \ int dmf = dequant_mf[i_qp%6][0] << i_qp/6; static inline void idct_dequant_2x2_dc( dctcoef dct[4], dctcoef dct4x4[4][16], int dequant_mf[6][16], int i_qp ) { <API key> dct4x4[0][0] = (d0 + d1) * dmf >> 5; dct4x4[1][0] = (d0 - d1) * dmf >> 5; dct4x4[2][0] = (d2 + d3) * dmf >> 5; dct4x4[3][0] = (d2 - d3) * dmf >> 5; } static inline void <API key>( dctcoef dct[4], int dequant_mf[6][16], int i_qp ) { <API key> dct[0] = (d0 + d1) * dmf >> 5; dct[1] = (d0 - d1) * dmf >> 5; dct[2] = (d2 + d3) * dmf >> 5; dct[3] = (d2 - d3) * dmf >> 5; } #undef <API key> static inline void dct2x2dc( dctcoef d[4], dctcoef dct4x4[4][16] ) { int d0 = dct4x4[0][0] + dct4x4[1][0]; int d1 = dct4x4[2][0] + dct4x4[3][0]; int d2 = dct4x4[0][0] - dct4x4[1][0]; int d3 = dct4x4[2][0] - dct4x4[3][0]; d[0] = d0 + d1; d[2] = d2 + d3; d[1] = d0 - d1; d[3] = d2 - d3; dct4x4[0][0] = 0; dct4x4[1][0] = 0; dct4x4[2][0] = 0; dct4x4[3][0] = 0; } static ALWAYS_INLINE int array_non_zero( dctcoef *v, int i_count ) { if( WORD_SIZE == 8 ) { for( int i = 0; i < i_count; i += 8/sizeof(dctcoef) ) if( M64( &v[i] ) ) return 1; } else { for( int i = 0; i < i_count; i += 4/sizeof(dctcoef) ) if( M32( &v[i] ) ) return 1; } return 0; } /* All encoding functions must output the correct CBP and NNZ values. * The entropy coding functions will check CBP first, then NNZ, before * actually reading the DCT coefficients. NNZ still must be correct even * if CBP is zero because of the use of NNZ values for context selection. * "NNZ" need only be 0 or 1 rather than the exact coefficient count because * that is only needed in CAVLC, and will be calculated by CAVLC's residual * coding and stored as necessary. */ /* This means that decimation can be done merely by adjusting the CBP and NNZ * rather than memsetting the coefficients. */ static void <API key>( x264_t *h, int p, int i_qp ) { pixel *p_src = h->mb.pic.p_fenc[p]; pixel *p_dst = h->mb.pic.p_fdec[p]; ALIGNED_ARRAY_32( dctcoef, dct4x4,[16],[16] ); ALIGNED_ARRAY_32( dctcoef, dct_dc4x4,[16] ); int nz, block_cbp = 0; int decimate_score = h->mb.b_dct_decimate ? 0 : 9; int i_quant_cat = p ? CQM_4IC : CQM_4IY; int i_mode = h->mb.<API key>; if( h->mb.b_lossless ) <API key>( h, p, i_mode ); else h->predict_16x16[i_mode]( h->mb.pic.p_fdec[p] ); if( h->mb.b_lossless ) { for( int i = 0; i < 16; i++ ) { int oe = block_idx_xy_fenc[i]; int od = block_idx_xy_fdec[i]; nz = h->zigzagf.sub_4x4ac( h->dct.luma4x4[16*p+i], p_src+oe, p_dst+od, &dct_dc4x4[block_idx_yx_1d[i]] ); h->mb.cache.non_zero_count[x264_scan8[16*p+i]] = nz; block_cbp |= nz; } h->mb.i_cbp_luma |= block_cbp * 0xf; h->mb.cache.non_zero_count[x264_scan8[LUMA_DC+p]] = array_non_zero( dct_dc4x4, 16 ); h->zigzagf.scan_4x4( h->dct.luma16x16_dc[p], dct_dc4x4 ); return; } CLEAR_16x16_NNZ( p ); h->dctf.sub16x16_dct( dct4x4, p_src, p_dst ); if( h->mb.b_noise_reduction ) for( int idx = 0; idx < 16; idx++ ) h->quantf.denoise_dct( dct4x4[idx], h->nr_residual_sum[0], h->nr_offset[0], 16 ); for( int idx = 0; idx < 16; idx++ ) { dct_dc4x4[block_idx_xy_1d[idx]] = dct4x4[idx][0]; dct4x4[idx][0] = 0; } if( h->mb.b_trellis ) { for( int idx = 0; idx < 16; idx++ ) if( <API key>( h, dct4x4[idx], i_quant_cat, i_qp, ctx_cat_plane[DCT_LUMA_AC][p], 1, !!p, idx ) ) { block_cbp = 0xf; h->zigzagf.scan_4x4( h->dct.luma4x4[16*p+idx], dct4x4[idx] ); h->quantf.dequant_4x4( dct4x4[idx], h->dequant4_mf[i_quant_cat], i_qp ); if( decimate_score < 6 ) decimate_score += h->quantf.decimate_score15( h->dct.luma4x4[16*p+idx] ); h->mb.cache.non_zero_count[x264_scan8[16*p+idx]] = 1; } } else { for( int i8x8 = 0; i8x8 < 4; i8x8++ ) { nz = h->quantf.quant_4x4x4( &dct4x4[i8x8*4], h->quant4_mf[i_quant_cat][i_qp], h->quant4_bias[i_quant_cat][i_qp] ); if( nz ) { block_cbp = 0xf; FOREACH_BIT( idx, i8x8*4, nz ) { h->zigzagf.scan_4x4( h->dct.luma4x4[16*p+idx], dct4x4[idx] ); h->quantf.dequant_4x4( dct4x4[idx], h->dequant4_mf[i_quant_cat], i_qp ); if( decimate_score < 6 ) decimate_score += h->quantf.decimate_score15( h->dct.luma4x4[16*p+idx] ); h->mb.cache.non_zero_count[x264_scan8[16*p+idx]] = 1; } } } } /* Writing the 16 CBFs in an i16x16 block is quite costly, so decimation can save many bits. */ /* More useful with CAVLC, but still useful with CABAC. */ if( decimate_score < 6 ) { CLEAR_16x16_NNZ( p ); block_cbp = 0; } else h->mb.i_cbp_luma |= block_cbp; h->dctf.dct4x4dc( dct_dc4x4 ); if( h->mb.b_trellis ) nz = <API key>( h, dct_dc4x4, i_quant_cat, i_qp, ctx_cat_plane[DCT_LUMA_DC][p], 1, LUMA_DC+p ); else nz = h->quantf.quant_4x4_dc( dct_dc4x4, h->quant4_mf[i_quant_cat][i_qp][0]>>1, h->quant4_bias[i_quant_cat][i_qp][0]<<1 ); h->mb.cache.non_zero_count[x264_scan8[LUMA_DC+p]] = nz; if( nz ) { h->zigzagf.scan_4x4( h->dct.luma16x16_dc[p], dct_dc4x4 ); /* output samples to fdec */ h->dctf.idct4x4dc( dct_dc4x4 ); h->quantf.dequant_4x4_dc( dct_dc4x4, h->dequant4_mf[i_quant_cat], i_qp ); /* XXX not inversed */ if( block_cbp ) for( int i = 0; i < 16; i++ ) dct4x4[i][0] = dct_dc4x4[block_idx_xy_1d[i]]; } /* put pixels to fdec */ if( block_cbp ) h->dctf.add16x16_idct( p_dst, dct4x4 ); else if( nz ) h->dctf.add16x16_idct_dc( p_dst, dct_dc4x4 ); } /* Round down coefficients losslessly in DC-only chroma blocks. * Unlike luma blocks, this can't be done with a lookup table or * other shortcut technique because of the interdependencies * between the coefficients due to the chroma DC transform. */ static ALWAYS_INLINE int <API key>( x264_t *h, dctcoef *dct_dc, int dequant_mf[6][16], int i_qp, int chroma422 ) { int dmf = dequant_mf[i_qp%6][0] << i_qp/6; /* If the QP is too high, there's no benefit to rounding optimization. */ if( dmf > 32*64 ) return 1; if( chroma422 ) return h->quantf.<API key>( dct_dc, dmf ); else return h->quantf.<API key>( dct_dc, dmf ); } static ALWAYS_INLINE void <API key>( x264_t *h, int b_inter, int i_qp, int chroma422 ) { int nz, nz_dc; int b_decimate = b_inter && h->mb.b_dct_decimate; int (*dequant_mf)[16] = h->dequant4_mf[CQM_4IC + b_inter]; ALIGNED_ARRAY_16( dctcoef, dct_dc,[8] ); h->mb.i_cbp_chroma = 0; h->nr_count[2] += h->mb.b_noise_reduction * 4; M16( &h->mb.cache.non_zero_count[x264_scan8[16]] ) = 0; M16( &h->mb.cache.non_zero_count[x264_scan8[18]] ) = 0; M16( &h->mb.cache.non_zero_count[x264_scan8[32]] ) = 0; M16( &h->mb.cache.non_zero_count[x264_scan8[34]] ) = 0; if( chroma422 ) { M16( &h->mb.cache.non_zero_count[x264_scan8[24]] ) = 0; M16( &h->mb.cache.non_zero_count[x264_scan8[26]] ) = 0; M16( &h->mb.cache.non_zero_count[x264_scan8[40]] ) = 0; M16( &h->mb.cache.non_zero_count[x264_scan8[42]] ) = 0; } /* Early termination: check variance of chroma residual before encoding. * Don't bother trying early termination at low QPs. * Values are experimentally derived. */ if( b_decimate && i_qp >= (h->mb.b_trellis ? 12 : 18) && !h->mb.b_noise_reduction ) { int thresh = chroma422 ? (x264_lambda2_tab[i_qp] + 16) >> 5 : (x264_lambda2_tab[i_qp] + 32) >> 6; int ssd[2]; int chromapix = chroma422 ? PIXEL_8x16 : PIXEL_8x8; int score = h->pixf.var2[chromapix]( h->mb.pic.p_fenc[1], FENC_STRIDE, h->mb.pic.p_fdec[1], FDEC_STRIDE, &ssd[0] ); if( score < thresh*4 ) score += h->pixf.var2[chromapix]( h->mb.pic.p_fenc[2], FENC_STRIDE, h->mb.pic.p_fdec[2], FDEC_STRIDE, &ssd[1] ); if( score < thresh*4 ) { h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+0]] = 0; h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+1]] = 0; for( int ch = 0; ch < 2; ch++ ) { if( ssd[ch] > thresh ) { pixel *p_src = h->mb.pic.p_fenc[1+ch]; pixel *p_dst = h->mb.pic.p_fdec[1+ch]; if( chroma422 ) /* Cannot be replaced by two calls to sub8x8_dct_dc since the hadamard transform is different */ h->dctf.sub8x16_dct_dc( dct_dc, p_src, p_dst ); else h->dctf.sub8x8_dct_dc( dct_dc, p_src, p_dst ); if( h->mb.b_trellis ) nz_dc = <API key>( h, dct_dc, i_qp+3*chroma422, !b_inter, CHROMA_DC+ch ); else { nz_dc = 0; for( int i = 0; i <= chroma422; i++ ) nz_dc |= h->quantf.quant_2x2_dc( &dct_dc[4*i], h->quant4_mf[CQM_4IC+b_inter][i_qp+3*chroma422][0] >> 1, h->quant4_bias[CQM_4IC+b_inter][i_qp+3*chroma422][0] << 1 ); } if( nz_dc ) { if( !<API key>( h, dct_dc, dequant_mf, i_qp+3*chroma422, chroma422 ) ) continue; h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+ch]] = 1; if( chroma422 ) { zigzag_scan_2x4_dc( h->dct.chroma_dc[ch], dct_dc ); h->quantf.<API key>( dct_dc, dequant_mf, i_qp+3 ); } else { zigzag_scan_2x2_dc( h->dct.chroma_dc[ch], dct_dc ); <API key>( dct_dc, dequant_mf, i_qp ); } for( int i = 0; i <= chroma422; i++ ) h->dctf.add8x8_idct_dc( p_dst + 8*i*FDEC_STRIDE, &dct_dc[4*i] ); h->mb.i_cbp_chroma = 1; } } } return; } } for( int ch = 0; ch < 2; ch++ ) { pixel *p_src = h->mb.pic.p_fenc[1+ch]; pixel *p_dst = h->mb.pic.p_fdec[1+ch]; int i_decimate_score = b_decimate ? 0 : 7; int nz_ac = 0; ALIGNED_ARRAY_32( dctcoef, dct4x4,[8],[16] ); if( h->mb.b_lossless ) { static const uint8_t chroma422_scan[8] = { 0, 2, 1, 5, 3, 6, 4, 7 }; for( int i = 0; i < (chroma422?8:4); i++ ) { int oe = 4*(i&1) + 4*(i>>1)*FENC_STRIDE; int od = 4*(i&1) + 4*(i>>1)*FDEC_STRIDE; nz = h->zigzagf.sub_4x4ac( h->dct.luma4x4[16+i+(chroma422?i&4:0)+ch*16], p_src+oe, p_dst+od, &h->dct.chroma_dc[ch][chroma422?chroma422_scan[i]:i] ); h->mb.cache.non_zero_count[x264_scan8[16+i+(chroma422?i&4:0)+ch*16]] = nz; h->mb.i_cbp_chroma |= nz; } h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+ch]] = array_non_zero( h->dct.chroma_dc[ch], chroma422?8:4 ); continue; } for( int i = 0; i <= chroma422; i++ ) h->dctf.sub8x8_dct( &dct4x4[4*i], p_src + 8*i*FENC_STRIDE, p_dst + 8*i*FDEC_STRIDE ); if( h->mb.b_noise_reduction ) for( int i = 0; i < (chroma422?8:4); i++ ) h->quantf.denoise_dct( dct4x4[i], h->nr_residual_sum[2], h->nr_offset[2], 16 ); if( chroma422 ) h->dctf.dct2x4dc( dct_dc, dct4x4 ); else dct2x2dc( dct_dc, dct4x4 ); /* calculate dct coeffs */ for( int i8x8 = 0; i8x8 < (chroma422?2:1); i8x8++ ) { if( h->mb.b_trellis ) { for( int i4x4 = 0; i4x4 < 4; i4x4++ ) { if( <API key>( h, dct4x4[i8x8*4+i4x4], CQM_4IC+b_inter, i_qp, DCT_CHROMA_AC, !b_inter, 1, 0 ) ) { int idx = 16+ch*16+i8x8*8+i4x4; h->zigzagf.scan_4x4( h->dct.luma4x4[idx], dct4x4[i8x8*4+i4x4] ); h->quantf.dequant_4x4( dct4x4[i8x8*4+i4x4], dequant_mf, i_qp ); if( i_decimate_score < 7 ) i_decimate_score += h->quantf.decimate_score15( h->dct.luma4x4[idx] ); h->mb.cache.non_zero_count[x264_scan8[idx]] = 1; nz_ac = 1; } } } else { nz = h->quantf.quant_4x4x4( &dct4x4[i8x8*4], h->quant4_mf[CQM_4IC+b_inter][i_qp], h->quant4_bias[CQM_4IC+b_inter][i_qp] ); nz_ac |= nz; FOREACH_BIT( i4x4, 0, nz ) { int idx = 16+ch*16+i8x8*8+i4x4; h->zigzagf.scan_4x4( h->dct.luma4x4[idx], dct4x4[i8x8*4+i4x4] ); h->quantf.dequant_4x4( dct4x4[i8x8*4+i4x4], dequant_mf, i_qp ); if( i_decimate_score < 7 ) i_decimate_score += h->quantf.decimate_score15( h->dct.luma4x4[idx] ); h->mb.cache.non_zero_count[x264_scan8[idx]] = 1; } } } if( h->mb.b_trellis ) nz_dc = <API key>( h, dct_dc, i_qp+3*chroma422, !b_inter, CHROMA_DC+ch ); else { nz_dc = 0; for( int i = 0; i <= chroma422; i++ ) nz_dc |= h->quantf.quant_2x2_dc( &dct_dc[4*i], h->quant4_mf[CQM_4IC+b_inter][i_qp+3*chroma422][0] >> 1, h->quant4_bias[CQM_4IC+b_inter][i_qp+3*chroma422][0] << 1 ); } h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+ch]] = nz_dc; if( i_decimate_score < 7 || !nz_ac ) { /* Decimate the block */ M16( &h->mb.cache.non_zero_count[x264_scan8[16+16*ch]] ) = 0; M16( &h->mb.cache.non_zero_count[x264_scan8[18+16*ch]] ) = 0; if( chroma422 ) { M16( &h->mb.cache.non_zero_count[x264_scan8[24+16*ch]] ) = 0; M16( &h->mb.cache.non_zero_count[x264_scan8[26+16*ch]] ) = 0; } if( !nz_dc ) /* Whole block is empty */ continue; if( !<API key>( h, dct_dc, dequant_mf, i_qp+3*chroma422, chroma422 ) ) { h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+ch]] = 0; continue; } /* DC-only */ if( chroma422 ) { zigzag_scan_2x4_dc( h->dct.chroma_dc[ch], dct_dc ); h->quantf.<API key>( dct_dc, dequant_mf, i_qp+3 ); } else { zigzag_scan_2x2_dc( h->dct.chroma_dc[ch], dct_dc ); <API key>( dct_dc, dequant_mf, i_qp ); } for( int i = 0; i <= chroma422; i++ ) h->dctf.add8x8_idct_dc( p_dst + 8*i*FDEC_STRIDE, &dct_dc[4*i] ); } else { h->mb.i_cbp_chroma = 1; if( nz_dc ) { if( chroma422 ) { zigzag_scan_2x4_dc( h->dct.chroma_dc[ch], dct_dc ); h->quantf.idct_dequant_2x4_dc( dct_dc, dct4x4, dequant_mf, i_qp+3 ); } else { zigzag_scan_2x2_dc( h->dct.chroma_dc[ch], dct_dc ); idct_dequant_2x2_dc( dct_dc, dct4x4, dequant_mf, i_qp ); } } for( int i = 0; i <= chroma422; i++ ) h->dctf.add8x8_idct( p_dst + 8*i*FDEC_STRIDE, &dct4x4[4*i] ); } } /* 0 = none, 1 = DC only, 2 = DC+AC */ h->mb.i_cbp_chroma += (h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+0]] | h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+1]] | h->mb.i_cbp_chroma); } void <API key>( x264_t *h, int b_inter, int i_qp ) { if( CHROMA_FORMAT == CHROMA_420 ) <API key>( h, b_inter, i_qp, 0 ); else <API key>( h, b_inter, i_qp, 1 ); } static void <API key>( x264_t *h ) { M32( &h->mb.cache.non_zero_count[x264_scan8[ 0]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[ 2]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[ 8]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[10]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[16+ 0]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[16+ 2]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[32+ 0]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[32+ 2]] ) = 0; if( CHROMA_FORMAT >= CHROMA_422 ) { M32( &h->mb.cache.non_zero_count[x264_scan8[16+ 8]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[16+10]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[32+ 8]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[32+10]] ) = 0; } h->mb.i_cbp_luma = 0; h->mb.i_cbp_chroma = 0; h->mb.cbp[h->mb.i_mb_xy] = 0; } void <API key>( x264_t *h, int i_mode ) { int height = 16 >> CHROMA_V_SHIFT; if( i_mode == I_PRED_CHROMA_V ) { h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fdec[1], FDEC_STRIDE, h->mb.pic.p_fenc[1]-FENC_STRIDE, FENC_STRIDE, height ); h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fdec[2], FDEC_STRIDE, h->mb.pic.p_fenc[2]-FENC_STRIDE, FENC_STRIDE, height ); memcpy( h->mb.pic.p_fdec[1], h->mb.pic.p_fdec[1]-FDEC_STRIDE, 8*sizeof(pixel) ); memcpy( h->mb.pic.p_fdec[2], h->mb.pic.p_fdec[2]-FDEC_STRIDE, 8*sizeof(pixel) ); } else if( i_mode == I_PRED_CHROMA_H ) { h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fdec[1], FDEC_STRIDE, h->mb.pic.p_fenc[1]-1, FENC_STRIDE, height ); h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fdec[2], FDEC_STRIDE, h->mb.pic.p_fenc[2]-1, FENC_STRIDE, height ); x264_copy_column8( h->mb.pic.p_fdec[1]+4*FDEC_STRIDE, h->mb.pic.p_fdec[1]+4*FDEC_STRIDE-1 ); x264_copy_column8( h->mb.pic.p_fdec[2]+4*FDEC_STRIDE, h->mb.pic.p_fdec[2]+4*FDEC_STRIDE-1 ); if( CHROMA_FORMAT == CHROMA_422 ) { x264_copy_column8( h->mb.pic.p_fdec[1]+12*FDEC_STRIDE, h->mb.pic.p_fdec[1]+12*FDEC_STRIDE-1 ); x264_copy_column8( h->mb.pic.p_fdec[2]+12*FDEC_STRIDE, h->mb.pic.p_fdec[2]+12*FDEC_STRIDE-1 ); } } else { h->predict_chroma[i_mode]( h->mb.pic.p_fdec[1] ); h->predict_chroma[i_mode]( h->mb.pic.p_fdec[2] ); } } void <API key>( x264_t *h, pixel *p_dst, int p, int idx, int i_mode ) { int stride = h->fenc->i_stride[p] << MB_INTERLACED; pixel *p_src = h->mb.pic.p_fenc_plane[p] + block_idx_x[idx]*4 + block_idx_y[idx]*4 * stride; if( i_mode == I_PRED_4x4_V ) h->mc.copy[PIXEL_4x4]( p_dst, FDEC_STRIDE, p_src-stride, stride, 4 ); else if( i_mode == I_PRED_4x4_H ) h->mc.copy[PIXEL_4x4]( p_dst, FDEC_STRIDE, p_src-1, stride, 4 ); else h->predict_4x4[i_mode]( p_dst ); } void <API key>( x264_t *h, pixel *p_dst, int p, int idx, int i_mode, pixel edge[36] ) { int stride = h->fenc->i_stride[p] << MB_INTERLACED; pixel *p_src = h->mb.pic.p_fenc_plane[p] + (idx&1)*8 + (idx>>1)*8*stride; if( i_mode == I_PRED_8x8_V ) h->mc.copy[PIXEL_8x8]( p_dst, FDEC_STRIDE, p_src-stride, stride, 8 ); else if( i_mode == I_PRED_8x8_H ) h->mc.copy[PIXEL_8x8]( p_dst, FDEC_STRIDE, p_src-1, stride, 8 ); else h->predict_8x8[i_mode]( p_dst, edge ); } void <API key>( x264_t *h, int p, int i_mode ) { int stride = h->fenc->i_stride[p] << MB_INTERLACED; if( i_mode == I_PRED_16x16_V ) h->mc.copy[PIXEL_16x16]( h->mb.pic.p_fdec[p], FDEC_STRIDE, h->mb.pic.p_fenc_plane[p]-stride, stride, 16 ); else if( i_mode == I_PRED_16x16_H ) h->mc.<API key>( h->mb.pic.p_fdec[p], FDEC_STRIDE, h->mb.pic.p_fenc_plane[p]-1, stride, 16 ); else h->predict_16x16[i_mode]( h->mb.pic.p_fdec[p] ); } static ALWAYS_INLINE void <API key>( x264_t *h, int plane_count, int chroma ) { int i_qp = h->mb.i_qp; int b_decimate = h->mb.b_dct_decimate; int b_force_no_skip = 0; int nz; h->mb.i_cbp_luma = 0; for( int p = 0; p < plane_count; p++ ) h->mb.cache.non_zero_count[x264_scan8[LUMA_DC+p]] = 0; if( h->mb.i_type == I_PCM ) { /* if PCM is chosen, we need to store reconstructed frame data */ for( int p = 0; p < plane_count; p++ ) h->mc.copy[PIXEL_16x16]( h->mb.pic.p_fdec[p], FDEC_STRIDE, h->mb.pic.p_fenc[p], FENC_STRIDE, 16 ); if( chroma ) { int height = 16 >> CHROMA_V_SHIFT; h->mc.copy[PIXEL_8x8] ( h->mb.pic.p_fdec[1], FDEC_STRIDE, h->mb.pic.p_fenc[1], FENC_STRIDE, height ); h->mc.copy[PIXEL_8x8] ( h->mb.pic.p_fdec[2], FDEC_STRIDE, h->mb.pic.p_fenc[2], FENC_STRIDE, height ); } return; } if( !h->mb.b_allow_skip ) { b_force_no_skip = 1; if( IS_SKIP(h->mb.i_type) ) { if( h->mb.i_type == P_SKIP ) h->mb.i_type = P_L0; else if( h->mb.i_type == B_SKIP ) h->mb.i_type = B_DIRECT; } } if( h->mb.i_type == P_SKIP ) { /* don't do pskip motion compensation if it was already done in macroblock_analyse */ if( !h->mb.b_skip_mc ) { int mvx = x264_clip3( h->mb.cache.mv[0][x264_scan8[0]][0], h->mb.mv_min[0], h->mb.mv_max[0] ); int mvy = x264_clip3( h->mb.cache.mv[0][x264_scan8[0]][1], h->mb.mv_min[1], h->mb.mv_max[1] ); for( int p = 0; p < plane_count; p++ ) h->mc.mc_luma( h->mb.pic.p_fdec[p], FDEC_STRIDE, &h->mb.pic.p_fref[0][0][p*4], h->mb.pic.i_stride[p], mvx, mvy, 16, 16, &h->sh.weight[0][p] ); if( chroma ) { int v_shift = CHROMA_V_SHIFT; int height = 16 >> v_shift; /* Special case for mv0, which is (of course) very common in P-skip mode. */ if( mvx | mvy ) h->mc.mc_chroma( h->mb.pic.p_fdec[1], h->mb.pic.p_fdec[2], FDEC_STRIDE, h->mb.pic.p_fref[0][0][4], h->mb.pic.i_stride[1], mvx, 2*mvy>>v_shift, 8, height ); else h->mc.<API key>( h->mb.pic.p_fdec[1], h->mb.pic.p_fref[0][0][4], h->mb.pic.i_stride[1], height ); if( h->sh.weight[0][1].weightfn ) h->sh.weight[0][1].weightfn[8>>2]( h->mb.pic.p_fdec[1], FDEC_STRIDE, h->mb.pic.p_fdec[1], FDEC_STRIDE, &h->sh.weight[0][1], height ); if( h->sh.weight[0][2].weightfn ) h->sh.weight[0][2].weightfn[8>>2]( h->mb.pic.p_fdec[2], FDEC_STRIDE, h->mb.pic.p_fdec[2], FDEC_STRIDE, &h->sh.weight[0][2], height ); } } <API key>( h ); return; } if( h->mb.i_type == B_SKIP ) { /* don't do bskip motion compensation if it was already done in macroblock_analyse */ if( !h->mb.b_skip_mc ) x264_mb_mc( h ); <API key>( h ); return; } if( h->mb.i_type == I_16x16 ) { h->mb.b_transform_8x8 = 0; for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) <API key>( h, p, i_qp ); } else if( h->mb.i_type == I_8x8 ) { h->mb.b_transform_8x8 = 1; /* If we already encoded 3 of the 4 i8x8 blocks, we don't have to do them again. */ if( h->mb.i_skip_intra ) { h->mc.copy[PIXEL_16x16]( h->mb.pic.p_fdec[0], FDEC_STRIDE, h->mb.pic.i8x8_fdec_buf, 16, 16 ); M32( &h->mb.cache.non_zero_count[x264_scan8[ 0]] ) = h->mb.pic.i8x8_nnz_buf[0]; M32( &h->mb.cache.non_zero_count[x264_scan8[ 2]] ) = h->mb.pic.i8x8_nnz_buf[1]; M32( &h->mb.cache.non_zero_count[x264_scan8[ 8]] ) = h->mb.pic.i8x8_nnz_buf[2]; M32( &h->mb.cache.non_zero_count[x264_scan8[10]] ) = h->mb.pic.i8x8_nnz_buf[3]; h->mb.i_cbp_luma = h->mb.pic.i8x8_cbp; /* In RD mode, restore the now-overwritten DCT data. */ if( h->mb.i_skip_intra == 2 ) h->mc.memcpy_aligned( h->dct.luma8x8, h->mb.pic.i8x8_dct_buf, sizeof(h->mb.pic.i8x8_dct_buf) ); } for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) { for( int i = (p == 0 && h->mb.i_skip_intra) ? 3 : 0; i < 4; i++ ) { int i_mode = h->mb.cache.intra4x4_pred_mode[x264_scan8[4*i]]; x264_mb_encode_i8x8( h, p, i, i_qp, i_mode, NULL, 1 ); } } } else if( h->mb.i_type == I_4x4 ) { h->mb.b_transform_8x8 = 0; /* If we already encoded 15 of the 16 i4x4 blocks, we don't have to do them again. */ if( h->mb.i_skip_intra ) { h->mc.copy[PIXEL_16x16]( h->mb.pic.p_fdec[0], FDEC_STRIDE, h->mb.pic.i4x4_fdec_buf, 16, 16 ); M32( &h->mb.cache.non_zero_count[x264_scan8[ 0]] ) = h->mb.pic.i4x4_nnz_buf[0]; M32( &h->mb.cache.non_zero_count[x264_scan8[ 2]] ) = h->mb.pic.i4x4_nnz_buf[1]; M32( &h->mb.cache.non_zero_count[x264_scan8[ 8]] ) = h->mb.pic.i4x4_nnz_buf[2]; M32( &h->mb.cache.non_zero_count[x264_scan8[10]] ) = h->mb.pic.i4x4_nnz_buf[3]; h->mb.i_cbp_luma = h->mb.pic.i4x4_cbp; /* In RD mode, restore the now-overwritten DCT data. */ if( h->mb.i_skip_intra == 2 ) h->mc.memcpy_aligned( h->dct.luma4x4, h->mb.pic.i4x4_dct_buf, sizeof(h->mb.pic.i4x4_dct_buf) ); } for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) { for( int i = (p == 0 && h->mb.i_skip_intra) ? 15 : 0; i < 16; i++ ) { pixel *p_dst = &h->mb.pic.p_fdec[p][block_idx_xy_fdec[i]]; int i_mode = h->mb.cache.intra4x4_pred_mode[x264_scan8[i]]; if( (h->mb.i_neighbour4[i] & (MB_TOPRIGHT|MB_TOP)) == MB_TOP ) /* emulate missing topright samples */ MPIXEL_X4( &p_dst[4-FDEC_STRIDE] ) = PIXEL_SPLAT_X4( p_dst[3-FDEC_STRIDE] ); x264_mb_encode_i4x4( h, p, i, i_qp, i_mode, 1 ); } } } else /* Inter MB */ { int i_decimate_mb = 0; /* Don't repeat motion compensation if it was already done in non-RD transform analysis */ if( !h->mb.b_skip_mc ) x264_mb_mc( h ); if( h->mb.b_lossless ) { if( h->mb.b_transform_8x8 ) for( int p = 0; p < plane_count; p++ ) for( int i8x8 = 0; i8x8 < 4; i8x8++ ) { int x = i8x8&1; int y = i8x8>>1; nz = h->zigzagf.sub_8x8( h->dct.luma8x8[p*4+i8x8], h->mb.pic.p_fenc[p] + 8*x + 8*y*FENC_STRIDE, h->mb.pic.p_fdec[p] + 8*x + 8*y*FDEC_STRIDE ); STORE_8x8_NNZ( p, i8x8, nz ); h->mb.i_cbp_luma |= nz << i8x8; } else for( int p = 0; p < plane_count; p++ ) for( int i4x4 = 0; i4x4 < 16; i4x4++ ) { nz = h->zigzagf.sub_4x4( h->dct.luma4x4[p*16+i4x4], h->mb.pic.p_fenc[p]+block_idx_xy_fenc[i4x4], h->mb.pic.p_fdec[p]+block_idx_xy_fdec[i4x4] ); h->mb.cache.non_zero_count[x264_scan8[p*16+i4x4]] = nz; h->mb.i_cbp_luma |= nz << (i4x4>>2); } } else if( h->mb.b_transform_8x8 ) { ALIGNED_ARRAY_32( dctcoef, dct8x8,[4],[64] ); b_decimate &= !h->mb.b_trellis || !h->param.b_cabac; // 8x8 trellis is inherently optimal decimation for CABAC for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) { int quant_cat = p ? CQM_8PC : CQM_8PY; CLEAR_16x16_NNZ( p ); h->dctf.sub16x16_dct8( dct8x8, h->mb.pic.p_fenc[p], h->mb.pic.p_fdec[p] ); h->nr_count[1+!!p*2] += h->mb.b_noise_reduction * 4; int plane_cbp = 0; for( int idx = 0; idx < 4; idx++ ) { nz = x264_quant_8x8( h, dct8x8[idx], i_qp, ctx_cat_plane[DCT_LUMA_8x8][p], 0, p, idx ); if( nz ) { h->zigzagf.scan_8x8( h->dct.luma8x8[p*4+idx], dct8x8[idx] ); if( b_decimate ) { int i_decimate_8x8 = h->quantf.decimate_score64( h->dct.luma8x8[p*4+idx] ); i_decimate_mb += i_decimate_8x8; if( i_decimate_8x8 >= 4 ) plane_cbp |= 1<<idx; } else plane_cbp |= 1<<idx; } } if( i_decimate_mb >= 6 || !b_decimate ) { h->mb.i_cbp_luma |= plane_cbp; FOREACH_BIT( idx, 0, plane_cbp ) { h->quantf.dequant_8x8( dct8x8[idx], h->dequant8_mf[quant_cat], i_qp ); h->dctf.add8x8_idct8( &h->mb.pic.p_fdec[p][8*(idx&1) + 8*(idx>>1)*FDEC_STRIDE], dct8x8[idx] ); STORE_8x8_NNZ( p, idx, 1 ); } } } } else { ALIGNED_ARRAY_32( dctcoef, dct4x4,[16],[16] ); for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) { int quant_cat = p ? CQM_4PC : CQM_4PY; CLEAR_16x16_NNZ( p ); h->dctf.sub16x16_dct( dct4x4, h->mb.pic.p_fenc[p], h->mb.pic.p_fdec[p] ); if( h->mb.b_noise_reduction ) { h->nr_count[0+!!p*2] += 16; for( int idx = 0; idx < 16; idx++ ) h->quantf.denoise_dct( dct4x4[idx], h->nr_residual_sum[0+!!p*2], h->nr_offset[0+!!p*2], 16 ); } int plane_cbp = 0; for( int i8x8 = 0; i8x8 < 4; i8x8++ ) { int i_decimate_8x8 = b_decimate ? 0 : 6; int nnz8x8 = 0; if( h->mb.b_trellis ) { for( int i4x4 = 0; i4x4 < 4; i4x4++ ) { int idx = i8x8*4+i4x4; if( <API key>( h, dct4x4[idx], quant_cat, i_qp, ctx_cat_plane[DCT_LUMA_4x4][p], 0, !!p, p*16+idx ) ) { h->zigzagf.scan_4x4( h->dct.luma4x4[p*16+idx], dct4x4[idx] ); h->quantf.dequant_4x4( dct4x4[idx], h->dequant4_mf[quant_cat], i_qp ); if( i_decimate_8x8 < 6 ) i_decimate_8x8 += h->quantf.decimate_score16( h->dct.luma4x4[p*16+idx] ); h->mb.cache.non_zero_count[x264_scan8[p*16+idx]] = 1; nnz8x8 = 1; } } } else { nnz8x8 = nz = h->quantf.quant_4x4x4( &dct4x4[i8x8*4], h->quant4_mf[quant_cat][i_qp], h->quant4_bias[quant_cat][i_qp] ); if( nz ) { FOREACH_BIT( idx, i8x8*4, nz ) { h->zigzagf.scan_4x4( h->dct.luma4x4[p*16+idx], dct4x4[idx] ); h->quantf.dequant_4x4( dct4x4[idx], h->dequant4_mf[quant_cat], i_qp ); if( i_decimate_8x8 < 6 ) i_decimate_8x8 += h->quantf.decimate_score16( h->dct.luma4x4[p*16+idx] ); h->mb.cache.non_zero_count[x264_scan8[p*16+idx]] = 1; } } } if( nnz8x8 ) { i_decimate_mb += i_decimate_8x8; if( i_decimate_8x8 < 4 ) STORE_8x8_NNZ( p, i8x8, 0 ); else plane_cbp |= 1<<i8x8; } } if( i_decimate_mb < 6 ) { plane_cbp = 0; CLEAR_16x16_NNZ( p ); } else { h->mb.i_cbp_luma |= plane_cbp; FOREACH_BIT( i8x8, 0, plane_cbp ) { h->dctf.add8x8_idct( &h->mb.pic.p_fdec[p][(i8x8&1)*8 + (i8x8>>1)*8*FDEC_STRIDE], &dct4x4[i8x8*4] ); } } } } } /* encode chroma */ if( chroma ) { if( IS_INTRA( h->mb.i_type ) ) { int i_mode = h->mb.i_chroma_pred_mode; if( h->mb.b_lossless ) <API key>( h, i_mode ); else { h->predict_chroma[i_mode]( h->mb.pic.p_fdec[1] ); h->predict_chroma[i_mode]( h->mb.pic.p_fdec[2] ); } } /* encode the 8x8 blocks */ <API key>( h, !IS_INTRA( h->mb.i_type ), h->mb.i_chroma_qp ); } else h->mb.i_cbp_chroma = 0; /* store cbp */ int cbp = h->mb.i_cbp_chroma << 4 | h->mb.i_cbp_luma; if( h->param.b_cabac ) cbp |= h->mb.cache.non_zero_count[x264_scan8[LUMA_DC ]] << 8 | h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+0]] << 9 | h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+1]] << 10; h->mb.cbp[h->mb.i_mb_xy] = cbp; /* Check for P_SKIP * XXX: in the me perhaps we should take <API key> into account * (if multiple mv give same result)*/ if( !b_force_no_skip ) { if( h->mb.i_type == P_L0 && h->mb.i_partition == D_16x16 && !(h->mb.i_cbp_luma | h->mb.i_cbp_chroma) && M32( h->mb.cache.mv[0][x264_scan8[0]] ) == M32( h->mb.cache.pskip_mv ) && h->mb.cache.ref[0][x264_scan8[0]] == 0 ) { h->mb.i_type = P_SKIP; } /* Check for B_SKIP */ if( h->mb.i_type == B_DIRECT && !(h->mb.i_cbp_luma | h->mb.i_cbp_chroma) ) { h->mb.i_type = B_SKIP; } } } void <API key>( x264_t *h ) { if( CHROMA444 ) <API key>( h, 3, 0 ); else <API key>( h, 1, 1 ); } static ALWAYS_INLINE int <API key>( x264_t *h, int b_bidir, int plane_count, int chroma ) { ALIGNED_ARRAY_32( dctcoef, dct4x4,[8],[16] ); ALIGNED_ARRAY_16( dctcoef, dctscan,[16] ); ALIGNED_4( int16_t mvp[2] ); int i_qp = h->mb.i_qp; for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) { int quant_cat = p ? CQM_4PC : CQM_4PY; if( !b_bidir ) { /* Get the MV */ mvp[0] = x264_clip3( h->mb.cache.pskip_mv[0], h->mb.mv_min[0], h->mb.mv_max[0] ); mvp[1] = x264_clip3( h->mb.cache.pskip_mv[1], h->mb.mv_min[1], h->mb.mv_max[1] ); /* Motion compensation */ h->mc.mc_luma( h->mb.pic.p_fdec[p], FDEC_STRIDE, &h->mb.pic.p_fref[0][0][p*4], h->mb.pic.i_stride[p], mvp[0], mvp[1], 16, 16, &h->sh.weight[0][p] ); } for( int i8x8 = 0, i_decimate_mb = 0; i8x8 < 4; i8x8++ ) { int fenc_offset = (i8x8&1) * 8 + (i8x8>>1) * FENC_STRIDE * 8; int fdec_offset = (i8x8&1) * 8 + (i8x8>>1) * FDEC_STRIDE * 8; h->dctf.sub8x8_dct( dct4x4, h->mb.pic.p_fenc[p] + fenc_offset, h->mb.pic.p_fdec[p] + fdec_offset ); if( h->mb.b_noise_reduction ) for( int i4x4 = 0; i4x4 < 4; i4x4++ ) h->quantf.denoise_dct( dct4x4[i4x4], h->nr_residual_sum[0+!!p*2], h->nr_offset[0+!!p*2], 16 ); int nz = h->quantf.quant_4x4x4( dct4x4, h->quant4_mf[quant_cat][i_qp], h->quant4_bias[quant_cat][i_qp] ); FOREACH_BIT( idx, 0, nz ) { h->zigzagf.scan_4x4( dctscan, dct4x4[idx] ); i_decimate_mb += h->quantf.decimate_score16( dctscan ); if( i_decimate_mb >= 6 ) return 0; } } } if( chroma == CHROMA_420 || chroma == CHROMA_422 ) { i_qp = h->mb.i_chroma_qp; int chroma422 = chroma == CHROMA_422; int thresh = chroma422 ? (x264_lambda2_tab[i_qp] + 16) >> 5 : (x264_lambda2_tab[i_qp] + 32) >> 6; int ssd; ALIGNED_ARRAY_16( dctcoef, dct_dc,[8] ); if( !b_bidir ) { /* Special case for mv0, which is (of course) very common in P-skip mode. */ if( M32( mvp ) ) h->mc.mc_chroma( h->mb.pic.p_fdec[1], h->mb.pic.p_fdec[2], FDEC_STRIDE, h->mb.pic.p_fref[0][0][4], h->mb.pic.i_stride[1], mvp[0], mvp[1]<<chroma422, 8, chroma422?16:8 ); else h->mc.<API key>( h->mb.pic.p_fdec[1], h->mb.pic.p_fref[0][0][4], h->mb.pic.i_stride[1], chroma422?16:8 ); } for( int ch = 0; ch < 2; ch++ ) { pixel *p_src = h->mb.pic.p_fenc[1+ch]; pixel *p_dst = h->mb.pic.p_fdec[1+ch]; if( !b_bidir && h->sh.weight[0][1+ch].weightfn ) h->sh.weight[0][1+ch].weightfn[8>>2]( h->mb.pic.p_fdec[1+ch], FDEC_STRIDE, h->mb.pic.p_fdec[1+ch], FDEC_STRIDE, &h->sh.weight[0][1+ch], chroma422?16:8 ); /* there is almost never a termination during chroma, but we can't avoid the check entirely */ /* so instead we check SSD and skip the actual check if the score is low enough. */ ssd = h->pixf.ssd[chroma422?PIXEL_8x16:PIXEL_8x8]( p_dst, FDEC_STRIDE, p_src, FENC_STRIDE ); if( ssd < thresh ) continue; /* The vast majority of chroma checks will terminate during the DC check or the higher * threshold check, so we can save time by doing a DC-only DCT. */ if( h->mb.b_noise_reduction ) { for( int i = 0; i <= chroma422; i++ ) h->dctf.sub8x8_dct( &dct4x4[4*i], p_src + 8*i*FENC_STRIDE, p_dst + 8*i*FDEC_STRIDE ); for( int i4x4 = 0; i4x4 < (chroma422?8:4); i4x4++ ) { h->quantf.denoise_dct( dct4x4[i4x4], h->nr_residual_sum[2], h->nr_offset[2], 16 ); dct_dc[i4x4] = dct4x4[i4x4][0]; dct4x4[i4x4][0] = 0; } } else { if( chroma422 ) h->dctf.sub8x16_dct_dc( dct_dc, p_src, p_dst ); else h->dctf.sub8x8_dct_dc( dct_dc, p_src, p_dst ); } for( int i = 0; i <= chroma422; i++ ) if( h->quantf.quant_2x2_dc( &dct_dc[4*i], h->quant4_mf[CQM_4PC][i_qp+3*chroma422][0] >> 1, h->quant4_bias[CQM_4PC][i_qp+3*chroma422][0] << 1 ) ) return 0; /* If there wasn't a termination in DC, we can check against a much higher threshold. */ if( ssd < thresh*4 ) continue; if( !h->mb.b_noise_reduction ) for( int i = 0; i <= chroma422; i++ ) { h->dctf.sub8x8_dct( &dct4x4[4*i], p_src + 8*i*FENC_STRIDE, p_dst + 8*i*FDEC_STRIDE ); dct4x4[i*4+0][0] = 0; dct4x4[i*4+1][0] = 0; dct4x4[i*4+2][0] = 0; dct4x4[i*4+3][0] = 0; } /* calculate dct coeffs */ for( int i8x8 = 0, i_decimate_mb = 0; i8x8 < (chroma422?2:1); i8x8++ ) { int nz = h->quantf.quant_4x4x4( &dct4x4[i8x8*4], h->quant4_mf[CQM_4PC][i_qp], h->quant4_bias[CQM_4PC][i_qp] ); FOREACH_BIT( idx, i8x8*4, nz ) { h->zigzagf.scan_4x4( dctscan, dct4x4[idx] ); i_decimate_mb += h->quantf.decimate_score15( dctscan ); if( i_decimate_mb >= 7 ) return 0; } } } } h->mb.b_skip_mc = 1; return 1; } int <API key>( x264_t *h, int b_bidir ) { if( CHROMA_FORMAT == CHROMA_444 ) return <API key>( h, b_bidir, 3, CHROMA_444 ); else if( CHROMA_FORMAT == CHROMA_422 ) return <API key>( h, b_bidir, 1, CHROMA_422 ); else return <API key>( h, b_bidir, 1, CHROMA_420 ); } void <API key>( x264_t *h ) { h->nr_offset = h->nr_offset_denoise; h->nr_residual_sum = h->nr_residual_sum_buf[0]; h->nr_count = h->nr_count_buf[0]; for( int cat = 0; cat < 3 + CHROMA444; cat++ ) { int dct8x8 = cat&1; int size = dct8x8 ? 64 : 16; const uint32_t *weight = dct8x8 ? <API key> : <API key>; if( h->nr_count[cat] > (dct8x8 ? (1<<16) : (1<<18)) ) { for( int i = 0; i < size; i++ ) h->nr_residual_sum[cat][i] >>= 1; h->nr_count[cat] >>= 1; } for( int i = 0; i < size; i++ ) h->nr_offset[cat][i] = ((uint64_t)h->param.analyse.i_noise_reduction * h->nr_count[cat] + h->nr_residual_sum[cat][i]/2) / ((uint64_t)h->nr_residual_sum[cat][i] * weight[i]/256 + 1); /* Don't denoise DC coefficients */ h->nr_offset[cat][0] = 0; } } static ALWAYS_INLINE void <API key>( x264_t *h, int i8, int plane_count, int chroma ) { int b_decimate = h->mb.b_dct_decimate; int i_qp = h->mb.i_qp; int x = i8&1; int y = i8>>1; int nz; int chroma422 = chroma == CHROMA_422; h->mb.i_cbp_chroma = 0; h->mb.i_cbp_luma &= ~(1 << i8); if( !h->mb.b_skip_mc ) x264_mb_mc_8x8( h, i8 ); if( h->mb.b_lossless ) { for( int p = 0; p < plane_count; p++ ) { pixel *p_fenc = h->mb.pic.p_fenc[p] + 8*x + 8*y*FENC_STRIDE; pixel *p_fdec = h->mb.pic.p_fdec[p] + 8*x + 8*y*FDEC_STRIDE; int nnz8x8 = 0; if( h->mb.b_transform_8x8 ) { nnz8x8 = h->zigzagf.sub_8x8( h->dct.luma8x8[4*p+i8], p_fenc, p_fdec ); STORE_8x8_NNZ( p, i8, nnz8x8 ); } else { for( int i4 = i8*4; i4 < i8*4+4; i4++ ) { nz = h->zigzagf.sub_4x4( h->dct.luma4x4[16*p+i4], h->mb.pic.p_fenc[p]+block_idx_xy_fenc[i4], h->mb.pic.p_fdec[p]+block_idx_xy_fdec[i4] ); h->mb.cache.non_zero_count[x264_scan8[16*p+i4]] = nz; nnz8x8 |= nz; } } h->mb.i_cbp_luma |= nnz8x8 << i8; } if( chroma == CHROMA_420 || chroma == CHROMA_422 ) { for( int ch = 0; ch < 2; ch++ ) { dctcoef dc; pixel *p_fenc = h->mb.pic.p_fenc[1+ch] + 4*x + (chroma422?8:4)*y*FENC_STRIDE; pixel *p_fdec = h->mb.pic.p_fdec[1+ch] + 4*x + (chroma422?8:4)*y*FDEC_STRIDE; for( int i4x4 = 0; i4x4 <= chroma422; i4x4++ ) { int offset = chroma422 ? 8*y + 2*i4x4 + x : i8; nz = h->zigzagf.sub_4x4ac( h->dct.luma4x4[16+offset+ch*16], p_fenc+4*i4x4*FENC_STRIDE, p_fdec+4*i4x4*FDEC_STRIDE, &dc ); h->mb.cache.non_zero_count[x264_scan8[16+offset+ch*16]] = nz; } } h->mb.i_cbp_chroma = 0x02; } } else { if( h->mb.b_transform_8x8 ) { for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) { int quant_cat = p ? CQM_8PC : CQM_8PY; pixel *p_fenc = h->mb.pic.p_fenc[p] + 8*x + 8*y*FENC_STRIDE; pixel *p_fdec = h->mb.pic.p_fdec[p] + 8*x + 8*y*FDEC_STRIDE; ALIGNED_ARRAY_32( dctcoef, dct8x8,[64] ); h->dctf.sub8x8_dct8( dct8x8, p_fenc, p_fdec ); int nnz8x8 = x264_quant_8x8( h, dct8x8, i_qp, ctx_cat_plane[DCT_LUMA_8x8][p], 0, p, i8 ); if( nnz8x8 ) { h->zigzagf.scan_8x8( h->dct.luma8x8[4*p+i8], dct8x8 ); if( b_decimate && !h->mb.b_trellis ) nnz8x8 = 4 <= h->quantf.decimate_score64( h->dct.luma8x8[4*p+i8] ); if( nnz8x8 ) { h->quantf.dequant_8x8( dct8x8, h->dequant8_mf[quant_cat], i_qp ); h->dctf.add8x8_idct8( p_fdec, dct8x8 ); STORE_8x8_NNZ( p, i8, 1 ); h->mb.i_cbp_luma |= 1 << i8; } else STORE_8x8_NNZ( p, i8, 0 ); } else STORE_8x8_NNZ( p, i8, 0 ); } } else { for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) { int quant_cat = p ? CQM_4PC : CQM_4PY; pixel *p_fenc = h->mb.pic.p_fenc[p] + 8*x + 8*y*FENC_STRIDE; pixel *p_fdec = h->mb.pic.p_fdec[p] + 8*x + 8*y*FDEC_STRIDE; int i_decimate_8x8 = b_decimate ? 0 : 4; ALIGNED_ARRAY_32( dctcoef, dct4x4,[4],[16] ); int nnz8x8 = 0; h->dctf.sub8x8_dct( dct4x4, p_fenc, p_fdec ); STORE_8x8_NNZ( p, i8, 0 ); if( h->mb.b_noise_reduction ) for( int idx = 0; idx < 4; idx++ ) h->quantf.denoise_dct( dct4x4[idx], h->nr_residual_sum[0+!!p*2], h->nr_offset[0+!!p*2], 16 ); if( h->mb.b_trellis ) { for( int i4x4 = 0; i4x4 < 4; i4x4++ ) { if( <API key>( h, dct4x4[i4x4], quant_cat, i_qp, ctx_cat_plane[DCT_LUMA_4x4][p], 0, !!p, i8*4+i4x4+p*16 ) ) { h->zigzagf.scan_4x4( h->dct.luma4x4[p*16+i8*4+i4x4], dct4x4[i4x4] ); h->quantf.dequant_4x4( dct4x4[i4x4], h->dequant4_mf[quant_cat], i_qp ); if( i_decimate_8x8 < 4 ) i_decimate_8x8 += h->quantf.decimate_score16( h->dct.luma4x4[p*16+i8*4+i4x4] ); h->mb.cache.non_zero_count[x264_scan8[p*16+i8*4+i4x4]] = 1; nnz8x8 = 1; } } } else { nnz8x8 = nz = h->quantf.quant_4x4x4( dct4x4, h->quant4_mf[quant_cat][i_qp], h->quant4_bias[quant_cat][i_qp] ); if( nz ) { FOREACH_BIT( i4x4, 0, nz ) { h->zigzagf.scan_4x4( h->dct.luma4x4[p*16+i8*4+i4x4], dct4x4[i4x4] ); h->quantf.dequant_4x4( dct4x4[i4x4], h->dequant4_mf[quant_cat], i_qp ); if( i_decimate_8x8 < 4 ) i_decimate_8x8 += h->quantf.decimate_score16( h->dct.luma4x4[p*16+i8*4+i4x4] ); h->mb.cache.non_zero_count[x264_scan8[p*16+i8*4+i4x4]] = 1; } } } if( nnz8x8 ) { /* decimate this 8x8 block */ if( i_decimate_8x8 < 4 ) STORE_8x8_NNZ( p, i8, 0 ); else { h->dctf.add8x8_idct( p_fdec, dct4x4 ); h->mb.i_cbp_luma |= 1 << i8; } } } } if( chroma == CHROMA_420 || chroma == CHROMA_422 ) { i_qp = h->mb.i_chroma_qp; for( int ch = 0; ch < 2; ch++ ) { ALIGNED_ARRAY_32( dctcoef, dct4x4,[2],[16] ); pixel *p_fenc = h->mb.pic.p_fenc[1+ch] + 4*x + (chroma422?8:4)*y*FENC_STRIDE; pixel *p_fdec = h->mb.pic.p_fdec[1+ch] + 4*x + (chroma422?8:4)*y*FDEC_STRIDE; for( int i4x4 = 0; i4x4 <= chroma422; i4x4++ ) { h->dctf.sub4x4_dct( dct4x4[i4x4], p_fenc + 4*i4x4*FENC_STRIDE, p_fdec + 4*i4x4*FDEC_STRIDE ); if( h->mb.b_noise_reduction ) h->quantf.denoise_dct( dct4x4[i4x4], h->nr_residual_sum[2], h->nr_offset[2], 16 ); dct4x4[i4x4][0] = 0; if( h->mb.b_trellis ) nz = <API key>( h, dct4x4[i4x4], CQM_4PC, i_qp, DCT_CHROMA_AC, 0, 1, 0 ); else nz = h->quantf.quant_4x4( dct4x4[i4x4], h->quant4_mf[CQM_4PC][i_qp], h->quant4_bias[CQM_4PC][i_qp] ); int offset = chroma422 ? ((5*i8) & 0x09) + 2*i4x4 : i8; h->mb.cache.non_zero_count[x264_scan8[16+offset+ch*16]] = nz; if( nz ) { h->zigzagf.scan_4x4( h->dct.luma4x4[16+offset+ch*16], dct4x4[i4x4] ); h->quantf.dequant_4x4( dct4x4[i4x4], h->dequant4_mf[CQM_4PC], i_qp ); h->dctf.add4x4_idct( p_fdec + 4*i4x4*FDEC_STRIDE, dct4x4[i4x4] ); } } } h->mb.i_cbp_chroma = 0x02; } } } void <API key>( x264_t *h, int i8 ) { if( CHROMA444 ) <API key>( h, i8, 3, CHROMA_444 ); else if( CHROMA_FORMAT == CHROMA_422 ) <API key>( h, i8, 1, CHROMA_422 ); else <API key>( h, i8, 1, CHROMA_420 ); } static ALWAYS_INLINE void <API key>( x264_t *h, int i4, int plane_count ) { int i_qp = h->mb.i_qp; for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) { int quant_cat = p ? CQM_4PC : CQM_4PY; pixel *p_fenc = &h->mb.pic.p_fenc[p][block_idx_xy_fenc[i4]]; pixel *p_fdec = &h->mb.pic.p_fdec[p][block_idx_xy_fdec[i4]]; int nz; /* Don't need motion compensation as this function is only used in qpel-RD, which caches pixel data. */ if( h->mb.b_lossless ) { nz = h->zigzagf.sub_4x4( h->dct.luma4x4[p*16+i4], p_fenc, p_fdec ); h->mb.cache.non_zero_count[x264_scan8[p*16+i4]] = nz; } else { ALIGNED_ARRAY_32( dctcoef, dct4x4,[16] ); h->dctf.sub4x4_dct( dct4x4, p_fenc, p_fdec ); nz = x264_quant_4x4( h, dct4x4, i_qp, ctx_cat_plane[DCT_LUMA_4x4][p], 0, p, i4 ); h->mb.cache.non_zero_count[x264_scan8[p*16+i4]] = nz; if( nz ) { h->zigzagf.scan_4x4( h->dct.luma4x4[p*16+i4], dct4x4 ); h->quantf.dequant_4x4( dct4x4, h->dequant4_mf[quant_cat], i_qp ); h->dctf.add4x4_idct( p_fdec, dct4x4 ); } } } } void <API key>( x264_t *h, int i8 ) { if( CHROMA444 ) <API key>( h, i8, 3 ); else <API key>( h, i8, 1 ); }
package oo.Prototype; /* * A Symbol Loader to register all prototype instance */ import java.util.*; public class SymbolLoader { private Hashtable symbols = new Hashtable(); public SymbolLoader() { symbols.put("Line", new LineSymbol()); symbols.put("Note", new NoteSymbol()); } public Hashtable getSymbols() { return symbols; } }
/** \file <API key>.h * We define function here that serve to open a mesh file generated by * GMSH and consructing a cmesh from it. */ #ifndef <API key> #define <API key> #include <t8.h> #include <t8_eclass.h> #include <t8_cmesh.h> /* The maximum supported .msh file version. * Currently, we support gmsh's file version 2 in ASCII format. */ #define <API key> 2 /* put typedefs here */ T8_EXTERN_C_BEGIN (); /* put declarations here */ /** Read a .msh file and create a cmesh from it. * \param [in] fileprefix The prefix of the mesh file. * The file fileprefix.msh is read. * \param [in] partition If true the file is only opened on one process * specified by the \a master argument and saved as * a partitioned cmesh where each other process does not * have any trees. * \param [in] comm The MPI communicator with which the cmesh is to be committed. * \param [in] dim The dimension to read from the .msh files. The .msh format * can store several dimensions of the mesh and therefore the * dimension to read has to be set manually. * \param [in] master If partition is true, a valid MPI rank that will * read the file and store all the trees alone. * \return A committed cmesh holding the mesh of dimension \a dim in the * specified .msh file. */ t8_cmesh_t <API key> (const char *fileprefix, int partition, sc_MPI_Comm comm, int dim, int master); T8_EXTERN_C_END (); #endif /* !<API key> */
package com.djtu.signExam.util; import java.io.IOException; import com.djtu.signExam.model.support.EntityGenerator; /** * use this class to bootstrap the project. * There is no need for developers to write model classes themselves. * Once there are some updates or modified parts in the database, * Please run this class as JavaApplication to update Modal class files. * * @author lihe * */ public class Bootstrap { public static void main(String[] args){ EntityGenerator generator = new EntityGenerator(); try { generator.generateModel(); } catch (IOException e) { e.printStackTrace(); } } }
#include <string.h> #include "FreeRTOS.h" #include "queue.h" #include "task.h" #include "can.h" #include "LPC17xx.h" #include "sys_config.h" #include "lpc_sys.h" // sys_get_uptime_ms() /** * If non-zero, test code is enabled, and each message sent is self-recepted. * You need to either connect a CAN transceiver, or connect RD/TD wires of * the board with a 1K resistor for the tests to work. * * Note that FullCAN and CAN filter is not tested together, but they both work individually. */ #define CAN_TESTING 0 CAN index: enum to struct index conversion #define CAN_INDEX(can) (can) #define CAN_STRUCT_PTR(can) (&(g_can_structs[CAN_INDEX(can)])) #define CAN_VALID(x) (can1 == x || can2 == x) #define CAN_ASSERT_CONCAT_(a, b) a #define CAN_ASSERT_CONCAT(a, b) CAN_ASSERT_CONCAT_(a, b) #define CAN_CT_ASSERT(e) enum { CAN_ASSERT_CONCAT(assert_line_, __LINE__) = 1/(!!(e)) } // Make some compile-time (CT) checks : // Check the sizes of the structs because the size needs to match the HW registers CAN_CT_ASSERT( 2 == sizeof(can_std_id_t)); CAN_CT_ASSERT( 4 == sizeof(can_ext_id_t)); CAN_CT_ASSERT( 8 == sizeof(can_data_t)); CAN_CT_ASSERT(16 == sizeof(can_msg_t)); CAN_CT_ASSERT(12 == sizeof(can_fullcan_msg_t)); Interrupt masks of the CANxIER and CANxICR registers typedef enum { intr_rx = (1 << 0), ///< Receive intr_tx1 = (1 << 1), ///< Transmit 1 intr_warn = (1 << 2), ///< Warning (if error BUS status changes) intr_ovrn = (1 << 3), ///< Data overrun intr_wkup = (1 << 4), ///< Wake-up intr_epi = (1 << 5), ///< Change from error active to error passive or vice versa intr_ali = (1 << 6), ///< Arbitration lost intr_berr = (1 << 7), ///< Bus error (happens during each error/retry of a message) intr_idi = (1 << 8), ///< ID ready (a message was transmitted or aborted) intr_tx2 = (1 << 9), ///< Transmit 2 intr_tx3 = (1 << 10), ///< Transmit 3 intr_all_tx = (intr_tx1 | intr_tx2 | intr_tx3), ///< Mask of the 3 transmit buffers } can_intr_t; Bit mask of SR register indicating which hardware buffer is available enum { tx1_avail = (1 << 2), ///< Transmit buffer 1 is available tx2_avail = (1 << 10), ///< Transmit buffer 2 is available tx3_avail = (1 << 18), ///< Transmit buffer 3 is available tx_all_avail = (tx1_avail | tx2_avail | tx3_avail), }; /** * Data values of the AFMR register * @note Since AFMR is common to both controllers, when bypass mode is enabled, * then ALL messages from ALL CAN controllers will be accepted * * Bit1: Bypass Bit0: ACC Off * 0 1 No messages accepted * 1 X All messages accepted * 0 0 HW Filter or FullCAN */ enum { afmr_enabled = 0x00, ///< Hardware acceptance filtering afmr_disabled = 0x01, ///< No messages will be accepted afmr_bypass = 0x02, ///< Bypass mode, all messages will be accepted. Both 0x02 or 0x03 will work. afmr_fullcan = 0x04, ///< Hardware will receive and store messages per FullCAN mode. }; CAN MOD register values enum { can_mod_normal = 0x00, ///< CAN MOD register value to enable the BUS can_mod_reset = 0x01, ///< CAN MOD register value to reset the BUS can_mod_normal_tpm = (can_mod_normal | (1 << 3)), ///< CAN bus enabled with TPM mode bits set can_mod_selftest = (1 << 2) | can_mod_normal, ///< Used to enable global self-test }; Mask of the PCONP register enum { can1_pconp_mask = (1 << 13), ///< CAN1 power on bitmask can2_pconp_mask = (1 << 14), ///< CAN2 power on bitmask }; Typedef of CAN queues and data typedef struct { LPC_CAN_TypeDef *pCanRegs; ///< The pointer to the CAN registers QueueHandle_t rxQ; ///< TX queue QueueHandle_t txQ; ///< RX queue uint16_t droppedRxMsgs; ///< Number of messages dropped if no space found during the CAN interrupt that queues the RX messages uint16_t rxQWatermark; ///< Watermark of the FreeRTOS Rx Queue uint16_t txQWatermark; ///< Watermark of the FreeRTOS Tx Queue uint16_t txMsgCount; ///< Number of messages sent uint16_t rxMsgCount; ///< Number of received messages can_void_func_t bus_error; ///< When serious BUS error occurs can_void_func_t data_overrun; ///< When we read the CAN buffer too late for incoming message } can_struct_t ; Structure of both CANs can_struct_t g_can_structs[can_max] = { {LPC_CAN1}, {LPC_CAN2}}; /** * This type of CAN interrupt should lead to "bus error", but note that intr_berr is not the right * one as that one is triggered upon each type of CAN error which may be a simple "retry" that * can be recovered. intr_epi or intr_warn should work for this selection. */ static const can_intr_t g_can_bus_err_intr = intr_epi; /** @{ Private functions */ /** * Sends a message using an available buffer. Initially this chose one out of the three buffers but that's * a little tricky to use when messages are always queued since one of the 3 buffers can be starved and not * get sent. So therefore some of that logic is #ifdef'd out to only use one HW buffer. * * @returns true if the message was written to the HW buffer to be sent, otherwise false if the HW buffer(s) are busy. * * Notes: * - Using the TX message counter and the TPM bit, we can ensure that the HW chooses between the TX1/TX2/TX3 * in a round-robin fashion otherwise there is a possibility that if the CAN Tx queue is always full, * a low message ID can be starved even if it was amongst the first ones written using this method call. * * @warning This should be called from critical section since this method is not thread-safe */ static bool CAN_tx_now (can_struct_t *struct_ptr, can_msg_t *msg_ptr) { // 32-bit command of CMR register to start transmission of one of the buffers enum { go_cmd_invalid = 0, go_cmd_tx1 = 0x21, go_cmd_tx2 = 0x41, go_cmd_tx3 = 0x81, }; LPC_CAN_TypeDef *pCAN = struct_ptr->pCanRegs; const uint32_t can_sr_reg = pCAN->SR; volatile can_msg_t *pHwMsgRegs = NULL; uint32_t go_cmd = go_cmd_invalid; if (can_sr_reg & tx1_avail){ pHwMsgRegs = (can_msg_t*)&(pCAN->TFI1); go_cmd = go_cmd_tx1; } #if 0 else if (can_sr_reg & tx2_avail){ pHwMsgRegs = (can_msg_t*)&(pCAN->TFI2); go_cmd = go_cmd_tx2; } else if (can_sr_reg & tx3_avail){ pHwMsgRegs = (can_msg_t*)&(pCAN->TFI3); go_cmd = go_cmd_tx3; } #endif else { /* No buffer available, return failure */ return false; } /* Copy the CAN message to the HW CAN registers and write the 8 TPM bits. * We set TPM bits each time by using the txMsgCount because otherwise if TX1, and TX2 are always * being written with a lower message ID, then TX3 will starve and never be sent. */ #if 0 // Higher number will be sent later, but how do we handle the rollover from 255 to 0 because then the // newly written 0 will be sent, and buffer that contains higher TPM can starve. const uint8_t tpm = struct_ptr->txMsgCount; msg_ptr->frame |= tpm; #endif *pHwMsgRegs = *msg_ptr; struct_ptr->txMsgCount++; #if CAN_TESTING go_cmd &= (0xF0); go_cmd = (1 << 4); /* Self reception */ #endif /* Send the message! */ pCAN->CMR = go_cmd; return true; } static void CAN_handle_isr(const can_t can) { can_struct_t *pStruct = CAN_STRUCT_PTR(can); LPC_CAN_TypeDef *pCAN = pStruct->pCanRegs; const uint32_t rbs = (1 << 0); const uint32_t ibits = pCAN->ICR; UBaseType_t count; can_msg_t msg; /* Handle the received message */ if ((ibits & intr_rx) | (pCAN->GSR & rbs)) { if( (count = <API key>(pStruct->rxQ)) > pStruct->rxQWatermark) { pStruct->rxQWatermark = count; } can_msg_t *pHwMsgRegs = (can_msg_t*) &(pCAN->RFS); if (xQueueSendFromISR(pStruct->rxQ, pHwMsgRegs, NULL)) { pStruct->rxMsgCount++; } else { pStruct->droppedRxMsgs++; } pCAN->CMR = 0x04; // Release the receive buffer, no need to bitmask } /* A transmit finished, send any queued message(s) */ if (ibits & intr_all_tx) { if( (count = <API key>(pStruct->txQ)) > pStruct->txQWatermark) { pStruct->txQWatermark = count; } if (<API key>(pStruct->txQ, &msg, NULL)) { CAN_tx_now(pStruct, &msg); } } /* We only enable interrupt when a valid callback exists, so no need * to check for the callback function being NULL */ if (ibits & g_can_bus_err_intr) { pStruct->bus_error(ibits); } if (ibits & intr_ovrn) { pStruct->data_overrun(ibits); } } /** * Actual ISR Handler (mapped to startup file's interrupt vector function name) * This interrupt is shared between CAN1, and CAN2 */ #ifdef __cplusplus extern "C" { #endif void CAN_IRQHandler(void) { const uint32_t pconp = LPC_SC->PCONP; /* Reading registers without CAN powered up will cause DABORT exception */ if (pconp & can1_pconp_mask) { CAN_handle_isr(can1); } if (pconp & can2_pconp_mask) { CAN_handle_isr(can2); } } #ifdef __cplusplus } #endif bool CAN_init(can_t can, uint32_t baudrate_kbps, uint16_t rxq_size, uint16_t txq_size, can_void_func_t bus_off_cb, can_void_func_t data_ovr_cb) { if (!CAN_VALID(can)){ return false; } can_struct_t *pStruct = CAN_STRUCT_PTR(can); LPC_CAN_TypeDef *pCAN = pStruct->pCanRegs; bool failed = true; /* Enable CAN Power, and select the PINS * CAN1 is at P0.0, P0.1 and P0.21, P0.22 * CAN2 is at P0.4, P0.5 and P2.7, P2.8 * On SJ-One board, we have P0.0, P0.1, and P2.7, P2.8 */ if (can1 == can) { LPC_SC->PCONP |= can1_pconp_mask; LPC_PINCON->PINSEL0 &= ~(0xF << 0); LPC_PINCON->PINSEL0 |= (0x5 << 0); } else if (can2 == can){ LPC_SC->PCONP |= can2_pconp_mask; LPC_PINCON->PINSEL4 &= ~(0xF << 14); LPC_PINCON->PINSEL4 |= (0x5 << 14); } /* Create the queues with minimum size of 1 to avoid NULL pointer reference */ if (!pStruct->rxQ) { pStruct->rxQ = xQueueCreate(rxq_size ? rxq_size : 1, sizeof(can_msg_t)); } if (!pStruct->txQ) { pStruct->txQ = xQueueCreate(txq_size ? txq_size : 1, sizeof(can_msg_t)); } /* The CAN dividers must all be the same for both CANs * Set the dividers of CAN1, CAN2, ACF to CLK / 1 */ lpc_pclk(pclk_can1, clkdiv_1); lpc_pclk(pclk_can2, clkdiv_1); lpc_pclk(pclk_can_flt, clkdiv_1); pCAN->MOD = can_mod_reset; pCAN->IER = 0x0; // Disable All CAN Interrupts pCAN->GSR = 0x0; // Clear error counters pCAN->CMR = 0xE; // Abort Tx, release Rx, clear data over-run /** * About the AFMR register : * B0 B1 * Filter Mode | AccOff bit | AccBP bit | CAN Rx interrupt * Off Mode 1 0 No messages accepted * Bypass Mode X 1 All messages accepted * FullCAN 0 0 HW acceptance filtering */ LPC_CANAF->AFMR = afmr_disabled; // Clear pending interrupts and the CAN Filter RAM LPC_CANAF_RAM->mask[0] = pCAN->ICR; memset((void*)&(LPC_CANAF_RAM->mask[0]), 0, sizeof(LPC_CANAF_RAM->mask)); /* Zero out the filtering registers */ LPC_CANAF->SFF_sa = 0; LPC_CANAF->SFF_GRP_sa = 0; LPC_CANAF->EFF_sa = 0; LPC_CANAF->EFF_GRP_sa = 0; LPC_CANAF->ENDofTable = 0; /* Do not accept any messages until CAN filtering is enabled */ LPC_CANAF->AFMR = afmr_disabled; do { const uint32_t baudDiv = sys_get_cpu_clock() / (1000 * baudrate_kbps); const uint32_t SJW = 3; const uint32_t SAM = 0; uint32_t BRP = 0, TSEG1 = 0, TSEG2 = 0, NT = 0; /* Calculate suitable nominal time value * NT (nominal time) = (TSEG1 + TSEG2 + 3) * NT <= 24 * TSEG1 >= 2*TSEG2 */ failed = true; for(NT=24; NT > 0; NT-=2) { if ((baudDiv % NT)==0) { BRP = baudDiv / NT - 1; NT TSEG2 = (NT/3) - 1; TSEG1 = NT -(NT/3) - 1; failed = false; break; } } if (!failed) { pCAN->BTR = (SAM << 23) | (TSEG2<<20) | (TSEG1<<16) | (SJW<<14) | BRP; // CANx->BTR = 0x002B001D; // 48Mhz 100Khz } } while (0); /* If everything okay so far, enable the CAN interrupts */ if (!failed) { /* At minimum, we need Rx/Tx interrupts */ pCAN->IER = (intr_rx | intr_all_tx); /* Enable BUS-off interrupt and callback if given */ if (bus_off_cb) { pStruct->bus_error = bus_off_cb; pCAN->IER |= g_can_bus_err_intr; } /* Enable data-overrun interrupt and callback if given */ if (data_ovr_cb) { pStruct->data_overrun = data_ovr_cb; pCAN->IER |= intr_ovrn; } /* Finally, enable the actual CPU core interrupt */ <API key>(CAN_IRQn, "CAN", IP_can); NVIC_EnableIRQ(CAN_IRQn); } /* return true if all is well */ return (false == failed); } bool CAN_tx (can_t can, can_msg_t *pCanMsg, uint32_t timeout_ms) { if (!CAN_VALID(can) || !pCanMsg || CAN_is_bus_off(can)) { return false; } bool ok = false; can_struct_t *pStruct = CAN_STRUCT_PTR(can); LPC_CAN_TypeDef *CANx = pStruct->pCanRegs; /* Try transmitting to one of the available buffers */ taskENTER_CRITICAL(); do { ok = CAN_tx_now(pStruct, pCanMsg); } while(0); taskEXIT_CRITICAL(); /* If HW buffer not available, then just queue the message */ if (!ok) { if (<API key> == <API key>()) { ok = xQueueSend(pStruct->txQ, pCanMsg, OS_MS(timeout_ms)); } else { ok = xQueueSend(pStruct->txQ, pCanMsg, 0); } /* There is possibility that before we queued the message, we got interrupted * and all hw buffers were emptied meanwhile, and our queued message will now * sit in the queue forever until another Tx interrupt takes place. * So we dequeue it here if all are empty and send it over. */ taskENTER_CRITICAL(); do { can_msg_t msg; if (tx_all_avail == (CANx->SR & tx_all_avail) && xQueueReceive(pStruct->txQ, &msg, 0) ) { ok = CAN_tx_now(pStruct, &msg); } } while(0); taskEXIT_CRITICAL(); } return ok; } bool CAN_rx (can_t can, can_msg_t *pCanMsg, uint32_t timeout_ms) { bool ok = false; if (CAN_VALID(can) && pCanMsg) { if (<API key> == <API key>()) { ok = xQueueReceive(CAN_STRUCT_PTR(can)->rxQ, pCanMsg, OS_MS(timeout_ms)); } else { uint64_t msg_timeout = sys_get_uptime_ms() + timeout_ms; while (! (ok = xQueueReceive(CAN_STRUCT_PTR(can)->rxQ, pCanMsg, 0))) { if (sys_get_uptime_ms() > msg_timeout) { break; } } } } return ok; } bool CAN_is_bus_off(can_t can) { const uint32_t bus_off_mask = (1 << 7); return (!CAN_VALID(can)) ? true : !! (CAN_STRUCT_PTR(can)->pCanRegs->GSR & bus_off_mask); } void CAN_reset_bus(can_t can) { if (CAN_VALID(can)) { CAN_STRUCT_PTR(can)->pCanRegs->MOD = can_mod_reset; #if CAN_TESTING CAN_STRUCT_PTR(can)->pCanRegs->MOD = can_mod_selftest; #else CAN_STRUCT_PTR(can)->pCanRegs->MOD = can_mod_normal_tpm; #endif } } uint16_t <API key>(can_t can) { return CAN_VALID(can) ? CAN_STRUCT_PTR(can)->rxQWatermark : 0; } uint16_t <API key>(can_t can) { return CAN_VALID(can) ? CAN_STRUCT_PTR(can)->txQWatermark : 0; } uint16_t CAN_get_tx_count(can_t can) { return CAN_VALID(can) ? CAN_STRUCT_PTR(can)->txMsgCount : 0; } uint16_t CAN_get_rx_count(can_t can) { return CAN_VALID(can) ? CAN_STRUCT_PTR(can)->rxMsgCount : 0; } uint16_t <API key>(can_t can) { return CAN_VALID(can) ? CAN_STRUCT_PTR(can)->droppedRxMsgs : 0; } void <API key>(void) { LPC_CANAF->AFMR = afmr_bypass; } can_std_id_t CAN_gen_sid(can_t can, uint16_t id) { /* SCC in datasheet is defined as can controller - 1 */ const uint16_t scc = (can); can_std_id_t ret; ret.can_num = scc; ret.disable = (0xffff == id) ? 1 : 0; ret.fc_intr = 0; ret.id = id; return ret; } can_ext_id_t CAN_gen_eid(can_t can, uint32_t id) { /* SCC in datasheet is defined as can controller - 1 */ const uint16_t scc = (can); can_ext_id_t ret; ret.can_num = scc; ret.id = id; return ret; } bool <API key>(can_t can, can_std_id_t id1, can_std_id_t id2) { /* Return if invalid CAN given */ if (!CAN_VALID(can)) { return false; } /* Check for enough room for more FullCAN entries * Each entry takes 2-byte entry, and 12-byte message RAM. */ const uint16_t existing_entries = <API key>(); const uint16_t size_per_entry = sizeof(can_std_id_t) + sizeof(can_fullcan_msg_t); if ((existing_entries * size_per_entry) >= sizeof(LPC_CANAF_RAM->mask)) { return false; } /* Locate where we should write the next entry */ uint8_t *base = (uint8_t*) &(LPC_CANAF_RAM->mask[0]); uint8_t *next_entry_ptr = base + LPC_CANAF->SFF_sa; /* Copy the new entry into the RAM filter */ LPC_CANAF->AFMR = afmr_disabled; do { const uint32_t entries = ((uint32_t) id2.raw & UINT16_MAX) | ((uint32_t) id1.raw << 16); * (uint32_t*) (next_entry_ptr) = entries; /* The new start of Standard Frame Filter is after the two new entries */ const uint32_t new_sff_sa = LPC_CANAF->SFF_sa + sizeof(id1) + sizeof(id2); LPC_CANAF->SFF_sa = new_sff_sa; /* Next filters start at SFF_sa (they are disabled) */ LPC_CANAF->SFF_GRP_sa = new_sff_sa; LPC_CANAF->EFF_sa = new_sff_sa; LPC_CANAF->EFF_GRP_sa = new_sff_sa; LPC_CANAF->ENDofTable = new_sff_sa; } while(0); LPC_CANAF->AFMR = afmr_fullcan; return true; } can_fullcan_msg_t* <API key>(can_std_id_t fc_id) { /* Number of entries depends on how far SFF_sa is from base of 0 */ const uint16_t num_entries = <API key>(); uint16_t idx = 0; /* The FullCAN entries are at the base of the CAN RAM */ const can_std_id_t *id_list = (can_std_id_t*) &(LPC_CANAF_RAM->mask[0]); /* Find the standard ID entered into the RAM * Once we find the ID, its message's RAM location is after * LPC_CANAF->ENDofTable based on the index location. * * Note that due to MSB/LSB of the CAN RAM, we check in terms of 16-bit WORDS * and LSB word match means we will find it at index + 1, and MSB word match * means we will find it at the index. */ for (idx = 0; idx < num_entries; idx+=2) { if (id_list[idx].id == fc_id.id) { ++idx; break; } if (id_list[idx+1].id == fc_id.id) { break; } } can_fullcan_msg_t *real_entry = NULL; if (idx < num_entries) { /* If we find an index, we have to convert it to the actual message pointer */ can_fullcan_msg_t *base_msg_entry = (can_fullcan_msg_t*) (((uint8_t*) &(LPC_CANAF_RAM->mask[0])) + LPC_CANAF->ENDofTable); real_entry = (base_msg_entry + idx); } return real_entry; } bool <API key>(can_fullcan_msg_t *pMsg, can_fullcan_msg_t *pMsgCopy) { const uint8_t *can_ram_base = (uint8_t*) &(LPC_CANAF_RAM->mask[0]); const uint8_t *start = can_ram_base + LPC_CANAF->ENDofTable; // Actual FullCAN msgs are stored after this const uint8_t *end = can_ram_base + sizeof(LPC_CANAF_RAM->mask); // Last byte of CAN RAM + 1 bool new_msg_received = false; /* Validate the input pointers. pMsg must be within range of our RAM filter * where the actual FullCAN message should be stored at */ const uint8_t *ptr = (uint8_t*) pMsg; if (ptr < start || ptr >= end || !pMsgCopy) { return false; } /* If semaphore bits change, then HW has updated the message so read it again. * After HW writes new message, semaphore bits are changed to 0b11. */ while (0 != pMsg->semphr) { new_msg_received = true; pMsg->semphr = 0; *pMsgCopy = *pMsg; } return new_msg_received; } uint8_t <API key>(void) { return LPC_CANAF->SFF_sa / sizeof(can_std_id_t); } bool CAN_setup_filter(const can_std_id_t *std_id_list, uint16_t sid_cnt, const can_std_grp_id_t *std_group_id_list, uint16_t sgp_cnt, const can_ext_id_t *ext_id_list, uint16_t eid_cnt, const can_ext_grp_id_t *ext_group_id_list, uint16_t egp_cnt) { bool ok = true; uint32_t i = 0; uint32_t temp32 = 0; // Count of standard IDs must be even if (sid_cnt & 1) { return false; } LPC_CANAF->AFMR = afmr_disabled; do { /* Filter RAM is after the FulLCAN entries */ uint32_t can_ram_base_addr = (uint32_t) &(LPC_CANAF_RAM->mask[0]); /* FullCAN entries take up 2 bytes each at beginning RAM, and 12-byte sections at the end */ const uint32_t can_ram_end_addr = can_ram_base_addr + sizeof(LPC_CANAF_RAM->mask) - ( sizeof(can_fullcan_msg_t) * <API key>()); /* Our filter RAM is after FullCAN entries */ uint32_t *ptr = (uint32_t*) (can_ram_base_addr + LPC_CANAF->SFF_sa); /* macro to swap top and bottom 16-bits of 32-bit DWORD */ #define CAN_swap32(t32) do { \ t32 = (t32 >> 16) | (t32 << 16);\ } while (0) /** * Standard ID list and group list need to swapped otherwise setting the wrong * filter will make the CAN ISR go into a loop for no apparent reason. * It looks like the filter data is motorolla big-endian format. * See "configuration example 5" in CAN chapter. */ #define CAN_add_filter_list(list, ptr, end, cnt, entry_size, swap) \ do { if (NULL != list) { \ if ((uint32_t)ptr + (cnt * entry_size) < end) { \ for (i = 0; i < (cnt * entry_size)/4; i++) { \ if(swap) { \ temp32 = ((uint32_t*)list) [i]; \ CAN_swap32(temp32); \ ptr[i] = temp32; \ } \ else { \ ptr[i] = ((uint32_t*)list) [i]; \ } \ } \ ptr += (cnt * entry_size)/4; \ } else { ok = false; } } } while(0) /* The sa (start addresses) are byte address offset from CAN RAM * and must be 16-bit (WORD) aligned * LPC_CANAF->SFF_sa should already be setup by FullCAN if used, or * set to zero by the can init function. */ CAN_add_filter_list(std_id_list, ptr, can_ram_end_addr, sid_cnt, sizeof(can_std_id_t), true); LPC_CANAF->SFF_GRP_sa = ((uint32_t)ptr - can_ram_base_addr); CAN_add_filter_list(std_group_id_list, ptr, can_ram_end_addr, sgp_cnt, sizeof(can_std_grp_id_t), true); LPC_CANAF->EFF_sa = ((uint32_t)ptr - can_ram_base_addr); CAN_add_filter_list(ext_id_list, ptr, can_ram_end_addr, eid_cnt, sizeof(can_ext_id_t), false); LPC_CANAF->EFF_GRP_sa = ((uint32_t)ptr - can_ram_base_addr); CAN_add_filter_list(ext_group_id_list, ptr, can_ram_end_addr, egp_cnt, sizeof(can_ext_grp_id_t), false); /* End of table is where the FullCAN messages are stored */ LPC_CANAF->ENDofTable = ((uint32_t)ptr - can_ram_base_addr); } while(0); /* If there was no FullCAN entry, then SFF_sa will be zero. * If it was zero, we just enable the AFMR, but if it was not zero, that means * FullCAN entry was added, so we restore AMFR to fullcan enable */ LPC_CANAF->AFMR = (0 == LPC_CANAF->SFF_sa) ? afmr_enabled : afmr_fullcan; return ok; } #if CAN_TESTING #include <printf_lib.h> #define CAN_ASSERT(x) if (!(x)) { u0_dbg_printf("Failed at %i, BUS: %s MOD: 0x%08x, GSR: 0x%08x\n"\ "IER/ICR: 0x%08X/0x%08x BTR: 0x%08x"\ "\nLine %i: %s\n", __LINE__, \ CAN_is_bus_off(can1) ? "OFF" : "ON", \ (int)LPC_CAN1->MOD, (int)LPC_CAN1->GSR, \ (int)LPC_CAN1->IER, (int)LPC_CAN1->ICR, \ (int)LPC_CAN1->BTR, \ __LINE__, #x); return false; } void CAN_test_bufoff_cb(uint32_t d) { u0_dbg_printf("CB: BUS OFF\n"); } void CAN_test_bufovr_cb(uint32_t d) { u0_dbg_printf("CB: DATA OVR\n"); } bool CAN_test(void) { uint32_t i = 0; #define can_test_msg(msg, id, rxtrue) do { \ u0_dbg_printf("Send ID: 0x%08X\n", id); \ msg.msg_id = id; \ CAN_ASSERT(CAN_tx(can1, &msg, 0)); \ msg.msg_id = 0; \ CAN_ASSERT(rxtrue == CAN_rx(can1, &msg, 10)); \ if (rxtrue) CAN_ASSERT(id == msg.msg_id); \ } while(0) u0_dbg_printf(" Test init()\n"); CAN_ASSERT(!CAN_init(can_max, 100, 0, 0, NULL, NULL)); CAN_ASSERT(CAN_init(can1, 100, 5, 5, CAN_test_bufoff_cb, CAN_test_bufovr_cb)); CAN_ASSERT(LPC_CAN1->MOD == can_mod_reset); <API key>(); CAN_ASSERT(g_can_rx_qs[0] != NULL); CAN_ASSERT(g_can_tx_qs[0] != NULL); CAN_ASSERT(LPC_CANAF->SFF_sa == 0); CAN_ASSERT(LPC_CANAF->SFF_GRP_sa == 0); CAN_ASSERT(LPC_CANAF->EFF_sa == 0); CAN_ASSERT(LPC_CANAF->EFF_GRP_sa == 0); CAN_ASSERT(LPC_CANAF->ENDofTable == 0); CAN_reset_bus(can1); CAN_ASSERT(LPC_CAN1->MOD == can_mod_selftest); /* Create a message, and test tx with bad input */ uint32_t id = 0x100; can_msg_t msg; memset(&msg, 0, sizeof(msg)); msg.frame = 0; msg.msg_id = id; msg.frame_fields.is_29bit = 0; msg.frame_fields.data_len = 8; msg.data.qword = 0x1122334455667788; CAN_ASSERT(!CAN_tx(can_max, &msg, 0)); // Invalid CAN CAN_ASSERT(!CAN_rx(can1, NULL, 0)); // Invalid message pointer /* Send msg and test receive */ u0_dbg_printf(" Test Tx/Rx\n"); can_test_msg(msg, 0x100, true); can_test_msg(msg, 0x200, true); can_test_msg(msg, 0x300, true); can_test_msg(msg, 0x400, true); can_test_msg(msg, 0x500, true); const can_std_id_t slist[] = { CAN_gen_sid(can1, 0x100), CAN_gen_sid(can1, 0x110), // 2 entries CAN_gen_sid(can1, 0x120), CAN_gen_sid(can1, 0x130) // 2 entries }; const can_std_grp_id_t sglist[] = { {CAN_gen_sid(can1, 0x200), CAN_gen_sid(can1, 0x210)}, // Group 1 {CAN_gen_sid(can1, 0x220), CAN_gen_sid(can1, 0x230)} // Group 2 }; const can_ext_id_t elist[] = { CAN_gen_eid(can1, 0x7500), CAN_gen_eid(can1, 0x8500)}; const can_ext_grp_id_t eglist[] = { {CAN_gen_eid(can1, 0xA000), CAN_gen_eid(can1, 0xB000)} }; // Group 1 /* Test filter setup */ u0_dbg_printf(" Test filter setup\n"); CAN_setup_filter(slist, 4, sglist, 2, elist, 2, eglist, 1); /* We use offset of zero if 2 FullCAN messages are added, otherwise 4 if none were added above */ const uint8_t offset = 4; CAN_ASSERT(LPC_CANAF->SFF_sa == 4 - offset); CAN_ASSERT(LPC_CANAF->SFF_GRP_sa == 12 - offset); CAN_ASSERT(LPC_CANAF->EFF_sa == 20 - offset); CAN_ASSERT(LPC_CANAF->EFF_GRP_sa == 28 - offset); CAN_ASSERT(LPC_CANAF->ENDofTable == 36 - offset); for ( i = 0; i < 10; i++) { u0_dbg_printf("%2i: 0x%08X\n", i, (uint32_t) LPC_CANAF_RAM->mask[i]); } /* Send a message defined in filter */ u0_dbg_printf(" Test filter messages\n"); msg.frame = 0; msg.frame_fields.is_29bit = 0; msg.frame_fields.data_len = 8; msg.data.qword = 0x1122334455667788; /* Test reception of messages defined in the filter */ u0_dbg_printf(" Test message reception according to filter\n"); msg.frame_fields.is_29bit = 0; can_test_msg(msg, 0x100, true); // standard id can_test_msg(msg, 0x110, true); // standard id can_test_msg(msg, 0x120, true); // standard id can_test_msg(msg, 0x130, true); // standard id can_test_msg(msg, 0x200, true); // Start of standard ID group can_test_msg(msg, 0x210, true); // Last of standard ID group can_test_msg(msg, 0x220, true); // Start of standard ID group can_test_msg(msg, 0x230, true); // Last of standard ID group msg.frame_fields.is_29bit = 1; can_test_msg(msg, 0x7500, true); // extended id can_test_msg(msg, 0x8500, true); // extended id can_test_msg(msg, 0xA000, true); // extended id group start can_test_msg(msg, 0xB000, true); // extended id group end u0_dbg_printf(" Test messages that should not be received\n"); /* Send a message not defined in filter */ msg.frame_fields.is_29bit = 0; can_test_msg(msg, 0x0FF, false); can_test_msg(msg, 0x111, false); can_test_msg(msg, 0x131, false); can_test_msg(msg, 0x1FF, false); can_test_msg(msg, 0x211, false); can_test_msg(msg, 0x21f, false); can_test_msg(msg, 0x231, false); msg.frame_fields.is_29bit = 1; can_test_msg(msg, 0x7501, false); can_test_msg(msg, 0x8501, false); can_test_msg(msg, 0xA000-1, false); can_test_msg(msg, 0xB000+1, false); /* Test FullCAN */ u0_dbg_printf(" Test FullCAN\n"); CAN_init(can1, 100, 5, 5, CAN_test_bufoff_cb, CAN_test_bufovr_cb); CAN_reset_bus(can1); id = 0x100; CAN_ASSERT(0 == <API key>()); CAN_ASSERT(<API key>(can1, CAN_gen_sid(can1, id), CAN_gen_sid(can1, id+1))); CAN_ASSERT(2 == <API key>()); CAN_ASSERT(LPC_CANAF->SFF_sa == 4); CAN_ASSERT(LPC_CANAF->SFF_GRP_sa == 4); CAN_ASSERT(LPC_CANAF->EFF_sa == 4); CAN_ASSERT(LPC_CANAF->EFF_GRP_sa == 4); CAN_ASSERT(LPC_CANAF->ENDofTable == 4); CAN_ASSERT(<API key>(can1, CAN_gen_sid(can1, id+2), CAN_gen_sid(can1, id+3))); CAN_ASSERT(4 == <API key>()); CAN_ASSERT(LPC_CANAF->SFF_sa == 8); for ( i = 0; i < 3; i++) { u0_dbg_printf("%2i: 0x%08X\n", i, (uint32_t) LPC_CANAF_RAM->mask[i]); } can_fullcan_msg_t *fc1 = <API key>(CAN_gen_sid(can1, id)); can_fullcan_msg_t *fc2 = <API key>(CAN_gen_sid(can1, id+1)); can_fullcan_msg_t *fc3 = <API key>(CAN_gen_sid(can1, id+2)); can_fullcan_msg_t *fc4 = <API key>(CAN_gen_sid(can1, id+3)); CAN_ASSERT((LPC_CANAF_RAM_BASE + LPC_CANAF->SFF_sa) == (uint32_t)fc1); CAN_ASSERT((LPC_CANAF_RAM_BASE + LPC_CANAF->SFF_sa + 1*sizeof(can_fullcan_msg_t)) == (uint32_t)fc2); CAN_ASSERT((LPC_CANAF_RAM_BASE + LPC_CANAF->SFF_sa + 2*sizeof(can_fullcan_msg_t)) == (uint32_t)fc3); CAN_ASSERT((LPC_CANAF_RAM_BASE + LPC_CANAF->SFF_sa + 3*sizeof(can_fullcan_msg_t)) == (uint32_t)fc4); can_fullcan_msg_t fc_temp; CAN_ASSERT(!<API key>(fc1, &fc_temp)); CAN_ASSERT(!<API key>(fc2, &fc_temp)); CAN_ASSERT(!<API key>(fc3, &fc_temp)); CAN_ASSERT(!<API key>(fc4, &fc_temp)); /* Send message, see if fullcan captures it */ msg.frame = 0; msg.msg_id = id; msg.frame_fields.is_29bit = 0; msg.frame_fields.data_len = 8; #define <API key>(fc, msg_copy, id) \ do { \ msg.msg_id = id; \ CAN_ASSERT(CAN_tx(can1, &msg, 0)); \ CAN_ASSERT(!CAN_rx(can1, &msg, 10)); \ CAN_ASSERT(<API key>(fc, &msg_copy)); \ CAN_ASSERT(fc->msg_id == id) \ } while(0) <API key>(fc1, fc_temp, id+0); CAN_ASSERT(!<API key>(fc2, &fc_temp)); <API key>(fc2, fc_temp, id+1); CAN_ASSERT(!<API key>(fc3, &fc_temp)); <API key>(fc3, fc_temp, id+2); CAN_ASSERT(!<API key>(fc4, &fc_temp)); <API key>(fc4, fc_temp, id+3); CAN_ASSERT(!<API key>(fc1, &fc_temp)); u0_dbg_printf(" \n--> All tests successful! <--\n"); return true; } #endif
<?php /* * acf_get_setting * * This function will return a value from the settings array found in the acf object * * @type function * @date 28/09/13 * @since 5.0.0 * * @param $name (string) the setting name to return * @return (mixed) */ function acf_get_setting( $name, $default = null ) { // vars $settings = acf()->settings; // find setting $setting = acf_maybe_get( $settings, $name, $default ); // filter for 3rd party customization $setting = apply_filters( "acf/settings/{$name}", $setting ); // return return $setting; } /* * <API key> * * This function will return true or false for a given compatibility setting * * @type function * @date 20/01/2015 * @since 5.1.5 * * @param $name (string) * @return (boolean) */ function <API key>( $name ) { return apply_filters( "acf/compatibility/{$name}", false ); } /* * acf_update_setting * * This function will update a value into the settings array found in the acf object * * @type function * @date 28/09/13 * @since 5.0.0 * * @param $name (string) * @param $value (mixed) * @return n/a */ function acf_update_setting( $name, $value ) { acf()->settings[ $name ] = $value; } /* * acf_append_setting * * This function will add a value into the settings array found in the acf object * * @type function * @date 28/09/13 * @since 5.0.0 * * @param $name (string) * @param $value (mixed) * @return n/a */ function acf_append_setting( $name, $value ) { // createa array if needed if( !isset(acf()->settings[ $name ]) ) { acf()->settings[ $name ] = array(); } // append to array acf()->settings[ $name ][] = $value; } /* * acf_get_path * * This function will return the path to a file within the ACF plugin folder * * @type function * @date 28/09/13 * @since 5.0.0 * * @param $path (string) the relative path from the root of the ACF plugin folder * @return (string) */ function acf_get_path( $path ) { return acf_get_setting('path') . $path; } /* * acf_get_dir * * This function will return the url to a file within the ACF plugin folder * * @type function * @date 28/09/13 * @since 5.0.0 * * @param $path (string) the relative path from the root of the ACF plugin folder * @return (string) */ function acf_get_dir( $path ) { return acf_get_setting('dir') . $path; } /* * acf_include * * This function will include a file * * @type function * @date 10/03/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_include( $file ) { $path = acf_get_path( $file ); if( file_exists($path) ) { include_once( $path ); } } /* * acf_parse_args * * This function will merge together 2 arrays and also convert any numeric values to ints * * @type function * @date 18/10/13 * @since 5.0.0 * * @param $args (array) * @param $defaults (array) * @return $args (array) */ function acf_parse_args( $args, $defaults = array() ) { // $args may not be na array! if( !is_array($args) ) { $args = array(); } // parse args $args = wp_parse_args( $args, $defaults ); // parse types $args = acf_parse_types( $args ); // return return $args; } /* * acf_parse_types * * This function will convert any numeric values to int and trim strings * * @type function * @date 18/10/13 * @since 5.0.0 * * @param $var (mixed) * @return $var (mixed) */ function acf_parse_types( $array ) { // some keys are restricted $restricted = array( 'label', 'name', 'value', 'instructions', 'nonce' ); // loop foreach( array_keys($array) as $k ) { // parse type if not restricted if( !in_array($k, $restricted, true) ) { $array[ $k ] = acf_parse_type( $array[ $k ] ); } } // return return $array; } /* * acf_parse_type * * description * * @type function * @date 11/11/2014 * @since 5.0.9 * * @param $post_id (int) * @return $post_id (int) */ function acf_parse_type( $v ) { // test for array if( is_array($v) ) { return acf_parse_types($v); } // bail early if not string if( !is_string($v) ) { return $v; } // trim $v = trim($v); // numbers if( is_numeric($v) && strval((int)$v) === $v ) { $v = intval( $v ); } // return return $v; } /* * acf_get_view * * This function will load in a file from the 'admin/views' folder and allow variables to be passed through * * @type function * @date 28/09/13 * @since 5.0.0 * * @param $view_name (string) * @param $args (array) * @return n/a */ function acf_get_view( $view_name = '', $args = array() ) { // vars $path = acf_get_path("admin/views/{$view_name}.php"); if( file_exists($path) ) { include( $path ); } } /* * acf_merge_atts * * description * * @type function * @date 2/11/2014 * @since 5.0.9 * * @param $post_id (int) * @return $post_id (int) */ function acf_merge_atts( $atts, $extra = array() ) { // bail ealry if no $extra if( empty($extra) ) { return $atts; } // merge in new atts foreach( $extra as $k => $v ) { if( $k == 'class' || $k == 'style' ) { if( $v === '' ) { continue; } $v = $atts[ $k ] . ' ' . $v; } $atts[ $k ] = $v; } // return return $atts; } /* * acf_esc_attr * * This function will return a render of an array of attributes to be used in markup * * @type function * @date 1/10/13 * @since 5.0.0 * * @param $atts (array) * @return n/a */ function acf_esc_attr( $atts ) { // is string? if( is_string($atts) ) { $atts = trim( $atts ); return esc_attr( $atts ); } // validate if( empty($atts) ) { return ''; } // vars $e = array(); // loop through and render foreach( $atts as $k => $v ) { // object if( is_array($v) || is_object($v) ) { $v = json_encode($v); // boolean } elseif( is_bool($v) ) { $v = $v ? 1 : 0; // string } elseif( is_string($v) ) { $v = trim($v); } // append $e[] = $k . '="' . esc_attr( $v ) . '"'; } // echo return implode(' ', $e); } function acf_esc_attr_e( $atts ) { echo acf_esc_attr( $atts ); } /* * acf_hidden_input * * description * * @type function * @date 3/02/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function <API key>( $atts ) { $atts['type'] = 'hidden'; return '<input ' . acf_esc_attr( $atts ) . ' />'; } function acf_hidden_input( $atts ) { echo <API key>( $atts ); } /* * acf_extract_var * * This function will remove the var from the array, and return the var * * @type function * @date 2/10/13 * @since 5.0.0 * * @param $array (array) * @param $key (string) * @return (mixed) */ function acf_extract_var( &$array, $key ) { // check if exists if( is_array($array) && array_key_exists($key, $array) ) { // store value $v = $array[ $key ]; // unset unset( $array[ $key ] ); // return return $v; } // return return null; } /* * acf_extract_vars * * This function will remove the vars from the array, and return the vars * * @type function * @date 8/10/13 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_extract_vars( &$array, $keys ) { $r = array(); foreach( $keys as $key ) { $r[ $key ] = acf_extract_var( $array, $key ); } return $r; } /* * acf_get_post_types * * This function will return an array of available post types * * @type function * @date 7/10/13 * @since 5.0.0 * * @param $exclude (array) * @param $include (array) * @return (array) */ function acf_get_post_types( $exclude = array(), $include = array() ) { // get all custom post types $post_types = get_post_types(); // core exclude $exclude = wp_parse_args( $exclude, array('acf-field', 'acf-field-group', 'revision', 'nav_menu_item') ); // include if( !empty($include) ) { foreach( array_keys($include) as $i ) { $post_type = $include[ $i ]; if( post_type_exists($post_type) ) { $post_types[ $post_type ] = $post_type; } } } // exclude foreach( array_values($exclude) as $i ) { unset( $post_types[ $i ] ); } // simplify keys $post_types = array_values($post_types); // return return $post_types; } function <API key>( $post_types = array() ) { // get post types if( empty($post_types) ) { // get all custom post types $post_types = acf_get_post_types(); } // get labels $ref = array(); $r = array(); foreach( $post_types as $post_type ) { // vars $label = $post_type; // check that object exists (case exists when importing field group from another install and post type does not exist) if( post_type_exists($post_type) ) { $obj = <API key>($post_type); $label = $obj->labels->singular_name; } // append to r $r[ $post_type ] = $label; // increase counter if( !isset($ref[ $label ]) ) { $ref[ $label ] = 0; } $ref[ $label ]++; } // get slugs foreach( array_keys($r) as $i ) { // vars $post_type = $r[ $i ]; if( $ref[ $post_type ] > 1 ) { $r[ $i ] .= ' (' . $i . ')'; } } // return return $r; } /* * acf_verify_nonce * * This function will look at the $_POST['_acfnonce'] value and return true or false * * @type function * @date 15/10/13 * @since 5.0.0 * * @param $nonce (string) * @return (boolean) */ function acf_verify_nonce( $value, $post_id = 0 ) { // vars $nonce = acf_maybe_get( $_POST, '_acfnonce' ); // bail early if no nonce or if nonce does not match (post|user|comment|term) if( !$nonce || !wp_verify_nonce($nonce, $value) ) { return false; } // if saving specific post if( $post_id ) { // vars $form_post_id = (int) acf_maybe_get( $_POST, 'post_ID' ); $post_parent = wp_is_post_revision( $post_id ); // 1. no $_POST['post_id'] (shopp plugin) if( !$form_post_id ) { // do nothing (don't remove this if statement!) // 2. direct match (this is the post we were editing) } elseif( $post_id === $form_post_id ) { // do nothing (don't remove this if statement!) // 3. revision (this post is a revision of the post we were editing) } elseif( $post_parent === $form_post_id ) { // return true early and prevent $_POST['_acfnonce'] from being reset // this will allow another save_post to save the real post return true; } else { // return false early and prevent $_POST['_acfnonce'] from being reset // this will allow another save_post to save the real post return false; } } // reset nonce (only allow 1 save) $_POST['_acfnonce'] = false; // return return true; } /* * acf_verify_ajax * * This function will return true if the current AJAX request is valid * It's action will also allow WPML to set the lang and avoid AJAX get_posts issues * * @type function * @date 7/08/2015 * @since 5.2.3 * * @param n/a * @return (boolean) */ function acf_verify_ajax() { // bail early if not acf action if( empty($_POST['action']) || substr($_POST['action'], 0, 3) !== 'acf' ) { return false; } // bail early if not acf nonce if( empty($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'acf_nonce') ) { return false; } // action for 3rd party customization do_action('acf/verify_ajax'); // return return true; } /* * <API key> * * This function will add the notice data to a setting in the acf object for the admin_notices action to use * * @type function * @date 17/10/13 * @since 5.0.0 * * @param $text (string) * @param $class (string) * @return (int) message ID (array position) */ function <API key>( $text, $class = '', $wrap = 'p' ) { // vars $admin_notices = <API key>(); // add to array $admin_notices[] = array( 'text' => $text, 'class' => "updated {$class}", 'wrap' => $wrap ); // update acf_update_setting( 'admin_notices', $admin_notices ); // return return ( count( $admin_notices ) - 1 ); } /* * <API key> * * This function will return an array containing any admin notices * * @type function * @date 17/10/13 * @since 5.0.0 * * @param n/a * @return (array) */ function <API key>() { // vars $admin_notices = acf_get_setting( 'admin_notices' ); // validate if( !$admin_notices ) { $admin_notices = array(); } // return return $admin_notices; } /* * acf_get_image_sizes * * This function will return an array of available image sizes * * @type function * @date 23/10/13 * @since 5.0.0 * * @param n/a * @return (array) */ function acf_get_image_sizes() { // global global $<API key>; // vars $sizes = array( 'thumbnail' => __("Thumbnail",'acf'), 'medium' => __("Medium",'acf'), 'large' => __("Large",'acf') ); // find all sizes $all_sizes = <API key>(); // add extra registered sizes if( !empty($all_sizes) ) { foreach( $all_sizes as $size ) { // bail early if already in array if( isset($sizes[ $size ]) ) { continue; } // append to array $label = str_replace('-', ' ', $size); $label = ucwords( $label ); $sizes[ $size ] = $label; } } // add sizes foreach( array_keys($sizes) as $s ) { // vars $w = isset($<API key>[$s]['width']) ? $<API key>[$s]['width'] : get_option( "{$s}_size_w" ); $h = isset($<API key>[$s]['height']) ? $<API key>[$s]['height'] : get_option( "{$s}_size_h" ); if( $w && $h ) { $sizes[ $s ] .= " ({$w} x {$h})"; } } // add full end $sizes['full'] = __("Full Size",'acf'); // filter for 3rd party customization $sizes = apply_filters( 'acf/get_image_sizes', $sizes ); // return return $sizes; } /* * acf_get_taxonomies * * This function will return an array of available taxonomies * * @type function * @date 7/10/13 * @since 5.0.0 * * @param n/a * @return (array) */ function acf_get_taxonomies() { // get all taxonomies $taxonomies = get_taxonomies( false, 'objects' ); $ignore = array( 'nav_menu', 'link_category' ); $r = array(); // populate $r foreach( $taxonomies as $taxonomy ) { if( in_array($taxonomy->name, $ignore) ) { continue; } $r[ $taxonomy->name ] = $taxonomy->name; //"{$taxonomy->labels->singular_name}"; // ({$taxonomy->name}) } // return return $r; } function <API key>( $taxonomies = array() ) { // get post types if( empty($taxonomies) ) { // get all custom post types $taxonomies = acf_get_taxonomies(); } // get labels $ref = array(); $r = array(); foreach( array_keys($taxonomies) as $i ) { // vars $taxonomy = acf_extract_var( $taxonomies, $i); $obj = get_taxonomy( $taxonomy ); $name = $obj->labels->singular_name; // append to r $r[ $taxonomy ] = $name; // increase counter if( !isset($ref[ $name ]) ) { $ref[ $name ] = 0; } $ref[ $name ]++; } // get slugs foreach( array_keys($r) as $i ) { // vars $taxonomy = $r[ $i ]; if( $ref[ $taxonomy ] > 1 ) { $r[ $i ] .= ' (' . $i . ')'; } } // return return $r; } /* * <API key> * * This function will return an array of available taxonomy terms * * @type function * @date 7/10/13 * @since 5.0.0 * * @param $taxonomies (array) * @return (array) */ function <API key>( $taxonomies = array() ) { // force array $taxonomies = acf_get_array( $taxonomies ); // get pretty taxonomy names $taxonomies = <API key>( $taxonomies ); // vars $r = array(); // populate $r foreach( array_keys($taxonomies) as $taxonomy ) { // vars $label = $taxonomies[ $taxonomy ]; $terms = get_terms( $taxonomy, array( 'hide_empty' => false ) ); if( !empty($terms) ) { $r[ $label ] = array(); foreach( $terms as $term ) { $k = "{$taxonomy}:{$term->slug}"; $r[ $label ][ $k ] = $term->name; } } } // return return $r; } /* * <API key> * * This function decodes the $taxonomy:$term strings into a nested array * * @type function * @date 27/02/2014 * @since 5.0.0 * * @param $terms (array) * @return (array) */ function <API key>( $terms = false ) { // load all taxonomies if not specified in args if( !$terms ) { $terms = <API key>(); } // vars $r = array(); foreach( $terms as $term ) { // vars $data = <API key>( $term ); // create empty array if( !array_key_exists($data['taxonomy'], $r) ) { $r[ $data['taxonomy'] ] = array(); } // append to taxonomy $r[ $data['taxonomy'] ][] = $data['term']; } // return return $r; } /* * <API key> * * This function will convert a term string into an array of term data * * @type function * @date 31/03/2014 * @since 5.0.0 * * @param $string (string) * @return (array) */ function <API key>( $string ) { // vars $r = array(); // vars $data = explode(':', $string); $taxonomy = 'category'; $term = ''; // check data if( isset($data[1]) ) { $taxonomy = $data[0]; $term = $data[1]; } // add data to $r $r['taxonomy'] = $taxonomy; $r['term'] = $term; // return return $r; } /* * acf_cache_get * * This function is a wrapper for the wp_cache_get to allow for 3rd party customization * * @type function * @date 4/12/2013 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ /* function acf_cache_get( $key, &$found ) { // vars $group = 'acf'; $force = false; // load from cache $cache = wp_cache_get( $key, $group, $force, $found ); // allow 3rd party customization if cache was not found if( !$found ) { $custom = apply_filters("acf/get_cache/{$key}", $cache); if( $custom !== $cache ) { $cache = $custom; $found = true; } } // return return $cache; } */ /* * acf_get_array * * This function will force a variable to become an array * * @type function * @date 4/02/2014 * @since 5.0.0 * * @param $var (mixed) * @return (array) */ function acf_get_array( $var = false, $delimiter = ',' ) { // is array? if( is_array($var) ) { return $var; } // bail early if empty if( empty($var) && !is_numeric($var) ) { return array(); } // string if( is_string($var) && $delimiter ) { return explode($delimiter, $var); } // place in array return array( $var ); } /* * acf_get_posts * * This function will return an array of posts making sure the order is correct * * @type function * @date 3/03/2015 * @since 5.1.5 * * @param $args (array) * @return (array) */ function acf_get_posts( $args = array() ) { // vars $posts = array(); // defaults // leave suppress_filters as true becuase we don't want any plugins to modify the query as we know exactly what $args = acf_parse_args( $args, array( 'posts_per_page' => -1, 'post_type' => '', 'post_status' => 'any' )); // post type if( empty($args['post_type']) ) { $args['post_type'] = acf_get_post_types(); } // validate post__in if( $args['post__in'] ) { // force value to array $args['post__in'] = acf_get_array( $args['post__in'] ); // convert to int $args['post__in'] = array_map('intval', $args['post__in']); // add filter to remove post_type // use 'query' filter so that 'suppress_filters' can remain true //add_filter('query', '<API key>'); // order by post__in $args['orderby'] = 'post__in'; } // load posts in 1 query to save multiple DB calls from following code $posts = get_posts($args); // remove this filter (only once) //remove_filter('query', '<API key>'); // validate order if( $posts && $args['post__in'] ) { // vars $order = array(); // generate sort order foreach( $posts as $i => $post ) { $order[ $i ] = array_search($post->ID, $args['post__in']); } // sort array_multisort($order, $posts); } // return return $posts; } /* * <API key> * * This function will remove the 'wp_posts.post_type' WHERE clause completely * When using 'post__in', this clause is unneccessary and slow. * * @type function * @date 4/03/2015 * @since 5.1.5 * * @param $sql (string) * @return $sql */ function <API key>( $sql ) { // global global $wpdb; // bail ealry if no 'wp_posts.ID IN' if( strpos($sql, "$wpdb->posts.ID IN") === false ) { return $sql; } // get bits $glue = 'AND'; $bits = explode($glue, $sql); // loop through $where and remove any post_type queries foreach( $bits as $i => $bit ) { if( strpos($bit, "$wpdb->posts.post_type") !== false ) { unset( $bits[ $i ] ); } } // join $where back together $sql = implode($glue, $bits); // return return $sql; } /* * <API key> * * This function will return all posts grouped by post_type * This is handy for select settings * * @type function * @date 27/02/2014 * @since 5.0.0 * * @param $args (array) * @return (array) */ function <API key>( $args ) { // vars $r = array(); // defaults $args = acf_parse_args( $args, array( 'posts_per_page' => -1, 'paged' => 0, 'post_type' => 'post', 'orderby' => 'menu_order title', 'order' => 'ASC', 'post_status' => 'any', 'suppress_filters' => false, '<API key>' => false, )); // find array of post_type $post_types = acf_get_array( $args['post_type'] ); $post_types_labels = <API key>($post_types); // attachment doesn't work if it is the only item in an array if( count($post_types) == 1 ) { $args['post_type'] = current($post_types); } // add filter to orderby post type add_filter('posts_orderby', '<API key>', 10, 2); // get posts $posts = get_posts( $args ); // remove this filter (only once) remove_filter('posts_orderby', '<API key>'); // loop foreach( $post_types as $post_type ) { // vars $this_posts = array(); $this_group = array(); // populate $this_posts foreach( array_keys($posts) as $key ) { if( $posts[ $key ]->post_type == $post_type ) { $this_posts[] = acf_extract_var( $posts, $key ); } } // bail early if no posts for this post type if( empty($this_posts) ) { continue; } // sort into hierachial order! // this will fail if a search has taken place because parents wont exist if( <API key>($post_type) && empty($args['s'])) { // vars $match_id = $this_posts[ 0 ]->ID; $offset = 0; $length = count($this_posts); $parent = acf_maybe_get( $args, 'post_parent', 0 ); // reset $this_posts $this_posts = array(); // get all posts $all_args = array_merge($args, array( 'posts_per_page' => -1, 'paged' => 0, 'post_type' => $post_type )); $all_posts = get_posts( $all_args ); // loop over posts and update $offset foreach( $all_posts as $offset => $p ) { if( $p->ID == $match_id ) { break; } } // order posts $all_posts = get_page_children( $parent, $all_posts ); // append for( $i = $offset; $i < ($offset + $length); $i++ ) { $this_posts[] = acf_extract_var( $all_posts, $i); } } // populate $this_posts foreach( array_keys($this_posts) as $key ) { // extract post $post = acf_extract_var( $this_posts, $key ); // add to group $this_group[ $post->ID ] = $post; } // group by post type $post_type_name = $post_types_labels[ $post_type ]; $r[ $post_type_name ] = $this_group; } // return return $r; } function <API key>( $ordeby, $wp_query ) { // global global $wpdb; // get post types $post_types = $wp_query->get('post_type'); // prepend SQL if( is_array($post_types) ) { $post_types = implode("','", $post_types); $ordeby = "FIELD({$wpdb->posts}.post_type,'$post_types')," . $ordeby; } // return return $ordeby; } function acf_get_post_title( $post = 0 ) { // load post if given an ID if( is_numeric($post) ) { $post = get_post($post); } // title $title = get_the_title( $post->ID ); // empty if( $title === '' ) { $title = __('(no title)', 'acf'); } // ancestors if( $post->post_type != 'attachment' ) { $ancestors = get_ancestors( $post->ID, $post->post_type ); $title = str_repeat('- ', count($ancestors)) . $title; } // status if( get_post_status( $post->ID ) != "publish" ) { $title .= ' (' . get_post_status( $post->ID ) . ')'; } // return return $title; } function acf_order_by_search( $array, $search ) { // vars $weights = array(); $needle = strtolower( $search ); // add key prefix foreach( array_keys($array) as $k ) { $array[ '_' . $k ] = acf_extract_var( $array, $k ); } // add search weight foreach( $array as $k => $v ) { // vars $weight = 0; $haystack = strtolower( $v ); $strpos = strpos( $haystack, $needle ); // detect search match if( $strpos !== false ) { // set eright to length of match $weight = strlen( $search ); // increase weight if match starts at begining of string if( $strpos == 0 ) { $weight++; } } // append to wights $weights[ $k ] = $weight; } // sort the array with menu_order ascending array_multisort( $weights, SORT_DESC, $array ); // remove key prefix foreach( array_keys($array) as $k ) { $array[ substr($k,1) ] = acf_extract_var( $array, $k ); } // return return $array; } /* * acf_json_encode * * This function will return pretty JSON for all PHP versions * * @type function * @date 6/03/2014 * @since 5.0.0 * * @param $json (array) * @return (string) */ function acf_json_encode( $json ) { // PHP at least 5.4 if( version_compare(PHP_VERSION, '5.4.0', '>=') ) { return json_encode($json, JSON_PRETTY_PRINT); } // PHP less than 5.4 $json = json_encode($json); $result = ''; $pos = 0; $strLen = strlen($json); $indentStr = " "; $newLine = "\n"; $prevChar = ''; $outOfQuotes = true; for ($i=0; $i<=$strLen; $i++) { // Grab the next character in the string. $char = substr($json, $i, 1); // Are we inside a quoted string? if ($char == '"' && $prevChar != '\\') { $outOfQuotes = !$outOfQuotes; // If this character is the end of an element, // output a new line and indent the next line. } else if(($char == '}' || $char == ']') && $outOfQuotes) { $result .= $newLine; $pos for ($j=0; $j<$pos; $j++) { $result .= $indentStr; } } // Add the character to the result string. $result .= $char; // If this character is ':' adda space after it if($char == ':' && $outOfQuotes) { $result .= ' '; } // If the last character was the beginning of an element, // output a new line and indent the next line. if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) { $result .= $newLine; if ($char == '{' || $char == '[') { $pos ++; } for ($j = 0; $j < $pos; $j++) { $result .= $indentStr; } } $prevChar = $char; } // return return $result; } /* * acf_str_exists * * This function will return true if a sub string is found * * @type function * @date 1/05/2014 * @since 5.0.0 * * @param $needle (string) * @param $haystack (string) * @return (boolean) */ function acf_str_exists( $needle, $haystack ) { // return true if $haystack contains the $needle if( is_string($haystack) && strpos($haystack, $needle) !== false ) { return true; } // return return false; } /* * acf_debug * * description * * @type function * @date 2/05/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_debug() { // vars $args = func_get_args(); $s = array_shift($args); $o = ''; $nl = "\r\n"; // start script $o .= '<script type="text/javascript">' . $nl; $o .= 'console.log("' . $s . '"'; if( !empty($args) ) { foreach( $args as $arg ) { if( is_object($arg) || is_array($arg) ) { $arg = json_encode($arg); } elseif( is_bool($arg) ) { $arg = $arg ? 'true' : 'false'; }elseif( is_string($arg) ) { $arg = '"' . $arg . '"'; } $o .= ', ' . $arg; } } $o .= ');' . $nl; // end script $o .= '</script>' . $nl; // echo echo $o; } function acf_debug_start() { acf_update_setting( 'debug_start', memory_get_usage()); } function acf_debug_end() { $start = acf_get_setting( 'debug_start' ); $end = memory_get_usage(); return $end - $start; } /* * acf_get_updates * * This function will reutrn all or relevant updates for ACF * * @type function * @date 12/05/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_get_updates() { // vars $updates = array(); $plugin_version = acf_get_setting('version'); $acf_version = get_option('acf_version'); $path = acf_get_path('admin/updates'); // bail early if no version (not activated) if( !$acf_version ) { return false; } // check that path exists if( !file_exists( $path ) ) { return false; } $dir = opendir( $path ); while(false !== ( $file = readdir($dir)) ) { // only php files if( substr($file, -4) !== '.php' ) { continue; } // get version number $update_version = substr($file, 0, -4); // ignore if update is for a future version. May exist for testing if( version_compare( $update_version, $plugin_version, '>') ) { continue; } // ignore if update has already been run if( version_compare( $update_version, $acf_version, '<=') ) { continue; } // append $updates[] = $update_version; } // return return $updates; } /* * acf_encode_choices * * description * * @type function * @date 4/06/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_encode_choices( $array = array() ) { // bail early if not array if( !is_array($array) ) { return $array; } // vars $string = ''; if( !empty($array) ) { foreach( $array as $k => $v ) { if( $k !== $v ) { $array[ $k ] = $k . ' : ' . $v; } } $string = implode("\n", $array); } // return return $string; } function acf_decode_choices( $string = '' ) { // validate if( $string === '') { return array(); // force array on single numeric values } elseif( is_numeric($string) ) { return array( $string ); // bail early if not a a string } elseif( !is_string($string) ) { return $string; } // vars $array = array(); // explode $lines = explode("\n", $string); // key => value foreach( $lines as $line ) { // vars $k = trim($line); $v = trim($line); // look for ' : ' if( acf_str_exists(' : ', $line) ) { $line = explode(' : ', $line); $k = trim($line[0]); $v = trim($line[1]); } // append $array[ $k ] = $v; } // return return $array; } /* * <API key> * * This fucntion converts a date format string from JS to PHP * * @type function * @date 20/06/2014 * @since 5.0.0 * * @param $date (string) * @return $date (string) */ acf_update_setting('<API key>', array( // Year 'Y' => 'yy', // Numeric, 4 digits 1999, 2003 'y' => 'y', // Numeric, 2 digits 99, 03 // Month 'm' => 'mm', 'n' => 'm', 'F' => 'MM', 'M' => 'M', // Textual three letters Jan - Dec // Weekday 'l' => 'DD', 'D' => 'D', // Day of Month 'd' => 'dd', 'j' => 'd', 'S' => '', // The English suffix for the day of the month st, nd or th in the 1st, 2nd or 15th. )); function <API key>( $date ) { // vars $ignore = array(); // conversion $php_to_js = acf_get_setting('<API key>'); // loop over conversions foreach( $php_to_js as $replace => $search ) { // ignore this replace? if( in_array($search, $ignore) ) { continue; } // replace $date = str_replace($search, $replace, $date); // append to ignore $ignore[] = $replace; } // return return $date; } /* * <API key> * * This fucntion converts a date format string from PHP to JS * * @type function * @date 20/06/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function <API key>( $date ) { // vars $ignore = array(); // conversion $php_to_js = acf_get_setting('<API key>'); // loop over conversions foreach( $php_to_js as $search => $replace ) { // ignore this replace? if( in_array($search, $ignore) ) { continue; } // replace $date = str_replace($search, $replace, $date); // append to ignore $ignore[] = $replace; } // return return $date; } /* * <API key> * * description * * @type function * @date 15/07/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function <API key>( $name, $value ) { // get current user id $user_id = get_current_user_id(); // get user settings $settings = get_user_meta( $user_id, 'acf_user_settings', false ); // find settings if( isset($settings[0]) ) { $settings = $settings[0]; } else { $settings = array(); } // append setting $settings[ $name ] = $value; // update user data return update_metadata('user', $user_id, 'acf_user_settings', $settings); } /* * <API key> * * description * * @type function * @date 15/07/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function <API key>( $name = '', $default = false ) { // get current user id $user_id = get_current_user_id(); // get user settings $settings = get_user_meta( $user_id, 'acf_user_settings', false ); // bail arly if no settings if( empty($settings[0][$name]) ) { return $default; } // return return $settings[0][$name]; } /* * acf_in_array * * description * * @type function * @date 22/07/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_in_array( $value, $array ) { // bail early if not array if( !is_array($array) ) { return false; } // find value in array return in_array($value, $array); } /* * <API key> * * This function will return a valid post_id based on the current screen / parameter * * @type function * @date 8/12/2013 * @since 5.0.0 * * @param $post_id (mixed) * @return $post_id (mixed) */ function <API key>( $post_id = 0 ) { // set post_id to global if( !$post_id ) { $post_id = (int) get_the_ID(); } // allow for option == options if( $post_id == 'option' ) { $post_id = 'options'; } // $post_id may be an object if( is_object($post_id) ) { if( isset($post_id->roles, $post_id->ID) ) { $post_id = 'user_' . $post_id->ID; } elseif( isset($post_id->taxonomy, $post_id->term_id) ) { $post_id = $post_id->taxonomy . '_' . $post_id->term_id; } elseif( isset($post_id->comment_ID) ) { $post_id = 'comment_' . $post_id->comment_ID; } elseif( isset($post_id->ID) ) { $post_id = $post_id->ID; } } // append language code if( $post_id == 'options' ) { $dl = acf_get_setting('default_language'); $cl = acf_get_setting('current_language'); if( $cl && $cl !== $dl ) { $post_id .= '_' . $cl; } } /* * Override for preview * * If the $_GET['preview_id'] is set, then the user wants to see the preview data. * There is also the case of previewing a page with post_id = 1, but using get_field * to load data from another post_id. * In this case, we need to make sure that the autosave revision is actually related * to the $post_id variable. If they match, then the autosave data will be used, otherwise, * the user wants to load data from a completely different post_id */ if( isset($_GET['preview_id']) ) { $autosave = <API key>( $_GET['preview_id'] ); if( $autosave && $autosave->post_parent == $post_id ) { $post_id = (int) $autosave->ID; } } // return return $post_id; } /* * acf_upload_files * * This function will walk througfh the $_FILES data and upload each found * * @type function * @date 25/10/2014 * @since 5.0.9 * * @param $ancestors (array) an internal parameter, not required * @return n/a */ function acf_upload_files( $ancestors = array() ) { // vars $file = array( 'name' => '', 'type' => '', 'tmp_name' => '', 'error' => '', 'size' => '' ); // populate with $_FILES data foreach( array_keys($file) as $k ) { $file[ $k ] = $_FILES['acf'][ $k ]; } // walk through ancestors if( !empty($ancestors) ) { foreach( $ancestors as $a ) { foreach( array_keys($file) as $k ) { $file[ $k ] = $file[ $k ][ $a ]; } } } // is array? if( is_array($file['name']) ) { foreach( array_keys($file['name']) as $k ) { $_ancestors = array_merge($ancestors, array($k)); acf_upload_files( $_ancestors ); } return; } // bail ealry if file has error (no file uploaded) if( $file['error'] ) { return; } // assign global _acfuploader for media validation $_POST['_acfuploader'] = end($ancestors); // file found! $attachment_id = acf_upload_file( $file ); // update $_POST array_unshift($ancestors, 'acf'); <API key>( $_POST, $ancestors, $attachment_id ); } /* * acf_upload_file * * This function will uploade a $_FILE * * @type function * @date 27/10/2014 * @since 5.0.9 * * @param $uploaded_file (array) array found from $_FILE data * @return $id (int) new attachment ID */ function acf_upload_file( $uploaded_file ) { // required require_once(ABSPATH . "/wp-load.php"); require_once(ABSPATH . "/wp-admin/includes/file.php"); require_once(ABSPATH . "/wp-admin/includes/image.php"); // required for wp_handle_upload() to upload the file $upload_overrides = array( 'test_form' => false ); // upload $file = wp_handle_upload( $uploaded_file, $upload_overrides ); // bail ealry if upload failed if( isset($file['error']) ) { return $file['error']; } // vars $url = $file['url']; $type = $file['type']; $file = $file['file']; $filename = basename($file); // Construct the object array $object = array( 'post_title' => $filename, 'post_mime_type' => $type, 'guid' => $url, 'context' => 'acf-upload' ); // Save the data $id = <API key>($object, $file); // Add the meta-data <API key>( $id, <API key>( $id, $file ) ); /** This action is documented in wp-admin/custom-header.php */ do_action( '<API key>', $file, $id ); // For replication // return new ID return $id; } /* * <API key> * * This function will update a nested array value. Useful for modifying the $_POST array * * @type function * @date 27/10/2014 * @since 5.0.9 * * @param $array (array) target array to be updated * @param $ancestors (array) array of keys to navigate through to find the child * @param $value (mixed) The new value * @return (boolean) */ function <API key>( &$array, $ancestors, $value ) { // if no more ancestors, update the current var if( empty($ancestors) ) { $array = $value; // return return true; } // shift the next ancestor from the array $k = array_shift( $ancestors ); // if exists if( isset($array[ $k ]) ) { return <API key>( $array[ $k ], $ancestors, $value ); } // return return false; } /* * acf_is_screen * * This function will return true if all args are matched for the current screen * * @type function * @date 9/12/2014 * @since 5.1.5 * * @param $post_id (int) * @return $post_id (int) */ function acf_is_screen( $id = '' ) { // vars $current_screen = get_current_screen(); // return return ($id === $current_screen->id); } /* * acf_maybe_get * * This function will return a var if it exists in an array * * @type function * @date 9/12/2014 * @since 5.1.5 * * @param $array (array) the array to look within * @param $key (key) the array key to look for. Nested values may be found using '/' * @param $default (mixed) the value returned if not found * @return $post_id (int) */ function acf_maybe_get( $array, $key, $default = null ) { // vars $keys = explode('/', $key); // loop through keys foreach( $keys as $k ) { // return default if does not exist if( !isset($array[ $k ]) ) { return $default; } // update $array $array = $array[ $k ]; } // return return $array; } /* * acf_get_attachment * * This function will return an array of attachment data * * @type function * @date 5/01/2015 * @since 5.1.5 * * @param $post (mixed) either post ID or post object * @return (array) */ function acf_get_attachment( $post ) { // get post if ( !$post = get_post( $post ) ) { return false; } // vars $thumb_id = 0; $id = $post->ID; $a = array( 'ID' => $id, 'id' => $id, 'title' => $post->post_title, 'filename' => wp_basename( $post->guid ), 'url' => <API key>( $id ), 'alt' => get_post_meta($id, '<API key>', true), 'author' => $post->post_author, 'description' => $post->post_content, 'caption' => $post->post_excerpt, 'name' => $post->post_name, 'date' => $post->post_date_gmt, 'modified' => $post->post_modified_gmt, 'mime_type' => $post->post_mime_type, 'type' => acf_maybe_get( explode('/', $post->post_mime_type), 0, '' ), 'icon' => wp_mime_type_icon( $id ) ); // video may use featured image if( $a['type'] === 'image' ) { $thumb_id = $id; $src = <API key>( $id, 'full' ); $a['url'] = $src[0]; $a['width'] = $src[1]; $a['height'] = $src[2]; } elseif( $a['type'] === 'audio' || $a['type'] === 'video' ) { // video dimentions if( $a['type'] == 'video' ) { $meta = <API key>( $id ); $a['width'] = acf_maybe_get($meta, 'width', 0); $a['height'] = acf_maybe_get($meta, 'height', 0); } // feature image if( $featured_id = <API key>($id) ) { $thumb_id = $featured_id; } } // sizes if( $thumb_id ) { // find all image sizes if( $sizes = <API key>() ) { $a['sizes'] = array(); foreach( $sizes as $size ) { // url $src = <API key>( $thumb_id, $size ); // add src $a['sizes'][ $size ] = $src[0]; $a['sizes'][ $size . '-width' ] = $src[1]; $a['sizes'][ $size . '-height' ] = $src[2]; } } } // return return $a; } /* * acf_get_truncated * * This function will truncate and return a string * * @type function * @date 8/08/2014 * @since 5.0.0 * * @param $text (string) * @param $length (int) * @return (string) */ function acf_get_truncated( $text, $length = 64 ) { // vars $text = trim($text); $the_length = strlen( $text ); // cut $return = substr( $text, 0, ($length - 3) ); if( $the_length > ($length - 3) ) { $return .= '...'; } // return return $return; } /* * acf_get_current_url * * This function will return the current URL * * @type function * @date 23/01/2015 * @since 5.1.5 * * @param n/a * @return (string) */ function acf_get_current_url() { // vars $home = home_url(); $url = home_url($_SERVER['REQUEST_URI']); // test //$url = $home . '/dev/wp-admin/api-template/acf_form'; // explode url (4th bit is the sub folder) $bits = explode('/', $home, 4); /* Array ( [0] => http: [1] => [2] => acf5 [3] => dev ) */ // handle sub folder if( !empty($bits[3]) ) { $find = '/' . $bits[3]; $pos = strpos($url, $find); $length = strlen($find); if( $pos !== false ) { $url = substr_replace($url, '', $pos, $length); } } // return return $url; } /* * <API key> * * This function will return true if the current user can administrate the ACF field groups * * @type function * @date 9/02/2015 * @since 5.1.5 * * @param $post_id (int) * @return $post_id (int) */ function <API key>() { if( acf_get_setting('show_admin') && current_user_can(acf_get_setting('capability')) ) { return true; } // return return false; } /* * acf_get_filesize * * This function will return a numeric value of bytes for a given filesize string * * @type function * @date 18/02/2015 * @since 5.1.5 * * @param $size (mixed) * @return (int) */ function acf_get_filesize( $size = 1 ) { // vars $unit = 'MB'; $units = array( 'TB' => 4, 'GB' => 3, 'MB' => 2, 'KB' => 1, ); // look for $unit within the $size parameter (123 KB) if( is_string($size) ) { // vars $custom = strtoupper( substr($size, -2) ); foreach( $units as $k => $v ) { if( $custom === $k ) { $unit = $k; $size = substr($size, 0, -2); } } } // calc bytes $bytes = floatval($size) * pow(1024, $units[$unit]); // return return $bytes; } /* * acf_format_filesize * * This function will return a formatted string containing the filesize and unit * * @type function * @date 18/02/2015 * @since 5.1.5 * * @param $size (mixed) * @return (int) */ function acf_format_filesize( $size = 1 ) { // convert $bytes = acf_get_filesize( $size ); // vars $units = array( 'TB' => 4, 'GB' => 3, 'MB' => 2, 'KB' => 1, ); // loop through units foreach( $units as $k => $v ) { $result = $bytes / pow(1024, $v); if( $result >= 1 ) { return $result . ' ' . $k; } } // return return $bytes . ' B'; } /* * acf_get_valid_terms * * This function will replace old terms with new split term ids * * @type function * @date 27/02/2015 * @since 5.1.5 * * @param $terms (int|array) * @param $taxonomy (string) * @return $terms */ function acf_get_valid_terms( $terms = false, $taxonomy = 'category' ) { // bail early if function does not yet exist or if( !function_exists('wp_get_split_term') || empty($terms) ) { return $terms; } // vars $is_array = is_array($terms); // force into array $terms = acf_get_array( $terms ); // force ints $terms = array_map('intval', $terms); // attempt to find new terms foreach( $terms as $i => $term_id ) { $new_term_id = wp_get_split_term($term_id, $taxonomy); if( $new_term_id ) { $terms[ $i ] = $new_term_id; } } // revert array if needed if( !$is_array ) { $terms = $terms[0]; } // return return $terms; } /* * acf_esc_html_deep * * Navigates through an array and escapes html from the values. * * @type function * @date 10/06/2015 * @since 5.2.7 * * @param $value (mixed) * @return $value */ /* function acf_esc_html_deep( $value ) { // array if( is_array($value) ) { $value = array_map('acf_esc_html_deep', $value); // object } elseif( is_object($value) ) { $vars = get_object_vars( $value ); foreach( $vars as $k => $v ) { $value->{$k} = acf_esc_html_deep( $v ); } // string } elseif( is_string($value) ) { $value = esc_html($value); } // return return $value; } */ /* * <API key> * * This function will validate an attachment based on a field's resrictions and return an array of errors * * @type function * @date 3/07/2015 * @since 5.2.3 * * @param $attachment (array) attachment data. Cahnges based on context * @param $field (array) field settings containing restrictions * @param $context (string) $file is different when uploading / preparing * @return $errors (array) */ function <API key>( $attachment, $field, $context = 'prepare' ) { // vars $errors = array(); $file = array( 'type' => '', 'width' => 0, 'height' => 0, 'size' => 0 ); // upload if( $context == 'upload' ) { // vars $file['type'] = pathinfo($attachment['name'], PATHINFO_EXTENSION); $file['size'] = filesize($attachment['tmp_name']); if( strpos($attachment['type'], 'image') !== false ) { $size = getimagesize($attachment['tmp_name']); $file['width'] = acf_maybe_get($size, 0); $file['height'] = acf_maybe_get($size, 1); } // prepare } elseif( $context == 'prepare' ) { $file['type'] = pathinfo($attachment['url'], PATHINFO_EXTENSION); $file['size'] = acf_maybe_get($attachment, 'filesizeInBytes', 0); $file['width'] = acf_maybe_get($attachment, 'width', 0); $file['height'] = acf_maybe_get($attachment, 'height', 0); // custom } else { $file = wp_parse_args($file, $attachment); } // image if( $file['width'] || $file['height'] ) { // width $min_width = (int) acf_maybe_get($field, 'min_width', 0); $max_width = (int) acf_maybe_get($field, 'max_width', 0); if( $file['width'] ) { if( $min_width && $file['width'] < $min_width ) { // min width $errors['min_width'] = sprintf(__('Image width must be at least %dpx.', 'acf'), $min_width ); } elseif( $max_width && $file['width'] > $max_width ) { // min width $errors['max_width'] = sprintf(__('Image width must not exceed %dpx.', 'acf'), $max_width ); } } // height $min_height = (int) acf_maybe_get($field, 'min_height', 0); $max_height = (int) acf_maybe_get($field, 'max_height', 0); if( $file['height'] ) { if( $min_height && $file['height'] < $min_height ) { // min height $errors['min_height'] = sprintf(__('Image height must be at least %dpx.', 'acf'), $min_height ); } elseif( $max_height && $file['height'] > $max_height ) { // min height $errors['max_height'] = sprintf(__('Image height must not exceed %dpx.', 'acf'), $max_height ); } } } // file size if( $file['size'] ) { $min_size = acf_maybe_get($field, 'min_size', 0); $max_size = acf_maybe_get($field, 'max_size', 0); if( $min_size && $file['size'] < acf_get_filesize($min_size) ) { // min width $errors['min_size'] = sprintf(__('File size must be at least %s.', 'acf'), acf_format_filesize($min_size) ); } elseif( $max_size && $file['size'] > acf_get_filesize($max_size) ) { // min width $errors['max_size'] = sprintf(__('File size must must not exceed %s.', 'acf'), acf_format_filesize($max_size) ); } } // file type if( $file['type'] ) { $mime_types = acf_maybe_get($field, 'mime_types', ''); // lower case $file['type'] = strtolower($file['type']); $mime_types = strtolower($mime_types); // explode $mime_types = str_replace(array(' ', '.'), '', $mime_types); $mime_types = explode(',', $mime_types); // split pieces $mime_types = array_filter($mime_types); // remove empty pieces if( !empty($mime_types) && !in_array($file['type'], $mime_types) ) { // glue together last 2 types if( count($mime_types) > 1 ) { $last1 = array_pop($mime_types); $last2 = array_pop($mime_types); $mime_types[] = $last2 . ' ' . __('or', 'acf') . ' ' . $last1; } $errors['mime_types'] = sprintf(__('File type must be %s.', 'acf'), implode(', ', $mime_types) ); } } // filter for 3rd party customization $errors = apply_filters("acf/validate_attachment", $errors, $file, $attachment, $field); $errors = apply_filters("acf/validate_attachment/type={$field['type']}", $errors, $file, $attachment, $field ); $errors = apply_filters("acf/validate_attachment/name={$field['name']}", $errors, $file, $attachment, $field ); $errors = apply_filters("acf/validate_attachment/key={$field['key']}", $errors, $file, $attachment, $field ); // return return $errors; } /* * <API key> * * Dynamic logic for uploader setting * * @type function * @date 7/05/2015 * @since 5.2.3 * * @param $uploader (string) * @return $uploader */ add_filter('acf/settings/uploader', '<API key>'); function <API key>( $uploader ) { // if can't upload files if( !current_user_can('upload_files') ) { $uploader = 'basic'; } // return return $uploader; } /* * Hacks * * description * * @type function * @date 17/01/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ add_filter("acf/settings/slug", '_acf_settings_slug'); function _acf_settings_slug( $v ) { $basename = acf_get_setting('basename'); $slug = explode('/', $basename); $slug = current($slug); return $slug; } ?>
<?xml version="1.0" encoding="UTF-8" ?> <! If you are working with a multi language form keep the order! <option lang="de">Deutschland</option> <option lang="de">Groß Britannien</option> <option lang="en">Germany</option> <option lang="en">United Kingdom</option> If you don't keep the order and the user switches the country you will have a wrong translation! <select_countries> <option lang="de">Deutschland</option> <option lang="de">Groß Britannien</option> <option lang="de">Frankreich</option> <option lang="de">Österreich</option> <option lang="en">Germany</option> <option lang="en">United Kingdom</option> <option lang="en">France</option> <option lang="en">Austria</option> </select_countries>
import { Query } from "../services"; export interface QueryState { queries?: Query[]; loading?: boolean; error?: String; visibilityFilter?: string; }
#include "xfs.h" #include "xfs_fs.h" #include "xfs_log_format.h" #include "xfs_trans_resv.h" #include "xfs_sb.h" #include "xfs_ag.h" #include "xfs_mount.h" #include "xfs_trans.h" #include "xfs_trans_priv.h" #include "xfs_trace.h" #include "xfs_error.h" #include "xfs_log.h" #ifdef DEBUG /* * Check that the list is sorted as it should be. */ STATIC void xfs_ail_check( struct xfs_ail *ailp, xfs_log_item_t *lip) { xfs_log_item_t *prev_lip; if (list_empty(&ailp->xa_ail)) return; /* * Check the next and previous entries are valid. */ ASSERT((lip->li_flags & XFS_LI_IN_AIL) != 0); prev_lip = list_entry(lip->li_ail.prev, xfs_log_item_t, li_ail); if (&prev_lip->li_ail != &ailp->xa_ail) ASSERT(XFS_LSN_CMP(prev_lip->li_lsn, lip->li_lsn) <= 0); prev_lip = list_entry(lip->li_ail.next, xfs_log_item_t, li_ail); if (&prev_lip->li_ail != &ailp->xa_ail) ASSERT(XFS_LSN_CMP(prev_lip->li_lsn, lip->li_lsn) >= 0); } #else /* !DEBUG */ #define xfs_ail_check(a,l) #endif /* DEBUG */ /* * Return a pointer to the last item in the AIL. If the AIL is empty, then * return NULL. */ static xfs_log_item_t * xfs_ail_max( struct xfs_ail *ailp) { if (list_empty(&ailp->xa_ail)) return NULL; return list_entry(ailp->xa_ail.prev, xfs_log_item_t, li_ail); } /* * Return a pointer to the item which follows the given item in the AIL. If * the given item is the last item in the list, then return NULL. */ static xfs_log_item_t * xfs_ail_next( struct xfs_ail *ailp, xfs_log_item_t *lip) { if (lip->li_ail.next == &ailp->xa_ail) return NULL; return list_first_entry(&lip->li_ail, xfs_log_item_t, li_ail); } /* * This is called by the log manager code to determine the LSN of the tail of * the log. This is exactly the LSN of the first item in the AIL. If the AIL * is empty, then this function returns 0. * * We need the AIL lock in order to get a coherent read of the lsn of the last * item in the AIL. */ xfs_lsn_t xfs_ail_min_lsn( struct xfs_ail *ailp) { xfs_lsn_t lsn = 0; xfs_log_item_t *lip; spin_lock(&ailp->xa_lock); lip = xfs_ail_min(ailp); if (lip) lsn = lip->li_lsn; spin_unlock(&ailp->xa_lock); return lsn; } /* * Return the maximum lsn held in the AIL, or zero if the AIL is empty. */ static xfs_lsn_t xfs_ail_max_lsn( struct xfs_ail *ailp) { xfs_lsn_t lsn = 0; xfs_log_item_t *lip; spin_lock(&ailp->xa_lock); lip = xfs_ail_max(ailp); if (lip) lsn = lip->li_lsn; spin_unlock(&ailp->xa_lock); return lsn; } /* * The cursor keeps track of where our current traversal is up to by tracking * the next item in the list for us. However, for this to be safe, removing an * object from the AIL needs to invalidate any cursor that points to it. hence * the traversal cursor needs to be linked to the struct xfs_ail so that * deletion can search all the active cursors for invalidation. */ STATIC void <API key>( struct xfs_ail *ailp, struct xfs_ail_cursor *cur) { cur->item = NULL; list_add_tail(&cur->list, &ailp->xa_cursors); } /* * Get the next item in the traversal and advance the cursor. If the cursor * was invalidated (indicated by a lip of 1), restart the traversal. */ struct xfs_log_item * <API key>( struct xfs_ail *ailp, struct xfs_ail_cursor *cur) { struct xfs_log_item *lip = cur->item; if ((__psint_t)lip & 1) lip = xfs_ail_min(ailp); if (lip) cur->item = xfs_ail_next(ailp, lip); return lip; } /* * When the traversal is complete, we need to remove the cursor from the list * of traversing cursors. */ void <API key>( struct xfs_ail_cursor *cur) { cur->item = NULL; list_del_init(&cur->list); } /* * Invalidate any cursor that is pointing to this item. This is called when an * item is removed from the AIL. Any cursor pointing to this object is now * invalid and the traversal needs to be terminated so it doesn't reference a * freed object. We set the low bit of the cursor item pointer so we can * distinguish between an invalidation and the end of the list when getting the * next item from the cursor. */ STATIC void <API key>( struct xfs_ail *ailp, struct xfs_log_item *lip) { struct xfs_ail_cursor *cur; list_for_each_entry(cur, &ailp->xa_cursors, list) { if (cur->item == lip) cur->item = (struct xfs_log_item *) ((__psint_t)cur->item | 1); } } /* * Find the first item in the AIL with the given @lsn by searching in ascending * LSN order and initialise the cursor to point to the next item for a * ascending traversal. Pass a @lsn of zero to initialise the cursor to the * first item in the AIL. Returns NULL if the list is empty. */ xfs_log_item_t * <API key>( struct xfs_ail *ailp, struct xfs_ail_cursor *cur, xfs_lsn_t lsn) { xfs_log_item_t *lip; <API key>(ailp, cur); if (lsn == 0) { lip = xfs_ail_min(ailp); goto out; } list_for_each_entry(lip, &ailp->xa_ail, li_ail) { if (XFS_LSN_CMP(lip->li_lsn, lsn) >= 0) goto out; } return NULL; out: if (lip) cur->item = xfs_ail_next(ailp, lip); return lip; } static struct xfs_log_item * <API key>( struct xfs_ail *ailp, xfs_lsn_t lsn) { xfs_log_item_t *lip; <API key>(lip, &ailp->xa_ail, li_ail) { if (XFS_LSN_CMP(lip->li_lsn, lsn) <= 0) return lip; } return NULL; } /* * Find the last item in the AIL with the given @lsn by searching in descending * LSN order and initialise the cursor to point to that item. If there is no * item with the value of @lsn, then it sets the cursor to the last item with an * LSN lower than @lsn. Returns NULL if the list is empty. */ struct xfs_log_item * <API key>( struct xfs_ail *ailp, struct xfs_ail_cursor *cur, xfs_lsn_t lsn) { <API key>(ailp, cur); cur->item = <API key>(ailp, lsn); return cur->item; } /* * Splice the log item list into the AIL at the given LSN. We splice to the * tail of the given LSN to maintain insert order for push traversals. The * cursor is optional, allowing repeated updates to the same LSN to avoid * repeated traversals. This should not be called with an empty list. */ static void xfs_ail_splice( struct xfs_ail *ailp, struct xfs_ail_cursor *cur, struct list_head *list, xfs_lsn_t lsn) { struct xfs_log_item *lip; ASSERT(!list_empty(list)); /* * Use the cursor to determine the insertion point if one is * provided. If not, or if the one we got is not valid, * find the place in the AIL where the items belong. */ lip = cur ? cur->item : NULL; if (!lip || (__psint_t) lip & 1) lip = <API key>(ailp, lsn); /* * If a cursor is provided, we know we're processing the AIL * in lsn order, and future items to be spliced in will * follow the last one being inserted now. Update the * cursor to point to that last item, now while we have a * reliable pointer to it. */ if (cur) cur->item = list_entry(list->prev, struct xfs_log_item, li_ail); /* * Finally perform the splice. Unless the AIL was empty, * lip points to the item in the AIL _after_ which the new * items should go. If lip is null the AIL was empty, so * the new items go at the head of the AIL. */ if (lip) list_splice(list, &lip->li_ail); else list_splice(list, &ailp->xa_ail); } /* * Delete the given item from the AIL. Return a pointer to the item. */ static void xfs_ail_delete( struct xfs_ail *ailp, xfs_log_item_t *lip) { xfs_ail_check(ailp, lip); list_del(&lip->li_ail); <API key>(ailp, lip); } static long xfsaild_push( struct xfs_ail *ailp) { xfs_mount_t *mp = ailp->xa_mount; struct xfs_ail_cursor cur; xfs_log_item_t *lip; xfs_lsn_t lsn; xfs_lsn_t target; long tout; int stuck = 0; int flushing = 0; int count = 0; /* * If we encountered pinned items or did not finish writing out all * buffers the last time we ran, force the log first and wait for it * before pushing again. */ if (ailp->xa_log_flush && ailp->xa_last_pushed_lsn == 0 && (!list_empty_careful(&ailp->xa_buf_list) || xfs_ail_min_lsn(ailp))) { ailp->xa_log_flush = 0; XFS_STATS_INC(xs_push_ail_flush); xfs_log_force(mp, XFS_LOG_SYNC); } spin_lock(&ailp->xa_lock); /* barrier matches the xa_target update in xfs_ail_push() */ smp_rmb(); target = ailp->xa_target; ailp->xa_target_prev = target; lip = <API key>(ailp, &cur, ailp->xa_last_pushed_lsn); if (!lip) { /* * If the AIL is empty or our push has reached the end we are * done now. */ <API key>(&cur); spin_unlock(&ailp->xa_lock); goto out_done; } XFS_STATS_INC(xs_push_ail); lsn = lip->li_lsn; while ((XFS_LSN_CMP(lip->li_lsn, target) <= 0)) { int lock_result; /* * Note that iop_push may unlock and reacquire the AIL lock. We * rely on the AIL cursor implementation to be able to deal with * the dropped lock. */ lock_result = lip->li_ops->iop_push(lip, &ailp->xa_buf_list); switch (lock_result) { case XFS_ITEM_SUCCESS: XFS_STATS_INC(xs_push_ail_success); trace_xfs_ail_push(lip); ailp->xa_last_pushed_lsn = lsn; break; case XFS_ITEM_FLUSHING: /* * The item or its backing buffer is already beeing * flushed. The typical reason for that is that an * inode buffer is locked because we already pushed the * updates to it as part of inode clustering. * * We do not want to to stop flushing just because lots * of items are already beeing flushed, but we need to * re-try the flushing relatively soon if most of the * AIL is beeing flushed. */ XFS_STATS_INC(<API key>); <API key>(lip); flushing++; ailp->xa_last_pushed_lsn = lsn; break; case XFS_ITEM_PINNED: XFS_STATS_INC(xs_push_ail_pinned); <API key>(lip); stuck++; ailp->xa_log_flush++; break; case XFS_ITEM_LOCKED: XFS_STATS_INC(xs_push_ail_locked); <API key>(lip); stuck++; break; default: ASSERT(0); break; } count++; /* * Are there too many items we can't do anything with? * * If we we are skipping too many items because we can't flush * them or they are already being flushed, we back off and * given them time to complete whatever operation is being * done. i.e. remove pressure from the AIL while we can't make * progress so traversals don't slow down further inserts and * removals to/from the AIL. * * The value of 100 is an arbitrary magic number based on * observation. */ if (stuck > 100) break; lip = <API key>(ailp, &cur); if (lip == NULL) break; lsn = lip->li_lsn; } <API key>(&cur); spin_unlock(&ailp->xa_lock); if (<API key>(&ailp->xa_buf_list)) ailp->xa_log_flush++; if (!count || XFS_LSN_CMP(lsn, target) >= 0) { out_done: /* * We reached the target or the AIL is empty, so wait a bit * longer for I/O to complete and remove pushed items from the * AIL before we start the next scan from the start of the AIL. */ tout = 50; ailp->xa_last_pushed_lsn = 0; } else if (((stuck + flushing) * 100) / count > 90) { /* * Either there is a lot of contention on the AIL or we are * stuck due to operations in progress. "Stuck" in this case * is defined as >90% of the items we tried to push were stuck. * * Backoff a bit more to allow some I/O to complete before * restarting from the start of the AIL. This prevents us from * spinning on the same items, and if they are pinned will all * the restart to issue a log force to unpin the stuck items. */ tout = 20; ailp->xa_last_pushed_lsn = 0; } else { /* * Assume we have more work to do in a short while. */ tout = 10; } return tout; } static int xfsaild( void *data) { struct xfs_ail *ailp = data; long tout = 0; /* milliseconds */ set_freezable(); current->flags |= PF_MEMALLOC; while (!<API key>(NULL)) { if (tout && tout <= 20) __set_current_state(TASK_KILLABLE); else __set_current_state(TASK_INTERRUPTIBLE); spin_lock(&ailp->xa_lock); /* * Idle if the AIL is empty and we are not racing with a target * update. We check the AIL after we set the task to a sleep * state to guarantee that we either catch an xa_target update * or that a wake_up resets the state to TASK_RUNNING. * Otherwise, we run the risk of sleeping indefinitely. * * The barrier matches the xa_target update in xfs_ail_push(). */ smp_rmb(); if (!xfs_ail_min(ailp) && ailp->xa_target == ailp->xa_target_prev) { spin_unlock(&ailp->xa_lock); schedule(); try_to_freeze(); tout = 0; continue; } spin_unlock(&ailp->xa_lock); if (tout) schedule_timeout(msecs_to_jiffies(tout)); __set_current_state(TASK_RUNNING); try_to_freeze(); tout = xfsaild_push(ailp); } return 0; } /* * This routine is called to move the tail of the AIL forward. It does this by * trying to flush items in the AIL whose lsns are below the given * threshold_lsn. * * The push is run asynchronously in a workqueue, which means the caller needs * to handle waiting on the async flush for space to become available. * We don't want to interrupt any push that is in progress, hence we only queue * work if we set the pushing bit approriately. * * We do this unlocked - we only need to know whether there is anything in the * AIL at the time we are called. We don't need to access the contents of * any of the objects, so the lock is not needed. */ void xfs_ail_push( struct xfs_ail *ailp, xfs_lsn_t threshold_lsn) { xfs_log_item_t *lip; lip = xfs_ail_min(ailp); if (!lip || XFS_FORCED_SHUTDOWN(ailp->xa_mount) || XFS_LSN_CMP(threshold_lsn, ailp->xa_target) <= 0) return; /* * Ensure that the new target is noticed in push code before it clears * the XFS_AIL_PUSHING_BIT. */ smp_wmb(); <API key>(ailp, &ailp->xa_target, &threshold_lsn); smp_wmb(); wake_up_process(ailp->xa_task); } /* * Push out all items in the AIL immediately */ void xfs_ail_push_all( struct xfs_ail *ailp) { xfs_lsn_t threshold_lsn = xfs_ail_max_lsn(ailp); if (threshold_lsn) xfs_ail_push(ailp, threshold_lsn); } /* * Push out all items in the AIL immediately and wait until the AIL is empty. */ void <API key>( struct xfs_ail *ailp) { struct xfs_log_item *lip; DEFINE_WAIT(wait); spin_lock(&ailp->xa_lock); while ((lip = xfs_ail_max(ailp)) != NULL) { prepare_to_wait(&ailp->xa_empty, &wait, <API key>); ailp->xa_target = lip->li_lsn; wake_up_process(ailp->xa_task); spin_unlock(&ailp->xa_lock); schedule(); spin_lock(&ailp->xa_lock); } spin_unlock(&ailp->xa_lock); finish_wait(&ailp->xa_empty, &wait); } /* * <API key> - bulk AIL insertion operation. * * @<API key> takes an array of log items that all need to be * positioned at the same LSN in the AIL. If an item is not in the AIL, it will * be added. Otherwise, it will be repositioned by removing it and re-adding * it to the AIL. If we move the first item in the AIL, update the log tail to * match the new minimum LSN in the AIL. * * This function takes the AIL lock once to execute the update operations on * all the items in the array, and as such should not be called with the AIL * lock held. As a result, once we have the AIL lock, we need to check each log * item LSN to confirm it needs to be moved forward in the AIL. * * To optimise the insert operation, we delete all the items from the AIL in * the first pass, moving them into a temporary list, then splice the temporary * list into the correct position in the AIL. This avoids needing to do an * insert operation on every item. * * This function must be called with the AIL lock held. The lock is dropped * before returning. */ void <API key>( struct xfs_ail *ailp, struct xfs_ail_cursor *cur, struct xfs_log_item **log_items, int nr_items, xfs_lsn_t lsn) __releases(ailp->xa_lock) { xfs_log_item_t *mlip; int mlip_changed = 0; int i; LIST_HEAD(tmp); ASSERT(nr_items > 0); /* Not required, but true. */ mlip = xfs_ail_min(ailp); for (i = 0; i < nr_items; i++) { struct xfs_log_item *lip = log_items[i]; if (lip->li_flags & XFS_LI_IN_AIL) { /* check if we really need to move the item */ if (XFS_LSN_CMP(lsn, lip->li_lsn) <= 0) continue; trace_xfs_ail_move(lip, lip->li_lsn, lsn); xfs_ail_delete(ailp, lip); if (mlip == lip) mlip_changed = 1; } else { lip->li_flags |= XFS_LI_IN_AIL; <API key>(lip, 0, lsn); } lip->li_lsn = lsn; list_add(&lip->li_ail, &tmp); } if (!list_empty(&tmp)) xfs_ail_splice(ailp, cur, &tmp, lsn); if (mlip_changed) { if (!XFS_FORCED_SHUTDOWN(ailp->xa_mount)) <API key>(ailp->xa_mount); spin_unlock(&ailp->xa_lock); xfs_log_space_wake(ailp->xa_mount); } else { spin_unlock(&ailp->xa_lock); } } /* * <API key> - remove multiple log items from the AIL * * @<API key> takes an array of log items that all need to * removed from the AIL. The caller is already holding the AIL lock, and done * all the checks necessary to ensure the items passed in via @log_items are * ready for deletion. This includes checking that the items are in the AIL. * * For each log item to be removed, unlink it from the AIL, clear the IN_AIL * flag from the item and reset the item's lsn to 0. If we remove the first * item in the AIL, update the log tail to match the new minimum LSN in the * AIL. * * This function will not drop the AIL lock until all items are removed from * the AIL to minimise the amount of lock traffic on the AIL. This does not * greatly increase the AIL hold time, but does significantly reduce the amount * of traffic on the lock, especially during IO completion. * * This function must be called with the AIL lock held. The lock is dropped * before returning. */ void <API key>( struct xfs_ail *ailp, struct xfs_log_item **log_items, int nr_items, int shutdown_type) __releases(ailp->xa_lock) { xfs_log_item_t *mlip; int mlip_changed = 0; int i; mlip = xfs_ail_min(ailp); for (i = 0; i < nr_items; i++) { struct xfs_log_item *lip = log_items[i]; if (!(lip->li_flags & XFS_LI_IN_AIL)) { struct xfs_mount *mp = ailp->xa_mount; spin_unlock(&ailp->xa_lock); if (!XFS_FORCED_SHUTDOWN(mp)) { xfs_alert_tag(mp, XFS_PTAG_AILDELETE, "%s: attempting to delete a log item that is not in the AIL", __func__); xfs_force_shutdown(mp, shutdown_type); } return; } <API key>(lip, mlip->li_lsn, lip->li_lsn); xfs_ail_delete(ailp, lip); lip->li_flags &= ~XFS_LI_IN_AIL; lip->li_lsn = 0; if (mlip == lip) mlip_changed = 1; } if (mlip_changed) { if (!XFS_FORCED_SHUTDOWN(ailp->xa_mount)) <API key>(ailp->xa_mount); if (list_empty(&ailp->xa_ail)) wake_up_all(&ailp->xa_empty); spin_unlock(&ailp->xa_lock); xfs_log_space_wake(ailp->xa_mount); } else { spin_unlock(&ailp->xa_lock); } } int xfs_trans_ail_init( xfs_mount_t *mp) { struct xfs_ail *ailp; ailp = kmem_zalloc(sizeof(struct xfs_ail), KM_MAYFAIL); if (!ailp) return ENOMEM; ailp->xa_mount = mp; INIT_LIST_HEAD(&ailp->xa_ail); INIT_LIST_HEAD(&ailp->xa_cursors); spin_lock_init(&ailp->xa_lock); INIT_LIST_HEAD(&ailp->xa_buf_list); init_waitqueue_head(&ailp->xa_empty); ailp->xa_task = kthread_run(xfsaild, ailp, "xfsaild/%s", ailp->xa_mount->m_fsname); if (IS_ERR(ailp->xa_task)) goto out_free_ailp; mp->m_ail = ailp; return 0; out_free_ailp: kmem_free(ailp); return ENOMEM; } void <API key>( xfs_mount_t *mp) { struct xfs_ail *ailp = mp->m_ail; kthread_stop(ailp->xa_task); kmem_free(ailp); }
<?php /** * Plugin Installer List Table class. * * @package WordPress * @subpackage List_Table * @since 3.1.0 * @access private */ class <API key> extends WP_List_Table { function ajax_user_can() { return current_user_can('install_plugins'); } function prepare_items() { include( ABSPATH . 'wp-admin/includes/plugin-install.php' ); global $tabs, $tab, $paged, $type, $term; wp_reset_vars( array( 'tab' ) ); $paged = $this->get_pagenum(); $per_page = 30; // These are the tabs which are shown on the page $tabs = array(); $tabs['dashboard'] = __( 'Поиск' ); if ( 'search' == $tab ) $tabs['search'] = __( 'Search Results' ); $tabs['upload'] = __( 'Upload' ); $tabs['featured'] = _x( 'Featured','Plugin Installer' ); $tabs['popular'] = _x( 'Popular','Plugin Installer' ); $tabs['new'] = _x( 'Newest','Plugin Installer' ); $nonmenu_tabs = array( 'plugin-information' ); //Valid actions to perform which do not have a Menu item. $tabs = apply_filters( '<API key>', $tabs ); $nonmenu_tabs = apply_filters( '<API key>', $nonmenu_tabs ); // If a non-valid menu tab has been selected, And its not a non-menu action. if ( empty( $tab ) || ( !isset( $tabs[ $tab ] ) && !in_array( $tab, (array) $nonmenu_tabs ) ) ) $tab = key( $tabs ); $args = array( 'page' => $paged, 'per_page' => $per_page ); switch ( $tab ) { case 'search': $type = isset( $_REQUEST['type'] ) ? stripslashes( $_REQUEST['type'] ) : 'term'; $term = isset( $_REQUEST['s'] ) ? stripslashes( $_REQUEST['s'] ) : ''; switch ( $type ) { case 'tag': $args['tag'] = <API key>( $term ); break; case 'term': $args['search'] = $term; break; case 'author': $args['author'] = $term; break; } add_action( '<API key>', 'install_search_form', 10, 0 ); break; case 'featured': case 'popular': case 'new': $args['browse'] = $tab; break; default: $args = false; } if ( !$args ) return; $api = plugins_api( 'query_plugins', $args ); if ( is_wp_error( $api ) ) wp_die( $api->get_error_message() . '</p> <p class="hide-if-no-js"><a href="#" onclick="document.location.reload(); return false;">' . __( 'Try again' ) . '</a>' ); $this->items = $api->plugins; $this->set_pagination_args( array( 'total_items' => $api->info['results'], 'per_page' => $per_page, ) ); } function no_items() { _e( 'No plugins match your request.' ); } function get_views() { global $tabs, $tab; $display_tabs = array(); foreach ( (array) $tabs as $action => $text ) { $class = ( $action == $tab ) ? ' class="current"' : ''; $href = self_admin_url('plugin-install.php?tab=' . $action); $display_tabs['plugin-install-'.$action] = "<a href='$href'$class>$text</a>"; } return $display_tabs; } function display_tablenav( $which ) { if ( 'top' == $which ) { ?> <div class="tablenav top"> <div class="alignleft actions"> <?php do_action( '<API key>' ); ?> </div> <?php $this->pagination( $which ); ?> <img src="<?php echo esc_url( admin_url( 'images/wpspin_light.gif' ) ); ?>" class="ajax-loading list-ajax-loading" alt="" /> <br class="clear" /> </div> <?php } else { ?> <div class="tablenav bottom"> <?php $this->pagination( $which ); ?> <img src="<?php echo esc_url( admin_url( 'images/wpspin_light.gif' ) ); ?>" class="ajax-loading list-ajax-loading" alt="" /> <br class="clear" /> </div> <?php } } function get_table_classes() { extract( $this->_args ); return array( 'widefat', $plural ); } function get_columns() { return array( 'name' => _x( 'Name', 'plugin name' ), 'version' => __( 'Version' ), 'rating' => __( 'Rating' ), 'description' => __( 'Description' ), ); } function display_rows() { $plugins_allowedtags = array( 'a' => array( 'href' => array(),'title' => array(), 'target' => array() ), 'abbr' => array( 'title' => array() ),'acronym' => array( 'title' => array() ), 'code' => array(), 'pre' => array(), 'em' => array(),'strong' => array(), 'ul' => array(), 'ol' => array(), 'li' => array(), 'p' => array(), 'br' => array() ); list( $columns, $hidden ) = $this->get_column_info(); $style = array(); foreach ( $columns as $column_name => $column_display_name ) { $style[ $column_name ] = in_array( $column_name, $hidden ) ? 'style="display:none;"' : ''; } foreach ( (array) $this->items as $plugin ) { if ( is_object( $plugin ) ) $plugin = (array) $plugin; $title = wp_kses( $plugin['name'], $plugins_allowedtags ); //Limit description to 400char, and remove any HTML. $description = strip_tags( $plugin['description'] ); if ( strlen( $description ) > 400 ) $description = mb_substr( $description, 0, 400 ) . '&#8230;'; //remove any trailing entities $description = preg_replace( '/&[^;\s]{0,6}$/', '', $description ); //strip leading/trailing & multiple consecutive lines $description = trim( $description ); $description = preg_replace( "|(\r?\n)+|", "\n", $description ); //\n => <br> $description = nl2br( $description ); $version = wp_kses( $plugin['version'], $plugins_allowedtags ); $name = strip_tags( $title . ' ' . $version ); $author = $plugin['author']; if ( ! empty( $plugin['author'] ) ) $author = ' <cite>' . sprintf( __( 'By %s' ), $author ) . '.</cite>'; $author = wp_kses( $author, $plugins_allowedtags ); $action_links = array(); $action_links[] = '<a href="' . self_admin_url( 'plugin-install.php?tab=plugin-information&amp;plugin=' . $plugin['slug'] . '&amp;TB_iframe=true&amp;width=600&amp;height=550' ) . '" class="thickbox" title="' . esc_attr( sprintf( __( 'More information about %s' ), $name ) ) . '">' . __( 'Details' ) . '</a>'; if ( current_user_can( 'install_plugins' ) || current_user_can( 'update_plugins' ) ) { $status = <API key>( $plugin ); switch ( $status['status'] ) { case 'install': if ( $status['url'] ) $action_links[] = '<a class="install-now" href="' . $status['url'] . '" title="' . esc_attr( sprintf( __( 'Install %s' ), $name ) ) . '">' . __( 'Install Now' ) . '</a>'; break; case 'update_available': if ( $status['url'] ) $action_links[] = '<a href="' . $status['url'] . '" title="' . esc_attr( sprintf( __( 'Update to version %s' ), $status['version'] ) ) . '">' . sprintf( __( 'Update Now' ), $status['version'] ) . '</a>'; break; case 'latest_installed': case 'newer_installed': $action_links[] = '<span title="' . esc_attr__( 'This plugin is already installed and is up to date' ) . ' ">' . _x( 'Installed', 'plugin' ) . '</span>'; break; } } $action_links = apply_filters( '<API key>', $action_links, $plugin ); ?> <tr> <td class="name column-name"<?php echo $style['name']; ?>><strong><?php echo $title; ?></strong> <div class="action-links"><?php if ( !empty( $action_links ) ) echo implode( ' | ', $action_links ); ?></div> </td> <td class="vers column-version"<?php echo $style['version']; ?>><?php echo $version; ?></td> <td class="vers column-rating"<?php echo $style['rating']; ?>> <div class="star-holder" title="<?php printf( _n( '(based on %s rating)', '(based on %s ratings)', $plugin['num_ratings'] ), number_format_i18n( $plugin['num_ratings'] ) ) ?>"> <div class="star star-rating" style="width: <?php echo esc_attr( str_replace( ',', '.', $plugin['rating'] ) ); ?>px"></div> </div> </td> <td class="desc column-description"<?php echo $style['description']; ?>><?php echo $description, $author; ?></td> </tr> <?php } } }
package com.ues21.ferreteria.login; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.ues21.ferreteria.productos.Productos; import com.ues21.ferreteria.productos.ProductosDAO; import com.ues21.ferreteria.usuarios.Usuarios; import com.ues21.ferreteria.usuarios.UsuariosDAO; @Controller public class LoginController { @Autowired private LoginDAO loginDAO; @Autowired private UsuariosDAO usuariosDAO; /* @RequestMapping(value = "/login", method = RequestMethod.GET) public String listaHome(Model model) { model.addAttribute("login", null); return "login"; } */ @RequestMapping(value = "/login", method = RequestMethod.GET) public String viewRegistration(Map<String, Object> model) { Login userForm = new Login(); model.put("userForm", userForm); return "login"; } @RequestMapping(value = "/login", method = RequestMethod.POST) public String processRegistration(@ModelAttribute("userForm") Login user, Model model, HttpSession session) { // implement your own registration logic here... Login login = loginDAO.verificarUsuario(user); // for testing purpose: System.out.println("username: " + user.getDni()); System.out.println("password: " + user.getContrasena()); if (login==null){ model.addAttribute("loginError", "Error logging in. Please try again"); return "index"; } else { Usuarios usuario = usuariosDAO.getUsuario(user.getDni()); session.setAttribute("loggedInUser", usuario); return "home"; } } @RequestMapping(value = "/logout", method = RequestMethod.GET) public String logout(HttpSession session){ session.removeAttribute("loggedInUser"); return "index"; } }
<?php /** * The Sidebar containing the primary and secondary widget areas. * * @package WordPress * @subpackage Twenty_Ten * @since Twenty Ten 1.0 */ ?> <div id="primary" class="widget-area" role="complementary"> <ul class="xoxo"> <?php /* When we call the dynamic_sidebar() function, it'll spit out * the widgets for that widget area. If it instead returns false, * then the sidebar simply doesn't exist, so we'll hard-code in * some default sidebar stuff just in case. */ if ( ! dynamic_sidebar( '<API key>' ) ) : ?> <?php endif; // end primary widget area ?> </ul> </div><!-- #primary .widget-area -->
<?php /** * @file * Contains \Drupal\migrate_drupal\Tests\<API key>. */ namespace Drupal\migrate_drupal\Tests; use Drupal\migrate\MigrateExecutable; use Drupal\simpletest\TestBase; /** * Test helper for running a complete Drupal migration. */ abstract class <API key> extends <API key> { /** * The test class which discovered migration tests must extend in order to be * included in this test run. */ const BASE_TEST_CLASS = 'Drupal\migrate_drupal\Tests\<API key>'; /** * A list of fully-qualified test classes which should be ignored. * * @var string[] */ protected static $blacklist = []; /** * Get the test classes that needs to be run for this test. * * @return array * The list of fully-classified test class names. */ protected function getTestClassesList() { $classes = []; $discovery = \Drupal::getContainer()->get('test_discovery'); foreach (static::$modules as $module) { foreach ($discovery->getTestClasses($module) as $group) { foreach (array_keys($group) as $class) { if (is_subclass_of($class, static::BASE_TEST_CLASS)) { $classes[] = $class; } } } } // Exclude blacklisted classes. return array_diff($classes, static::$blacklist); } /** * {@inheritdoc} */ protected function tearDown() { // Move the results of every class under ours. This is solely for // reporting, the filename will guide developers. self::<API key>() ->update('simpletest') ->fields(array('test_class' => get_class($this))) ->condition('test_id', $this->testId) ->execute(); parent::tearDown(); } /** * Test the complete Drupal migration. */ public function testDrupal() { $classes = $this->getTestClassesList(); foreach ($classes as $class) { if (is_subclass_of($class, '\Drupal\migrate\Tests\<API key>')) { $class::migrateDumpAlter($this); } } // Run every migration in the order specified by the storage controller. foreach (<API key>('migration', static::$migrations) as $migration) { (new MigrateExecutable($migration, $this))->import(); } foreach ($classes as $class) { $test_object = new $class($this->testId); $test_object->databasePrefix = $this->databasePrefix; $test_object->container = $this->container; // run() does a lot of setup and tear down work which we don't need: // it would setup a new database connection and wouldn't find the // Drupal dump. Also by skipping the setUp() methods there are no id // mappings or entities prepared. The tests run against solely migrated // data. foreach (get_class_methods($test_object) as $method) { if (strtolower(substr($method, 0, 4)) == 'test') { // Insert a fail record. This will be deleted on completion to ensure // that testing completed. $method_info = new \ReflectionMethod($class, $method); $caller = array( 'file' => $method_info->getFileName(), 'line' => $method_info->getStartLine(), 'function' => $class . '->' . $method . '()', ); $completion_check_id = TestBase::insertAssert($this->testId, $class, FALSE, 'The test did not complete due to a fatal error.', 'Completion check', $caller); // Run the test method. try { $test_object->$method(); } catch (\Exception $e) { $this->exceptionHandler($e); } // Remove the completion check record. TestBase::deleteAssert($completion_check_id); } } // Add the pass/fail/exception/debug results. foreach ($this->results as $key => &$value) { $value += $test_object->results[$key]; } } } }
<?php JLoader::register('JPath', JPATH_PLATFORM . '/joomla/filesystem/path.php'); /** * Tests for the JPath class. * * @package Joomla.UnitTest * @subpackage Filesystem * @since 12.2 */ class JPathTest extends TestCase { /** * Data provider for testClean() method. * * @return array * * @since 12.2 */ public function getCleanData() { return array( // Input Path, Directory Separator, Expected Output 'Nothing to do.' => array('/var/www/foo/bar/baz', '/', '/var/www/foo/bar/baz'), 'One backslash.' => array('/var/www/foo\\bar/baz', '/', '/var/www/foo/bar/baz'), 'Two and one backslashes.' => array('/var/www\\\\foo\\bar/baz', '/', '/var/www/foo/bar/baz'), 'Mixed backslashes and double forward slashes.' => array('/var\\/www//foo\\bar/baz', '/', '/var/www/foo/bar/baz'), 'UNC path.' => array('\\\\www\\docroot', '\\', '\\\\www\\docroot'), 'UNC path with forward slash.' => array('\\\\www/docroot', '\\', '\\\\www\\docroot'), 'UNC path with UNIX directory separator.' => array('\\\\www/docroot', '/', '/www/docroot'), ); } /** * Test... * * @todo Implement testCanChmod(). * * @return void */ public function testCanChmod() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } public function testSetPermissions() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } public function testGetPermissions() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Test... * * @todo Implement testCheck(). * * @return void */ public function testCheck() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Tests the clean method. * * @param string $input @todo * @param string $ds @todo * @param string $expected @todo * * @return void * * @covers JPath::clean * @dataProvider getCleanData * @since 12.2 */ public function testClean($input, $ds, $expected) { $this->assertEquals( $expected, JPath::clean($input, $ds) ); } /** * Test... * * @todo Implement testIsOwner(). * * @return void */ public function testIsOwner() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Test... * * @todo Implement testFind(). * * @return void */ public function testFind() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } }
body { background-color: #f9f9f9; font-family: 'Helvetica Neue', Helvetica, 'Segoe UI', Arial, freesans, sans-serif; font-size: 1em; font-style: normal; font-variant: normal; line-height: 1.25em; } h1, h2, h3, h4 { font-weight: bold; margin-bottom: 1em; margin-top: 1em; } h1 { font-size: 2em; line-height: 1.2em; } h2 { font-size: 1.5em; line-height: 1.2; } a { color: #4078c0; text-decoration: none; } a:hover, a:active { text-decoration: underline; } ul { list-style: disc; margin-bottom: 1em; padding-left: 2em; } p { margin-bottom: 1em; } table { display: block; margin-bottom: 1em; overflow: auto; width: 100%; word-break: keep-all; } table th, table td { border: 1px solid #ddd; padding: 0.4em 0.8em; } table tr { border-top: 1px solid #ccc; } table tr:nth-child(2n) { background-color: #f8f8f8; } /* FORMS */ label { margin: 0.9375em 0; display: block; cursor: default; } label span { display: block; margin: 0 0 0.35em; } input[type="text"], input[type="password"], input[type="email"], input[type="number"], input[type="tel"], input[type="url"], select, textarea { background-color: #fafafa; border: 1px solid #ccc; border-radius: 0.188em; box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.075); font: inherit; font-size: 0.813em; max-width: 33.846em; min-height: 2.615em; outline: none; padding: 0.538em 0.615em; vertical-align: middle; width: 100%; } input[type="text"]:focus, input[type="password"]:focus, input[type="email"]:focus, input[type="number"]:focus, input[type="tel"]:focus, input[type="url"]:focus, select:focus, textarea:focus { background-color: #fff; } textarea { min-height: 10em; } textarea.short { min-height: 5em; } input[type="submit"], .button { background-color: #eee; border: 1px solid #d5d5d5; border-radius: 0.188em; color: #333; cursor: pointer; display: inline-block; font: inherit; font-size: 0.813em; font-weight: bold; padding: 0.462em 0.923em; vertical-align: middle; white-space: nowrap; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-appearance: none; } input[type="submit"]:hover, input[type="submit"]:active, .button:hover, .button:active { background-color: #ddd; border-color: #ccc; text-decoration: none; } /* ALERT BOXES */ .alert-box { border-radius: 0.188em; margin-bottom: 1em; padding: 1em; } .alert-box span { font-weight: bold; text-transform: uppercase; } .error { background: #ffecec; border: 1px solid #f5aca6; } .success { background: #e9ffd9; border: 1px solid #a6ca8a; } .warning { background: #fff8c4; border: 1px solid #f2c779; } .notice { background: #e3f7fc; border: 1px solid #8ed9f6; }
/* Freenet 0.7 node. */ package freenet.node; import static freenet.node.stats.DataStoreKeyType.CHK; import static freenet.node.stats.DataStoreKeyType.PUB_KEY; import static freenet.node.stats.DataStoreKeyType.SSK; import static freenet.node.stats.DataStoreType.CACHE; import static freenet.node.stats.DataStoreType.CLIENT; import static freenet.node.stats.DataStoreType.SLASHDOT; import static freenet.node.stats.DataStoreType.STORE; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.SECONDS; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.io.<API key>; import java.net.InetAddress; import java.net.<API key>; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import java.util.<API key>; import java.util.Random; import java.util.Set; import freenet.config.*; import freenet.node.useralerts.*; import org.tanukisoftware.wrapper.WrapperManager; import freenet.client.FetchContext; import freenet.clients.fcp.FCPMessage; import freenet.clients.fcp.FeedMessage; import freenet.clients.http.<API key>; import freenet.clients.http.SimpleToadletServer; import freenet.crypt.DSAPublicKey; import freenet.crypt.ECDH; import freenet.crypt.MasterSecret; import freenet.crypt.<API key>; import freenet.crypt.RandomSource; import freenet.crypt.Yarrow; import freenet.io.comm.DMT; import freenet.io.comm.<API key>; import freenet.io.comm.FreenetInetAddress; import freenet.io.comm.<API key>; import freenet.io.comm.Message; import freenet.io.comm.MessageCore; import freenet.io.comm.MessageFilter; import freenet.io.comm.Peer; import freenet.io.comm.PeerParseException; import freenet.io.comm.<API key>; import freenet.io.comm.TrafficClass; import freenet.io.comm.UdpSocketHandler; import freenet.io.xfer.<API key>; import freenet.keys.CHKBlock; import freenet.keys.CHKVerifyException; import freenet.keys.ClientCHK; import freenet.keys.ClientCHKBlock; import freenet.keys.ClientKey; import freenet.keys.ClientKeyBlock; import freenet.keys.ClientSSK; import freenet.keys.ClientSSKBlock; import freenet.keys.Key; import freenet.keys.KeyBlock; import freenet.keys.KeyVerifyException; import freenet.keys.NodeCHK; import freenet.keys.NodeSSK; import freenet.keys.SSKBlock; import freenet.keys.SSKVerifyException; import freenet.l10n.BaseL10n; import freenet.l10n.NodeL10n; import freenet.node.DarknetPeerNode.FRIEND_TRUST; import freenet.node.DarknetPeerNode.FRIEND_VISIBILITY; import freenet.node.NodeDispatcher.<API key>; import freenet.node.OpennetManager.ConnectionType; import freenet.node.SecurityLevels.<API key>; import freenet.node.SecurityLevels.<API key>; import freenet.node.probe.Listener; import freenet.node.probe.Type; import freenet.node.stats.<API key>; import freenet.node.stats.DataStoreStats; import freenet.node.stats.<API key>; import freenet.node.stats.StoreCallbackStats; import freenet.node.updater.NodeUpdateManager; import freenet.pluginmanager.ForwardPort; import freenet.pluginmanager.<API key>; import freenet.pluginmanager.PluginManager; import freenet.store.BlockMetadata; import freenet.store.CHKStore; import freenet.store.FreenetStore; import freenet.store.<API key>; import freenet.store.NullFreenetStore; import freenet.store.PubkeyStore; import freenet.store.RAMFreenetStore; import freenet.store.SSKStore; import freenet.store.SlashdotStore; import freenet.store.StorableBlock; import freenet.store.StoreCallback; import freenet.store.caching.CachingFreenetStore; import freenet.store.caching.<API key>; import freenet.store.saltedhash.<API key>; import freenet.store.saltedhash.<API key>; import freenet.support.Executor; import freenet.support.Fields; import freenet.support.HTMLNode; import freenet.support.HexUtil; import freenet.support.JVMVersion; import freenet.support.<API key>; import freenet.support.Logger; import freenet.support.Logger.LogLevel; import freenet.support.PooledExecutor; import freenet.support.PrioritizedTicker; import freenet.support.ShortBuffer; import freenet.support.SimpleFieldSet; import freenet.support.Ticker; import freenet.support.TokenBucket; import freenet.support.api.BooleanCallback; import freenet.support.api.IntCallback; import freenet.support.api.LongCallback; import freenet.support.api.ShortCallback; import freenet.support.api.StringCallback; import freenet.support.io.ArrayBucketFactory; import freenet.support.io.Closer; import freenet.support.io.FileUtil; import freenet.support.io.NativeThread; import freenet.support.math.MersenneTwister; import freenet.support.transport.ip.<API key>; /** * @author amphibian */ public class Node implements <API key> { public class MigrateOldStoreData implements Runnable { private final boolean clientCache; public MigrateOldStoreData(boolean clientCache) { this.clientCache = clientCache; if(clientCache) { oldCHKClientCache = chkClientcache; oldPKClientCache = pubKeyClientcache; oldSSKClientCache = sskClientcache; } else { oldCHK = chkDatastore; oldPK = pubKeyDatastore; oldSSK = sskDatastore; oldCHKCache = chkDatastore; oldPKCache = pubKeyDatastore; oldSSKCache = sskDatastore; } } @Override public void run() { System.err.println("Migrating old "+(clientCache ? "client cache" : "datastore")); if(clientCache) { migrateOldStore(oldCHKClientCache, chkClientcache, true); StoreCallback<? extends StorableBlock> old; synchronized(Node.this) { old = oldCHKClientCache; oldCHKClientCache = null; } closeOldStore(old); migrateOldStore(oldPKClientCache, pubKeyClientcache, true); synchronized(Node.this) { old = oldPKClientCache; oldPKClientCache = null; } closeOldStore(old); migrateOldStore(oldSSKClientCache, sskClientcache, true); synchronized(Node.this) { old = oldSSKClientCache; oldSSKClientCache = null; } closeOldStore(old); } else { migrateOldStore(oldCHK, chkDatastore, false); oldCHK = null; migrateOldStore(oldPK, pubKeyDatastore, false); oldPK = null; migrateOldStore(oldSSK, sskDatastore, false); oldSSK = null; migrateOldStore(oldCHKCache, chkDatacache, false); oldCHKCache = null; migrateOldStore(oldPKCache, pubKeyDatacache, false); oldPKCache = null; migrateOldStore(oldSSKCache, sskDatacache, false); oldSSKCache = null; } System.err.println("Finished migrating old "+(clientCache ? "client cache" : "datastore")); } } volatile CHKStore oldCHK; volatile PubkeyStore oldPK; volatile SSKStore oldSSK; volatile CHKStore oldCHKCache; volatile PubkeyStore oldPKCache; volatile SSKStore oldSSKCache; volatile CHKStore oldCHKClientCache; volatile PubkeyStore oldPKClientCache; volatile SSKStore oldSSKClientCache; private <T extends StorableBlock> void migrateOldStore(StoreCallback<T> old, StoreCallback<T> newStore, boolean canReadClientCache) { FreenetStore<T> store = old.getStore(); if(store instanceof RAMFreenetStore) { RAMFreenetStore<T> ramstore = (RAMFreenetStore<T>)store; try { ramstore.migrateTo(newStore, canReadClientCache); } catch (IOException e) { Logger.error(this, "Caught migrating old store: "+e, e); } ramstore.clear(); } else if(store instanceof <API key>) { Logger.error(this, "Migrating from from a saltedhashstore not fully supported yet: will not keep old keys"); } } public <T extends StorableBlock> void closeOldStore(StoreCallback<T> old) { FreenetStore<T> store = old.getStore(); if(store instanceof <API key>) { <API key><T> saltstore = (<API key><T>) store; saltstore.close(); saltstore.destruct(); } } private static volatile boolean logMINOR; private static volatile boolean logDEBUG; static { Logger.<API key>(new <API key>(){ @Override public void shouldUpdate(){ logMINOR = Logger.shouldLog(LogLevel.MINOR, this); logDEBUG = Logger.shouldLog(LogLevel.DEBUG, this); } }); } private static <API key> nodeNameUserAlert; private static <API key> <API key>; public class NodeNameCallback extends StringCallback { NodeNameCallback() { } @Override public String get() { String name; synchronized(this) { name = myName; } if(name.startsWith("Node id|")|| name.equals("MyFirstFreenetNode") || name.startsWith("Freenet node with no name clientCore.alerts.register(nodeNameUserAlert); }else{ clientCore.alerts.unregister(nodeNameUserAlert); } return name; } @Override public void set(String val) throws <API key> { if(get().equals(val)) return; else if(val.length() > 128) throw new <API key>("The given node name is too long ("+val+')'); else if("".equals(val)) val = "~none~"; synchronized(this) { myName = val; } // We'll broadcast the new name to our connected darknet peers via a differential node reference SimpleFieldSet fs = new SimpleFieldSet(true); fs.putSingle("myName", myName); peers.<API key>(fs, true, false); // We call the callback once again to ensure <API key> // has been unregistered ... see #1595 get(); } } private class StoreTypeCallback extends StringCallback implements <API key> { @Override public String get() { synchronized(Node.this) { return storeType; } } @Override public void set(String val) throws <API key>, <API key> { boolean found = false; for (String p : getPossibleValues()) { if (p.equals(val)) { found = true; break; } } if (!found) throw new <API key>("Invalid store type"); String type; synchronized(Node.this) { type = storeType; } if(type.equals("ram")) { synchronized(this) { // Serialise this part. makeStore(val); } } else { synchronized(Node.this) { storeType = val; } throw new <API key>("Store type cannot be changed on the fly"); } } @Override public String[] getPossibleValues() { return new String[] { "salt-hash", "ram" }; } } private class <API key> extends StringCallback implements <API key> { @Override public String get() { synchronized(Node.this) { return clientCacheType; } } @Override public void set(String val) throws <API key>, <API key> { boolean found = false; for (String p : getPossibleValues()) { if (p.equals(val)) { found = true; break; } } if (!found) throw new <API key>("Invalid store type"); synchronized(this) { // Serialise this part. String suffix = getStoreSuffix(); if (val.equals("salt-hash")) { byte[] key; try { synchronized(Node.this) { if(keys == null) throw new <API key>(); key = keys.<API key>; clientCacheType = val; } } catch (<API key> e1) { <API key>(); throw new <API key>("You must enter the password"); } try { <API key>(suffix, true, key); } catch (NodeInitException e) { Logger.error(this, "Unable to create new store", e); System.err.println("Unable to create new store: "+e); e.printStackTrace(); // FIXME l10n both on the NodeInitException and the wrapper message throw new <API key>("Unable to create new store: "+e); } } else if(val.equals("ram")) { <API key>(); } else /*if(val.equals("none")) */{ initNoClientCacheFS(); } synchronized(Node.this) { clientCacheType = val; } } } @Override public String[] getPossibleValues() { return new String[] { "salt-hash", "ram", "none" }; } } private static class L10nCallback extends StringCallback implements <API key> { @Override public String get() { return NodeL10n.getBase().getSelectedLanguage().fullName; } @Override public void set(String val) throws <API key> { if(val == null || get().equalsIgnoreCase(val)) return; try { NodeL10n.getBase().setLanguage(BaseL10n.LANGUAGE.mapToLanguage(val)); } catch (<API key> e) { throw new <API key>(e.getLocalizedMessage()); } PluginManager.setLanguage(NodeL10n.getBase().getSelectedLanguage()); } @Override public String[] getPossibleValues() { return BaseL10n.LANGUAGE.valuesWithFullNames(); } } /** Encryption key for client.dat.crypt or client.dat.bak.crypt */ private DatabaseKey databaseKey; /** Encryption keys, if loaded, null if waiting for a password. We must be able to write them, * and they're all used elsewhere anyway, so there's no point trying not to keep them in memory. */ private MasterKeys keys; /** Stats */ public final NodeStats nodeStats; /** Config object for the whole node. */ public final PersistentConfig config; // Static stuff related to logger /** Directory to log to */ static File logDir; /** Maximum size of gzipped logfiles */ static long maxLogSize; /** Log config handler */ public static <API key> logConfigHandler; public static final int PACKETS_IN_BLOCK = 32; public static final int PACKET_SIZE = 1024; public static final double <API key> = 0.25; public static final double <API key> = 0.5; // Send keepalives every 7-14 seconds. Will be acked and if necessary resent. // Old behaviour was keepalives every 14-28. Even that was adequate for a 30 second // timeout. Most nodes don't need to send keepalives because they are constantly busy, // this is only an issue for disabled darknet connections, very quiet private networks // etc. public static final long KEEPALIVE_INTERVAL = SECONDS.toMillis(7); // If no activity for 30 seconds, node is dead // 35 seconds allows plenty of time for resends etc even if above is 14 sec as it is on older nodes. public static final long MAX_PEER_INACTIVITY = SECONDS.toMillis(35); /** Time after which a handshake is assumed to have failed. */ public static final int HANDSHAKE_TIMEOUT = (int) MILLISECONDS.toMillis(4800); // Keep the below within the 30 second assumed timeout. // Inter-handshake time must be at least 2x handshake timeout public static final int <API key> = HANDSHAKE_TIMEOUT*2; // 10-20 secs public static final int <API key> = HANDSHAKE_TIMEOUT*2; // avoid overlap when the two handshakes are at the same time public static final int <API key> = HANDSHAKE_TIMEOUT*4; public static final int <API key> = HANDSHAKE_TIMEOUT*2; // 20-30 secs public static final int <API key> = HANDSHAKE_TIMEOUT*4; public static final int <API key> = HANDSHAKE_TIMEOUT*2; // 20-30 secs public static final int <API key> = HANDSHAKE_TIMEOUT*24; // 2-5 minutes public static final int <API key> = HANDSHAKE_TIMEOUT*36; public static final int <API key> = 1; // 1-4 handshake sends per burst public static final int <API key> = 3; // If we don't receive any packets at all in this period, from any node, tell the user public static final long ALARM_TIME = MINUTES.toMillis(1); static final long <API key> = MILLISECONDS.toMillis(900); static final long <API key> = MILLISECONDS.toMillis(1000); public static final int <API key> = 32; // 256 bits - note that this isn't used everywhere to determine it /** Datastore directory */ private final ProgramDirectory storeDir; /** Datastore properties */ private String storeType; private boolean storeUseSlotFilters; private boolean <API key>; /** Minimum total datastore size */ static final long MIN_STORE_SIZE = 32 * 1024 * 1024; /** Default datastore size (must be at least MIN_STORE_SIZE) */ static final long DEFAULT_STORE_SIZE = 32 * 1024 * 1024; /** Minimum client cache size */ static final long <API key> = 0; /** Default client cache size (must be at least <API key>) */ static final long <API key> = 10 * 1024 * 1024; /** Minimum slashdot cache size */ static final long <API key> = 0; /** Default slashdot cache size (must be at least <API key>) */ static final long <API key> = 10 * 1024 * 1024; /** The number of bytes per key total in all the different datastores. All the datastores * are always the same size in number of keys. */ public static final int sizePerKey = CHKBlock.DATA_LENGTH + CHKBlock.<API key> + DSAPublicKey.PADDED_SIZE + SSKBlock.DATA_LENGTH + SSKBlock.<API key>; /** The maximum number of keys stored in each of the datastores, cache and store combined. */ private long maxTotalKeys; long maxCacheKeys; long maxStoreKeys; /** The maximum size of the datastore. Kept to avoid rounding turning 5G into 5368698672 */ private long <API key>; /** If true, store shrinks occur immediately even if they are over 10% of the store size. If false, * we just set the storeSize and do an offline shrink on the next startup. Online shrinks do not * preserve the most recently used data so are not recommended. */ private boolean <API key>; private final <API key> shutdownHook; /** The CHK datastore. Long term storage; data should only be inserted here if * this node is the closest location on the chain so far, and it is on an * insert (because inserts will always reach the most specialized node; if we * allow requests to store here, then we get pollution by inserts for keys not * close to our specialization). These conclusions derived from Oskar's simulations. */ private CHKStore chkDatastore; /** The SSK datastore. See description for chkDatastore. */ private SSKStore sskDatastore; /** The store of DSAPublicKeys (by hash). See description for chkDatastore. */ private PubkeyStore pubKeyDatastore; /** Client cache store type */ private String clientCacheType; /** Client cache could not be opened so is a RAMFS until the correct password is entered */ private boolean <API key>; private boolean <API key>; /** Client cache maximum cached keys for each type */ long maxClientCacheKeys; /** Maximum size of the client cache. Kept to avoid rounding problems. */ private long <API key>; /** The CHK datacache. Short term cache which stores everything that passes * through this node. */ private CHKStore chkDatacache; /** The SSK datacache. Short term cache which stores everything that passes * through this node. */ private SSKStore sskDatacache; /** The public key datacache (by hash). Short term cache which stores * everything that passes through this node. */ private PubkeyStore pubKeyDatacache; /** The CHK client cache. Caches local requests only. */ private CHKStore chkClientcache; /** The SSK client cache. Caches local requests only. */ private SSKStore sskClientcache; /** The pubkey client cache. Caches local requests only. */ private PubkeyStore pubKeyClientcache; // These only cache keys for 30 minutes. // FIXME make the first two configurable private long <API key>; private int <API key>; static final long PURGE_INTERVAL = SECONDS.toMillis(60); private CHKStore chkSlashdotcache; private SlashdotStore<CHKBlock> <API key>; private SSKStore sskSlashdotcache; private SlashdotStore<SSKBlock> <API key>; private PubkeyStore pubKeySlashdotcache; private SlashdotStore<DSAPublicKey> <API key>; /** If false, only ULPRs will use the slashdot cache. If true, everything does. */ private boolean useSlashdotCache; /** If true, we write stuff to the datastore even though we shouldn't because the HTL is * too high. However it is flagged as old so it won't be included in the Bloom filter for * sharing purposes. */ private boolean <API key>; final NodeGetPubkey getPubKey; /** FetchContext for ARKs */ public final FetchContext arkFetcherContext; /** IP detector */ public final NodeIPDetector ipDetector; /** For debugging/testing, set this to true to stop the * probabilistic decrement at the edges of the HTLs. */ boolean <API key>; public final RequestTracker tracker; /** Semi-unique ID for swap requests. Used to identify us so that the * topology can be reconstructed. */ public long swapIdentifier; private String myName; public final LocationManager lm; /** My peers */ public final PeerManager peers; /** Node-reference directory (node identity, peers, etc) */ final ProgramDirectory nodeDir; /** Config directory (l10n overrides, etc) */ final ProgramDirectory cfgDir; /** User data directory (bookmarks, download lists, etc) */ final ProgramDirectory userDir; /** Run-time state directory (bootID, PRNG seed, etc) */ final ProgramDirectory runDir; /** Plugin directory */ final ProgramDirectory pluginDir; /** File to write crypto master keys into, possibly passworded */ final File masterKeysFile; /** Directory to put extra peer data into */ final File extraPeerDataDir; private volatile boolean hasPanicked; /** Strong RNG */ public final RandomSource random; /** JCA-compliant strong RNG. WARNING: DO NOT CALL THIS ON THE MAIN NETWORK * HANDLING THREADS! In some configurations it can block, potentially * forever, on nextBytes()! */ public final SecureRandom secureRandom; /** Weak but fast RNG */ public final Random fastWeakRandom; /** The object which handles incoming messages and allows us to wait for them */ final MessageCore usm; // Darknet stuff NodeCrypto darknetCrypto; // Back compat private boolean <API key>; // Opennet stuff private final NodeCryptoConfig opennetCryptoConfig; OpennetManager opennet; private volatile boolean <API key>; private int maxOpennetPeers; private boolean <API key>; private boolean <API key>; // General stuff public final Executor executor; public final PacketSender ps; public final PrioritizedTicker ticker; final DNSRequester dnsr; final NodeDispatcher dispatcher; public final UptimeEstimator uptime; public final TokenBucket outputThrottle; public boolean throttleLocalData; private int <API key>; private int inputBandwidthLimit; private long <API key>; private int <API key>; private int <API key>; private boolean <API key>; boolean inputLimitDefault; final boolean enableARKs; final boolean <API key>; final boolean <API key>; final boolean enableSwapping; private volatile boolean <API key>; private volatile boolean <API key>; boolean enableSwapQueueing; boolean <API key>; public static final short DEFAULT_MAX_HTL = (short)18; private short maxHTL; private boolean skipWrapperWarning; private int maxPacketSize; /** Should inserts ignore low backoff times by default? */ public static final boolean <API key> = false; /** Definition of "low backoff times" for above. */ public static final long LOW_BACKOFF = SECONDS.toMillis(30); /** Should inserts be fairly blatently prioritised on accept by default? */ public static final boolean <API key> = false; /** Should inserts fork when the HTL reaches cacheability? */ public static final boolean <API key> = true; public final <API key> collector; /** Type identifier for fproxy node to node messages, as sent on DMT.nodeToNodeMessage's */ public static final int <API key> = 1; /** Type identifier for differential node reference messages, as sent on DMT.nodeToNodeMessage's */ public static final int <API key> = 2; /** Identifier within fproxy messages for simple, short text messages to be displayed on the homepage as useralerts */ public static final int <API key> = 1; /** Identifier within fproxy messages for an offer to transfer a file */ public static final int <API key> = 2; /** Identifier within fproxy messages for accepting an offer to transfer a file */ public static final int <API key> = 3; /** Identifier within fproxy messages for rejecting an offer to transfer a file */ public static final int <API key> = 4; /** Identified within friend feed for the recommendation of a bookmark */ public static final int <API key> = 5; /** Identified within friend feed for the recommendation of a file */ public static final int <API key> = 6; public static final int <API key> = 1; public static final int <API key> = 2; public static final int <API key> = 3; public static final int <API key> = 4; public static final int <API key> = 5; public static final int <API key> = 1; public final long lastBootID; public final long bootID; public final long startupTime; private SimpleToadletServer toadlets; public final NodeClientCore clientCore; // ULPRs, RecentlyFailed, per node failure tables, are all managed by FailureTable. final FailureTable failureTable; // The version we were before we restarted. public int lastVersion; /** NodeUpdater **/ public final NodeUpdateManager nodeUpdater; public final SecurityLevels securityLevels; // Things that's needed to keep track of public final PluginManager pluginManager; // Helpers public final InetAddress localhostAddress; public final FreenetInetAddress fLocalhostAddress; // The node starter private static NodeStarter nodeStarter; // The watchdog will be silenced until it's true private boolean hasStarted; private boolean isStopping = false; /** * Minimum uptime for us to consider a node an acceptable place to store a key. We store a key * to the datastore only if it's from an insert, and we are a sink, but when calculating whether * we are a sink we ignore nodes which have less uptime (percentage) than this parameter. */ static final int <API key> = 40; private volatile boolean isPRNGReady = false; private boolean storePreallocate; private boolean enableRoutedPing; private boolean <API key>; /** * Minimum bandwidth limit in bytes considered usable: 10 KiB. If there is an attempt to set a limit below this - * excluding the reserved -1 for input bandwidth - the callback will throw. See the callbacks for * <API key> and inputBandwidthLimit. 10 KiB are equivalent to 50 GiB traffic per month. */ private static final int minimumBandwidth = 10 * 1024; /** Quality of Service mark we will use for all outgoing packets (opennet/darknet) */ private TrafficClass trafficClass; public TrafficClass getTrafficClass() { return trafficClass; } /* * Gets minimum bandwidth in bytes considered usable. * * @see #minimumBandwidth */ public static int getMinimumBandwidth() { return minimumBandwidth; } /** * Dispatches a probe request with the specified settings * @see freenet.node.probe.Probe#start(byte, long, Type, Listener) */ public void startProbe(final byte htl, final long uid, final Type type, final Listener listener) { dispatcher.probe.start(htl, uid, type, listener); } /** * Read all storable settings (identity etc) from the node file. * @param filename The name of the file to read from. * @throws IOException throw when I/O error occur */ private void readNodeFile(String filename) throws IOException { // REDFLAG: Any way to share this code with NodePeer? FileInputStream fis = new FileInputStream(filename); InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); BufferedReader br = new BufferedReader(isr); SimpleFieldSet fs = new SimpleFieldSet(br, false, true); br.close(); // Read contents String[] udp = fs.getAll("physical.udp"); if((udp != null) && (udp.length > 0)) { for(String udpAddr : udp) { // Just keep the first one with the correct port number. Peer p; try { p = new Peer(udpAddr, false, true); } catch (<API key> e) { Logger.error(this, "Invalid hostname or IP Address syntax error while parsing our darknet node reference: "+udpAddr); System.err.println("Invalid hostname or IP Address syntax error while parsing our darknet node reference: "+udpAddr); continue; } catch (PeerParseException e) { throw (IOException)new IOException().initCause(e); } if(p.getPort() == <API key>()) { // DNSRequester doesn't deal with our own node ipDetector.setOldIPAddress(p.getFreenetAddress()); break; } } } darknetCrypto.readCrypto(fs); swapIdentifier = Fields.bytesToLong(darknetCrypto.identityHashHash); String loc = fs.get("location"); double locD = Location.getLocation(loc); if (locD == -1.0) throw new IOException("Invalid location: " + loc); lm.setLocation(locD); myName = fs.get("myName"); if(myName == null) { myName = newName(); } String verString = fs.get("version"); if(verString == null) { Logger.error(this, "No version!"); System.err.println("No version!"); } else { lastVersion = Version.<API key>(verString, -1); } } public void makeStore(String val) throws <API key> { String suffix = getStoreSuffix(); if (val.equals("salt-hash")) { try { initSaltHashFS(suffix, true, null); } catch (NodeInitException e) { Logger.error(this, "Unable to create new store", e); System.err.println("Unable to create new store: "+e); e.printStackTrace(); // FIXME l10n both on the NodeInitException and the wrapper message throw new <API key>("Unable to create new store: "+e); } } else { initRAMFS(); } synchronized(Node.this) { storeType = val; } } private String newName() { return "Freenet node with no name #"+random.nextLong(); } private final Object writeNodeFileSync = new Object(); public void writeNodeFile() { synchronized(writeNodeFileSync) { writeNodeFile(nodeDir.file("node-"+<API key>()), nodeDir.file("node-"+<API key>()+".bak")); } } public void writeOpennetFile() { OpennetManager om = opennet; if(om != null) om.writeFile(); } private void writeNodeFile(File orig, File backup) { SimpleFieldSet fs = darknetCrypto.<API key>(); if(orig.exists()) backup.delete(); FileOutputStream fos = null; try { fos = new FileOutputStream(backup); fs.writeTo(fos); fos.close(); fos = null; FileUtil.renameTo(backup, orig); } catch (IOException ioe) { Logger.error(this, "IOE :"+ioe.getMessage(), ioe); return; } finally { Closer.close(fos); } } private void <API key>() { Logger.normal(this, "Creating new node file from scratch"); // Don't need to set <API key>() // FIXME use a real IP! darknetCrypto.initCrypto(); swapIdentifier = Fields.bytesToLong(darknetCrypto.identityHashHash); myName = newName(); } /** * Read the config file from the arguments. * Then create a node. * Anything that needs static init should ideally be in here. * @param args */ public static void main(String[] args) throws IOException { NodeStarter.main(args); } public boolean isUsingWrapper(){ if(nodeStarter!=null && WrapperManager.<API key>()) return true; else return false; } public NodeStarter getNodeStarter(){ return nodeStarter; } /** * Create a Node from a Config object. * @param config The Config object for this node. * @param r The random number generator for this node. Passed in because we may want * to use a non-secure RNG for e.g. one-JVM live-code simulations. Should be a Yarrow in * a production node. Yarrow will be used if that parameter is null * @param weakRandom The fast random number generator the node will use. If null a MT * instance will be used, seeded from the secure PRNG. * @param lc logging config Handler * @param ns NodeStarter * @param executor Executor * @throws NodeInitException If the node initialization fails. */ Node(PersistentConfig config, RandomSource r, RandomSource weakRandom, <API key> lc, NodeStarter ns, Executor executor) throws NodeInitException { this.shutdownHook = <API key>.get(); // Easy stuff String tmp = "Initializing Node using Freenet Build #"+Version.buildNumber()+" r"+Version.cvsRevision()+" and freenet-ext Build #"+NodeStarter.extBuildNumber+" r"+NodeStarter.extRevisionNumber+" with "+System.getProperty("java.vendor")+" JVM version "+System.getProperty("java.version")+" running on "+System.getProperty("os.arch")+' '+System.getProperty("os.name")+' '+System.getProperty("os.version"); fixCertsFiles(); Logger.normal(this, tmp); System.out.println(tmp); collector = new <API key>(); this.executor = executor; nodeStarter=ns; if(logConfigHandler != lc) logConfigHandler=lc; getPubKey = new NodeGetPubkey(this); startupTime = System.currentTimeMillis(); SimpleFieldSet oldConfig = config.getSimpleFieldSet(); // Setup node-specific configuration final SubConfig nodeConfig = config.createSubConfig("node"); final SubConfig installConfig = config.createSubConfig("node.install"); int sortOrder = 0; // Directory for node-related files other than store this.userDir = setupProgramDir(installConfig, "userDir", ".", "Node.userDir", "Node.userDirLong", nodeConfig); this.cfgDir = setupProgramDir(installConfig, "cfgDir", getUserDir().toString(), "Node.cfgDir", "Node.cfgDirLong", nodeConfig); this.nodeDir = setupProgramDir(installConfig, "nodeDir", getUserDir().toString(), "Node.nodeDir", "Node.nodeDirLong", nodeConfig); this.runDir = setupProgramDir(installConfig, "runDir", getUserDir().toString(), "Node.runDir", "Node.runDirLong", nodeConfig); this.pluginDir = setupProgramDir(installConfig, "pluginDir", userDir().file("plugins").toString(), "Node.pluginDir", "Node.pluginDirLong", nodeConfig); // l10n stuffs nodeConfig.register("l10n", Locale.getDefault().getLanguage().toLowerCase(), sortOrder++, false, true, "Node.l10nLanguage", "Node.l10nLanguageLong", new L10nCallback()); try { new NodeL10n(BaseL10n.LANGUAGE.mapToLanguage(nodeConfig.getString("l10n")), getCfgDir()); } catch (<API key> e) { try { new NodeL10n(BaseL10n.LANGUAGE.mapToLanguage(nodeConfig.getOption("l10n").getDefault()), getCfgDir()); } catch (<API key> e1) { new NodeL10n(BaseL10n.LANGUAGE.mapToLanguage(BaseL10n.LANGUAGE.getDefault().shortCode), getCfgDir()); } } // FProxy config needs to be here too SubConfig fproxyConfig = config.createSubConfig("fproxy"); try { toadlets = new SimpleToadletServer(fproxyConfig, new ArrayBucketFactory(), executor, this); fproxyConfig.<API key>(); toadlets.start(); } catch (IOException e4) { Logger.error(this, "Could not start web interface: "+e4, e4); System.err.println("Could not start web interface: "+e4); e4.printStackTrace(); throw new NodeInitException(NodeInitException.<API key>, "Could not start FProxy: "+e4); } catch (<API key> e4) { System.err.println("Invalid config value, cannot start web interface: "+e4); e4.printStackTrace(); throw new NodeInitException(NodeInitException.<API key>, "Could not start FProxy: "+e4); } final NativeThread <API key> = new NativeThread(new Runnable() { long tLastAdded = -1; private void recurse(File f) { if(isPRNGReady) return; extendTimeouts(); File[] subDirs = f.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.exists() && pathname.canRead() && pathname.isDirectory(); } }); if(subDirs != null) for(File currentDir : subDirs) recurse(currentDir); } @Override public void run() { try { // Delay entropy generation helper hack if enough entropy available Thread.sleep(100); } catch (<API key> e) { } if(isPRNGReady) return; System.out.println("Not enough entropy available."); System.out.println("Trying to gather entropy (randomness) by reading the disk..."); if(File.separatorChar == '/') { if(new File("/dev/hwrng").exists()) System.out.println("/dev/hwrng exists - have you installed rng-tools?"); else System.out.println("You should consider installing a better random number generator e.g. haveged."); } extendTimeouts(); for(File root : File.listRoots()) { if(isPRNGReady) return; recurse(root); } } /** This is ridiculous, but for some users it can take more than an hour, and timing out sucks * a few bytes and then times out again. :( */ static final int EXTEND_BY = 60*60*1000; private void extendTimeouts() { long now = System.currentTimeMillis(); if(now - tLastAdded < EXTEND_BY/2) return; long target = tLastAdded + EXTEND_BY; while(target < now) target += EXTEND_BY; long extend = target - now; assert(extend < Integer.MAX_VALUE); assert(extend > 0); WrapperManager.signalStarting((int)extend); tLastAdded = now; } }, "Entropy Gathering Thread", NativeThread.MIN_PRIORITY, true); // Setup RNG if needed : DO NOT USE IT BEFORE THAT POINT! if (r == null) { // Preload required freenet.crypt.Util and freenet.crypt.Rijndael classes (selftest can delay Yarrow startup and trigger false lack-of-enthropy message) freenet.crypt.Util.mdProviders.size(); freenet.crypt.ciphers.Rijndael.getProviderName(); File seed = userDir.file("prng.seed"); FileUtil.setOwnerRW(seed); <API key>.start(); // Can block. this.random = new Yarrow(seed); // This might block on /dev/random while doing new SecureRandom(). Once it's created, it won't block. ECDH.blockingInit(); } else { this.random = r; // if it's not null it's because we are running in the simulator } // This can block too. this.secureRandom = NodeStarter.<API key>(); isPRNGReady = true; toadlets.getStartupToadlet().setIsPRNGReady(); if(weakRandom == null) { byte buffer[] = new byte[16]; random.nextBytes(buffer); this.fastWeakRandom = new MersenneTwister(buffer); }else this.fastWeakRandom = weakRandom; nodeNameUserAlert = new <API key>(this); this.config = config; lm = new LocationManager(random, this); try { localhostAddress = InetAddress.getByName("127.0.0.1"); } catch (<API key> e3) { // Does not do a reverse lookup, so this is impossible throw new Error(e3); } fLocalhostAddress = new FreenetInetAddress(localhostAddress); this.securityLevels = new SecurityLevels(this, config); // Location of master key nodeConfig.register("masterKeyFile", "master.keys", sortOrder++, true, true, "Node.masterKeyFile", "Node.masterKeyFileLong", new StringCallback() { @Override public String get() { if(masterKeysFile == null) return "none"; else return masterKeysFile.getPath(); } @Override public void set(String val) throws <API key>, <API key> { // FIXME l10n // FIXME wipe the old one and move throw new <API key>("Node.masterKeyFile cannot be changed on the fly, you must shutdown, wipe the old file and reconfigure"); } }); String value = nodeConfig.getString("masterKeyFile"); File f; if (value.equalsIgnoreCase("none")) { f = null; } else { f = new File(value); if(f.exists() && !(f.canWrite() && f.canRead())) throw new NodeInitException(NodeInitException.<API key>, "Cannot read from and write to master keys file "+f); } masterKeysFile = f; FileUtil.setOwnerRW(masterKeysFile); nodeConfig.register("<API key>", false, sortOrder++, true, false, "Node.<API key>", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { synchronized(Node.this) { return <API key>; } } @Override public void set(Boolean val) throws <API key>, <API key> { synchronized(this) { if(val == <API key>) return; if(val) return; } <API key>(); } }); <API key> = nodeConfig.getBoolean("<API key>"); byte[] clientCacheKey = null; Master<API key> = null; for(int i=0;i<2; i++) { try { if(securityLevels.physicalThreatLevel == <API key>.MAXIMUM) { keys = MasterKeys.createRandom(secureRandom); } else { keys = MasterKeys.read(masterKeysFile, secureRandom, ""); } clientCacheKey = keys.<API key>; persistentSecret = keys.<API key>(); databaseKey = keys.createDatabaseKey(secureRandom); if(securityLevels.<API key>() == <API key>.HIGH) { System.err.println("Physical threat level is set to HIGH but no password, resetting to NORMAL - probably timing glitch"); securityLevels.<API key>(<API key>.NORMAL); } break; } catch (<API key> e) { break; } catch (<API key> e) { System.err.println("Impossible: master keys file "+masterKeysFile+" too " + e.sizeToString() + "! Deleting to enable startup, but you will lose your client cache."); masterKeysFile.delete(); } catch (IOException e) { break; } } // Boot ID bootID = random.nextLong(); // Fixed length file containing boot ID. Accessed with random access file. So hopefully it will always be // written. Note that we set lastBootID to -1 if we can't _write_ our ID as well as if we can't read it, // because if we can't write it then we probably couldn't write it on the last bootup either. File bootIDFile = runDir.file("bootID"); int BOOT_FILE_LENGTH = 64 / 4; // A long in padded hex bytes long oldBootID = -1; RandomAccessFile raf = null; try { raf = new RandomAccessFile(bootIDFile, "rw"); if(raf.length() < BOOT_FILE_LENGTH) { oldBootID = -1; } else { byte[] buf = new byte[BOOT_FILE_LENGTH]; raf.readFully(buf); String s = new String(buf, "ISO-8859-1"); try { oldBootID = Fields.bytesToLong(HexUtil.hexToBytes(s)); } catch (<API key> e) { oldBootID = -1; } raf.seek(0); } String s = HexUtil.bytesToHex(Fields.longToBytes(bootID)); byte[] buf = s.getBytes("ISO-8859-1"); if(buf.length != BOOT_FILE_LENGTH) System.err.println("Not 16 bytes for boot ID "+bootID+" - WTF??"); raf.write(buf); } catch (IOException e) { oldBootID = -1; // If we have an error in reading, *or in writing*, we don't reliably know the last boot ID. } finally { Closer.close(raf); } lastBootID = oldBootID; nodeConfig.register("<API key>", false, sortOrder++, true, false, "Node.disablePHTLS", "Node.disablePHTLSLong", new BooleanCallback() { @Override public Boolean get() { return <API key>; } @Override public void set(Boolean val) throws <API key> { <API key> = val; } }); <API key> = nodeConfig.getBoolean("<API key>"); nodeConfig.register("maxHTL", DEFAULT_MAX_HTL, sortOrder++, true, false, "Node.maxHTL", "Node.maxHTLLong", new ShortCallback() { @Override public Short get() { return maxHTL; } @Override public void set(Short val) throws <API key> { if(val < 0) throw new <API key>("Impossible max HTL"); maxHTL = val; } }, false); maxHTL = nodeConfig.getShort("maxHTL"); class <API key> extends StringCallback implements <API key> { @Override public String get() { return trafficClass.name(); } @Override public void set(String tcName) throws <API key>, <API key> { try { trafficClass = TrafficClass.fromNameOrValue(tcName); } catch (<API key> e) { throw new <API key>(e); } throw new <API key>("TrafficClass cannot change on the fly"); } @Override public String[] getPossibleValues() { ArrayList<String> array = new ArrayList<String>(); for (TrafficClass tc : TrafficClass.values()) array.add(tc.name()); return array.toArray(new String[0]); } } nodeConfig.register("trafficClass", TrafficClass.getDefault().name(), sortOrder++, true, false, "Node.trafficClass", "Node.trafficClassLong", new <API key>()); String trafficClassValue = nodeConfig.getString("trafficClass"); try { trafficClass = TrafficClass.fromNameOrValue(trafficClassValue); } catch (<API key> e) { Logger.error(this, "Invalid trafficClass:"+trafficClassValue+" resetting the value to default.", e); trafficClass = TrafficClass.getDefault(); } // FIXME maybe these should persist? They need to be private. decrementAtMax = random.nextDouble() <= <API key>; decrementAtMin = random.nextDouble() <= <API key>; // Determine where to bind to usm = new MessageCore(executor); // FIXME maybe these configs should actually be under a node.ip subconfig? ipDetector = new NodeIPDetector(this); sortOrder = ipDetector.registerConfigs(nodeConfig, sortOrder); // ARKs enabled? nodeConfig.register("enableARKs", true, sortOrder++, true, false, "Node.enableARKs", "Node.enableARKsLong", new BooleanCallback() { @Override public Boolean get() { return enableARKs; } @Override public void set(Boolean val) throws <API key> { throw new <API key>("Cannot change on the fly"); } @Override public boolean isReadOnly() { return true; } }); enableARKs = nodeConfig.getBoolean("enableARKs"); nodeConfig.register("<API key>", true, sortOrder++, true, false, "Node.<API key>", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { return <API key>; } @Override public void set(Boolean val) throws <API key> { throw new <API key>("Cannot change on the fly"); } @Override public boolean isReadOnly() { return true; } }); <API key> = nodeConfig.getBoolean("<API key>"); nodeConfig.register("<API key>", true, sortOrder++, true, false, "Node.<API key>", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { return <API key>; } @Override public void set(Boolean val) throws <API key> { throw new <API key>("Cannot change on the fly"); } @Override public boolean isReadOnly() { return true; } }); <API key> = nodeConfig.getBoolean("<API key>"); nodeConfig.register("enableSwapping", true, sortOrder++, true, false, "Node.enableSwapping", "Node.enableSwappingLong", new BooleanCallback() { @Override public Boolean get() { return enableSwapping; } @Override public void set(Boolean val) throws <API key> { throw new <API key>("Cannot change on the fly"); } @Override public boolean isReadOnly() { return true; } }); enableSwapping = nodeConfig.getBoolean("enableSwapping"); /* * Publish our peers' locations is enabled, even in MAXIMUM network security and/or HIGH friends security, * because a node which doesn't publish its peers' locations will get dramatically less traffic. * * Publishing our peers' locations does make us slightly more vulnerable to some attacks, but I don't think * it's a big difference: swapping reveals the same information, it just doesn't update as quickly. This * may help slightly, but probably not dramatically against a clever attacker. * * FIXME review this decision. */ nodeConfig.register("<API key>", true, sortOrder++, true, false, "Node.<API key>", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { return <API key>; } @Override public void set(Boolean val) throws <API key> { <API key> = val; } }); <API key> = nodeConfig.getBoolean("<API key>"); nodeConfig.register("<API key>", true, sortOrder++, true, false, "Node.<API key>", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { return <API key>; } @Override public void set(Boolean val) throws <API key> { <API key> = val; } }); <API key> = nodeConfig.getBoolean("<API key>"); nodeConfig.register("enableSwapQueueing", true, sortOrder++, true, false, "Node.enableSwapQueueing", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { return enableSwapQueueing; } @Override public void set(Boolean val) throws <API key> { enableSwapQueueing = val; } }); enableSwapQueueing = nodeConfig.getBoolean("enableSwapQueueing"); nodeConfig.register("<API key>", true, sortOrder++, true, false, "Node.<API key>", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { return <API key>; } @Override public void set(Boolean val) throws <API key> { <API key> = val; } }); <API key> = nodeConfig.getBoolean("<API key>"); // Determine the port number // @see #191 if(oldConfig != null && "-1".equals(oldConfig.get("node.listenPort"))) throw new NodeInitException(NodeInitException.<API key>, "Your freenet.ini file is corrupted! 'listenPort=-1'"); NodeCryptoConfig darknetConfig = new NodeCryptoConfig(nodeConfig, sortOrder++, false, securityLevels); sortOrder += NodeCryptoConfig.OPTION_COUNT; darknetCrypto = new NodeCrypto(this, false, darknetConfig, startupTime, enableARKs); // Must be created after darknetCrypto dnsr = new DNSRequester(this); ps = new PacketSender(this); ticker = new PrioritizedTicker(executor, <API key>()); if(executor instanceof PooledExecutor) ((PooledExecutor)executor).setTicker(ticker); Logger.normal(Node.class, "Creating node..."); shutdownHook.addEarlyJob(new Thread() { @Override public void run() { if (opennet != null) opennet.stop(false); } }); shutdownHook.addEarlyJob(new Thread() { @Override public void run() { darknetCrypto.stop(); } }); // Bandwidth limit nodeConfig.register("<API key>", "15K", sortOrder++, false, true, "Node.outBWLimit", "Node.outBWLimitLong", new IntCallback() { @Override public Integer get() { //return BlockTransmitter.<API key>(); return <API key>; } @Override public void set(Integer obwLimit) throws <API key> { BandwidthManager.<API key>(obwLimit); try { outputThrottle.<API key>(SECONDS.toNanos(1) / obwLimit, obwLimit/2); } catch (<API key> e) { throw new <API key>(e); } synchronized(Node.this) { <API key> = obwLimit; } } }); int obwLimit = nodeConfig.getInt("<API key>"); if (obwLimit < minimumBandwidth) { obwLimit = minimumBandwidth; // upgrade slow nodes automatically Logger.normal(Node.class, "Output bandwidth was lower than minimum bandwidth. Increased to minimum bandwidth."); } <API key> = obwLimit; try { BandwidthManager.<API key>(<API key>); } catch (<API key> e) { throw new NodeInitException(NodeInitException.EXIT_BAD_BWLIMIT, e.getMessage()); } // Bucket size of 0.5 seconds' worth of bytes. // Add them at a rate determined by the obwLimit. // Maximum forced bytes 80%, in other words, 20% of the bandwidth is reserved for // block transfers, so we will use that 20% for block transfers even if more than 80% of the limit is used for non-limited data (resends etc). int bucketSize = obwLimit/2; // Must have at least space for ONE PACKET. // FIXME: make compatible with alternate transports. bucketSize = Math.max(bucketSize, 2048); try { outputThrottle = new TokenBucket(bucketSize, SECONDS.toNanos(1) / obwLimit, obwLimit/2); } catch (<API key> e) { throw new NodeInitException(NodeInitException.EXIT_BAD_BWLIMIT, e.getMessage()); } nodeConfig.register("inputBandwidthLimit", "-1", sortOrder++, false, true, "Node.inBWLimit", "Node.inBWLimitLong", new IntCallback() { @Override public Integer get() { if(inputLimitDefault) return -1; return inputBandwidthLimit; } @Override public void set(Integer ibwLimit) throws <API key> { synchronized(Node.this) { BandwidthManager.<API key>(ibwLimit); if(ibwLimit == -1) { inputLimitDefault = true; ibwLimit = <API key> * 4; } else { inputLimitDefault = false; } inputBandwidthLimit = ibwLimit; } } }); int ibwLimit = nodeConfig.getInt("inputBandwidthLimit"); if(ibwLimit == -1) { inputLimitDefault = true; ibwLimit = obwLimit * 4; } else if (ibwLimit < minimumBandwidth) { ibwLimit = minimumBandwidth; // upgrade slow nodes automatically Logger.normal(Node.class, "Input bandwidth was lower than minimum bandwidth. Increased to minimum bandwidth."); } inputBandwidthLimit = ibwLimit; try { BandwidthManager.<API key>(inputBandwidthLimit); } catch (<API key> e) { throw new NodeInitException(NodeInitException.EXIT_BAD_BWLIMIT, e.getMessage()); } nodeConfig.register("<API key>", "8MiB", sortOrder++, true, true, "Node.<API key>", "Node.<API key>", new LongCallback() { @Override public Long get() { return <API key>; } @Override public void set(Long <API key>) { synchronized(Node.this) { Node.this.<API key> = <API key>; } } }, true); <API key> = nodeConfig.getLong("<API key>"); nodeConfig.register("<API key>", "10", sortOrder++, true, true, "Node.<API key>", "Node.<API key>", new IntCallback() { @Override public Integer get() { return <API key>; } @Override public void set(Integer <API key>) { synchronized(Node.this) { if (<API key> < 0 || <API key> > 100) { Logger.normal(Node.class, "Wrong minimum compression percentage" + <API key>); return; } Node.this.<API key> = <API key>; } } }, Dimension.NOT); <API key> = nodeConfig.getInt("<API key>"); nodeConfig.register("<API key>", "20m", sortOrder++, true, true, "Node.<API key>", "Node.<API key>", new IntCallback() { @Override public Integer get() { return <API key>; } @Override public void set(Integer <API key>) { synchronized(Node.this) { Node.this.<API key> = <API key>; } } }, Dimension.DURATION); <API key> = nodeConfig.getInt("<API key>"); nodeConfig.register("<API key>", true, sortOrder++, true, true, "Node.<API key>", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { return <API key>; } @Override public void set(Boolean <API key>) { synchronized(Node.this) { Node.this.<API key> = <API key>; } } }); <API key> = nodeConfig.getBoolean("<API key>"); nodeConfig.register("<API key>", false, sortOrder++, true, false, "Node.<API key>", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { return throttleLocalData; } @Override public void set(Boolean val) throws <API key> { throttleLocalData = val; } }); throttleLocalData = nodeConfig.getBoolean("<API key>"); String s = "Testnet mode DISABLED. You may have some level of anonymity. :)\n"+ "Note that this version of Freenet is still a very early alpha, and may well have numerous bugs and design flaws.\n"+ "In particular: YOU ARE WIDE OPEN TO YOUR IMMEDIATE PEERS! They can eavesdrop on your requests with relatively little difficulty at present (correlation attacks etc)."; Logger.normal(this, s); System.err.println(s); File nodeFile = nodeDir.file("node-"+<API key>()); File nodeFileBackup = nodeDir.file("node-"+<API key>()+".bak"); // After we have set up testnet and IP address, load the node file try { // FIXME should take file directly? readNodeFile(nodeFile.getPath()); } catch (IOException e) { try { System.err.println("Trying to read node file backup ..."); readNodeFile(nodeFileBackup.getPath()); } catch (IOException e1) { if(nodeFile.exists() || nodeFileBackup.exists()) { System.err.println("No node file or cannot read, (re)initialising crypto etc"); System.err.println(e1.toString()); e1.printStackTrace(); System.err.println("After:"); System.err.println(e.toString()); e.printStackTrace(); } else { System.err.println("Creating new cryptographic keys..."); } <API key>(); } } // Then read the peers peers = new PeerManager(this, shutdownHook); tracker = new RequestTracker(peers, ticker); usm.setDispatcher(dispatcher=new NodeDispatcher(this)); uptime = new UptimeEstimator(runDir, ticker, darknetCrypto.identityHash); // ULPRs failureTable = new FailureTable(this); nodeStats = new NodeStats(this, sortOrder, config.createSubConfig("node.load"), obwLimit, ibwLimit, lastVersion); // clientCore needs new load management and other settings from stats. clientCore = new NodeClientCore(this, config, nodeConfig, installConfig, <API key>(), sortOrder, oldConfig, fproxyConfig, toadlets, databaseKey, persistentSecret); toadlets.setCore(clientCore); if (JVMVersion.isEOL()) { clientCore.alerts.register(new JVMVersionAlert()); } if(<API key>) <API key>(); // Node updater support System.out.println("Initializing Node Updater"); try { nodeUpdater = NodeUpdateManager.maybeCreate(this, config); } catch (<API key> e) { e.printStackTrace(); throw new NodeInitException(NodeInitException.<API key>, "Could not create Updater: "+e); } // Opennet final SubConfig opennetConfig = config.createSubConfig("node.opennet"); opennetConfig.register("connectToSeednodes", true, 0, true, false, "Node.withAnnouncement", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { return <API key>; } @Override public void set(Boolean val) throws <API key>, <API key> { if (get().equals(val)) return; synchronized(Node.this) { <API key> = val; if(opennet != null) throw new <API key>(l10n("<API key>")); } } }); <API key> = opennetConfig.getBoolean("connectToSeednodes"); // Can be enabled on the fly opennetConfig.register("enabled", false, 0, true, true, "Node.opennetEnabled", "Node.opennetEnabledLong", new BooleanCallback() { @Override public Boolean get() { synchronized(Node.this) { return opennet != null; } } @Override public void set(Boolean val) throws <API key> { OpennetManager o; synchronized(Node.this) { if(val == (opennet != null)) return; if(val) { try { o = opennet = new OpennetManager(Node.this, opennetCryptoConfig, System.currentTimeMillis(), <API key>); } catch (NodeInitException e) { opennet = null; throw new <API key>(e.getMessage()); } } else { o = opennet; opennet = null; } } if(val) o.start(); else o.stop(true); ipDetector.ipDetectorManager.notifyPortChange(<API key>()); } }); boolean opennetEnabled = opennetConfig.getBoolean("enabled"); opennetConfig.register("maxOpennetPeers", OpennetManager.<API key>, 1, true, false, "Node.maxOpennetPeers", "Node.maxOpennetPeersLong", new IntCallback() { @Override public Integer get() { return maxOpennetPeers; } @Override public void set(Integer <API key>) throws <API key> { if(<API key> < 0) throw new <API key>(l10n("mustBePositive")); if(<API key> > OpennetManager.<API key>) throw new <API key>(l10n("<API key>", "maxpeers", Integer.toString(OpennetManager.<API key>))); maxOpennetPeers = <API key>; } } , false); maxOpennetPeers = opennetConfig.getInt("maxOpennetPeers"); if(maxOpennetPeers > OpennetManager.<API key>) { Logger.error(this, "maxOpennetPeers may not be over "+OpennetManager.<API key>); maxOpennetPeers = OpennetManager.<API key>; } opennetCryptoConfig = new NodeCryptoConfig(opennetConfig, 2 /* 0 = enabled */, true, securityLevels); if(opennetEnabled) { opennet = new OpennetManager(this, opennetCryptoConfig, System.currentTimeMillis(), <API key>); // Will be started later } else { opennet = null; } securityLevels.<API key>(new <API key><<API key>>() { @Override public void onChange(<API key> oldLevel, <API key> newLevel) { if(newLevel == <API key>.HIGH || newLevel == <API key>.MAXIMUM) { OpennetManager om; synchronized(Node.this) { om = opennet; if(om != null) opennet = null; } if(om != null) { om.stop(true); ipDetector.ipDetectorManager.notifyPortChange(<API key>()); } } else if(newLevel == <API key>.NORMAL || newLevel == <API key>.LOW) { OpennetManager o = null; synchronized(Node.this) { if(opennet == null) { try { o = opennet = new OpennetManager(Node.this, opennetCryptoConfig, System.currentTimeMillis(), <API key>); } catch (NodeInitException e) { opennet = null; Logger.error(this, "UNABLE TO ENABLE OPENNET: "+e, e); clientCore.alerts.register(new SimpleUserAlert(false, l10n("<API key>"), l10n("enableOpennetFailed", "message", e.getLocalizedMessage()), l10n("enableOpennetFailed", "message", e.getLocalizedMessage()), UserAlert.ERROR)); } } } if(o != null) { o.start(); ipDetector.ipDetectorManager.notifyPortChange(<API key>()); } } Node.this.config.store(); } }); opennetConfig.register("<API key>", false, 2, true, true, "Node.<API key>", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { return <API key>; } @Override public void set(Boolean val) throws <API key> { <API key> = val; } }); <API key> = opennetConfig.getBoolean("<API key>"); if(<API key> && opennet != null) opennet.crypto.socket.getAddressTracker().setHugeTracker(); opennetConfig.<API key>(); nodeConfig.register("<API key>", true, sortOrder++, true, false, "Node.<API key>", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { synchronized(Node.this) { return <API key>; } } @Override public void set(Boolean val) throws <API key> { synchronized(Node.this) { <API key> = val; } } }); <API key> = nodeConfig.getBoolean("<API key>"); this.extraPeerDataDir = userDir.file("extra-peer-data-"+<API key>()); if (!((extraPeerDataDir.exists() && extraPeerDataDir.isDirectory()) || (extraPeerDataDir.mkdir()))) { String msg = "Could not find or create extra peer data directory"; throw new NodeInitException(NodeInitException.EXIT_BAD_DIR, msg); } // Name nodeConfig.register("name", myName, sortOrder++, false, true, "Node.nodeName", "Node.nodeNameLong", new NodeNameCallback()); myName = nodeConfig.getString("name"); // Datastore nodeConfig.register("<API key>", false, sortOrder++, true, false, "Node.forceBigShrink", "Node.forceBigShrinkLong", new BooleanCallback() { @Override public Boolean get() { synchronized(Node.this) { return <API key>; } } @Override public void set(Boolean val) throws <API key> { synchronized(Node.this) { <API key> = val; } } }); // Datastore nodeConfig.register("storeType", "ram", sortOrder++, true, true, "Node.storeType", "Node.storeTypeLong", new StoreTypeCallback()); storeType = nodeConfig.getString("storeType"); /* * Very small initial store size, since the node will preallocate it when starting up for the first time, * BLOCKING STARTUP, and since everyone goes through the wizard anyway... */ nodeConfig.register("storeSize", DEFAULT_STORE_SIZE, sortOrder++, false, true, "Node.storeSize", "Node.storeSizeLong", new LongCallback() { @Override public Long get() { return <API key>; } @Override public void set(Long storeSize) throws <API key> { if(storeSize < MIN_STORE_SIZE) throw new <API key>(l10n("invalidStoreSize")); long newMaxStoreKeys = storeSize / sizePerKey; if(newMaxStoreKeys == maxTotalKeys) return; // Update each datastore synchronized(Node.this) { <API key> = storeSize; maxTotalKeys = newMaxStoreKeys; maxStoreKeys = maxTotalKeys / 2; maxCacheKeys = maxTotalKeys - maxStoreKeys; } try { chkDatastore.setMaxKeys(maxStoreKeys, <API key>); chkDatacache.setMaxKeys(maxCacheKeys, <API key>); pubKeyDatastore.setMaxKeys(maxStoreKeys, <API key>); pubKeyDatacache.setMaxKeys(maxCacheKeys, <API key>); sskDatastore.setMaxKeys(maxStoreKeys, <API key>); sskDatacache.setMaxKeys(maxCacheKeys, <API key>); } catch (IOException e) { // FIXME we need to be able to tell the user. Logger.error(this, "Caught "+e+" resizing the datastore", e); System.err.println("Caught "+e+" resizing the datastore"); e.printStackTrace(); } //Perhaps a bit hackish...? Seems like this should be near it's definition in NodeStats. nodeStats.avgStoreCHKLocation.changeMaxReports((int)maxStoreKeys); nodeStats.avgCacheCHKLocation.changeMaxReports((int)maxCacheKeys); nodeStats.<API key>.changeMaxReports((int)maxCacheKeys); nodeStats.<API key>.changeMaxReports((int)maxCacheKeys); nodeStats.avgStoreSSKLocation.changeMaxReports((int)maxStoreKeys); nodeStats.avgCacheSSKLocation.changeMaxReports((int)maxCacheKeys); nodeStats.<API key>.changeMaxReports((int)maxCacheKeys); nodeStats.<API key>.changeMaxReports((int)maxCacheKeys); } }, true); <API key> = nodeConfig.getLong("storeSize"); if(<API key> < MIN_STORE_SIZE && !storeType.equals("ram")) { // totally arbitrary minimum! throw new NodeInitException(NodeInitException.<API key>, "Store size too small"); } maxTotalKeys = <API key> / sizePerKey; nodeConfig.register("storeUseSlotFilters", true, sortOrder++, true, false, "Node.storeUseSlotFilters", "Node.<API key>", new BooleanCallback() { public Boolean get() { synchronized(Node.this) { return storeUseSlotFilters; } } public void set(Boolean val) throws <API key>, <API key> { synchronized(Node.this) { storeUseSlotFilters = val; } // FIXME l10n throw new <API key>("Need to restart to change storeUseSlotFilters"); } }); storeUseSlotFilters = nodeConfig.getBoolean("storeUseSlotFilters"); nodeConfig.register("<API key>", <API key>.<API key>, sortOrder++, true, false, "Node.<API key>", "Node.<API key>", new IntCallback() { @Override public Integer get() { return <API key>.getPersistenceTime(); } @Override public void set(Integer val) throws <API key>, <API key> { if(val >= -1) <API key>.setPersistenceTime(val); else throw new <API key>(l10n("<API key>")); } }, false); nodeConfig.register("<API key>", false, sortOrder++, true, false, "Node.<API key>", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { return <API key>; } @Override public void set(Boolean val) throws <API key>, <API key> { <API key> = val; } }); <API key> = nodeConfig.getBoolean("<API key>"); this.storeDir = setupProgramDir(installConfig, "storeDir", userDir().file("datastore").getPath(), "Node.storeDirectory", "Node.storeDirectoryLong", nodeConfig); installConfig.<API key>(); final String suffix = getStoreSuffix(); maxStoreKeys = maxTotalKeys / 2; maxCacheKeys = maxTotalKeys - maxStoreKeys; /* * On Windows, setting the file length normally involves writing lots of zeros. * So it's an uninterruptible system call that takes a loooong time. On OS/X, * presumably the same is true. If the RNG is fast enough, this means that * setting the length and writing random data take exactly the same amount * of time. On most versions of Unix, holes can be created. However on all * systems, predictable disk usage is a good thing. So lets turn it on by * default for now, on all systems. The datastore can be read but mostly not * written while the random data is being written. */ nodeConfig.register("storePreallocate", true, sortOrder++, true, true, "Node.storePreallocate", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { return storePreallocate; } @Override public void set(Boolean val) throws <API key>, <API key> { storePreallocate = val; if (storeType.equals("salt-hash")) { setPreallocate(chkDatastore, val); setPreallocate(chkDatacache, val); setPreallocate(pubKeyDatastore, val); setPreallocate(pubKeyDatacache, val); setPreallocate(sskDatastore, val); setPreallocate(sskDatacache, val); } } private void setPreallocate(StoreCallback<?> datastore, boolean val) { // Avoid race conditions by checking first. FreenetStore<?> store = datastore.getStore(); if(store instanceof <API key>) ((<API key><?>)store).setPreallocate(val); }} ); storePreallocate = nodeConfig.getBoolean("storePreallocate"); if(File.separatorChar == '/' && System.getProperty("os.name").toLowerCase().indexOf("mac os") < 0) { securityLevels.<API key>(new <API key><SecurityLevels.<API key>>() { @Override public void onChange(<API key> oldLevel, <API key> newLevel) { try { if(newLevel == <API key>.LOW) nodeConfig.set("storePreallocate", false); else nodeConfig.set("storePreallocate", true); } catch (<API key> e) { // Ignore } catch (<API key> e) { // Ignore } } }); } securityLevels.<API key>(new <API key><SecurityLevels.<API key>>() { @Override public void onChange(<API key> oldLevel, <API key> newLevel) { if(newLevel == <API key>.MAXIMUM) { synchronized(this) { <API key> = false; <API key> = false; } try { killMasterKeysFile(); clientCore.<API key>.disableWrite(); clientCore.<API key>.waitForNotWriting(); clientCore.<API key>.deleteAllFiles(); } catch (IOException e) { masterKeysFile.delete(); Logger.error(this, "Unable to securely delete "+masterKeysFile); System.err.println(NodeL10n.getBase().getString("SecurityLevels.<API key>", "filename", masterKeysFile.getAbsolutePath())); clientCore.alerts.register(new SimpleUserAlert(true, NodeL10n.getBase().getString("SecurityLevels.<API key>"), NodeL10n.getBase().getString("SecurityLevels.<API key>"), NodeL10n.getBase().getString("SecurityLevels.<API key>"), UserAlert.CRITICAL_ERROR)); } } if(oldLevel == <API key>.MAXIMUM && newLevel != <API key>.HIGH) { // Not passworded. // Create the master.keys. // Keys must exist. try { MasterKeys keys; synchronized(this) { keys = Node.this.keys; } keys.changePassword(masterKeysFile, "", secureRandom); } catch (IOException e) { Logger.error(this, "Unable to create encryption keys file: "+masterKeysFile+" : "+e, e); System.err.println("Unable to create encryption keys file: "+masterKeysFile+" : "+e); e.printStackTrace(); } } } }); if(securityLevels.physicalThreatLevel == <API key>.MAXIMUM) { try { killMasterKeysFile(); } catch (IOException e) { String msg = "Unable to securely delete old master.keys file when switching to MAXIMUM seclevel!!"; System.err.println(msg); throw new NodeInitException(NodeInitException.<API key>, msg); } } long defaultCacheSize; long memoryLimit = NodeStarter.getMemoryLimitBytes(); // This is tricky because systems with low memory probably also have slow disks, but using // up too much memory can be catastrophic... // Total alchemy, FIXME! if(memoryLimit == Long.MAX_VALUE || memoryLimit < 0) defaultCacheSize = 1024*1024; else if(memoryLimit <= 128*1024*1024) defaultCacheSize = 0; // Turn off completely for very small memory. else { // 9 stores, total should be 5% of memory, up to maximum of 1MB per store at 308MB+ defaultCacheSize = Math.min(1024*1024, (memoryLimit - 128*1024*1024) / (20*9)); } nodeConfig.register("<API key>", defaultCacheSize, sortOrder++, true, false, "Node.<API key>", "Node.<API key>", new LongCallback() { @Override public Long get() { synchronized(Node.this) { return <API key>; } } @Override public void set(Long val) throws <API key>, <API key> { if(val < 0) throw new <API key>(l10n("<API key>")); synchronized(Node.this) { <API key> = val; } throw new <API key>("Caching Maximum Size cannot be changed on the fly"); } }, true); <API key> = nodeConfig.getLong("<API key>"); if(<API key> < 0) throw new NodeInitException(NodeInitException.EXIT_BAD_CONFIG, l10n("<API key>")); nodeConfig.register("<API key>", "300k", sortOrder++, true, false, "Node.<API key>", "Node.<API key>", new LongCallback() { @Override public Long get() { synchronized(Node.this) { return <API key>; } } @Override public void set(Long val) throws <API key>, <API key> { synchronized(Node.this) { <API key> = val; } throw new <API key>("Caching Period cannot be changed on the fly"); } }, true); <API key> = nodeConfig.getLong("<API key>"); if(<API key> > 0 && <API key> > 0) { <API key> = new <API key>(<API key>, <API key>, ticker); } boolean shouldWriteConfig = false; if(storeType.equals("bdb-index")) { System.err.println("Old format Berkeley DB datastore detected."); System.err.println("This datastore format is no longer supported."); System.err.println("The old datastore will be securely deleted."); storeType = "salt-hash"; shouldWriteConfig = true; <API key>(); } if (storeType.equals("salt-hash")) { initRAMFS(); initSaltHashFS(suffix, false, null); } else { initRAMFS(); } if(<API key>) <API key>(); // Client cache // Default is 10MB, in memory only. The wizard will change this. nodeConfig.register("clientCacheType", "ram", sortOrder++, true, true, "Node.clientCacheType", "Node.clientCacheTypeLong", new <API key>()); clientCacheType = nodeConfig.getString("clientCacheType"); nodeConfig.register("clientCacheSize", <API key>, sortOrder++, false, true, "Node.clientCacheSize", "Node.clientCacheSizeLong", new LongCallback() { @Override public Long get() { return <API key>; } @Override public void set(Long storeSize) throws <API key> { if(storeSize < <API key>) throw new <API key>(l10n("invalidStoreSize")); long newMaxStoreKeys = storeSize / sizePerKey; if(newMaxStoreKeys == maxClientCacheKeys) return; // Update each datastore synchronized(Node.this) { <API key> = storeSize; maxClientCacheKeys = newMaxStoreKeys; } try { chkClientcache.setMaxKeys(maxClientCacheKeys, <API key>); pubKeyClientcache.setMaxKeys(maxClientCacheKeys, <API key>); sskClientcache.setMaxKeys(maxClientCacheKeys, <API key>); } catch (IOException e) { // FIXME we need to be able to tell the user. Logger.error(this, "Caught "+e+" resizing the clientcache", e); System.err.println("Caught "+e+" resizing the clientcache"); e.printStackTrace(); } } }, true); <API key> = nodeConfig.getLong("clientCacheSize"); if(<API key> < <API key>) { throw new NodeInitException(NodeInitException.<API key>, "Client cache size too small"); } maxClientCacheKeys = <API key> / sizePerKey; boolean startedClientCache = false; if (clientCacheType.equals("salt-hash")) { if(clientCacheKey == null) { System.err.println("Cannot open client-cache, it is passworded"); <API key>(); } else { <API key>(suffix, false, clientCacheKey); startedClientCache = true; } } else if(clientCacheType.equals("none")) { initNoClientCacheFS(); startedClientCache = true; } else { // ram <API key>(); startedClientCache = true; } if(!startedClientCache) <API key>(); if(!clientCore.loadedDatabase() && databaseKey != null) { try { lateSetupDatabase(databaseKey); } catch (<API key> e2) { System.err.println("Impossible: "+e2); e2.printStackTrace(); } catch (<API key> e2) { System.err.println("Impossible: "+e2); e2.printStackTrace(); } catch (IOException e2) { System.err.println("Unable to load database: "+e2); e2.printStackTrace(); } } nodeConfig.register("useSlashdotCache", true, sortOrder++, true, false, "Node.useSlashdotCache", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { return useSlashdotCache; } @Override public void set(Boolean val) throws <API key>, <API key> { useSlashdotCache = val; } }); useSlashdotCache = nodeConfig.getBoolean("useSlashdotCache"); nodeConfig.register("<API key>", false, sortOrder++, true, false, "Node.<API key>", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { return <API key>; } @Override public void set(Boolean val) throws <API key>, <API key> { <API key> = val; } }); <API key> = nodeConfig.getBoolean("<API key>"); // LOW network *and* physical seclevel = <API key> securityLevels.<API key>(new <API key><<API key>>() { @Override public void onChange(<API key> oldLevel, <API key> newLevel) { if(newLevel == <API key>.LOW && securityLevels.<API key>() == <API key>.LOW) <API key> = true; else <API key> = false; } }); securityLevels.<API key>(new <API key><<API key>>() { @Override public void onChange(<API key> oldLevel, <API key> newLevel) { if(newLevel == <API key>.LOW && securityLevels.<API key>() == <API key>.LOW) <API key> = true; else <API key> = false; } }); nodeConfig.register("<API key>", MINUTES.toMillis(30), sortOrder++, true, false, "Node.<API key>", "Node.<API key>", new LongCallback() { @Override public Long get() { return <API key>.getLifetime(); } @Override public void set(Long val) throws <API key>, <API key> { if(val < 0) throw new <API key>("Must be positive!"); <API key>.setLifetime(val); <API key>.setLifetime(val); <API key>.setLifetime(val); } }, false); long <API key> = nodeConfig.getLong("<API key>"); nodeConfig.register("slashdotCacheSize", <API key>, sortOrder++, false, true, "Node.slashdotCacheSize", "Node.<API key>", new LongCallback() { @Override public Long get() { return <API key>; } @Override public void set(Long storeSize) throws <API key> { if(storeSize < <API key>) throw new <API key>(l10n("invalidStoreSize")); int newMaxStoreKeys = (int) Math.min(storeSize / sizePerKey, Integer.MAX_VALUE); if(newMaxStoreKeys == <API key>) return; // Update each datastore synchronized(Node.this) { <API key> = storeSize; <API key> = newMaxStoreKeys; } try { chkSlashdotcache.setMaxKeys(<API key>, <API key>); pubKeySlashdotcache.setMaxKeys(<API key>, <API key>); sskSlashdotcache.setMaxKeys(<API key>, <API key>); } catch (IOException e) { // FIXME we need to be able to tell the user. Logger.error(this, "Caught "+e+" resizing the slashdotcache", e); System.err.println("Caught "+e+" resizing the slashdotcache"); e.printStackTrace(); } } }, true); <API key> = nodeConfig.getLong("slashdotCacheSize"); if(<API key> < <API key>) { throw new NodeInitException(NodeInitException.<API key>, "Slashdot cache size too small"); } <API key> = (int) Math.min(<API key> / sizePerKey, Integer.MAX_VALUE); chkSlashdotcache = new CHKStore(); <API key> = new SlashdotStore<CHKBlock>(chkSlashdotcache, <API key>, <API key>, PURGE_INTERVAL, ticker, this.clientCore.tempBucketFactory); pubKeySlashdotcache = new PubkeyStore(); <API key> = new SlashdotStore<DSAPublicKey>(pubKeySlashdotcache, <API key>, <API key>, PURGE_INTERVAL, ticker, this.clientCore.tempBucketFactory); getPubKey.<API key>(pubKeySlashdotcache); sskSlashdotcache = new SSKStore(getPubKey); <API key> = new SlashdotStore<SSKBlock>(sskSlashdotcache, <API key>, <API key>, PURGE_INTERVAL, ticker, this.clientCore.tempBucketFactory); // MAXIMUM seclevel = no slashdot cache. securityLevels.<API key>(new <API key><<API key>>() { @Override public void onChange(<API key> oldLevel, <API key> newLevel) { if(newLevel == <API key>.MAXIMUM) useSlashdotCache = false; else if(oldLevel == <API key>.MAXIMUM) useSlashdotCache = true; } }); nodeConfig.register("skipWrapperWarning", false, sortOrder++, true, false, "Node.skipWrapperWarning", "Node.<API key>", new BooleanCallback() { @Override public void set(Boolean value) throws <API key>, <API key> { skipWrapperWarning = value; } @Override public Boolean get() { return skipWrapperWarning; } }); skipWrapperWarning = nodeConfig.getBoolean("skipWrapperWarning"); nodeConfig.register("maxPacketSize", 1280, sortOrder++, true, true, "Node.maxPacketSize", "Node.maxPacketSizeLong", new IntCallback() { @Override public Integer get() { synchronized(Node.this) { return maxPacketSize; } } @Override public void set(Integer val) throws <API key>, <API key> { synchronized(Node.this) { if(val == maxPacketSize) return; if(val < UdpSocketHandler.MIN_MTU) throw new <API key>("Must be over 576"); if(val > 1492) throw new <API key>("Larger than ethernet frame size unlikely to work!"); maxPacketSize = val; } updateMTU(); } }, true); maxPacketSize = nodeConfig.getInt("maxPacketSize"); nodeConfig.register("enableRoutedPing", false, sortOrder++, true, false, "Node.enableRoutedPing", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { synchronized(Node.this) { return enableRoutedPing; } } @Override public void set(Boolean val) throws <API key>, <API key> { synchronized(Node.this) { enableRoutedPing = val; } } }); enableRoutedPing = nodeConfig.getBoolean("enableRoutedPing"); updateMTU(); /* Take care that no configuration options are registered after this point; they will not persist * between restarts. */ nodeConfig.<API key>(); if(shouldWriteConfig) config.store(); writeNodeFile(); // Initialize the plugin manager Logger.normal(this, "Initializing Plugin Manager"); System.out.println("Initializing Plugin Manager"); pluginManager = new PluginManager(this, lastVersion); shutdownHook.addEarlyJob(new NativeThread("Shutdown plugins", NativeThread.HIGH_PRIORITY, true) { @Override public void realRun() { pluginManager.stop(SECONDS.toMillis(30)); // FIXME make it configurable?? } }); // FIXME // Short timeouts and JVM timeouts with nothing more said than the above have been seen... // I don't know why... need a stack dump... // For now just give it an extra 2 minutes. If it doesn't start in that time, // it's likely (on reports so far) that a restart will fix it. // And we have to get a build out because ALL plugins are now failing to load, // including the absolutely essential (for most nodes) JSTUN and UPnP. WrapperManager.signalStarting((int) MINUTES.toMillis(2)); FetchContext ctx = clientCore.makeClient((short)0, true, false).getFetchContext(); ctx.allowSplitfiles = false; ctx.<API key> = true; ctx.maxArchiveRestarts = 0; ctx.maxMetadataSize = 256; ctx.<API key> = 10; ctx.maxOutputLength = 4096; ctx.maxRecursionLevel = 2; ctx.maxTempLength = 4096; this.arkFetcherContext = ctx; <API key>(<API key>, fproxyN2NMListener); <API key>(Node.<API key>, diffNoderefListener); // FIXME this is a hack // toadlet server should start after all initialized // see NodeClientCore line 437 if (toadlets.isEnabled()) { toadlets.finishStart(); toadlets.createFproxy(); toadlets.<API key>(); } Logger.normal(this, "Node constructor completed"); System.out.println("Node constructor completed"); new BandwidthManager(this).start(); } private void <API key>(SubConfig nodeConfig, int <API key>) { final Node node = this; nodeConfig.register("<API key>", false, <API key>, true, true, "Node.<API key>", "Node.<API key>", new BooleanCallback() { @Override public Boolean get() { return <API key>; } @Override public void set(Boolean val) { if (val) { for (UserAlert alert : clientCore.alerts.getAlerts()) if (alert instanceof <API key>) clientCore.alerts.unregister(alert); } else <API key>.createAlert(node); <API key> = val; } }); <API key> = nodeConfig.getBoolean("<API key>"); } private boolean <API key>() { File[] files = runDir.file("peers-offers").listFiles(); if (files != null && files.length > 0) { for (File file : files) { if (file.isFile()) { String filename = file.getName(); if (filename.endsWith(".fref")) return true; } } } return false; } /** Delete files from old BDB-index datastore. */ private void <API key>() { File dbDir = storeDir.file("database-"+<API key>()); FileUtil.removeAll(dbDir); File dir = storeDir.dir(); File[] list = dir.listFiles(); for(File f : list) { String name = f.getName(); if(f.isFile() && name.toLowerCase().matches("((chk)|(ssk)|(pubkey))-[0-9]*\\.((store)|(cache))(\\.((keys)|(lru)))?")) { System.out.println("Deleting old datastore file \""+f+"\""); try { FileUtil.secureDelete(f); } catch (IOException e) { System.err.println("Failed to delete old datastore file \""+f+"\": "+e); e.printStackTrace(); } } } } private void fixCertsFiles() { // Hack to update certificates file to fix update.cmd // startssl.pem: Might be useful for old versions of update.sh too? File certs = new File(<API key>.certfileOld); fixCertsFile(certs); if(FileUtil.detectedOS.isWindows) { // updater\startssl.pem: Needed for Windows update.cmd. certs = new File("updater", <API key>.certfileOld); fixCertsFile(certs); } } private void fixCertsFile(File certs) { long oldLength = certs.exists() ? certs.length() : -1; try { File tmpFile = File.createTempFile(<API key>.certfileOld, ".tmp", new File(".")); <API key>.writeCertsTo(tmpFile); if(FileUtil.renameTo(tmpFile, certs)) { long newLength = certs.length(); if(newLength != oldLength) System.err.println("Updated "+certs+" so that update scripts will work"); } else { if(certs.length() != tmpFile.length()) { System.err.println("Cannot update "+certs+" : last-resort update scripts (in particular update.cmd on Windows) may not work"); File manual = new File(<API key>.certfileOld+".new"); manual.delete(); if(tmpFile.renameTo(manual)) System.err.println("Please delete "+certs+" and rename "+manual+" over it"); else tmpFile.delete(); } } } catch (IOException e) { } } /** ** Sets up a program directory using the config value defined by the given ** parameters. */ public ProgramDirectory setupProgramDir(SubConfig installConfig, String cfgKey, String defaultValue, String shortdesc, String longdesc, String moveErrMsg, SubConfig oldConfig) throws NodeInitException { ProgramDirectory dir = new ProgramDirectory(moveErrMsg); int sortOrder = ProgramDirectory.nextOrder(); // forceWrite=true because currently it can't be changed on the fly, also for packages installConfig.register(cfgKey, defaultValue, sortOrder, true, true, shortdesc, longdesc, dir.getStringCallback()); String dirName = installConfig.getString(cfgKey); try { dir.move(dirName); } catch (IOException e) { throw new NodeInitException(NodeInitException.EXIT_BAD_DIR, "could not set up directory: " + longdesc); } return dir; } protected ProgramDirectory setupProgramDir(SubConfig installConfig, String cfgKey, String defaultValue, String shortdesc, String longdesc, SubConfig oldConfig) throws NodeInitException { return setupProgramDir(installConfig, cfgKey, defaultValue, shortdesc, longdesc, null, oldConfig); } public void lateSetupDatabase(DatabaseKey databaseKey) throws <API key>, <API key>, IOException { if(clientCore.loadedDatabase()) return; System.out.println("Starting late database initialisation"); try { if(!clientCore.lateInitDatabase(databaseKey)) <API key>(); } catch (NodeInitException e) { <API key>(); } } private void <API key>() { System.err.println("Failed late initialisation of database, closing..."); } public void killMasterKeysFile() throws IOException { MasterKeys.killMasterKeys(masterKeysFile); } private void <API key>() { <API key>(); synchronized(this) { <API key> = true; } } /** Called when the client layer needs the decryption password. */ void <API key>() { synchronized(this) { <API key> = true; } } private final UserAlert <API key> = new UserAlert() { final long creationTime = System.currentTimeMillis(); @Override public String anchor() { return "password"; } @Override public String dismissButtonText() { return null; } @Override public long getUpdatedTime() { return creationTime; } @Override public FCPMessage getFCPMessage() { return new FeedMessage(getTitle(), getShortText(), getText(), getPriorityClass(), getUpdatedTime()); } @Override public HTMLNode getHTMLText() { HTMLNode content = new HTMLNode("div"); <API key>.<API key>(false, clientCore.getToadletContainer(), content, false, false, false, null, null); return content; } @Override public short getPriorityClass() { return UserAlert.ERROR; } @Override public String getShortText() { return NodeL10n.getBase().getString("SecurityLevels.enterPassword"); } @Override public String getText() { return NodeL10n.getBase().getString("SecurityLevels.enterPassword"); } @Override public String getTitle() { return NodeL10n.getBase().getString("SecurityLevels.enterPassword"); } @Override public boolean isEventNotification() { return false; } @Override public boolean isValid() { synchronized(Node.this) { return <API key> || <API key>; } } @Override public void isValid(boolean validity) { // Ignore } @Override public void onDismiss() { // Ignore } @Override public boolean <API key>() { return false; } @Override public boolean userCanDismiss() { return false; } }; private void <API key>() { this.clientCore.alerts.register(<API key>); } private void <API key>() { chkClientcache = new CHKStore(); new RAMFreenetStore<CHKBlock>(chkClientcache, (int) Math.min(Integer.MAX_VALUE, maxClientCacheKeys)); pubKeyClientcache = new PubkeyStore(); new RAMFreenetStore<DSAPublicKey>(pubKeyClientcache, (int) Math.min(Integer.MAX_VALUE, maxClientCacheKeys)); sskClientcache = new SSKStore(getPubKey); new RAMFreenetStore<SSKBlock>(sskClientcache, (int) Math.min(Integer.MAX_VALUE, maxClientCacheKeys)); } private void initNoClientCacheFS() { chkClientcache = new CHKStore(); new NullFreenetStore<CHKBlock>(chkClientcache); pubKeyClientcache = new PubkeyStore(); new NullFreenetStore<DSAPublicKey>(pubKeyClientcache); sskClientcache = new SSKStore(getPubKey); new NullFreenetStore<SSKBlock>(sskClientcache); } private String getStoreSuffix() { return "-" + <API key>(); } private void <API key>(final String suffix, NodeClientCore clientCore) { if(clientCore.alerts == null) throw new <API key>(); chkDatastore.getStore().setUserAlertManager(clientCore.alerts); chkDatacache.getStore().setUserAlertManager(clientCore.alerts); pubKeyDatastore.getStore().setUserAlertManager(clientCore.alerts); pubKeyDatacache.getStore().setUserAlertManager(clientCore.alerts); sskDatastore.getStore().setUserAlertManager(clientCore.alerts); sskDatacache.getStore().setUserAlertManager(clientCore.alerts); } private void initRAMFS() { chkDatastore = new CHKStore(); new RAMFreenetStore<CHKBlock>(chkDatastore, (int) Math.min(Integer.MAX_VALUE, maxStoreKeys)); chkDatacache = new CHKStore(); new RAMFreenetStore<CHKBlock>(chkDatacache, (int) Math.min(Integer.MAX_VALUE, maxCacheKeys)); pubKeyDatastore = new PubkeyStore(); new RAMFreenetStore<DSAPublicKey>(pubKeyDatastore, (int) Math.min(Integer.MAX_VALUE, maxStoreKeys)); pubKeyDatacache = new PubkeyStore(); getPubKey.setDataStore(pubKeyDatastore, pubKeyDatacache); new RAMFreenetStore<DSAPublicKey>(pubKeyDatacache, (int) Math.min(Integer.MAX_VALUE, maxCacheKeys)); sskDatastore = new SSKStore(getPubKey); new RAMFreenetStore<SSKBlock>(sskDatastore, (int) Math.min(Integer.MAX_VALUE, maxStoreKeys)); sskDatacache = new SSKStore(getPubKey); new RAMFreenetStore<SSKBlock>(sskDatacache, (int) Math.min(Integer.MAX_VALUE, maxCacheKeys)); } private long <API key>; private long <API key>; private <API key> <API key>; private void initSaltHashFS(final String suffix, boolean dontResizeOnStart, byte[] masterKey) throws NodeInitException { try { final CHKStore chkDatastore = new CHKStore(); final FreenetStore<CHKBlock> chkDataFS = makeStore("CHK", true, chkDatastore, dontResizeOnStart, masterKey); final CHKStore chkDatacache = new CHKStore(); final FreenetStore<CHKBlock> chkCacheFS = makeStore("CHK", false, chkDatacache, dontResizeOnStart, masterKey); ((<API key><CHKBlock>) chkCacheFS.getUnderlyingStore()).setAltStore(((<API key><CHKBlock>) chkDataFS.getUnderlyingStore())); final PubkeyStore pubKeyDatastore = new PubkeyStore(); final FreenetStore<DSAPublicKey> pubkeyDataFS = makeStore("PUBKEY", true, pubKeyDatastore, dontResizeOnStart, masterKey); final PubkeyStore pubKeyDatacache = new PubkeyStore(); final FreenetStore<DSAPublicKey> pubkeyCacheFS = makeStore("PUBKEY", false, pubKeyDatacache, dontResizeOnStart, masterKey); ((<API key><DSAPublicKey>) pubkeyCacheFS.getUnderlyingStore()).setAltStore(((<API key><DSAPublicKey>) pubkeyDataFS.getUnderlyingStore())); final SSKStore sskDatastore = new SSKStore(getPubKey); final FreenetStore<SSKBlock> sskDataFS = makeStore("SSK", true, sskDatastore, dontResizeOnStart, masterKey); final SSKStore sskDatacache = new SSKStore(getPubKey); final FreenetStore<SSKBlock> sskCacheFS = makeStore("SSK", false, sskDatacache, dontResizeOnStart, masterKey); ((<API key><SSKBlock>) sskCacheFS.getUnderlyingStore()).setAltStore(((<API key><SSKBlock>) sskDataFS.getUnderlyingStore())); boolean delay = chkDataFS.start(ticker, false) | chkCacheFS.start(ticker, false) | pubkeyDataFS.start(ticker, false) | pubkeyCacheFS.start(ticker, false) | sskDataFS.start(ticker, false) | sskCacheFS.start(ticker, false); if(delay) { System.err.println("Delayed init of datastore"); initRAMFS(); final Runnable migrate = new MigrateOldStoreData(false); this.getTicker().queueTimedJob(new Runnable() { @Override public void run() { System.err.println("Starting delayed init of datastore"); try { chkDataFS.start(ticker, true); chkCacheFS.start(ticker, true); pubkeyDataFS.start(ticker, true); pubkeyCacheFS.start(ticker, true); sskDataFS.start(ticker, true); sskCacheFS.start(ticker, true); } catch (IOException e) { Logger.error(this, "Failed to start datastore: "+e, e); System.err.println("Failed to start datastore: "+e); e.printStackTrace(); return; } Node.this.chkDatastore = chkDatastore; Node.this.chkDatacache = chkDatacache; Node.this.pubKeyDatastore = pubKeyDatastore; Node.this.pubKeyDatacache = pubKeyDatacache; getPubKey.setDataStore(pubKeyDatastore, pubKeyDatacache); Node.this.sskDatastore = sskDatastore; Node.this.sskDatacache = sskDatacache; <API key>(suffix, clientCore); System.err.println("Finishing delayed init of datastore"); migrate.run(); } }, "Start store", 0, true, false); // Use Ticker to guarantee that this runs *after* constructors have completed. } else { Node.this.chkDatastore = chkDatastore; Node.this.chkDatacache = chkDatacache; Node.this.pubKeyDatastore = pubKeyDatastore; Node.this.pubKeyDatacache = pubKeyDatacache; getPubKey.setDataStore(pubKeyDatastore, pubKeyDatacache); Node.this.sskDatastore = sskDatastore; Node.this.sskDatacache = sskDatacache; this.getTicker().queueTimedJob(new Runnable() { @Override public void run() { Node.this.chkDatastore = chkDatastore; Node.this.chkDatacache = chkDatacache; Node.this.pubKeyDatastore = pubKeyDatastore; Node.this.pubKeyDatacache = pubKeyDatacache; getPubKey.setDataStore(pubKeyDatastore, pubKeyDatacache); Node.this.sskDatastore = sskDatastore; Node.this.sskDatacache = sskDatacache; <API key>(suffix, clientCore); } }, "Start store", 0, true, false); } } catch (IOException e) { System.err.println("Could not open store: " + e); e.printStackTrace(); throw new NodeInitException(NodeInitException.EXIT_STORE_OTHER, e.getMessage()); } } private void <API key>(final String suffix, boolean dontResizeOnStart, byte[] <API key>) throws NodeInitException { try { final CHKStore chkClientcache = new CHKStore(); final FreenetStore<CHKBlock> chkDataFS = makeClientcache("CHK", true, chkClientcache, dontResizeOnStart, <API key>); final PubkeyStore pubKeyClientcache = new PubkeyStore(); final FreenetStore<DSAPublicKey> pubkeyDataFS = makeClientcache("PUBKEY", true, pubKeyClientcache, dontResizeOnStart, <API key>); final SSKStore sskClientcache = new SSKStore(getPubKey); final FreenetStore<SSKBlock> sskDataFS = makeClientcache("SSK", true, sskClientcache, dontResizeOnStart, <API key>); boolean delay = chkDataFS.start(ticker, false) | pubkeyDataFS.start(ticker, false) | sskDataFS.start(ticker, false); if(delay) { System.err.println("Delayed init of client-cache"); <API key>(); final Runnable migrate = new MigrateOldStoreData(true); getTicker().queueTimedJob(new Runnable() { @Override public void run() { System.err.println("Starting delayed init of client-cache"); try { chkDataFS.start(ticker, true); pubkeyDataFS.start(ticker, true); sskDataFS.start(ticker, true); } catch (IOException e) { Logger.error(this, "Failed to start client-cache: "+e, e); System.err.println("Failed to start client-cache: "+e); e.printStackTrace(); return; } Node.this.chkClientcache = chkClientcache; Node.this.pubKeyClientcache = pubKeyClientcache; getPubKey.setLocalDataStore(pubKeyClientcache); Node.this.sskClientcache = sskClientcache; System.err.println("Finishing delayed init of client-cache"); migrate.run(); } }, "Migrate store", 0, true, false); } else { Node.this.chkClientcache = chkClientcache; Node.this.pubKeyClientcache = pubKeyClientcache; getPubKey.setLocalDataStore(pubKeyClientcache); Node.this.sskClientcache = sskClientcache; } } catch (IOException e) { System.err.println("Could not open store: " + e); e.printStackTrace(); throw new NodeInitException(NodeInitException.EXIT_STORE_OTHER, e.getMessage()); } } private <T extends StorableBlock> FreenetStore<T> makeClientcache(String type, boolean isStore, StoreCallback<T> cb, boolean dontResizeOnStart, byte[] <API key>) throws IOException { FreenetStore<T> store = makeStore(type, "clientcache", maxClientCacheKeys, cb, dontResizeOnStart, <API key>); return store; } private <T extends StorableBlock> FreenetStore<T> makeStore(String type, boolean isStore, StoreCallback<T> cb, boolean dontResizeOnStart, byte[] <API key>) throws IOException { String store = isStore ? "store" : "cache"; long maxKeys = isStore ? maxStoreKeys : maxCacheKeys; return makeStore(type, store, maxKeys, cb, dontResizeOnStart, <API key>); } private <T extends StorableBlock> FreenetStore<T> makeStore(String type, String store, long maxKeys, StoreCallback<T> cb, boolean lateStart, byte[] <API key>) throws IOException { Logger.normal(this, "Initializing "+type+" Data"+store); System.out.println("Initializing "+type+" Data"+store+" (" + maxStoreKeys + " keys)"); <API key><T> fs = <API key>.<T>construct(getStoreDir(), type+"-"+store, cb, random, maxKeys, storeUseSlotFilters, shutdownHook, storePreallocate, <API key> && !lateStart, lateStart ? ticker : null, <API key>); cb.setStore(fs); if(<API key> > 0) return new CachingFreenetStore<T>(cb, fs, <API key>); else return fs; } public void start(boolean noSwaps) throws NodeInitException { // IMPORTANT: Read the peers only after we have finished initializing Node. // Peer constructors are complex and can call methods on Node. peers.tryReadPeers(nodeDir.file("peers-"+<API key>()).getPath(), darknetCrypto, null, false, false); peers.updatePMUserAlert(); dispatcher.start(nodeStats); // must be before usm dnsr.start(); peers.start(); // must be before usm nodeStats.start(); uptime.start(); failureTable.start(); darknetCrypto.start(); if(opennet != null) opennet.start(); ps.start(nodeStats); ticker.start(); <API key>(); usm.start(ticker); if(isUsingWrapper()) { Logger.normal(this, "Using wrapper correctly: "+nodeStarter); System.out.println("Using wrapper correctly: "+nodeStarter); } else { Logger.error(this, "NOT using wrapper (at least not correctly). Your freenet-ext.jar <http: System.out.println("NOT using wrapper (at least not correctly). Your freenet-ext.jar <http: } Logger.normal(this, "Freenet 0.7.5 Build #"+Version.buildNumber()+" r"+Version.cvsRevision()); System.out.println("Freenet 0.7.5 Build #"+Version.buildNumber()+" r"+Version.cvsRevision()); Logger.normal(this, "FNP port is on "+darknetCrypto.getBindTo()+ ':' +<API key>()); System.out.println("FNP port is on "+darknetCrypto.getBindTo()+ ':' +<API key>()); // Start services // SubConfig pluginManagerConfig = new SubConfig("pluginmanager3", config); // pluginManager3 = new freenet.plugin_new.PluginManager(pluginManagerConfig); ipDetector.start(); // Start sending swaps lm.start(); // Node Updater try{ Logger.normal(this, "Starting the node updater"); nodeUpdater.start(); }catch (Exception e) { e.printStackTrace(); throw new NodeInitException(NodeInitException.<API key>, "Could not start Updater: "+e); } /* TODO: Make sure that this is called BEFORE any instances of HTTPFilter are created. * HTTPFilter uses <API key>() which returns the value of the static * variable <API key> - and this is initialized in the following function. * If this is not possible then create a separate function to check for the GCJ bug and * call this function earlier. */ checkForEvilJVMBugs(); if(!NativeThread.<API key>) clientCore.alerts.register(new <API key>()); this.clientCore.start(config); tracker.startDeadUIDChecker(); // After everything has been created, write the config file back to disk. if(config instanceof <API key>) { <API key> cfg = (<API key>) config; cfg.finishedInit(this.ticker); cfg.setHasNodeStarted(); } config.store(); // Process any data in the extra peer data directory peers.readExtraPeerData(); Logger.normal(this, "Started node"); hasStarted = true; } private void <API key>() { long now = System.currentTimeMillis(); long transition = Version.transitionTime(); if(now < transition) ticker.queueTimedJob(new Runnable() { @Override public void run() { freenet.support.Logger.OSThread.logPID(this); for(PeerNode pn: peers.myPeers()) { pn.<API key>(); } } }, transition - now); } private static boolean <API key>=false; private void checkForEvilJVMBugs() { // Now check whether we are likely to get the EvilJVMBug. // If we are running a Sun/Oracle or Blackdown JVM, on Linux, and LD_ASSUME_KERNEL is not set, then we are. String jvmVendor = System.getProperty("java.vm.vendor"); String jvmSpecVendor = System.getProperty("java.specification.vendor",""); String javaVersion = System.getProperty("java.version"); String jvmName = System.getProperty("java.vm.name"); String osName = System.getProperty("os.name"); String osVersion = System.getProperty("os.version"); boolean isOpenJDK = false; //boolean isOracle = false; if(logMINOR) Logger.minor(this, "JVM vendor: "+jvmVendor+", JVM name: "+jvmName+", JVM version: "+javaVersion+", OS name: "+osName+", OS version: "+osVersion); if(jvmName.startsWith("OpenJDK ")) { isOpenJDK = true; } //Add some checks for "Oracle" to futureproof against them renaming from "Sun". //Should have no effect because if a user has downloaded a new enough file for Oracle to have changed the name these bugs shouldn't apply. //Still, one never knows and this code might be extended to cover future bugs. if((!isOpenJDK) && (jvmVendor.startsWith("Sun ") || jvmVendor.startsWith("Oracle ")) || (jvmVendor.startsWith("The FreeBSD Foundation") && (jvmSpecVendor.startsWith("Sun ") || jvmSpecVendor.startsWith("Oracle "))) || (jvmVendor.startsWith("Apple "))) { //isOracle = true; // Sun/Oracle bugs // Spurious OOMs // Fixed in 1.5.0_10 and 1.4.2_13 boolean is150 = javaVersion.startsWith("1.5.0_"); boolean is160 = javaVersion.startsWith("1.6.0_"); if(is150 || is160) { String[] split = javaVersion.split("_"); String secondPart = split[1]; if(secondPart.indexOf("-") != -1) { split = secondPart.split("-"); secondPart = split[0]; } int subver = Integer.parseInt(secondPart); Logger.minor(this, "JVM version: "+javaVersion+" subver: "+subver+" from "+secondPart); } } else if (jvmVendor.startsWith("Apple ") || jvmVendor.startsWith("\"Apple ")) { //Note that Sun/Oracle does not produce VMs for the Macintosh operating system, dont ask the user to find one... } else if(!isOpenJDK) { if(jvmVendor.startsWith("Free Software Foundation")) { // GCJ/GIJ. try { javaVersion = System.getProperty("java.version").split(" ")[0].replaceAll("[.]",""); int jvmVersionInt = Integer.parseInt(javaVersion); if(jvmVersionInt <= 422 && jvmVersionInt >= 100) // make sure that no bogus values cause true <API key>=true; } catch(Throwable t) { Logger.error(this, "GCJ version check is broken!", t); } clientCore.alerts.register(new SimpleUserAlert(true, l10n("usingGCJTitle"), l10n("usingGCJ"), l10n("usingGCJTitle"), UserAlert.WARNING)); } } if(!isUsingWrapper() && !skipWrapperWarning) { clientCore.alerts.register(new SimpleUserAlert(true, l10n("<API key>"), l10n("notUsingWrapper"), l10n("<API key>"), UserAlert.WARNING)); } // Unfortunately debian's version of OpenJDK appears to have segfaulting issues. // Which presumably are exploitable. // So we can't recommend people switch just yet. :( // if(isOracle && Rijndael.AesCtrProvider == null) { // if(!(FileUtil.detectedOS == FileUtil.OperatingSystem.Windows || FileUtil.detectedOS == FileUtil.OperatingSystem.MacOS)) // clientCore.alerts.register(new SimpleUserAlert(true, l10n("usingOracleTitle"), l10n("usingOracle"), l10n("usingOracleTitle"), UserAlert.WARNING)); } public static boolean <API key>() { return <API key>; // should be initialized on early startup } private String l10n(String key) { return NodeL10n.getBase().getString("Node."+key); } private String l10n(String key, String pattern, String value) { return NodeL10n.getBase().getString("Node."+key, pattern, value); } private String l10n(String key, String[] pattern, String[] value) { return NodeL10n.getBase().getString("Node."+key, pattern, value); } /** * Export volatile data about the node as a SimpleFieldSet */ public SimpleFieldSet <API key>() { return nodeStats.<API key>(); } /** * Do a routed ping of another node on the network by its location. * @param loc2 The location of the other node to ping. It must match * exactly. * @param pubKeyHash The hash of the pubkey of the target node. We match * by location; this is just a shortcut if we get close. * @return The number of hops it took to find the node, if it was found. * Otherwise -1. */ public int routedPing(double loc2, byte[] pubKeyHash) { long uid = random.nextLong(); int initialX = random.nextInt(); Message m = DMT.createFNPRoutedPing(uid, loc2, maxHTL, initialX, pubKeyHash); Logger.normal(this, "Message: "+m); dispatcher.handleRouted(m, null); // FIXME: might be rejected MessageFilter mf1 = MessageFilter.create().setField(DMT.UID, uid).setType(DMT.FNPRoutedPong).setTimeout(5000); try { //MessageFilter mf2 = MessageFilter.create().setField(DMT.UID, uid).setType(DMT.FNPRoutedRejected).setTimeout(5000); // Ignore Rejected - let it be retried on other peers m = usm.waitFor(mf1/*.or(mf2)*/, null); } catch (<API key> e) { Logger.normal(this, "Disconnected in waiting for pong"); return -1; } if(m == null) return -1; if(m.getSpec() == DMT.FNPRoutedRejected) return -1; return m.getInt(DMT.COUNTER) - initialX; } /** * Look for a block in the datastore, as part of a request. * @param key The key to fetch. * @param uid The UID of the request (for logging only). * @param promoteCache Whether to promote the key if found. * @param canReadClientCache If the request is local, we can read the client cache. * @param canWriteClientCache If the request is local, and the client hasn't turned off * writing to the client cache, we can write to the client cache. * @param canWriteDatastore If the request HTL is too high, including if it is local, we * cannot write to the datastore. * @return A KeyBlock for the key requested or null. */ private KeyBlock makeRequestLocal(Key key, long uid, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore, boolean offersOnly) { KeyBlock kb = null; if (key instanceof NodeCHK) { kb = fetch(key, false, canReadClientCache, canWriteClientCache, canWriteDatastore, null); } else if (key instanceof NodeSSK) { NodeSSK sskKey = (NodeSSK) key; DSAPublicKey pubKey = sskKey.getPubKey(); if (pubKey == null) { pubKey = getPubKey.getKey(sskKey.getPubKeyHash(), canReadClientCache, offersOnly, null); if (logMINOR) Logger.minor(this, "Fetched pubkey: " + pubKey); try { sskKey.setPubKey(pubKey); } catch (SSKVerifyException e) { Logger.error(this, "Error setting pubkey: " + e, e); } } if (pubKey != null) { if (logMINOR) Logger.minor(this, "Got pubkey: " + pubKey); kb = fetch(sskKey, canReadClientCache, canWriteClientCache, canWriteDatastore, false, null); } else { if (logMINOR) Logger.minor(this, "Not found because no pubkey: " + uid); } } else throw new <API key>("Unknown key type: " + key.getClass()); if (kb != null) { // Probably somebody waiting for it. Trip it. if (clientCore != null && clientCore.requestStarters != null) { if (kb instanceof CHKBlock) { clientCore.requestStarters.<API key>.tripPendingKey(kb); clientCore.requestStarters.chkFetchSchedulerRT.tripPendingKey(kb); } else { clientCore.requestStarters.<API key>.tripPendingKey(kb); clientCore.requestStarters.sskFetchSchedulerRT.tripPendingKey(kb); } } failureTable.onFound(kb); return kb; } return null; } /** * Check the datastore, then if the key is not in the store, * check whether another node is requesting the same key at * the same HTL, and if all else fails, create a new * RequestSender for the key/htl. * @param closestLocation The closest location to the key so far. * @param localOnly If true, only check the datastore. * @return A KeyBlock if the data is in the store, otherwise * a RequestSender, unless the HTL is 0, in which case NULL. * RequestSender. */ public Object makeRequestSender(Key key, short htl, long uid, RequestTag tag, PeerNode source, boolean localOnly, boolean ignoreStore, boolean offersOnly, boolean canReadClientCache, boolean canWriteClientCache, boolean realTimeFlag) { boolean canWriteDatastore = <API key>(htl); if(logMINOR) Logger.minor(this, "makeRequestSender("+key+ ',' +htl+ ',' +uid+ ',' +source+") on "+<API key>()); // In store? if(!ignoreStore) { KeyBlock kb = makeRequestLocal(key, uid, canReadClientCache, canWriteClientCache, canWriteDatastore, offersOnly); if (kb != null) return kb; } if(localOnly) return null; if(logMINOR) Logger.minor(this, "Not in store locally"); // Transfer coalescing - match key only as HTL irrelevant RequestSender sender = key instanceof NodeCHK ? tracker.<API key>((NodeCHK)key, realTimeFlag) : null; if(sender != null) { if(logMINOR) Logger.minor(this, "Data already being transferred: "+sender); sender.<API key>(); tag.setSender(sender, true); return sender; } // HTL == 0 => Don't search further if(htl == 0) { if(logMINOR) Logger.minor(this, "No HTL"); return null; } sender = new RequestSender(key, null, htl, uid, tag, this, source, offersOnly, canWriteClientCache, canWriteDatastore, realTimeFlag); tag.setSender(sender, false); sender.start(); if(logMINOR) Logger.minor(this, "Created new sender: "+sender); return sender; } /** Can we write to the datastore for a given request? * We do not write to the datastore until 2 hops below maximum. This is an average of 4 * hops from the originator. Thus, data returned from local requests is never cached, * finally solving The Register's attack, Bloom filter sharing doesn't give away your local * requests and inserts, and *anything starting at high HTL* is not cached, including stuff * from other nodes which hasn't been decremented far enough yet, so it's not ONLY local * requests that don't get cached. */ boolean <API key>(short htl) { return htl <= (maxHTL - 2); } /** Can we write to the datastore for a given insert? * We do not write to the datastore until 3 hops below maximum. This is an average of 5 * hops from the originator. Thus, data sent by local inserts is never cached, * finally solving The Register's attack, Bloom filter sharing doesn't give away your local * requests and inserts, and *anything starting at high HTL* is not cached, including stuff * from other nodes which hasn't been decremented far enough yet, so it's not ONLY local * inserts that don't get cached. */ boolean <API key>(short htl) { return htl <= (maxHTL - 3); } /** * Fetch a block from the datastore. * @param key * @param canReadClientCache * @param canWriteClientCache * @param canWriteDatastore * @param forULPR * @param <API key> If true, the key must have the * ENTRY_NEW_BLOCK flag (if saltedhash), indicating that it a) has been added * since the caching changes in 1224 (since we didn't delete the stores), and b) * that it wasn't added due to low network security caching everything, unless we * are currently in low network security mode. Only applies to main store. */ public KeyBlock fetch(Key key, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR, BlockMetadata meta) { if(key instanceof NodeSSK) return fetch((NodeSSK)key, false, canReadClientCache, canWriteClientCache, canWriteDatastore, forULPR, meta); else if(key instanceof NodeCHK) return fetch((NodeCHK)key, false, canReadClientCache, canWriteClientCache, canWriteDatastore, forULPR, meta); else throw new <API key>(); } public SSKBlock fetch(NodeSSK key, boolean dontPromote, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR, BlockMetadata meta) { double loc=key.toNormalizedDouble(); double dist=Location.distance(lm.getLocation(), loc); if(canReadClientCache) { try { SSKBlock block = sskClientcache.fetch(key, dontPromote || !canWriteClientCache, canReadClientCache, forULPR, false, meta); if(block != null) { nodeStats.<API key>.report(loc); if (dist > nodeStats.<API key>) nodeStats.<API key>=dist; if(logDEBUG) Logger.debug(this, "Found key "+key+" in client-cache"); return block; } } catch (IOException e) { Logger.error(this, "Could not read from client cache: "+e, e); } } if(forULPR || useSlashdotCache || canReadClientCache) { try { SSKBlock block = sskSlashdotcache.fetch(key, dontPromote, canReadClientCache, forULPR, false, meta); if(block != null) { nodeStats.<API key>.report(loc); if (dist > nodeStats.<API key>) nodeStats.<API key>=dist; if(logDEBUG) Logger.debug(this, "Found key "+key+" in slashdot-cache"); return block; } } catch (IOException e) { Logger.error(this, "Could not read from slashdot/ULPR cache: "+e, e); } } boolean ignoreOldBlocks = !<API key>; if(canReadClientCache) ignoreOldBlocks = false; if(logMINOR) dumpStoreHits(); try { nodeStats.avgRequestLocation.report(loc); SSKBlock block = sskDatastore.fetch(key, dontPromote || !canWriteDatastore, canReadClientCache, forULPR, ignoreOldBlocks, meta); if(block == null) { SSKStore store = oldSSK; if(store != null) block = store.fetch(key, dontPromote || !canWriteDatastore, canReadClientCache, forULPR, ignoreOldBlocks, meta); } if(block != null) { nodeStats.avgStoreSSKSuccess.report(loc); if (dist > nodeStats.<API key>) nodeStats.<API key>=dist; if(logDEBUG) Logger.debug(this, "Found key "+key+" in store"); return block; } block=sskDatacache.fetch(key, dontPromote || !canWriteDatastore, canReadClientCache, forULPR, ignoreOldBlocks, meta); if(block == null) { SSKStore store = oldSSKCache; if(store != null) block = store.fetch(key, dontPromote || !canWriteDatastore, canReadClientCache, forULPR, ignoreOldBlocks, meta); } if (block != null) { nodeStats.avgCacheSSKSuccess.report(loc); if (dist > nodeStats.<API key>) nodeStats.<API key>=dist; if(logDEBUG) Logger.debug(this, "Found key "+key+" in cache"); } return block; } catch (IOException e) { Logger.error(this, "Cannot fetch data: "+e, e); return null; } } public CHKBlock fetch(NodeCHK key, boolean dontPromote, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR, BlockMetadata meta) { double loc=key.toNormalizedDouble(); double dist=Location.distance(lm.getLocation(), loc); if(canReadClientCache) { try { CHKBlock block = chkClientcache.fetch(key, dontPromote || !canWriteClientCache, false, meta); if(block != null) { nodeStats.<API key>.report(loc); if (dist > nodeStats.<API key>) nodeStats.<API key>=dist; return block; } } catch (IOException e) { Logger.error(this, "Could not read from client cache: "+e, e); } } if(forULPR || useSlashdotCache || canReadClientCache) { try { CHKBlock block = chkSlashdotcache.fetch(key, dontPromote, false, meta); if(block != null) { nodeStats.<API key>.report(loc); if (dist > nodeStats.<API key>) nodeStats.<API key>=dist; return block; } } catch (IOException e) { Logger.error(this, "Could not read from slashdot/ULPR cache: "+e, e); } } boolean ignoreOldBlocks = !<API key>; if(canReadClientCache) ignoreOldBlocks = false; if(logMINOR) dumpStoreHits(); try { nodeStats.avgRequestLocation.report(loc); CHKBlock block = chkDatastore.fetch(key, dontPromote || !canWriteDatastore, ignoreOldBlocks, meta); if(block == null) { CHKStore store = oldCHK; if(store != null) block = store.fetch(key, dontPromote || !canWriteDatastore, ignoreOldBlocks, meta); } if (block != null) { nodeStats.avgStoreCHKSuccess.report(loc); if (dist > nodeStats.<API key>) nodeStats.<API key>=dist; return block; } block=chkDatacache.fetch(key, dontPromote || !canWriteDatastore, ignoreOldBlocks, meta); if(block == null) { CHKStore store = oldCHKCache; if(store != null) block = store.fetch(key, dontPromote || !canWriteDatastore, ignoreOldBlocks, meta); } if (block != null) { nodeStats.avgCacheCHKSuccess.report(loc); if (dist > nodeStats.<API key>) nodeStats.<API key>=dist; } return block; } catch (IOException e) { Logger.error(this, "Cannot fetch data: "+e, e); return null; } } CHKStore getChkDatacache() { return chkDatacache; } CHKStore getChkDatastore() { return chkDatastore; } SSKStore getSskDatacache() { return sskDatacache; } SSKStore getSskDatastore() { return sskDatastore; } CHKStore getChkSlashdotCache() { return chkSlashdotcache; } CHKStore getChkClientCache() { return chkClientcache; } SSKStore getSskSlashdotCache() { return sskSlashdotcache; } SSKStore getSskClientCache() { return sskClientcache; } /** * This method returns all statistics info for our data store stats table * * @return map that has an entry for each data store instance type and corresponding stats */ public Map<<API key>, DataStoreStats> getDataStoreStats() { Map<<API key>, DataStoreStats> map = new LinkedHashMap<<API key>, DataStoreStats>(); map.put(new <API key>(CHK, STORE), new StoreCallbackStats(chkDatastore, nodeStats.chkStoreStats())); map.put(new <API key>(CHK, CACHE), new StoreCallbackStats(chkDatacache, nodeStats.chkCacheStats())); map.put(new <API key>(CHK, SLASHDOT), new StoreCallbackStats(chkSlashdotcache,nodeStats.<API key>())); map.put(new <API key>(CHK, CLIENT), new StoreCallbackStats(chkClientcache, nodeStats.chkClientCacheStats())); map.put(new <API key>(SSK, STORE), new StoreCallbackStats(sskDatastore, nodeStats.sskStoreStats())); map.put(new <API key>(SSK, CACHE), new StoreCallbackStats(sskDatacache, nodeStats.sskCacheStats())); map.put(new <API key>(SSK, SLASHDOT), new StoreCallbackStats(sskSlashdotcache, nodeStats.<API key>())); map.put(new <API key>(SSK, CLIENT), new StoreCallbackStats(sskClientcache, nodeStats.sskClientCacheStats())); map.put(new <API key>(PUB_KEY, STORE), new StoreCallbackStats(pubKeyDatastore, new <API key>())); map.put(new <API key>(PUB_KEY, CACHE), new StoreCallbackStats(pubKeyDatacache, new <API key>())); map.put(new <API key>(PUB_KEY, SLASHDOT), new StoreCallbackStats(pubKeySlashdotcache, new <API key>())); map.put(new <API key>(PUB_KEY, CLIENT), new StoreCallbackStats(pubKeyClientcache, new <API key>())); return map; } public long getMaxTotalKeys() { return maxTotalKeys; } long timeLastDumpedHits; public void dumpStoreHits() { long now = System.currentTimeMillis(); if(now - timeLastDumpedHits > 5000) { timeLastDumpedHits = now; } else return; Logger.minor(this, "Distribution of hits and misses over stores:\n"+ "CHK Datastore: "+chkDatastore.hits()+ '/' +(chkDatastore.hits()+chkDatastore.misses())+ '/' +chkDatastore.keyCount()+ "\nCHK Datacache: "+chkDatacache.hits()+ '/' +(chkDatacache.hits()+chkDatacache.misses())+ '/' +chkDatacache.keyCount()+ "\nSSK Datastore: "+sskDatastore.hits()+ '/' +(sskDatastore.hits()+sskDatastore.misses())+ '/' +sskDatastore.keyCount()+ "\nSSK Datacache: "+sskDatacache.hits()+ '/' +(sskDatacache.hits()+sskDatacache.misses())+ '/' +sskDatacache.keyCount()); } public void storeShallow(CHKBlock block, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR) { store(block, false, canWriteClientCache, canWriteDatastore, forULPR); } /** * Store a datum. * @param block * a KeyBlock * @param deep If true, insert to the store as well as the cache. Do not set * this to true unless the store results from an insert, and this node is the * closest node to the target; see the description of chkDatastore. */ public void store(KeyBlock block, boolean deep, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR) throws <API key> { if(block instanceof CHKBlock) store((CHKBlock)block, deep, canWriteClientCache, canWriteDatastore, forULPR); else if(block instanceof SSKBlock) store((SSKBlock)block, deep, false, canWriteClientCache, canWriteDatastore, forULPR); else throw new <API key>("Unknown keytype "); } private void store(CHKBlock block, boolean deep, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR) { try { double loc = block.getKey().toNormalizedDouble(); if (canWriteClientCache) { chkClientcache.put(block, false); nodeStats.<API key>.report(loc); } if ((forULPR || useSlashdotCache) && !(canWriteDatastore || <API key>)) { chkSlashdotcache.put(block, false); nodeStats.<API key>.report(loc); } if (canWriteDatastore || <API key>) { if (deep) { chkDatastore.put(block, !canWriteDatastore); nodeStats.avgStoreCHKLocation.report(loc); } chkDatacache.put(block, !canWriteDatastore); nodeStats.avgCacheCHKLocation.report(loc); } if (canWriteDatastore || forULPR || useSlashdotCache) failureTable.onFound(block); } catch (IOException e) { Logger.error(this, "Cannot store data: "+e, e); } catch (Throwable t) { System.err.println(t); t.printStackTrace(); Logger.error(this, "Caught "+t+" storing data", t); } if(clientCore != null && clientCore.requestStarters != null) { clientCore.requestStarters.<API key>.tripPendingKey(block); clientCore.requestStarters.chkFetchSchedulerRT.tripPendingKey(block); } } /** Store the block if this is a sink. Call for inserts. */ public void storeInsert(SSKBlock block, boolean deep, boolean overwrite, boolean canWriteClientCache, boolean canWriteDatastore) throws <API key> { store(block, deep, overwrite, canWriteClientCache, canWriteDatastore, false); } /** Store only to the cache, and not the store. Called by requests, * as only inserts cause data to be added to the store. */ public void storeShallow(SSKBlock block, boolean canWriteClientCache, boolean canWriteDatastore, boolean fromULPR) throws <API key> { store(block, false, canWriteClientCache, canWriteDatastore, fromULPR); } public void store(SSKBlock block, boolean deep, boolean overwrite, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR) throws <API key> { try { // Store the pubkey before storing the data, otherwise we can get a race condition and // end up deleting the SSK data. double loc = block.getKey().toNormalizedDouble(); getPubKey.cacheKey((block.getKey()).getPubKeyHash(), (block.getKey()).getPubKey(), deep, canWriteClientCache, canWriteDatastore, forULPR || useSlashdotCache, <API key>); if(canWriteClientCache) { sskClientcache.put(block, overwrite, false); nodeStats.<API key>.report(loc); } if((forULPR || useSlashdotCache) && !(canWriteDatastore || <API key>)) { sskSlashdotcache.put(block, overwrite, false); nodeStats.<API key>.report(loc); } if(canWriteDatastore || <API key>) { if(deep) { sskDatastore.put(block, overwrite, !canWriteDatastore); nodeStats.avgStoreSSKLocation.report(loc); } sskDatacache.put(block, overwrite, !canWriteDatastore); nodeStats.avgCacheSSKLocation.report(loc); } if(canWriteDatastore || forULPR || useSlashdotCache) failureTable.onFound(block); } catch (IOException e) { Logger.error(this, "Cannot store data: "+e, e); } catch (<API key> e) { throw e; } catch (Throwable t) { System.err.println(t); t.printStackTrace(); Logger.error(this, "Caught "+t+" storing data", t); } if(clientCore != null && clientCore.requestStarters != null) { clientCore.requestStarters.<API key>.tripPendingKey(block); clientCore.requestStarters.sskFetchSchedulerRT.tripPendingKey(block); } } final boolean decrementAtMax; final boolean decrementAtMin; /** * Decrement the HTL according to the policy of the given * NodePeer if it is non-null, or do something else if it is * null. */ public short decrementHTL(PeerNode source, short htl) { if(source != null) return source.decrementHTL(htl); // Otherwise... if(htl >= maxHTL) htl = maxHTL; if(htl <= 0) { return 0; } if(htl == maxHTL) { if(decrementAtMax || <API key>) htl return htl; } if(htl == 1) { if(decrementAtMin || <API key>) htl return htl; } return --htl; } /** * Fetch or create an CHKInsertSender for a given key/htl. * @param key The key to be inserted. * @param htl The current HTL. We can't coalesce inserts across * HTL's. * @param uid The UID of the caller's request chain, or a new * one. This is obviously not used if there is already an * CHKInsertSender running. * @param source The node that sent the InsertRequest, or null * if it originated locally. * @param ignoreLowBackoff * @param preferInsert */ public CHKInsertSender makeInsertSender(NodeCHK key, short htl, long uid, InsertTag tag, PeerNode source, byte[] headers, <API key> prb, boolean fromStore, boolean canWriteClientCache, boolean forkOnCacheable, boolean preferInsert, boolean ignoreLowBackoff, boolean realTimeFlag) { if(logMINOR) Logger.minor(this, "makeInsertSender("+key+ ',' +htl+ ',' +uid+ ',' +source+",...,"+fromStore); CHKInsertSender is = null; is = new CHKInsertSender(key, uid, tag, headers, htl, source, this, prb, fromStore, canWriteClientCache, forkOnCacheable, preferInsert, ignoreLowBackoff,realTimeFlag); is.start(); // CHKInsertSender adds itself to insertSenders return is; } /** * Fetch or create an SSKInsertSender for a given key/htl. * @param key The key to be inserted. * @param htl The current HTL. We can't coalesce inserts across * HTL's. * @param uid The UID of the caller's request chain, or a new * one. This is obviously not used if there is already an * SSKInsertSender running. * @param source The node that sent the InsertRequest, or null * if it originated locally. * @param ignoreLowBackoff * @param preferInsert */ public SSKInsertSender makeInsertSender(SSKBlock block, short htl, long uid, InsertTag tag, PeerNode source, boolean fromStore, boolean canWriteClientCache, boolean canWriteDatastore, boolean forkOnCacheable, boolean preferInsert, boolean ignoreLowBackoff, boolean realTimeFlag) { NodeSSK key = block.getKey(); if(key.getPubKey() == null) { throw new <API key>("No pub key when inserting"); } getPubKey.cacheKey(key.getPubKeyHash(), key.getPubKey(), false, canWriteClientCache, canWriteDatastore, false, <API key>); Logger.minor(this, "makeInsertSender("+key+ ',' +htl+ ',' +uid+ ',' +source+",...,"+fromStore); SSKInsertSender is = null; is = new SSKInsertSender(block, uid, tag, htl, source, this, fromStore, canWriteClientCache, forkOnCacheable, preferInsert, ignoreLowBackoff, realTimeFlag); is.start(); return is; } /** * @return Some status information. */ public String getStatus() { StringBuilder sb = new StringBuilder(); if (peers != null) sb.append(peers.getStatus()); else sb.append("No peers yet"); sb.append(tracker.<API key>()); sb.append('\n'); return sb.toString(); } /** * @return TMCI peer list */ public String getTMCIPeerList() { StringBuilder sb = new StringBuilder(); if (peers != null) sb.append(peers.getTMCIPeerList()); else sb.append("No peers yet"); return sb.toString(); } /** Length of signature parameters R and S */ static final int <API key> = 32; public ClientKeyBlock fetchKey(ClientKey key, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore) throws KeyVerifyException { if(key instanceof ClientCHK) return fetch((ClientCHK)key, canReadClientCache, canWriteClientCache, canWriteDatastore); else if(key instanceof ClientSSK) return fetch((ClientSSK)key, canReadClientCache, canWriteClientCache, canWriteDatastore); else throw new <API key>("Don't know what to do with "+key); } public ClientKeyBlock fetch(ClientSSK clientSSK, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore) throws SSKVerifyException { DSAPublicKey key = clientSSK.getPubKey(); if(key == null) { key = getPubKey.getKey(clientSSK.pubKeyHash, canReadClientCache, false, null); } if(key == null) return null; clientSSK.setPublicKey(key); SSKBlock block = fetch((NodeSSK)clientSSK.getNodeKey(true), false, canReadClientCache, canWriteClientCache, canWriteDatastore, false, null); if(block == null) { if(logMINOR) Logger.minor(this, "Could not find key for "+clientSSK); return null; } // Move the pubkey to the top of the LRU, and fix it if it // was corrupt. getPubKey.cacheKey(clientSSK.pubKeyHash, key, false, canWriteClientCache, canWriteDatastore, false, <API key>); return ClientSSKBlock.construct(block, clientSSK); } private ClientKeyBlock fetch(ClientCHK clientCHK, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore) throws CHKVerifyException { CHKBlock block = fetch(clientCHK.getNodeCHK(), false, canReadClientCache, canWriteClientCache, canWriteDatastore, false, null); if(block == null) return null; return new ClientCHKBlock(block, clientCHK); } public void exit(int reason) { try { this.park(); System.out.println("Goodbye."); System.out.println(reason); } finally { System.exit(reason); } } public void exit(String reason){ try { this.park(); System.out.println("Goodbye. from "+this+" ("+reason+ ')'); } finally { System.exit(0); } } /** * Returns true if the node is shutting down. * The packet receiver calls this for every packet, and boolean is atomic, so this method is not synchronized. */ public boolean isStopping() { return isStopping; } /** * Get the node into a state where it can be stopped safely * May be called twice - once in exit (above) and then again * from the wrapper triggered by calling System.exit(). Beware! */ public void park() { synchronized(this) { if(isStopping) return; isStopping = true; } try { Message msg = DMT.createFNPDisconnect(false, false, -1, new ShortBuffer(new byte[0])); peers.localBroadcast(msg, true, false, peers.ctrDisconn); } catch (Throwable t) { try { // E.g. if we haven't finished startup Logger.error(this, "Failed to tell peers we are going down: "+t, t); } catch (Throwable t1) { // Ignore. We don't want to mess up the exit process! } } config.store(); if(random instanceof <API key>) { ((<API key>) random).write_seed(true); } } public NodeUpdateManager getNodeUpdater(){ return nodeUpdater; } public DarknetPeerNode[] <API key>() { return peers.getDarknetPeers(); } public boolean addPeerConnection(PeerNode pn) { boolean retval = peers.addPeer(pn); peers.writePeersUrgent(pn.isOpennet()); return retval; } public void <API key>(PeerNode pn) { peers.disconnectAndRemove(pn, true, false, false); } public void onConnectedPeer() { if(logMINOR) Logger.minor(this, "onConnectedPeer()"); ipDetector.onConnectedPeer(); } public int getFNPPort(){ return this.<API key>(); } public boolean isOudated() { return peers.isOutdated(); } private Map<Integer, <API key>> n2nmListeners = new HashMap<Integer, <API key>>(); public synchronized void <API key>(int type, <API key> listener) { n2nmListeners.put(type, listener); } /** * Handle a received node to node message */ public void <API key>(Message m, PeerNode src) { int type = ((Integer) m.getObject(DMT.<API key>)).intValue(); ShortBuffer messageData = (ShortBuffer) m.getObject(DMT.<API key>); <API key>(src, type, messageData, false); } public void <API key>(PeerNode src, int type, ShortBuffer messageData, boolean partingMessage) { boolean fromDarknet = src instanceof DarknetPeerNode; <API key> listener = null; synchronized(this) { listener = n2nmListeners.get(type); } if(listener == null) { Logger.error(this, "Unknown n2nm ID: "+type+" - discarding packet length "+messageData.getLength()); return; } listener.handleMessage(messageData.getData(), fromDarknet, src, type); } private <API key> diffNoderefListener = new <API key>() { @Override public void handleMessage(byte[] data, boolean fromDarknet, PeerNode src, int type) { Logger.normal(this, "Received differential node reference node to node message from "+src.getPeer()); SimpleFieldSet fs = null; try { fs = new SimpleFieldSet(new String(data, "UTF-8"), false, true, false); } catch (IOException e) { Logger.error(this, "IOException while parsing node to node message data", e); return; } if(fs.get("n2nType") != null) { fs.removeValue("n2nType"); } try { src.processDiffNoderef(fs); } catch (FSParseException e) { Logger.error(this, "FSParseException while parsing node to node message data", e); return; } } }; private <API key> fproxyN2NMListener = new <API key>() { @Override public void handleMessage(byte[] data, boolean fromDarknet, PeerNode src, int type) { if(!fromDarknet) { Logger.error(this, "Got N2NTM from non-darknet node ?!?!?!: from "+src); return; } DarknetPeerNode darkSource = (DarknetPeerNode) src; Logger.normal(this, "Received N2NTM from '"+darkSource.getPeer()+"'"); SimpleFieldSet fs = null; try { fs = new SimpleFieldSet(new String(data, "UTF-8"), false, true, false); } catch (<API key> e) { throw new Error("Impossible: JVM doesn't support UTF-8: " + e, e); } catch (IOException e) { Logger.error(this, "IOException while parsing node to node message data", e); return; } fs.putOverwrite("n2nType", Integer.toString(type)); fs.putOverwrite("receivedTime", Long.toString(System.currentTimeMillis())); fs.putOverwrite("receivedAs", "nodeToNodeMessage"); int fileNumber = darkSource.<API key>( fs, <API key>); if( fileNumber == -1 ) { Logger.error( this, "Failed to write N2NTM to extra peer data file for peer "+darkSource.getPeer()); } // Keep track of the fileNumber so we can potentially delete the extra peer data file later, the file is authoritative try { <API key>(fs, darkSource, fileNumber); } catch (FSParseException e) { // Shouldn't happen throw new Error(e); } } }; /** * Handle a node to node text message SimpleFieldSet * @throws FSParseException */ public void <API key>(SimpleFieldSet fs, DarknetPeerNode source, int fileNumber) throws FSParseException { if(logMINOR) Logger.minor(this, "Got node to node message: \n"+fs); int overallType = fs.getInt("n2nType"); fs.removeValue("n2nType"); if(overallType == Node.<API key>) { <API key>(fs, source, fileNumber); } else { Logger.error(this, "Received unknown node to node message type '"+overallType+"' from "+source.getPeer()); } } private void <API key>(SimpleFieldSet fs, DarknetPeerNode source, int fileNumber) throws FSParseException { int type = fs.getInt("type"); if(type == Node.<API key>) { source.handleFproxyN2NTM(fs, fileNumber); } else if(type == Node.<API key>) { source.<API key>(fs, fileNumber); } else if(type == Node.<API key>) { source.<API key>(fs, fileNumber); } else if(type == Node.<API key>) { source.<API key>(fs, fileNumber); } else if(type == Node.<API key>) { source.<API key>(fs, fileNumber); } else if(type == Node.<API key>) { source.<API key>(fs, fileNumber); } else { Logger.error(this, "Received unknown fproxy node to node message sub-type '"+type+"' from "+source.getPeer()); } } public String getMyName() { return myName; } public MessageCore getUSM() { return usm; } public LocationManager getLocationManager() { return lm; } public int getSwaps() { return LocationManager.swaps; } public int getNoSwaps() { return LocationManager.noSwaps; } public int getStartedSwaps() { return LocationManager.startedSwaps; } public int <API key>() { return LocationManager.<API key>; } public int <API key>() { return LocationManager.<API key>; } public int <API key>() { return LocationManager.<API key>; } public int <API key>() { return LocationManager.<API key>; } public PeerNode[] getPeerNodes() { return peers.myPeers(); } public PeerNode[] getConnectedPeers() { return peers.connectedPeers(); } /** * Return a peer of the node given its ip and port, name or identity, as a String */ public PeerNode getPeerNode(String nodeIdentifier) { for(PeerNode pn: peers.myPeers()) { Peer peer = pn.getPeer(); String nodeIpAndPort = ""; if(peer != null) { nodeIpAndPort = peer.toString(); } String identity = pn.getIdentityString(); if(pn instanceof DarknetPeerNode) { DarknetPeerNode dpn = (DarknetPeerNode) pn; String name = dpn.myName; if(identity.equals(nodeIdentifier) || nodeIpAndPort.equals(nodeIdentifier) || name.equals(nodeIdentifier)) { return pn; } } else { if(identity.equals(nodeIdentifier) || nodeIpAndPort.equals(nodeIdentifier)) { return pn; } } } return null; } public boolean isHasStarted() { return hasStarted; } public void queueRandomReinsert(KeyBlock block) { clientCore.queueRandomReinsert(block); } public String getExtraPeerDataDir() { return extraPeerDataDir.getPath(); } public boolean noConnectedPeers() { return !peers.anyConnectedPeers(); } public double getLocation() { return lm.getLocation(); } public double <API key>() { return lm.getLocChangeSession(); } public int <API key>() { return lm.getAverageSwapTime(); } public long getSendSwapInterval() { return lm.getSendSwapInterval(); } public int <API key>() { return lm.<API key>; } public boolean <API key>() { if(clientCore == null) return false; return clientCore.<API key>(); } public boolean <API key>() { return clientCore.<API key>(); } // FIXME convert these kind of threads to Checkpointed's and implement a handler // using the PacketSender/Ticker. Would save a few threads. public int getNumARKFetchers() { int x = 0; for(PeerNode p: peers.myPeers()) { if(p.isFetchingARK()) x++; } return x; } // FIXME put this somewhere else private volatile Object statsSync = new Object(); /** The total number of bytes of real data i.e.&nbsp;payload sent by the node */ private long totalPayloadSent; public void sentPayload(int len) { synchronized(statsSync) { totalPayloadSent += len; } } /** * Get the total number of bytes of payload (real data) sent by the node * * @return Total payload sent in bytes */ public long getTotalPayloadSent() { synchronized(statsSync) { return totalPayloadSent; } } public void setName(String key) throws <API key>, <API key> { config.get("node").getOption("name").setValue(key); } public Ticker getTicker() { return ticker; } public int <API key>() { return usm.<API key>(); } /** * Connect this node to another node (for purposes of testing) */ public void connectToSeednode(<API key> node) throws <API key>, FSParseException, PeerParseException, <API key> { peers.addPeer(node,false,false); } public void connect(Node node, FRIEND_TRUST trust, FRIEND_VISIBILITY visibility) throws FSParseException, PeerParseException, <API key>, PeerTooOldException { peers.connect(node.darknetCrypto.<API key>(), darknetCrypto.packetMangler, trust, visibility); } public short maxHTL() { return maxHTL; } public int <API key>() { return darknetCrypto.portNumber; } public synchronized int <API key>() { return <API key>; } public synchronized int <API key>() { if(inputLimitDefault) return <API key> * 4; return inputBandwidthLimit; } /** * @return total datastore size in bytes. */ public synchronized long getStoreSize() { return <API key>; } @Override public synchronized void <API key>() { if(<API key> == null) { <API key> = new <API key>(); clientCore.alerts.register(<API key>); } } public File getNodeDir() { return nodeDir.dir(); } public File getCfgDir() { return cfgDir.dir(); } public File getUserDir() { return userDir.dir(); } public File getRunDir() { return runDir.dir(); } public File getStoreDir() { return storeDir.dir(); } public File getPluginDir() { return pluginDir.dir(); } public ProgramDirectory nodeDir() { return nodeDir; } public ProgramDirectory cfgDir() { return cfgDir; } public ProgramDirectory userDir() { return userDir; } public ProgramDirectory runDir() { return runDir; } public ProgramDirectory storeDir() { return storeDir; } public ProgramDirectory pluginDir() { return pluginDir; } public DarknetPeerNode <API key>(SimpleFieldSet fs, FRIEND_TRUST trust, FRIEND_VISIBILITY visibility) throws FSParseException, PeerParseException, <API key>, PeerTooOldException { return new DarknetPeerNode(fs, this, darknetCrypto, false, trust, visibility); } public OpennetPeerNode <API key>(SimpleFieldSet fs) throws FSParseException, <API key>, PeerParseException, <API key>, PeerTooOldException { if(opennet == null) throw new <API key>("Opennet is not currently enabled"); return new OpennetPeerNode(fs, this, opennet.crypto, opennet, false); } public <API key> <API key>(SimpleFieldSet fs) throws FSParseException, <API key>, PeerParseException, <API key>, PeerTooOldException { if(opennet == null) throw new <API key>("Opennet is not currently enabled"); return new <API key>(fs, this, opennet.crypto, true); } public OpennetPeerNode addNewOpennetNode(SimpleFieldSet fs, ConnectionType connectionType) throws FSParseException, PeerParseException, <API key> { // FIXME: perhaps this should throw <API key> rather than returing false? if(opennet == null) return null; return opennet.addNewOpennetNode(fs, connectionType, false); } public byte[] <API key>() { return opennet.crypto.ecdsaPubKeyHash; } public byte[] <API key>() { return darknetCrypto.ecdsaPubKeyHash; } public synchronized boolean isOpennetEnabled() { return opennet != null; } public SimpleFieldSet <API key>() { return darknetCrypto.<API key>(); } public SimpleFieldSet <API key>() { return opennet.crypto.<API key>(); } public SimpleFieldSet <API key>() { return darknetCrypto.<API key>(); } public SimpleFieldSet <API key>() { return opennet.crypto.<API key>(); } /** * Should the IP detection code only use the IP address override and the bindTo information, * rather than doing a full detection? */ public synchronized boolean dontDetect() { // Only return true if bindTo is set on all ports which are in use if(!darknetCrypto.getBindTo().<API key>(false, true, false)) return false; if(opennet != null) { if(opennet.crypto.getBindTo().<API key>(false, true, false)) return false; } return true; } public int getOpennetFNPPort() { if(opennet == null) return -1; return opennet.crypto.portNumber; } public OpennetManager getOpennet() { return opennet; } public synchronized boolean <API key>() { return <API key>; } /** * Get the set of public ports that need to be forwarded. These are internal * ports, not necessarily external - they may be rewritten by the NAT. * @return A Set of ForwardPort's to be fed to port forward plugins. */ public Set<ForwardPort> <API key>() { HashSet<ForwardPort> set = new HashSet<ForwardPort>(); // FIXME IPv6 support set.add(new ForwardPort("darknet", false, ForwardPort.PROTOCOL_UDP_IPV4, darknetCrypto.portNumber)); if(opennet != null) { NodeCrypto crypto = opennet.crypto; if(crypto != null) { set.add(new ForwardPort("opennet", false, ForwardPort.PROTOCOL_UDP_IPV4, crypto.portNumber)); } } return set; } /** * Get the time since the node was started in milliseconds. * * @return Uptime in milliseconds */ public long getUptime() { return System.currentTimeMillis() - usm.getStartedTime(); } public synchronized UdpSocketHandler[] <API key>() { // FIXME better way to get these! if(opennet != null) { return new UdpSocketHandler[] { darknetCrypto.socket, opennet.crypto.socket }; // TODO Auto-generated method stub } else { return new UdpSocketHandler[] { darknetCrypto.socket }; } } public int getMaxOpennetPeers() { return maxOpennetPeers; } public void onAddedValidIP() { OpennetManager om; synchronized(this) { om = opennet; } if(om != null) { Announcer announcer = om.announcer; if(announcer != null) { announcer.<API key>(); } } } public boolean isSeednode() { return <API key>; } /** * Returns true if the packet receiver should try to decode/process packets that are not from a peer (i.e. from a seed connection) * The packet receiver calls this upon receiving an unrecognized packet. */ public boolean wantAnonAuth(boolean isOpennet) { if(isOpennet) return opennet != null && <API key>; else return false; } // FIXME make this configurable // Probably should wait until we have non-opennet anon auth so we can add it to NodeCrypto. public boolean <API key>(boolean isOpennet) { return !isOpennet; } public boolean <API key>() { OpennetManager om; synchronized(this) { om = this.opennet; } if(om == null) return false; NodeCrypto crypto = om.crypto; if(crypto == null) return false; return crypto.<API key>(); } public boolean <API key>() { if(darknetCrypto == null) return false; return darknetCrypto.<API key>(); } public boolean hasKey(Key key, boolean canReadClientCache, boolean forULPR) { // FIXME optimise! if(key instanceof NodeCHK) return fetch((NodeCHK)key, true, canReadClientCache, false, false, forULPR, null) != null; else return fetch((NodeSSK)key, true, canReadClientCache, false, false, forULPR, null) != null; } /** * Warning: does not announce change in location! */ public void setLocation(double loc) { lm.setLocation(loc); } public boolean peersWantKey(Key key) { return failureTable.peersWantKey(key, null); } private SimpleUserAlert alertMTUTooSmall; public final RequestClient <API key> = new <API key>().build(); public final RequestClient <API key> = new <API key>().realTime().build(); public void setDispatcherHook(<API key> cb) { this.dispatcher.setHook(cb); } public boolean <API key>() { return <API key>; } public boolean <API key>(int htl) { return <API key> && htl > 1; } /** Can be called to decrypt client.dat* etc, or can be called when switching from another * security level to HIGH. */ public void setMasterPassword(String password, boolean inFirstTimeWizard) throws <API key>, <API key>, <API key>, IOException { MasterKeys k; synchronized(this) { if(keys == null) { // Decrypting. keys = MasterKeys.read(masterKeysFile, secureRandom, password); databaseKey = keys.createDatabaseKey(secureRandom); } else { // Setting password when changing to HIGH from another mode. keys.changePassword(masterKeysFile, password, secureRandom); return; } k = keys; } setPasswordInner(k, inFirstTimeWizard); } private void setPasswordInner(MasterKeys keys, boolean inFirstTimeWizard) throws <API key>, <API key>, IOException { MasterSecret secret = keys.<API key>(); clientCore.setupMasterSecret(secret); boolean wantClientCache = false; boolean wantDatabase = false; synchronized(this) { wantClientCache = <API key>; wantDatabase = <API key>; <API key> = false; } if(wantClientCache) <API key>(keys); if(wantDatabase) lateSetupDatabase(keys.createDatabaseKey(secureRandom)); } private void <API key>(MasterKeys keys) { synchronized(this) { if(clientCacheType.equals("ram")) { System.err.println("RAM client cache cannot be passworded!"); return; } if(!clientCacheType.equals("salt-hash")) { System.err.println("Unknown client cache type, cannot activate passworded store: "+clientCacheType); return; } } Runnable migrate = new MigrateOldStoreData(true); String suffix = getStoreSuffix(); try { <API key>(suffix, true, keys.<API key>); } catch (NodeInitException e) { Logger.error(this, "Unable to activate passworded client cache", e); System.err.println("Unable to activate passworded client cache: "+e); e.printStackTrace(); return; } synchronized(this) { <API key> = false; } executor.execute(migrate, "Migrate data from previous store"); } public void <API key>(String oldPassword, String newPassword, boolean inFirstTimeWizard) throws <API key>, <API key>, IOException, <API key> { if(securityLevels.<API key>() == <API key>.MAXIMUM) Logger.error(this, "Changing password while physical threat level is at MAXIMUM???"); if(masterKeysFile.exists()) { keys.changePassword(masterKeysFile, newPassword, secureRandom); setPasswordInner(keys, inFirstTimeWizard); } else { setMasterPassword(newPassword, inFirstTimeWizard); } } public static class <API key> extends Exception { final private static long serialVersionUID = -<API key>; } public synchronized File <API key>() { return masterKeysFile; } boolean hasPanicked() { return hasPanicked; } public void panic() { hasPanicked = true; clientCore.<API key>.panic(); clientCore.<API key>.<API key>(); try { MasterKeys.killMasterKeys(<API key>()); } catch (IOException e) { System.err.println("Unable to wipe master passwords key file!"); System.err.println("Please delete " + <API key>() + " to ensure that nobody can recover your old downloads."); } // persistent-temp will be cleaned on restart. } public void finishPanic() { WrapperManager.restart(); System.exit(0); } public boolean awaitingPassword() { if(<API key>) return true; if(<API key>) return true; return false; } public boolean <API key>() { return this.securityLevels.<API key>() != <API key>.LOW; } public boolean <API key>() { return this.securityLevels.<API key>() == <API key>.MAXIMUM; } public boolean hasDatabase() { return !clientCore.<API key>.isKilledOrNotLoaded(); } /** * @return canonical path of the database file in use. */ public String getDatabasePath() throws IOException { return clientCore.<API key>.getWriteFilename().toString(); } /** Should we commit the block to the store rather than the cache? * * <p>We used to check whether we are a sink by checking whether any peer has * a closer location than we do. Then we made low-uptime nodes exempt from * this calculation: if we route to a low uptime node with a closer location, * we want to store it anyway since he may go offline. The problem was that * if we routed to a low-uptime node, and there was another option that wasn't * low-uptime but was closer to the target than we were, then we would not * store in the store. Also, routing isn't always by the closest peer location: * FOAF and per-node failure tables change it. So now, we consider the nodes * we have actually routed to:</p> * * <p>Store in datastore if our location is closer to the target than:</p><ol> * <li>the source location (if any, and ignoring if low-uptime)</li> * <li>the locations of the nodes we just routed to (ditto)</li> * </ol> * * @param key * @param source * @param routedTo * @return */ public boolean shouldStoreDeep(Key key, PeerNode source, PeerNode[] routedTo) { double myLoc = getLocation(); double target = key.toNormalizedDouble(); double myDist = Location.distance(myLoc, target); // First, calculate whether we would have stored it using the old formula. if(logMINOR) Logger.minor(this, "Should store for "+key+" ?"); // Don't sink store if any of the nodes we routed to, or our predecessor, is both high-uptime and closer to the target than we are. if(source != null && !source.isLowUptime()) { if(Location.distance(source, target) < myDist) { if(logMINOR) Logger.minor(this, "Not storing because source is closer to target for "+key+" : "+source); return false; } } for(PeerNode pn : routedTo) { if(Location.distance(pn, target) < myDist && !pn.isLowUptime()) { if(logMINOR) Logger.minor(this, "Not storing because peer "+pn+" is closer to target for "+key+" his loc "+pn.getLocation()+" my loc "+myLoc+" target is "+target); return false; } else { if(logMINOR) Logger.minor(this, "Should store maybe, peer "+pn+" loc = "+pn.getLocation()+" my loc is "+myLoc+" target is "+target+" low uptime is "+pn.isLowUptime()); } } if(logMINOR) Logger.minor(this, "Should store returning true for "+key+" target="+target+" myLoc="+myLoc+" peers: "+routedTo.length); return true; } public boolean <API key>() { return <API key>; } public boolean getUseSlashdotCache() { return useSlashdotCache; } // FIXME remove the visibility alert after a few builds. public void <API key>() { synchronized(this) { if(<API key>) return; <API key> = true; } // Wait until startup completed. this.getTicker().queueTimedJob(new Runnable() { @Override public void run() { config.store(); } }, 0); <API key>(); } private UserAlert visibilityAlert = new SimpleUserAlert(true, l10n("<API key>"), l10n("<API key>"), l10n("<API key>"), UserAlert.ERROR) { @Override public void onDismiss() { synchronized(Node.this) { <API key> = false; } config.store(); <API key>(); } }; private void <API key>() { if(clientCore == null || clientCore.alerts == null) { // Wait until startup completed. this.getTicker().queueTimedJob(new Runnable() { @Override public void run() { <API key>(); } }, 0); return; } clientCore.alerts.register(visibilityAlert); } private void <API key>() { clientCore.alerts.unregister(visibilityAlert); } public int getMinimumMTU() { int mtu; synchronized(this) { mtu = maxPacketSize; } if(ipDetector != null) { int detected = ipDetector.<API key>(); if(detected < mtu) return detected; } return mtu; } public void updateMTU() { this.darknetCrypto.socket.<API key>(); OpennetManager om = opennet; if(om != null) { om.crypto.socket.<API key>(); } } public static boolean isTestnetEnabled() { return false; } public MersenneTwister createRandom() { byte[] buf = new byte[16]; random.nextBytes(buf); return new MersenneTwister(buf); } public boolean <API key>(boolean realTimeFlag) { NodeStats stats = this.nodeStats; if(stats == null) { Logger.error(this, "Calling <API key> before Node constructor completes! FIX THIS!", new Exception("error")); return false; } return stats.<API key>(realTimeFlag); } /** FIXME move to Probe.java? */ public boolean enableRoutedPing() { return enableRoutedPing; } public boolean updateIsUrgent() { OpennetManager om = getOpennet(); if(om != null) { if(om.announcer != null && om.announcer.isWaitingForUpdater()) return true; } if(peers.<API key>(PeerManager.<API key>, true) > PeerManager.<API key>) return true; return false; } public byte[] getPluginStoreKey(String storeIdentifier) { DatabaseKey key; synchronized(this) { key = databaseKey; } if(key != null) return key.getPluginStoreKey(storeIdentifier); else return null; } public PluginManager getPluginManager() { return pluginManager; } DatabaseKey getDatabaseKey() { return databaseKey; } }
/* $Id: style.css,v 1.38.2.4 2009/09/14 13:10:47 goba Exp $ */ /** * Garland, for Drupal 6.x * Stefan Nagtegaal, iStyledThis [dot] nl * Steven Wittens, acko [dot] net` * * If you use a customized color scheme, you must regenerate it after * modifying this file. */ /** * Generic elements */ body { margin: 0; padding: 0; font: 12px/170% Arial, Helvetica, sans-serif; color: #494949; } input { font: 12px/100% Arial, Helvetica, sans-serif; color: #494949; } textarea, select { font: 12px/160% Arial, Helvetica, sans-serif; color: #494949; } h1, h2, h3, h4, h5, h6 { margin: 0; padding: 0; font-weight: normal; font-family: Arial, Helvetica, sans-serif; } h1 { font-size: 170%; } h2 { font-size: 160%; line-height: 130%; } h3 { font-size: 140%; } h4 { font-size: 130%; } h5 { font-size: 120%; } h6 { font-size: 110%; } ul, quote, code, fieldset { margin: .5em 0; } p { margin: 0.6em 0 1.2em; padding: 0; } a:link, a:visited { color: #027AC6; text-decoration: none; } a:hover { color: #0062A0; text-decoration: underline; } a:active, a.active { color: #5895be; } hr { margin: 0; padding: 0; border: none; height: 1px; background: #5294c1; } ul { margin: 0.5em 0 1em; padding: 0; } ol { margin: 0.75em 0 1.25em; padding: 0; } ol li, ul li { margin: 0.4em 0 0.4em .5em; /* LTR */ } ul.menu, .item-list ul { margin: 0.35em 0 0 -0.5em; /* LTR */ padding: 0; } ul.menu ul, .item-list ul ul { margin-left: 0em; /* LTR */ } ol li, ul li, ul.menu li, .item-list ul li, li.leaf { margin: 0.15em 0 0.15em .5em; /* LTR */ } ul li, ul.menu li, .item-list ul li, li.leaf { padding: 0 0 .2em 1.5em; list-style-type: none; list-style-image: none; background: transparent url(images/menu-leaf.gif) no-repeat 1px .35em; /* LTR */ } ol li { padding: 0 0 .3em; margin-left: 2em; /* LTR */ } ul li.expanded { background: transparent url(images/menu-expanded.gif) no-repeat 1px .35em; /* LTR */ } ul li.collapsed { background: transparent url(images/menu-collapsed.gif) no-repeat 0px .35em; /* LTR */ } ul li.leaf a, ul li.expanded a, ul li.collapsed a { display: block; } ul.inline li { background: none; margin: 0; padding: 0 1em 0 0; /* LTR */ } ol.task-list { margin-left: 0; /* LTR */ list-style-type: none; list-style-image: none; } ol.task-list li { padding: 0.5em 1em 0.5em 2em; /* LTR */ } ol.task-list li.active { background: transparent url(images/task-list.png) no-repeat 3px 50%; /* LTR */ } ol.task-list li.done { color: #393; background: transparent url(../../misc/watchdog-ok.png) no-repeat 0px 50%; /* LTR */ } ol.task-list li.active { margin-right: 1em; /* LTR */ } fieldset ul.clear-block li { margin: 0; padding: 0; background-image: none; } dl { margin: 0.5em 0 1em 1.5em; /* LTR */ } dl dt { } dl dd { margin: 0 0 .5em 1.5em; /* LTR */ } img, a img { border: none; } table { margin: 1em 0; width: 100%; } thead th { border-bottom: 2px solid #d3e7f4; color: #494949; font-weight: bold; } th a:link, th a:visited { color: #6f9dbd; } td, th { padding: .3em .5em; } tr.even, tr.odd, tbody th { border: solid #d3e7f4; border-width: 1px 0; } tr.odd, tr.info { background-color: #edf5fa; } tr.even { background-color: #fff; } tr.drag { background-color: #fffff0; } tr.drag-previous { background-color: #ffd; } tr.odd td.active { background-color: #ddecf5; } tr.even td.active { background-color: #e6f1f7; } td.region, td.module, td.container, td.category { border-top: 1.5em solid #fff; border-bottom: 1px solid #b4d7f0; background-color: #d4e7f3; color: #455067; font-weight: bold; } tr:first-child td.region, tr:first-child td.module, tr:first-child td.container, tr:first-child td.category { border-top-width: 0; } span.form-required { color: #ffae00; } span.submitted, .description { font-size: 0.92em; color: #898989; } .description { line-height: 150%; margin-bottom: 0.75em; color: #898989; } .messages, .preview { margin: .75em 0 .75em; padding: .5em 1em; } .messages ul { margin: 0; } .form-checkboxes, .form-radios, .form-checkboxes .form-item, .form-radios .form-item { margin: 0.25em 0; } #center form { margin-bottom: 2em; } .form-button, .form-submit { margin: 2em 0.5em 1em 0; /* LTR */ } #dblog-form-overview .form-submit, .confirmation .form-submit, .search-form .form-submit, .poll .form-submit, fieldset .form-button, fieldset .form-submit, .sidebar .form-button, .sidebar .form-submit, table .form-button, table .form-submit { margin: 0; } .box { margin-bottom: 2.5em; } /** * Layout */ #header-region { min-height: 1em; background: #d2e6f3 url(images/bg-navigation.png) repeat-x 50% 100%; } #header-region .block { display: block; margin: 0 1em; } #header-region .block-region { display: block; margin: 0 0.5em 1em; padding: 0.5em; position: relative; top: 0.5em; } #header-region * { display: inline; line-height: 1.5em; margin-top: 0; margin-bottom: 0; } /* Header part*/ .headerMain{ background:url(images/bg.png) repeat-x 0 0; height:83px; width:100%; } .headertop{ width:885px; margin:0 auto; background:url(images/header.png) no-repeat top center; height:83px; } .headerLogo{ width:180px; float:left; } /* Prevent the previous directive from showing the content of script elements in Mozilla browsers. */ #header-region script { display: none; } #header-region p, #header-region img { margin-top: 0.5em; } #header-region h2 { margin: 0 1em 0 0; /* LTR */ } #header-region h3, #header-region label, #header-region li { margin: 0 1em; padding: 0; background: none; } #wrapper { background:#bebab8 url(images/main_bg.png) repeat 0 0; } #wrapper #container { margin: 0 auto; padding: 0 20px; max-width: 980px; } #wrapper #container #header { height: 80px; } #wrapper #container #header #logo-floater { position: absolute; } #wrapper #container #header h1, #wrapper #container #header h1 a:link, #wrapper #container #header h1 a:visited { line-height: 120px; position: relative; z-index: 2; white-space: nowrap; } #wrapper #container #header h1 span { font-weight: bold; } #wrapper #container #header h1 img { padding-top: 14px; padding-right: 20px; /* LTR */ float: left; /* LTR */ } /* With 3 columns, require a minimum width of 1000px to ensure there is enough horizontal space. */ body.sidebars { min-width: 980px; } /* With 2 columns, require a minimum width of 800px. */ body.sidebar-left, body.sidebar-right { min-width: 780px; } /* We must define 100% width to avoid the body being too narrow for near-empty pages */ #wrapper #container #center { margin:0px auto; width: 100%; } /* So we move the #center container over the sidebars to compensate */ body.sidebar-left #center { margin-left: -210px; } body.sidebar-right #center { margin-right: 0px; } body.sidebars #center { margin: 0 0px; } /* And add blanks left and right for the sidebars to fill */ body.sidebar-left #squeeze { margin-left: 0px; } body.sidebar-right #squeeze { margin-right: 0px; } body.sidebars #squeeze { margin: 0 0px; } /* We ensure the sidebars are still clickable using z-index */ #wrapper #container .sidebar { margin: 60px 0 5em; width: 210px; float: left; z-index: 2; position: relative; } #wrapper #container .sidebar .block { margin: 0 0 1.5em 0; } #sidebar-left .block { padding: 0 15px 0 0px; } #sidebar-right .block { padding: 0 0px 0 15px; } .block .content { margin: 0.5em 0; } #sidebar-left .block-region { margin: 0 15px 0 0px; /* LTR */ } #sidebar-right .block-region { margin: 0 0px 0 15px; /* LTR */ } .block-region { padding: 1em; background: transparent; border: 2px dashed #b4d7f0; text-align: center; font-size: 1.3em; } /* Now we add the backgrounds for the main content shading */ #wrapper #container #center #squeeze { background: #fff url(images/bg-content.png) repeat-x 50% 0; position: relative; } #wrapper #container #center .right-corner { background: #e3e0df; position: relative; left: 10px; border-right:1px solid #FFF; } #wrapper #container #center .right-corner .left-corner { padding: 60px 25px 5em 35px; background: #e3e0df; border:1px solid #FFF; border-right:0px; margin-left: -10px; position: relative; left: -10px; min-height: 400px; } #wrapper #container #footer { float: none; clear: both; text-align: center; margin: 4em 0 -3em; color: #898989; } #wrapper #container .breadcrumb { position: absolute; top: 15px; left: 35px; /* LTR */ z-index: 3; } body.sidebar-left #footer { margin-left: -210px; } body.sidebar-right #footer { margin-right: -210px; } body.sidebars #footer { margin: 0 -210px; } /** * Header */ #wrapper #container #header h1, #wrapper #container #header h1 a:link, #wrapper #container #header h1 a:visited { color: #fff; font-weight: normal; text-shadow: #1659ac 0px 1px 3px; font-size: 1.5em; } #wrapper #container #header h1 a:hover { text-decoration: none; } #wrapper #container .breadcrumb { font-size: 0.92em; } #wrapper #container .breadcrumb, #wrapper #container .breadcrumb a { color: #529ad6; } #mission { padding: 1em; background-color: #fff; border: 1px solid #e0e5fb; margin-bottom: 2em; } /** * Primary navigation */ ul.primary-links { margin: 0; padding: 0; float: right; /* LTR */ position: relative; z-index: 4; } ul.primary-links li { margin: 0; padding: 0; float: left; /* LTR */ background-image: none; } ul.primary-links li a, ul.primary-links li a:link, ul.primary-links li a:visited { display: block; margin: 0 1em; padding: .75em 0 0; color: #fff; background: transparent url(images/bg-navigation-item.png) no-repeat 50% 0; } ul.primary-links li a:hover, ul.primary-links li a.active { color: #fff; background: transparent url(images/<API key>.png) no-repeat 50% 0; } /** * Secondary navigation */ ul.secondary-links { margin: 0; padding: 18px 0 0; float: right; /* LTR */ clear: right; /* LTR */ position: relative; z-index: 4; } ul.secondary-links li { margin: 0; padding: 0; float: left; /* LTR */ background-image: none; } ul.secondary-links li a, ul.secondary-links li a:link, ul.secondary-links li a:visited { display: block; margin: 0 1em; padding: .75em 0 0; color: #cde3f1; background: transparent; } ul.secondary-links li a:hover, ul.secondary-links li a.active { color: #cde3f1; background: transparent; } /** * Local tasks */ ul.primary, ul.primary li, ul.secondary, ul.secondary li { border: 0; background: none; margin: 0; padding: 0; } #tabs-wrapper { margin: 0 -26px 1em; padding: 0 26px; border-bottom: 1px solid #e9eff3; position: relative; } ul.primary { padding: 0.5em 0 10px; float: left; /* LTR */ } ul.secondary { clear: both; text-align: left; /* LTR */ border-bottom: 1px solid #e9eff3; margin: -0.2em -26px 1em; padding: 0 26px 0.6em; } h2.with-tabs { float: left; /* LTR */ margin: 0 2em 0 0; /* LTR */ padding: 0; } ul.primary li a, ul.primary li.active a, ul.primary li a:hover, ul.primary li a:visited, ul.secondary li a, ul.secondary li.active a, ul.secondary li a:hover, ul.secondary li a:visited { border: 0; background: transparent; padding: 4px 1em; margin: 0 0 0 1px; /* LTR */ height: auto; text-decoration: none; position: relative; top: -1px; display: inline-block; } ul.primary li.active a, ul.primary li.active a:link, ul.primary li.active a:visited, ul.primary li a:hover, ul.secondary li.active a, ul.secondary li.active a:link, ul.secondary li.active a:visited, ul.secondary li a:hover { background: url(images/bg-tab.png) repeat-x 0 50%; color: #fff; } ul.primary li.active a, ul.secondary li.active a { font-weight: bold; } /** * Nodes & comments */ .node { border-bottom: 1px solid #e9eff3; margin: 0 -26px 1.5em; padding: 1.5em 26px; } ul.links li, ul.inline li { margin-left: 0; margin-right: 0; padding-left: 0; /* LTR */ padding-right: 1em; /* LTR */ background-image: none; } .node .links, .comment .links { text-align: left; /* LTR */ } .node .links ul.links li, .comment .links ul.links li {} .terms ul.links li { margin-left: 0; margin-right: 0; padding-right: 0; padding-left: 1em; } .picture, .comment .submitted { float: right; /* LTR */ clear: right; /* LTR */ padding-left: 1em; /* LTR */ } .new { color: #ffae00; font-size: 0.92em; font-weight: bold; float: right; /* LTR */ } .terms { float: right; /* LTR */ } .preview .node, .preview .comment, .sticky { margin: 0; padding: 0.5em 0; border: 0; background: 0; } .sticky { padding: 1em; background-color: #fff; border: 1px solid #e0e5fb; margin-bottom: 2em; } #comments { position: relative; top: -1px; border-bottom: 1px solid #e9eff3; margin: -1.5em -25px 0; padding: 0 25px; } #comments h2.comments { margin: 0 -25px; padding: .5em 25px; background: #fff url(images/gradient-inner.png) repeat-x 0 0; } .comment { margin: 0 -25px; padding: 1.5em 25px 1.5em; border-top: 1px solid #e9eff3; } .indented { margin-left: 25px; /* LTR */ } .comment h3 a.active { color: #494949; } .node .content, .comment .content { margin: 0.6em 0; } /** * Aggregator.module */ #aggregator { margin-top: 1em; } #aggregator .feed-item-title { font-size: 160%; line-height: 130%; } #aggregator .feed-item { border-bottom: 1px solid #e9eff3; margin: -1.5em -31px 1.75em; padding: 1.5em 31px; } #aggregator .<API key> { font-size: 0.92em; } #aggregator .feed-item-meta { font-size: 0.92em; color: #898989; } /** * Color.module */ #palette .form-item { border: 1px solid #fff; } #palette .item-selected { background: #fff url(images/gradient-inner.png) repeat-x 0 0; border: 1px solid #d9eaf5; } /** * Menu.module */ tr.menu-disabled { opacity: 0.5; } tr.odd td.menu-disabled { background-color: #edf5fa; } tr.even td.menu-disabled { background-color: #fff; } /** * Poll.module */ .poll .bar { background: #fff url(images/bg-bar-white.png) repeat-x 0 0; border: solid #f0f0f0; border-width: 0 1px 1px; } .poll .bar .foreground { background: #71a7cc url(images/bg-bar.png) repeat-x 0 100%; } .poll .percent { font-size: .9em; } /** * Autocomplete. */ #autocomplete li { cursor: default; padding: 2px; margin: 0; } /** * Collapsible fieldsets */ fieldset { margin: 1em 0; padding: 1em; border: 1px solid #d9eaf5; background: #fff url(images/gradient-inner.png) repeat-x 0 0; } /* Targets IE 7. Fixes background image in field sets. */ *:first-child+html fieldset { padding: 0 1em 1em; background-position: 0 .75em; background-color: transparent; } *:first-child+html fieldset > .description, *:first-child+html fieldset .fieldset-wrapper .description { padding-top: 1em; } fieldset legend { /* Fix disappearing legend in FFox */ display: block; } *:first-child+html fieldset legend, *:first-child+html fieldset.collapsed legend { display: inline; } html.js fieldset.collapsed { background: transparent; padding-top: 0; padding-bottom: .6em; } html.js fieldset.collapsible legend a { padding-left: 2em; /* LTR */ background: url(images/menu-expanded.gif) no-repeat 0% 50%; /* LTR */ } html.js fieldset.collapsed legend a { background: url(images/menu-collapsed.gif) no-repeat 0% 50%; /* LTR */ } /** * Syndication icons and block */ #block-node-0 h2 { float: left; /* LTR */ padding-right: 20px; /* LTR */ } #block-node-0 img, .feed-icon { float: right; /* LTR */ padding-top: 4px; } #block-node-0 .content { clear: right; /* LTR */ } /** * Login Block */ #user-login-form { text-align: center; } #user-login-form ul { text-align: left; /* LTR */ } /** * User profiles. */ .profile { margin-top: 1.5em; } .profile h3 { border-bottom: 0; margin-bottom: 1em; } .profile dl { margin: 0; } .profile dt { font-weight: normal; color: #898989; font-size: 0.92em; line-height: 1.3em; margin-top: 1.4em; margin-bottom: 0.45em; } .profile dd { margin-bottom: 1.6em; } /** * Admin Styles */ div.admin-panel, div.admin-panel .description, div.admin-panel .body, div.admin, div.admin .left, div.admin .right, div.admin .expert-link, div.item-list, .menu { margin: 0; padding: 0; } div.admin .left { float: left; /* LTR */ width: 48%; } div.admin .right { float: right; /* LTR */ width: 48%; } div.admin-panel { background: #fff url(images/gradient-inner.png) repeat-x 0 0; padding: 1em 1em 1.5em; } div.admin-panel .description { margin-bottom: 1.5em; } div.admin-panel dl { margin: 0; } div.admin-panel dd { color: #898989; font-size: 0.92em; line-height: 1.3em; margin-top: -.2em; margin-bottom: .65em; } table.<API key> th { border-color: #d3e7f4; } #autocomplete li.selected, tr.selected td, tr.selected td.active { background: #027ac6; color: #fff; } tr.selected td a:link, tr.selected td a:visited, tr.selected td a:active { color: #d3e7f4; } tr.<API key> { opacity: 0.5; } tr.<API key> { border-bottom: none; } tr.<API key> { border-top: 1px dotted #CCC; } /** * CSS support */ /** * Generic elements. */ .messages { background-color: #fff; border: 1px solid #b8d3e5; } .preview { background-color: #fcfce8; border: 1px solid #e5e58f; } div.status { color: #33a333; border-color: #c7f2c8; } div.error, tr.error { color: #a30000; background-color: #FFCCCC; } .form-item input.error, .form-item textarea.error { border: 1px solid #c52020; color: #363636; } /** * dblog.module */ tr.dblog-user { background-color: #fcf9e5; } tr.dblog-user td.active { background-color: #fbf5cf; } tr.dblog-content { background-color: #fefefe; } tr.dblog-content td.active { background-color: #f5f5f5; } tr.dblog-warning { background-color: #fdf5e6; } tr.dblog-warning td.active { background-color: #fdf2de; } tr.dblog-error { background-color: #fbe4e4; } tr.dblog-error td.active { background-color: #fbdbdb; } tr.<API key>, tr.dblog-access-denied { background: #d7ffd7; } tr.<API key> td.active, tr.dblog-access-denied td.active { background: #c7eec7; } /** * Status report colors. */ table.<API key> tr.error, table.<API key> tr.error th { background-color: #fcc; border-color: #ebb; color: #200; } table.<API key> tr.warning, table.<API key> tr.warning th { background-color: #ffd; border-color: #eeb; } table.<API key> tr.ok, table.<API key> tr.ok th { background-color: #dfd; border-color: #beb; } /* footer part*/ .footerMain{ background:#000 url(images/footer.png) repeat-x 0 0; height:159px; width:100%; float:left; } .footer{ width:885px; margin:0 auto; color:#FFF; padding-top:30px; letter-spacing:1px; } .footerCopyright{ width:885px; clear:both; padding-top:10px; } .footerLogo{ width:197px; background: url(images/qualcomm.png) no-repeat top left; height:49px; float:left; } .footerLink{ color: #FFFFFF; float: left; height: auto; padding: 10px 0 0 35px; width: 610px; } .footerLink span{ margin:0 5px; color:#666; } .footerLink a{ text-decoration:none; color:#FFF; text-transform:uppercase; font-weight:normal; } .footerLink a:hover{ text-decoration:none; color:#09C; }
/* * This class issues Transaction ID and keeps track of the current version ID */ #include <sys/types.h> #include <sys/stat.h> #include <cerrno> #include <fcntl.h> #include <unistd.h> #include <iostream> #include <string> #include <stdexcept> #include <limits> #ifdef _MSC_VER #include <io.h> #include <psapi.h> #endif using namespace std; #include <boost/thread/mutex.hpp> #include <boost/scoped_ptr.hpp> using namespace boost; #include "brmtypes.h" #include "<API key>.h" using namespace execplan; #include "configcpp.h" #include "atomicops.h" #define <API key> #include "<API key>.h" #undef <API key> #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_DIRECT #define O_DIRECT 0 #endif #ifndef O_LARGEFILE #define O_LARGEFILE 0 #endif #ifndef O_NOATIME #define O_NOATIME 0 #endif #include "IDBDataFile.h" #include "IDBPolicy.h" using namespace idbdatafile; namespace BRM { const uint32_t <API key>::SS_READY = 1 << 0; // Set by dmlProc one time when dmlProc is ready const uint32_t <API key>::SS_SUSPENDED = 1 << 1; // Set by console when the system has been suspended by user. const uint32_t <API key>::SS_SUSPEND_PENDING = 1 << 2; // Set by console when user wants to suspend, but writing is occuring. const uint32_t <API key>::SS_SHUTDOWN_PENDING = 1 << 3; // Set by console when user wants to shutdown, but writing is occuring. const uint32_t <API key>::SS_ROLLBACK = 1 << 4; // In combination with a PENDING flag, force a rollback as soom as possible. const uint32_t <API key>::SS_FORCE = 1 << 5; // In combination with a PENDING flag, force a shutdown without rollback. const uint32_t <API key>::SS_QUERY_READY = 1 << 6; // Set by ProcManager when system is ready for queries <API key>::<API key>() : unique32(0), unique64(0) { config::Config* conf; string stmp; const char* ctmp; conf = config::Config::makeConfig(); try { stmp = conf->getConfig("SessionManager", "<API key>"); } catch (const std::exception& e) { cout << e.what() << endl; stmp.clear(); } if (stmp != "") { int64_t tmp; ctmp = stmp.c_str(); tmp = config::Config::fromText(ctmp); if (tmp < 1) maxTxns = 1; else maxTxns = static_cast<int>(tmp); } else maxTxns = 1; txnidFilename = conf->getConfig("SessionManager", "TxnIDFile"); semValue = maxTxns; _verID = 0; _sysCatVerID = 0; systemState = 0; try { loadState(); } catch (...) { // first-time run most likely, ignore the error } } <API key>::~<API key>() { } void <API key>::reset() { mutex.try_lock(); semValue = maxTxns; condvar.notify_all(); activeTxns.clear(); mutex.unlock(); } void <API key>::loadState() { int lastTxnID; int err; int lastSysCatVerId; again: // There are now 3 pieces of info stored in the txnidfd file: last // transaction id, last system catalog version id, and the // system state flags. All these values are stored in shared, an // instance of struct Overlay. // If we fail to read a full four bytes for any value, then the // value isn't in the file, and we start with the default. if (IDBPolicy::exists(txnidFilename.c_str())) { scoped_ptr<IDBDataFile> txnidfp(IDBDataFile::open( IDBPolicy::getType(txnidFilename.c_str(), IDBPolicy::WRITEENG), txnidFilename.c_str(), "rb", 0)); if (!txnidfp) { perror("<API key>(): open"); throw runtime_error("<API key>: Could not open the transaction ID file"); } // Last transaction id txnidfp->seek(0, SEEK_SET); err = txnidfp->read(&lastTxnID, 4); if (err < 0 && errno != EINTR) { perror("Sessionmanager::initSegment(): read"); throw runtime_error("<API key>: read failed, aborting"); } else if (err < 0) goto again; else if (err == sizeof(int)) _verID = lastTxnID; // last system catalog version id err = txnidfp->read(&lastSysCatVerId, 4); if (err < 0 && errno != EINTR) { perror("Sessionmanager::initSegment(): read"); throw runtime_error("<API key>: read failed, aborting"); } else if (err < 0) goto again; else if (err == sizeof(int)) _sysCatVerID = lastSysCatVerId; // System state. Contains flags regarding the suspend state of the system. err = txnidfp->read(&systemState, 4); if (err < 0 && errno == EINTR) { goto again; } else if (err == sizeof(int)) { // Turn off the pending and force flags. They make no sense for a clean start. // Turn off the ready flag. DMLProc will set it back on when // initialized. systemState &= ~(SS_READY | SS_QUERY_READY | SS_SUSPEND_PENDING | SS_SHUTDOWN_PENDING | SS_ROLLBACK | SS_FORCE); } else { // else no problem. System state wasn't saved. Might be an upgraded system. systemState = 0; } } } /* Save the systemState flags of the Overlay * segment. This is saved in the third * word of txnid File */ void <API key>::saveSystemState() { saveSMTxnIDAndState(); } const QueryContext <API key>::verID() { QueryContext ret; boost::mutex::scoped_lock lk(mutex); ret.currentScn = _verID; for (iterator i = activeTxns.begin(); i != activeTxns.end(); ++i) ret.currentTxns->push_back(i->second); return ret; } const QueryContext <API key>::sysCatVerID() { QueryContext ret; boost::mutex::scoped_lock lk(mutex); ret.currentScn = _sysCatVerID; for (iterator i = activeTxns.begin(); i != activeTxns.end(); ++i) ret.currentTxns->push_back(i->second); return ret; } const TxnID <API key>::newTxnID(const SID session, bool block, bool isDDL) { TxnID ret; // ctor must set valid = false iterator it; boost::mutex::scoped_lock lk(mutex); // if it already has a txn... it = activeTxns.find(session); if (it != activeTxns.end()) { ret.id = it->second; ret.valid = true; return ret; } if (!block && semValue == 0) return ret; else while (semValue == 0) condvar.wait(lk); semValue idbassert(semValue <= (uint32_t)maxTxns); ret.id = ++_verID; ret.valid = true; activeTxns[session] = ret.id; if (isDDL) ++_sysCatVerID; saveSMTxnIDAndState(); return ret; } void <API key>::finishTransaction(TxnID& txn) { iterator it; boost::mutex::scoped_lock lk(mutex); bool found = false; if (!txn.valid) throw invalid_argument("<API key>::finishTransaction(): transaction is invalid"); for (it = activeTxns.begin(); it != activeTxns.end();) { if (it->second == txn.id) { activeTxns.erase(it++); txn.valid = false; found = true; // we could probably break at this point, but there won't be that many active txns, and, // even though it'd be an error to have multiple entries for the same txn, we might // well just get rid of them... } else ++it; } if (found) { semValue++; idbassert(semValue <= (uint32_t)maxTxns); condvar.notify_one(); } else throw invalid_argument("<API key>::finishTransaction(): transaction doesn't exist"); } const TxnID <API key>::getTxnID(const SID session) { TxnID ret; iterator it; boost::mutex::scoped_lock lk(mutex); it = activeTxns.find(session); if (it != activeTxns.end()) { ret.id = it->second; ret.valid = true; } return ret; } shared_array<SIDTIDEntry> <API key>::SIDTIDMap(int& len) { int j; shared_array<SIDTIDEntry> ret; boost::mutex::scoped_lock lk(mutex); iterator it; ret.reset(new SIDTIDEntry[activeTxns.size()]); len = activeTxns.size(); for (it = activeTxns.begin(), j = 0; it != activeTxns.end(); ++it, ++j) { ret[j].sessionid = it->first; ret[j].txnid.id = it->second; ret[j].txnid.valid = true; } return ret; } void <API key>::setSystemState(uint32_t state) { boost::mutex::scoped_lock lk(mutex); systemState |= state; saveSystemState(); } void <API key>::clearSystemState(uint32_t state) { boost::mutex::scoped_lock lk(mutex); systemState &= ~state; saveSystemState(); } uint32_t <API key>::getTxnCount() { boost::mutex::scoped_lock lk(mutex); return activeTxns.size(); } void <API key>::saveSMTxnIDAndState() { // caller holds the lock scoped_ptr<IDBDataFile> txnidfp(IDBDataFile::open( IDBPolicy::getType(txnidFilename.c_str(), IDBPolicy::WRITEENG), txnidFilename.c_str(), "wb", 0)); if (!txnidfp) { perror("<API key>(): open"); throw runtime_error("<API key>: Could not open the transaction ID file"); } int filedata[2]; filedata[0] = _verID; filedata[1] = _sysCatVerID; int err = txnidfp->write(filedata, 8); if (err < 0) { perror("<API key>::newTxnID(): write(verid)"); throw runtime_error("<API key>::newTxnID(): write(verid) failed"); } uint32_t lSystemState = systemState; // We don't save the pending flags, the force flag or the ready flags. lSystemState &= ~(SS_READY | SS_QUERY_READY | SS_SUSPEND_PENDING | SS_SHUTDOWN_PENDING | SS_FORCE); err = txnidfp->write(&lSystemState, sizeof(int)); if (err < 0) { perror("<API key>::saveSystemState(): write(systemState)"); throw runtime_error("<API key>::saveSystemState(): write(systemState) failed"); } txnidfp->flush(); } } // namespace BRM
package org.adempiere.impexp.impl; import java.util.HashMap; import java.util.Map; import org.adempiere.exceptions.AdempiereException; import org.adempiere.impexp.<API key>; import org.adempiere.impexp.IImportProcess; import org.adempiere.impexp.<API key>; import org.adempiere.impexp.<API key>; import org.adempiere.impexp.spi.<API key>; import org.adempiere.model.<API key>; import org.adempiere.util.Check; import org.compiere.model.I_I_BPartner; import org.compiere.model.I_I_Product; import com.google.common.base.Supplier; public class <API key> implements <API key> { private final Map<Class<?>, Class<?>> <API key> = new HashMap<>(); private final Map<String, Class<?>> <API key> = new HashMap<>(); private Supplier<<API key>> <API key>; public <API key>() { // Register standard import processes <API key>(I_I_BPartner.class, <API key>.class); <API key>(I_I_Product.class, <API key>.class); } @Override public <ImportRecordType> void <API key>(final Class<ImportRecordType> modelImportClass, final Class<? extends IImportProcess<ImportRecordType>> importProcessClass) { Check.assumeNotNull(modelImportClass, "modelImportClass not null"); Check.assumeNotNull(importProcessClass, "importProcessClass not null"); <API key>.put(modelImportClass, importProcessClass); final String tableName = <API key>.getTableName(modelImportClass); <API key>.put(tableName, importProcessClass); } @Override public <ImportRecordType> IImportProcess<ImportRecordType> newImportProcess(final Class<ImportRecordType> modelImportClass) { final IImportProcess<ImportRecordType> importProcess = <API key>(modelImportClass); Check.assumeNotNull(importProcess, "importProcess not null for {}", modelImportClass); return importProcess; } @Override public <ImportRecordType> IImportProcess<ImportRecordType> <API key>(final Class<ImportRecordType> modelImportClass) { Check.assumeNotNull(modelImportClass, "modelImportClass not null"); final Class<?> importProcessClass = <API key>.get(modelImportClass); if (importProcessClass == null) { return null; } return newInstance(importProcessClass); } private <ImportRecordType> IImportProcess<ImportRecordType> newInstance(final Class<?> importProcessClass) { try { @SuppressWarnings("unchecked") final IImportProcess<ImportRecordType> importProcess = (IImportProcess<ImportRecordType>)importProcessClass.newInstance(); return importProcess; } catch (Exception e) { throw new AdempiereException("Failed instantiating " + importProcessClass, e); } } @Override public <ImportRecordType> IImportProcess<ImportRecordType> <API key>(final String tableName) { Check.assumeNotNull(tableName, "tableName not null"); final Class<?> importProcessClass = <API key>.get(tableName); if (importProcessClass == null) { return null; } return newInstance(importProcessClass); } @Override public <ImportRecordType> IImportProcess<ImportRecordType> <API key>(final String tableName) { final IImportProcess<ImportRecordType> importProcess = <API key>(tableName); Check.assumeNotNull(importProcess, "importProcess not null for {}", tableName); return importProcess; } @Override public <API key> <API key>() { Check.assumeNotNull(<API key>, "A supplier for {} shall be registered first", <API key>.class); return <API key>.get(); } @Override public void <API key>(Supplier<<API key>> <API key>) { Check.assumeNotNull(<API key>, "<API key> not null"); this.<API key> = <API key>; } }
#pragma once #include <MellowPlayer/Presentation/Notifications/ISystemTrayIcon.hpp> #include <QMenu> #include <QSystemTrayIcon> namespace MellowPlayer::Domain { class ILogger; class IPlayer; class Setting; class Settings; } class <API key> : public QObject { Q_OBJECT public: QString playPause() const; QString next() const; QString previous() const; QString restoreWindow() const; QString quit() const; }; namespace MellowPlayer::Infrastructure { class IApplication; } namespace MellowPlayer::Presentation { class IMainWindow; class SystemTrayIcon : public QObject, public ISystemTrayIcon { Q_OBJECT public: SystemTrayIcon(Domain::IPlayer& player, IMainWindow& mainWindow, Domain::Settings& settings); void show() override; void hide() override; void showMessage(const QString& title, const QString& message) override; public slots: void onActivated(QSystemTrayIcon::ActivationReason reason); void togglePlayPause(); void next(); void previous(); void restoreWindow(); void quit(); private slots: void <API key>(); private: void setUpMenu(); Domain::ILogger& logger_; Domain::IPlayer& player_; IMainWindow& mainWindow_; Domain::Settings& settings_; Domain::Setting& <API key>; QSystemTrayIcon qSystemTrayIcon_; QMenu menu_; QAction* playPauseAction_; QAction* previousSongAction_; QAction* nextSongAction_; QAction* <API key>; QAction* <API key>; }; }
#include "hex.h" #include "exhaustive/arg.h" #include "field.h" #include "util/bits.h" #include "util/memory.h" #include "util/str.h" static char *hex_point(point_t *point) { GEN fx = field_elementi(gel(point->point, 1)); GEN fy = field_elementi(gel(point->point, 2)); char *fxs = pari_sprintf("%P0#*x", cfg->hex_digits, fx); char *fxy = pari_sprintf("%P0#*x", cfg->hex_digits, fy); char *result = str_joinv(",", fxs, fxy, NULL); pari_free(fxs); pari_free(fxy); return result; } static char *hex_points(point_t *points[], size_t len) { char *p[len]; for (size_t i = 0; i < len; ++i) { point_t *pt = points[i]; p[i] = hex_point(pt); } size_t total = 1; for (size_t i = 0; i < len; ++i) { total += strlen(p[i]); } char *result = try_calloc(total); for (size_t i = 0; i < len; ++i) { strcat(result, p[i]); try_free(p[i]); } return result; } CHECK(hex_check_param) { HAS_ARG(args); char *search_hex = try_strdup(args->args); char *p = search_hex; for (; *p; ++p) *p = (char)tolower(*p); char *params[OFFSET_END] = {NULL}; bool pari[OFFSET_END] = {false}; if (state >= OFFSET_SEED) { if (curve->seed && curve->seed->seed) { params[OFFSET_SEED] = bits_to_hex(curve->seed->seed); } } if (state >= OFFSET_FIELD) { if (cfg->field == FIELD_PRIME) { params[OFFSET_FIELD] = pari_sprintf("%P0#*x", cfg->hex_digits, curve->field); pari[OFFSET_FIELD] = true; } else if (cfg->field == FIELD_BINARY) { } } if (state >= OFFSET_A) { params[OFFSET_A] = pari_sprintf("%P0#*x", cfg->hex_digits, field_elementi(curve->a)); pari[OFFSET_A] = true; } if (state >= OFFSET_B) { params[OFFSET_B] = pari_sprintf("%P0#*x", cfg->hex_digits, field_elementi(curve->b)); pari[OFFSET_B] = true; } if (state >= OFFSET_ORDER) { params[OFFSET_ORDER] = pari_sprintf("%P0#*x", cfg->hex_digits, curve->order); pari[OFFSET_ORDER] = true; } if (state >= OFFSET_GENERATORS) { char *subgroups[curve->ngens]; for (size_t i = 0; i < curve->ngens; ++i) { subgroups[i] = hex_point(curve->generators[i]->generator); } params[OFFSET_GENERATORS] = str_join(",", subgroups, curve->ngens); for (size_t i = 0; i < curve->ngens; ++i) { try_free(subgroups[i]); } } if (state >= OFFSET_POINTS) { char *subgroups[curve->ngens]; for (size_t i = 0; i < curve->ngens; ++i) { subgroups[i] = hex_points(curve->generators[i]->points, curve->generators[i]->npoints); } params[OFFSET_POINTS] = str_join(",", subgroups, curve->ngens); for (size_t i = 0; i < curve->ngens; ++i) { try_free(subgroups[i]); } } int result = OFFSET_FIELD - state; for (offset_e i = OFFSET_SEED; i < OFFSET_END; ++i) { if (params[i]) { if (result != 1 && strstr(params[i], search_hex)) { result = 1; } if (pari[i]) { pari_free(params[i]); } else { try_free(params[i]); } } } try_free(search_hex); return result; }
package irc.bot; import java.io.*; public class OutHandler implements Runnable { OutHandler(Connection connection) { this.connection = connection; } private Connection connection; public void run() {} }
package com.ellcs.stack.android; public final class R { public static final class attr { } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class string { public static final int app_name=0x7f030000; } public static final class style { public static final int GdxTheme=0x7f040000; } }
PageProcessor::Application.configure do # Settings specified here will take precedence over those in config/application.rb # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.<API key> = false config.action_controller.perform_caching = true # Disable Rails's static asset server (Apache or nginx will already do this) config.serve_static_assets = false # Compress JavaScripts and CSS config.assets.compress = true # Don't fallback to assets pipeline if a precompiled asset is missed config.assets.compile = false # Generate digests for assets URLs config.assets.digest = true # Defaults to nil and saved in location specified by config.assets.prefix # config.assets.manifest = YOUR_PATH # Specifies the header that your server uses for sending files # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use <API key>, and use secure cookies. # config.force_ssl = true # See everything in the log (default is :info) # config.log_level = :debug # Prepend all log lines with the following tags # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # config.assets.precompile += %w( search.js ) # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.<API key> = false # Enable threaded mode # config.threadsafe! # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found) config.i18n.fallbacks = true # Send deprecation notices to registered listeners config.active_support.deprecation = :notify # Log the query plan for queries taking more than this (works # with SQLite, MySQL, and PostgreSQL) # config.active_record.<API key> = 0.5 # config.middleware.insert 0, "Rack::WWWhisper" end
<?php function edd_rp_settings( $settings ) { $<API key> = array( array( 'id' => 'edd_rp_header', 'name' => '<strong>' . __('Recommended Products', 'edd-rp-txt') . '</strong>', 'desc' => '', 'type' => 'header', 'size' => 'regular' ), array( 'id' => '<API key>', 'name' => __('Show on Downloads', 'edd-rp-txt'), 'desc' => __('Display the recommended products on the download post type', 'edd-rp-txt'), 'type' => 'checkbox', 'size' => 'regular' ), array( 'id' => '<API key>', 'name' => __('Show on Checkout', 'edd-rp-txt'), 'desc' => __('Display the recommended products after the Checkout Cart, and before the Checkout Form', 'edd-rp-txt'), 'type' => 'checkbox', 'size' => 'regular' ), array( 'id' => '<API key>', 'name' => __('Number of Recommendations', 'edd-rp-txt'), 'desc' => __('How many recommendations should be shown to users', 'edd-rp-txt'), 'type' => 'select', 'options' => <API key>() ), array( 'id' => 'edd_rp_show_free', 'name' => __('Show Free Products', 'edd-rp-txt'), 'desc' => __('Allows free products to be shown in the recommendations. (Requires Refresh of Recommendations after save)', 'edd-rp-txt'), 'type' => 'checkbox', 'size' => 'regular' ), array( 'id' => '<API key>', 'name' => '', 'desc' => '', 'type' => 'hook' ) ); return array_merge( $settings, $<API key> ); } add_filter( '<API key>', 'edd_rp_settings' ); function <API key>() { for ( $i = 1; $i <= 5; $i++ ) { $count[$i] = $i; } $count[3] = __( '3 - Default', 'edd-rp-txt' ); return apply_filters( '<API key>', $count ); } function <API key>() { echo '<a href="' . wp_nonce_url( add_query_arg( array( 'edd_action' => 'refresh_edd_rp' ) ), 'edd-rp-recalculate' ) . '" class="button-secondary">' . __( 'Refresh Recommendations', 'edd-rp-txt' ) . '</a>'; } add_action( '<API key>', '<API key>' ); function refresh_edd_rp( $data ) { if ( ! wp_verify_nonce( $data['_wpnonce'], 'edd-rp-recalculate' ) ) { return; } // Refresh Suggestions <API key>(); add_action( 'admin_notices', '<API key>' ); } add_action( 'edd_refresh_edd_rp', 'refresh_edd_rp' ); function <API key>() { printf( '<div class="updated settings-error"> <p> %s </p> </div>', esc_html__( 'Recommendations Updated.', 'edd-rp-txt' ) ); }
package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest06598") public class BenchmarkTest06598 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { org.owasp.benchmark.helpers.<API key> scr = new org.owasp.benchmark.helpers.<API key>( request ); String param = scr.getTheValue("foo"); java.util.List<String> valuesList = new java.util.ArrayList<String>( ); valuesList.add("safe"); valuesList.add( param ); valuesList.add( "moresafe" ); valuesList.remove(0); // remove the 1st safe value String bar = valuesList.get(0); // get the param value try { java.util.Properties Benchmarkprops = new java.util.Properties(); Benchmarkprops.load(this.getClass().getClassLoader().getResourceAsStream("Benchmark.properties")); String algorithm = Benchmarkprops.getProperty("cryptoAlg2", "AES/ECB/PKCS5Padding"); javax.crypto.Cipher c = javax.crypto.Cipher.getInstance(algorithm); } catch (java.security.<API key> e) { System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case"); throw new ServletException(e); } catch (javax.crypto.<API key> e) { System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case"); throw new ServletException(e); } response.getWriter().println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String) executed"); } }
define(function(require) { var Model = require("web/common/model"); var SpsrModel = Model.extend({ idAttribute: "recordId", defaults: { name: "SDI1", kzck: 0, ydsd: 0, srjkxh: 0, ld: 123, dbd: 124, bhd: 125, sppy: 126, czpy: 127 }, urls: { "create": "spsr.psp", "update": "spsr.psp", "delete": "spsr.psp", "read": "spsr.psp" } }); return SpsrModel; });
<?php if (!defined('TFUSE')) exit('Direct access forbidden.'); /** * Class UPDATER. Check for new versions of the theme, framework, or modules. Installs if found. */ class TF_UPDATER extends TF_TFUSE { public $_the_class_name = 'UPDATER'; public $themefuse_update = false; public $check_url; public function __construct() { parent::__construct(); $this->check_url = 'http://themefuse.com/update-themes/'; } public function __init() { $this->themefuse_update = $this-><API key>(); if (get_option(TF_THEME_PREFIX . '_disable_updates') != 1) { add_action('admin_menu', array($this, '<API key>'), 20); if ($this->themefuse_update) { add_action('admin_notices', array($this, '<API key>')); } } } function <API key>() { if (!empty($this->themefuse_update->response[TF_THEME_PREFIX])) $count = count($this->themefuse_update->response[TF_THEME_PREFIX]); $title = !empty($count) ? __('Updates', 'tfuse') . '<span class="update-plugins count-' . $count . '"><span class="update-count">' . number_format_i18n($count) . '</span></span>' : __('Updates', 'tfuse'); add_submenu_page('themefuse', __('Updates', 'tfuse'), $title, 'manage_options', 'tfupdates', array($this, '<API key>')); } function <API key>() { if (!current_user_can('update_themes')) return false; if (!$this->request->empty_GET('action') && $this->request->GET('action') == 'checkagain') { <API key>('themefuse-update'); wp_redirect(self_admin_url('admin.php?page=tfupdates')); } $themefuse_update = get_site_transient('themefuse-update'); if (!$themefuse_update) { $url = $this->check_url; $options = array( 'body' => $this->update_params() ); $request = wp_remote_post($url, $options); $response = <API key>($request); $themefuse_update = new stdClass(); $themefuse_update->last_checked = time(); // If an error occurred, return FALSE, store for 1 hour if ($response == 'error' || is_wp_error($response) || !is_serialized($response)) { $themefuse_update->response[TF_THEME_PREFIX]['Framework']['new_version'] = $this->theme->framework_version; $themefuse_update->response[TF_THEME_PREFIX]['ThemeMods']['new_version'] = $this->theme->mods_version; $themefuse_update->response[TF_THEME_PREFIX]['Templates']['new_version'] = $this->theme->theme_version; set_site_transient('themefuse-update', $themefuse_update, 60 * 60); // store for 1 hour return false; } // Else, unserialize $themefuse_update->response[TF_THEME_PREFIX] = maybe_unserialize($response); // And store in transient set_site_transient('themefuse-update', $themefuse_update, 60 * 60 * 24); // store for 24 hours } if (!(@$themefuse_update->response[TF_THEME_PREFIX])) { // If response is empty return false; } else if (!empty($themefuse_update->response[TF_THEME_PREFIX]['suspended'])) { // Verify if updates for this theme are not suspended from themefuse return false; } else if ( version_compare( $this->theme->framework_version, (!empty($themefuse_update->response[TF_THEME_PREFIX]['Framework']) ? @$themefuse_update->response[TF_THEME_PREFIX]['Framework']['new_version'] : '0' ), '>=' ) && version_compare( $this->theme->mods_version, (!empty($themefuse_update->response[TF_THEME_PREFIX]['ThemeMods']) ? @$themefuse_update->response[TF_THEME_PREFIX]['ThemeMods']['new_version'] : '0' ), '>=' ) && version_compare( $this->theme->theme_version, (!empty($themefuse_update->response[TF_THEME_PREFIX]['Templates']) ? @$themefuse_update->response[TF_THEME_PREFIX]['Templates']['new_version'] : '0' ), '>=' ) ) { // If we're already using the latest version, return FALSE return false; } return $themefuse_update; } function update_params() { global $wp_version, $wpdb; $params = array( 'theme_name' => $this->theme->theme_name, 'prefix' => $this->theme->prefix, 'framework_version' => $this->theme->framework_version, 'mods_version' => $this->theme->mods_version, 'theme_version' => $this->theme->theme_version, 'wp_version' => $wp_version, 'php_version' => phpversion(), 'mysql_version' => $wpdb->db_version(), 'uri' => home_url(), 'locale' => get_locale(), 'is_multi' => is_multisite(), 'is_child' => is_child_theme() ); return apply_filters('tf_update_param', $params); } /** * This function displays the update nag at the top of the * dashboard if there is an ThemeFuse update available. * * @since 2.0 */ function <API key>() { global $upgrading; if (!$this->request->empty_GET('page') && $this->request->GET('page') == 'tfupdates') return; echo apply_filters('<API key>', $this->load->view('updater/update_nag', NULL, true) ); } function <API key>() { if ('tf-do-upgrade' == $this->theme->action || 'tf-do-reinstall' == $this->theme->action || ($this->request->isset_POST('upgrade') && $this->request->POST('upgrade') == __('Proceed', 'tfuse'))) { check_admin_referer('<API key>'); $updates = !empty($this->themefuse_update->response[TF_THEME_PREFIX]) ? array_keys($this->themefuse_update->response[TF_THEME_PREFIX]) : array(); $updates = array_map('urldecode', $updates); $this->load->view('updater/update_page'); if ($this->request->isset_POST('connection_type') && $this->request->POST('connection_type') == 'ftp') { $filesystem = WP_Filesystem($this->request->POST()); } $this->do_core_upgrade($updates); } else { $this-><API key>(); } } function <API key>() { $updates = get_site_transient('themefuse-update'); $data = array( 'updates' => $updates ); if (isset($this->themefuse_update->response)) $data['response'] = $this->themefuse_update->response; $this->load->view('updater/upgrade_preamble', $data); } public function do_core_upgrade($updates) { $this->load->helper('UPGRADER'); $updates = array_map('urldecode', $updates); $url = 'admin.php?page=tfupdates&amp;updates=' . urlencode(implode(',', $updates)); $nonce = '<API key>'; //wp_enqueue_script('jquery'); //iframe_header(); $upgrader = new TF_Theme_Upgrader(new <API key>(compact('nonce', 'url'))); $upgrader->bulk_upgrade($updates); //iframe_footer(); } }
from sys import argv script, input_file = argv def print_all(f): print f.read() def rewind(f): f.seek(0) def print_a_line(line_count, f): print line_count, f.readline() current_file = open(input_file) print "First let's print the whole file:\n" print_all(current_file) print "Now let's rewind, kind of like a tape." rewind(current_file) print "Let's print three lines:" current_line = 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file)
<?php session_start(); $_SESSION["Status"]=0; include("dbconn.php"); require ('../xajax.inc.php'); include("../dbinfo.inc.php"); $memid=$_SESSION['userId']; $_SESSION["userid"]=$memid; function viewuseralbums($userid,$jumpto) {//list all the albums owned by the user $objResponse = new xajaxResponse(); // how many rows to show per page $rowsPerPage = 5; // if $jumpto defined, use it as page number if($jumpto!="") $pageNum = $jumpto; else // by default show first page $pageNum = 1; $start = ($pageNum -1) * $rowsPerPage; // enter query and display stuff $query = "select * from album, ownalbum where album.AlbumId =ownalbum.AlbumId and ownalbum.OwnerId ='$userid' limit $start, $rowsPerPage"; $result=mysql_query($query)or die(mysql_error()); $count =mysql_numrows($result); $msg; if($count==0) {$msg= "No Records founds"; $objResponse->addAssign("mytable","innerHTML",$msg); } else{ //create a table to display album pictures now $msg.="<table class=\"table-wrapper\">";//echo $msg.="<tr>";//end of echo for($S=0;$S<$count;$S++) { $albumid =mysql_result($result,$S,"album.AlbumId"); $albumname= mysql_result($result,$S,"album.AlbumName"); //now display the album pic //1st get the image path of the pic // call a function Getpath2 $path = Getpath2($albumid); // now display the album //3 by 2 $msg.="<td>"; $msg.="<table class=\"table-shadows\" > <tr> <td class=\"td-shadows-main\"> <a href=\"javascript:void(null);\"onclick = \"<API key>($albumid,''); \" >";//end of echo //GetImage path $msg.="<IMG SRC=\"".$path."\"width=150 height=160> </a> </td > <td class=\"td-shadows-right\"></td> </tr> <tr> <td class=\"td-shadows-bottom\"></td> <td class=\"<API key>\"> </td> </tr> <tr><td width = 50 class =\"mytext_account\">$albumname</td></tr> </table><!--end of table shadows </td>";//end of echo //if no if col = 5 then new row if(($S %5 )==0 &&($S+1)!==1 ) $msg.="</tr><tr>"; }//for $msg.="</tr><table>"; // // how many rows we have in database $query="select COUNT(*) AS numrows from album, ownalbum where album.AlbumId =ownalbum.AlbumId and ownalbum.OwnerId ='$userid'"; $result = mysql_query($query) or die('Error, query failed'); $row = mysql_fetch_array($result, MYSQL_ASSOC); $numrows = $row['numrows']; // how many pages we have when using paging? $maxPage = ceil($numrows/$rowsPerPage); // // creating 'previous' and 'next' link if ($pageNum > 1) { $page = $pageNum -1; $prev="<input type=\"button\" name=\"prev\" onclick =\"<API key>($userid,$page);\" value=\"Prev\">"; $first = "<input type=\"button\" name=\"first\" onclick =\"<API key>($userid,1);\" value=\"First\">"; } else { $prev = ' '; // we're on page one, don't enable 'previous' link $first = ' '; // nor 'first page' link } // print 'next' link only if we're not // on the last page if ($pageNum < $maxPage) { $page = $pageNum + 1; $next = "<input type=\"button\" name=\"next\"onclick=\"<API key>($userid,$page);\"value=\"Next\">"; $last = "<input type=\"button\" name=\"Last\"onclick=\"<API key>($userid,$maxPage);\"value=\"Last\">"; } else { $next = ' '; // we're on the last page, don't enable 'next' link $last = ' '; // nor 'last page' link } // print the page navigation link $msg.="<div class =\"mytext_account\">"; $msg.=$first . $prev . " Page <strong>$pageNum</strong> of <strong>$maxPage</strong> pages " . $next . $last; $msg.="</div>"; $objResponse->addAssign("mytable","innerHTML",$msg); //$objResponse->addAssign("but","innerHTML",$but); }//else return $objResponse->getXML(); }//end of function function Getpath2($albumid) { $query="SELECT images.Url FROM images,albumcontainsimages where images.ImageId=albumcontainsimages.ImageId and albumcontainsimages.AlbumId=$albumid"; $result=mysql_query($query); $num=mysql_numrows($result); //check $msg; if($num==0) $msg= "No Records founds"; else { $Url=mysql_result($result,$num-1,"images.Url"); $msg="../Images/".$Url; }//else return $msg; }//end of function function createAlbumView($albumid,$jumpto) { $objResponse = new xajaxResponse(); // how many rows to show per page $rowsPerPage = 15; // if $jumpto defined, use it as page number if($jumpto!="") $pageNum = $jumpto; else // by default show first page $pageNum = 1; $start = ($pageNum -1) * $rowsPerPage; // enter query and display stuff $query="select * from images ,albumcontainsimages,album where images.ImageId=albumcontainsimages.ImageId and albumcontainsimages.AlbumId=album.AlbumId and album.AlbumId =$albumid limit $start, $rowsPerPage"; $result=mysql_query($query); $num=mysql_numrows($result); $msg; if($num==0) {$msg= "No Records founds"; $objResponse->addAssign("mytable","innerHTML",$msg); } else { //display Album Name $AlbumName= mysql_result($result,0,'album.AlbumName'); //display Creation Date $Date = mysql_result($result,0,'album.CreationDate'); //display description of album $des= mysql_result($result,0,'album.Description'); //display no of times viewed //call function GetViewed($albumid) //create a table to display album details first $msg="<table ><tr >";//end of echo $msg.= "<td class =\"td-thumbnails-navi\">Album Name :$AlbumName</td></tr>"; $msg.= "<tr><td class =\"td-thumbnails-navi\">Created on :$Date</td></tr>"; $msg.= "<tr><td class =\"td-thumbnails-navi\">Description :$des</td></tr>"; $msg.= "</table>"; //create a table to display album pictures now $msg.="<table class=\"table-wrapper\">";//echo $msg.="<tr>";//end of echo for($S=0;$S<$num;$S++) { //get path of image $path="../Images/"; $path .= mysql_result($result,$S,"images.Url"); //get des of image $imgdescription= mysql_result($result,$S,"images.Description"); //get dateuploaded of image $dateUploaded=mysql_result($result,$S,"images.DateUploaded"); //get name of image $ImgName=mysql_result($result,$S,"images.ImageName"); //get datecreated of image $imageId=mysql_result($result,$S,"images.ImageId"); $msg.="<td> "; $msg.="<table class=\"table-shadows\" > <tr> <td class=\"td-shadows-main\"> <a href=\"ImageZoom.php?ImgId=$imageId\" >";//end of echo //GetImage path $msg.="<IMG SRC=\"".$path."\"width=150 height=160 align=bottom alt=$ImgName> </a> </td> <td class=\"td-shadows-right\"></td> </tr> <tr> <td class=\"td-shadows-bottom\"></td> <td class=\"<API key>\"> </td> </tr> </table><!--end of table shadows </td>";//end of echo //if no if col = 5 then new row if(($S %4 )==0 &&($S+1)!==1 ) $msg.="</tr><tr>"; }//for $msg.="</tr><table>"; // // how many rows we have in database $query="select COUNT(*) AS numrows from images ,albumcontainsimages,album where images.ImageId=albumcontainsimages.ImageId and albumcontainsimages.AlbumId=album.AlbumId and album.AlbumId =$albumid "; $result = mysql_query($query) or die('Error, query failed'); $row = mysql_fetch_array($result, MYSQL_ASSOC); $numrows = $row['numrows']; // how many pages we have when using paging? $maxPage = ceil($numrows/$rowsPerPage); // // creating 'previous' and 'next' link if ($pageNum > 1) { $page = $pageNum -1; $prev="<input type=\"button\" name=\"prev\" onclick =\"<API key>($albumid,$page);\" value=\"Prev\">"; $first = "<input type=\"button\" name=\"first\" onclick =\"<API key>($albumid,1);\" value=\"First\">"; } else { $prev = ' '; // we're on page one, don't enable 'previous' link $first = ' '; // nor 'first page' link } // print 'next' link only if we're not // on the last page if ($pageNum < $maxPage) { $page = $pageNum + 1; $next = "<input type=\"button\" name=\"next\"onclick=\"<API key>($albumid,$page);\"value=\"Next\">"; $last = "<input type=\"button\" name=\"Last\"onclick=\"<API key>($albumid,$maxPage);\"value=\"Last\">"; } else { $next = ' '; // we're on the last page, don't enable 'next' link $last = ' '; // nor 'last page' link } // print the page navigation link $msg.=$first . $prev . " Page <strong>$pageNum</strong> of <strong>$maxPage</strong> pages " . $next . $last; $objResponse->addAssign("mytable","innerHTML",$msg); //$objResponse->addAssign("but","innerHTML",$but); }//else return $objResponse->getXML(); }//end of function $xajax = new xajax(); $xajax->registerFunction("viewuseralbums"); $xajax->registerFunction("createAlbumView"); $xajax->processRequests(); ?> <html><head><?php $xajax->printJavascript("../"); ?><title>Select Album</title> <link href="../css/style.css" type="text/css" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="../icons/spgm_style.css" /> </head><body onload = "<API key>(<?php echo $memid ; ?>,'');"> <!--Start of footer table <table id="wapper" border=0> <tr> <td id="topleft">&nbsp;</td> <td id="top">&nbsp;</td> <td id="topright">&nbsp;</td> </tr> <tr><td id="left"></td> <td id="logocenter"> <p><span id="title">&nbsp;Select Album</span></p> <div id = "mytable"></div> </td> <td id="right">&nbsp;</td> </tr> <tr> <td id="bottomleft">&nbsp;</td> <td id="bottom">&nbsp;</td> <td id="bottomright">&nbsp;</td> </tr> </table> <!--End of footer table <br> <?php ?> </body> </html>
package edu.ucsd.ncmir.WIB.client.core.components; import com.google.gwt.user.client.ui.Widget; import edu.ucsd.ncmir.WIB.client.core.message.Message; import edu.ucsd.ncmir.WIB.client.core.message.MessageListener; import edu.ucsd.ncmir.WIB.client.core.message.MessageManager; import edu.ucsd.ncmir.WIB.client.core.messages.ResetMessage; /** * HorizontalSlider bar. * @author spl */ public class HorizontalSlider extends SliderHorizontal implements <API key>, MessageListener, <API key> { private final Message _message; /** * Creates a <code>HorizontalSlider</code> object. */ public HorizontalSlider( Message message ) { super( "150px" ); this._message = message; super.<API key>( this ); MessageManager.registerListener( ResetMessage.class, this ); } private int _min_value = 0; private int _max_value = 1; private int _default_value = 0; @Override public final void setSliderParameters( int min_value, int max_value, int default_value ) { this._min_value = min_value; this._max_value = max_value; this._default_value = default_value; this.setMaxValue( this._max_value - this._min_value ); this.setSliderValue( default_value ); super.setMinMarkStep( 1 ); } @Override public void setWidth( String size ) { this._transmit_value = false; double value = super.getValue(); super.setWidth( size ); super.setValue( value ); this._transmit_value = true; } private boolean _transmit_value = true; /** * Updates the value of the slider without firing the handler. * @param value The value to be set. */ @Override public void setSliderValueOnly( int value ) { // Turn off the handler. this._transmit_value = false; this.setSliderValue( value ); this._transmit_value = true; } @Override public void setSliderValue( double value ) { super.setValue( value - this._min_value ); } @Override public void action( Message m, Object o ) { this.setSliderValue( this._default_value ); } private boolean _initial = true; // To prevent premature Message firing. /** * Fired when the bar value changes. * @param event The <code><API key></code>. */ @Override public void onBarValueChanged( <API key> event ) { if ( this._transmit_value && !this._initial ) this.updateHandler( event.getValue() + this._min_value ); // Turn off the initial flag. The SliderBar object fires a // spurious <API key> when the object is loaded. // This prevents it being propagated. this._initial = false; } @Override public void updateHandler( double value ) { this._message.send( value ); } @Override public Widget widget() { return this; } @Override public double getSliderValue() { return this.getValue(); } }
# The absolute path of the main script(p4_tools.rb) ROOT = File.expand_path('..', File.dirname(__FILE__)) # The absolute path of the folder which contains the command files COMMANDS_ROOT = ROOT + '/commands' # The absolute path of the folder which contains the custom command files <API key> = COMMANDS_ROOT + '/custom' # The absolute path of the folder which contains the configuration files CONFIG_ROOT = ROOT + '/config' # Array of command names, read from the COMMAND_ROOT folder
-- Thalorien Dawnseeker's Remains SET @ENTRY := 37552; UPDATE `creature_template` SET `faction`=1770 WHERE `entry`=@ENTRY; -- Phase DELETE FROM `spell_area` WHERE `spell`=70193; INSERT INTO `spell_area` (`spell`, `area`, `quest_start`, `quest_end`, `aura_spell`, `racemask`, `gender`, `autocast`, `quest_start_status`, `quest_end_status`) VALUES ('70193', '4075', '24535', '0', '0', '0', '2', '1', '8', '11'), ('70193', '4075', '24563', '0', '0', '0', '2', '1', '8', '11'); SET @CGUID := 600009; DELETE FROM `creature` WHERE `guid`=@CGUID;
Create a song class # Attributes: 1. Title 2. Band members: a dictionary with name as the key and instrument as the values. 3. (Highest) place on the charts. # Methods: 1. __init__ Has a filepointer as an optional parameter. If filepointer is None have the user input the attributes. If the filepointer is not None input the song from the file. 2. __str__ Output the attributes in a nice way 3. save Save a song to a file, the filepointer should be a parameter. Create an album class # Attributes: 1. Title 2. Year 3. Producer 4. Songs - a list of songs each of which are of type class song. # Methods: 1. __init__ Has a filepointer as an optional parameter. If filepointer is None have the user input the attributes. If the filepointer is not None input the album from the file. In both cases, when you input a song make sure to use the songs method for input. The song attribute should be an optional parameter. If the value is None keep inputting songs until the user is done. 2. __str__ Output the attributes of the album in a nice way. 3. save saves the entire album to a file, makes use of the song.save attribute for the songs. The filepointer is a parameter. Create a menu # Options: 1. Input a new album 2. Print albums 3. Quit When your program is opened it should read in the albums into a list of albums from the file, and when the user quits it should write the albums in the list to a file. Option 1 should add a new album to the album list.
<?php include 'init.php'; $output = ''; $setup = new ON_Settings(); $setup->load(); $setup->registerForm('setup'); // fill form with elements $setup->fillForm(); // process forms if posted if ($setup->form->isSubmitted() && $setup->form->validate()) { $values =& $setup->form->exportValues(); $setup->setValues($values); if($setup->globalid > 0) { $res = $setup->update(); if ($res) { ON_Say::add(fmtSuccess(_('Settings updated successfuly'))); $defaults = $setup->defaults(); $setup->form->resetDefaults($defaults); } else { ON_Say::add(fmtError(_('Database error: settings update failed'))); } } else { $res = $setup->insert(); if ($res) { ON_Say::add(fmtSuccess(_('Settings inserted successfuly'))); } else { ON_Say::add(fmtError(_('Database error: settings insert failed'))); } } } $output .= $setup->form->toHtml(); include 'theme.php'; ?>
# Find Python # Find the Python interpreter and related Python directories. # This file defines the following variables: # PYTHON_EXECUTABLE - The path and filename of the Python interpreter. # <API key> - The version of the Python interpreter found, # excluding the patch version number. (e.g. 2.5 and not 2.5.1)) # PYTHON_LONG_VERSION - The version of the Python interpreter found as a human # readable string. # <API key> - Location of the Python site-packages directory. # PYTHON_INCLUDE_PATH - Directory holding the python.h include file. # PYTHON_LIBRARY, PYTHON_LIBRARIES- Location of the Python library. # For details see the accompanying <API key> file. INCLUDE(CMakeFindFrameworks) if(EXISTS "${PYTHON_INCLUDE_PATH}" AND EXISTS "${PYTHON_LIBRARY}" AND EXISTS "${<API key>}") # Already in cache, be silent set(PYTHONLIBRARY_FOUND TRUE) else(EXISTS "${PYTHON_INCLUDE_PATH}" AND EXISTS "${PYTHON_LIBRARY}" AND EXISTS "${<API key>}") set(_custom_python_fw FALSE) if(APPLE AND <API key>) if("${<API key>}" MATCHES "Python\\.framework") STRING(REGEX REPLACE "(.*Python\\.framework).*$" "\\1" _python_fw "${<API key>}") set(PYTHON_EXECUTABLE "${_python_fw}/Versions/Current/bin/python") set(PYTHON_INCLUDE_PATH "${_python_fw}/Versions/Current/Headers") set(PYTHON_LIBRARY "${_python_fw}/Versions/Current/Python") if(EXISTS "${PYTHON_EXECUTABLE}" AND EXISTS "${PYTHON_INCLUDE_PATH}" AND EXISTS "${PYTHON_LIBRARY}") set(_custom_python_fw TRUE) endif() endif("${<API key>}" MATCHES "Python\\.framework") endif(APPLE AND <API key>) IF (ENABLE_QT5) FIND_PACKAGE(PythonInterp 3) ADD_DEFINITIONS(-DPYTHON3) ELSE (ENABLE_QT5) FIND_PACKAGE(PythonInterp 2) ADD_DEFINITIONS(-DPYTHON2) ENDIF (ENABLE_QT5) if(PYTHONINTERP_FOUND) FIND_FILE(_find_lib_python_py FindLibPython.py PATHS ${CMAKE_MODULE_PATH}) EXECUTE_PROCESS(COMMAND ${PYTHON_EXECUTABLE} ${_find_lib_python_py} OUTPUT_VARIABLE python_config) if(python_config) STRING(REGEX REPLACE ".*exec_prefix:([^\n]+).*$" "\\1" PYTHON_PREFIX ${python_config}) STRING(REGEX REPLACE ".*\nshort_version:([^\n]+).*$" "\\1" <API key> ${python_config}) STRING(REGEX REPLACE ".*\nlong_version:([^\n]+).*$" "\\1" PYTHON_LONG_VERSION ${python_config}) STRING(REGEX REPLACE ".*\npy_inc_dir:([^\n]+).*$" "\\1" PYTHON_INCLUDE_PATH ${python_config}) if(NOT <API key>) if(NOT <API key>) STRING(REGEX REPLACE ".*\nsite_packages_dir:([^\n]+).*$" "\\1" <API key> ${python_config}) else(NOT <API key>) set(<API key> ${<API key>}/python${<API key>}/site-packages) endif(NOT <API key>) endif(NOT <API key>) STRING(REGEX REPLACE "([0-9]+).([0-9]+)" "\\1\\2" <API key> ${<API key>}) set(<API key> python${<API key>} python${<API key>} python${<API key>}m python${<API key>}m) if(WIN32) STRING(REPLACE "\\" "/" <API key> ${<API key>}) endif(WIN32) FIND_LIBRARY(PYTHON_LIBRARY NAMES ${<API key>}) set(PYTHON_INCLUDE_PATH ${PYTHON_INCLUDE_PATH} CACHE FILEPATH "Directory holding the python.h include file" FORCE) set(PYTHONLIBRARY_FOUND TRUE) endif(python_config) # adapted from cmake's builtin FindPythonLibs if(APPLE AND NOT _custom_python_fw) <API key>(Python) set(<API key>) if(Python_FRAMEWORKS) # If a framework has been selected for the include path, # make sure "-framework" is used to link it. if("${PYTHON_INCLUDE_PATH}" MATCHES "Python\\.framework") set(PYTHON_LIBRARY "") set(<API key> "") endif("${PYTHON_INCLUDE_PATH}" MATCHES "Python\\.framework") if(NOT PYTHON_LIBRARY) set (PYTHON_LIBRARY "-framework Python" CACHE FILEPATH "Python Framework" FORCE) endif(NOT PYTHON_LIBRARY) set(PYTHONLIBRARY_FOUND TRUE) endif(Python_FRAMEWORKS) endif(APPLE AND NOT _custom_python_fw) endif(PYTHONINTERP_FOUND) if(PYTHONLIBRARY_FOUND) if(APPLE) # keep reference to system or custom python site-packages # useful during app-bundling operations set(<API key> ${<API key>}) endif(APPLE) set(PYTHON_LIBRARIES ${PYTHON_LIBRARY}) if(NOT <API key>) message(STATUS "Found Python executable: ${PYTHON_EXECUTABLE}") message(STATUS "Found Python version: ${PYTHON_LONG_VERSION}") message(STATUS "Found Python library: ${PYTHON_LIBRARY}") endif(NOT <API key>) else(PYTHONLIBRARY_FOUND) if(<API key>) message(FATAL_ERROR "Could not find Python") endif(<API key>) endif(PYTHONLIBRARY_FOUND) endif (EXISTS "${PYTHON_INCLUDE_PATH}" AND EXISTS "${PYTHON_LIBRARY}" AND EXISTS "${<API key>}")
#include <mach/regs-clock.h> #include <linux/delay.h> #include <linux/dma-mapping.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/clk.h> #include <linux/io.h> #include <linux/gpio.h> #include <linux/mmc/host.h> #include <plat/sdhci.h> #include <plat/regs-sdhci.h> #include <plat/clock.h> #include <plat/clock-clksrc.h> #include <linux/kernel.h> #include "sdhci.h" #define MAX_BUS_CLK (1) void mmc_valid(u16 valid, struct mmc_host *host); /* add by cym 20130328 */ #if <API key> /* skip do suspend for mmc2 host. But it would fail because clock is stopped * but NOT restored automatically after resume. */ #define MMC2_SKIP_SUSPEND (0) /* Enable the following pm capabilities for mmc2 host for wlan suspend/resume: * MMC_PM_KEEP_POWER * <API key> * <API key> * It works on mldk4x12. */ #define <API key> (1) #endif /* end add */ /** * struct sdhci_s3c - S3C SDHCI instance * @host: The SDHCI host created * @pdev: The platform device we where created from. * @ioarea: The resource created when we claimed the IO area. * @pdata: The platform data for this controller. * @cur_clk: The index of the current bus clock. * @clk_io: The clock for the internal bus interface. * @clk_bus: The clocks that are available for the SD/MMC bus clock. */ struct sdhci_s3c { struct sdhci_host *host; struct platform_device *pdev; struct resource *ioarea; struct s3c_sdhci_platdata *pdata; unsigned int cur_clk; int ext_cd_irq; int ext_cd_gpio; struct clk *clk_io; struct clk *clk_bus[MAX_BUS_CLK]; }; static inline struct sdhci_s3c *to_s3c(struct sdhci_host *host) { return sdhci_priv(host); } /** * get_curclk - convert ctrl2 register to clock source number * @ctrl2: Control2 register value. */ static u32 get_curclk(u32 ctrl2) { ctrl2 &= <API key>; ctrl2 >>= <API key>; return ctrl2; } static void <API key>(struct sdhci_host *host) { struct sdhci_s3c *ourhost = to_s3c(host); u32 tmp = readl(host->ioaddr + S3C_SDHCI_CONTROL2); if (get_curclk(tmp) != ourhost->cur_clk) { dev_dbg(&ourhost->pdev->dev, "restored ctrl2 clock setting\n"); tmp &= ~<API key>; tmp |= ourhost->cur_clk << <API key>; writel(tmp, host->ioaddr + 0x80); } } /** * <API key> - callback to get maximum clock frequency. * @host: The SDHCI host instance. * * Callback to return the maximum clock rate acheivable by the controller. */ static unsigned int <API key>(struct sdhci_host *host) { struct sdhci_s3c *ourhost = to_s3c(host); struct clk *busclk; unsigned int rate, max; int clk; /* note, a reset will reset the clock source */ <API key>(host); for (max = 0, clk = 0; clk < MAX_BUS_CLK; clk++) { busclk = ourhost->clk_bus[clk]; if (!busclk) continue; rate = clk_get_rate(busclk); if (rate > max) max = rate; } return max; } static inline struct clksrc_clk *to_clksrc(struct clk *clk)//lisw sd { return container_of(clk, struct clksrc_clk, clk); } /** * <API key> - consider one the bus clocks for current setting * @ourhost: Our SDHCI instance. * @src: The source clock index. * @wanted: The clock frequency wanted. */ static unsigned int <API key>(struct sdhci_s3c *ourhost, unsigned int src, unsigned int wanted) { unsigned long rate; struct clk *clk_sclk_mmc = ourhost->clk_bus[0];//lisw sd : for different clk source structure struct clksrc_clk *clksrc_parent = to_clksrc(clk_sclk_mmc->parent); struct clk *clksrc = clksrc_parent->sources->sources[src]; int div; if (!clksrc) return UINT_MAX; /* * Clock divider's step is different as 1 from that of host controller * when 'clk_type' is <API key>. */ // if (ourhost->pdata->clk_type) { // rate = clk_round_rate(clksrc, wanted); // return wanted - rate; rate = clk_get_rate(clksrc); for (div = 1; div < 256; div++) { if ((rate / div) <= wanted) break; } dev_dbg(&ourhost->pdev->dev, "clk %d: rate %ld, want %d, got %ld\n", src, rate, wanted, rate / div); return (wanted - (rate / div)); } /** * <API key> - callback on clock change * @host: The SDHCI host being changed * @clock: The clock rate being requested. * * When the card's clock is going to be changed, look at the new frequency * and find the best clock source to go with it. */ int <API key>(struct clk *clk, unsigned long rate);//lisw sd int clk_set_parent(struct clk *clk, struct clk *parent);//lisw sd static void <API key>(struct sdhci_host *host, unsigned int clock) { struct sdhci_s3c *ourhost = to_s3c(host); struct clk *clk_sclk_mmc = ourhost->clk_bus[0];//lisw sd : for different clk source structure struct clksrc_clk *clksrc_parent = to_clksrc(clk_sclk_mmc->parent); unsigned int best = UINT_MAX; unsigned int delta; int best_src = 0; int src; u32 ctrl; /* don't bother if the clock is going off. */ if (clock == 0) return; if(MAX_BUS_CLK==1){ for (src = 6; src < clksrc_parent->sources->nr_sources; src++) {//lisw ms : set 6 as firsrt selection because XXTI 24Mhz is not stable delta = <API key>(ourhost, src, clock); if (delta < best) { best = delta; best_src = src; } } } else return; //printk("selected source %d, clock %d, delta %d\n", // best_src, clock, best); /* select the new clock source */ if (ourhost->cur_clk != best_src) { struct clk *clk = clksrc_parent->sources->sources[best_src]; /* turn clock off to card before changing clock source */ writew(0, host->ioaddr + SDHCI_CLOCK_CONTROL); ourhost->cur_clk = best_src; host->max_clk = clk_get_rate(clk); // ctrl = readl(host->ioaddr + S3C_SDHCI_CONTROL2); // ctrl &= ~<API key>; // ctrl |= best_src << <API key>; // writel(ctrl, host->ioaddr + S3C_SDHCI_CONTROL2); //***use base clock select funtion in CMU instread in SD host controller***// if (clk_set_parent(clk_sclk_mmc->parent, clk)) printk("Unable to set parent %s of clock %s.\n", clk->name, clksrc_parent->clk.name); clk_sclk_mmc->parent->parent = clk; } // <API key>(clk_sclk_mmc,clock); /* reconfigure the hardware for new clock rate */ { struct mmc_ios ios; ios.clock = clock; if (ourhost->pdata->cfg_card) (ourhost->pdata->cfg_card)(ourhost->pdev, host->ioaddr, &ios, NULL); } } /** * sdhci_s3c_set_clock - callback on clock change * @host: The SDHCI host being changed * @clock: The clock rate being requested. * * When the card's clock is going to be changed, look at the new frequency * and find the best clock source to go with it. */ static void sdhci_s3c_set_clock(struct sdhci_host *host, unsigned int clock) { struct sdhci_s3c *ourhost = to_s3c(host); unsigned int best = UINT_MAX; unsigned int delta; int best_src = 0; int src; u32 ctrl; /* don't bother if the clock is going off. */ if (clock == 0) return; for (src = 0; src < MAX_BUS_CLK; src++) { delta = <API key>(ourhost, src, clock); if (delta < best) { best = delta; best_src = src; } } dev_dbg(&ourhost->pdev->dev, "selected source %d, clock %d, delta %d\n", best_src, clock, best); /* select the new clock source */ if (ourhost->cur_clk != best_src) { struct clk *clk = ourhost->clk_bus[best_src]; /* turn clock off to card before changing clock source */ writew(0, host->ioaddr + SDHCI_CLOCK_CONTROL); ourhost->cur_clk = best_src; host->max_clk = clk_get_rate(clk); ctrl = readl(host->ioaddr + S3C_SDHCI_CONTROL2); ctrl &= ~<API key>; ctrl |= best_src << <API key>; writel(ctrl, host->ioaddr + S3C_SDHCI_CONTROL2); } /* reconfigure the hardware for new clock rate */ { struct mmc_ios ios; ios.clock = clock; if (ourhost->pdata->cfg_card) (ourhost->pdata->cfg_card)(ourhost->pdev, host->ioaddr, &ios, NULL); } } /** * <API key> - callback to get minimal supported clock value * @host: The SDHCI host being queried * * To init mmc host properly a minimal clock value is needed. For high system * bus clock's values the standard formula gives values out of allowed range. * The clock still can be set to lower values, if clock source other then * system bus is selected. */ static unsigned int <API key>(struct sdhci_host *host) { struct sdhci_s3c *ourhost = to_s3c(host); unsigned int delta, min = UINT_MAX; int src; for (src = 0; src < MAX_BUS_CLK; src++) { delta = <API key>(ourhost, src, 0); if (delta == UINT_MAX) continue; /* delta is a negative value in this case */ if (-delta < min) min = -delta; } return min; } /* <API key> - callback to get maximum clock frequency.*/ static unsigned int <API key>(struct sdhci_host *host) { struct sdhci_s3c *ourhost = to_s3c(host); host->max_clk = clk_get_rate(to_clksrc(ourhost->clk_bus[0]->parent)->sources->sources[ourhost->cur_clk]); return host->max_clk;//clk_round_rate(ourhost->clk_bus[ourhost->cur_clk], UINT_MAX); } /* <API key> - callback to get minimal supported clock value. */ static unsigned int <API key>(struct sdhci_host *host) { struct sdhci_s3c *ourhost = to_s3c(host); /* * initial clock can be in the frequency range of * 100KHz-400KHz, so we set it as max value. */ return <API key>(host)/((1 << to_clksrc(ourhost->clk_bus[0]->parent)->reg_div.size)*(1 << to_clksrc(ourhost->clk_bus[0])->reg_div.size)); } /* sdhci_cmu_set_clock - callback on clock change.*/ static void sdhci_cmu_set_clock(struct sdhci_host *host, unsigned int clock) { struct sdhci_s3c *ourhost = to_s3c(host); /* don't bother if the clock is going off */ if (clock == 0) return; // sdhci_s3c_set_clock(host, clock); <API key>(host, clock); // clk_set_rate(ourhost->clk_bus[ourhost->cur_clk], clock); <API key>(ourhost->clk_bus[0],clock); host->clock = clock; } /** * <API key> - support 8bit buswidth * @host: The SDHCI host being queried * @width: MMC_BUS_WIDTH_ macro for the bus width being requested * * We have 8-bit width support but is not a v3 controller. * So we add platform_8bit_width() and support 8bit width. */ static int <API key>(struct sdhci_host *host, int width) { u8 ctrl; ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL); switch (width) { case MMC_BUS_WIDTH_8: ctrl |= SDHCI_CTRL_8BITBUS; ctrl &= ~SDHCI_CTRL_4BITBUS; break; case MMC_BUS_WIDTH_4: ctrl |= SDHCI_CTRL_4BITBUS; ctrl &= ~SDHCI_CTRL_8BITBUS; break; default: break; } sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL); return 0; } //ly 20111123 int sdhci_s3c_get_cd(struct sdhci_host *mmc)//lisw sd hotplug { int detect; struct sdhci_s3c* sc = sdhci_priv(mmc); if(mmc->mmc->index== 1){ //ch0+1 is emmc ch2 is TF int status = gpio_get_value(sc->pdata->ext_cd_gpio); if (sc->pdata->ext_cd_gpio_invert) status = !status; if (status){ detect = true; }else{ detect = false; } }else{ detect = true; } return detect; } static struct sdhci_ops sdhci_s3c_ops = { .get_max_clock = <API key>, .set_clock = sdhci_s3c_set_clock, .get_min_clock = <API key>, .platform_8bit_width = <API key>, .get_cd = sdhci_s3c_get_cd, }; void sdhci_init(struct sdhci_host *host, int soft); static void <API key>(struct platform_device *dev, int state) { struct sdhci_host *host = <API key>(dev); unsigned long flags; if (host) { spin_lock_irqsave(&host->lock, flags); if (state) { dev_dbg(&dev->dev, "card inserted.\n"); host->flags &= ~SDHCI_DEVICE_DEAD; host->quirks |= <API key>; sdhci_init(host,0);//lisw sd hotplug : for reinitialize host controller each time plugin } else { dev_dbg(&dev->dev, "card removed.\n"); host->flags |= SDHCI_DEVICE_DEAD; host->quirks &= ~<API key>; } tasklet_schedule(&host->card_tasklet); <API key>(&host->lock, flags); } } static irqreturn_t <API key>(int irq, void *dev_id) { struct sdhci_s3c *sc = dev_id; int status = gpio_get_value(sc->pdata->ext_cd_gpio); if (sc->pdata->ext_cd_gpio_invert) status = !status; if(status){//card present mmc_valid(1,sc->host->mmc);//lisw sd hotplug } else{//card absent mmc_valid(0,sc->host->mmc); } <API key>(sc->pdev, status); return IRQ_HANDLED; } void <API key>(struct platform_device *pdev) { struct sdhci_host *host = <API key>(pdev); //printk(KERN_DEBUG "+%s", __FUNCTION__); printk("+%s\n", __FUNCTION__); // mmc_detect_change(host->mmc, msecs_to_jiffies(60)); mmc_detect_change(host->mmc, msecs_to_jiffies(500)); //printk(KERN_DEBUG "-%s", __FUNCTION__); printk("-%s\n", __FUNCTION__); } EXPORT_SYMBOL(<API key>); static void <API key>(struct sdhci_s3c *sc) { struct s3c_sdhci_platdata *pdata = sc->pdata; struct device *dev = &sc->pdev->dev; if (gpio_request(pdata->ext_cd_gpio, "SDHCI EXT CD") == 0) { sc->ext_cd_gpio = pdata->ext_cd_gpio; sc->ext_cd_irq = gpio_to_irq(pdata->ext_cd_gpio); enable_irq_wake(sc->ext_cd_irq);//lisw hotplug during suspend if (sc->ext_cd_irq && <API key>(sc->ext_cd_irq, NULL, <API key>, IRQF_TRIGGER_RISING | <API key>, dev_name(dev), sc) == 0) { int status = gpio_get_value(sc->ext_cd_gpio); if (pdata->ext_cd_gpio_invert) status = !status; <API key>(sc->pdev, status); } else { dev_warn(dev, "cannot request irq for card detect\n"); sc->ext_cd_irq = 0; } } else { dev_err(dev, "cannot request gpio for card detect\n"); } } static int __devinit sdhci_s3c_probe(struct platform_device *pdev) { struct s3c_sdhci_platdata *pdata = pdev->dev.platform_data; struct device *dev = &pdev->dev; struct sdhci_host *host; struct sdhci_s3c *sc; struct resource *res; int ret, irq, ptr, clks; if (!pdata) { dev_err(dev, "no device data specified\n"); return -ENOENT; } irq = platform_get_irq(pdev, 0); if (irq < 0) { dev_err(dev, "no irq specified\n"); return irq; } res = <API key>(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(dev, "no memory specified\n"); return -ENOENT; } host = sdhci_alloc_host(dev, sizeof(struct sdhci_s3c)); if (IS_ERR(host)) { dev_err(dev, "sdhci_alloc_host() failed\n"); return PTR_ERR(host); } sc = sdhci_priv(host); sc->host = host; sc->pdev = pdev; sc->pdata = pdata; sc->ext_cd_gpio = -1; /* invalid gpio number */ <API key>(pdev, host); sc->clk_io = clk_get(dev, "hsmmc"); if (IS_ERR(sc->clk_io)) { dev_err(dev, "failed to get io clock\n"); ret = PTR_ERR(sc->clk_io); goto err_io_clk; } /* enable the local io clock and keep it running for the moment. */ clk_enable(sc->clk_io); for (clks = 0, ptr = 0; ptr < MAX_BUS_CLK; ptr++) { struct clk *clk; char *name = pdata->clocks[ptr]; if (name == NULL) continue; clk = clk_get(dev, name); if (IS_ERR(clk)) { dev_err(dev, "failed to get clock %s\n", name); continue; } clks++; sc->clk_bus[ptr] = clk; /* * save current clock index to know which clock bus * is used later in overriding functions. */ sc->cur_clk = 7;// clock sources select number clk_set_parent(clk->parent,to_clksrc(clk->parent)->sources->sources[7]); clk_enable(clk); dev_info(dev, "clock source %d: %s (%ld Hz)\n", ptr, name, clk_get_rate(clk)); } if (clks == 0) { dev_err(dev, "failed to find any bus clocks\n"); ret = -ENOENT; goto err_no_busclks; } sc->ioarea = request_mem_region(res->start, resource_size(res), mmc_hostname(host->mmc)); if (!sc->ioarea) { dev_err(dev, "failed to reserve register area\n"); ret = -ENXIO; goto err_req_regs; } host->ioaddr = ioremap_nocache(res->start, resource_size(res)); if (!host->ioaddr) { dev_err(dev, "failed to map registers\n"); ret = -ENXIO; goto err_req_regs; } /* Ensure we have minimal gpio selected CMD/CLK/Detect */ if (pdata->cfg_gpio) pdata->cfg_gpio(pdev, pdata->max_width); host->hw_name = "samsung-hsmmc"; host->ops = &sdhci_s3c_ops; host->quirks = 0; host->irq = irq; /* Setup quirks for the controller */ host->quirks |= <API key>; host->quirks |= <API key>; #ifndef <API key> /* we currently see overruns on errors, so disable the SDMA * support as well. */ host->quirks |= <API key>; #endif /* <API key> */ /* It seems we do not get an DATA transfer complete on non-busy * transfers, not sure if this is a problem with this specific * SDHCI block, or a missing configuration that needs to be set. */ host->quirks |= <API key>; /* This host supports the Auto CMD12 */ host->quirks |= <API key>; if (pdata->cd_type == S3C_SDHCI_CD_NONE || pdata->cd_type == <API key>) host->quirks |= <API key>; if (pdata->cd_type == <API key>) host->mmc->caps = <API key>; if (pdata->host_caps) host->mmc->caps |= pdata->host_caps; host->quirks |= (<API key> | <API key>); /* HSMMC on Samsung SoCs uses SDCLK as timeout clock */ host->quirks |= <API key>; /* * If controller does not have internal clock divider, * we can use overriding functions instead of default. */ if (pdata->clk_type) { sdhci_s3c_ops.set_clock = sdhci_cmu_set_clock; sdhci_s3c_ops.get_min_clock = <API key>; sdhci_s3c_ops.get_max_clock = <API key>; } /* It supports additional host capabilities if needed */ if (pdata->host_caps) host->mmc->caps |= pdata->host_caps; /* add by cym 20130328 */ #if MMC2_SKIP_SUSPEND if (2 == host->mmc->index) { /* to avoid redundant mmc_detect_change() called by mmc_pm_notify() */ printk(KERN_INFO "%s: set <API key> for %s pm_flags\n", __func__, mmc_hostname(host->mmc)); host->mmc->pm_flags |= <API key>; } #elif <API key> if (2 == host->mmc->index) { /* to avoid redundant mmc_detect_change() called by mmc_pm_notify() */ printk(KERN_INFO "%s: set <API key> for %s pm_flags\n", __func__, mmc_hostname(host->mmc)); host->mmc->pm_flags |= <API key>; printk(KERN_INFO "%s: set MMC_PM_KEEP_POWER | <API key> for %s pm_caps\n", __func__, mmc_hostname(host->mmc)); host->mmc->pm_caps |= MMC_PM_KEEP_POWER | <API key>; } #endif /* end add */ ret = sdhci_add_host(host); if (ret) { dev_err(dev, "sdhci_add_host() failed\n"); goto err_add_host; } /* The following two methods of card detection might call <API key>() immediately, so they can be called only after sdhci_add_host(). Setup errors are ignored. */ if (pdata->cd_type == <API key> && pdata->ext_cd_init) pdata->ext_cd_init(&<API key>); if (pdata->cd_type == S3C_SDHCI_CD_GPIO && gpio_is_valid(pdata->ext_cd_gpio)) <API key>(sc); return 0; err_add_host: release_resource(sc->ioarea); kfree(sc->ioarea); err_req_regs: for (ptr = 0; ptr < MAX_BUS_CLK; ptr++) { clk_disable(sc->clk_bus[ptr]); clk_put(sc->clk_bus[ptr]); } err_no_busclks: clk_disable(sc->clk_io); clk_put(sc->clk_io); err_io_clk: sdhci_free_host(host); return ret; } static int __devexit sdhci_s3c_remove(struct platform_device *pdev) { struct s3c_sdhci_platdata *pdata = pdev->dev.platform_data; struct sdhci_host *host = <API key>(pdev); struct sdhci_s3c *sc = sdhci_priv(host); int ptr; if (pdata->cd_type == <API key> && pdata->ext_cd_cleanup) pdata->ext_cd_cleanup(&<API key>); if (sc->ext_cd_irq) free_irq(sc->ext_cd_irq, sc); if (gpio_is_valid(sc->ext_cd_gpio)) gpio_free(sc->ext_cd_gpio); sdhci_remove_host(host, 1); for (ptr = 0; ptr < 3; ptr++) { if (sc->clk_bus[ptr]) { clk_disable(sc->clk_bus[ptr]); clk_put(sc->clk_bus[ptr]); } } clk_disable(sc->clk_io); clk_put(sc->clk_io); iounmap(host->ioaddr); release_resource(sc->ioarea); kfree(sc->ioarea); sdhci_free_host(host); <API key>(pdev, NULL); return 0; } #ifdef CONFIG_PM static int sdhci_s3c_suspend(struct platform_device *dev, pm_message_t pm) { struct sdhci_host *host = <API key>(dev); /* add by cym 20130328 */ #if MMC2_SKIP_SUSPEND /* mmc2 is s3c_device_hsmmc3 */ if (2 == host->mmc->index) { printk(KERN_INFO "skip %s for %s dev->id(%d)\n", __func__, mmc_hostname(host->mmc), dev->id); return 0; } else { printk(KERN_INFO "%s for %s dev->id(%d)\n", __func__, mmc_hostname(host->mmc), dev->id); } #endif /* end add */ sdhci_suspend_host(host, pm); return 0; } static int sdhci_s3c_resume(struct platform_device *dev) { struct sdhci_host *host = <API key>(dev); struct sdhci_s3c *sc = sdhci_priv(host); /* add by cym 20130328 */ #if MMC2_SKIP_SUSPEND /* mmc2 is s3c_device_hsmmc3 */ if (2 == host->mmc->index) { printk(KERN_INFO "skip %s for %s dev->id(%d)\n", __func__, mmc_hostname(host->mmc), dev->id); return 0; } else { printk(KERN_INFO "%s for %s dev->id(%d)\n", __func__, mmc_hostname(host->mmc), dev->id); } #endif /* end add */ sdhci_resume_host(host); /* add by cym 20130328 */ #ifndef MMC2_SKIP_SUSPEND /* end add */ if(!(host->mmc->caps & <API key>)){//lisw hotplug during suspend int status = gpio_get_value(sc->ext_cd_gpio); if (sc->pdata->ext_cd_gpio_invert) status = !status; <API key>(sc->pdev, status); } /* add by cym 20130328 */ #endif /* end add */ return 0; } #else #define sdhci_s3c_suspend NULL #define sdhci_s3c_resume NULL #endif static struct platform_driver sdhci_s3c_driver = { .probe = sdhci_s3c_probe, .remove = __devexit_p(sdhci_s3c_remove), .suspend = sdhci_s3c_suspend, .resume = sdhci_s3c_resume, .driver = { .owner = THIS_MODULE, .name = "s3c-sdhci", }, }; static int __init sdhci_s3c_init(void) { return <API key>(&sdhci_s3c_driver); } static void __exit sdhci_s3c_exit(void) { <API key>(&sdhci_s3c_driver); } module_init(sdhci_s3c_init); module_exit(sdhci_s3c_exit); MODULE_DESCRIPTION("Samsung SDHCI (HSMMC) glue"); MODULE_AUTHOR("Ben Dooks, <ben@simtec.co.uk>"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:s3c-sdhci");
#include <linux/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/time.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/hrtimer.h> #include <linux/delay.h> #include <mach/hardware.h> #include <linux/io.h> #include <asm/system.h> #include <asm/mach-types.h> #include <linux/semaphore.h> #include <linux/spinlock.h> #include <linux/fb.h> #include "mdp.h" #include "msm_fb.h" #include "mdp4.h" /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption start */ extern struct mutex <API key>; /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption end */ static struct mdp4_overlay_pipe *mddi_pipe; static struct msm_fb_data_type *mddi_mfd; static int busy_wait_cnt; static int <API key> = 4; static int dmap_vsync_enable; /* FUJITSU:2011-12-22 add sandstorm blocker --> */ #if defined(CONFIG_FB_MSM_MDDI) extern void <API key>(void); #endif /* FUJITSU:2011-12-22 add sandstorm blocker <-- */ void mdp_dmap_vsync_set(int enable) { dmap_vsync_enable = enable; } int mdp_dmap_vsync_get(void) { return dmap_vsync_enable; } void <API key>(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe, int which) { uint32 start_y, data, tear_en; tear_en = (1 << which); if ((mfd->use_mdp_vsync) && (mfd->ibuf.vsync_enable) && (mfd->panel_info.lcd.vsync_enable)) { if (mdp_hw_revision < MDP4_REVISION_V2_1) { /* need dmas dmap switch */ if (which == 0 && dmap_vsync_enable == 0 && mfd->panel_info.lcd.rev < 2) /* dma_p */ return; } if (<API key> <= pipe->dst_y) start_y = pipe->dst_y - <API key>; else start_y = (mfd->total_lcd_lines - 1) - (<API key> - pipe->dst_y); if (which == 0) MDP_OUTP(MDP_BASE + 0x210, start_y); /* primary */ else MDP_OUTP(MDP_BASE + 0x214, start_y); /* secondary */ data = inpdw(MDP_BASE + 0x20c); data |= tear_en; MDP_OUTP(MDP_BASE + 0x20c, data); } else { data = inpdw(MDP_BASE + 0x20c); data &= ~tear_en; MDP_OUTP(MDP_BASE + 0x20c, data); } } #define WHOLESCREEN void <API key>(struct msm_fb_data_type *mfd) { MDPIBUF *iBuf = &mfd->ibuf; uint8 *src; int ptype; uint32 mddi_ld_param; uint16 mddi_vdo_packet_reg; struct mdp4_overlay_pipe *pipe; int ret; if (mfd->key != MFD_KEY) return; /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption start */ mutex_lock(&<API key>); /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption end */ mddi_mfd = mfd; /* keep it */ /* FUJITSU:2011-12-22 add sandstorm blocker --> */ #if defined(CONFIG_FB_MSM_MDDI) /* if update RAM image size is full screen size */ if (iBuf->dma_h == mfd->panel_info.yres) { <API key>(); } #endif /* FUJITSU:2011-12-22 add sandstorm blocker <-- */ /* MDP cmd block enable */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); if (mddi_pipe == NULL) { ptype = <API key>(mfd->fb_imgType); if (ptype < 0) printk(KERN_INFO "%s: format2type failed\n", __func__); pipe = <API key>(ptype, MDP4_MIXER0); if (pipe == NULL) printk(KERN_INFO "%s: pipe_alloc failed\n", __func__); pipe->pipe_used++; pipe->mixer_num = MDP4_MIXER0; pipe->src_format = mfd->fb_imgType; <API key>(pipe->mixer_num, MDP4_PANEL_MDDI); ret = <API key>(pipe); if (ret < 0) printk(KERN_INFO "%s: format2type failed\n", __func__); mddi_pipe = pipe; /* keep it */ mddi_pipe->blt_end = 1; /* mark as end */ mddi_ld_param = 0; mddi_vdo_packet_reg = mfd->panel_info.mddi.vdopkt; if (mdp_hw_revision == MDP4_REVISION_V2_1) { uint32 data; data = inpdw(MDP_BASE + 0x0028); data &= ~0x0300; /* bit 8, 9, MASTER4 */ if (mfd->fbi->var.xres == 540) /* qHD, 540x960 */ data |= 0x0200; else data |= 0x0100; MDP_OUTP(MDP_BASE + 0x00028, data); } if (mfd->panel_info.type == MDDI_PANEL) { if (mfd->panel_info.pdest == DISPLAY_1) mddi_ld_param = 0; else mddi_ld_param = 1; } else { mddi_ld_param = 2; } MDP_OUTP(MDP_BASE + 0x00090, mddi_ld_param); if (mfd->panel_info.bpp == 24) MDP_OUTP(MDP_BASE + 0x00094, (<API key> << 16) | mddi_vdo_packet_reg); else if (mfd->panel_info.bpp == 16) MDP_OUTP(MDP_BASE + 0x00094, (<API key> << 16) | mddi_vdo_packet_reg); else MDP_OUTP(MDP_BASE + 0x00094, (<API key> << 16) | mddi_vdo_packet_reg); MDP_OUTP(MDP_BASE + 0x00098, 0x01); } else { pipe = mddi_pipe; } /* 0 for dma_p, client_id = 0 */ MDP_OUTP(MDP_BASE + 0x00090, 0); src = (uint8 *) iBuf->buf; #ifdef WHOLESCREEN { struct fb_info *fbi; fbi = mfd->fbi; pipe->src_height = fbi->var.yres; pipe->src_width = fbi->var.xres; pipe->src_h = fbi->var.yres; pipe->src_w = fbi->var.xres; pipe->src_y = 0; pipe->src_x = 0; pipe->dst_h = fbi->var.yres; pipe->dst_w = fbi->var.xres; pipe->dst_y = 0; pipe->dst_x = 0; pipe->srcp0_addr = (uint32)src; pipe->srcp0_ystride = fbi->fix.line_length; } #else if (mdp4_overlay_active(MDP4_MIXER0)) { struct fb_info *fbi; fbi = mfd->fbi; pipe->src_height = fbi->var.yres; pipe->src_width = fbi->var.xres; pipe->src_h = fbi->var.yres; pipe->src_w = fbi->var.xres; pipe->src_y = 0; pipe->src_x = 0; pipe->dst_h = fbi->var.yres; pipe->dst_w = fbi->var.xres; pipe->dst_y = 0; pipe->dst_x = 0; pipe->srcp0_addr = (uint32) src; pipe->srcp0_ystride = fbi->fix.line_length; } else { /* starting input address */ src += (iBuf->dma_x + iBuf->dma_y * iBuf->ibuf_width) * iBuf->bpp; pipe->src_height = iBuf->dma_h; pipe->src_width = iBuf->dma_w; pipe->src_h = iBuf->dma_h; pipe->src_w = iBuf->dma_w; pipe->src_y = 0; pipe->src_x = 0; pipe->dst_h = iBuf->dma_h; pipe->dst_w = iBuf->dma_w; pipe->dst_y = iBuf->dma_y; pipe->dst_x = iBuf->dma_x; pipe->srcp0_addr = (uint32) src; pipe->srcp0_ystride = iBuf->ibuf_width * iBuf->bpp; } #endif pipe->mixer_stage = <API key>; <API key>(pipe); mdp4_mixer_stage_up(pipe); <API key>(pipe); <API key>(pipe); <API key>(mfd, 0); <API key>(mfd, pipe, 0); /* MDP cmd block disable */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } int <API key>(int *off) { if (mdp_hw_revision < MDP4_REVISION_V2_1) { /* need dmas dmap switch */ if (mddi_pipe->blt_end || (<API key>(mddi_pipe->mixer_num) == 0)) { *off = -1; return -EINVAL; } } else { /* no dmas dmap switch */ if (mddi_pipe->blt_end) { *off = -1; return -EINVAL; } } if (mddi_pipe->blt_cnt & 0x01) *off = mddi_pipe->src_height * mddi_pipe->src_width * 3; else *off = 0; return 0; } void <API key>(ulong addr) { unsigned long flag; spin_lock_irqsave(&mdp_spin_lock, flag); if (addr) { mdp_pipe_ctrl(MDP_DMA2_BLOCK, MDP_BLOCK_POWER_ON, FALSE); mdp_intr_mask |= INTR_DMA_P_DONE; outp32(MDP_INTR_ENABLE, mdp_intr_mask); mdp_pipe_ctrl(MDP_DMA2_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); mddi_pipe->blt_cnt = 0; mddi_pipe->blt_end = 0; mddi_pipe->blt_addr = addr; } else { mddi_pipe->blt_end = 1; /* mark as end */ } <API key>(&mdp_spin_lock, flag); } void mdp4_blt_xy_update(struct mdp4_overlay_pipe *pipe) { uint32 off, addr; int bpp; char *overlay_base; if (pipe->blt_addr == 0) return; #ifdef BLT_RGB565 bpp = 2; /* overlay ouput is RGB565 */ #else bpp = 3; /* overlay ouput is RGB888 */ #endif off = 0; if (pipe->dmap_cnt & 0x01) off = pipe->src_height * pipe->src_width * bpp; addr = pipe->blt_addr + off; /* dmap */ MDP_OUTP(MDP_BASE + 0x90008, addr); /* overlay 0 */ overlay_base = MDP_BASE + <API key>;/* 0x10000 */ outpdw(overlay_base + 0x000c, addr); outpdw(overlay_base + 0x001c, addr); } /* * mdp4_dmap_done_mddi: called from isr */ void <API key>(void) { if (mddi_pipe->blt_end) { mddi_pipe->blt_addr = 0; mdp_intr_mask &= ~INTR_DMA_P_DONE; outp32(MDP_INTR_ENABLE, mdp_intr_mask); <API key>(mddi_pipe); <API key>(mddi_pipe); } /* * single buffer, no need to increase * mdd_pipe->dmap_cnt here */ } /* * <API key>: called from isr */ void <API key>(struct mdp_dma_data *dma) { <API key>(MDP_OVERLAY0_TERM); dma->busy = FALSE; /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption start */ mutex_unlock(&<API key>); /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption end */ complete(&dma->comp); mdp_pipe_ctrl(MDP_OVERLAY0_BLOCK, MDP_BLOCK_POWER_OFF, TRUE); if (busy_wait_cnt) busy_wait_cnt pr_debug("%s: ISR-done\n", __func__); if (mddi_pipe->blt_addr) { if (mddi_pipe->blt_cnt == 0) { <API key>(mddi_pipe); <API key>(mddi_pipe); mddi_pipe->ov_cnt = 0; mddi_pipe->dmap_cnt = 0; /* BLT start from next frame */ } else { mdp_pipe_ctrl(MDP_DMA2_BLOCK, MDP_BLOCK_POWER_ON, FALSE); mdp4_blt_xy_update(mddi_pipe); outpdw(MDP_BASE + 0x000c, 0x0); /* start DMAP */ } mddi_pipe->blt_cnt++; mddi_pipe->ov_cnt++; } } void <API key>(void) { if (mddi_mfd == NULL) return; pr_debug("%s: resotre, pid=%d\n", __func__, current->pid); if (mddi_mfd->panel_power_on == 0) return; if (mddi_mfd && mddi_pipe) { <API key>(mddi_mfd); <API key>(mddi_mfd); <API key>(mddi_mfd, mddi_pipe); mddi_mfd->dma_update_flag = 1; } if (mdp_hw_revision < MDP4_REVISION_V2_1) /* need dmas dmap switch */ <API key>(); } /* * <API key>: check mddi link activity * dsi link is a shared resource and it can only be used * while it is in idle state. * ov_mutex need to be acquired before call this function. */ void <API key>(struct msm_fb_data_type *mfd) { unsigned long flag; int need_wait = 0; pr_debug("%s: START, pid=%d\n", __func__, current->pid); spin_lock_irqsave(&mdp_spin_lock, flag); if (mfd->dma->busy == TRUE) { if (busy_wait_cnt == 0) INIT_COMPLETION(mfd->dma->comp); busy_wait_cnt++; need_wait++; } <API key>(&mdp_spin_lock, flag); if (need_wait) { /* wait until DMA finishes the current job */ pr_debug("%s: PENDING, pid=%d\n", __func__, current->pid); wait_for_completion(&mfd->dma->comp); } pr_debug("%s: DONE, pid=%d\n", __func__, current->pid); } void <API key>(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { pr_debug("%s: pid=%d\n", __func__, current->pid); <API key>(mfd, pipe); } void <API key>(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { pr_debug("%s: pid=%d\n", __func__, current->pid); <API key>(mfd, pipe); } void <API key>(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { /* change mdp clk while mdp is idle` */ mdp4_set_perf_level(); if (mdp_hw_revision == MDP4_REVISION_V2_1) { if (<API key>(<API key>)) { uint32 data; data = inpdw(MDP_BASE + 0x0028); data &= ~0x0300; /* bit 8, 9, MASTER4 */ if (mfd->fbi->var.xres == 540) /* qHD, 540x960 */ data |= 0x0200; else data |= 0x0100; MDP_OUTP(MDP_BASE + 0x00028, data); <API key>(<API key>, false); } if (<API key>(<API key>)) { uint32 data; data = inpdw(MDP_BASE + 0x0028); data &= ~0x0300; /* bit 8, 9, MASTER4 */ MDP_OUTP(MDP_BASE + 0x00028, data); <API key>(<API key>, false); } } mdp_enable_irq(MDP_OVERLAY0_TERM); mfd->dma->busy = TRUE; /* start OVERLAY pipe */ mdp_pipe_kickoff(MDP_OVERLAY0_TERM, mfd); mdp4_stat.kickoff_ov0++; } void <API key>(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { MDPIBUF *iBuf = &mfd->ibuf; uint32 outBpp = iBuf->bpp; uint16 mddi_vdo_packet_reg; uint32 dma_s_cfg_reg; dma_s_cfg_reg = 0; if (mfd->fb_imgType == MDP_RGBA_8888) dma_s_cfg_reg |= <API key>; /* on purpose */ else if (mfd->fb_imgType == MDP_BGR_565) dma_s_cfg_reg |= <API key>; else dma_s_cfg_reg |= <API key>; if (outBpp == 4) dma_s_cfg_reg |= (1 << 26); /* xRGB8888 */ else if (outBpp == 2) dma_s_cfg_reg |= <API key>; dma_s_cfg_reg |= DMA_DITHER_EN; /* MDP cmd block enable */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* PIXELSIZE */ MDP_OUTP(MDP_BASE + 0xa0004, (pipe->dst_h << 16 | pipe->dst_w)); MDP_OUTP(MDP_BASE + 0xa0008, pipe->srcp0_addr); /* ibuf address */ MDP_OUTP(MDP_BASE + 0xa000c, pipe->srcp0_ystride);/* ystride */ if (mfd->panel_info.bpp == 24) { dma_s_cfg_reg |= DMA_DSTC0G_8BITS | /* 666 18BPP */ DMA_DSTC1B_8BITS | DMA_DSTC2R_8BITS; } else if (mfd->panel_info.bpp == 18) { dma_s_cfg_reg |= DMA_DSTC0G_6BITS | /* 666 18BPP */ DMA_DSTC1B_6BITS | DMA_DSTC2R_6BITS; } else { dma_s_cfg_reg |= DMA_DSTC0G_6BITS | /* 565 16BPP */ DMA_DSTC1B_5BITS | DMA_DSTC2R_5BITS; } MDP_OUTP(MDP_BASE + 0xa0010, (pipe->dst_y << 16) | pipe->dst_x); /* 1 for dma_s, client_id = 0 */ MDP_OUTP(MDP_BASE + 0x00090, 1); mddi_vdo_packet_reg = mfd->panel_info.mddi.vdopkt; if (mfd->panel_info.bpp == 24) MDP_OUTP(MDP_BASE + 0x00094, (<API key> << 16) | mddi_vdo_packet_reg); else if (mfd->panel_info.bpp == 16) MDP_OUTP(MDP_BASE + 0x00094, (<API key> << 16) | mddi_vdo_packet_reg); else MDP_OUTP(MDP_BASE + 0x00094, (<API key> << 16) | mddi_vdo_packet_reg); MDP_OUTP(MDP_BASE + 0x00098, 0x01); MDP_OUTP(MDP_BASE + 0xa0000, dma_s_cfg_reg); <API key>(mfd, pipe, 1); /* MDP cmd block disable */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } void <API key>(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { /* change mdp clk while mdp is idle` */ mdp4_set_perf_level(); mdp_enable_irq(MDP_DMA_S_TERM); mfd->dma->busy = TRUE; mfd->ibuf_flushed = TRUE; /* start dma_s pipe */ mdp_pipe_kickoff(MDP_DMA_S_TERM, mfd); mdp4_stat.kickoff_dmas++; /* wait until DMA finishes the current job */ wait_for_completion(&mfd->dma->comp); mdp_disable_irq(MDP_DMA_S_TERM); } void <API key>(void) { /* mutex held by caller */ if (mddi_mfd && mddi_pipe) { <API key>(mddi_mfd); <API key>(mddi_mfd, mddi_pipe); <API key>(mddi_mfd, mddi_pipe); mddi_mfd->dma_update_flag = 1; } } void mdp4_mddi_overlay(struct msm_fb_data_type *mfd) { mutex_lock(&mfd->dma->ov_mutex); if (mfd && mfd->panel_power_on) { <API key>(mfd); <API key>(mfd); if (mdp_hw_revision < MDP4_REVISION_V2_1) { /* dmas dmap switch */ if (<API key>(mddi_pipe->mixer_num) == 0) { <API key>(mfd, mddi_pipe); <API key>(mfd, mddi_pipe); } else <API key>(mfd, mddi_pipe); } else /* no dams dmap switch */ <API key>(mfd, mddi_pipe); /* signal if pan function is waiting for the update completion */ if (mfd->pan_waiting) { mfd->pan_waiting = FALSE; complete(&mfd->pan_comp); } } mutex_unlock(&mfd->dma->ov_mutex); } int <API key>(struct fb_info *info, struct fb_cursor *cursor) { struct msm_fb_data_type *mfd = info->par; mutex_lock(&mfd->dma->ov_mutex); if (mfd && mfd->panel_power_on) { <API key>(mfd); <API key>(info, cursor); } mutex_unlock(&mfd->dma->ov_mutex); return 0; }
<?php get_header(); ?> <div id="primary" class="content-area"> <?php if ( have_posts() ) : ?> <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'page-templates/partials/content', 'page' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || '0' != get_comments_number() ) : comments_template(); endif; ?> <?php endwhile; ?> <?php else : ?> <?php get_template_part( 'partials/content', 'none' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || '0' != get_comments_number() ) : comments_template(); endif; ?> <?php endif; ?> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
package org.nla.tarotdroid.lib.helpers; import static com.google.common.base.Preconditions.checkArgument; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; /** * Network and internet connexion helper class. */ public class ConnexionHelper { /** * Checking for all possible internet providers * **/ public static boolean <API key>(Context context) { checkArgument(context != null, "context is null"); boolean toReturn = false; ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.<API key>); if (connectivity != null) { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) for (int i = 0; i < info.length; i++) if (info[i].getState() == NetworkInfo.State.CONNECTED) { toReturn = true; break; } } return toReturn; } }
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_18) on Tue Nov 02 13:16:53 CET 2010 --> <TITLE> com.redhat.rhn.common.filediff Class Hierarchy </TITLE> <META NAME="date" CONTENT="2010-11-02"> <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="com.redhat.rhn.common.filediff Class Hierarchy"; } } </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"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&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;<A HREF="../../../../../com/redhat/rhn/common/errors/test/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../com/redhat/rhn/common/filediff/test/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?com/redhat/rhn/common/filediff/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.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> Hierarchy For Package com.redhat.rhn.common.filediff </H2> </CENTER> <DL> <DT><B>Package Hierarchies:</B><DD><A HREF="../../../../../overview-tree.html">All Packages</A></DL> <HR> <H2> Class Hierarchy </H2> <UL> <LI TYPE="circle">java.lang.Object<UL> <LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/Diff.html" title="class in com.redhat.rhn.common.filediff"><B>Diff</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/Differ.html" title="class in com.redhat.rhn.common.filediff"><B>Differ</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/Edit.html" title="class in com.redhat.rhn.common.filediff"><B>Edit</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/FileLines.html" title="class in com.redhat.rhn.common.filediff"><B>FileLines</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/Hunk.html" title="class in com.redhat.rhn.common.filediff"><B>Hunk</B></A><UL> <LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/ChangeHunk.html" title="class in com.redhat.rhn.common.filediff"><B>ChangeHunk</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DeleteHunk.html" title="class in com.redhat.rhn.common.filediff"><B>DeleteHunk</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/InsertHunk.html" title="class in com.redhat.rhn.common.filediff"><B>InsertHunk</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/MatchHunk.html" title="class in com.redhat.rhn.common.filediff"><B>MatchHunk</B></A></UL> <LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/RhnHtmlDiffWriter.html" title="class in com.redhat.rhn.common.filediff"><B>RhnHtmlDiffWriter</B></A> (implements com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffVisitor.html" title="interface in com.redhat.rhn.common.filediff">DiffVisitor</A>, com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffWriter.html" title="interface in com.redhat.rhn.common.filediff">DiffWriter</A>) <LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/RhnPatchDiffWriter.html" title="class in com.redhat.rhn.common.filediff"><B>RhnPatchDiffWriter</B></A> (implements com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffVisitor.html" title="interface in com.redhat.rhn.common.filediff">DiffVisitor</A>, com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffWriter.html" title="interface in com.redhat.rhn.common.filediff">DiffWriter</A>) <LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/Trace.html" title="class in com.redhat.rhn.common.filediff"><B>Trace</B></A></UL> </UL> <H2> Interface Hierarchy </H2> <UL> <LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffVisitor.html" title="interface in com.redhat.rhn.common.filediff"><B>DiffVisitor</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffWriter.html" title="interface in com.redhat.rhn.common.filediff"><B>DiffWriter</B></A></UL> <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"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&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;<A HREF="../../../../../com/redhat/rhn/common/errors/test/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../com/redhat/rhn/common/filediff/test/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?com/redhat/rhn/common/filediff/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.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> </BODY> </HTML>
<?php class SatellitePlugin { var $plugin_name; var $plugin_base; var $pre = 'Satellite'; var $debugging = false; var $menus = array(); var $latestorbit = 'jquery.orbit-1.3.1.js'; //var $latestorbit = 'orbit-min.js'; var $cssfile = 'orbit-css.php'; var $cssadmin = 'admin-styles.css'; var $sections = array( 'satellite' => 'satellite-slides', 'settings' => 'satellite', 'newgallery' => 'satellite-galleries', ); var $helpers = array('Ajax', 'Config', 'Db', 'Html', 'Form', 'Metabox', 'Version'); var $models = array('Slide','Gallery'); function register_plugin($name, $base) { $this->plugin_base = rtrim(dirname($base), DS); $this->initialize_classes(); $this->initialize_options(); if (function_exists('<API key>')) { $currentlocale = get_locale(); if (!empty($currentlocale)) { $moFile = dirname(__FILE__) . DS . "languages" . DS . SATL_PLUGIN_NAME . "-" . $currentlocale . ".mo"; if (@file_exists($moFile) && is_readable($moFile)) { load_textdomain(SATL_PLUGIN_NAME, $moFile); } } } if ($this->debugging == true) { global $wpdb; $wpdb->show_errors(); error_reporting(E_ALL); @ini_set('display_errors', 1); } $this->add_action('wp_head', 'enqueue_scripts', 1); $this->add_action('admin_head', 'add_admin_styles'); $this->add_action("admin_head", 'plupload_admin_head'); $this->add_action('admin_init', 'admin_scripts'); $this->add_filter('the_posts', '<API key>'); // the_posts gets triggered before wp_head $this->add_action('<API key>', "g_plupload_action"); return true; } function add_admin_styles() { $adminStyleUrl = SATL_PLUGIN_URL . '/css/' . $this -> cssadmin . '?v=' . SATL_VERSION; wp_register_style(SATL_PLUGIN_NAME . "_adstyle", $adminStyleUrl); wp_enqueue_style(SATL_PLUGIN_NAME . "_adstyle"); } function <API key>($posts){ if (empty($posts)) return $posts; $shortcode_found = false; // use this flag to see if styles and scripts need to be enqueued if ($this->get_option('shortreq') == 'N') { $shortcode_found = true; } else { foreach ($posts as $post) { if ( ( stripos($post->post_content, '[gpslideshow') !== false ) || ( stripos($post->post_content, '[satellite') !== false) || ( stripos($post->post_content, '[slideshow') !== false && $this->get_option('embedss') == "Y" ) ) { $shortcode_found = true; // bingo! $pID = $post->ID; break; } } } if ($shortcode_found) { $satlStyleFile = SATL_PLUGIN_DIR . '/css/' . $this -> cssfile; $satlStyleUrl = SATL_PLUGIN_URL . '/css/' . $this -> cssfile . '?v=' . SATL_VERSION . '&amp;pID=' . $pID; if ($_SERVER['HTTPS']) { $satlStyleUrl = str_replace("http:", "https:", $satlStyleUrl); } //$infogal = $this; if (file_exists($satlStyleFile)) { if ($styles = $this->get_option('styles')) { foreach ($styles as $skey => $sval) { $satlStyleUrl .= "&amp;" . $skey . "=" . urlencode($sval); } } $width_temp = $this->get_option('width_temp'); $height_temp = $this->get_option('height_temp'); $align_temp = $this->get_option('align_temp'); $nav_temp = $this->get_option('nav_temp'); //print_r($wp_query->current_post); if (is_array($width_temp)) { foreach ($width_temp as $skey => $sval) { if ($skey == $pID) $satlStyleUrl .= "&amp;width_temp=" . urlencode($sval); } } if (is_array($height_temp)) { foreach ($height_temp as $skey => $sval) { if ($skey == $pID) $satlStyleUrl .= "&amp;height_temp=" . urlencode($sval); } } if (is_array($align_temp)) { foreach ($align_temp as $skey => $sval) { if ($skey == $pID) $satlStyleUrl .= "&amp;align=" . urlencode($sval); } } if (is_array($nav_temp)) { foreach ($nav_temp as $skey => $sval) { if ($skey == $pID) $satlStyleUrl .= "&amp;nav=" . urlencode($sval); } } wp_register_style(SATL_PLUGIN_NAME . "_style", $satlStyleUrl); } // enqueue here wp_enqueue_style(SATL_PLUGIN_NAME . "_style"); wp_enqueue_script(SATL_PLUGIN_NAME . "_script", '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/js/' . $this->latestorbit, array('jquery'), SATL_VERSION); //wp_enqueue_script(SATL_PLUGIN_NAME . "_script"); } return $posts; } function init_class($name = null, $params = array()) { if (!empty($name)) { $name = $this->pre . $name; if (class_exists($name)) { if ($class = new $name($params)) { return $class; } } } $this->init_class('Country'); return false; } function initialize_classes() { if (!empty($this->helpers)) { foreach ($this->helpers as $helper) { $hfile = dirname(__FILE__) . DS . 'helpers' . DS . strtolower($helper) . '.php'; if (file_exists($hfile)) { require_once($hfile); if (empty($this->{$helper}) || !is_object($this->{$helper})) { $classname = $this->pre . $helper . 'Helper'; if (class_exists($classname)) { $this->{$helper} = new $classname; } } } } } if (!empty($this->models)) { foreach ($this->models as $model) { $mfile = dirname(__FILE__) . DS . 'models' . DS . strtolower($model) . '.php'; if (file_exists($mfile)) { require_once($mfile); if (empty($this->{$model}) || !is_object($this->{$model})) { $classname = $this->pre . $model; if (class_exists($classname)) { $this->{$model} = new $classname; } } } } } } function initialize_options() { $styles = array( 'width' => "450", 'height' => "300", 'thumbheight' => "75", 'thumbarea' => "275", 'thumbareamargin' => "30", 'thumbmargin' => "2", 'thumbspacing' => "5", 'thumbactive' => "#FFFFFF", 'thumbopacity' => "70", 'align' => "none", 'border' => "1px solid #CCCCCC", 'background' => "#000000", 'infotitle' => "2", 'infobackground' => "#000000", 'infocolor' => "#FFFFFF", 'playshow' => "A", 'navpush' => "0", 'infomin' => "Y" ); $this->add_option('styles', $styles); //General Settings $this->add_option('fadespeed', 10); $this->add_option('nav_opacity', 30); $this->add_option('navhover', 70); $this->add_option('nolinker', "N"); $this->add_option('nolinkpage', 0); $this->add_option('pagelink', "S"); $this->add_option('wpattach', "N"); $this->add_option('captionlink', "N"); $this->add_option('transition', "FB"); $this->add_option('information', "Y"); $this->add_option('infospeed', 10); $this->add_option('showhover', "P"); $this->add_option('thumbnails', "N"); $this->add_option('thumbposition', "bottom"); $this->add_option('thumbscrollspeed', 5); $this->add_option('autoslide', "Y"); $this->add_option('autoslide_temp', "Y"); $this->add_option('imagesbox', "T"); $this->add_option('autospeed', 10); $this->add_option('abscenter', "Y"); $this->add_option('embedss', "Y"); $this->add_option('satwiz', "Y"); $this->add_option('shortreq', "Y"); $this->add_option('ggljquery', "Y"); $this->add_option('splash', "N"); $this->add_option('stldb_version', "1.0"); // Orbit Only $this->add_option('autospeed2', 5000); $this->add_option('duration', 700); $this->add_option('othumbs', "B"); $this->add_option('bullcenter', "true"); //Multi-ImageSlide $this->add_option('multicols', 3); $this->add_option('dropshadow', 'N'); //Full Right / Left $this->add_option('thumbarea', 250); //Premium $this->add_option('custslide', 10); $this->add_option('preload', 'N'); $this->add_option('keyboard', 'N'); $this->add_option('manager', 'manage_options'); $this->add_option('nav', "on"); //$this->add_option('orbitinfo', 'Y'); //$this->add_option('orbitinfo_temp', 'Y'); } function render_msg($message = '') { $this->render('msg-top', array('message' => $message), true, 'admin'); } function render_err($message = '') { $this->render('err-top', array('message' => $message), true, 'admin'); } function redirect($location = '', $msgtype = '', $message = '') { $url = $location; if ($msgtype == "message") { $url .= '&' . $this->pre . 'updated=true'; } elseif ($msgtype == "error") { $url .= '&' . $this->pre . 'error=true'; } if (!empty($message)) { $url .= '&' . $this->pre . 'message=' . urlencode($message); } ?> <script type="text/javascript"> window.location = '<?php echo (empty($url)) ? get_option('home') : $url; ?>'; </script> <?php flush(); } function paginate($model = null, $fields = '*', $sub = null, $conditions = null, $searchterm = null, $per_page = 10, $order = array('modified', "DESC")) { global $wpdb; if (!empty($model)) { global $paginate; $paginate = $this->vendor('Paginate'); $paginate->table = $this->{$model}->table; $paginate->sub = (empty($sub)) ? $this->{$model}->controller : $sub; $paginate->fields = (empty($fields)) ? '*' : $fields; $paginate->where = (empty($conditions)) ? false : $conditions; $paginate->searchterm = (empty($searchterm)) ? false : $searchterm; $paginate->per_page = $per_page; $paginate->order = $order; $data = $paginate->start_paging($_GET[$this->pre . 'page']); if (!empty($data)) { $newdata = array(); foreach ($data as $record) { $newdata[] = $this->init_class($model, $record); } $data = array(); $data[$model] = $newdata; $data['Paginate'] = $paginate; } return $data; } return false; } function vendor($name = '', $folder = '') { if (!empty($name)) { $filename = 'class.' . strtolower($name) . '.php'; $filepath = rtrim(dirname(__FILE__), DS) . DS . 'vendors' . DS . $folder . ''; $filefull = $filepath . $filename; if (file_exists($filefull)) { require_once($filefull); $class = 'Satellite' . $name; if (${$name} = new $class) { return ${$name}; } } } return false; } function check_uploaddir() { if (!file_exists(SATL_UPLOAD_DIR)) { if (@mkdir(SATL_UPLOAD_DIR, 0777)) { @chmod(SATL_UPLOAD_DIR, 0755); return true; } else { $message = __('Uploads folder named "' . SATL_PLUGIN_NAME . '" cannot be created inside "' . SATL_UPLOAD_DIR, SATL_PLUGIN_NAME); $this->render_msg($message); } } return false; } function check_sgprodir() { $sgprodir = SATL_UPLOAD_DIR.'/../<API key>/'; if (file_exists($sgprodir) && $this->is_empty_folder(SATL_UPLOAD_DIR)) { if ($this->is_empty_folder($sgprodir)) { return false; } $message = __('Transitioning from <strong>Slideshow Gallery Pro</strong>? <a href="admin.php?page=satellite-slides&method=copysgpro">Copy Files</a> from your previous custom galleries', SATL_PLUGIN_NAME); $this->render_msg($message); } return false; } function is_empty_folder($folder){ $c=0; if(is_dir($folder) ){ $files = opendir($folder); while ($file=readdir($files)){$c++;} if ($c>2){ return false; }else{ return true; } } } function add_action($action, $function = null, $priority = 10, $params = 1) { if (add_action($action, array($this, (empty($function)) ? $action : $function), $priority, $params)) { return true; } return false; } function add_filter($filter, $function = null, $priority = 10, $params = 1) { if (add_filter($filter, array($this, (empty($function)) ? $filter : $function), $priority, $params)) { return true; } return false; } function admin_scripts() { if (!empty($_GET['page']) && in_array($_GET['page'], (array) $this->sections)) { wp_enqueue_script('autosave'); if ($_GET['page'] == 'satellite') { wp_enqueue_script('common'); wp_enqueue_script('wp-lists'); wp_enqueue_script('postbox'); wp_enqueue_script('settings-editor', '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/js/settings-editor.js', array('jquery'), SATL_VERSION); wp_enqueue_script('admin', '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/js/admin.js', array('jquery'), SATL_VERSION); } if ($_GET['page'] == "satellite-slides" && $_GET['method'] == "order") { wp_enqueue_script('jquery-ui-sortable'); } if ($_GET['page'] == "satellite-galleries") { wp_enqueue_script('plupload-all'); wp_enqueue_script('jquery-ui-sortable'); wp_enqueue_script('admin', '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/js/admin.js', array('jquery'), SATL_VERSION); } wp_enqueue_scripts(); //wp_enqueue_script('jquery-ui-sortable'); add_thickbox(); } } function enqueue_scripts() { if ($this->get_option('ggljquery') == "Y") { <API key>( 'jquery' ); wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'); } wp_enqueue_script('jquery'); if (SATL_PRO && ($this->get_option('preload') == 'Y')) { wp_register_script('satellite_preloader', '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/pro/preloader.js'); wp_enqueue_script('satellite_preloader'); } if ($this->get_option('imagesbox') == "T") add_thickbox(); return true; } function plupload_admin_head() { // place js config array for plupload $plupload_init = array( 'runtimes' => 'html5,silverlight,flash,html4', 'browse_button' => '<API key>', // will be adjusted per uploader 'container' => 'plupload-upload-ui', // will be adjusted per uploader 'drop_element' => 'drag-drop-area', // will be adjusted per uploader 'file_data_name' => 'async-upload', // will be adjusted per uploader 'multiple_queues' => true, 'max_file_size' => wp_max_upload_size() . 'b', 'url' => admin_url('admin-ajax.php'), 'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'), 'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'), 'filters' => array(array('title' => __('Allowed Files'), 'extensions' => '*')), 'multipart' => true, 'urlstream_upload' => true, 'multi_selection' => false, // will be added per uploader // additional post data to send to our ajax hook 'multipart_params' => array( '_ajax_nonce' => "", // will be added per uploader 'action' => 'plupload_action', // the ajax action name 'imgid' => 0 // will be added per uploader ) ); ?> <script type="text/javascript"> var <API key>=<?php echo json_encode($plupload_init); ?>; </script> <?php } function g_plupload_action() { // check ajax noonce $imgid = $_POST["imgid"]; check_ajax_referer($imgid . 'pluploadan'); // handle file upload $status = wp_handle_upload($_FILES[$imgid . 'async-upload'], array('test_form' => true, 'action' => 'plupload_action')); // send the uploaded file url in response echo $status['url']; exit; } function plugin_base() { return rtrim(dirname(__FILE__), '/'); } function url() { return rtrim(WP_PLUGIN_URL, '/') . '/' . substr(preg_replace("/\\" . DS . "/si", "/", $this->plugin_base()), strlen(ABSPATH)); } function add_option($name = '', $value = '') { if (add_option($this->pre . $name, $value)) { return true; } return false; } function update_option($name = '', $value = '') { if (update_option($this->pre . $name, $value)) { return true; } return false; } function get_option($name = '', $stripslashes = true) { if ($option = get_option($this->pre . $name)) { if (@unserialize($option) !== false) { return unserialize($option); } if ($stripslashes == true) { $option = stripslashes_deep($option); } return $option; } return false; } function debug($var = array()) { if ($this->debugging) { echo '<pre>' . print_r($var, true) . '</pre>'; return true; } return false; } function check_table( $model = null ) { global $wpdb; if ( !empty($model) ) { if ( !empty($this->fields) && is_array($this->fields ) ) { if ( /* !$wpdb->get_var("SHOW TABLES LIKE '" . $this->table . "'") ||*/ $this->get_option($model.'db_version') != SATL_VERSION ) { $query = "CREATE TABLE " . $this->table . " (\n"; $c = 1; foreach ( $this->fields as $field => $attributes ) { if ( $field != "key" ) { $query .= "`" . $field . "` " . $attributes . ""; //$query .= "`".$field . "` " . $attributes ; } else { $query .= "" . $attributes . ""; } if ($c < count($this->fields)) { $query .= ",\n"; } $c++; } $query .= ");"; if (!empty($query)) { $this->table_query[] = $query; } if (SATL_PRO) { if ( class_exists( 'SatellitePremium' ) ) { $satlprem = new SatellitePremium; $satlprem->check_pro_dirs(); } } if (!empty($this->table_query)) { require_once(ABSPATH . 'wp-admin'.DS.'includes'.DS.'upgrade.php'); dbDelta($this->table_query, true); $this -> update_option($model.'db_version', SATL_VERSION); $this -> update_option('stldb_version', SATL_VERSION); error_log("Updated slideshow satellite databases"); } } else { $field_array = $this->get_fields($this->table); foreach ($this->fields as $field => $attributes) { if ($field != "key") { $this->add_field($this->table, $field, $attributes); } } } } } return false; } function get_fields($table = null) { global $wpdb; if (!empty($table)) { $fullname = $table; if (($tablefields = mysql_list_fields(DB_NAME, $fullname, $wpdb->dbh)) !== false) { $columns = mysql_num_fields($tablefields); $field_array = array(); for ($i = 0; $i < $columns; $i++) { $fieldname = mysql_field_name($tablefields, $i); $field_array[] = $fieldname; } return $field_array; } } return false; } function delete_field($table = '', $field = '') { global $wpdb; if (!empty($table)) { if (!empty($field)) { $query = "ALTER TABLE `" . $wpdb->prefix . "" . $table . "` DROP `" . $field . "`"; if ($wpdb->query($query)) { return false; } } } return false; } function change_field($table = '', $field = '', $newfield = '', $attributes = "TEXT NOT NULL") { global $wpdb; if (!empty($table)) { if (!empty($field)) { if (!empty($newfield)) { $field_array = $this->get_fields($table); if (!in_array($field, $field_array)) { if ($this->add_field($table, $newfield)) { return true; } } else { $query = "ALTER TABLE `" . $table . "` CHANGE `" . $field . "` `" . $newfield . "` " . $attributes . ";"; if ($wpdb->query($query)) { return true; } } } } } return false; } function add_field($table = '', $field = '', $attributes = "TEXT NOT NULL") { global $wpdb; if (!empty($table)) { if (!empty($field)) { $field_array = $this->get_fields($table); if (!empty($field_array)) { if (!in_array($field, $field_array)) { $query = "ALTER TABLE `" . $table . "` ADD `" . $field . "` " . $attributes . ";"; if ($wpdb->query($query)) { return true; } } } } } return false; } function render($file = '', $params = array(), $output = true, $folder = 'admin') { if (!empty($file)) { $filename = $file . '.php'; $filepath = $this->plugin_base() . DS . 'views' . DS . $folder . DS; $filefull = $filepath . $filename; if (file_exists($filefull)) { if (!empty($params)) { foreach ($params as $pkey => $pval) { ${$pkey} = $pval; } } if ($output == false) { ob_start(); } include($filefull); if ($output == false) { $data = ob_get_clean(); return $data; } else { flush(); return true; } } } return false; } /** * Add Settings link to plugins - code from GD Star Ratings */ function <API key>($links, $file) { static $this_plugin; if (!$this_plugin) $this_plugin = plugin_basename(__FILE__); if ($file == $this_plugin) { $settings_link = '<a href="admin.php?page=satellite">' . __("Settings", SATL_PLUGIN_NAME) . '</a>'; array_unshift($links, $settings_link); } return $links; } } ?>
# -*- coding: UTF-8 -*- import re,os,urllib,urllib2,cookielib import util,resolver from provider import ContentProvider class <API key>(ContentProvider): def __init__(self,username=None,password=None,filter=None): ContentProvider.__init__(self,'hejbejse.tv','http: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.LWPCookieJar())) urllib2.install_opener(opener) def capabilities(self): return ['resolve','categories','list'] def categories(self): page = util.parse_html('http: result = [] for title,uri in [(x.h3.text,x.h3.a['href']) for x in page.select('div.entry5') if x.h3]: item = self.dir_item() item['title'] = title item['url'] = uri result.append(item) return result def list(self, url): url = self._url(url) page = util.parse_html(url) result = [] for title,uri in [(x.img['title'],x['href']) for x in page.select('div.entry3')[0].findAll('a')]: item = self.video_item() item['title'] = title item['url'] = uri result.append(item) return result def resolve(self,item,captcha_cb=None,select_cb=None): item = item.copy() url = self._url(item['url']) page = util.parse_html(url) result = [] data=str(page.select('div.entry3 > center')[0]) resolved = resolver.findstreams(data,['<iframe(.+?)src=[\"\'](?P<url>.+?)[\'\"]']) try: for i in resolved: item = self.video_item() item['title'] = i['name'] item['url'] = i['url'] item['quality'] = i['quality'] item['surl'] = i['surl'] result.append(item) except: print '===Unknown resolver===' if len(result)==1: return result[0] elif len(result) > 1 and select_cb: return select_cb(result)
# Wider Gravity Forms Stop Entries Selectively stop Gravity Forms entries being stored on your web server to comply with privacy and the GDPR. Gravity Forms is a wonderful plugin and each form submission is stored on your web server and is accessible through the admin area - which can be great if you have problems with the email address you have setup to receive form submissions. However, there is no easy way in the admin area to selectively stop entries being stored on your web server, it has to be done in code and is a bit of hassle - this plugin makes it easy to stop this potentially sensitive data being stored. Improve the privacy of your visitors form submissions and make your website comply with the GDPR - this plugin allows you to select individual Gravity Forms you have setup and stop these entries being stored through easy to use admin options. You will find the options under `Settings > Gravity Forms Stop Entries`. NOTE: Requires Gravity Forms v1.8 or newer!
<?php ?> <?php get_header(); ?> <div id="fullwidth"> <h2 class="<API key>"><?php the_title(); ?></h2> <div id="home1post"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="post"> <div class="entry"> <?php the_content('Read more'); ?> </div> </div> <?php endwhile; else : endif; ?> </div> <div id="fullwidth_blog"> <?php $exclude_categories = <API key>(); $temp = $wp_query; $wp_query = null; $wp_query = new WP_Query(); $wp_query->query('cat='.$exclude_categories.'&paged='.$paged); if ($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post(); ?> <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php global $more; $more = 0; blogBox_post_format(); ?> </div> <?php endwhile; ?> <?php if(function_exists('wp_pagenavi')) { echo '<div class="postpagenav">'; wp_pagenavi(); echo '</div>'; } else { ?> <div class="postpagenav"> <div class="left"><?php next_posts_link(__('&lt;&lt; older entries','blogBox') ); ?></div> <div class="right"><?php previous_posts_link(__(' newer entries &gt;&gt;','blogBox') ); ?></div> <br/> </div> <?php } ?> <?php $wp_query = null; $wp_query = $temp;?> <?php else : ?> <?php endif; ?> <br/> </div> </div> <?php get_footer(); ?>
<?php get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <section class="error-404 not-found"> <header class="page-header"> <h1 class="page-title"><?php esc_html_e( 'Oops! That page can&rsquo;t be found.', 'wapp' ); ?></h1> </header><!-- .page-header --> <div class="page-content"> <p><?php esc_html_e( 'It looks like nothing was found at this location. Maybe try one of the links below or a search?', 'wapp' ); ?></p> <?php get_search_form(); the_widget( '<API key>' ); // Only show the widget if site has multiple categories. if ( <API key>() ) : ?> <div class="widget widget_categories"> <h2 class="widget-title"><?php esc_html_e( 'Most Used Categories', 'wapp' ); ?></h2> <ul> <?php wp_list_categories( array( 'orderby' => 'count', 'order' => 'DESC', 'show_count' => 1, 'title_li' => '', 'number' => 10, ) ); ?> </ul> </div><!-- .widget --> <?php endif; /* translators: %1$s: smiley */ $archive_content = '<p>' . sprintf( esc_html__( 'Try looking in the monthly archives. %1$s', 'wapp' ), convert_smilies( ':)' ) ) . '</p>'; the_widget( 'WP_Widget_Archives', 'dropdown=1', "after_title=</h2>$archive_content" ); the_widget( 'WP_Widget_Tag_Cloud' ); ?> </div><!-- .page-content --> </section><!-- .error-404 --> </main><!-- #main --> </div><!-- #primary --> <?php get_footer();
-- phpMyAdmin SQL Dump -- version 3.3.9 -- http: -- Host: localhost -- Generation Time: Jun 16, 2011 at 10:05 AM SET SQL_MODE="<API key>"; /*!40101 SET @<API key>=@@<API key> */; /*!40101 SET @<API key>=@@<API key> */; /*!40101 SET @<API key>=@@<API key> */; /*!40101 SET NAMES utf8 */; -- Database: `sqlparser` -- Table structure for table `articles` CREATE TABLE IF NOT EXISTS `articles` ( `article_id` int(10) NOT NULL AUTO_INCREMENT, `article_format_id` int(10) NOT NULL, `article_title` varchar(150) NOT NULL, `article_body` text NOT NULL, `article_date` date NOT NULL, `article_cat_id` int(10) NOT NULL, `article_active` tinyint(1) NOT NULL, `article_user_id` int(10) NOT NULL, PRIMARY KEY (`article_id`), KEY `article_format_id` (`article_format_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ; -- Dumping data for table `articles` INSERT INTO `articles` (`article_id`, `article_format_id`, `article_title`, `article_body`, `article_date`, `article_cat_id`, `article_active`, `article_user_id`) VALUES (1, 2, 'Tinie Tempah, Arcade Fire score Brits doubles', 'Tinie Tempah and Arcade Fire were the major winners at tonight''s Brit Awards, taking home two trophies apiece.', '2011-02-15', 3, 1, 1),
# bzr support for dpkg-source # Based on Dpkg::Source::Package::V3_0::git, which is: # This program is free software; you can redistribute it and/or modify # (at your option) any later version. # This program is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the package Dpkg::Source::Package::V3::Bzr; use strict; use warnings; our $VERSION = '0.01'; use Cwd; use File::Basename; use File::Find; use File::Temp qw(tempdir); use Dpkg::Gettext; use Dpkg::Compression; use Dpkg::ErrorHandling; use Dpkg::Source::Archive; use Dpkg::Exit qw(push_exit_handler pop_exit_handler); use Dpkg::Source::Functions qw(erasedir); use parent qw(Dpkg::Source::Package); our $<API key> = '0'; sub import { foreach my $dir (split(/:/, $ENV{PATH})) { if (-x "$dir/bzr") { return 1; } } error(g_('cannot unpack bzr-format source package because ' . 'bzr is not in the PATH')); } sub sanity_check { my $srcdir = shift; if (! -d "$srcdir/.bzr") { error(g_('source directory is not the top directory of a bzr repository (%s/.bzr not present), but Format bzr was specified'), $srcdir); } # Symlinks from .bzr to outside could cause unpack failures, or # point to files they shouldn't, so check for and don't allow. if (-l "$srcdir/.bzr") { error(g_('%s is a symlink'), "$srcdir/.bzr"); } my $abs_srcdir = Cwd::abs_path($srcdir); find(sub { if (-l) { if (Cwd::abs_path(readlink) !~ /^\Q$abs_srcdir\E(?:\/|$)/) { error(g_('%s is a symlink to outside %s'), $File::Find::name, $srcdir); } } }, "$srcdir/.bzr"); return 1; } sub can_build { my ($self, $dir) = @_; return (0, g_("doesn't contain a bzr repository")) unless -d "$dir/.bzr"; return 1; } sub do_build { my ($self, $dir) = @_; my @argv = @{$self->{options}{ARGV}}; # TODO: warn here? #my @tar_ignore = map { "--exclude=$_" } @{$self->{options}{tar_ignore}}; my $diff_ignore_regex = $self->{options}{diff_ignore_regex}; $dir =~ s{/+$}{}; # Strip trailing / my ($dirname, $updir) = fileparse($dir); if (scalar(@argv)) { usageerr(g_("-b takes only one parameter with format '%s'"), $self->{fields}{'Format'}); } my $sourcepackage = $self->{fields}{'Source'}; my $basenamerev = $self->get_basename(1); my $basename = $self->get_basename(); my $basedirname = $basename; $basedirname =~ s/_/-/; sanity_check($dir); my $old_cwd = getcwd(); chdir $dir or syserr(g_("unable to chdir to '%s'"), $dir); local $_; # Check for uncommitted files. # To support dpkg-source -i, remove any ignored files from the # output of bzr status. open(my $bzr_status_fh, '-|', 'bzr', 'status') or subprocerr('bzr status'); my @files; while (<$bzr_status_fh>) { chomp; next unless s/^ + if (! length $diff_ignore_regex || ! m/$diff_ignore_regex/o) { push @files, $_; } } close($bzr_status_fh) or syserr(g_('bzr status exited nonzero')); if (@files) { error(g_('uncommitted, not-ignored changes in working directory: %s'), join(' ', @files)); } chdir $old_cwd or syserr(g_("unable to chdir to '%s'"), $old_cwd); my $tmp = tempdir("$dirname.bzr.XXXXXX", DIR => $updir); push_exit_handler(sub { erasedir($tmp) }); my $tardir = "$tmp/$dirname"; system('bzr', 'branch', $dir, $tardir); subprocerr("bzr branch $dir $tardir") if $?; # Remove the working tree. system('bzr', 'remove-tree', $tardir); subprocerr("bzr remove-tree $tardir") if $?; # Some branch metadata files are unhelpful. unlink("$tardir/.bzr/branch/branch-name", "$tardir/.bzr/branch/parent"); # Create the tar file my $debianfile = "$basenamerev.bzr.tar." . $self->{options}{comp_ext}; info(g_('building %s in %s'), $sourcepackage, $debianfile); my $tar = Dpkg::Source::Archive->new(filename => $debianfile, compression => $self->{options}{compression}, compression_level => $self->{options}{comp_level}); $tar->create(chdir => $tmp); $tar->add_directory($dirname); $tar->finish(); erasedir($tmp); pop_exit_handler(); $self->add_file($debianfile); } # Called after a tarball is unpacked, to check out the working copy. sub do_extract { my ($self, $newdirectory) = @_; my $fields = $self->{fields}; my $dscdir = $self->{basedir}; my $basename = $self->get_basename(); my $basenamerev = $self->get_basename(1); my @files = $self->get_files(); if (@files > 1) { error(g_('format v3.0 uses only one source file')); } my $tarfile = $files[0]; my $comp_ext_regex = <API key>(); if ($tarfile !~ /^\Q$basenamerev\E\.bzr\.tar\.$comp_ext_regex$/) { error(g_('expected %s, got %s'), "$basenamerev.bzr.tar.$comp_ext_regex", $tarfile); } if ($self->{options}{no_overwrite_dir} and -e $newdirectory) { error(g_('unpack target exists: %s'), $newdirectory); } else { erasedir($newdirectory); } # Extract main tarball info(g_('unpacking %s'), $tarfile); my $tar = Dpkg::Source::Archive->new(filename => "$dscdir$tarfile"); $tar->extract($newdirectory); sanity_check($newdirectory); my $old_cwd = getcwd(); chdir($newdirectory) or syserr(g_("unable to chdir to '%s'"), $newdirectory); # Reconstitute the working tree. system('bzr', 'checkout'); subprocerr('bzr checkout') if $?; chdir $old_cwd or syserr(g_("unable to chdir to '%s'"), $old_cwd); } 1;
/*! \file vpHinkley.cpp \brief Definition of the vpHinkley class corresponding to the Hinkley's cumulative sum test. */ #include <visp/vpHinkley.h> #include <visp/vpDebug.h> #include <visp/vpIoTools.h> #include <visp/vpMath.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <cmath> // std::fabs #include <limits> // numeric_limits /* VP_DEBUG_MODE fixed by configure: 1: 2: 3: Print data */ /*! Constructor. Call init() to initialise the Hinkley's test and set \f$\alpha\f$ and \f$\delta\f$ to default values. By default \f$ \delta = 0.2 \f$ and \f$ \alpha = 0.2\f$. Use setDelta() and setAlpha() to modify these values. */ vpHinkley::vpHinkley() { init(); setAlpha(0.2); setDelta(0.2); } /*! Constructor. Call init() to initialise the Hinkley's test and set \f$\alpha\f$ and \f$\delta\f$ thresholds. \param alpha : \f$\alpha\f$ is a predefined threshold. \param delta : \f$\delta\f$ denotes the jump minimal magnitude that we want to detect. \sa setAlpha(), setDelta() */ vpHinkley::vpHinkley(double alpha, double delta) { init(); setAlpha(alpha); setDelta(delta); } /*! Call init() to initialise the Hinkley's test and set \f$\alpha\f$ and \f$\delta\f$ thresholds. \param alpha : \f$\alpha\f$ is a predefined threshold. \param delta : \f$\delta\f$ denotes the jump minimal magnitude that we want to detect. \sa setAlpha(), setDelta() */ void vpHinkley::init(double alpha, double delta) { init(); setAlpha(alpha); setDelta(delta); } /*! Destructor. */ vpHinkley::~vpHinkley() { } /*! Initialise the Hinkley's test by setting the mean signal value \f$m_0\f$ to zero as well as \f$S_k, M_k, T_k, N_k\f$. */ void vpHinkley::init() { nsignal = 0; mean = 0.0; Sk = 0; Mk = 0; Tk = 0; Nk = 0; } /*! Set the value of \f$\delta\f$, the jump minimal magnetude that we want to detect. \sa setAlpha() */ void vpHinkley::setDelta(double delta) { dmin2 = delta / 2; } /*! Set the value of \f$\alpha\f$, a predefined threshold. \sa setDelta() */ void vpHinkley::setAlpha(double alpha) { this->alpha = alpha; } /*! Perform the Hinkley test. A downward jump is detected if \f$ M_k - S_k > \alpha \f$. \param signal : Observed signal \f$ s(t) \f$. \sa setDelta(), setAlpha(), testUpwardJump() */ vpHinkley::vpHinkleyJumpType vpHinkley::testDownwardJump(double signal) { vpHinkleyJumpType jump = noJump; nsignal ++; // Signal length if (nsignal == 1) mean = signal; computeSk(signal); computeMk(); vpCDEBUG(2) << "alpha: " << alpha << " dmin2: " << dmin2 << " signal: " << signal << " Sk: " << Sk << " Mk: " << Mk; if ((Mk - Sk) > alpha) jump = downwardJump; #ifdef VP_DEBUG if (VP_DEBUG_MODE >=2) { switch(jump) { case noJump: std::cout << "noJump " << std::endl; break; case downwardJump: std::cout << "downWardJump " << std::endl; break; case upwardJump: std::cout << "upwardJump " << std::endl; break; } } #endif computeMean(signal); if (jump == downwardJump) { vpCDEBUG(2) << "\n*** Reset the Hinkley test ***\n"; Sk = 0; Mk = 0; nsignal = 0; } return (jump); } /*! Perform the Hinkley test. An upward jump is detected if \f$ T_k - N_k > \alpha \f$. \param signal : Observed signal \f$ s(t) \f$. \sa setDelta(), setAlpha(), testDownwardJump() */ vpHinkley::vpHinkleyJumpType vpHinkley::testUpwardJump(double signal) { vpHinkleyJumpType jump = noJump; nsignal ++; // Signal length if (nsignal == 1) mean = signal; computeTk(signal); computeNk(); vpCDEBUG(2) << "alpha: " << alpha << " dmin2: " << dmin2 << " signal: " << signal << " Tk: " << Tk << " Nk: " << Nk; if ((Tk - Nk) > alpha) jump = upwardJump; #ifdef VP_DEBUG if (VP_DEBUG_MODE >= 2) { switch(jump) { case noJump: std::cout << "noJump " << std::endl; break; case downwardJump: std::cout << "downWardJump " << std::endl; break; case upwardJump: std::cout << "upWardJump " << std::endl; break; } } #endif computeMean(signal); if (jump == upwardJump) { vpCDEBUG(2) << "\n*** Reset the Hinkley test ***\n"; Tk = 0; Nk = 0; nsignal = 0; } return (jump); } /*! Perform the Hinkley test. A downward jump is detected if \f$ M_k - S_k > \alpha \f$. An upward jump is detected if \f$ T_k - N_k > \alpha \f$. \param signal : Observed signal \f$ s(t) \f$. \sa setDelta(), setAlpha(), testDownwardJump(), testUpwardJump() */ vpHinkley::vpHinkleyJumpType vpHinkley::testDownUpwardJump(double signal) { vpHinkleyJumpType jump = noJump; nsignal ++; // Signal length if (nsignal == 1) mean = signal; computeSk(signal); computeTk(signal); computeMk(); computeNk(); vpCDEBUG(2) << "alpha: " << alpha << " dmin2: " << dmin2 << " signal: " << signal << " Sk: " << Sk << " Mk: " << Mk << " Tk: " << Tk << " Nk: " << Nk << std::endl; if ((Mk - Sk) > alpha) jump = downwardJump; else if ((Tk - Nk) > alpha) jump = upwardJump; #ifdef VP_DEBUG if (VP_DEBUG_MODE >= 2) { switch(jump) { case noJump: std::cout << "noJump " << std::endl; break; case downwardJump: std::cout << "downWardJump " << std::endl; break; case upwardJump: std::cout << "upwardJump " << std::endl; break; } } #endif computeMean(signal); if ((jump == upwardJump) || (jump == downwardJump)) { vpCDEBUG(2) << "\n*** Reset the Hinkley test ***\n"; Sk = 0; Mk = 0; Tk = 0; Nk = 0; nsignal = 0; // Debut modif FS le 03/09/2003 mean = signal; // Fin modif FS le 03/09/2003 } return (jump); } /*! Compute the mean value \f$m_0\f$ of the signal. The mean value must be computed before the jump is estimated on-line. \param signal : Observed signal \f$ s(t) \f$. */ void vpHinkley::computeMean(double signal) { // Debut modif FS le 03/09/2003 //if ( ((Mk-Sk) == 0) && ((Tk-Nk) == 0) ) if ( ( std::fabs(Mk-Sk) <= std::fabs(vpMath::maximum(Mk,Sk))*std::numeric_limits<double>::epsilon() ) && ( std::fabs(Tk-Nk) <= std::fabs(vpMath::maximum(Tk,Nk))*std::numeric_limits<double>::epsilon() ) ) // Fin modif FS le 03/09/2003 // Mise a jour de la moyenne. mean = (mean * (nsignal - 1) + signal) / (nsignal); } /*! Compute \f$S_k = \sum_{t=0}^{k} (s(t) - m_0 + \frac{\delta}{2})\f$ \param signal : Observed signal \f$ s(t) \f$. */ void vpHinkley::computeSk(double signal) { Sk += signal - mean + dmin2; } /*! Compute \f$M_k\f$, the maximum value of \f$S_k\f$. */ void vpHinkley::computeMk() { if (Sk > Mk) Mk = Sk; } /*! Compute \f$T_k = \sum_{t=0}^{k} (s(t) - m_0 - \frac{\delta}{2})\f$ \param signal : Observed signal \f$ s(t) \f$. */ void vpHinkley::computeTk(double signal) { Tk += signal - mean - dmin2; } /*! Compute \f$N_k\f$, the minimum value of \f$T_k\f$. */ void vpHinkley::computeNk() { if (Tk < Nk) Nk = Tk; } void vpHinkley::print(vpHinkley::vpHinkleyJumpType jump) { switch(jump) { case noJump : std::cout << " No jump detected " << std::endl ; break ; case downwardJump : std::cout << " Jump downward detected " << std::endl ; break ; case upwardJump : std::cout << " Jump upward detected " << std::endl ; break ; default: std::cout << " Jump detected " << std::endl ; break ; } }
<?php /** * The template for displaying all single posts. * * @package srh_framework */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'single' ); ?> <?php the_post_navigation(); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || get_comments_number() ) : comments_template(); endif; ?> <?php endwhile; // end of the loop. ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
//: containers/MapDataTest.java package course.containers; /* Added by Eclipse.py */ import java.util.*; import net.mindview.util.*; import static net.mindview.util.Print.*; class Letters implements Generator<Pair<Integer,String>>, Iterable<Integer> { private int size = 9; private int number = 1; private char letter = 'A'; public Pair<Integer,String> next() { return new Pair<Integer,String>( number++, "" + letter++); } public Iterator<Integer> iterator() { return new Iterator<Integer>() { public Integer next() { return number++; } public boolean hasNext() { return number < size; } public void remove() { throw new <API key>(); } }; } } public class MapDataTest { public static void main(String[] args) { // Pair Generator: print(MapData.map(new Letters(), 11)); // Two separate generators: print(MapData.map(new CountingGenerator.Character(), new RandomGenerator.String(3), 8)); // A key Generator and a single value: print(MapData.map(new CountingGenerator.Character(), "Value", 6)); // An Iterable and a value Generator: print(MapData.map(new Letters(), new RandomGenerator.String(3))); // An Iterable and a single value: print(MapData.map(new Letters(), "Pop")); } } /* Output: {1=A, 2=B, 3=C, 4=D, 5=E, 6=F, 7=G, 8=H, 9=I, 10=J, 11=K} {a=YNz, b=brn, c=yGc, d=FOW, e=ZnT, f=cQr, g=Gse, h=GZM} {a=Value, b=Value, c=Value, d=Value, e=Value, f=Value} {1=mJM, 2=RoE, 3=suE, 4=cUO, 5=neO, 6=EdL, 7=smw, 8=HLG} {1=Pop, 2=Pop, 3=Pop, 4=Pop, 5=Pop, 6=Pop, 7=Pop, 8=Pop} *///:~
#if !defined( HARDWARE_H ) #define HARDWARE_H /**< Include Guard */ #include "Config.h" #include <avr/io.h> // LED Constants #define RED_LED_PIN 4 #define RED_LED_MASK ( 1 << RED_LED_PIN ) #define RED_LED_DDR DDRG #define RED_LED_PORT PORTG #define BLUE_LED_PIN 3 #define BLUE_LED_MASK ( 1 << BLUE_LED_PIN ) #define BLUE_LED_DDR DDRG #define BLUE_LED_PORT PORTG #define YELLOW_LED_PIN 4 #define YELLOW_LED_MASK ( 1 << YELLOW_LED_PIN ) #define YELLOW_LED_DDR DDRB #define YELLOW_LED_PORT PORTB // Some convenience macros to turn the LEDs on/off. // Usage: LED_ON( BLUE ); // to turn on the blue LED. // Note: Setting the pin to 0 turns the LED on. #define LED_ON( color ) do { color ## _LED_PORT &= ~color ## _LED_MASK; } while (0) #define LED_OFF( color ) do { color ## _LED_PORT |= color ## _LED_MASK; } while (0) // Port registers. // Note: For input ports, writing a 1 to the PORT register casues an internal // pullup resistor to be activated. This feature also requires the // PUD bit to be set in the SFIOR register. // For the DDR pins, 0 = input, 1 = output // Port A if the one that's just pads on the bottom of the board #define PORTA_INIT 0xFF #define DDRA_INIT 0x00 // Port B has 3 PWM lines, and SPI. Pin 4 is connected to the Yellow LED // 7 - OC2 ATM_PWM1C // 6 - OC1B ATM_PWM1B // 5 - OC1A ATM_PWM1A // 4 - OC0 PB4 (Yellow LED) // 3 - MISO ATM_MISO // 2 - MOSI ATM_MOSI // 1 - SCK ATM_SCK // 0 - SS ATM_SS #define PORTB_INIT 0xFF // Enable pullups for inputs, Yellow LED off #define DDRB_INIT YELLOW_LED_MASK // Port C is available on the headers as 8 I/O lines. We'll assume all inputs // for now. #define PORTC_INIT 0xFF // enable pullups for all inputs #define DDRC_INIT 0x00 // Port D // 7 - T2 ATM_T2 // 6 - T1 ATM_T1 // 5 - PD5 ATM_PD5 // 4 - IC1 ATM_IC1 // 3 - INT3 ATM_TX1 // 2 - INT2 ATM_RX1 // 1 - INT1 ATM_SDA // 0 - INT0 ATM_SCL #define PORTD_INIT 0xFF // enable pullups for all inputs #define DDRD_INIT 0x00 // Port E // 7 - INT7 ATM_INT7 // 6 - INT6 ATM_INT6 // 5 - OC3C ATM_PWM3C // 4 - OC3B ATM_PWM3B // 3 - OC3A ATM_PWM3A // 2 - PE2 ATM_IRQ Used to interrupt gumstix // 1 - TXD ATM_TX0 // 0 - RXD ATM_RX0 #define PORTE_INIT 0xFF // enable pullups for all inputs #define DDRE_INIT 0x00 // Port F - A/D lines - could be used as GPIO // We disable all pullups by default so they don't mess with the A/D #define PORTF_INIT 0x00 // disable pullups for A/D channels #define DDRF_INIT 0x00 // Port G // 7 - N/A // 6 - N/A // 5 - N/A // 4 - TOSC1 ATM_PG4 - Red LED // 3 - TOSC2 ATM_PG3 - Blue LED // 2 - ALE ATM_PG2 // 1 - /RD ATM_PG1 // 0 - /WR ATM_PG0 #define PORTG_INIT 0xFF // Enable pullups for inputs, LEDs off #define DDRG_INIT ( RED_LED_MASK | BLUE_LED_MASK ) // Make LEDs outputs // ASSR - Asynchronous Status Register // TOSC1 & TOSC2 are connected to the Red/Blue LEDs so we need to set // AS0 to 0. AS0 is the only writable bit. #define ASSR_INIT 0x00 // ADC Settings #define ADC_PRESCALAR_2 (( 0 << ADPS2 ) | ( 0 << ADPS1 ) | ( 1 << ADPS0 )) #define ADC_PRESCALAR_4 (( 0 << ADPS2 ) | ( 1 << ADPS1 ) | ( 0 << ADPS0 )) #define ADC_PRESCALAR_8 (( 0 << ADPS2 ) | ( 1 << ADPS1 ) | ( 1 << ADPS0 )) #define ADC_PRESCALAR_16 (( 1 << ADPS2 ) | ( 0 << ADPS1 ) | ( 0 << ADPS0 )) #define ADC_PRESCALAR_32 (( 1 << ADPS2 ) | ( 0 << ADPS1 ) | ( 1 << ADPS0 )) #define ADC_PRESCALAR_64 (( 1 << ADPS2 ) | ( 1 << ADPS1 ) | ( 0 << ADPS0 )) #define ADC_PRESCALAR_128 (( 1 << ADPS2 ) | ( 1 << ADPS1 ) | ( 1 << ADPS0 )) #define ADCSR_INIT (( 1 << ADEN ) | ( 1 << ADSC ) | ADC_PRESCALAR_128 ) #define ADMUX_REF_AREF (( 0 << REFS1 ) | ( 0 << REFS0 )) #define ADMUX_REF_AVCC (( 0 << REFS1 ) | ( 1 << REFS0 )) #define ADMUX_REF_INTERNAL (( 1 << REFS1 ) | ( 1 << REFS0 )) #define ADMUX_INIT ADMUX_REF_AVCC // UART settings #define UART0_BAUD_RATE 38400 #define UART1_BAUD_RATE 38400 #define UART_DATA_BIT_8 (( 1 << UCSZ1 ) | ( 1 << UCSZ0 )) #define UART_PARITY_NONE (( 0 << UPM1 ) | ( 0 << UPM0 )) #define UART_STOP_BIT_1 ( 0 << USBS ) #define UBRR0_INIT (( CFG_CPU_CLOCK / 16 / UART0_BAUD_RATE ) - 1 ) #define UBRR1_INIT (( CFG_CPU_CLOCK / 16 / UART1_BAUD_RATE ) - 1 ) #define UCSR0A_INIT 0 #define UCSR0B_INIT (( 1 << RXCIE ) | ( 1 << RXEN ) | ( 1 << TXEN )) #define UCSR0C_INIT ( UART_DATA_BIT_8 | UART_PARITY_NONE | UART_STOP_BIT_1 ) #define UCSR1A_INIT 0 #define UCSR1B_INIT (( 1 << RXCIE ) | ( 1 << RXEN ) | ( 1 << TXEN )) #define UCSR1C_INIT ( UART_DATA_BIT_8 | UART_PARITY_NONE | UART_STOP_BIT_1 ) /** * Description of variable. */ void InitHardware( void ); #endif // HARDWARE_H
<?php class <API key> { public function __construct() { add_filter( '<API key>', array( $this, 'visual_composer' ) ); } public function visual_composer( $page_templates ) { if ( <API key>( 'visual-composer' ) ) { return $page_templates; } unset( $page_templates[ 'page-templates/template-home-vc.php' ] ); return $page_templates; } }
import socket import threading import time def tcplink(sock, addr): print 'Accept new connection from %s:%s...' % addr sock.send('Welcome!') while True: data = sock.recv(1024) time.sleep(1) if data == 'exit' or not data: break sock.send('Hello, %s!' % data) sock.close() print 'Connection from %s:%s closed.' % addr s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('127.0.0.1', 8888)) s.listen(5) print 'Waiting for connection...' while True: sock, addr = s.accept() t = threading.Thread(target=tcplink, args=(sock, addr)) t.start()
import os import sys import shutil import binascii import traceback import subprocess from win32com.client import Dispatch LAUNCHER_PATH = "C:\\Program Files\\Augur" DATA_PATH = os.path.join(os.path.expanduser('~'), 'AppData', 'Roaming', "Augur") PASSFILE = os.path.join(DATA_PATH, "password.txt") if getattr(sys, 'frozen', False): # we are running in a |PyInstaller| bundle BASEDIR = sys._MEIPASS else: # we are running in a normal Python environment BASEDIR = os.path.dirname(os.path.abspath(__file__)) GETH_EXE = os.path.join(BASEDIR, 'geth.exe') LAUNCHER_EXE = os.path.join(BASEDIR, 'augurlauncher.exe') def main(): # first make all the appropriate directories print("Making directories...") for d in LAUNCHER_PATH, DATA_PATH: print("Creating", d, end=" ", flush=True) os.mkdir(d) print("Success!") print("Generating random password file...", end=" ", flush=True) # then generate the password password = binascii.b2a_hex(os.urandom(32)) passfile = open(PASSFILE, "w") passfile.write(password.decode('ascii')) passfile.close() print("Success!") # Then copy ".exe"s to the launcher path exes = GETH_EXE, LAUNCHER_EXE results = [] for exe in exes: print("Copying", os.path.basename(exe), "to", LAUNCHER_PATH, "...", end=" ", flush=True) results.append(shutil.copy(exe, LAUNCHER_PATH)) print("Sucess!") print("Creating node account...", end=" ", flush=True) # create account on node p = subprocess.Popen([results[0], "--password", PASSFILE, "account", "new"]) p.wait() print("Success!") print("Creating shortcut...", end=" ", flush=True) desktop = os.path.join(os.path.expanduser('~'), 'Desktop') shortcut_path = os.path.join(desktop, "Augur Launcher.lnk") wDir = LAUNCHER_PATH shell = Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(shortcut_path) shortcut.Targetpath = results[1] shortcut.WorkingDirectory = wDir shortcut.IconLocation = results[1] shortcut.save() print("Success!") def uninstall(): paths = LAUNCHER_PATH, DATA_PATH for p in paths: print("Deleting", p, "...", end=" ", flush=True) shutil.rmtree(p) print("Success!") print("Removing desktop shortcut...", end=" ", flush=True) desktop = os.path.join(os.path.expanduser('~'), 'Desktop') shortcut_path = os.path.join(desktop, "Augur Launcher.lnk") os.remove(shortcut_path) print("Success!") if __name__ == '__main__': try: if len(sys.argv) == 2 and sys.argv[1] == 'uninstall': uninstall() elif len(sys.argv) == 1: main() else: assert len(sys.argv) <= 2, "wrong number of arguements!" except Exception as exc: traceback.print_exc() finally: os.system("pause") sys.exit(0)
import unittest from libs.funcs import * class TestFuncs(unittest.TestCase): def test_buildPaths(self): recPaths, repPaths, rouPaths, corePaths = buildPaths() findTxt = lambda x, y: x.find(y) > -1 assert findTxt(recPaths["Task"][0], "base") assert findTxt(recPaths["Department"][0], "StdPy") assert findTxt(recPaths["Department"][1], "standard") assert findTxt(repPaths["ListWindowReport"][0], "base") assert findTxt(repPaths["ExpensesList"][0], "StdPy") assert findTxt(repPaths["ExpensesList"][1], "standard") assert findTxt(rouPaths["GenNLT"][0], "StdPy") assert findTxt(rouPaths["GenNLT"][1], "standard") assert findTxt(corePaths["Field"][0], "embedded") self.assertFalse([k for (k, v) in rouPaths.iteritems() if findTxt(v[0], "base")]) #no routines in base def <API key>(self): recf, recd = <API key>("Invoice") assert all([f1 in recf for f1 in ("SalesMan", "InvoiceDate", "CustCode", "Currency", "ShiftDate", "OriginNr", "SerNr", "attachFlag")]) assert all([d in recd for d in ("CompoundItemCosts", "Payments", "Items", "Taxes", "Installs")]) recf, recd = <API key>("AccessGroup") assert all([f2 in recf for f2 in ("<API key>", "InitialModule", "Closed", "internalId")]) assert all([d in recd for d in ("PurchaseItems", "Customs", "Modules")]) def test_recordsInfo(self): recf, recd = getRecordsInfo("Department", RECORD) assert recf["Department"]["AutoCashCancel"] == "integer" #From StdPy assert recf["Department"]["DeptName"] == "string" #From standard assert recf["Department"]["Closed"] == "Boolean" #From Master assert recf["Department"]["internalId"] == "internalid" #From Record assert recd["Department"]["OfficePayModes"] == "<API key>" #Recordname from detail repf, repd = getRecordsInfo("Balance", REPORT) assert repf["Balance"]["LabelType"] == "string" #StdPy assert repf["Balance"]["ExplodeByLabel"] == "boolean" #Standard assert repf["Balance"]["internalId"] == "internalid" #Record assert not repd["Balance"] #Empty dict, no detail rouf, roud = getRecordsInfo("GenNLT", ROUTINE) assert rouf["GenNLT"]["ExcludeInvalid"] == "boolean" assert rouf["GenNLT"]["Table"] == "string" assert not roud["GenNLT"] rouf, roud = getRecordsInfo("LoginDialog", RECORD) assert rouf["LoginDialog"]["Password"] == "string" #embedded assert not roud["LoginDialog"] def test_classInfo(self): attr, meth = getClassInfo("Invoice") assert attr["DEBITNOTE"] == 2 assert attr["ATTACH_NOTE"] == 3 assert attr["rowNr"] == 0 assert attr["ParentInvoice"] == "SuperClass" assert isinstance(attr["DocTypes"], list) assert isinstance(attr["Origin"], dict) assert all([m in meth for m in ("getCardReader", "<API key>", "updateCredLimit", "generateTaxes", "roundValue", "getOriginType", "bring", "getXML", "createField")]) assert meth["fieldIsEditable"][0] == "self" assert meth["fieldIsEditable"][1] == "fieldname" assert meth["fieldIsEditable"][2] == {"rowfieldname":'None'} assert meth["fieldIsEditable"][3] == {"rownr":'None'} attr, meth = getClassInfo("User") assert attr["buffer"] == "RecordBuffer" assert all([m in meth for m in ("store", "save", "load", "hasField")]) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestFuncs)) return suite if __name__ == '__main__': unittest.main(defaultTest='test_suite')
<div class="twelve columns alpha"> <h3 class="headline">Descripción del Proyecto</h3><span class="line"></span><div class="clearfix"></div> <p>O Parque Tecnológico Itaipu (conocido como PTI) tiene un sitio web que proporciona mucha información sobre las actividades y los proyectos de PTI. <p>PTI ha identificado algunos problemas en su sitio, y presentado estas demandas a Celtab, para resolver estos problemas, así como mejorar el sitio en general, completamente en Drupal. <p>Por lo tanto, al ser necesario el desarrollo de algunas mejoras en Drupal y crear "plugins" para ayudar a la publicación de noticias y edición.</p> <p><strong>Investigadores:</strong> Cristhian Urunaga; Mario Villagra</p> </div> <!-- Job Description --> <div class="four columns omega"> <h3 class="headline">Detalles del Proyecto</h3><span class="line"></span><div class="clearfix"></div> <ul style="margin: 2px 0 18px 0;" class="list-3"> <li>PHP</li> <li>HTML</li> <li>CSS</li> <li>JavaScript</li> <li>CMS Drupal 7.x</li> </ul> <div class="clearfix"></div> </div>
var express = require('express'), formidable = require('formidable'), imgur = require('imgur'), fs = require('fs'), url = require('url'), bodyParser = require('body-parser'), router = express.Router(), uuid = require('node-uuid'), db = require('../lib/database'), tools = require('../lib/functions'); var connection = db.connectdb(); router.post('/upload', function(req, res) { res.writeHead(200, { 'Content-Type': 'text/html', 'Transfer-Encoding': 'chunked' }); var id = tools.makeid(); var owner = uuid.v1(); var form = new formidable.IncomingForm(), files = [], fields = []; form.uploadDir = 'tmp/'; form.on('field', function(field, value) { fields.push(value); }); form.on('file', function(field, file) { files.push(file); }); form.on('end', function() { res.end('http://' + req.headers.host + '/' + id); if (fields[0]) { owner = fields[0]; } files.forEach(function(file) { imgur.uploadFile(file.path) .then(function(json) { fs.unlink(file.path); connection.query("INSERT INTO `imgsnap`.`images` (`id`, `direct`, `timestamp`, `delete`, `owner`) VALUES ('" + connection.escape(id).replace(/'/g, '') + "', '" + connection.escape(json.data.link).replace(/'/g, '') + "', '" + connection.escape(json.data.datetime) + "', '" + connection.escape(json.data.deletehash).replace(/'/g, '') + "', '" + connection.escape(owner).replace(/'/g, '') + "')"); }) .catch(function(err) { fs.unlink(file.path); console.log(err); }); }); }); form.parse(req); }); router.get('/image/:id', function(req, res) { var id = req.params.id; connection.query('SELECT * FROM images WHERE id = ' + connection.escape(id), function(err, row, fields) { if (!row[0]) { res.json({ status: false }); } else { res.json({ status: true, direct: row[0].direct, timestamp: row[0].timestamp }); } }); }); router.get('/check', function(req, res) { res.writeHead(200, { 'Content-Type': 'text/html', 'Transfer-Encoding': 'chunked' }); res.end('Server Online'); }); module.exports = router;
# -*- coding: utf-8 -*- def outfit(): collection = [] for _ in range(0, 5): collection.append("Item{}".format(_)) return { "data": collection, } api = [ ('/outfit', 'outfit', outfit), ]
var UniteNivoPro = new function() { var t = this; var containerID = "slider_container"; var container, arrow_left, arrow_right, bullets_container; var caption_back, caption_text; var bulletsRelativeY = ""; /** * show slider view error, hide all the elements */ t.showSliderViewError = function(errorMessage) { jQuery("#config-document").hide(); UniteAdmin.showErrorMessage(errorMessage); } /** * main init of the object */ var init = function() { container = jQuery("#" + containerID); arrow_left = jQuery("#arrow_left"); arrow_right = jQuery("#arrow_right"); bullets_container = jQuery("#bullets_wrapper"); caption_back = jQuery("#caption_back"); caption_text = jQuery("#caption_text"); UniteAdmin.<API key>(); } /** * init visual form width */ t.initSliderView = function() { init(); //init the object - must call //update menu event jQuery("#visual").click(function() { setTimeout("UniteNivoPro.initAfterDelay()", 300); }); //update visual from fields updateFromFields(); initSliderEvents(); initVisualTabs(); //update arrows fields ) if not set setTimeout("UniteNivoPro.initAfterDelay()", 1000); } /** * init item view */ t.initItemView = function() { //operate on slide image change var obj = document.getElementById("jform_params_image"); obj.addEvent('change', function() { var urlImage = g_urlRoot + this.value; //trace(urlImage); jQuery("#<API key>").show().css("background-image", "url(\"" + urlImage + "\")"); }); } /** * on visual tab display event. update some fields */ t.onVisualDisplay = function() { <API key>(); bulletsAlignCenter(); } /** * init elements after delay */ t.initAfterDelay = function() { <API key>(); initBullets(); } /** * align the bullets to center */ var bulletsAlignCenter = function() { var align = jQuery("#<API key>").val(); if (align != "center") return(true); var data = getElementsData(); var bulletsX = Math.round((data.sliderWidth - data.bulletsWidth) / 2); bullets_container.css("left", bulletsX + "px"); updateBulletFields("center"); } /** * set bullets position by relative. */ var <API key> = function() { var data = getElementsData(); if (data.bulletsWidth == 0) return(true); if (bulletsRelativeY == "") return(true); var bulletsPosY = data.sliderHeight + bulletsRelativeY; bullets_container.css("top", bulletsPosY + "px"); updateBulletFields("relative"); } /** * do some actions on bullets align change */ var <API key> = function(align) { switch (align) { case "center": bullets_container.draggable("option", "axis", "y"); bulletsAlignCenter(); UniteAdmin.hideFormField("<API key>"); UniteAdmin.hideFormField("<API key>"); break; case "left": bullets_container.draggable("option", "axis", ""); UniteAdmin.showFormField("<API key>"); UniteAdmin.hideFormField("<API key>"); jQuery("#<API key>").css('display', 'inline'); break; case "right": bullets_container.draggable("option", "axis", ""); UniteAdmin.hideFormField("<API key>"); UniteAdmin.showFormField("<API key>"); jQuery("#<API key>").css('display', 'inline'); break; } } /** * on bullets drag event, update fields. */ var onBulletsDrag = function() { updateBulletFields("drag"); } /** * update relative y */ var <API key> = function() { var data = getElementsData(); bulletsRelativeY = data.bulletsY - data.sliderHeight; } /** * init the bullets position */ var initBullets = function() { var <API key> = "#<API key>"; var <API key> = "#<API key>"; var align = jQuery(<API key>).val(); //set bullets draggable var drag_options = {drag: onBulletsDrag}; if (align == "center") { bulletsAlignCenter(); //set draggable only y axis drag_options.axis = "y"; } jQuery(<API key>).change(function() { reverse_bullets(); }) //set select event jQuery(<API key>).change(function() { <API key>(this.value); }); //set draggable event bullets_container.draggable(drag_options); //show the bullets (if hidden) bullets_container.removeClass("invisible"); <API key>(); } /** * show some tab, set it selecetd class, and hide the others. */ var showVisualTab = function(linkID) { var link = jQuery("#" + linkID); if (!link.length) return(false); var tabID = link.data("tab"); //set togler selected jQuery("#tabs_visual li a").removeClass("selected"); link.addClass("selected"); //show panel jQuery(".visual_panel").removeClass("hidden").hide(); jQuery(tabID).show(); } /** * init visual tabs functionality */ var initVisualTabs = function() { var hash = location.hash; if (hash) { var linkID = hash.replace("#tab-", ""); showVisualTab(linkID); } //set event jQuery("#tabs_visual li a").click(function() { showVisualTab(this.id); }); } /** * on slider resize event. update all elements and fields accordingly */ var onSliderResize = function(event, ui) { //update fields widht / height if (event) { //only if came from event jQuery("#jform_visual_width").val(container.width()); jQuery("#jform_visual_height").val(container.height()); } <API key>("arrow_left"); <API key>(); bulletsAlignCenter(); } /** * init slider view onchange events */ var initSliderEvents = function() { //set fields onchange events var fields = "#visual_wrapper input"; jQuery(fields).blur(updateFromFields).click(updateFromFields); jQuery(fields).keypress(function(event) { if (event.keyCode == 13) updateFromFields(this); }); jQuery("#visual_wrapper select").change(updateFromFields); //set resizible event: container.resizable({resize: onSliderResize}); //set on color picker move event: UniteAdmin.onColorPickerMove(function() { updateFromFields(); }); //set arrows draggable jQuery("#arrow_left,#arrow_right").draggable({ drag: onArrowsDrag }); jQuery("#arrows_gocenter").click(arrowsToCenter); } /** * get all element sizes and positions. */ var getElementsData = function() { var data = {}; //slider data data.sliderWidth = Number(jQuery("#jform_visual_width").val()); data.sliderHeight = Number(jQuery("#jform_visual_height").val()); //arrows data var arrowLeftPos = arrow_left.position(); var arrowRightPos = arrow_right.position(); data.arrowLeftX = Math.round(arrowLeftPos.left); data.arrowLeftY = Math.round(arrowLeftPos.top); data.arrowRightX = Math.round(arrowRightPos.left); data.arrowRightY = Math.round(arrowRightPos.top); data.arrowLeftWidth = arrow_left.width(); data.arrowLeftHeight = arrow_left.height(); data.arrowRightWidth = arrow_right.width(); data.arrowRightHeight = arrow_right.height(); //bullets data: var bulletsPos = bullets_container.position(); data.bulletsWidth = bullets_container.width(); data.bulletsHeight = bullets_container.height(); data.bulletsX = Math.round(bulletsPos.left); data.bulletsY = Math.round(bulletsPos.top); return(data); } /** * get the arrows to center of the banner (y axes) */ var arrowsToCenter = function() { var data = getElementsData(); var arrowsNewY = Math.round(data.sliderHeight - data.arrowLeftHeight) / 2; arrow_right.css("top", arrowsNewY + "px"); arrow_left.css("top", arrowsNewY + "px"); //update position fields on the panel <API key>(); } /** * check arrows connection, and */ var <API key> = function(arrowID) { var freeDrag = jQuery("#<API key>").is(":checked"); if (freeDrag == true) { <API key>(); return(false); } var data = getElementsData(); if (arrowID == "arrow_left") { //left arrow is main. var arrowRightNewX = data.sliderWidth - data.arrowLeftX - data.arrowRightWidth; //set right arrow position arrow_right.css({"top": data.arrowLeftY + "px", "left": arrowRightNewX + "px"}); } else if (arrowID == "arrow_right") { //right arrow is main var arrowLeftNewX = data.sliderWidth - data.arrowRightX - data.arrowRightWidth; //set left arrow position arrow_left.css({"top": data.arrowRightY + "px", "left": arrowLeftNewX + "px"}); } <API key>(); } /** * on arrows drag event. update form fields, and operate arrow connections. */ var onArrowsDrag = function() { var arrowID = this.id; <API key>(arrowID); } /** * * update bullets position from the bullets */ var updateBulletFields = function(fromWhere) { //trace("update fields "+fromWhere);return(false); if (bullets_container.is(":visible") == false) return(true); var data = getElementsData(); //update fields: var bulletsRightX = data.sliderWidth - data.bulletsX - data.bulletsWidth; jQuery("#<API key>").val(data.bulletsY); jQuery("#<API key>").val(data.bulletsX); jQuery("#<API key>").val(bulletsRightX); //update relative option <API key>(); } /** * update arrows positions from the arrows */ var <API key> = function() { //don't update if the container not visible if (container.is(':visible') == false) return(true); if (arrow_left.is(':visible') == false) return(true); var data = getElementsData(); //set values jQuery("#<API key>").val(data.arrowLeftX); jQuery("#<API key>").val(data.arrowLeftY); jQuery("#<API key>").val(data.arrowRightX); jQuery("#<API key>").val(data.arrowRightY); } /** * hide arrows and disable panel elements */ var hideArrows = function() { if (arrow_left.is(':visible') == false) return(true); arrow_left.hide(); arrow_right.hide(); //hide arrow fields jQuery("#section_arrows").hide(); } /** * show arrows and enable panel elements */ var showArrows = function() { if (arrow_left.is(':visible') == true) return(true); arrow_left.show(); arrow_right.show(); //show arrow fields jQuery("#section_arrows").show(); } /** * update the container from fields. */ var updateFromFields = function(element) { if (element == undefined || element.id == undefined) element = this; var elemID = null; if (element.id != undefined) elemID = element.id; var width = jQuery("#jform_visual_width").val(); var height = jQuery("#jform_visual_height").val(); container.width(width).height(height); //width / heigth event switch (elemID) { case "jform_visual_width": case "jform_visual_height": onSliderResize(); break; } //update border <API key>(); //update shadow <API key>(); //update arrows <API key>(elemID); //update bullets <API key>(elemID); //set the bullets according the resize <API key>(); //update captions <API key>(elemID); //update caption text <API key>(); } /** * update caption text */ var <API key> = function() { var css = {}; if (caption_back.is(":visible") == false) return(true); //set color var textColor = jQuery("#<API key>").val(); css["color"] = textColor; //set text align var textAlign = jQuery("#<API key>").val(); css["text-align"] = textAlign; //set padding var textPadding = jQuery("#<API key>").val(); css["padding"] = textPadding + "px"; var fontSize = jQuery("#<API key>").val(); css["font-size"] = fontSize + "px"; //set the css caption_text.css(css); } /** * show the caption */ var showCaption = function() { if (caption_back.is(":visible") == true) return(false); caption_back.show(); } /** * hide the caption */ var hideCaption = function() { if (caption_back.is(":visible") == false) return(false); caption_back.hide(); } /** * update captions fields */ var <API key> = function(elemID) { var css = {}; if (elemID == "<API key>") { var hasCaption = jQuery("#<API key>").is(":checked"); if (hasCaption == true) showCaption(); else hideCaption(); } if (caption_back.is(":visible") == false) return(true); //set back color var backColor = jQuery("#<API key>").val(); css["background-color"] = backColor; //set alpha var alpha = jQuery("#<API key>").val(); var alpha = Number(alpha) / 100; caption_back.fadeTo(0, alpha); //set position: var position = jQuery("#<API key>").val(); if (position == "top") { css["bottom"] = ""; //set to top css["top"] = "0px"; } else { css["bottom"] = "0px"; //set to bottom css["top"] = ""; } //set the css caption_back.css(css); } /** * hide the bullets */ var hideBullets = function() { if (bullets_container.is(":visible") == false) return(true); //hide fields jQuery("#section_bullets").hide(); //hide bullets bullets_container.hide(); } /** * show the bullets */ var showBullets = function() { if (bullets_container.is(":visible") == true) return(true); //show fields jQuery("#section_bullets").show(); //show bullets bullets_container.removeClass("invisible").show(); } /** * update bullets fields */ var reverse_bullets = function() { var reverseChecked = jQuery("#<API key>").is(":checked"); var normal = 'normal'; var active = 'active'; if (reverseChecked) { normal = 'active'; active = 'normal'; } jQuery("#bullets_wrapper img").each(function(index, value) { if (index == 1) { jQuery(this).attr('src', jQuery(this).attr('src').replace(normal, active)); } else { jQuery(this).attr('src', jQuery(this).attr('src').replace(active, normal)); } }); } /** * update bullets fields */ var <API key> = function(elemID) { //trace("update bullets");return(false); switch (elemID) { case "<API key>": var showBulletsCheck = jQuery("#<API key>").is(":checked"); if (showBulletsCheck) showBullets(); else hideBullets(); break; } //skip invisible container if (bullets_container.is(':visible') == false) return(true); var bulletsY = jQuery("#<API key>").val(); switch (elemID) { default: case "<API key>": var bulletsX = jQuery("#<API key>").val(); break; case "<API key>": var data = getElementsData(); var bulletsRightX = jQuery("#<API key>").val(); var bulletsX = data.sliderWidth - data.bulletsWidth - bulletsRightX; break; case "<API key>": //set spacing var spacing = jQuery("#<API key>").val(); bullets_container.find("ul li:not(:first-child)").css("margin-left", spacing + "px"); bulletsAlignCenter(); break; } bullets_container.css({"top": bulletsY + "px", "left": bulletsX + "px"}); updateBulletFields("fields"); } /** * update border */ var <API key> = function() { var has_border = jQuery("#<API key>").is(':checked'); if (has_border == true) { var border_color = jQuery("#<API key>").val(); var border_size = jQuery("#<API key>").val(); container.css({"border-style": "solid", "border-width": border_size + "px", "border-color": border_color }); } else container.css({"border-style": "none"}); } /** * update shadow from fields */ var <API key> = function() { var has_shadow = jQuery("#<API key>").is(':checked'); if (has_shadow == true) { var shadow_color = jQuery("#<API key>").val(); var shadowProps = "0px 1px 5px 0px " + shadow_color; container.css({"box-shadow": shadowProps, "-moz-box-shadow": shadowProps, "-webkit-box-shadow": shadowProps}); } else container.css({"box-shadow": "none", "-moz-box-shadow": "none", "-webkit-box-shadow": "none"}); } /** * set arrows in the place of the fields */ var <API key> = function(elemID) { var showArrows_check = jQuery("#<API key>").is(":checked"); //check arrows hide / show if (elemID == "<API key>") { if (showArrows_check == false) hideArrows(); else showArrows(); } //position arrows if (arrow_left.is(':visible') == false) return(true); var arrowLeftX = jQuery("#<API key>").val(); var arrowLeftY = jQuery("#<API key>").val(); var arrowRightX = jQuery("#<API key>").val(); var arrowRightY = jQuery("#<API key>").val(); arrow_left.css({"top": arrowLeftY + "px", "left": arrowLeftX + "px"}); arrow_right.css({"top": arrowRightY + "px", "left": arrowRightX + "px"}); //operate errors connection: switch (elemID) { case "<API key>": case "<API key>": case "<API key>": <API key>("arrow_left"); break; case "<API key>": case "<API key>": <API key>("arrow_right"); break; } } /** * on arrows select event - update arrow pictures and change arrows set */ t.onArrowsSelect = function(data) { jQuery("#arrow_left").attr("src", data.url_left); jQuery("#arrow_right").attr("src", data.url_right); jQuery("#<API key>").val(data.arrowName); //align arrows setTimeout("UniteNivoPro.operationDelay('<API key>')", 500); } /** * on bullets select - take bullets html by ajax, and change the bullets. */ t.onBulletsSelect = function(setName) { var data = {setName: setName}; UniteAdmin.ajaxRequest("get_bullets_html", data, function(response) { jQuery("#bullets_wrapper").html(response.bullets_html); jQuery("#<API key>").val(setName); //align center after delay setTimeout("UniteNivoPro.operationDelay('bulletsAlignCenter')", 500); bulletsAlignCenter(); reverse_bullets(); }); } /** * align center after delay function */ t.operationDelay = function(operation) { switch (operation) { case "bulletsAlignCenter": bulletsAlignCenter(); break; case "<API key>": <API key>("arrow_left"); break; } } }
#ifndef _UMLNCRELATION_H #define _UMLNCRELATION_H #include "UmlBaseNcRelation.h" #include <qcstring.h> //This class manages 'relations' between non class objects // You can modify it as you want (except the constructor) class UmlNcRelation : public UmlBaseNcRelation { public: UmlNcRelation(void * id, const QCString & n) : UmlBaseNcRelation(id, n) {}; virtual int orderWeight(); }; #endif
package org.n52.series.spi.geo; import org.locationtech.jts.geom.Geometry; import org.n52.io.crs.CRSUtils; import org.n52.io.request.IoParameters; import org.n52.io.response.dataset.StationOutput; import org.opengis.referencing.FactoryException; import org.opengis.referencing.operation.TransformException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class <API key> { private static final Logger LOGGER = LoggerFactory.getLogger(<API key>.class); /** * @param station * the station to transform * @param parameters * the query containing CRS and how to handle axes order */ protected void transformInline(StationOutput station, IoParameters parameters) { String crs = parameters.getCrs(); if (CRSUtils.DEFAULT_CRS.equals(crs)) { // no need to transform return; } Geometry geometry = transform(station.getGeometry(), parameters); station.setValue(StationOutput.GEOMETRY, geometry, parameters, station::setGeometry); } public Geometry transform(Geometry geometry, IoParameters query) { String crs = query.getCrs(); if (CRSUtils.DEFAULT_CRS.equals(crs)) { // no need to transform return geometry; } return transformGeometry(query, geometry, crs); } private Geometry transformGeometry(IoParameters query, Geometry geometry, String crs) throws RuntimeException { try { CRSUtils crsUtils = query.isForceXY() ? CRSUtils.<API key>() : CRSUtils.<API key>(); return geometry != null ? crsUtils.<API key>(geometry, crs) : geometry; } catch (TransformException e) { <API key>(crs, e); } catch (FactoryException e) { LOGGER.debug("Couldn't create geometry factory", e); } return geometry; } private void <API key>(String crs, TransformException e) throws RuntimeException { throw new RuntimeException("Could not transform to requested CRS: " + crs, e); } }
wrapper around MPFIT (cmpfit) library, http: which is Levenberg-Marquardt implementation based on MINPACK-1 #ifndef FITYK_MPFIT_H_ #define FITYK_MPFIT_H_ #include "fit.h" #include "cmpfit/mpfit.h" namespace fityk { Wrapper around CMPFIT class MPfit : public Fit { public: MPfit(Full* F, const char* fname) : Fit(F, fname) {} virtual double run_method(std::vector<realt>* best_a); // implementation (must be public to be called inside callback function) int calculate(int m, int npar, double *par, double *deviates, double **derivs); int on_iteration(); virtual std::vector<double> <API key>(const std::vector<Data*>& datas); virtual std::vector<double> get_standard_errors(const std::vector<Data*>& datas); private: mp_config_struct mp_conf_; mp_result result_; int run_mpfit(const std::vector<Data*>& datas, const std::vector<realt>& parameters, const std::vector<bool>& param_usage, double *final_a=NULL); }; } // namespace fityk #endif
#include <stdio.h> #include <string.h> #include <stdlib.h> // prototypes declarations char** split(char *str, char *delimitators); int main(void) { char** result; char str[] = "1-0:0.0.1(132412515)\n1-0:0.2.3.4(654236517)\n"; result = split(str, "()\n"); for(size_t index = 0; *(result + index); index++) { printf("%s\n",*(result + index)); } free(result); return 0; } char** split(char *str, char* delimitators) { int count = 0; size_t index = 0; char **parse; char *tmp = str; char *token; char *last_delimitator; while(*tmp) { if(strchr(delimitators, *tmp) != NULL) { count++; last_delimitator = tmp; } tmp++; } //Espacio para datos ubicados luego del ultimo delimitador count += last_delimitator < (str + strlen(str) - 1); //Espacio para el caracter nulo del arreglo de punteros count++; parse = malloc(sizeof(char*) * count); token = strtok(str, delimitators); while(token != NULL) { *(parse + index++) = token; token = strtok(NULL, delimitators); } *(parse + index) = 0; return parse; }
package edu.ku.brc.af.ui.forms.persist; import static edu.ku.brc.helpers.XMLHelper.getAttr; import static edu.ku.brc.ui.UIHelper.<API key>; import static edu.ku.brc.ui.UIRegistry.getResourceString; import static org.apache.commons.lang.StringUtils.isEmpty; import static org.apache.commons.lang.StringUtils.isNotEmpty; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Vector; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ScrollPaneConstants; import javax.swing.table.DefaultTableModel; import org.apache.commons.betwixt.XMLIntrospector; import org.apache.commons.betwixt.io.BeanWriter; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.dom4j.Element; import org.dom4j.Node; import com.jgoodies.forms.builder.PanelBuilder; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import edu.ku.brc.af.core.db.DBFieldInfo; import edu.ku.brc.af.core.db.DBRelationshipInfo; import edu.ku.brc.af.core.db.DBTableChildIFace; import edu.ku.brc.af.core.db.DBTableIdMgr; import edu.ku.brc.af.core.db.DBTableInfo; import edu.ku.brc.af.prefs.AppPreferences; import edu.ku.brc.af.ui.forms.FormDataObjIFace; import edu.ku.brc.af.ui.forms.FormHelper; import edu.ku.brc.af.ui.forms.formatters.<API key>; import edu.ku.brc.af.ui.forms.formatters.UIFieldFormatterMgr; import edu.ku.brc.af.ui.forms.validation.<API key>; import edu.ku.brc.ui.CustomFrame; import edu.ku.brc.ui.UIHelper; import edu.ku.brc.ui.UIRegistry; import edu.ku.brc.helpers.XMLHelper; /** * Factory that creates Views from ViewSet files. This class uses the singleton ViewSetMgr to verify the View Set Name is unique. * If it is not unique than it throws an exception.<br> In this case a "form" is really the definition of a form. The form's object hierarchy * is used to creates the forms using Swing UI objects. The classes will also be used by the forms editor. * @code_status Beta ** * @author rods */ public class ViewLoader { public static final int DEFAULT_ROWS = 4; public static final int DEFAULT_COLS = 10; public static final int <API key> = 5; // Statics private static final Logger log = Logger.getLogger(ViewLoader.class); private static final ViewLoader instance = new ViewLoader(); private static final String ID = "id"; private static final String NAME = "name"; private static final String TYPE = "type"; private static final String LABEL = "label"; private static final String DESC = "desc"; private static final String TITLE = "title"; private static final String CLASSNAME = "class"; private static final String GETTABLE = "gettable"; private static final String SETTABLE = "settable"; private static final String INITIALIZE = "initialize"; private static final String DSPUITYPE = "dspuitype"; private static final String VALIDATION = "validation"; private static final String ISREQUIRED = "isrequired"; private static final String RESOURCELABELS = "useresourcelabels"; // Data Members protected boolean doingResourceLabels = false; protected String viewSetName = null; // Members needed for verification protected static boolean doFieldVerification = true; protected static boolean isTreeClass = false; protected static DBTableInfo fldVerTableInfo = null; protected static FormViewDef fldVerFormViewDef = null; protected static String colDefType = null; protected static CustomFrame verifyDlg = null; protected <API key> fldVerTableModel = null; // Debug //protected static ViewDef gViewDef = null; static { doFieldVerification = AppPreferences.getLocalPrefs().getBoolean("verify_field_names", false); } /** * Default Constructor * */ protected ViewLoader() { // do nothing } /** * Creates the view. * @param element the element to build the View from * @param altViewsViewDefName the hashtable to track the AltView's ViewDefName * @return the View * @throws Exception */ protected static ViewIFace createView(final Element element, final Hashtable<AltViewIFace, String> altViewsViewDefName) throws Exception { String name = element.attributeValue(NAME); String objTitle = getAttr(element, "objtitle", null); String className = element.attributeValue(CLASSNAME); String desc = getDesc(element); String businessRules = getAttr(element, "busrules", null); boolean isInternal = getAttr(element, "isinternal", true); DBTableInfo ti = DBTableIdMgr.getInstance().getByClassName(className); if (ti != null && StringUtils.isEmpty(objTitle)) { objTitle = ti.getTitle(); } View view = new View(instance.viewSetName, name, objTitle, className, businessRules != null ? businessRules.trim() : null, getAttr(element, "usedefbusrule", true), isInternal, desc); // Later we should get this from a properties file. if (ti != null) { view.setTitle(ti.getTitle()); } /*if (!isInternal) { System.err.println(StringUtils.replace(name, " ", "_")+"="+UIHelper.makeNamePretty(name)); }*/ Element altviews = (Element)element.selectSingleNode("altviews"); if (altviews != null) { AltViewIFace defaultAltView = null; AltView.CreationMode defaultMode = AltView.parseMode(getAttr(altviews, "mode", ""), AltViewIFace.CreationMode.VIEW); String selectorName = altviews.attributeValue("selector"); view.setDefaultMode(defaultMode); view.setSelectorName(selectorName); Hashtable<String, Boolean> nameCheckHash = new Hashtable<String, Boolean>(); // iterate through child elements for ( Iterator<?> i = altviews.elementIterator( "altview" ); i.hasNext(); ) { Element altElement = (Element) i.next(); AltView.CreationMode mode = AltView.parseMode(getAttr(altElement, "mode", ""), AltViewIFace.CreationMode.VIEW); String altName = altElement.attributeValue(NAME); String viewDefName = altElement.attributeValue("viewdef"); String title = altElement.attributeValue(TITLE); boolean isValidated = getAttr(altElement, "validated", mode == AltViewIFace.CreationMode.EDIT); boolean isDefault = getAttr(altElement, "default", false); // Make sure we only have one default view if (defaultAltView != null && isDefault) { isDefault = false; } // Check to make sure all the AlViews have different names. Boolean nameExists = nameCheckHash.get(altName); if (nameExists == null) // no need to check the boolean { AltView altView = new AltView(view, altName, title, mode, isValidated, isDefault, null); // setting a null viewdef altViewsViewDefName.put(altView, viewDefName); if (StringUtils.isNotEmpty(selectorName)) { altView.setSelectorName(selectorName); String selectorValue = altElement.attributeValue("selector_value"); if (StringUtils.isNotEmpty(selectorValue)) { altView.setSelectorValue(selectorValue); } else { FormDevHelper.appendFormDevError("Selector Value is missing for viewDefName["+viewDefName+"] altName["+altName+"]"); } } if (defaultAltView == null && isDefault) { defaultAltView = altView; } view.addAltView(altView); nameCheckHash.put(altName, true); } else { log.error("The altView name["+altName+"] already exists!"); } nameCheckHash.clear(); // why not? } // No default Alt View was indicated, so choose the first one (if there is one) if (defaultAltView == null && view.getAltViews() != null && view.getAltViews().size() > 0) { view.getAltViews().get(0).setDefault(true); } } return view; } /** * Creates a ViewDef * @param element the element to build the ViewDef from * @return a viewdef * @throws Exception */ private static ViewDef createViewDef(final Element element) throws Exception { String name = element.attributeValue(NAME); String className = element.attributeValue(CLASSNAME); String gettableClassName = element.attributeValue(GETTABLE); String settableClassName = element.attributeValue(SETTABLE); String desc = getDesc(element); String resLabels = getAttr(element, RESOURCELABELS, "false"); boolean useResourceLabels = resLabels.equals("true"); if (isEmpty(name)) { FormDevHelper.appendFormDevError("Name is null for element["+element.asXML()+"]"); return null; } if (isEmpty(className)) { FormDevHelper.appendFormDevError("className is null. name["+name+"] for element["+element.asXML()+"]"); return null; } if (isEmpty(gettableClassName)) { FormDevHelper.appendFormDevError("gettableClassName Name is null.name["+name+"] classname["+className+"]"); return null; } DBTableInfo tableinfo = DBTableIdMgr.getInstance().getByClassName(className); ViewDef.ViewType type = null; try { type = ViewDefIFace.ViewType.valueOf(element.attributeValue(TYPE)); } catch (Exception ex) { String msg = "view["+name+"] has illegal type["+element.attributeValue(TYPE)+"]"; log.error(msg, ex); FormDevHelper.appendFormDevError(msg, ex); return null; } ViewDef viewDef = null;//new ViewDef(type, name, className, gettableClassName, settableClassName, desc); switch (type) { case rstable: case formtable : case form : viewDef = createFormViewDef(element, type, name, className, gettableClassName, settableClassName, desc, useResourceLabels, tableinfo); break; case table : //view = createTableView(element, id, name, className, gettableClassName, settableClassName, // desc, instance.doingResourceLabels, isValidated); break; case field : //view = createFormView(FormView.ViewType.field, element, id, name, gettableClassName, settableClassName, // className, desc, instance.doingResourceLabels, isValidated); break; case iconview: viewDef = createIconViewDef(type, name, className, gettableClassName, settableClassName, desc, useResourceLabels); break; } return viewDef; } /** * Gets the optional description text * @param element the parent element of the desc node * @return the string of the text or null */ protected static String getDesc(final Element element) { String desc = null; Element descElement = (Element)element.selectSingleNode(DESC); if (descElement != null) { desc = descElement.getTextTrim(); } return desc; } /** * Fill the Vector with all the views from the DOM document * @param doc the DOM document conforming to form.xsd * @param views the list to be filled * @throws Exception for duplicate view set names or if a Form ID is not unique */ public static String getViews(final Element doc, final Hashtable<String, ViewIFace> views, final Hashtable<AltViewIFace, String> altViewsViewDefName) throws Exception { instance.viewSetName = doc.attributeValue(NAME); Element viewsElement = (Element)doc.selectSingleNode("views"); if (viewsElement != null) { for ( Iterator<?> i = viewsElement.elementIterator( "view" ); i.hasNext(); ) { Element element = (Element) i.next(); // assume element is NOT null, if it is null it will cause an exception ViewIFace view = createView(element, altViewsViewDefName); if (view != null) { if (views.get(view.getName()) == null) { views.put(view.getName(), view); } else { String msg = "View Set ["+instance.viewSetName+"] ["+view.getName()+"] is not unique."; log.error(msg); FormDevHelper.appendFormDevError(msg); } } } } return instance.viewSetName; } /** * Fill the Vector with all the views from the DOM document * @param doc the DOM document conforming to form.xsd * @param viewDefs the list to be filled * @param doMapDefinitions tells it to map and clone the definitions for formtables (use false for the FormEditor) * @return the viewset name * @throws Exception for duplicate view set names or if a ViewDef name is not unique */ public static String getViewDefs(final Element doc, final Hashtable<String, ViewDefIFace> viewDefs, @SuppressWarnings("unused") final Hashtable<String, ViewIFace> views, final boolean doMapDefinitions) throws Exception { colDefType = AppPreferences.getLocalPrefs().get("ui.formatting.formtype", UIHelper.getOSTypeAsStr()); instance.viewSetName = doc.attributeValue(NAME); Element viewDefsElement = (Element)doc.selectSingleNode("viewdefs"); if (viewDefsElement != null) { for ( Iterator<?> i = viewDefsElement.elementIterator( "viewdef" ); i.hasNext(); ) { Element element = (Element) i.next(); // assume element is NOT null, if it is null it will cause an exception ViewDef viewDef = createViewDef(element); if (viewDef != null) { if (viewDefs.get(viewDef.getName()) == null) { viewDefs.put(viewDef.getName(), viewDef); } else { String msg = "View Set ["+instance.viewSetName+"] the View Def Name ["+viewDef.getName()+"] is not unique."; log.error(msg); FormDevHelper.appendFormDevError(msg); } } } if (doMapDefinitions) { <API key>(viewDefs); } } return instance.viewSetName; } /** * Re-maps and clones the definitions. * @param viewDefs the hash table to be mapped * @throws Exception */ public static void <API key>(final Hashtable<String, ViewDefIFace> viewDefs) throws Exception { // Now that all the definitions have been read in // cycle thru and have all the tableform objects clone there definitions for (ViewDefIFace viewDef : new Vector<ViewDefIFace>(viewDefs.values())) { if (viewDef.getType() == ViewDefIFace.ViewType.formtable) { String viewDefName = ((FormViewDefIFace)viewDef).getDefinitionName(); if (viewDefName != null) { //log.debug(viewDefName); ViewDefIFace actualDef = viewDefs.get(viewDefName); if (actualDef != null) { viewDefs.remove(viewDef.getName()); actualDef = (ViewDef)actualDef.clone(); actualDef.setType(ViewDefIFace.ViewType.formtable); actualDef.setName(viewDef.getName()); viewDefs.put(actualDef.getName(), actualDef); } else { String msg = "Couldn't find the ViewDef for formtable definition name["+((FormViewDefIFace)viewDef).getDefinitionName()+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); } } } } } /** * Processes all the AltViews * @param aFormView the form they should be associated with * @param aElement the element to process */ public static Hashtable<String, String> getEnableRules(final Element element) { Hashtable<String, String> rulesList = new Hashtable<String, String>(); if (element != null) { Element enableRules = (Element)element.selectSingleNode("enableRules"); if (enableRules != null) { // iterate through child elements of root with element name "foo" for ( Iterator<?> i = enableRules.elementIterator( "rule" ); i.hasNext(); ) { Element ruleElement = (Element) i.next(); String id = getAttr(ruleElement, ID, ""); if (isNotEmpty(id)) { rulesList.put(id, ruleElement.getTextTrim()); } else { String msg = "The name is missing for rule["+ruleElement.getTextTrim()+"] is missing."; log.error(msg); FormDevHelper.appendFormDevError(msg); } } } } else { log.error("View Set ["+instance.viewSetName+"] element ["+element+"] is null."); } return rulesList; } /** * Gets the string (or creates one) from a columnDef * @param element the DOM element to process * @param attrName the name of the element to go get all the elements (strings) from * @param numRows the number of rows * @param item * @return the String representing the column definition for JGoodies */ protected static String createDef(final Element element, final String attrName, final int numRows, final FormViewDef.JGDefItem item) { Element cellDef = null; if (attrName.equals("columnDef")) { // For columnDef(s) we can mark one or more as being platform specific // but if we can't find a default one (no 'os' defined) // then we ultimately pick the first one. List<?> list = element.selectNodes(attrName); if (list.size() == 1) { cellDef = (Element)list.get(0); // pick the first one if there is only one. } else { String osTypeStr = UIHelper.getOSTypeAsStr(); Element defCD = null; Element defOSCD = null; Element ovrOSCD = null; for (Object obj : list) { Element ce = (Element)obj; String osType = getAttr(ce, "os", null); if (osType == null) { defCD = ce; // ok we found the default one } else { if (osType.equals(osTypeStr)) { defOSCD = ce; // we found the matching our OS } if (colDefType != null && osType.equals(colDefType)) { ovrOSCD = ce; // we found the one matching prefs } } } if (ovrOSCD != null) { cellDef = ovrOSCD; } else if (defOSCD != null) { cellDef = defOSCD; } else if (defCD != null) { cellDef = defCD; } else { // ok, we couldn't find one for our platform, so use the default // or pick the first one. cellDef = (Element)list.get(0); } } } else { // this is for rowDef cellDef = (Element)element.selectSingleNode(attrName); } if (cellDef != null) { String cellText = cellDef.getText(); String cellStr = getAttr(cellDef, "cell", null); String sepStr = getAttr(cellDef, "sep", null); item.setDefStr(cellText); item.setCellDefStr(cellStr); item.setSepDefStr(sepStr); if (StringUtils.isNotEmpty(cellStr) && StringUtils.isNotEmpty(sepStr)) { boolean auto = getAttr(cellDef, "auto", false); item.setAuto(auto); if (auto) { String autoStr = <API key>(cellStr, sepStr, numRows) + (StringUtils.isNotEmpty(cellText) ? ("," + cellText) : ""); item.setDefStr(autoStr); return autoStr; } // else FormDevHelper.appendFormDevError("Element ["+element.getName()+"] Cell or Sep is null for 'dup' or 'auto 'on column def."); return ""; } // else item.setAuto(false); return cellText; } // else String msg = "Element ["+element.getName()+"] must have a columnDef"; log.error(msg); FormDevHelper.appendFormDevError(msg); return ""; } /** * Returns a resource string if it is suppose to * @param label the label or the label key * @return Returns a resource string if it is suppose to */ protected static String getResourceLabel(final String label) { if (isNotEmpty(label) && StringUtils.deleteWhitespace(label).length() > 0) { return instance.doingResourceLabels ? getResourceString(label) : label; } // else return ""; } /** * Returns a Label from the cell and gets the resource string for it if necessary * @param cellElement the cell * @param labelId the Id of the resource or the string * @return the localized string (if necessary) */ protected static String getLabel(final Element cellElement) { String lbl = getAttr(cellElement, LABEL, null); if (lbl == null || lbl.equals(" { return " } return getResourceLabel(lbl); } /** * Processes all the rows * @param element the parent DOM element of the rows * @param cellRows the list the rows are to be added to */ protected static void processRows(final Element element, final List<FormRowIFace> cellRows, final DBTableInfo tableinfo) { Element rowsElement = (Element)element.selectSingleNode("rows"); if (rowsElement != null) { byte rowNumber = 0; for ( Iterator<?> i = rowsElement.elementIterator( "row" ); i.hasNext(); ) { Element rowElement = (Element) i.next(); FormRow formRow = new FormRow(); formRow.setRowNumber(rowNumber); for ( Iterator<?> cellIter = rowElement.elementIterator( "cell" ); cellIter.hasNext(); ) { Element cellElement = (Element)cellIter.next(); String cellId = getAttr(cellElement, ID, ""); String cellName = getAttr(cellElement, NAME, cellId); // let the name default to the id if it doesn't have a name int colspan = getAttr(cellElement, "colspan", 1); int rowspan = getAttr(cellElement, "rowspan", 1); /*boolean isReq = getAttr(cellElement, ISREQUIRED, false); if (isReq) { System.err.println(String.format("%s\t%s\t%s\t%s", gViewDef.getName(), cellId, cellName, tableinfo != null ? tableinfo.getTitle() : "N/A")); }*/ FormCell.CellType cellType = null; FormCellIFace cell = null; try { cellType = FormCellIFace.CellType.valueOf(cellElement.attributeValue(TYPE)); } catch (java.lang.<API key> ex) { FormDevHelper.appendFormDevError(ex.toString()); FormDevHelper.appendFormDevError(String.format("Cell Name[%s] Id[%s] Type[%s]", cellName, cellId, cellElement.attributeValue(TYPE))); return; } if (doFieldVerification && fldVerTableInfo != null && cellType == FormCellIFace.CellType.field && StringUtils.isNotEmpty(cellId) && !cellName.equals("this")) { processFieldVerify(cellName, cellId, rowNumber); } switch (cellType) { case label: { cell = formRow.addCell(new FormCellLabel(cellId, cellName, getLabel(cellElement), getAttr(cellElement, "labelfor", ""), getAttr(cellElement, "icon", null), getAttr(cellElement, "recordobj", false), colspan)); String initialize = getAttr(cellElement, INITIALIZE, null); if (StringUtils.isNotEmpty(initialize)) { cell.setProperties(UIHelper.parseProperties(initialize)); } break; } case separator: { cell = formRow.addCell(new FormCellSeparator(cellId, cellName, getLabel(cellElement), getAttr(cellElement, "collapse", ""), colspan)); String initialize = getAttr(cellElement, INITIALIZE, null); if (StringUtils.isNotEmpty(initialize)) { cell.setProperties(UIHelper.parseProperties(initialize)); } break; } case field: { String uitypeStr = getAttr(cellElement, "uitype", ""); String format = getAttr(cellElement, "format", ""); String formatName = getAttr(cellElement, "formatname", ""); String <API key> = getAttr(cellElement, "uifieldformatter", ""); int cols = getAttr(cellElement, "cols", DEFAULT_COLS); // XXX PREF for default width of text field int rows = getAttr(cellElement, "rows", DEFAULT_ROWS); // XXX PREF for default heightof text area String validationType = getAttr(cellElement, "valtype", "Changed"); String validationRule = getAttr(cellElement, VALIDATION, ""); String initialize = getAttr(cellElement, INITIALIZE, ""); boolean isRequired = getAttr(cellElement, ISREQUIRED, false); String pickListName = getAttr(cellElement, "picklist", ""); if (isNotEmpty(format) && isNotEmpty(formatName)) { String msg = "Both format and formatname cannot both be set! ["+cellName+"] ignoring format"; log.error(msg); FormDevHelper.appendFormDevError(msg); format = ""; } Properties properties = UIHelper.parseProperties(initialize); if (isEmpty(uitypeStr)) { // XXX DEBUG ONLY PLease REMOVE LATER uitypeStr = "text"; } // THis switch is used to get the "display type" and // set up other vars needed for creating the controls FormCellFieldIFace.FieldType uitype = null; try { uitype = FormCellFieldIFace.FieldType.valueOf(uitypeStr); } catch (java.lang.<API key> ex) { FormDevHelper.appendFormDevError(ex.toString()); FormDevHelper.appendFormDevError(String.format("Cell Name[%s] Id[%s] uitype[%s] is in error", cellName, cellId, uitypeStr)); uitype = FormCellFieldIFace.FieldType.text; // default to text } String dspUITypeStr = null; switch (uitype) { case textarea: dspUITypeStr = getAttr(cellElement, DSPUITYPE, "dsptextarea"); break; case textareabrief: dspUITypeStr = getAttr(cellElement, DSPUITYPE, "textareabrief"); break; case querycbx: { dspUITypeStr = getAttr(cellElement, DSPUITYPE, "textfieldinfo"); String fmtName = <API key>.getInstance().<API key>(properties.getProperty("name")); if (isEmpty(formatName) && isNotEmpty(fmtName)) { formatName = fmtName; } break; } case formattedtext: { validationRule = getAttr(cellElement, VALIDATION, "formatted"); // XXX Is this OK? dspUITypeStr = getAttr(cellElement, DSPUITYPE, "formattedtext"); // This part should be moved to the ViewFactory // because it is the only part that need the Schema Information if (isNotEmpty(<API key>)) { <API key> uiFormatter = UIFieldFormatterMgr.getInstance().getFormatter(<API key>); if (uiFormatter == null) { String msg = "Couldn't find formatter["+<API key>+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); <API key> = ""; uitype = FormCellFieldIFace.FieldType.text; } } else // ok now check the schema for the UI formatter { if (tableinfo != null) { DBFieldInfo fieldInfo = tableinfo.getFieldByName(cellName); if (fieldInfo != null) { if (fieldInfo.getFormatter() != null) { <API key> = fieldInfo.getFormatter().getName(); } else if (fieldInfo.getDataClass().isAssignableFrom(Date.class) || fieldInfo.getDataClass().isAssignableFrom(Calendar.class)) { String msg = "Missing Date Formatter for ["+cellName+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); <API key> = "Date"; <API key> uiFormatter = UIFieldFormatterMgr.getInstance().getFormatter(<API key>); if (uiFormatter == null) { <API key> = ""; uitype = FormCellFieldIFace.FieldType.text; } } else { <API key> = ""; uitype = FormCellFieldIFace.FieldType.text; } } } } break; } case url: dspUITypeStr = getAttr(cellElement, DSPUITYPE, uitypeStr); properties = UIHelper.parseProperties(initialize); break; case list: case image: case tristate: case checkbox: case password: dspUITypeStr = getAttr(cellElement, DSPUITYPE, uitypeStr); break; case plugin: case button: dspUITypeStr = getAttr(cellElement, DSPUITYPE, uitypeStr); properties = UIHelper.parseProperties(initialize); String ttl = properties.getProperty(TITLE); if (ttl != null) { properties.put(TITLE, getResourceLabel(ttl)); } break; case spinner: dspUITypeStr = getAttr(cellElement, DSPUITYPE, "dsptextfield"); properties = UIHelper.parseProperties(initialize); break; case combobox: dspUITypeStr = getAttr(cellElement, DSPUITYPE, "textpl"); if (tableinfo != null) { DBFieldInfo fieldInfo = tableinfo.getFieldByName(cellName); if (fieldInfo != null) { if (StringUtils.isNotEmpty(pickListName)) { fieldInfo.setPickListName(pickListName); } else { pickListName = fieldInfo.getPickListName(); } } } break; default: dspUITypeStr = getAttr(cellElement, DSPUITYPE, "dsptextfield"); break; } //switch FormCellFieldIFace.FieldType dspUIType = FormCellFieldIFace.FieldType.valueOf(dspUITypeStr); try { dspUIType = FormCellFieldIFace.FieldType.valueOf(dspUITypeStr); } catch (java.lang.<API key> ex) { FormDevHelper.appendFormDevError(ex.toString()); FormDevHelper.appendFormDevError(String.format("Cell Name[%s] Id[%s] dspuitype[%s] is in error", cellName, cellId, dspUIType)); uitype = FormCellFieldIFace.FieldType.label; // default to text } // check to see see if the validation is a node in the cell if (isEmpty(validationRule)) { Element valNode = (Element)cellElement.selectSingleNode(VALIDATION); if (valNode != null) { String str = valNode.getTextTrim(); if (isNotEmpty(str)) { validationRule = str; } } } boolean isEncrypted = getAttr(cellElement, "isencrypted", false); boolean isReadOnly = uitype == FormCellFieldIFace.FieldType.dsptextfield || uitype == FormCellFieldIFace.FieldType.dsptextarea || uitype == FormCellFieldIFace.FieldType.label; FormCellField field = new FormCellField(FormCellIFace.CellType.field, cellId, cellName, uitype, dspUIType, format, formatName, <API key>, isRequired, cols, rows, colspan, rowspan, validationType, validationRule, isEncrypted); String labelStr = uitype == FormCellFieldIFace.FieldType.checkbox ? getLabel(cellElement) : getAttr(cellElement, "label", ""); field.setLabel(labelStr); field.setReadOnly(getAttr(cellElement, "readonly", isReadOnly)); field.setDefaultValue(getAttr(cellElement, "default", "")); field.setPickListName(pickListName); field.<API key>(getAttr(cellElement, "changesonly", true) && !isRequired); field.setProperties(properties); cell = formRow.addCell(field); break; } case command: { cell = formRow.addCell(new FormCellCommand(cellId, cellName, getLabel(cellElement), getAttr(cellElement, "commandtype", ""), getAttr(cellElement, "action", ""))); String initialize = getAttr(cellElement, INITIALIZE, null); if (StringUtils.isNotEmpty(initialize)) { cell.setProperties(UIHelper.parseProperties(initialize)); } break; } case panel: { FormCellPanel cellPanel = new FormCellPanel(cellId, cellName, getAttr(cellElement, "paneltype", ""), getAttr(cellElement, "coldef", "p"), getAttr(cellElement, "rowdef", "p"), colspan, rowspan); String initialize = getAttr(cellElement, INITIALIZE, null); if (StringUtils.isNotEmpty(initialize)) { cellPanel.setProperties(UIHelper.parseProperties(initialize)); } processRows(cellElement, cellPanel.getRows(), tableinfo); fixLabels(cellPanel.getName(), cellPanel.getRows(), tableinfo); cell = formRow.addCell(cellPanel); break; } case subview: { Properties properties = UIHelper.parseProperties(getAttr(cellElement, INITIALIZE, null)); String svViewSetName = cellElement.attributeValue("viewsetname"); if (isEmpty(svViewSetName)) { svViewSetName = null; } if (instance.doingResourceLabels && properties != null) { String title = properties.getProperty(TITLE); if (title != null) { properties.setProperty(TITLE, UIRegistry.getResourceString(title)); } } String viewName = getAttr(cellElement, "viewname", null); cell = formRow.addCell(new FormCellSubView(cellId, cellName, svViewSetName, viewName, cellElement.attributeValue("class"), getAttr(cellElement, "desc", ""), getAttr(cellElement, "defaulttype", null), getAttr(cellElement, "rows", <API key>), colspan, rowspan, getAttr(cellElement, "single", false))); cell.setProperties(properties); break; } case iconview: { String vsName = cellElement.attributeValue("viewsetname"); if (isEmpty(vsName)) { vsName = instance.viewSetName; } String viewName = getAttr(cellElement, "viewname", null); cell = formRow.addCell(new FormCellSubView(cellId, cellName, vsName, viewName, cellElement.attributeValue("class"), getAttr(cellElement, "desc", ""), colspan, rowspan)); break; } case statusbar: { cell = formRow.addCell(new FormCell(FormCellIFace.CellType.statusbar, cellId, cellName, colspan, rowspan)); break; } default: { // what is this? log.error("Encountered unknown cell type"); continue; } } // switch cell.setIgnoreSetGet(getAttr(cellElement, "ignore", false)); } cellRows.add(formRow); rowNumber++; } } } /** * @param cellName * @param cellId * @param rowNumber */ private static void processFieldVerify(final String cellName, final String cellId, final int rowNumber) { try { boolean isOK = false; if (StringUtils.contains(cellName, '.')) { DBTableInfo tblInfo = fldVerTableInfo; String[] fieldNames = StringUtils.split(cellName, "."); for (int i=0;i<fieldNames.length-1;i++) { String type = null; DBTableChildIFace child = tblInfo.getItemByName(fieldNames[i]); if (child instanceof DBFieldInfo) { DBFieldInfo fldInfo = (DBFieldInfo)child; type = fldInfo.getType(); if (type != null) { DBTableInfo tInfo = DBTableIdMgr.getInstance().getByClassName(type); tblInfo = tInfo != null ? tInfo : tblInfo; } isOK = tblInfo.getItemByName(fieldNames[fieldNames.length-1]) != null; } else if (child instanceof DBRelationshipInfo) { DBRelationshipInfo relInfo = (DBRelationshipInfo)child; type = relInfo.getDataClass().getName(); if (type != null) { tblInfo = DBTableIdMgr.getInstance().getByClassName(type); } } //System.out.println(type); } if (tblInfo != null) { isOK = tblInfo.getItemByName(fieldNames[fieldNames.length-1]) != null; } } else { isOK = fldVerTableInfo.getItemByName(cellName) != null; } if (!isOK) { String msg = " ViewSet["+instance.viewSetName+"]\n ViewDef["+fldVerFormViewDef.getName()+"]\n The cell name ["+cellName+"] for cell with Id ["+cellId+"] is not a field\n in Data Object["+fldVerTableInfo.getName()+"]\n on Row ["+rowNumber+"]"; if (!isTreeClass) { instance.fldVerTableModel.addRow(instance.viewSetName, fldVerFormViewDef.getName(), cellId, cellName, Integer.toString(rowNumber)); } log.error(msg); } } catch (Exception ex) { log.error(ex); } } /** * @param element the DOM element for building the form * @param type the type of form to be built * @param id the id of the form * @param name the name of the form * @param className the class name of the data object * @param gettableClassName the class name of the getter * @param settableClassName the class name of the setter * @param desc the description * @param useResourceLabels whether to use resource labels * @param tableinfo table info * @return a form view of type "form" */ protected static FormViewDef createFormViewDef(final Element element, final ViewDef.ViewType type, final String name, final String className, final String gettableClassName, final String settableClassName, final String desc, final boolean useResourceLabels, final DBTableInfo tableinfo) { FormViewDef formViewDef = new FormViewDef(type, name, className, gettableClassName, settableClassName, desc, useResourceLabels, XMLHelper.getAttr(element, "editableDlg", true)); fldVerTableInfo = null; if (type != ViewDefIFace.ViewType.formtable) { if (doFieldVerification) { if (instance.fldVerTableModel == null) { instance.<API key>(); } try { //log.debug(className); Class<?> classObj = Class.forName(className); if (FormDataObjIFace.class.isAssignableFrom(classObj)) { fldVerTableInfo = DBTableIdMgr.getInstance().getByClassName(className); isTreeClass = fldVerTableInfo != null && fldVerTableInfo.getFieldByName("<API key>") != null; fldVerFormViewDef = formViewDef; } } catch (<API key> ex) { String msg = "<API key>["+className+"] Name["+name+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); //edu.ku.brc.af.core.UsageTracker.<API key>(); //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ViewLoader.class, comments, ex); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.<API key>(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ViewLoader.class, ex); } } List<FormRowIFace> rows = formViewDef.getRows(); instance.doingResourceLabels = useResourceLabels; //gViewDef = formViewDef; processRows(element, rows, tableinfo); instance.doingResourceLabels = false; createDef(element, "columnDef", rows.size(), formViewDef.getColumnDefItem()); createDef(element, "rowDef", rows.size(), formViewDef.getRowDefItem()); formViewDef.setEnableRules(getEnableRules(element)); fixLabels(formViewDef.getName(), rows, tableinfo); } else { Node defNode = element.selectSingleNode("definition"); if (defNode != null) { String defName = defNode.getText(); if (StringUtils.isNotEmpty(defName)) { formViewDef.setDefinitionName(defName); return formViewDef; } } String msg = "formtable is missing or has empty <defintion> node"; log.error(msg); FormDevHelper.appendFormDevError(msg); return null; } return formViewDef; } /** * @param fieldName * @param tableInfo * @return */ protected static String <API key>(final String fieldName, final DBTableInfo tableInfo) { DBTableChildIFace derivedCI = null; if (fieldName.indexOf(".") > -1) { derivedCI = FormHelper.<API key>(fieldName, tableInfo); if (derivedCI == null) { String msg = "The name 'path' ["+fieldName+"] was not valid in ViewSet ["+instance.viewSetName+"]"; FormDevHelper.appendFormDevError(msg); log.error(msg); return ""; } } DBTableChildIFace tblChild = derivedCI != null ? derivedCI : tableInfo.getItemByName(fieldName); if (tblChild == null) { String msg = "The Field Name ["+fieldName+"] was not in the Table ["+tableInfo.getTitle()+"] in ViewSet ["+instance.viewSetName+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); return ""; } return tblChild.getTitle(); } /** * @param rows * @param tableInfo */ protected static void fixLabels(final String name, final List<FormRowIFace> rows, final DBTableInfo tableInfo) { if (tableInfo == null) { return; } Hashtable<String, String> fldIdMap = new Hashtable<String, String>(); for (FormRowIFace row : rows) { for (FormCellIFace cell : row.getCells()) { if (cell.getType() == FormCellIFace.CellType.field || cell.getType() == FormCellIFace.CellType.subview) { fldIdMap.put(cell.getIdent(), cell.getName()); }/* else { System.err.println("Skipping ["+cell.getIdent()+"] " + cell.getType()); }*/ } } for (FormRowIFace row : rows) { for (FormCellIFace cell : row.getCells()) { if (cell.getType() == FormCellIFace.CellType.label) { FormCellLabelIFace lblCell = (FormCellLabelIFace)cell; String label = lblCell.getLabel(); if (label.length() == 0 || label.equals(" { String idFor = lblCell.getLabelFor(); if (StringUtils.isNotEmpty(idFor)) { String fieldName = fldIdMap.get(idFor); if (StringUtils.isNotEmpty(fieldName)) { if (!fieldName.equals("this")) { //FormCellFieldIFace fcf = get lblCell.setLabel(<API key>(fieldName, tableInfo)); } } else { String msg = "Setting Label - Form control with id["+idFor+"] is not in ViewDef or Panel ["+name+"] in ViewSet ["+instance.viewSetName+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); } } } } else if (cell.getType() == FormCellIFace.CellType.field && cell instanceof FormCellFieldIFace && ((((FormCellFieldIFace)cell).getUiType() == FormCellFieldIFace.FieldType.checkbox) || (((FormCellFieldIFace)cell).getUiType() == FormCellFieldIFace.FieldType.tristate))) { FormCellFieldIFace fcf = (FormCellFieldIFace)cell; if (fcf.getLabel().equals(" { fcf.setLabel(<API key>(cell.getName(), tableInfo)); } } } } } /** * @param type the type of form to be built * @param name the name of the form * @param className the class name of the data object * @param gettableClassName the class name of the getter * @param settableClassName the class name of the setter * @param desc the description * @param useResourceLabels whether to use resource labels * @return a form view of type "form" */ protected static ViewDef createIconViewDef(final ViewDef.ViewType type, final String name, final String className, final String gettableClassName, final String settableClassName, final String desc, final boolean useResourceLabels) { ViewDef formView = new ViewDef(type, name, className, gettableClassName, settableClassName, desc, useResourceLabels); //formView.setEnableRules(getEnableRules(element)); return formView; } /** * Creates a Table Form View * @param typeName the type of form to be built * @param element the DOM element for building the form * @param name the name of the form * @param className the class name of the data object * @param gettableClassName the class name of the getter * @param settableClassName the class name of the setter * @param desc the description * @param useResourceLabels whether to use resource labels * @return a form view of type "table" */ protected static TableViewDefIFace createTableView(final Element element, final String name, final String className, final String gettableClassName, final String settableClassName, final String desc, final boolean useResourceLabels) { TableViewDefIFace tableView = new TableViewDef( name, className, gettableClassName, settableClassName, desc, useResourceLabels); //tableView.setResourceLabels(resLabels); Element columns = (Element)element.selectSingleNode("columns"); if (columns != null) { for ( Iterator<?> i = columns.elementIterator( "column" ); i.hasNext(); ) { Element colElement = (Element) i.next(); FormColumn column = new FormColumn(colElement.attributeValue(NAME), colElement.attributeValue(LABEL), getAttr(colElement, "dataobjformatter", null), getAttr(colElement, "format", null) ); tableView.addColumn(column); } } return tableView; } /** * Save out a viewSet to a file * @param viewSet the viewSet to save * @param filename the filename (full path) as to where to save it */ public static void save(final ViewSet viewSet, final String filename) { try { Vector<ViewSet> viewsets = new Vector<ViewSet>(); viewsets.add(viewSet); File file = new File(filename); FileWriter fw = new FileWriter(file); fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); BeanWriter beanWriter = new BeanWriter(fw); XMLIntrospector introspector = beanWriter.getXMLIntrospector(); introspector.getConfiguration().<API key>(false); beanWriter.<API key>().setMapIDs(false); beanWriter.<API key>(false); beanWriter.enablePrettyPrint(); beanWriter.write(viewSet); fw.close(); } catch(Exception ex) { log.error("error writing views", ex); } } //-- Field Verify Methods, Classes, Helpers public void <API key>() { fldVerTableModel = new <API key>(); } /** * @return the doFieldVerification */ public static boolean <API key>() { return doFieldVerification; } /** * @param doFieldVerification the doFieldVerification to set */ public static void <API key>(boolean doFieldVerification) { ViewLoader.doFieldVerification = doFieldVerification; } public static void clearFieldVerInfo() { if (instance.fldVerTableModel != null) { instance.fldVerTableModel.clear(); } } public static void displayFieldVerInfo() { if (verifyDlg != null) { verifyDlg.setVisible(false); verifyDlg.dispose(); verifyDlg = null; } System.err.println(" if (instance.fldVerTableModel != null && instance.fldVerTableModel.getRowCount() > 0) { JLabel lbl = UIHelper.createLabel("<html><i>(Some of fields are special buttons or labal names. Review them to make sure you have not <br>mis-named any of the fields you are working with.)"); final JTable table = new JTable(instance.fldVerTableModel); UIHelper.calcColumnWidths(table); CellConstraints cc = new CellConstraints(); JScrollPane sp = new JScrollPane(table, ScrollPaneConstants.<API key>, ScrollPaneConstants.<API key>); PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "f:p:g,4px,p")); pb.add(sp, cc.xy(1, 1)); pb.add(lbl, cc.xy(1, 3)); pb.<API key>(); verifyDlg = new CustomFrame("Field Names on Form, but not in Database : "+instance.fldVerTableModel.getRowCount(), CustomFrame.OK_BTN, pb.getPanel()) { @Override protected void okButtonPressed() { super.okButtonPressed(); table.setModel(new DefaultTableModel()); dispose(); verifyDlg = null; } }; verifyDlg.setOkLabel(getResourceString("CLOSE")); verifyDlg.createUI(); verifyDlg.setVisible(true); } } class <API key> extends DefaultTableModel { protected Vector<List<String>> rowData = new Vector<List<String>>(); protected String[] colNames = {"ViewSet", "View Def", "Cell Id", "Cell Name", "Row"}; protected Hashtable<String, Boolean> nameHash = new Hashtable<String, Boolean>(); public <API key>() { super(); } public void clear() { for (List<String> list : rowData) { list.clear(); } rowData.clear(); nameHash.clear(); } public void addRow(final String viewSet, final String viewDef, final String cellId, final String cellName, final String rowInx) { String key = viewSet + viewDef + cellId; if (nameHash.get(key) == null) { List<String> row = new ArrayList<String>(5); row.add(viewSet); row.add(viewDef); row.add(cellId); row.add(cellName); row.add(rowInx); rowData.add(row); nameHash.put(key, true); } } /* (non-Javadoc) * @see javax.swing.table.DefaultTableModel#getColumnCount() */ @Override public int getColumnCount() { return colNames.length; } /* (non-Javadoc) * @see javax.swing.table.DefaultTableModel#getColumnName(int) */ @Override public String getColumnName(int column) { return colNames[column]; } /* (non-Javadoc) * @see javax.swing.table.DefaultTableModel#getRowCount() */ @Override public int getRowCount() { return rowData == null ? 0 : rowData.size(); } /* (non-Javadoc) * @see javax.swing.table.DefaultTableModel#getValueAt(int, int) */ @Override public Object getValueAt(int row, int column) { List<String> rowList = rowData.get(row); return rowList.get(column); } } }
#!/bin/bash RRD=/data/mirror/rrd PNG=/data/mirror/www/size
/* * MBP - Mobile boilerplate helper functions */ (function(document){ window.MBP = window.MBP || {}; // Fix for iPhone viewport scale bug MBP.viewportmeta = document.querySelector && document.querySelector('meta[name="viewport"]'); MBP.ua = navigator.userAgent; MBP.scaleFix = function () { if (MBP.viewportmeta && /iPhone|iPad/.test(MBP.ua) && !/Opera Mini/.test(MBP.ua)) { MBP.viewportmeta.content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0"; document.addEventListener("gesturestart", MBP.gestureStart, false); } }; MBP.gestureStart = function () { MBP.viewportmeta.content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6"; }; // Hide URL Bar for iOS MBP.hideUrlBar = function () { /iPhone/.test(MBP.ua) && !pageYOffset && !location.hash && setTimeout(function () { window.scrollTo(0, 1); }, 1000), /iPad/.test(MBP.ua) && !pageYOffset && !location.hash && setTimeout(function () { window.scrollTo(0, 1); }, 1000); }; }); jQuery( function() { $("a.facebox").fancybox(); //$("a.fancybox").prettyPhoto({ // social_tools: false jQuery('.entenlogo').click(function() { $('.entenlogo').hide(); }); var current_url = $(location).attr('href'); //console.log($(location).attr('href')); jQuery('body').bind( 'taphold', function( e ) { //$('#next_post_link').attr('refresh'); //$('#previous_post_link').attr('refresh'); $('#page').page('refresh'); var next_url = $('#next_post_link').attr('href'); var previous_url = $('#previous_post_link').attr('href'); console.log(next_url + ' --- ' + previous_url); e.<API key>(); return false; } ); jQuery('body').bind( 'swipeleft', function( e ) { var next_url = $('.ui-page-active #next_post_link').attr('href'); var previous_url = $('.ui-page-active #previous_post_link').attr('href'); console.log("Swiped Left: " + next_url + ' --- ' + previous_url); if (undefined != previous_url) { //$.mobile.changePage( previous_url,"slide", true); $.mobile.changePage( previous_url, { transition: "slide", reverse: false, changeHash: true }); e.<API key>(); return false; } } ); jQuery('body').bind( 'swiperight', function( e ) { var next_url = $('.ui-page-active #next_post_link').attr('href'); var previous_url = $('.ui-page-active #previous_post_link').attr('href'); console.log("Swiped Right: " + next_url + ' --- ' + previous_url); if (undefined != next_url) { //$.mobile.changePage( next_url, "slide", true); $.mobile.changePage( next_url, { transition: "slide", reverse: true, changeHash: true }); e.<API key>(); return false; } } ); } );
#include "tacticattacker.h" TacticAttacker::TacticAttacker(WorldModel *worldmodel, QObject *parent) : Tactic("TacticAttacker", worldmodel, parent) { everyOneInTheirPos = false; maxDistance = sqrt(pow(Field::MaxX*2,2)+pow(Field::MaxY*2,2)); } RobotCommand TacticAttacker::getCommand() { RobotCommand rc; if(!wm->ourRobot[id].isValid) return rc; if(wm->ourRobot[id].Status == AgentStatus::FollowingBall) { rc.maxSpeed = 2; tANDp target = findTarget(); // OperatingPosition p = BallControl(target.pos, target.prob, this->id, rc.maxSpeed); OperatingPosition p = BallControl(target.pos, target.prob, this->id, rc.maxSpeed,3); if( p.readyToShoot ) // rc.kickspeedx = detectKickSpeed(kickType::Shoot, p.shootSensor); { rc.kickspeedz = detectChipSpeed(/*kickType::Shoot, */p.shootSensor); } rc.fin_pos = p.pos; rc.useNav = p.useNav; rc.isBallObs = true; rc.isKickObs = true; } else if(wm->ourRobot[id].Status == AgentStatus::Kicking) { // if(wm->gs == <API key>) // rc = KickTheBallIndirect(); // else if(wm->gs == STATE_Free_kick_Our) // rc = KickTheBallDirect(); // else if(wm->gs == STATE_Start) // rc = StartTheGame(); if(wm->gs == STATE_Start) { rc = StartTheGame(); } else { rc = KickTheBallIndirect(); } rc.isBallObs = true; rc.isKickObs = true; } else if(wm->ourRobot[id].Status == AgentStatus::Chiping) { rc = ChipTheBallIndirect(); rc.isBallObs = true; rc.isKickObs = true; } else if(wm->ourRobot[id].Status == AgentStatus::RecievingPass) { rc.fin_pos = idlePosition; rc.maxSpeed = 2.5; rc.useNav = true; rc.isBallObs = true; rc.isKickObs = true; } else if(wm->ourRobot[id].Status == AgentStatus::BlockingRobot) { AngleDeg desiredDeg = (wm->oppRobot[playerToKeep].pos.loc-Field::ourGoalCenter).dir(); Position final; final.loc.x = wm->oppRobot[playerToKeep].pos.loc.x - (300*cos(desiredDeg.radian())); final.loc.y = wm->oppRobot[playerToKeep].pos.loc.y - (300*sin(desiredDeg.radian())); final.dir = desiredDeg.radian(); if( wm->gs == GameStateType::STATE_Free_kick_Opp || wm->gs == GameStateType::<API key>) { if( wm->kn->IsInsideSecureArea(final.loc,wm->ball.pos.loc) ) { Vector2D fstInt,secInt; Circle2D secArea(wm->ball.pos.loc,<API key>); Line2D connectedLine(wm->ball.pos.loc,Field::ourGoalCenter); int <API key> = secArea.intersection(connectedLine,&fstInt,&secInt); rc.fin_pos.dir = (wm->oppRobot[playerToKeep].pos.loc - Field::ourGoalCenter).dir().radian(); if( <API key> == 2 ) { if( (fstInt-final.loc).length() > (secInt-final.loc).length() ) rc.fin_pos.loc = secInt; else rc.fin_pos.loc = fstInt; } else if( <API key> == 1 ) { rc.fin_pos.loc = fstInt; } else rc.fin_pos = wm->ourRobot[this->id].pos; } else { rc.fin_pos = final; } } else { rc.fin_pos = final; } if( wm->opp_vel > 3 ) rc.maxSpeed = 3; else rc.maxSpeed = wm->opp_vel; rc.useNav = true; rc.isBallObs = true; rc.isKickObs = true; } else if(wm->ourRobot[id].Status == AgentStatus::Idle) { rc.fin_pos = idlePosition; rc.maxSpeed = 2; rc.useNav = true; rc.isBallObs = true; rc.isKickObs = true; if( wm->gs == STATE_Stop ) return rc; } if( wm->kn->IsInsideGolieArea(rc.fin_pos.loc) ) { Circle2D attackerCircles(Field::ourGoalCenter , Field::goalCircle_R+300); Line2D robotRay(rc.fin_pos.loc,wm->ourRobot[this->id].pos.loc); Vector2D firstPoint,secondPoint; attackerCircles.intersection(robotRay,&firstPoint,&secondPoint); if( (wm->ourRobot[this->id].pos.loc-firstPoint).length() < (wm->ourRobot[this->id].pos.loc-secondPoint).length() ) rc.fin_pos.loc = firstPoint; else rc.fin_pos.loc = secondPoint; } if( wm->kn-><API key>(rc.fin_pos.loc) && !wm->cmgs.ourPenaltyKick() /*&& wm->defenceMode*/) { Circle2D attackerCircles(Field::oppGoalCenter , Field::goalCircle_R+300); Line2D robotRay(rc.fin_pos.loc, wm->ourRobot[this->id].pos.loc); Vector2D firstPoint,secondPoint; attackerCircles.intersection(robotRay,&firstPoint,&secondPoint); if( (wm->ourRobot[this->id].pos.loc-firstPoint).length() < (wm->ourRobot[this->id].pos.loc-secondPoint).length() ) rc.fin_pos.loc = firstPoint; else rc.fin_pos.loc = secondPoint; } return rc; } RobotCommand TacticAttacker::goBehindBall() { RobotCommand rc; canKick=false; rc.maxSpeed = 1; float deg=atan((0-wm->ball.pos.loc.y)/(3025-wm->ball.pos.loc.x)); if(!wm->kn->ReachedToPos(wm->ourRobot[id].pos, rc.fin_pos, 30, 180)) { rc.fin_pos.loc= {wm->ball.pos.loc.x-110*cos(deg),wm->ball.pos.loc.y-110*sin(deg)}; rc.fin_pos.dir=atan((0-wm->ball.pos.loc.y)/(3025-wm->ball.pos.loc.x)); } if(!wm->kn->ReachedToPos(wm->ourRobot[id].pos, rc.fin_pos, 20, 2)) { //double test=findBestPoint(); //rc.fin_pos.dir=test; } rc.fin_pos.loc= {wm->ball.pos.loc.x-100*cos(deg),wm->ball.pos.loc.y-100*sin(deg)}; if(wm->kn->ReachedToPos(wm->ourRobot[id].pos, rc.fin_pos, 10, 4)) { canKick=true; } return rc; } RobotCommand TacticAttacker::KickTheBallIndirect() { RobotCommand rc; rc.maxSpeed = 0.5; Vector2D target = receiverPos; Line2D b2g(target,Field::oppGoalCenter); Circle2D cir(target,300); Vector2D goal,first,second; int numOfPoints = cir.intersection(b2g,&first,&second); // if( numOfPoints == 2) // if( first.x > target.x ) // goal = first; // else if( second.x > target.x ) // goal = second; // else // goal = target; // else if( numOfPoints == 1) // goal = first; // else goal = target; wm->passPoints.clear(); wm->passPoints.push_back(goal); OperatingPosition kickPoint = BallControl(goal,100,this->id,rc.maxSpeed); rc.fin_pos = kickPoint.pos; rc.useNav = kickPoint.useNav; qDebug()<<"readyToShoot : "<<kickPoint.readyToShoot<<" , everyOneInTheirPos : "<<everyOneInTheirPos; if( kickPoint.readyToShoot && everyOneInTheirPos) { rc.kickspeedx = detectKickSpeed(freeKickType, kickPoint.shootSensor); // Line2D ball2Target(wm->ball.pos.loc,goal); // QList<int> activeOpp = wm->kn->ActiveOppAgents(); // bool wayIsClear = true; // for(int i=0;i<activeOpp.size();i++) // double distance = ball2Target.dist(wm->oppRobot[activeOpp.at(i)].pos.loc); // if( distance < ROBOT_RADIUS+BALL_RADIUS ) // wayIsClear = false; // break; // if( wayIsClear ) // rc.kickspeedx = 255;// detectKickSpeed(goal); // qDebug()<<"Kickk..."; // else // rc.kickspeedx = 3;//255;// detectKickSpeed(goal); // rc.kickspeedz = 3; // qDebug()<<"CHIP..."; } return rc; } RobotCommand TacticAttacker::KickTheBallDirect() { RobotCommand rc; rc.maxSpeed = 0.5; tANDp target = findTarget(); OperatingPosition kickPoint = BallControl(target.pos, target.prob, this->id, rc.maxSpeed); rc.fin_pos = kickPoint.pos; if( kickPoint.readyToShoot ) { rc.kickspeedx = detectKickSpeed(kickType::Shoot, kickPoint.shootSensor); qDebug()<<"Kickk..."; } rc.useNav = kickPoint.useNav; return rc; } RobotCommand TacticAttacker::StartTheGame() { RobotCommand rc; rc.maxSpeed = 0.5; Vector2D target(Field::oppGoalCenter.x,Field::oppGoalCenter.y); OperatingPosition kickPoint = BallControl(target, 100, this->id, rc.maxSpeed); rc.fin_pos = kickPoint.pos; rc.useNav = kickPoint.useNav; if( kickPoint.readyToShoot ) { //rc.kickspeedz = 2.5;//50; rc.kickspeedx = detectKickSpeed(kickType::Shoot, kickPoint.shootSensor); qDebug()<<"Kickk..."; } return rc; } RobotCommand TacticAttacker::ChipTheBallIndirect() { RobotCommand rc; rc.maxSpeed = 0.5; Vector2D target = receiverPos; Vector2D goal(target.x,target.y); OperatingPosition kickPoint = BallControl(goal, 100, this->id, rc.maxSpeed); rc.fin_pos = kickPoint.pos; rc.useNav = kickPoint.useNav; if( kickPoint.readyToShoot && everyOneInTheirPos) { rc.kickspeedz = detectChipSpeed(kickPoint.shootSensor); qDebug()<<"Chip..."; } return rc; } int TacticAttacker::<API key>() { QList<int> ourAgents = wm->kn->findAttackers(); ourAgents.removeOne(this->id); QList<int> freeAgents , busyAgents; while( !ourAgents.isEmpty() ) { int index = ourAgents.takeFirst(); if(isFree(index)) freeAgents.append(index); else busyAgents.append(index); } QList<double> weights; for(int i=0;i<freeAgents.size();i++) { double weight = -1000000; if( wm->ourRobot[freeAgents.at(i)].isValid ) { double dist = 1 - ((wm->ball.pos.loc - wm->ourRobot[freeAgents.at(i)].pos.loc).length()/maxDistance); double prob = wm->kn->scoringChance(wm->ourRobot[freeAgents.at(i)].pos.loc) / 100; weight = (20 * prob) + (10*dist); } weights.append(weight); } int index = -1; double max = -10000; for(int i=0;i<weights.size();i++) { if( max < weights.at(i) ) { max = weights.at(i); index = freeAgents.at(i); } } return index; } void TacticAttacker::isKicker() { wm->ourRobot[this->id].Status = AgentStatus::Kicking; findReciever = true; } void TacticAttacker::isChiper() { wm->ourRobot[this->id].Status = AgentStatus::Chiping; findReciever = true; } void TacticAttacker::isKicker(int recieverID) { wm->ourRobot[this->id].Status = AgentStatus::Kicking; findReciever = false; this->receiverPos = wm->ourRobot[recieverID].pos.loc; } void TacticAttacker::isKicker(Vector2D pos) { wm->ourRobot[this->id].Status = AgentStatus::Kicking; findReciever = false; this->receiverPos = pos; } void TacticAttacker::isChiper(Vector2D pos) { wm->ourRobot[this->id].Status = AgentStatus::Chiping; findReciever = false; this->receiverPos = pos; } void TacticAttacker::setGameOnPositions(Position pos) { setIdlePosition(pos); } void TacticAttacker::setGameOnPositions(Vector2D pos) { Position position = wm->kn->AdjustKickPoint(pos,Field::oppGoalCenter); setIdlePosition(position); } void TacticAttacker::setIdlePosition(Position pos) { this->idlePosition = pos; } void TacticAttacker::setIdlePosition(Vector2D pos) { this->idlePosition.loc = pos; this->idlePosition.dir = ( wm->ball.pos.loc - pos).dir().radian(); } void TacticAttacker::<API key>() { everyOneInTheirPos = true; if( findReciever ) { int indexOfReciever = <API key>(); if( indexOfReciever != -1 ) receiverPos = wm->ourRobot[indexOfReciever].pos.loc; } } void TacticAttacker::setFreeKickType(kickType type) { this->freeKickType = type; } bool TacticAttacker::isFree(int index) { QList<int> oppAgents = wm->kn->ActiveOppAgents(); while( !oppAgents.isEmpty() ) { int indexOPP = oppAgents.takeFirst(); if( (wm->ourRobot[index].pos.loc-wm->oppRobot[indexOPP].pos.loc).length() < DangerDist && fabs((wm->ourRobot[index].vel.loc - wm->oppRobot[indexOPP].vel.loc).length())<0.3 ) { return false; } } return true; }
#pragma once #include <cbang/SmartPointer.h> #include <QDialog> namespace Ui {class DonateDialog;} namespace CAMotics { class DonateDialog : public QDialog { Q_OBJECT; cb::SmartPointer<Ui::DonateDialog> ui; public: DonateDialog(QWidget *parent); QString getVersion() const; void onStartup(); // From QDialog int exec(); // From QWidget void showEvent(QShowEvent *event); }; }
#include<stdio.h> int main() { double r,pi=3.14159; scanf("%lf",&r); printf("A=%.4lf\n",pi*r*r); return 0; }
package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest04982") public class BenchmarkTest04982 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { org.owasp.benchmark.helpers.<API key> scr = new org.owasp.benchmark.helpers.<API key>( request ); String param = scr.getTheParameter("foo"); String bar; String guess = "ABC"; char switchTarget = guess.charAt(1); // condition 'B', which is safe // Simple case statement that assigns param to bar on conditions 'A' or 'C' switch (switchTarget) { case 'A': bar = param; break; case 'B': bar = "bob"; break; case 'C': case 'D': bar = param; break; default: bar = "bob's your uncle"; break; } Object[] obj = { bar, "b"}; response.getWriter().printf("notfoo",obj); } }
<?php $words = new MOD_words(); ?> <div id="teaser" class="clearfix"> <div class="subcolumns"> <div class="c62l"> <div class="subcl"> <h1 class="slogan"><span id="something" ><?php echo $words->get('<API key>');?></span> <span id="real" ><?php echo $words->get('<API key>');?></span>&nbsp;</h1> <h2><?php echo $words->get('<API key>');?></h2> <a class="bigbutton float_left" href="signup" onclick="this.blur();"><span><?php echo $words->get('signup_now');?></span></a> <a class="bigbutton float_left" href="tour" onclick="this.blur();"><span><?php echo $words->get('tour_take');?></span></a> </div> <!-- subcl --> </div> <!-- c50l --> <div class="c38r"> <div class="subcr"> <div id="slideshow-content"> <div class="slide" id="slide1"> <img src="images/tour/share4_small.jpg" alt="share" /> </div> <div class="slide" id="slide2" style="display: none;"> <img src="images/tour/syrien.jpg" alt="syria" /> </div> <div class="slide" id="slide3" style="display: none;"> <img src="images/tour/mountain1.jpg" alt="mountain" /> </div> <div class="slide" id="slide4" style="display: none;"> <img src="images/tour/river.jpg" alt="river" /> </div> <div class="slide" id="slide5" style="display: none;"> <img src="images/tour/dancing2.jpg" alt="dancing" /> </div> <div class="slide" id="slide6" style="display: none;"> <img src="images/tour/mountain2.jpg" alt="river" /> </div> <div class="slide" id="slide7" style="display: none;"> <img src="images/tour/people.jpg" alt="river" /> </div> <div class="slide" id="slide8" style="display: none;"> <img src="images/tour/people2.jpg" alt="river" /> </div> <p class="small photodesc"> (cc) <?=$words->get('<API key>');?> </p> </div> </div> <!-- subcr --> </div> <!-- c50r --> </div> <!-- subcolumns --> <script type="text/javascript"> <! function realeffect() { new Effect.toggle('real', 'appear', {duration: 2}) } $('real').hide(); $('something').hide(); window.onload = function () { new Effect.toggle('something', 'appear', {duration: 2}); setTimeout('realeffect()',2000); start_slideshow(1, 8, 10000); }; </script> <script type="text/javascript"> function start_slideshow(start_frame, end_frame, delay) { setTimeout(switch_slides(start_frame,start_frame,end_frame, delay), delay); } function switch_slides(frame, start_frame, end_frame, delay) { return (function() { Effect.Fade('slide' + frame); if (frame == end_frame) { frame = start_frame; } else { frame = frame + 1; } setTimeout("Effect.Appear('slide" + frame + "');", 950); setTimeout(switch_slides(frame, start_frame, end_frame, delay), delay + 950); }) } </script> </div>
using UnityEngine; using System.Collections; public class <API key> : MonoBehaviour { // Use this for initialization void Start () { } void FixedUpdate() { } /*void OnCollisionEnter(Collision collision) { foreach(var contact in collision.contacts) print (contact.otherCollider.gameObject.name); }*/ }
#ifndef GLSL_SHADER_H #define GLSL_SHADER_H #include "Shader.h" #include <iostream> #include <irrlicht.h> class GlslShader : public Shader { private: irr::video::E_MATERIAL_TYPE _materialType; bool _isLoaded; public: GlslShader(); GlslShader(std::string fileName, irr::video::<API key>* gpu, int type); void load(std::string fileName, irr::video::<API key>* gpu, int type); void apply(irr::scene::ISceneNode* node); }; #endif
package com.espertech.esper.epl.join.pollindex; import com.espertech.esper.epl.join.table.EventTable; import com.espertech.esper.epl.join.table.<API key>; import com.espertech.esper.epl.join.table.<API key>; import com.espertech.esper.client.EventBean; import com.espertech.esper.client.EventType; import java.util.Arrays; import java.util.List; /** * Strategy for building an index out of poll-results knowing the properties to base the index on. */ public class <API key> implements <API key> { private final int streamNum; private final EventType eventType; private final String[] propertyNames; /** * Ctor. * @param streamNum is the stream number of the indexed stream * @param eventType is the event type of the indexed stream * @param propertyNames is the property names to be indexed */ public <API key>(int streamNum, EventType eventType, String[] propertyNames) { this.streamNum = streamNum; this.eventType = eventType; this.propertyNames = propertyNames; } public EventTable index(List<EventBean> pollResult, boolean isActiveCache) { if (!isActiveCache) { return new <API key>(pollResult); } <API key> table = new <API key>(streamNum, eventType, propertyNames); table.add(pollResult.toArray(new EventBean[pollResult.size()])); return table; } public String toQueryPlan() { return this.getClass().getSimpleName() + " properties " + Arrays.toString(propertyNames); } }
#include <linux/init.h> #include <linux/module.h> #include <linux/device.h> #include <linux/delay.h> #include <linux/io.h> #include <linux/mfd/davinci_voicecodec.h> #include <linux/slab.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/initval.h> #include <sound/soc.h> #include "davinci-pcm.h" #include "davinci-i2s.h" #include "davinci-vcif.h" #define MOD_REG_BIT(val, mask, set) do { \ if (set) { \ val |= mask; \ } else { \ val &= ~mask; \ } \ } while (0) struct davinci_vcif_dev { struct davinci_vc *davinci_vc; struct <API key> dma_params[2]; }; static void davinci_vcif_start(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct davinci_vcif_dev *davinci_vcif_dev = rtd->dai->cpu_dai->private_data; struct davinci_vc *davinci_vc = davinci_vcif_dev->davinci_vc; u32 w; /* Start the sample generator and enable transmitter/receiver */ w = readl(davinci_vc->base + DAVINCI_VC_CTRL); if (substream->stream == <API key>) MOD_REG_BIT(w, <API key>, 0); else MOD_REG_BIT(w, <API key>, 0); writel(w, davinci_vc->base + DAVINCI_VC_CTRL); } static void davinci_vcif_stop(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct davinci_vcif_dev *davinci_vcif_dev = rtd->dai->cpu_dai->private_data; struct davinci_vc *davinci_vc = davinci_vcif_dev->davinci_vc; u32 w; /* Reset transmitter/receiver and sample rate/frame sync generators */ w = readl(davinci_vc->base + DAVINCI_VC_CTRL); if (substream->stream == <API key>) MOD_REG_BIT(w, <API key>, 1); else MOD_REG_BIT(w, <API key>, 1); writel(w, davinci_vc->base + DAVINCI_VC_CTRL); } static int <API key>(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct davinci_vcif_dev *davinci_vcif_dev = dai->private_data; struct davinci_vc *davinci_vc = davinci_vcif_dev->davinci_vc; struct <API key> *dma_params = &davinci_vcif_dev->dma_params[substream->stream]; u32 w; /* Restart the codec before setup */ davinci_vcif_stop(substream); davinci_vcif_start(substream); /* General line settings */ writel(<API key>, davinci_vc->base + DAVINCI_VC_CTRL); writel(DAVINCI_VC_INT_MASK, davinci_vc->base + DAVINCI_VC_INTCLR); writel(DAVINCI_VC_INT_MASK, davinci_vc->base + DAVINCI_VC_INTEN); w = readl(davinci_vc->base + DAVINCI_VC_CTRL); /* Determine xfer data type */ switch (params_format(params)) { case SNDRV_PCM_FORMAT_U8: dma_params->data_type = 0; MOD_REG_BIT(w, <API key> | <API key> | <API key> | <API key>, 1); break; case SNDRV_PCM_FORMAT_S8: dma_params->data_type = 1; MOD_REG_BIT(w, <API key> | <API key>, 1); MOD_REG_BIT(w, <API key> | <API key>, 0); break; case <API key>: dma_params->data_type = 2; MOD_REG_BIT(w, <API key> | <API key> | <API key> | <API key>, 0); break; default: printk(KERN_WARNING "davinci-vcif: unsupported PCM format"); return -EINVAL; } dma_params->acnt = dma_params->data_type; writel(w, davinci_vc->base + DAVINCI_VC_CTRL); return 0; } static int <API key>(struct snd_pcm_substream *substream, int cmd, struct snd_soc_dai *dai) { int ret = 0; switch (cmd) { case <API key>: case <API key>: case <API key>: davinci_vcif_start(substream); break; case <API key>: case <API key>: case <API key>: davinci_vcif_stop(substream); break; default: ret = -EINVAL; } return ret; } #define DAVINCI_VCIF_RATES <API key> static struct snd_soc_dai_ops <API key> = { .trigger = <API key>, .hw_params = <API key>, }; struct snd_soc_dai davinci_vcif_dai = { .name = "davinci-vcif", .playback = { .channels_min = 1, .channels_max = 2, .rates = DAVINCI_VCIF_RATES, .formats = <API key>,}, .capture = { .channels_min = 1, .channels_max = 2, .rates = DAVINCI_VCIF_RATES, .formats = <API key>,}, .ops = &<API key>, }; EXPORT_SYMBOL_GPL(davinci_vcif_dai); static int davinci_vcif_probe(struct platform_device *pdev) { struct davinci_vc *davinci_vc = <API key>(pdev); struct davinci_vcif_dev *davinci_vcif_dev; int ret; davinci_vcif_dev = kzalloc(sizeof(struct davinci_vcif_dev), GFP_KERNEL); if (!davinci_vc) { dev_dbg(&pdev->dev, "could not allocate memory for private data\n"); return -ENOMEM; } /* DMA tx params */ davinci_vcif_dev->davinci_vc = davinci_vc; davinci_vcif_dev->dma_params[<API key>].channel = davinci_vc->davinci_vcif.dma_tx_channel; davinci_vcif_dev->dma_params[<API key>].dma_addr = davinci_vc->davinci_vcif.dma_tx_addr; /* DMA rx params */ davinci_vcif_dev->dma_params[<API key>].channel = davinci_vc->davinci_vcif.dma_rx_channel; davinci_vcif_dev->dma_params[<API key>].dma_addr = davinci_vc->davinci_vcif.dma_rx_addr; davinci_vcif_dai.dev = &pdev->dev; davinci_vcif_dai.capture.dma_data = davinci_vcif_dev->dma_params; davinci_vcif_dai.playback.dma_data = davinci_vcif_dev->dma_params; davinci_vcif_dai.private_data = davinci_vcif_dev; ret = <API key>(&davinci_vcif_dai); if (ret != 0) { dev_err(&pdev->dev, "could not register dai\n"); goto fail; } return 0; fail: kfree(davinci_vcif_dev); return ret; } static int davinci_vcif_remove(struct platform_device *pdev) { <API key>(&davinci_vcif_dai); return 0; } static struct platform_driver davinci_vcif_driver = { .probe = davinci_vcif_probe, .remove = davinci_vcif_remove, .driver = { .name = "davinci_vcif", .owner = THIS_MODULE, }, }; static int __init davinci_vcif_init(void) { return <API key>(&davinci_vcif_driver, davinci_vcif_probe); } module_init(davinci_vcif_init); static void __exit davinci_vcif_exit(void) { <API key>(&davinci_vcif_driver); } module_exit(davinci_vcif_exit); MODULE_AUTHOR("Miguel Aguilar"); MODULE_DESCRIPTION("Texas Instruments DaVinci ASoC Voice Codec Interface"); MODULE_LICENSE("GPL");
package com.ht.halo.hibernate3.base; import java.beans.BeanInfo; import java.beans.<API key>; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.<API key>; import java.lang.reflect.Method; import java.util.Map.Entry; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.ht.halo.hibernate3.HaloDao; import com.ht.halo.map.HaloMap; public class MyEntityUtils { private static final Log logger = LogFactory.getLog(MyEntityUtils.class); /** * @Title: setEntity * @Description: TODO Action mapentity * @param entity * @param parameters */ public static Object setEntity(Object entity,HaloMap parameter){ if(null!=parameter){ for (Entry<String, ?> entry : parameter.entrySet()) { try { BeanUtils.setProperty(entity, entry.getKey(), entry.getValue()); } catch (<API key> e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (<API key> e) { // TODO Auto-generated catch block e.printStackTrace(); } // MyBeanUtils.setFieldValue(entity, entry.getKey(), entry.getValue()); } } return entity; } public static <T> T toEntity(Class<T> clazz, HaloMap map) { T obj = null; try { BeanInfo beanInfo = Introspector.getBeanInfo(clazz); obj = clazz.newInstance(); // JavaBean // JavaBean PropertyDescriptor[] propertyDescriptors = beanInfo.<API key>(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (map.containsKey(propertyName)) { // try Object value = map.get(propertyName); if ("".equals(value)) { value = null; } Object[] args = new Object[1]; args[0] = value; try { descriptor.getWriteMethod().invoke(obj, args); } catch (<API key> e) { logger.warn(""); } } } } catch (<API key> e) { logger.error(" JavaBean "); } catch (<API key> e) { logger.error(""); } catch (<API key> e) { logger.error(""); } catch (<API key> e) { logger.error(" JavaBean "); } return (T) obj; } public static HaloMap toHaloMap(Object bean) { Class<? extends Object> clazz = bean.getClass(); HaloMap returnMap = new HaloMap(); BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.<API key>(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (!propertyName.equals("class")) { Method readMethod = descriptor.getReadMethod(); Object result = readMethod.invoke(bean, new Object[0]); if (null != propertyName) { propertyName = propertyName.toString(); } if(null==result){ continue; } if (null != result) { result = result.toString(); } returnMap.put(propertyName, result); } } } catch (<API key> e) { logger.error(""); } catch (<API key> e) { logger.error(" JavaBean "); } catch (<API key> e) { logger.error(""); } catch (<API key> e) { logger.error(" setter "); } return returnMap; } public static HaloMap toFindHaloMap(Object bean) { Class<? extends Object> clazz = bean.getClass(); HaloMap returnMap = new HaloMap(); BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.<API key>(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (!propertyName.equals("class")) { Method readMethod = descriptor.getReadMethod(); Object result = readMethod.invoke(bean, new Object[0]); if (null != propertyName) { propertyName = propertyName.toString(); } if(null==result){ continue; } if (null != result) { result = result.toString(); } if(propertyName.equals("json")){ continue; } returnMap.put(propertyName+HaloDao.MYSPACE+HaloDao.PRM, result); } } } catch (<API key> e) { logger.error(""); } catch (<API key> e) { logger.error(" JavaBean "); } catch (<API key> e) { logger.error(""); } catch (<API key> e) { logger.error(" setter "); } return returnMap; } }
import os import unittest import tempfile from git import Repo from oeqa.utils.commands import get_bb_var from oe.<API key> import blob_to_dict, compare_dict_blobs class TestBlobParsing(unittest.TestCase): def setUp(self): import time self.repo_path = tempfile.mkdtemp(prefix='<API key>', dir=get_bb_var('TOPDIR')) self.repo = Repo.init(self.repo_path) self.test_file = "test" self.var_map = {} def tearDown(self): import shutil shutil.rmtree(self.repo_path) def commit_vars(self, to_add={}, to_remove = [], msg="A commit message"): if len(to_add) == 0 and len(to_remove) == 0: return for k in to_remove: self.var_map.pop(x,None) for k in to_add: self.var_map[k] = to_add[k] with open(os.path.join(self.repo_path, self.test_file), 'w') as repo_file: for k in self.var_map: repo_file.write("%s = %s\n" % (k, self.var_map[k])) self.repo.git.add("--all") self.repo.git.commit(message=msg) def test_blob_to_dict(self): """ Test convertion of git blobs to dictionary """ valuesmap = { "foo" : "1", "bar" : "2" } self.commit_vars(to_add = valuesmap) blob = self.repo.head.commit.tree.blobs[0] self.assertEqual(valuesmap, blob_to_dict(blob), "commit was not translated correctly to dictionary") def <API key>(self): """ Test comparisson of dictionaries extracted from git blobs """ changesmap = { "foo-2" : ("2", "8"), "bar" : ("","4"), "bar-2" : ("","5")} self.commit_vars(to_add = { "foo" : "1", "foo-2" : "2", "foo-3" : "3" }) blob1 = self.repo.heads.master.commit.tree.blobs[0] self.commit_vars(to_add = { "foo-2" : "8", "bar" : "4", "bar-2" : "5" }) blob2 = self.repo.heads.master.commit.tree.blobs[0] change_records = compare_dict_blobs(os.path.join(self.repo_path, self.test_file), blob1, blob2, False, False) var_changes = { x.fieldname : (x.oldvalue, x.newvalue) for x in change_records} self.assertEqual(changesmap, var_changes, "Changes not reported correctly") def <API key>(self): """ Test default values for comparisson of git blob dictionaries """ defaultmap = { x : ("default", "1") for x in ["PKG", "PKGE", "PKGV", "PKGR"]} self.commit_vars(to_add = { "foo" : "1" }) blob1 = self.repo.heads.master.commit.tree.blobs[0] self.commit_vars(to_add = { "PKG" : "1", "PKGE" : "1", "PKGV" : "1", "PKGR" : "1" }) blob2 = self.repo.heads.master.commit.tree.blobs[0] change_records = compare_dict_blobs(os.path.join(self.repo_path, self.test_file), blob1, blob2, False, False) var_changes = {} for x in change_records: oldvalue = "default" if ("default" in x.oldvalue) else x.oldvalue var_changes[x.fieldname] = (oldvalue, x.newvalue) self.assertEqual(defaultmap, var_changes, "Defaults not set properly")
#ifdef __KERNEL__ #include <linux/rwsem.h> /* This file contains declarations of usbcore internals that are mostly * used or exposed by Host Controller Drivers. */ /* * USB Packet IDs (PIDs) */ #define USB_PID_UNDEF_0 0xf0 #define USB_PID_OUT 0xe1 #define USB_PID_ACK 0xd2 #define USB_PID_DATA0 0xc3 #define USB_PID_PING 0xb4 /* USB 2.0 */ #define USB_PID_SOF 0xa5 #define USB_PID_NYET 0x96 /* USB 2.0 */ #define USB_PID_DATA2 0x87 /* USB 2.0 */ #define USB_PID_SPLIT 0x78 /* USB 2.0 */ #define USB_PID_IN 0x69 #define USB_PID_NAK 0x5a #define USB_PID_DATA1 0x4b #define USB_PID_PREAMBLE 0x3c /* Token mode */ #define USB_PID_ERR 0x3c /* USB 2.0: handshake mode */ #define USB_PID_SETUP 0x2d #define USB_PID_STALL 0x1e #define USB_PID_MDATA 0x0f /* USB 2.0 */ /* * USB Host Controller Driver (usb_hcd) framework * * Since "struct usb_bus" is so thin, you can't share much code in it. * This framework is a layer over that, and should be more sharable. * * @authorized_default: Specifies if new devices are authorized to * connect by default or they require explicit * user space authorization; this bit is settable * through /sys/class/usb_host/X/authorized_default. * For the rest is RO, so we don't lock to r/w it. */ struct usb_hcd { /* * housekeeping */ struct usb_bus self; /* hcd is-a bus */ struct kref kref; /* reference counter */ const char *product_desc; /* product/vendor string */ char irq_descr[24]; /* driver + bus # */ struct timer_list rh_timer; /* drives root-hub polling */ struct urb *status_urb; /* the current status urb */ #ifdef CONFIG_PM struct work_struct wakeup_work; /* for remote wakeup */ #endif /* * hardware info/state */ const struct hc_driver *driver; /* hw-specific hooks */ /* Flags that need to be manipulated atomically */ unsigned long flags; #define <API key> 0x00000001 #define HCD_FLAG_SAW_IRQ 0x00000002 unsigned rh_registered:1;/* is root hub registered? */ /* The next flag is a stopgap, to be removed when all the HCDs * support the new root-hub polling mechanism. */ unsigned uses_new_polling:1; unsigned poll_rh:1; /* poll for rh status? */ unsigned poll_pending:1; /* status has changed? */ unsigned wireless:1; /* Wireless USB HCD */ unsigned authorized_default:1; int irq; /* irq allocated */ void __iomem *regs; /* device memory/io */ u64 rsrc_start; /* memory/io resource start */ u64 rsrc_len; /* memory/io resource length */ unsigned power_budget; /* in mA, 0 = no limit */ #define HCD_BUFFER_POOLS 4 struct dma_pool *pool [HCD_BUFFER_POOLS]; int state; # define __ACTIVE 0x01 # define __SUSPEND 0x04 # define __TRANSIENT 0x80 # define HC_STATE_HALT 0 # define HC_STATE_RUNNING (__ACTIVE) # define HC_STATE_QUIESCING (__SUSPEND|__TRANSIENT|__ACTIVE) # define HC_STATE_RESUMING (__SUSPEND|__TRANSIENT) # define HC_STATE_SUSPENDED (__SUSPEND) #define HC_IS_RUNNING(state) ((state) & __ACTIVE) #define HC_IS_SUSPENDED(state) ((state) & __SUSPEND) /* more shared queuing code would be good; it should support * smarter scheduling, handle transaction translators, etc; * input size of periodic table to an interrupt scheduler. * (ohci 32, uhci 1024, ehci 256/512/1024). */ /* The HC driver's private data is stored at the end of * this structure. */ unsigned long hcd_priv[0] __attribute__ ((aligned (sizeof(unsigned long)))); }; /* 2.4 does this a bit differently ... */ static inline struct usb_bus *hcd_to_bus (struct usb_hcd *hcd) { return &hcd->self; } static inline struct usb_hcd *bus_to_hcd (struct usb_bus *bus) { return container_of(bus, struct usb_hcd, self); } struct hcd_timeout { /* timeouts we allocate */ struct list_head timeout_list; struct timer_list timer; }; struct hc_driver { const char *description; /* "ehci-hcd" etc */ const char *product_desc; /* product/vendor string */ size_t hcd_priv_size; /* size of private data */ /* irq handler */ irqreturn_t (*irq) (struct usb_hcd *hcd); int flags; #define HCD_MEMORY 0x0001 /* HC regs use memory (else I/O) */ #define HCD_USB11 0x0010 /* USB 1.1 */ #define HCD_USB2 0x0020 /* USB 2.0 */ /* called to init HCD and root hub */ int (*reset) (struct usb_hcd *hcd); int (*start) (struct usb_hcd *hcd); /* NOTE: these suspend/resume calls relate to the HC as * a whole, not just the root hub; they're for PCI bus glue. */ /* called after suspending the hub, before entering D3 etc */ int (*suspend) (struct usb_hcd *hcd, pm_message_t message); /* called after entering D0 (etc), before resuming the hub */ int (*resume) (struct usb_hcd *hcd); /* cleanly make HCD stop writing memory and doing I/O */ void (*stop) (struct usb_hcd *hcd); /* shutdown HCD */ void (*shutdown) (struct usb_hcd *hcd); /* return current frame number */ int (*get_frame_number) (struct usb_hcd *hcd); /* manage i/o requests, device state */ int (*urb_enqueue)(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags); int (*urb_dequeue)(struct usb_hcd *hcd, struct urb *urb, int status); /* hw synch, freeing endpoint resources that urb_dequeue can't */ void (*endpoint_disable)(struct usb_hcd *hcd, struct usb_host_endpoint *ep); /* root hub support */ int (*hub_status_data) (struct usb_hcd *hcd, char *buf); int (*hub_control) (struct usb_hcd *hcd, u16 typeReq, u16 wValue, u16 wIndex, char *buf, u16 wLength); int (*bus_suspend)(struct usb_hcd *); int (*bus_resume)(struct usb_hcd *); int (*start_port_reset)(struct usb_hcd *, unsigned port_num); void (*hub_irq_enable)(struct usb_hcd *); /* Needed only if port-change IRQs are level-triggered */ #ifdef CONFIG_KDB_USB /* KDB poll function for this HC */ int (*kdb_poll_char)(struct urb *urb); #endif /* CONFIG_KDB_USB */ }; extern int <API key>(struct usb_hcd *hcd, struct urb *urb); extern int <API key>(struct usb_hcd *hcd, struct urb *urb, int status); extern void <API key>(struct usb_hcd *hcd, struct urb *urb); extern int usb_hcd_submit_urb (struct urb *urb, gfp_t mem_flags); extern int usb_hcd_unlink_urb (struct urb *urb, int status); extern void <API key>(struct usb_hcd *hcd, struct urb *urb, int status); extern void <API key>(struct usb_device *udev, struct usb_host_endpoint *ep); extern void <API key>(struct usb_device *udev, struct usb_host_endpoint *ep); extern int <API key> (struct usb_device *udev); extern struct usb_hcd *usb_create_hcd (const struct hc_driver *driver, struct device *dev, char *bus_name); extern struct usb_hcd *usb_get_hcd (struct usb_hcd *hcd); extern void usb_put_hcd (struct usb_hcd *hcd); extern int usb_add_hcd(struct usb_hcd *hcd, unsigned int irqnum, unsigned long irqflags); extern void usb_remove_hcd(struct usb_hcd *hcd); struct platform_device; extern void <API key>(struct platform_device* dev); #ifdef CONFIG_PCI struct pci_dev; struct pci_device_id; extern int usb_hcd_pci_probe (struct pci_dev *dev, const struct pci_device_id *id); extern void usb_hcd_pci_remove (struct pci_dev *dev); #ifdef CONFIG_PM extern int usb_hcd_pci_suspend (struct pci_dev *dev, pm_message_t state); extern int usb_hcd_pci_resume (struct pci_dev *dev); #endif /* CONFIG_PM */ extern void <API key> (struct pci_dev *dev); #endif /* CONFIG_PCI */ /* pci-ish (pdev null is ok) buffer alloc/mapping support */ int hcd_buffer_create (struct usb_hcd *hcd); void hcd_buffer_destroy (struct usb_hcd *hcd); void *hcd_buffer_alloc (struct usb_bus *bus, size_t size, gfp_t mem_flags, dma_addr_t *dma); void hcd_buffer_free (struct usb_bus *bus, size_t size, void *addr, dma_addr_t dma); /* generic bus glue, needed for host controllers that don't use PCI */ extern irqreturn_t usb_hcd_irq (int irq, void *__hcd); extern void usb_hc_died (struct usb_hcd *hcd); extern void <API key>(struct usb_hcd *hcd); /* Enumeration is only for the hub driver, or HCD virtual root hubs */ extern struct usb_device *usb_alloc_dev(struct usb_device *parent, struct usb_bus *, unsigned port); extern int usb_new_device(struct usb_device *dev); extern void usb_disconnect(struct usb_device **); extern int <API key>(struct usb_device *dev); extern void <API key>(struct usb_device *dev); /* * HCD Root Hub support */ #include "hub.h" /* (shifted) direction/type/recipient from the USB 2.0 spec, table 9.2 */ #define DeviceRequest \ ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE)<<8) #define DeviceOutRequest \ ((USB_DIR_OUT|USB_TYPE_STANDARD|USB_RECIP_DEVICE)<<8) #define InterfaceRequest \ ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_INTERFACE)<<8) #define EndpointRequest \ ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_INTERFACE)<<8) #define EndpointOutRequest \ ((USB_DIR_OUT|USB_TYPE_STANDARD|USB_RECIP_INTERFACE)<<8) /* class requests from the USB 2.0 hub spec, table 11-15 */ /* GetBusState and SetHubDescriptor are optional, omitted */ #define ClearHubFeature (0x2000 | <API key>) #define ClearPortFeature (0x2300 | <API key>) #define GetHubDescriptor (0xa000 | <API key>) #define GetHubStatus (0xa000 | USB_REQ_GET_STATUS) #define GetPortStatus (0xa300 | USB_REQ_GET_STATUS) #define SetHubFeature (0x2000 | USB_REQ_SET_FEATURE) #define SetPortFeature (0x2300 | USB_REQ_SET_FEATURE) /* * Generic bandwidth allocation constants/support */ #define FRAME_TIME_USECS 1000L #define BitTime(bytecount) (7 * 8 * bytecount / 6) /* with integer truncation */ /* Trying not to use worst-case bit-stuffing of (7/6 * 8 * bytecount) = 9.33 * bytecount */ /* bytecount = data payload byte count */ #define NS_TO_US(ns) ((ns + 500L) / 1000L) /* convert & round nanoseconds to microseconds */ /* * Full/low speed bandwidth allocation constants/support. */ #define BW_HOST_DELAY 1000L /* nanoseconds */ #define BW_HUB_LS_SETUP 333L /* nanoseconds */ /* 4 full-speed bit times (est.) */ #define FRAME_TIME_BITS 12000L /* frame = 1 millisecond */ #define <API key> (90L * FRAME_TIME_BITS / 100L) #define <API key> (90L * FRAME_TIME_USECS / 100L) /* * Ceiling [nano/micro]seconds (typical) for that many bytes at high speed * ISO is a bit less, no ACK ... from USB 2.0 spec, 5.11.3 (and needed * to preallocate bandwidth) */ #define USB2_HOST_DELAY 5 /* nsec, guess */ #define HS_NSECS(bytes) ( ((55 * 8 * 2083) \ + (2083UL * (3 + BitTime(bytes))))/1000 \ + USB2_HOST_DELAY) #define HS_NSECS_ISO(bytes) ( ((38 * 8 * 2083) \ + (2083UL * (3 + BitTime(bytes))))/1000 \ + USB2_HOST_DELAY) #define HS_USECS(bytes) NS_TO_US (HS_NSECS(bytes)) #define HS_USECS_ISO(bytes) NS_TO_US (HS_NSECS_ISO(bytes)) extern long usb_calc_bus_time (int speed, int is_input, int isoc, int bytecount); extern void <API key>(struct usb_device *udev, enum usb_device_state new_state); /* exported only within usbcore */ extern struct list_head usb_bus_list; extern struct mutex usb_bus_list_lock; extern wait_queue_head_t usb_kill_urb_queue; extern void <API key> (struct usb_bus *bus); extern int <API key> (struct usb_device *dev, struct usb_interface *interface); #define usb_endpoint_out(ep_dir) (!((ep_dir) & USB_DIR_IN)) #ifdef CONFIG_PM extern void <API key> (struct usb_hcd *hcd); extern void <API key> (struct usb_device *rhdev); extern int hcd_bus_suspend(struct usb_device *rhdev); extern int hcd_bus_resume(struct usb_device *rhdev); #else static inline void <API key>(struct usb_hcd *hcd) { return; } #endif /* CONFIG_PM */ /* * USB device fs stuff */ #ifdef CONFIG_USB_DEVICEFS /* * these are expected to be called from the USB core/hub thread * with the kernel lock held */ extern void <API key> (void); extern int usbfs_init(void); extern void usbfs_cleanup(void); #else /* CONFIG_USB_DEVICEFS */ static inline void <API key> (void) {} static inline int usbfs_init(void) { return 0; } static inline void usbfs_cleanup(void) { } #endif /* CONFIG_USB_DEVICEFS */ #if defined(CONFIG_USB_MON) struct usb_mon_operations { void (*urb_submit)(struct usb_bus *bus, struct urb *urb); void (*urb_submit_error)(struct usb_bus *bus, struct urb *urb, int err); void (*urb_complete)(struct usb_bus *bus, struct urb *urb, int status); /* void (*urb_unlink)(struct usb_bus *bus, struct urb *urb); */ }; extern struct usb_mon_operations *mon_ops; static inline void usbmon_urb_submit(struct usb_bus *bus, struct urb *urb) { if (bus->monitored) (*mon_ops->urb_submit)(bus, urb); } static inline void <API key>(struct usb_bus *bus, struct urb *urb, int error) { if (bus->monitored) (*mon_ops->urb_submit_error)(bus, urb, error); } static inline void usbmon_urb_complete(struct usb_bus *bus, struct urb *urb, int status) { if (bus->monitored) (*mon_ops->urb_complete)(bus, urb, status); } int usb_mon_register(struct usb_mon_operations *ops); void usb_mon_deregister(void); #else static inline void usbmon_urb_submit(struct usb_bus *bus, struct urb *urb) {} static inline void <API key>(struct usb_bus *bus, struct urb *urb, int error) {} static inline void usbmon_urb_complete(struct usb_bus *bus, struct urb *urb, int status) {} #endif /* CONFIG_USB_MON */ /* hub.h ... DeviceRemovable in 2.4.2-ac11, gone in 2.4.10 */ // bleech -- resurfaced in 2.4.11 or 2.4.12 #define bitmap DeviceRemovable /* random stuff */ #define RUN_CONTEXT (in_irq () ? "in_irq" \ : (in_interrupt () ? "in_interrupt" : "can sleep")) /* This rwsem is for use only by the hub driver and ehci-hcd. * Nobody else should touch it. */ extern struct rw_semaphore <API key>; #endif /* __KERNEL__ */
# -*- coding: utf-8 -*- # Picard, the next-generation MusicBrainz tagger # This program is free software; you can redistribute it and/or # as published by the Free Software Foundation; either version 2 # This program is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import re from PyQt5 import QtWidgets from picard import config from picard.plugin import ExtensionPoint class OptionsCheckError(Exception): def __init__(self, title, info): self.title = title self.info = info class OptionsPage(QtWidgets.QWidget): PARENT = None SORT_ORDER = 1000 ACTIVE = True STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }" STYLESHEET = "QLabel { qproperty-wordWrap: true; }" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setStyleSheet(self.STYLESHEET) def info(self): raise NotImplementedError def check(self): pass def load(self): pass def save(self): pass def restore_defaults(self): try: options = self.options except AttributeError: return old_options = {} for option in options: if option.section == 'setting': old_options[option.name] = config.setting[option.name] config.setting[option.name] = option.default self.load() # Restore the config values incase the user doesn't save after restoring defaults for key in old_options: config.setting[key] = old_options[key] def display_error(self, error): dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self) dialog.exec_() def init_regex_checker(self, regex_edit, regex_error): """ regex_edit : a widget supporting text() and textChanged() methods, ie QLineEdit regex_error : a widget supporting setStyleSheet() and setText() methods, ie. QLabel """ def check(): try: re.compile(regex_edit.text()) except re.error as e: raise OptionsCheckError(_("Regex Error"), string_(e)) def live_checker(text): regex_error.setStyleSheet("") regex_error.setText("") try: check() except OptionsCheckError as e: regex_error.setStyleSheet(self.STYLESHEET_ERROR) regex_error.setText(e.info) regex_edit.textChanged.connect(live_checker) _pages = ExtensionPoint() def <API key>(page_class): _pages.register(page_class.__module__, page_class)
#include "defs.h" #include "target.h" #include "value.h" #include "mi-cmds.h" #include "mi-getopt.h" #include "gdb_string.h" #include "ui-out.h" #include "disasm.h" /* The arguments to be passed on the command line and parsed here are: either: START-ADDRESS: address to start the disassembly at. END-ADDRESS: address to end the disassembly at. or: FILENAME: The name of the file where we want disassemble from. LINE: The line around which we want to disassemble. It will disassemble the function that contins that line. HOW_MANY: Number of disassembly lines to display. In mixed mode, it is the number of disassembly lines only, not counting the source lines. always required: MODE: 0 or 1 for disassembly only, or mixed source and disassembly, respectively. */ void mi_cmd_disassemble (char *command, char **argv, int argc) { CORE_ADDR start; int <API key>; struct symtab *s; /* Which options have we processed ... */ int file_seen = 0; int line_seen = 0; int num_seen = 0; int start_seen = 0; int end_seen = 0; /* ... and their corresponding value. */ char *file_string = NULL; int line_num = -1; int how_many = -1; CORE_ADDR low = 0; CORE_ADDR high = 0; /* Options processing stuff. */ int optind = 0; char *optarg; enum opt { FILE_OPT, LINE_OPT, NUM_OPT, START_OPT, END_OPT }; static struct mi_opt opts[] = { {"f", FILE_OPT, 1}, {"l", LINE_OPT, 1}, {"n", NUM_OPT, 1}, {"s", START_OPT, 1}, {"e", END_OPT, 1}, { 0, 0, 0 } }; /* Get the options with their arguments. Keep track of what we encountered. */ while (1) { int opt = mi_getopt ("mi_cmd_disassemble", argc, argv, opts, &optind, &optarg); if (opt < 0) break; switch ((enum opt) opt) { case FILE_OPT: file_string = xstrdup (optarg); file_seen = 1; break; case LINE_OPT: line_num = atoi (optarg); line_seen = 1; break; case NUM_OPT: how_many = atoi (optarg); num_seen = 1; break; case START_OPT: low = <API key> (optarg); start_seen = 1; break; case END_OPT: high = <API key> (optarg); end_seen = 1; break; } } argv += optind; argc -= optind; /* Allow only filename + linenum (with how_many which is not required) OR start_addr + and_addr */ if (!((line_seen && file_seen && num_seen && !start_seen && !end_seen) || (line_seen && file_seen && !num_seen && !start_seen && !end_seen) || (!line_seen && !file_seen && !num_seen && start_seen && end_seen))) error ("mi_cmd_disassemble: Usage: ( [-f filename -l linenum [-n howmany]] | [-s startaddr -e endaddr]) [--] mixed_mode."); if (argc != 1) error ("mi_cmd_disassemble: Usage: [-f filename -l linenum [-n howmany]] [-s startaddr -e endaddr] [--] mixed_mode."); <API key> = atoi (argv[0]); if ((<API key> != 0) && (<API key> != 1)) error (_("mi_cmd_disassemble: Mixed_mode argument must be 0 or 1.")); /* We must get the function beginning and end where line_num is contained. */ if (line_seen && file_seen) { s = lookup_symtab (file_string); if (s == NULL) error (_("mi_cmd_disassemble: Invalid filename.")); if (!find_line_pc (s, line_num, &start)) error (_("mi_cmd_disassemble: Invalid line number")); if (<API key> (start, NULL, &low, &high) == 0) error (_("mi_cmd_disassemble: No function contains specified address")); } gdb_disassembly (uiout, file_string, line_num, <API key>, how_many, low, high); }
<?php namespace DynamicHub\Module\Match; class MatchBaseConfig{ // players public $maxPlayers; public $semiMaxPlayers; public $minPlayers; // time, in seconds public $minWaitTime; public $maxWaitTime; public $maxMatchTime; public $maxPrepTime; // positions public $playerJoinPositions = []; public $<API key> = []; public function <API key>(){ if(next($this->playerJoinPositions) === false){ reset($this->playerJoinPositions); } return current($this->playerJoinPositions); } public function <API key>(){ if(next($this-><API key>) === false){ reset($this-><API key>); } return current($this-><API key>); } }
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http: <head> <title>schrodinger.application.desmond.<API key>.ProteinReport</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" >2015-2Schrodinger Python API</th> </tr></table></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="schrodinger-module.html">Package&nbsp;schrodinger</a> :: <a href="schrodinger.application-module.html">Package&nbsp;application</a> :: <a href="schrodinger.application.desmond-module.html">Package&nbsp;desmond</a> :: <a href="schrodinger.application.desmond.<API key>.html">Module&nbsp;<API key></a> :: Class&nbsp;ProteinReport </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="schrodinger.application.desmond.<API key>.ProteinReport-class.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <h1 class="epydoc">Class ProteinReport</h1><p class="nomargin-top"></p> <pre class="base-tree"> <a href="object-class.html">object</a> | <strong class="uidshort">ProteinReport</strong> </pre> <hr /> <a name="<API key>"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Instance Methods</span></td> <td align="right" valign="top" ><span class="options">[<a href="#<API key>" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.application.desmond.<API key>.ProteinReport-class.html#__init__" class="summary-sig-name">__init__</a>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">cms_st</span>)</span><br /> x.__init__(...) initializes x; see help(type(x)) for signature</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="export"></a><span class="summary-sig-name">export</span>(<span class="summary-sig-arg">self</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="get_hot_atoms"></a><span class="summary-sig-name">get_hot_atoms</span>(<span class="summary-sig-arg">self</span>)</span><br /> Returns number of atoms in the hot region</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="get_residues"></a><span class="summary-sig-name">get_residues</span>(<span class="summary-sig-arg">self</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="get_number_atoms"></a><span class="summary-sig-name">get_number_atoms</span>(<span class="summary-sig-arg">self</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="get_protein"></a><span class="summary-sig-name">get_protein</span>(<span class="summary-sig-arg">self</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="<API key>"><b>Inherited from <code><a href="object-class.html">object</a></code></b>: <code><a href="object-class.html#__delattr__">__delattr__</a></code>, <code><a href="object-class.html#__format__">__format__</a></code>, <code><a href="object-class.html#__getattribute__">__getattribute__</a></code>, <code><a href="object-class.html#__hash__">__hash__</a></code>, <code><a href="object-class.html#__new__">__new__</a></code>, <code><a href="object-class.html#__reduce__">__reduce__</a></code>, <code><a href="object-class.html#__reduce_ex__">__reduce_ex__</a></code>, <code><a href="object-class.html#__repr__">__repr__</a></code>, <code><a href="object-class.html#__setattr__">__setattr__</a></code>, <code><a href="object-class.html#__sizeof__">__sizeof__</a></code>, <code><a href="object-class.html#__str__">__str__</a></code>, <code><a href="object-class.html#__subclasshook__">__subclasshook__</a></code> </p> </td> </tr> </table> <a name="section-Properties"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Properties</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Properties" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="<API key>"><b>Inherited from <code><a href="object-class.html">object</a></code></b>: <code><a href="object-class.html#__class__">__class__</a></code> </p> </td> </tr> </table> <a name="<API key>"></a> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Method Details</span></td> <td align="right" valign="top" ><span class="options">[<a href="#<API key>" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> </table> <a name="__init__"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">__init__</span>(<span class="sig-arg">self</span>, <span class="sig-arg">cms_st</span>)</span> <br /><em class="fname">(Constructor)</em> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>x.__init__(...) initializes x; see help(type(x)) for signature</p> <dl class="fields"> <dt>Overrides: object.__init__ <dd><em class="note">(inherited documentation)</em></dd> </dt> </dl> </td></tr></table> </div> <br /> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" >2015-2Schrodinger Python API</th> </tr></table></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Sat May 9 06:31:10 2015 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <! // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); </script> </body> </html>
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> <meta name="<API key>" content="black"> <meta name="<API key>" content="<?php gp_keywords(); ?>"> <meta name="keywords" content="<?php gp_keywords(); ?>" /> <meta name="description" itemprop="description" content="<?php gp_description(); ?>" /> <link rel="stylesheet" href="<?php echo <API key>(); ?>/dist/css/main.css"/> <title><?php wp_title( '_', true, 'right' ); bloginfo( 'name' ); ?></title> </head> <body> <header class="head-s"> <div class="r"> <a href="/book_tag" class="l" title=""><i class="icon-search"></i></a> <a href="/" class="l" title=""><i class="icon-home"></i></a> </div> <a href="/" class="l"><i class="icon-pre"></i></a> <h3></h3> </header> <div class="content"> <div class="help-box"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php the_content( __( '<p class="serif">Read the rest of this page &rarr;</p>', 'gampress' ) ); ?> <?php endwhile; endif; ?> </div> </div> <?php get_footer();?>
<!DOCTYPE html> <html lang="en-us"> <head> <meta charset="UTF-8"> <title>8v18.GitHub.io by 8v18</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="stylesheets/normalize.css" media="screen"> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen"> <link rel="stylesheet" type="text/css" href="stylesheets/github-light.css" media="screen"> </head> <body> <section class="page-header"> <h1 class="project-name">8v18.GitHub.io</h1> <h2 class="project-tagline"></h2> </section> <section class="main-content"> <h3> <a id="<API key>" class="anchor" href="#<API key>" aria-hidden="true"><span class="octicon octicon-link"></span></a>Welcome to GitHub Pages.</h3> <p>This automatic page generator is the easiest way to create beautiful pages for all of your projects. Author your page content here <a href="https: <h3> <a id="designer-templates" class="anchor" href="#designer-templates" aria-hidden="true"><span class="octicon octicon-link"></span></a>Designer Templates</h3> <p>We’ve crafted some handsome templates for you to use. Go ahead and click 'Continue to layouts' to browse through them. You can easily go back to edit your page before publishing. After publishing your page, you can revisit the page generator and switch to another theme. Your Page content will be preserved.</p> <h3> <a id="<API key>" class="anchor" href="#<API key>" aria-hidden="true"><span class="octicon octicon-link"></span></a>Creating pages manually</h3> <p>If you prefer to not use the automatic generator, push a branch named <code>gh-pages</code> to your repository to create a page manually. In addition to supporting regular HTML content, GitHub Pages support Jekyll, a simple, blog aware static site generator. Jekyll makes it easy to create site-wide headers and footers without having to copy them across every page. It also offers intelligent blog support and other advanced templating features.</p> <h3> <a id="<API key> class="anchor" href="#<API key> aria-hidden="true"><span class="octicon octicon-link"></span></a>Authors and Contributors</h3> <p>You can <a href="https: <h3> <a id="support-or-contact" class="anchor" href="#support-or-contact" aria-hidden="true"><span class="octicon octicon-link"></span></a>Support or Contact</h3> <p>Having trouble with Pages? Check out our <a href="https: <footer class="site-footer"> <span class="site-footer-credits">This page was generated by <a href="https: </footer> </section> </body> </html>
<<<< HEAD <p>The <strong>view type</strong> describes how this view is stored; Views is capable of having Views entirely in code that are not in the database. This allows modules to easily ship with Views built in, and it allows you to create a module to store your views for easy deployment between development and production servers.</p> <dl> <dt><strong>Normal</strong></dt> <dd>Normal views are stored in your database and are completely local to your system.</dd> <dt><strong>Default</strong></dt> <dd>Default views are stored only in code and are not anywhere in your database. They may be <strong>enabled</strong> or <strong>disabled</strong> but you may not completely remove them from your system. You can <strong>override</strong> the view which will create a local copy of your view. If you do this, future updates to the version in code will not affect your view.</dd> <dt><strong>Overridden</strong></dt> <dd>Overridden views are stored both in code and in the database; while overridden, the version that is in code is completely dormant. If you <strong>revert</strong> the view, the version in the database will be deleted, and the version that is in code will once again be used.</dd> </dl> You may store your views in code with the following procedure: <ol> <li> Create a module to store the views. </li> <li> Add the function <em><API key>()</em> to this module. </li> <li> Export the view you wish to store in your module in code. Cut and paste that into the abovenamed function. Make sure the last line of the view is: <em>$views[$view-&gt;name] = $view;</em></li> <li> Make sure the last line of the function is <em>return $views;</em></li> <li> After you make any changes, be sure to <strong>clear the Views' cache</strong>. You may do this from the <strong>Tools</strong> menu.</li> </ol> ==== <p>The <strong>view type</strong> describes how this view is stored; Views is capable of having Views entirely in code that are not in the database. This allows modules to easily ship with Views built in, and it allows you to create a module to store your views for easy deployment between development and production servers.</p> <dl> <dt><strong>Normal</strong></dt> <dd>Normal views are stored in your database and are completely local to your system.</dd> <dt><strong>Default</strong></dt> <dd>Default views are stored only in code and are not anywhere in your database. They may be <strong>enabled</strong> or <strong>disabled</strong> but you may not completely remove them from your system. You can <strong>override</strong> the view which will create a local copy of your view. If you do this, future updates to the version in code will not affect your view.</dd> <dt><strong>Overridden</strong></dt> <dd>Overridden views are stored both in code and in the database; while overridden, the version that is in code is completely dormant. If you <strong>revert</strong> the view, the version in the database will be deleted, and the version that is in code will once again be used.</dd> </dl> You may store your views in code with the following procedure: <ol> <li> Create a module to store the views. </li> <li> Add the function <em><API key>()</em> to this module. </li> <li> Export the view you wish to store in your module in code. Cut and paste that into the abovenamed function. Make sure the last line of the view is: <em>$views[$view-&gt;name] = $view;</em></li> <li> Make sure the last line of the function is <em>return $views;</em></li> <li> After you make any changes, be sure to <strong>clear the Views' cache</strong>. You may do this from the <strong>Tools</strong> menu.</li> </ol> >>>> <SHA1-like>
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include "duktape.h" #include "prg.h" static struct prg *prg_call; static struct native_mod *prg_native_modules; int prg_register(struct prg *prg, struct native_mod *native_modules) { prg_call = prg; prg_native_modules = native_modules; return 0; } struct mod *prg_storage_byname(const char *name) { struct mod *mod; for(mod = prg_call->modules; mod; mod=mod->next) { if(!strcmp(mod->fullname, name)) return mod; } return (void*)0; } struct mod *prg_storage_byid(int id) { struct mod *mod; for(mod = prg_call->modules; mod; mod=mod->next) { if(mod->id == id) return mod; } return (void*)0; } static struct mod *mod_new() { struct mod *m; m = malloc(sizeof(struct mod)); if(m) memset(m, 0, sizeof(struct mod)); return m; } int <API key>(duk_context *ctx) { int ret; struct prg *prg = prg_call; duk_compile(ctx, 0); close(prg->fd); munmap(prg->buf, prg->size); <API key>(ctx); /* 'this' binding */ duk_call_method(ctx, 0); prg->status = duk_to_int(ctx, -1); duk_pop(ctx); // pop return value // Check if global property 'main' exists <API key>(ctx); ret = duk_get_prop_string(ctx, -1, "main"); duk_remove(ctx, -2); // remove global object // If main exists we call it if(ret && duk_get_type(ctx, -1) != DUK_TYPE_UNDEFINED) { int i; <API key>(ctx); /* 'this' binding */ for(i=1;i<prg->argc;i++) { duk_push_string(ctx, prg->argv[i]); } duk_call_method(ctx, prg->argc-1); prg->status = duk_to_int(ctx, -1); } duk_pop(ctx); return 0; // no values returned (0) } static int x(duk_context *ctx) { duk_push_string(ctx, "hello from x"); return 1; } static const <API key> x_funcs[] = { { "x", x, 0 }, { NULL, NULL, 0 } }; /* Duktape.modSearch = function (id, require, exports, module) */ static int modSearch(duk_context *ctx) { struct mod *mod; struct prg *prg; int i; prg = prg_call; const char *id = duk_to_string(ctx, 0); /* * To support the native module case, the module search function can also return undefined * (or any non-string value), in which case Duktape will assume that the module was found * but has no Ecmascript source to execute. Symbols written to exports in the module search * function are the only symbols provided by the module. */ for(i=0;;i++) { if(!prg_native_modules[i].name) break; if(!strcmp(id, prg_native_modules[i].name)) { prg_native_modules[i].fn(ctx, 2, prg); duk_push_undefined(ctx); return 1; } } if(!strcmp(id, "x")) { <API key>(ctx, 2, x_funcs); duk_push_undefined(ctx); return 1; } /* * If a module is found, the module search function can return a string providing the source * code for the module. Duktape will then take care of compiling and executing the module code * so that module symbols get registered into the exports object. */ for(mod=prg->modules;mod;mod=mod->next) { if(!strcmp(mod->name, id)) { duk_push_lstring(ctx, mod->buf, mod->size); return 1; } } duk_error(ctx, DUK_ERR_ERROR, "failed to find module '%s'", id); return DUK_RET_ERROR; } int prg_push_modsearch(duk_context *ctx) { duk_get_prop_string(ctx, -1, "Duktape"); duk_push_c_function(ctx, modSearch, 4); duk_put_prop_string(ctx, -2, "modSearch"); duk_pop(ctx); // pop Duktape return 0; } int prg_parse_appfile(struct prg *prg) { char *p, *endp, *start, *m, *mainstart; off_t offset, pa_offset; struct mod *mod; int id = 1000; // read file prg->name prg->fd = open(prg->name, O_RDONLY); if(prg->fd == -1) { exit(1); } prg->size = lseek(prg->fd, 0, SEEK_END); prg->buf = mmap((void*)0, prg->size, PROT_READ, MAP_PRIVATE, prg->fd, 0); /* parse file header */ p = prg->buf; endp = prg->buf + prg->size; if(*p == ' while((p < endp) && (*p != '\n')) p++; if(p >= endp) { fprintf(stderr, "EOF\n"); exit(1); } p++; } mainstart = p; mod = mod_new(); mod->id = id++; for(start=p;p < endp;p++) { if(*p == '\n') { /* is this a module specification? */ for(m = start; *m == ' '; m++); if((*m >= '0') && (*m <= '9')) { mod->size = strtoul(m, &m, 10); if(!m) break; if(*m != ' ') break; m++; mod->name = strndup(m, p-m); mod->fullname = strdup(mod->name); if(!strcmp(mod->name, "total")) break; mod->next = prg->modules; prg->modules = mod; mod = mod_new(); mod->id = id++; } else break; start = p+1; } } offset = prg->size; for(mod = prg->modules; mod; mod=mod->next) { offset -= mod->size; pa_offset = offset & ~(sysconf(_SC_PAGE_SIZE) - 1); mod->buf = mmap((void*)0, mod->size + offset - pa_offset, PROT_READ, MAP_PRIVATE, prg->fd, pa_offset); if(mod->buf == MAP_FAILED) { fprintf(stderr, "mmap failed\n"); exit(1); } mod->buf += (offset - pa_offset); } for(mod = prg->modules; mod; mod=mod->next) { char *p; if((p=strrchr(mod->name, '.'))) { if(!strcmp(p, ".js")) *p=0; } } for(mod = prg->modules; mod; mod=mod->next) { if(!strcmp(mod->name, "main")) { prg->main = mod; } else { char *p; if((p=strrchr(mod->name, '/'))) { if(!strcmp(p+1, "main")) { prg->main = mod; } } } } if(!prg->modules) { prg->main = mod_new(); prg->main->id = id++; prg->main->buf = mainstart; prg->main->size = prg->size - (mainstart - prg->buf); prg->main->name = "main"; prg->main->fullname = "main"; } if(!prg->main) { fprintf(stderr, "no main module\n"); exit(1); } return 0; } static int prg1_storage(duk_context *ctx) { const char *name = duk_to_string(ctx, 0); struct mod *mod; mod = prg_storage_byname(name); if(mod) { duk_push_object(ctx); duk_push_int(ctx, mod->id); duk_put_prop_string(ctx, -2, "id"); duk_push_int(ctx, mod->size); duk_put_prop_string(ctx, -2, "size"); duk_push_string(ctx, mod->name); duk_put_prop_string(ctx, -2, "name"); duk_push_string(ctx, mod->fullname); duk_put_prop_string(ctx, -2, "fullname"); } else { duk_push_undefined(ctx); } return 1; } static int prg1_storage_write(duk_context *ctx) { struct mod *mod; int rc = -1; int id, fd; size_t offset, len; fd = duk_to_int(ctx, 0); id = duk_to_int(ctx, 1); offset = duk_to_int(ctx, 2); len = duk_to_int(ctx, 3); mod = prg_storage_byid(id); if(mod) { rc = write(fd, mod->buf + offset, len); } duk_push_int(ctx, rc); return 1; } static int prg1_storage_buffer(duk_context *ctx) { struct mod *mod; int id; size_t offset, len; char *buf; id = duk_to_int(ctx, 0); offset = duk_to_int(ctx, 1); len = duk_to_int(ctx, 2); mod = prg_storage_byid(id); if(mod) { buf = <API key>(ctx, len); memcpy(buf, mod->buf + offset, len); } else { duk_push_undefined(ctx); } return 1; } static const <API key> prg1_funcs[] = { { "storage", prg1_storage, 1 /* name */ }, { "storage_write", prg1_storage_write, 4 /* fd, id, offset, len */ }, { "storage_buffer", prg1_storage_buffer, 4 /* id, offset, len */ }, { NULL, NULL, 0 } }; static const <API key> prg1_consts[] = { { NULL, 0.0 } }; int prg1_load(duk_context *ctx, int n, struct prg *prg) { <API key>(ctx, n, prg1_funcs); duk_put_number_list(ctx, n, prg1_consts); return 0; }
#include "hw.h" #include "pxa.h" #define ICIP 0x00 /* Interrupt Controller IRQ Pending register */ #define ICMR 0x04 /* Interrupt Controller Mask register */ #define ICLR 0x08 /* Interrupt Controller Level register */ #define ICFP 0x0c /* Interrupt Controller FIQ Pending register */ #define ICPR 0x10 /* Interrupt Controller Pending register */ #define ICCR 0x14 /* Interrupt Controller Control register */ #define ICHP 0x18 /* Interrupt Controller Highest Priority register */ #define IPR0 0x1c /* Interrupt Controller Priority register 0 */ #define IPR31 0x98 /* Interrupt Controller Priority register 31 */ #define ICIP2 0x9c /* Interrupt Controller IRQ Pending register 2 */ #define ICMR2 0xa0 /* Interrupt Controller Mask register 2 */ #define ICLR2 0xa4 /* Interrupt Controller Level register 2 */ #define ICFP2 0xa8 /* Interrupt Controller FIQ Pending register 2 */ #define ICPR2 0xac /* Interrupt Controller Pending register 2 */ #define IPR32 0xb0 /* Interrupt Controller Priority register 32 */ #define IPR39 0xcc /* Interrupt Controller Priority register 39 */ #define PXA2XX_PIC_SRCS 40 typedef struct { CPUState *cpu_env; uint32_t int_enabled[2]; uint32_t int_pending[2]; uint32_t is_fiq[2]; uint32_t int_idle; uint32_t priority[PXA2XX_PIC_SRCS]; } PXA2xxPICState; static void pxa2xx_pic_update(void *opaque) { uint32_t mask[2]; PXA2xxPICState *s = (PXA2xxPICState *) opaque; if (s->cpu_env->halted) { mask[0] = s->int_pending[0] & (s->int_enabled[0] | s->int_idle); mask[1] = s->int_pending[1] & (s->int_enabled[1] | s->int_idle); if (mask[0] || mask[1]) cpu_interrupt(s->cpu_env, <API key>); } mask[0] = s->int_pending[0] & s->int_enabled[0]; mask[1] = s->int_pending[1] & s->int_enabled[1]; if ((mask[0] & s->is_fiq[0]) || (mask[1] & s->is_fiq[1])) cpu_interrupt(s->cpu_env, CPU_INTERRUPT_FIQ); else cpu_reset_interrupt(s->cpu_env, CPU_INTERRUPT_FIQ); if ((mask[0] & ~s->is_fiq[0]) || (mask[1] & ~s->is_fiq[1])) cpu_interrupt(s->cpu_env, CPU_INTERRUPT_HARD); else cpu_reset_interrupt(s->cpu_env, CPU_INTERRUPT_HARD); } /* Note: Here level means state of the signal on a pin, not * IRQ/FIQ distinction as in PXA Developer Manual. */ static void pxa2xx_pic_set_irq(void *opaque, int irq, int level) { PXA2xxPICState *s = (PXA2xxPICState *) opaque; int int_set = (irq >= 32); irq &= 31; if (level) s->int_pending[int_set] |= 1 << irq; else s->int_pending[int_set] &= ~(1 << irq); pxa2xx_pic_update(opaque); } static inline uint32_t pxa2xx_pic_highest(PXA2xxPICState *s) { int i, int_set, irq; uint32_t bit, mask[2]; uint32_t ichp = 0x003f003f; /* Both IDs invalid */ mask[0] = s->int_pending[0] & s->int_enabled[0]; mask[1] = s->int_pending[1] & s->int_enabled[1]; for (i = PXA2XX_PIC_SRCS - 1; i >= 0; i irq = s->priority[i] & 0x3f; if ((s->priority[i] & (1 << 31)) && irq < PXA2XX_PIC_SRCS) { /* Source peripheral ID is valid. */ bit = 1 << (irq & 31); int_set = (irq >= 32); if (mask[int_set] & bit & s->is_fiq[int_set]) { /* FIQ asserted */ ichp &= 0xffff0000; ichp |= (1 << 15) | irq; } if (mask[int_set] & bit & ~s->is_fiq[int_set]) { /* IRQ asserted */ ichp &= 0x0000ffff; ichp |= (1 << 31) | (irq << 16); } } } return ichp; } static uint32_t pxa2xx_pic_mem_read(void *opaque, target_phys_addr_t offset) { PXA2xxPICState *s = (PXA2xxPICState *) opaque; switch (offset) { case ICIP: /* IRQ Pending register */ return s->int_pending[0] & ~s->is_fiq[0] & s->int_enabled[0]; case ICIP2: /* IRQ Pending register 2 */ return s->int_pending[1] & ~s->is_fiq[1] & s->int_enabled[1]; case ICMR: /* Mask register */ return s->int_enabled[0]; case ICMR2: /* Mask register 2 */ return s->int_enabled[1]; case ICLR: /* Level register */ return s->is_fiq[0]; case ICLR2: /* Level register 2 */ return s->is_fiq[1]; case ICCR: /* Idle mask */ return (s->int_idle == 0); case ICFP: /* FIQ Pending register */ return s->int_pending[0] & s->is_fiq[0] & s->int_enabled[0]; case ICFP2: /* FIQ Pending register 2 */ return s->int_pending[1] & s->is_fiq[1] & s->int_enabled[1]; case ICPR: /* Pending register */ return s->int_pending[0]; case ICPR2: /* Pending register 2 */ return s->int_pending[1]; case IPR0 ... IPR31: return s->priority[0 + ((offset - IPR0 ) >> 2)]; case IPR32 ... IPR39: return s->priority[32 + ((offset - IPR32) >> 2)]; case ICHP: /* Highest Priority register */ return pxa2xx_pic_highest(s); default: printf("%s: Bad register offset " REG_FMT "\n", __FUNCTION__, offset); return 0; } } static void <API key>(void *opaque, target_phys_addr_t offset, uint32_t value) { PXA2xxPICState *s = (PXA2xxPICState *) opaque; switch (offset) { case ICMR: /* Mask register */ s->int_enabled[0] = value; break; case ICMR2: /* Mask register 2 */ s->int_enabled[1] = value; break; case ICLR: /* Level register */ s->is_fiq[0] = value; break; case ICLR2: /* Level register 2 */ s->is_fiq[1] = value; break; case ICCR: /* Idle mask */ s->int_idle = (value & 1) ? 0 : ~0; break; case IPR0 ... IPR31: s->priority[0 + ((offset - IPR0 ) >> 2)] = value & 0x8000003f; break; case IPR32 ... IPR39: s->priority[32 + ((offset - IPR32) >> 2)] = value & 0x8000003f; break; default: printf("%s: Bad register offset " REG_FMT "\n", __FUNCTION__, offset); return; } pxa2xx_pic_update(opaque); } /* Interrupt Controller Coprocessor Space Register Mapping */ static const int pxa2xx_cp_reg_map[0x10] = { [0x0 ... 0xf] = -1, [0x0] = ICIP, [0x1] = ICMR, [0x2] = ICLR, [0x3] = ICFP, [0x4] = ICPR, [0x5] = ICHP, [0x6] = ICIP2, [0x7] = ICMR2, [0x8] = ICLR2, [0x9] = ICFP2, [0xa] = ICPR2, }; static uint32_t pxa2xx_pic_cp_read(void *opaque, int op2, int reg, int crm, void *retaddr) { target_phys_addr_t offset; if (pxa2xx_cp_reg_map[reg] == -1) { printf("%s: Bad register 0x%x\n", __FUNCTION__, reg); return 0; } offset = pxa2xx_cp_reg_map[reg]; return pxa2xx_pic_mem_read(opaque, offset); } static void pxa2xx_pic_cp_write(void *opaque, int op2, int reg, int crm, uint32_t value, void *retaddr) { target_phys_addr_t offset; if (pxa2xx_cp_reg_map[reg] == -1) { printf("%s: Bad register 0x%x\n", __FUNCTION__, reg); return; } offset = pxa2xx_cp_reg_map[reg]; <API key>(opaque, offset, value); } static CPUReadMemoryFunc * const pxa2xx_pic_readfn[] = { pxa2xx_pic_mem_read, pxa2xx_pic_mem_read, pxa2xx_pic_mem_read, }; static CPUWriteMemoryFunc * const pxa2xx_pic_writefn[] = { <API key>, <API key>, <API key>, }; static void pxa2xx_pic_save(QEMUFile *f, void *opaque) { PXA2xxPICState *s = (PXA2xxPICState *) opaque; int i; for (i = 0; i < 2; i ++) qemu_put_be32s(f, &s->int_enabled[i]); for (i = 0; i < 2; i ++) qemu_put_be32s(f, &s->int_pending[i]); for (i = 0; i < 2; i ++) qemu_put_be32s(f, &s->is_fiq[i]); qemu_put_be32s(f, &s->int_idle); for (i = 0; i < PXA2XX_PIC_SRCS; i ++) qemu_put_be32s(f, &s->priority[i]); } static int pxa2xx_pic_load(QEMUFile *f, void *opaque, int version_id) { PXA2xxPICState *s = (PXA2xxPICState *) opaque; int i; for (i = 0; i < 2; i ++) qemu_get_be32s(f, &s->int_enabled[i]); for (i = 0; i < 2; i ++) qemu_get_be32s(f, &s->int_pending[i]); for (i = 0; i < 2; i ++) qemu_get_be32s(f, &s->is_fiq[i]); qemu_get_be32s(f, &s->int_idle); for (i = 0; i < PXA2XX_PIC_SRCS; i ++) qemu_get_be32s(f, &s->priority[i]); pxa2xx_pic_update(opaque); return 0; } qemu_irq *pxa2xx_pic_init(target_phys_addr_t base, CPUState *env) { PXA2xxPICState *s; int iomemtype; qemu_irq *qi; s = (PXA2xxPICState *) qemu_mallocz(sizeof(PXA2xxPICState)); if (!s) return NULL; s->cpu_env = env; s->int_pending[0] = 0; s->int_pending[1] = 0; s->int_enabled[0] = 0; s->int_enabled[1] = 0; s->is_fiq[0] = 0; s->is_fiq[1] = 0; qi = qemu_allocate_irqs(pxa2xx_pic_set_irq, s, PXA2XX_PIC_SRCS); /* Enable IC memory-mapped registers access. */ iomemtype = <API key>(pxa2xx_pic_readfn, pxa2xx_pic_writefn, s, <API key>); <API key>(base, 0x00100000, iomemtype); /* Enable IC coprocessor access. */ cpu_arm_set_cp_io(env, 6, pxa2xx_pic_cp_read, pxa2xx_pic_cp_write, s); register_savevm(NULL, "pxa2xx_pic", 0, 0, pxa2xx_pic_save, pxa2xx_pic_load, s); return qi; }
#include <linux/module.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/jiffies.h> #include <asm/system.h> #include <asm/io.h> #include <asm/setup.h> #include <asm/amigaints.h> #include <asm/amigahw.h> #include <asm/amigayle.h> #include <asm/amipcmcia.h> #include "8390.h" #define DRV_NAME "apne" #define NE_BASE (dev->base_addr) #define NE_CMD 0x00 #define NE_DATAPORT 0x10 #define NE_RESET 0x1f #define NE_IO_EXTENT 0x20 #define NE_EN0_ISR 0x07 #define NE_EN0_DCFG 0x0e #define NE_EN0_RSARLO 0x08 #define NE_EN0_RSARHI 0x09 #define NE_EN0_RCNTLO 0x0a #define NE_EN0_RXCR 0x0c #define NE_EN0_TXCR 0x0d #define NE_EN0_RCNTHI 0x0b #define NE_EN0_IMR 0x0f #define NE1SM_START_PG 0x20 #define NE1SM_STOP_PG 0x40 #define NESM_START_PG 0x40 #define NESM_STOP_PG 0x80 struct net_device * __init apne_probe(int unit); static int apne_probe1(struct net_device *dev, int ioaddr); static void apne_reset_8390(struct net_device *dev); static void apne_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr, int ring_page); static void apne_block_input(struct net_device *dev, int count, struct sk_buff *skb, int ring_offset); static void apne_block_output(struct net_device *dev, const int count, const unsigned char *buf, const int start_page); static irqreturn_t apne_interrupt(int irq, void *dev_id); static int init_pcmcia(void); #define IOBASE 0x300 static const char version[] = "apne.c:v1.1 7/10/98 Alain Malek (Alain.Malek@cryogen.ch)\n"; static int apne_owned; struct net_device * __init apne_probe(int unit) { struct net_device *dev; #ifndef MANUAL_CONFIG char tuple[8]; #endif int err; if (!MACH_IS_AMIGA) return ERR_PTR(-ENODEV); if (apne_owned) return ERR_PTR(-ENODEV); if ( !(AMIGAHW_PRESENT(PCMCIA)) ) return ERR_PTR(-ENODEV); printk("Looking for PCMCIA ethernet card : "); if (!(PCMCIA_INSERTED)) { printk("NO PCMCIA card inserted\n"); return ERR_PTR(-ENODEV); } dev = alloc_ei_netdev(); if (!dev) return ERR_PTR(-ENOMEM); if (unit >= 0) { sprintf(dev->name, "eth%d", unit); <API key>(dev); } pcmcia_disable_irq(); #ifndef MANUAL_CONFIG if ((pcmcia_copy_tuple(CISTPL_FUNCID, tuple, 8) < 3) || (tuple[2] != <API key>)) { printk("not an ethernet card\n"); free_netdev(dev); return ERR_PTR(-ENODEV); } #endif printk("ethernet PCMCIA card inserted\n"); if (!init_pcmcia()) { free_netdev(dev); return ERR_PTR(-ENODEV); } if (!request_region(IOBASE, 0x20, DRV_NAME)) { free_netdev(dev); return ERR_PTR(-EBUSY); } err = apne_probe1(dev, IOBASE); if (err) { release_region(IOBASE, 0x20); free_netdev(dev); return ERR_PTR(err); } err = register_netdev(dev); if (!err) return dev; pcmcia_disable_irq(); free_irq(IRQ_AMIGA_PORTS, dev); pcmcia_reset(); release_region(IOBASE, 0x20); free_netdev(dev); return ERR_PTR(err); } static int __init apne_probe1(struct net_device *dev, int ioaddr) { int i; unsigned char SA_prom[32]; int wordlength = 2; const char *name = NULL; int start_page, stop_page; #ifndef MANUAL_HWADDR0 int neX000, ctron; #endif static unsigned version_printed; if (ei_debug && version_printed++ == 0) printk(version); printk("PCMCIA NE*000 ethercard probe"); { unsigned long reset_start_time = jiffies; outb(inb(ioaddr + NE_RESET), ioaddr + NE_RESET); while ((inb(ioaddr + NE_EN0_ISR) & ENISR_RESET) == 0) if (time_after(jiffies, reset_start_time + 2*HZ/100)) { printk(" not found (no reset ack).\n"); return -ENODEV; } outb(0xff, ioaddr + NE_EN0_ISR); } #ifndef MANUAL_HWADDR0 { struct {unsigned long value, offset; } program_seq[] = { {E8390_NODMA+E8390_PAGE0+E8390_STOP, NE_CMD}, {0x48, NE_EN0_DCFG}, {0x00, NE_EN0_RCNTLO}, {0x00, NE_EN0_RCNTHI}, {0x00, NE_EN0_IMR}, {0xFF, NE_EN0_ISR}, {E8390_RXOFF, NE_EN0_RXCR}, {E8390_TXOFF, NE_EN0_TXCR}, {32, NE_EN0_RCNTLO}, {0x00, NE_EN0_RCNTHI}, {0x00, NE_EN0_RSARLO}, {0x00, NE_EN0_RSARHI}, {E8390_RREAD+E8390_START, NE_CMD}, }; for (i = 0; i < ARRAY_SIZE(program_seq); i++) { outb(program_seq[i].value, ioaddr + program_seq[i].offset); } } for(i = 0; i < 32 ; i+=2) { SA_prom[i] = inb(ioaddr + NE_DATAPORT); SA_prom[i+1] = inb(ioaddr + NE_DATAPORT); if (SA_prom[i] != SA_prom[i+1]) wordlength = 1; } if (wordlength == 2) for (i = 0; i < 16; i++) SA_prom[i] = SA_prom[i+i]; if (wordlength == 2) { outb(0x49, ioaddr + NE_EN0_DCFG); start_page = NESM_START_PG; stop_page = NESM_STOP_PG; } else { start_page = NE1SM_START_PG; stop_page = NE1SM_STOP_PG; } neX000 = (SA_prom[14] == 0x57 && SA_prom[15] == 0x57); ctron = (SA_prom[0] == 0x00 && SA_prom[1] == 0x00 && SA_prom[2] == 0x1d); if (neX000) { name = (wordlength == 2) ? "NE2000" : "NE1000"; } else if (ctron) { name = (wordlength == 2) ? "Ctron-8" : "Ctron-16"; start_page = 0x01; stop_page = (wordlength == 2) ? 0x40 : 0x20; } else { printk(" not found.\n"); return -ENXIO; } #else wordlength = 2; outb(0x49, ioaddr + NE_EN0_DCFG); start_page = NESM_START_PG; stop_page = NESM_STOP_PG; SA_prom[0] = MANUAL_HWADDR0; SA_prom[1] = MANUAL_HWADDR1; SA_prom[2] = MANUAL_HWADDR2; SA_prom[3] = MANUAL_HWADDR3; SA_prom[4] = MANUAL_HWADDR4; SA_prom[5] = MANUAL_HWADDR5; name = "NE2000"; #endif dev->base_addr = ioaddr; dev->irq = IRQ_AMIGA_PORTS; dev->netdev_ops = &ei_netdev_ops; i = request_irq(dev->irq, apne_interrupt, IRQF_SHARED, DRV_NAME, dev); if (i) return i; for(i = 0; i < ETHER_ADDR_LEN; i++) dev->dev_addr[i] = SA_prom[i]; printk(" %pM\n", dev->dev_addr); printk("%s: %s found.\n", dev->name, name); ei_status.name = name; ei_status.tx_start_page = start_page; ei_status.stop_page = stop_page; ei_status.word16 = (wordlength == 2); ei_status.rx_start_page = start_page + TX_PAGES; ei_status.reset_8390 = &apne_reset_8390; ei_status.block_input = &apne_block_input; ei_status.block_output = &apne_block_output; ei_status.get_8390_hdr = &apne_get_8390_hdr; NS8390_init(dev, 0); pcmcia_ack_int(pcmcia_get_intreq()); pcmcia_enable_irq(); apne_owned = 1; return 0; } static void apne_reset_8390(struct net_device *dev) { unsigned long reset_start_time = jiffies; init_pcmcia(); if (ei_debug > 1) printk("resetting the 8390 t=%ld...", jiffies); outb(inb(NE_BASE + NE_RESET), NE_BASE + NE_RESET); ei_status.txing = 0; ei_status.dmaing = 0; while ((inb(NE_BASE+NE_EN0_ISR) & ENISR_RESET) == 0) if (time_after(jiffies, reset_start_time + 2*HZ/100)) { printk("%s: ne_reset_8390() did not complete.\n", dev->name); break; } outb(ENISR_RESET, NE_BASE + NE_EN0_ISR); } static void apne_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr, int ring_page) { int nic_base = dev->base_addr; int cnt; char *ptrc; short *ptrs; if (ei_status.dmaing) { printk("%s: DMAing conflict in ne_get_8390_hdr " "[DMAstat:%d][irqlock:%d][intr:%d].\n", dev->name, ei_status.dmaing, ei_status.irqlock, dev->irq); return; } ei_status.dmaing |= 0x01; outb(E8390_NODMA+E8390_PAGE0+E8390_START, nic_base+ NE_CMD); outb(ENISR_RDC, nic_base + NE_EN0_ISR); outb(sizeof(struct e8390_pkt_hdr), nic_base + NE_EN0_RCNTLO); outb(0, nic_base + NE_EN0_RCNTHI); outb(0, nic_base + NE_EN0_RSARLO); outb(ring_page, nic_base + NE_EN0_RSARHI); outb(E8390_RREAD+E8390_START, nic_base + NE_CMD); if (ei_status.word16) { ptrs = (short*)hdr; for(cnt = 0; cnt < (sizeof(struct e8390_pkt_hdr)>>1); cnt++) *ptrs++ = inw(NE_BASE + NE_DATAPORT); } else { ptrc = (char*)hdr; for(cnt = 0; cnt < sizeof(struct e8390_pkt_hdr); cnt++) *ptrc++ = inb(NE_BASE + NE_DATAPORT); } outb(ENISR_RDC, nic_base + NE_EN0_ISR); ei_status.dmaing &= ~0x01; le16_to_cpus(&hdr->count); } static void apne_block_input(struct net_device *dev, int count, struct sk_buff *skb, int ring_offset) { int nic_base = dev->base_addr; char *buf = skb->data; char *ptrc; short *ptrs; int cnt; if (ei_status.dmaing) { printk("%s: DMAing conflict in ne_block_input " "[DMAstat:%d][irqlock:%d][intr:%d].\n", dev->name, ei_status.dmaing, ei_status.irqlock, dev->irq); return; } ei_status.dmaing |= 0x01; outb(E8390_NODMA+E8390_PAGE0+E8390_START, nic_base+ NE_CMD); outb(ENISR_RDC, nic_base + NE_EN0_ISR); outb(count & 0xff, nic_base + NE_EN0_RCNTLO); outb(count >> 8, nic_base + NE_EN0_RCNTHI); outb(ring_offset & 0xff, nic_base + NE_EN0_RSARLO); outb(ring_offset >> 8, nic_base + NE_EN0_RSARHI); outb(E8390_RREAD+E8390_START, nic_base + NE_CMD); if (ei_status.word16) { ptrs = (short*)buf; for (cnt = 0; cnt < (count>>1); cnt++) *ptrs++ = inw(NE_BASE + NE_DATAPORT); if (count & 0x01) { buf[count-1] = inb(NE_BASE + NE_DATAPORT); } } else { ptrc = (char*)buf; for (cnt = 0; cnt < count; cnt++) *ptrc++ = inb(NE_BASE + NE_DATAPORT); } outb(ENISR_RDC, nic_base + NE_EN0_ISR); ei_status.dmaing &= ~0x01; } static void apne_block_output(struct net_device *dev, int count, const unsigned char *buf, const int start_page) { int nic_base = NE_BASE; unsigned long dma_start; char *ptrc; short *ptrs; int cnt; if (ei_status.word16 && (count & 0x01)) count++; if (ei_status.dmaing) { printk("%s: DMAing conflict in ne_block_output." "[DMAstat:%d][irqlock:%d][intr:%d]\n", dev->name, ei_status.dmaing, ei_status.irqlock, dev->irq); return; } ei_status.dmaing |= 0x01; outb(E8390_PAGE0+E8390_START+E8390_NODMA, nic_base + NE_CMD); outb(ENISR_RDC, nic_base + NE_EN0_ISR); outb(count & 0xff, nic_base + NE_EN0_RCNTLO); outb(count >> 8, nic_base + NE_EN0_RCNTHI); outb(0x00, nic_base + NE_EN0_RSARLO); outb(start_page, nic_base + NE_EN0_RSARHI); outb(E8390_RWRITE+E8390_START, nic_base + NE_CMD); if (ei_status.word16) { ptrs = (short*)buf; for (cnt = 0; cnt < count>>1; cnt++) outw(*ptrs++, NE_BASE+NE_DATAPORT); } else { ptrc = (char*)buf; for (cnt = 0; cnt < count; cnt++) outb(*ptrc++, NE_BASE + NE_DATAPORT); } dma_start = jiffies; while ((inb(NE_BASE + NE_EN0_ISR) & ENISR_RDC) == 0) if (time_after(jiffies, dma_start + 2*HZ/100)) { printk("%s: timeout waiting for Tx RDC.\n", dev->name); apne_reset_8390(dev); NS8390_init(dev,1); break; } outb(ENISR_RDC, nic_base + NE_EN0_ISR); ei_status.dmaing &= ~0x01; return; } static irqreturn_t apne_interrupt(int irq, void *dev_id) { unsigned char pcmcia_intreq; if (!(gayle.inten & GAYLE_IRQ_IRQ)) return IRQ_NONE; pcmcia_intreq = pcmcia_get_intreq(); if (!(pcmcia_intreq & GAYLE_IRQ_IRQ)) { pcmcia_ack_int(pcmcia_intreq); return IRQ_NONE; } if (ei_debug > 3) printk("pcmcia intreq = %x\n", pcmcia_intreq); pcmcia_disable_irq(); ei_interrupt(irq, dev_id); pcmcia_ack_int(pcmcia_get_intreq()); pcmcia_enable_irq(); return IRQ_HANDLED; } #ifdef MODULE static struct net_device *apne_dev; static int __init apne_module_init(void) { apne_dev = apne_probe(-1); if (IS_ERR(apne_dev)) return PTR_ERR(apne_dev); return 0; } static void __exit apne_module_exit(void) { unregister_netdev(apne_dev); pcmcia_disable_irq(); free_irq(IRQ_AMIGA_PORTS, apne_dev); pcmcia_reset(); release_region(IOBASE, 0x20); free_netdev(apne_dev); } module_init(apne_module_init); module_exit(apne_module_exit); #endif static int init_pcmcia(void) { u_char config; #ifndef MANUAL_CONFIG u_char tuple[32]; int offset_len; #endif u_long offset; pcmcia_reset(); <API key>(PCMCIA_0V); pcmcia_access_speed(PCMCIA_SPEED_250NS); pcmcia_write_enable(); #ifdef MANUAL_CONFIG config = MANUAL_CONFIG; #else if (pcmcia_copy_tuple(<API key>, tuple, 32) < 3) return 0; config = tuple[2] & 0x3f; #endif #ifdef MANUAL_OFFSET offset = MANUAL_OFFSET; #else if (pcmcia_copy_tuple(CISTPL_CONFIG, tuple, 32) < 6) return 0; offset_len = (tuple[2] & 0x3) + 1; offset = 0; while(offset_len offset = (offset << 8) | tuple[4+offset_len]; } #endif out_8(GAYLE_ATTRIBUTE+offset, config); return 1; } MODULE_LICENSE("GPL");
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <title>Curate | Prototype</title> <link rel="stylesheet" href="curate.css"> <script src="script.js"></script> </head> <body> <!-- First Page --> <div> <h1>Canvas 1 - Intro Animations <br> Hit Refresh for Animation Replay.</h1> <section> <header> <img src="http://lorinsteel.com/blog/wp-content/uploads/2014/11/iOS-8-Status-Bar-01.png" alt="iOS 8 Status Bar"> </header> <main> <img src="assets/logo.png" alt=""> <img src="assets/bg1.png" alt=""> <div> <img src="assets/albums1.png" alt=""> <img src="assets/albums2.png" alt=""> </div> <aside> <p>Feel like savoring <br> these dishes, fam? &UpperRightArrow; </p> <br> <hr> <div></div> <br> <br> <img src="assets/icon.png" alt=""> <p>"you got flavor, boi"</p> </aside> </main> </section> </div> <!-- Second Page --> <div> <h1>Canvas 2 - Bot Function <br> Hit Refresh for Animation Replay.</h1> <section> <header> <img src="http://lorinsteel.com/blog/wp-content/uploads/2014/11/iOS-8-Status-Bar-01.png" alt="iOS 8 Status Bar"> </header> <main> <img src="assets/logo.png" alt=""> <aside> <p>Forget Kansas yet?<br> Here's Portugal in an <br> acoustic nutshell &LowerRightArrow; </p> <img src="assets/icon.png" alt=""> <br> <hr> <div></div> <p>start speaking or type</p> <p>"I miss home, toto."</p> <p>Alright, here's what's <br> lit back in Topeka. &LowerRightArrow;</p> </aside> <img src="assets/suggestion.png" alt=""> <img src="assets/<API key>.png" alt=""> <img src="assets/new_suggestion_bg.png" alt=""> </main> <img src="assets/keyboard.png" alt=""> </section> </div> <!-- Third Page --> <div> <h1>Canvas 3 - Navigation <br> Hit Refresh for Animation Replay.</h1> <section> <header> <img src="http://lorinsteel.com/blog/wp-content/uploads/2014/11/iOS-8-Status-Bar-01.png" alt="iOS 8 Status Bar"> </header> <main> <aside> <p>“ You might fall in love with pop duo Nuremburg’s silky synths <p>- Variety, 2016</p> <img src="assets/icon.png" alt=""> </aside> <img src="assets/logo.png" alt=""> <img src="assets/album_bg.png" alt=""> <img src="assets/album_nav.png" alt=""> </main> <main> <img src="assets/player.png" alt=""> <img src="assets/waveform.png" alt=""> <img src="assets/player_bg.png" alt=""> <img src="assets/player_suggest.png" alt=""> </main> <main> <img src="assets/suggestion_bot.png" alt=""> <img src="assets/suggestion_album.png" alt=""> </main> </section> </div> </body> </html>
<?php class departamento extends controller { public function __construct() { parent::__construct(); include 'controllers/loginController.php'; $valida = new login(); $valida->sessao_valida(); } public function index_action($pagina = 1) { //list all records $_SESSION['pagina'] = $pagina; $this->smarty->assign('paginador', $this->mostraGrid()); $this->smarty->assign('title', 'Departamento'); //call the smarty $this->smarty->display('departamento/index.tpl'); } public function add() { $this->smarty->assign('title', 'Novo Departamento'); $this->smarty->display('departamento/new.tpl'); } public function save() { $modeldepartamento = new departamentoModel(); $dados['departamento'] = $_POST['name']; //$dados['created'] = date("Y-m-d H:i:s"); //$dados['active'] = 1; $modeldepartamento->setDepartamento($dados); header('Location: /departamento'); } public function update() { $id = $this->getParam('id'); $modeldepartamento = new departamentoModel(); $dados['codigo'] = $id; $dados['departamento'] = $_POST['name']; $modeldepartamento->updDepartamento($dados); header('Location: /departamento'); } public function detalhes() { $id = $this->getParam('id'); $modeldepartamento = new departamentoModel(); $resdepartamento = $modeldepartamento->getDepartamento('codigo=' . $id); $this->smarty->assign('registro', $resdepartamento[0]); $this->smarty->assign('title', 'Detalhes do Departamento'); //call the smarty $this->smarty->display('departamento/detail.tpl'); } public function edit() { //die(); $id = $this->getParam('id'); $modeldepartamento = new departamentoModel(); $resdepartamento = $modeldepartamento->getDepartamento('codigo=' . $id); $this->smarty->assign('registro', $resdepartamento[0]); $this->smarty->assign('title', 'Editar Departamento'); //call the smarty $this->smarty->display('departamento/edit.tpl'); } public function delete() { $id = $this->getParam('id'); $modeldepartamento = new departamentoModel(); $dados['codigo'] = $id; $modeldepartamento->delDepartamento($dados); header('Location: /departamento'); } public function mostraGrid(){ $total_reg = "10"; $pagina = $_SESSION['pagina']; if (!$pagina) { $pc = "1"; } else { $pc = $pagina; } $inicio = $pc - 1; $inicio = $inicio * $total_reg; //list all records $model_departamentos = new departamentoModel(); $departamentos_res = $model_departamentos-><API key>(null,$inicio,$total_reg); //Full table Scan :( or :) //send the records to template sytem $this->smarty->assign('listdepartamento', $departamentos_res); $query_total = $model_departamentos-><API key>(); $total_registros = $query_total[0]['total']; //pega o valor $html = $this->paginador($pc, $total_registros, 'departamento'); return $html; } public function paginacao() { $this->index_action($this->getParam('pagina')); } } ?>
Webspark FeaturesCustom ========= A collection of features compiled specifically for the Webspark distro of Panopoly. This includes: ASU GSA - Google Search Appliance ASU Maps Enhanced ASU Security Scan Fixes Various Fieldable Panel Pane Elements: ASU Spotlight Webspark Banner Webspark Hero Webspark Jumbohero Webspark Content Callout Webspark Extras Webspark feeds content: Webspark News & Events Webspark Page Elements: Webspark Breadcrumbs Mega Footer Mega Footer Menu Webspark Megamenu Webspark Panels Styles Webspark WYSIWYG settings
<?php // $Id: oci8po.class.php 68 2009-07-31 18:23:01Z dlandau $ // Moodle - Modular Object-Oriented Dynamic Learning Environment // // This program is free software; you can redistribute it and/or modify // // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // This class generate SQL code to be used against Oracle It extends XMLDBgenerator so everything can be overriden as needed to generate correct SQL. class XMLDBoci8po extends XMLDBgenerator { Only set values that are different from the defaults present in XMLDBgenerator var $statement_end = "\n/"; // String to be automatically added at the end of each statement // Using "/" because the standard ";" isn't good for stored procedures (triggers) var $number_type = 'NUMBER'; // Proper type for NUMBER(x) in this DB var $unsigned_allowed = false; // To define in the generator must handle unsigned information var $default_for_char = ' '; // To define the default to set for NOT NULLs CHARs without default (null=do nothing) // Using this whitespace here because Oracle doesn't distinguish empty and null! :-( var $<API key> = true; //To specify if the generator must use some DEFAULT clause to drop defaults var $drop_default_clause = 'NULL'; //The DEFAULT clause required to drop defaults var $default_after_null = false; //To decide if the default clause of each field must go after the null clause var $sequence_extra_code = true; //Does the generator need to add extra code to generate the sequence fields var $sequence_name = ''; //Particular name for inline sequences in this generator var $<API key> = true; //Does the generator need to add code after table drop var $<API key> = true; //Does the generator need to add code after table rename var $<API key> = true; //Does the generator need to add code after field rename var $enum_inline_code = false; //Does the generator need to add inline code in the column definition var $alter_column_sql = 'ALTER TABLE TABLENAME MODIFY (COLUMNSPECS)'; //The SQL template to alter columns /** * Creates one new XMLDBoci8po */ function XMLDBoci8po() { parent::XMLDBgenerator(); $this->prefix = ''; $this->reserved_words = $this->getReservedWords(); } /** * Given one XMLDB Type, lenght and decimals, returns the DB proper SQL type */ function getTypeSQL ($xmldb_type, $xmldb_length=null, $xmldb_decimals=null) { switch ($xmldb_type) { case XMLDB_TYPE_INTEGER: if (empty($xmldb_length)) { $xmldb_length = 10; } $dbtype = 'NUMBER(' . $xmldb_length . ')'; break; case XMLDB_TYPE_NUMBER: $dbtype = $this->number_type; 38 is the max allowed if ($xmldb_length > 38) { $xmldb_length = 38; } if (!empty($xmldb_length)) { $dbtype .= '(' . $xmldb_length; if (!empty($xmldb_decimals)) { $dbtype .= ',' . $xmldb_decimals; } $dbtype .= ')'; } break; case XMLDB_TYPE_FLOAT: $dbtype = 'NUMBER'; break; case XMLDB_TYPE_CHAR: $dbtype = 'VARCHAR2'; if (empty($xmldb_length)) { $xmldb_length='255'; } $dbtype .= '(' . $xmldb_length . ')'; break; case XMLDB_TYPE_TEXT: $dbtype = 'CLOB'; break; case XMLDB_TYPE_BINARY: $dbtype = 'BLOB'; break; case XMLDB_TYPE_DATETIME: $dbtype = 'DATE'; break; } return $dbtype; } /** * Returns the code needed to create one enum for the xmldb_table and xmldb_field passes */ function getEnumExtraSQL ($xmldb_table, $xmldb_field) { $sql = 'CONSTRAINT ' . $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'ck'); $sql.= ' CHECK (' . $this->getEncQuoted($xmldb_field->getName()) . ' IN (' . implode(', ', $xmldb_field->getEnumValues()) . '))'; return $sql; } /** * Returns the code needed to create one sequence for the xmldb_table and xmldb_field passes */ function <API key> ($xmldb_table, $xmldb_field) { $results = array(); $sequence_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'seq'); $sequence = "CREATE SEQUENCE " . $sequence_name; $sequence.= "\n START WITH 1"; $sequence.= "\n INCREMENT BY 1"; $sequence.= "\n NOMAXVALUE"; $results[] = $sequence; $results = array_merge($results, $this->getCreateTriggerSQL ($xmldb_table, $xmldb_field)); return $results; } /** * Returns the code needed to create one trigger for the xmldb_table and xmldb_field passed */ function getCreateTriggerSQL ($xmldb_table, $xmldb_field) { $trigger_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'trg'); $sequence_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'seq'); $trigger = "CREATE TRIGGER " . $trigger_name; $trigger.= "\n BEFORE INSERT"; $trigger.= "\nON " . $this->getTableName($xmldb_table); $trigger.= "\n FOR EACH ROW"; $trigger.= "\nBEGIN"; $trigger.= "\n IF :new." . $this->getEncQuoted($xmldb_field->getName()) . ' IS NULL THEN'; $trigger.= "\n SELECT " . $sequence_name . '.nextval INTO :new.' . $this->getEncQuoted($xmldb_field->getName()) . " FROM dual;"; $trigger.= "\n END IF;"; $trigger.= "\nEND;"; return array($trigger); } /** * Returns the code needed to drop one sequence for the xmldb_table and xmldb_field passed * Can, optionally, specify if the underlying trigger will be also dropped */ function getDropSequenceSQL ($xmldb_table, $xmldb_field, $include_trigger=false) { $sequence_name = $this->getSequenceFromDB($xmldb_table); $sequence = "DROP SEQUENCE " . $sequence_name; $trigger_name = $this->getTriggerFromDB($xmldb_table); $trigger = "DROP TRIGGER " . $trigger_name; if ($include_trigger) { $result = array($sequence, $trigger); } else { $result = array($sequence); } return $result; } /** * Returns the code (in array) needed to add one comment to the table */ function getCommentSQL ($xmldb_table) { $comment = "COMMENT ON TABLE " . $this->getTableName($xmldb_table); $comment.= " IS '" . addslashes(substr($xmldb_table->getComment(), 0, 250)) . "'"; return array($comment); } /** * Returns the code (array of statements) needed to execute extra statements on field rename */ function <API key> ($xmldb_table, $xmldb_field, $newname) { $results = array(); If the field is enum, drop and re-create the check constraint if ($xmldb_field->getEnum()) { Drop the current enum $results = array_merge($results, $this->getDropEnumSQL($xmldb_table, $xmldb_field)); Change field name (over a clone to avoid some potential problems later) $new_xmldb_field = clone($xmldb_field); $new_xmldb_field->setName($newname); Recreate the enum $results = array_merge($results, $this->getCreateEnumSQL($xmldb_table, $new_xmldb_field)); } return $results; } /** * Returns the code (array of statements) needed to execute extra statements on table drop */ function <API key> ($xmldb_table) { $xmldb_field = new XMLDBField('id'); // Fields having sequences should be exclusively, id. return $this->getDropSequenceSQL($xmldb_table, $xmldb_field, false); } /** * Returns the code (array of statements) needed to execute extra statements on table rename */ function <API key> ($xmldb_table, $newname) { $results = array(); $xmldb_field = new XMLDBField('id'); // Fields having sequences should be exclusively, id. $oldseqname = $this->getSequenceFromDB($xmldb_table); $newseqname = $this->getNameForObject($newname, $xmldb_field->getName(), 'seq'); Rename de sequence $results[] = 'RENAME ' . $oldseqname . ' TO ' . $newseqname; $oldtriggername = $this->getTriggerFromDB($xmldb_table); $newtriggername = $this->getNameForObject($newname, $xmldb_field->getName(), 'trg'); Drop old trigger $results[] = "DROP TRIGGER " . $oldtriggername; $newt = new XMLDBTable($newname); /// Temp table for trigger code generation Create new trigger $results = array_merge($results, $this->getCreateTriggerSQL($newt, $xmldb_field)); Rename all the check constraints in the table $oldtablename = $this->getTableName($xmldb_table); $newtablename = $this->getTableName($newt); $oldconstraintprefix = $this->getNameForObject($xmldb_table->getName(), ''); $newconstraintprefix = $this->getNameForObject($newt->getName(), '', ''); if ($constraints = $this-><API key>($xmldb_table)) { foreach ($constraints as $constraint) { Drop the old constraint $results[] = 'ALTER TABLE ' . $newtablename . ' DROP CONSTRAINT ' . $constraint->name; Calculate the new constraint name $newconstraintname = str_replace($oldconstraintprefix, $newconstraintprefix, $constraint->name); Add the new constraint $results[] = 'ALTER TABLE ' . $newtablename . ' ADD CONSTRAINT ' . $newconstraintname . ' CHECK (' . $constraint->description . ')'; } } return $results; } /** * Given one XMLDBTable and one XMLDBField, return the SQL statements needded to alter the field in the table * Oracle has some severe limits: * - clob and blob fields doesn't allow type to be specified * - error is dropped if the null/not null clause is specified and hasn't changed * - changes in precision/decimals of numeric fields drop an ORA-1440 error */ function getAlterFieldSQL($xmldb_table, $xmldb_field) { global $db; $results = array(); /// To store all the needed SQL commands Get the quoted name of the table and field $tablename = $this->getTableName($xmldb_table); $fieldname = $this->getEncQuoted($xmldb_field->getName()); Take a look to field metadata $meta = <API key>($db->MetaColumns($tablename)); $metac = $meta[$fieldname]; $oldtype = strtolower($metac->type); $oldmetatype = column_type($xmldb_table->getName(), $fieldname); $oldlength = $metac->max_length; To calculate the oldlength if the field is numeric, we need to perform one extra query because ADOdb has one bug here. http://phplens.com/lens/lensforum/msgs.php?id=15883 if ($oldmetatype == 'N') { $uppertablename = strtoupper($tablename); $upperfieldname = strtoupper($fieldname); if ($col = get_record_sql("SELECT cname, precision FROM col WHERE tname = '$uppertablename' AND cname = '$upperfieldname'")) { $oldlength = $col->precision; } } $olddecimals = empty($metac->scale) ? null : $metac->scale; $oldnotnull = empty($metac->not_null) ? false : $metac->not_null; $olddefault = empty($metac->default_value) || strtoupper($metac->default_value) == 'NULL' ? null : $metac->default_value; $typechanged = true; //By default, assume that the column type has changed $precisionchanged = true; //By default, assume that the column precision has changed $decimalchanged = true; //By default, assume that the column decimal has changed $defaultchanged = true; //By default, assume that the column default has changed $notnullchanged = true; //By default, assume that the column notnull has changed $from_temp_fields = false; //By default don't assume we are going to use temporal fields Detect if we are changing the type of the column if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER && substr($oldmetatype, 0, 1) == 'I') || ($xmldb_field->getType() == XMLDB_TYPE_NUMBER && $oldmetatype == 'N') || ($xmldb_field->getType() == XMLDB_TYPE_FLOAT && $oldmetatype == 'F') || ($xmldb_field->getType() == XMLDB_TYPE_CHAR && substr($oldmetatype, 0, 1) == 'C') || ($xmldb_field->getType() == XMLDB_TYPE_TEXT && substr($oldmetatype, 0, 1) == 'X') || ($xmldb_field->getType() == XMLDB_TYPE_BINARY && $oldmetatype == 'B')) { $typechanged = false; } Detect if precision has changed if (($xmldb_field->getType() == XMLDB_TYPE_TEXT) || ($xmldb_field->getType() == XMLDB_TYPE_BINARY) || ($oldlength == -1) || ($xmldb_field->getLength() == $oldlength)) { $precisionchanged = false; } Detect if decimal has changed if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER) || ($xmldb_field->getType() == XMLDB_TYPE_CHAR) || ($xmldb_field->getType() == XMLDB_TYPE_TEXT) || ($xmldb_field->getType() == XMLDB_TYPE_BINARY) || (!$xmldb_field->getDecimals()) || (!$olddecimals) || ($xmldb_field->getDecimals() == $olddecimals)) { $decimalchanged = false; } Detect if we are changing the default if (($xmldb_field->getDefault() === null && $olddefault === null) || ($xmldb_field->getDefault() === $olddefault) || //Check both equality and ("'" . $xmldb_field->getDefault() . "'" === $olddefault)) { //Equality with quotes because ADOdb returns the default with quotes $defaultchanged = false; } Detect if we are changing the nullability if (($xmldb_field->getNotnull() === $oldnotnull)) { $notnullchanged = false; } If type has changed or precision or decimal has changed and we are in one numeric field - create one temp column with the new specs - fill the new column with the values from the old one - drop the old column - rename the temp column to the original name if (($typechanged) || (($oldmetatype == 'N' || $oldmetatype == 'I') && ($precisionchanged || $decimalchanged))) { $tempcolname = $xmldb_field->getName() . '_alter_column_tmp'; Prevent temp field to have both NULL/NOT NULL and DEFAULT constraints $this-><API key> = true; $this-><API key> = true; $xmldb_field->setName($tempcolname); Create the temporal column $results = array_merge($results, $this->getAddFieldSQL($xmldb_table, $xmldb_field)); Copy contents from original col to the temporal one $results[] = 'UPDATE ' . $tablename . ' SET ' . $tempcolname . ' = ' . $fieldname; Drop the old column $xmldb_field->setName($fieldname); //Set back the original field name $results = array_merge($results, $this->getDropFieldSQL($xmldb_table, $xmldb_field)); Rename the temp column to the original one $results[] = 'ALTER TABLE ' . $tablename . ' RENAME COLUMN ' . $tempcolname . ' TO ' . $fieldname; Mark we have performed one change based in temp fields $from_temp_fields = true; Re-enable the notnull and default sections so the general AlterFieldSQL can use it $this-><API key> = false; $this-><API key> = false; Dissable the type section because we have done it with the temp field $this-><API key> = true; If new field is nullable, nullability hasn't changed if (!$xmldb_field->getNotnull()) { $notnullchanged = false; } If new field hasn't default, default hasn't changed if ($xmldb_field->getDefault() === null) { $defaultchanged = false; } } If type and precision and decimals hasn't changed, prevent the type clause if (!$typechanged && !$precisionchanged && !$decimalchanged) { $this-><API key> = true; } If NULL/NOT NULL hasn't changed prevent null clause to be specified if (!$notnullchanged) { $this-><API key> = true; /// Initially, prevent the notnull clause But, if we have used the temp field and the new field is not null, then enforce the not null clause if ($from_temp_fields && $xmldb_field->getNotnull()) { $this-><API key> = false; } } If default hasn't changed prevent default clause to be specified if (!$defaultchanged) { $this-><API key> = true; /// Initially, prevent the default clause But, if we have used the temp field and the new field has default clause, then enforce the default clause if ($from_temp_fields && $default_clause = $this->getDefaultClause($xmldb_field)) { $this-><API key> = false; } } If arriving here, something is not being skiped (type, notnull, default), calculate the standar AlterFieldSQL if (!$this-><API key> || !$this-><API key> || !$this-><API key>) { $results = array_merge($results, parent::getAlterFieldSQL($xmldb_table, $xmldb_field)); return $results; } Finally return results return $results; } /** * Given one XMLDBTable and one XMLDBField, return the SQL statements needded to create its enum * (usually invoked from getModifyEnumSQL() */ function getCreateEnumSQL($xmldb_table, $xmldb_field) { All we have to do is to create the check constraint return array('ALTER TABLE ' . $this->getTableName($xmldb_table) . ' ADD ' . $this->getEnumExtraSQL($xmldb_table, $xmldb_field)); } /** * Given one XMLDBTable and one XMLDBField, return the SQL statements needded to drop its enum * (usually invoked from getModifyEnumSQL() */ function getDropEnumSQL($xmldb_table, $xmldb_field) { Let's introspect to know the real name of the check constraint if ($check_constraints = $this-><API key>($xmldb_table, $xmldb_field)) { $check_constraint = array_shift($check_constraints); /// Get the 1st (should be only one) $constraint_name = strtolower($check_constraint->name); /// Extract the REAL name All we have to do is to drop the check constraint return array('ALTER TABLE ' . $this->getTableName($xmldb_table) . ' DROP CONSTRAINT ' . $constraint_name); } else { /// Constraint not found. Nothing to do return array(); } } /** * Given one XMLDBTable and one XMLDBField, return the SQL statements needded to create its default * (usually invoked from getModifyDefaultSQL() */ function getCreateDefaultSQL($xmldb_table, $xmldb_field) { Just a wrapper over the getAlterFieldSQL() function for Oracle that is capable of handling defaults return $this->getAlterFieldSQL($xmldb_table, $xmldb_field); } /** * Given one XMLDBTable and one XMLDBField, return the SQL statements needded to drop its default * (usually invoked from getModifyDefaultSQL() */ function getDropDefaultSQL($xmldb_table, $xmldb_field) { Just a wrapper over the getAlterFieldSQL() function for Oracle that is capable of handling defaults return $this->getAlterFieldSQL($xmldb_table, $xmldb_field); } /** * Given one XMLDBTable returns one array with all the check constrainsts * in the table (fetched from DB) * Optionally the function allows one xmldb_field to be specified in * order to return only the check constraints belonging to one field. * Each element contains the name of the constraint and its description * If no check constraints are found, returns an empty array */ function <API key>($xmldb_table, $xmldb_field = null) { $results = array(); $tablename = strtoupper($this->getTableName($xmldb_table)); if ($constraints = get_records_sql("SELECT lower(c.constraint_name) AS name, c.search_condition AS description FROM user_constraints c WHERE c.table_name = '{$tablename}' AND c.constraint_type = 'C' AND c.constraint_name not like 'SYS%'")) { foreach ($constraints as $constraint) { $results[$constraint->name] = $constraint; } } Filter by the required field if specified if ($xmldb_field) { $filtered_results = array(); $filter = $xmldb_field->getName(); Lets clean a bit each constraint description, looking for the filtered field foreach ($results as $key => $result) { description starts by "$filter IN" assume it's a constraint beloging to the field if (preg_match("/^{$filter} IN/i", $result->description)) { $filtered_results[$key] = $result; } } Assign filtered results to the final results array $results = $filtered_results; } return $results; } /** * Given one XMLDBTable returns one string with the sequence of the table * in the table (fetched from DB) * The sequence name for oracle is calculated by looking the corresponding * trigger and retrieving the sequence name from it (because sequences are * independent elements) * If no sequence is found, returns false */ function getSequenceFromDB($xmldb_table) { $tablename = strtoupper($this->getTableName($xmldb_table)); $prefixupper = strtoupper($this->prefix); $sequencename = false; if ($trigger = get_record_sql("SELECT trigger_name, trigger_body FROM user_triggers WHERE table_name = '{$tablename}' AND trigger_name LIKE '{$prefixupper}%_ID%_TRG'")) { If trigger found, regexp it looking for the sequence name preg_match('/.*SELECT (.*)\.nextval/i', $trigger->trigger_body, $matches); if (isset($matches[1])) { $sequencename = $matches[1]; } } return $sequencename; } /** * Given one XMLDBTable returns one string with the trigger * in the table (fetched from DB) * If no trigger is found, returns false */ function getTriggerFromDB($xmldb_table) { $tablename = strtoupper($this->getTableName($xmldb_table)); $prefixupper = strtoupper($this->prefix); $triggername = false; if ($trigger = get_record_sql("SELECT trigger_name, trigger_body FROM user_triggers WHERE table_name = '{$tablename}' AND trigger_name LIKE '{$prefixupper}%_ID%_TRG'")) { $triggername = $trigger->trigger_name; } return $triggername; } /** * Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg) * return if such name is currently in use (true) or no (false) * (invoked from getNameForObject() */ function isNameInUse($object_name, $type, $table_name) { switch($type) { case 'ix': case 'uix': case 'seq': case 'trg': if ($check = get_records_sql("SELECT object_name FROM user_objects WHERE lower(object_name) = '" . strtolower($object_name) . "'")) { return true; } break; case 'pk': case 'uk': case 'fk': case 'ck': if ($check = get_records_sql("SELECT constraint_name FROM user_constraints WHERE lower(constraint_name) = '" . strtolower($object_name) . "'")) { return true; } break; } return false; //No name in use found } /** * Returns an array of reserved words (lowercase) for this DB */ function getReservedWords() { This file contains the reserved words for Oracle databases from http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a96540/ap_keywd.htm $reserved_words = array ( 'access', 'add', 'all', 'alter', 'and', 'any', 'as', 'asc', 'audit', 'between', 'by', 'char', 'check', 'cluster', 'column', 'comment', 'compress', 'connect', 'create', 'current', 'date', 'decimal', 'default', 'delete', 'desc', 'distinct', 'drop', 'else', 'exclusive', 'exists', 'file', 'float', 'for', 'from', 'grant', 'group', 'having', 'identified', 'immediate', 'in', 'increment', 'index', 'initial', 'insert', 'integer', 'intersect', 'into', 'is', 'level', 'like', 'lock', 'long', 'maxextents', 'minus', 'mlslabel', 'mode', 'modify', 'noaudit', 'nocompress', 'not', 'nowait', 'null', 'number', 'of', 'offline', 'on', 'online', 'option', 'or', 'order', 'pctfree', 'prior', 'privileges', 'public', 'raw', 'rename', 'resource', 'revoke', 'row', 'rowid', 'rownum', 'rows', 'select', 'session', 'set', 'share', 'size', 'smallint', 'start', 'successful', 'synonym', 'sysdate', 'table', 'then', 'to', 'trigger', 'uid', 'union', 'unique', 'update', 'user', 'validate', 'values', 'varchar', 'varchar2', 'view', 'whenever', 'where', 'with' ); return $reserved_words; } } ?>
<!DOCTYPE html> <html> <head> <title>SceneJS / cannon.js example</title> <meta charset="utf-8"> <style> * {margin:0;padding:0} </style> </head> <body> <script src="../libs/scenejs.js"></script> <script src="../build/cannon.js"></script> <canvas id="theCanvas" width="600" height="400"/> <script> var scene, quaternionNode, translationNode, world, body, shape, timeStep=1/60; initCannon(); initSceneJS(); animate(); function initCannon() { world = new CANNON.World(); world.gravity.set(0,0,0); shape = new CANNON.Box(new CANNON.Vec3(1,1,1)); body = new CANNON.Body({ mass: 1 }); body.addShape(shape); body.angularVelocity.set(0,10,0); body.angularDamping = 0.01; world.add(body); } function initSceneJS() { SceneJS.createScene({ id: "theScene", canvasId: "theCanvas", nodes: [ { type: "lookAt", eye : { x: 0.0, y: 10.0, z: 15 }, look : { y:1.0 }, up : { y: 1.0 }, nodes: [ { type: "camera", optics: { type: "perspective", fovy : 25.0, aspect : 1.47, near : 0.10, far : 300.0 }, nodes: [ { type: "renderer", clearColor: { r: 1.0, g: 1.0, b: 1.0 }, clear: { depth : true, color : true }, nodes: [ { type: "light", mode: "dir", color: { r: 1.0, g: 1.0, b: 1.0 }, diffuse: true, specular: true, dir: { x: 1.0, y: -0.5, z: -1.0 } }, { type: "light", mode: "dir", color: { r: 1.0, g: 1.0, b: 0.8 }, diffuse: true, specular: false, dir: { x: 0.0, y: -0.5, z: -1.0 } }, { type: "translate", id: "translate", x : 0.0, y : 0.0, z : 0.0, nodes: [ { type: "quaternion", id: "quaternion", x : 1.0, y : 0.0, z : 0.0, angle : 0.0, nodes: [ { type: "material", emit: 0, baseColor: { r: 0.5, g: 0.5, b: 0.6 }, specularColor: { r: 0.9, g: 0.9, b: 0.9 }, specular: 1.0, shine: 70.0, nodes: [ { type : "cube", xSize: shape.halfExtents.x, ySize: shape.halfExtents.y, zSize: shape.halfExtents.z, } ] } ] } ] } ] } ] } ] } ] }); // Get handles to some nodes scene = SceneJS.scene("theScene"); quaternionNode = scene.findNode("quaternion"); translationNode = scene.findNode("translate"); } function animate() { // Start the scene rendering scene.start({ idleFunc: updatePhysics }); } function updatePhysics() { var axisAndAngle, axis, angle; // Step the physics world world.step(timeStep); // Copy position from cannon to SceneJS translation node translationNode.set("xyz",body.position); // Get orientation of the body from cannon.js axisAndAngle = body.quaternion.toAxisAngle(); axis = axisAndAngle[0]; angle = axisAndAngle[1]; // Copy orientation to the SceneJS quaternion node quaternionNode.set("rotation",{ x: axis.x, y: axis.y, z: axis.z, angle: angle*180 / Math.PI }); } </script> </body> </html>
<?php class <API key> { // Events // // Constants // // Variables // private $model; // Constructor & Destructor // public function __construct($model) { $this->model = $model; } // Public Methods // public function display() { global $WD_BWG_UPLOAD_DIR; $rows_data = $this->model->get_rows_data(); $page_nav = $this->model->page_nav(); $search_value = ((isset($_POST['search_value'])) ? esc_html(stripslashes($_POST['search_value'])) : ''); $search_select_value = ((isset($_POST['search_select_value'])) ? (int) $_POST['search_select_value'] : 0); $asc_or_desc = ((isset($_POST['asc_or_desc'])) ? esc_html(stripslashes($_POST['asc_or_desc'])) : 'asc'); $order_by = (isset($_POST['order_by']) ? esc_html(stripslashes($_POST['order_by'])) : 'order'); $order_class = 'manage-column column-title sorted ' . $asc_or_desc; $ids_string = ''; ?> <div style="clear: both; float: left; width: 95%;"> <div style="float:left; font-size: 14px; font-weight: bold;"> This section allows you to create, edit and delete galleries. <a style="color: blue; text-decoration: none;" target="_blank" href="http://web-dorado.com/<API key>.html">Read More in User Manual</a> </div> <div style="float: right; text-align: right;"> <a style="text-decoration: none;" target="_blank" href="http://web-dorado.com/products/<API key>.html"> <img width="215" border="0" alt="web-dorado.com" src="<?php echo WD_BWG_URL . '/images/logo.png'; ?>" /> </a> </div> </div> <form class="wrap" id="galleries_form" method="post" action="admin.php?page=galleries_bwg" style="float: left; width: 95%;"> <span class="gallery-icon"></span> <h2> Galleries <a href="" class="add-new-h2" onclick="<API key>('task', 'add'); spider_form_submit(event, 'galleries_form')">Add new</a> </h2> <div id="draganddrop" class="updated" style="display:none;"><strong><p>Changes made in this table should be saved.</p></strong></div> <div class="buttons_div"> <span class="button-secondary non_selectable" onclick="<API key>()"> <input type="checkbox" id="check_all_items" name="check_all_items" onclick="<API key>()" style="margin: 0; vertical-align: middle;" /> <span style="vertical-align: middle;">Select All</span> </span> <input id="show_hide_weights" class="button-secondary" type="button" onclick="<API key>();return false;" value="Hide order column" /> <input class="button-secondary" type="submit" onclick="<API key>('task', 'save_order')" value="Save Order" /> <input class="button-secondary" type="submit" onclick="<API key>('task', 'publish_all')" value="Publish" /> <input class="button-secondary" type="submit" onclick="<API key>('task', 'unpublish_all')" value="Unpublish" /> <input class="button-secondary" type="submit" onclick="if (confirm('Do you want to delete selected items?')) { <API key>('task', 'delete_all'); } else { return false; }" value="Delete" /> </div> <div class="tablenav top"> <?php WDWLibrary::search('Name', $search_value, 'galleries_form'); WDWLibrary::html_page_nav($page_nav['total'], $page_nav['limit'], 'galleries_form'); ?> </div> <table class="wp-list-table widefat fixed pages"> <thead> <th class="table_small_col"></th> <th class="manage-column column-cb check-column table_small_col"><input id="check_all" type="checkbox" onclick="spider_check_all(this)" style="margin:0;" /></th> <th class="table_small_col <?php if ($order_by == 'id') {echo $order_class;} ?>"> <a onclick="<API key>('task', ''); <API key>('order_by', 'id'); <API key>('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'id') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>ID</span><span class="sorting-indicator"></span> </a> </th> <th class="<API key>">Thumbnail</th> <th class="<?php if ($order_by == 'name') {echo $order_class;} ?>"> <a onclick="<API key>('task', ''); <API key>('order_by', 'name'); <API key>('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'name') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>Name</span><span class="sorting-indicator"></span> </a> </th> <th class="<?php if ($order_by == 'slug') {echo $order_class;} ?>"> <a onclick="<API key>('task', ''); <API key>('order_by', 'slug'); <API key>('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'slug') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>Slug</span><span class="sorting-indicator"></span> </a> </th> <th class="<?php if ($order_by == 'display_name') {echo $order_class;} ?>"> <a onclick="<API key>('task', ''); <API key>('order_by', 'display_name'); <API key>('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'display_name') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>Author</span><span class="sorting-indicator"></span> </a> </th> <th id="th_order" class="table_medium_col <?php if ($order_by == 'order') {echo $order_class;} ?>"> <a onclick="<API key>('task', ''); <API key>('order_by', 'order'); <API key>('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'order') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>Order</span><span class="sorting-indicator"></span> </a> </th> <th class="table_big_col <?php if ($order_by == 'published') {echo $order_class;} ?>"> <a onclick="<API key>('task', ''); <API key>('order_by', 'published'); <API key>('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'published') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>Published</span><span class="sorting-indicator"></span> </a> </th> <th class="table_big_col">Edit</th> <th class="table_big_col">Delete</th> </thead> <tbody id="tbody_arr"> <?php if ($rows_data) { foreach ($rows_data as $row_data) { $alternate = (!isset($alternate) || $alternate == 'class="alternate"') ? '' : 'class="alternate"'; $published_image = (($row_data->published) ? 'publish' : 'unpublish'); $published = (($row_data->published) ? 'unpublish' : 'publish'); if ($row_data->preview_image == '') { $preview_image = WD_BWG_URL . '/images/no-image.png'; } else { $preview_image = site_url() . '/' . $WD_BWG_UPLOAD_DIR . $row_data->preview_image; } ?> <tr id="tr_<?php echo $row_data->id; ?>" <?php echo $alternate; ?>> <td class="connectedSortable table_small_col"><div title="Drag to re-order"class="handle" style="margin:5px auto 0 auto;"></div></td> <td class="table_small_col check-column"><input id="check_<?php echo $row_data->id; ?>" name="check_<?php echo $row_data->id; ?>" onclick="spider_check_all(this)" type="checkbox" /></td> <td class="table_small_col"><?php echo $row_data->id; ?></td> <td class="<API key>"> <img title="<?php echo $row_data->name; ?>" style="border: 1px solid #CCCCCC; max-width:60px; max-height:60px;" src="<?php echo $preview_image . '?date=' . date('Y-m-y H:i:s'); ?>"> </td> <td><a onclick="<API key>('task', 'edit'); <API key>('page_number', '1'); <API key>('search_value', ''); <API key>('search_or_not', ''); <API key>('asc_or_desc', 'asc'); <API key>('order_by', 'order'); <API key>('current_id', '<?php echo $row_data->id; ?>'); spider_form_submit(event, 'galleries_form')" href="" title="Edit"><?php echo $row_data->name; ?></a></td> <td><?php echo $row_data->slug; ?></td> <td><?php echo get_userdata($row_data->author)->display_name; ?></td> <td class="spider_order table_medium_col"><input id="order_input_<?php echo $row_data->id; ?>" name="order_input_<?php echo $row_data->id; ?>" type="text" size="1" value="<?php echo $row_data->order; ?>" /></td> <td class="table_big_col"><a onclick="<API key>('task', '<?php echo $published; ?>');<API key>('current_id', '<?php echo $row_data->id; ?>');spider_form_submit(event, 'galleries_form')" href=""><img src="<?php echo WD_BWG_URL . '/images/' . $published_image . '.png'; ?>"></img></a></td> <td class="table_big_col"><a onclick="<API key>('task', 'edit'); <API key>('page_number', '1'); <API key>('search_value', ''); <API key>('search_or_not', ''); <API key>('asc_or_desc', 'asc'); <API key>('order_by', 'order'); <API key>('current_id', '<?php echo $row_data->id; ?>'); spider_form_submit(event, 'galleries_form')" href="">Edit</a></td> <td class="table_big_col"><a onclick="<API key>('task', 'delete'); <API key>('current_id', '<?php echo $row_data->id; ?>'); spider_form_submit(event, 'galleries_form')" href="">Delete</a></td> </tr> <?php $ids_string .= $row_data->id . ','; } } ?> </tbody> </table> <input id="task" name="task" type="hidden" value="" /> <input id="current_id" name="current_id" type="hidden" value="" /> <input id="ids_string" name="ids_string" type="hidden" value="<?php echo $ids_string; ?>" /> <input id="asc_or_desc" name="asc_or_desc" type="hidden" value="asc" /> <input id="order_by" name="order_by" type="hidden" value="<?php echo $order_by; ?>" /> <script> window.onload = <API key>; </script> </form> <?php } public function edit($id) { global $WD_BWG_UPLOAD_DIR; $row = $this->model->get_row_data($id); $option_row = $this->model->get_option_row_data(); $page_title = (($id != 0) ? 'Edit gallery ' . $row->name : 'Create new gallery'); ?> <div style="clear: both; float: left; width: 95%;"> <div id="message_div" class="updated" style="display: none;"></div> <div style="float:left; font-size: 14px; font-weight: bold;"> This section allows you to add/edit gallery. <a style="color: blue; text-decoration: none;" target="_blank" href="http://web-dorado.com/<API key>.html">Read More in User Manual</a> </div> <div style="float: right; text-align: right;"> <a style="text-decoration: none;" target="_blank" href="http://web-dorado.com/products/<API key>.html"> <img width="215" border="0" alt="web-dorado.com" src="<?php echo WD_BWG_URL . '/images/logo.png'; ?>" /> </a> </div> </div> <script> function spider_set_href(a, number, type) { var image_url = document.getElementById("image_url_" + number).value; var thumb_url = document.getElementById("thumb_url_" + number).value; a.href='<?php echo add_query_arg(array('action' => 'editThumb', 'width' => '800', 'height' => '500'), admin_url('admin-ajax.php')); ?>&type=' + type + '&image_id=' + number + '&image_url=' + image_url + '&thumb_url=' + thumb_url + '&TB_iframe=1'; } function <API key>(files) { document.getElementById("preview_image").value = files[0]['thumb_url']; document.getElementById("<API key>").style.display = "none"; document.getElementById("<API key>").style.display = "inline-block"; if (document.getElementById("img_preview_image")) { document.getElementById("img_preview_image").src = files[0]['reliative_url']; document.getElementById("img_preview_image").style.display = "inline-block"; } } var j_int = 0; var bwg_j = 'pr_' + j_int; function bwg_add_image(files) { var tbody = document.getElementById('tbody_arr'); for (var i in files) { var is_video = files[i]['filetype'] == 'YOUTUBE' || files[i]['filetype'] == 'VIMEO'; var tr = document.createElement('tr'); tr.setAttribute('id', "tr_" + bwg_j); if (tbody.firstChild) { tbody.insertBefore(tr, tbody.firstChild); } else { tbody.appendChild(tr); } // Handle TD. var td_handle = document.createElement('td'); td_handle.setAttribute('class', "connectedSortable table_small_col"); td_handle.setAttribute('title', "Drag to re-order"); tr.appendChild(td_handle); var div_handle = document.createElement('div'); div_handle.setAttribute('class', "handle connectedSortable"); div_handle.setAttribute('style', "margin: 5px auto 0px;"); td_handle.appendChild(div_handle); // Checkbox TD. var td_checkbox = document.createElement('td'); td_checkbox.setAttribute('class', "table_small_col check-column"); td_checkbox.setAttribute('onclick', "spider_check_all(this)"); tr.appendChild(td_checkbox); var input_checkbox = document.createElement('input'); input_checkbox.setAttribute('id', "check_" + bwg_j); input_checkbox.setAttribute('name', "check_" + bwg_j); input_checkbox.setAttribute('type', "checkbox"); td_checkbox.appendChild(input_checkbox); // Numbering TD. var td_numbering = document.createElement('td'); td_numbering.setAttribute('class', "table_small_col"); td_numbering.innerHTML = ""; tr.appendChild(td_numbering); // Thumb TD. var td_thumb = document.createElement('td'); td_thumb.setAttribute('class', "<API key>"); tr.appendChild(td_thumb); var a_thumb = document.createElement('a'); a_thumb.setAttribute('class', "thickbox thickbox-preview"); a_thumb.setAttribute('href', "<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'display'/*thumb_display*/, 'width' => '650', 'height' => '500'), admin_url('admin-ajax.php')); ?>&image_id=" + bwg_j + "&TB_iframe=1"); a_thumb.setAttribute('title', files[i]['name']); td_thumb.appendChild(a_thumb); var img_thumb = document.createElement('img'); img_thumb.setAttribute('id', "image_thumb_" + bwg_j); img_thumb.setAttribute('class', "thumb"); img_thumb.setAttribute('src', files[i]['thumb']); a_thumb.appendChild(img_thumb); // Filename TD. var td_filename = document.createElement('td'); td_filename.setAttribute('class', "<API key>"); tr.appendChild(td_filename); var div_filename = document.createElement('div'); div_filename.setAttribute('class', "filename"); div_filename.setAttribute('id', "filename_" + bwg_j); td_filename.appendChild(div_filename); var strong_filename = document.createElement('strong'); div_filename.appendChild(strong_filename); var a_filename = document.createElement('a'); a_filename.setAttribute('href', "<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'display', 'width' => '800', 'height' => '500'), admin_url('admin-ajax.php')); ?>&image_id=" + bwg_j + "&TB_iframe=1"); a_filename.setAttribute('class', "spider_word_wrap thickbox thickbox-preview"); a_filename.setAttribute('title', files[i]['filename']); a_filename.innerHTML = files[i]['filename']; strong_filename.appendChild(a_filename); var div_date_modified = document.createElement('div'); div_date_modified.setAttribute('class', "fileDescription"); div_date_modified.setAttribute('title', "Date modified"); div_date_modified.setAttribute('id', "date_modified_" + bwg_j); div_date_modified.innerHTML = files[i]['date_modified']; td_filename.appendChild(div_date_modified); var div_fileresolution = document.createElement('div'); div_fileresolution.setAttribute('class', "fileDescription"); div_fileresolution.setAttribute('title', "Image Resolution"); div_fileresolution.setAttribute('id', "fileresolution" + bwg_j); div_fileresolution.innerHTML = files[i]['resolution']; td_filename.appendChild(div_fileresolution); var div_filesize = document.createElement('div'); div_filesize.setAttribute('class', "fileDescription"); div_filesize.setAttribute('title', (!is_video) ? "Image size" : "Duration"); div_filesize.setAttribute('id', "filesize" + bwg_j); div_filesize.innerHTML = files[i]['size']; td_filename.appendChild(div_filesize); var div_filetype = document.createElement('div'); div_filetype.setAttribute('class', "fileDescription"); div_filetype.setAttribute('title', "Type"); div_filetype.setAttribute('id', "filetype" + bwg_j); div_filetype.innerHTML = files[i]['filetype']; td_filename.appendChild(div_filetype); if (!is_video) { var div_edit = document.createElement('div'); td_filename.appendChild(div_edit); var span_edit_crop = document.createElement('span'); span_edit_crop.setAttribute('class', "edit_thumb"); div_edit.appendChild(span_edit_crop); var a_crop = document.createElement('a'); a_crop.setAttribute('class', "thickbox thickbox-preview"); a_crop.setAttribute('onclick', "spider_set_href(this, '" + bwg_j + "', 'crop');"); a_crop.innerHTML = "Crop"; span_edit_crop.appendChild(a_crop); div_edit.innerHTML += " | "; var span_edit_rotate = document.createElement('span'); span_edit_rotate.setAttribute('class', "edit_thumb"); div_edit.appendChild(span_edit_rotate); var a_rotate = document.createElement('a'); a_rotate.setAttribute('class', "thickbox thickbox-preview"); a_rotate.setAttribute('onclick', "spider_set_href(this, '" + bwg_j + "', 'rotate');"); a_rotate.innerHTML = "Rotate"; span_edit_rotate.appendChild(a_rotate); div_edit.innerHTML += " | " var span_edit_recover = document.createElement('span'); span_edit_recover.setAttribute('class', "edit_thumb"); div_edit.appendChild(span_edit_recover); var a_recover = document.createElement('a'); a_recover.setAttribute('onclick', 'if (confirm("Do you want to reset the image?")) { <API key>("ajax_task", "recover"); <API key>("image_current_id", "' + bwg_j + '"); spider_ajax_save("galleries_form");} return false;'); a_recover.innerHTML = "Reset"; span_edit_recover.appendChild(a_recover); } var input_image_url = document.createElement('input'); input_image_url.setAttribute('id', "image_url_" + bwg_j); input_image_url.setAttribute('name', "image_url_" + bwg_j); input_image_url.setAttribute('type', "hidden"); input_image_url.setAttribute('value', files[i]['url']); td_filename.appendChild(input_image_url); var input_thumb_url = document.createElement('input'); input_thumb_url.setAttribute('id', "thumb_url_" + bwg_j); input_thumb_url.setAttribute('name', "thumb_url_" + bwg_j); input_thumb_url.setAttribute('type', "hidden"); input_thumb_url.setAttribute('value', files[i]['thumb_url']); td_filename.appendChild(input_thumb_url); var input_filename = document.createElement('input'); input_filename.setAttribute('id', "input_filename_" + bwg_j); input_filename.setAttribute('name', "input_filename_" + bwg_j); input_filename.setAttribute('type', "hidden"); input_filename.setAttribute('value', files[i]['filename']); td_filename.appendChild(input_filename); var input_date_modified = document.createElement('input'); input_date_modified.setAttribute('id', "<API key>" + bwg_j); input_date_modified.setAttribute('name', "<API key>" + bwg_j); input_date_modified.setAttribute('type', "hidden"); input_date_modified.setAttribute('value', files[i]['date_modified']); td_filename.appendChild(input_date_modified); var input_resolution = document.createElement('input'); input_resolution.setAttribute('id', "input_resolution_" + bwg_j); input_resolution.setAttribute('name', "input_resolution_" + bwg_j); input_resolution.setAttribute('type', "hidden"); input_resolution.setAttribute('value', files[i]['resolution']); td_filename.appendChild(input_resolution); var input_size = document.createElement('input'); input_size.setAttribute('id', "input_size_" + bwg_j); input_size.setAttribute('name', "input_size_" + bwg_j); input_size.setAttribute('type', "hidden"); input_size.setAttribute('value', files[i]['size']); td_filename.appendChild(input_size); var input_filetype = document.createElement('input'); input_filetype.setAttribute('id', "input_filetype_" + bwg_j); input_filetype.setAttribute('name', "input_filetype_" + bwg_j); input_filetype.setAttribute('type', "hidden"); input_filetype.setAttribute('value', files[i]['filetype']); td_filename.appendChild(input_filetype); // Alt/Title TD. var td_alt = document.createElement('td'); td_alt.setAttribute('class', "<API key>"); tr.appendChild(td_alt); var input_alt = document.createElement('input'); input_alt.setAttribute('id', "image_alt_text_" + bwg_j); input_alt.setAttribute('name', "image_alt_text_" + bwg_j); input_alt.setAttribute('type', "text"); input_alt.setAttribute('size', "24"); if (is_video) { input_alt.setAttribute('value', files[i]['name']); } else { input_alt.setAttribute('value', files[i]['filename']); } td_alt.appendChild(input_alt); <?php if ($option_row->thumb_click_action != 'open_lightbox') { ?> //Redirect url input_alt = document.createElement('input'); input_alt.setAttribute('id', "redirect_url_" + bwg_j); input_alt.setAttribute('name', "redirect_url_" + bwg_j); input_alt.setAttribute('type', "text"); input_alt.setAttribute('size', "24"); td_alt.appendChild(input_alt); <?php } ?> // Description TD. var td_desc = document.createElement('td'); td_desc.setAttribute('class', "<API key>"); tr.appendChild(td_desc); var textarea_desc = document.createElement('textarea'); textarea_desc.setAttribute('id', "image_description_" + bwg_j); textarea_desc.setAttribute('name', "image_description_" + bwg_j); textarea_desc.setAttribute('rows', "2"); textarea_desc.setAttribute('cols', "20"); textarea_desc.setAttribute('style', "resize:vertical;"); if (is_video) { textarea_desc.innerHTML = files[i]['description']; } td_desc.appendChild(textarea_desc); // Tag TD. var td_tag = document.createElement('td'); td_tag.setAttribute('class', "<API key>"); tr.appendChild(td_tag); var a_tag = document.createElement('a'); a_tag.setAttribute('class', "button button-small button-primary thickbox thickbox-preview"); a_tag.setAttribute('href', "<?php echo add_query_arg(array('action' => 'addTags', 'width' => '650', 'height' => '500'), admin_url('admin-ajax.php')); ?>&image_id=" + bwg_j + "&TB_iframe=1"); a_tag.innerHTML = 'Add tag'; td_tag.appendChild(a_tag); var div_tag = document.createElement('div'); div_tag.setAttribute('class', "tags_div"); div_tag.setAttribute('id', "tags_div_" + bwg_j); td_tag.appendChild(div_tag); var hidden_tag = document.createElement('input'); hidden_tag.setAttribute('type', "hidden"); hidden_tag.setAttribute('id', "tags_" + bwg_j); hidden_tag.setAttribute('name', "tags_" + bwg_j); hidden_tag.setAttribute('value', ""); td_tag.appendChild(hidden_tag); // Order TD. var td_order = document.createElement('td'); td_order.setAttribute('class', "spider_order table_medium_col"); td_order.setAttribute('style', "display: none;"); tr.appendChild(td_order); var input_order = document.createElement('input'); input_order.setAttribute('id', "order_input_" + bwg_j); input_order.setAttribute('name', "order_input_" + bwg_j); input_order.setAttribute('type', "text"); input_order.setAttribute('value', 0 - j_int); input_order.setAttribute('size', "1"); td_order.appendChild(input_order); // Publish TD. var td_publish = document.createElement('td'); td_publish.setAttribute('class', "table_big_col"); tr.appendChild(td_publish); var a_publish = document.createElement('a'); a_publish.setAttribute('onclick', "<API key>('ajax_task', 'image_unpublish');<API key>('image_current_id', '" + bwg_j + "');spider_ajax_save('galleries_form');"); td_publish.appendChild(a_publish); var img_publish = document.createElement('img'); img_publish.setAttribute('src', "<?php echo WD_BWG_URL . '/images/publish.png'; ?>"); a_publish.appendChild(img_publish); // Delete TD. var td_delete = document.createElement('td'); td_delete.setAttribute('class', "table_big_col"); tr.appendChild(td_delete); var a_delete = document.createElement('a'); a_delete.setAttribute('onclick', "<API key>('ajax_task', 'image_delete');<API key>('image_current_id', '" + bwg_j + "');spider_ajax_save('galleries_form');"); a_delete.innerHTML = 'Delete'; td_delete.appendChild(a_delete); document.getElementById("ids_string").value += bwg_j + ','; j_int++; bwg_j = 'pr_' + j_int; } jQuery("#show_hide_weights").val("Hide order column"); <API key>(); } </script> <form class="wrap" method="post" id="galleries_form" action="admin.php?page=galleries_bwg" style="float: left; width: 95%;"> <span class="gallery-icon"></span> <h2><?php echo $page_title; ?></h2> <div style="float:right;"> <input class="button-secondary" type="button" onclick="if (<API key>('name', 'Name')) {return false;}; <API key>('page_number', '1'); <API key>('ajax_task', 'ajax_save'); spider_ajax_save('galleries_form'); <API key>('task', 'save')" value="Save" /> <input class="button-secondary" type="button" onclick="if (<API key>('name', 'Name')) {return false;}; <API key>('ajax_task', 'ajax_apply'); spider_ajax_save('galleries_form')" value="Apply" /> <input class="button-secondary" type="submit" onclick="<API key>('page_number', '1'); <API key>('task', 'cancel')" value="Cancel" /> </div> <table style="clear:both;"> <tbody> <tr> <td class="spider_label"><label for="name">Name: <span style="color:#FF0000;">*</span> </label></td> <td><input type="text" id="name" name="name" value="<?php echo $row->name; ?>" size="39" /></td> </tr> <tr> <td class="spider_label"><label for="slug">Slug: </label></td> <td><input type="text" id="slug" name="slug" value="<?php echo $row->slug; ?>" size="39" /></td> </tr> <tr> <td class="spider_label"><label for="description">Description: </label></td> <td> <div style="width:500px;"> <?php if (user_can_richedit()) { wp_editor($row->description, 'description', array('teeny' => FALSE, 'textarea_name' => 'description', 'media_buttons' => FALSE, 'textarea_rows' => 5)); } else { ?> <textarea cols="36" rows="5" id="description" name="description" style="resize:vertical"> <?php echo $row->description; ?> </textarea> <?php } ?> </div> </td> </tr> <tr> <td class="spider_label"><label>Author: </label></td> <td><?php echo get_userdata($row->author)->display_name; ?></td> </tr> <tr> <td class="spider_label"><label for="published1">Published: </label></td> <td> <input type="radio" class="inputbox" id="published0" name="published" <?php echo (($row->published) ? '' : 'checked="checked"'); ?> value="0" > <label for="published0">No</label> <input type="radio" class="inputbox" id="published1" name="published" <?php echo (($row->published) ? 'checked="checked"' : ''); ?> value="1" > <label for="published1">Yes</label> </td> </tr> <tr> <td class="spider_label"><label for="url">Preview image: </label></td> <td> <a href="<?php echo add_query_arg(array('action' => 'addImages', 'width' => '700', 'height' => '550', 'extensions' => 'jpg,jpeg,png,gif', 'callback' => '<API key>', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>" id="<API key>" class="button-primary thickbox thickbox-preview" title="Add Preview Image" onclick="return false;" style="margin-bottom:5px; display:none;"> Add Preview Image </a> <input type="hidden" id="preview_image" name="preview_image" value="<?php echo $row->preview_image; ?>" style="display:inline-block;"/> <img id="img_preview_image" style="max-height:90px; max-width:120px; vertical-align:middle;" src="<?php echo site_url() . '/' . $WD_BWG_UPLOAD_DIR . $row->preview_image; ?>"> <span id="<API key>" class="spider_delete_img" onclick="spider_remove_url('<API key>', 'preview_image', '<API key>', 'img_preview_image')"></span> </td> </tr> <tr> <td colspan=2> <?php echo $this->image_display($id); ?> </td> </tr> </tbody> </table> <input id="task" name="task" type="hidden" value="" /> <input id="current_id" name="current_id" type="hidden" value="<?php echo $row->id; ?>" /> <script> <?php if ($row->preview_image == '') { ?> spider_remove_url('<API key>', 'preview_image', '<API key>', 'img_preview_image'); <?php } ?> </script> <div id="opacity_div" style="display: none; background-color: rgba(0, 0, 0, 0.2); position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99998;"></div> <div id="loading_div" style="display:none; text-align: center; position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99999;"> <img src="<?php echo WD_BWG_URL . '/images/ajax_loader.png'; ?>" class="spider_ajax_loading" style="margin-top: 200px; width:50px;"> </div> </form> <?php } public function image_display($id) { global $WD_BWG_UPLOAD_DIR; $rows_data = $this->model->get_image_rows_data($id); $page_nav = $this->model->image_page_nav($id); $option_row = $this->model->get_option_row_data(); $search_value = ((isset($_POST['search_value'])) ? esc_html(stripslashes($_POST['search_value'])) : ''); $asc_or_desc = ((isset($_POST['asc_or_desc'])) ? esc_html(stripslashes($_POST['asc_or_desc'])) : 'asc'); $image_order_by = (isset($_POST['image_order_by']) ? esc_html(stripslashes($_POST['image_order_by'])) : 'order'); $order_class = 'manage-column column-title sorted ' . $asc_or_desc; $page_number = (isset($_POST['page_number']) ? esc_html(stripslashes($_POST['page_number'])) : 1); $ids_string = ''; ?> <div id="draganddrop" class="updated" style="display:none;"><strong><p>Changes made in this table should be saved.</p></strong></div> <div class="buttons_div_left"> <a href="<?php echo add_query_arg(array('action' => 'addImages', 'width' => '700', 'height' => '550', 'extensions' => 'jpg,jpeg,png,gif', 'callback' => 'bwg_add_image', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>" class="button-primary thickbox thickbox-preview" id="content-add_media" title="Add Images" onclick="return false;" style="margin-bottom:5px;"> Add Images </a> <input id="show_add_video" class="button-primary" type="button" onclick="jQuery('.opacity_add_video').show(); return false;" value="Add Video" /> </div> <div class="buttons_div_right"> <span class="button-secondary non_selectable" onclick="<API key>()"> <input type="checkbox" id="check_all_items" name="check_all_items" onclick="<API key>()" style="margin: 0; vertical-align: middle;" /> <span style="vertical-align: middle;">Select All</span> </span> <input id="show_hide_weights" class="button-secondary" type="button" onclick="<API key>();return false;" value="Hide order column" /> <input class="button-primary" type="submit" onclick="<API key>('ajax_task', 'image_set_watermark'); spider_ajax_save('galleries_form'); return false;" value="Set Watermark" /> <input class="button-secondary" type="submit" onclick="jQuery('.<API key>').show(); return false;" value="Resize" /> <input class="button-secondary" type="submit" onclick="<API key>('ajax_task', 'image_recover_all'); spider_ajax_save('galleries_form'); return false;" value="Reset" /> <a onclick="return <API key>();" href="<?php echo add_query_arg(array('action' => 'addTags', 'width' => '650', 'height' => '500'), admin_url('admin-ajax.php')); ?>&TB_iframe=1" class="button-primary thickbox thickbox-preview">Add tag</a> <input class="button-secondary" type="submit" onclick="<API key>('ajax_task', 'image_publish_all'); spider_ajax_save('galleries_form'); return false;" value="Publish" /> <input class="button-secondary" type="submit" onclick="<API key>('ajax_task', 'image_unpublish_all'); spider_ajax_save('galleries_form'); return false;" value="Unpublish" /> <input class="button-secondary" type="submit" onclick="if (confirm('Do you want to delete selected items?')) { <API key>('ajax_task', 'image_delete_all'); spider_ajax_save('galleries_form'); return false; } else { return false; }" value="Delete" /> </div> <div id="opacity_add_video" class="<API key> opacity_add_video bwg_opacity_video" onclick="jQuery('.opacity_add_video').hide();jQuery('.<API key>').hide();"></div> <div id="add_video" class="opacity_add_video bwg_add_video"> <input type="text" id="video_url" name="video_url" value="" /> <input class="button-primary" type="button" onclick="if (bwg_get_video_info('video_url')) {jQuery('.opacity_add_video').hide();} return false;" value="Add to gallery" /> <input class="button-secondary" type="button" onclick="jQuery('.opacity_add_video').hide(); return false;" value="Cancel" /> <div class="spider_description">Enter YouTube or Vimeo link here.</div> </div> <div id="" class="<API key> bwg_resize_image"> Resize images to: <input type="text" name="image_width" id="image_width" value="1600" /> x <input type="text" name="image_height" id="image_height" value="1200" /> px <input class="button-primary" type="button" onclick="<API key>('ajax_task', 'image_resize'); spider_ajax_save('galleries_form'); jQuery('.<API key>').hide(); return false;" value="Resize" /> <input class="button-secondary" type="button" onclick="jQuery('.<API key>').hide(); return false;" value="Cancel" /> <div class="spider_description">The maximum size of resized image.</div> </div> <div class="tablenav top"> <?php WDWLibrary::ajax_search('Filename', $search_value, 'galleries_form'); WDWLibrary::ajax_html_page_nav($page_nav['total'], $page_nav['limit'], 'galleries_form'); ?> </div> <table id="images_table" class="wp-list-table widefat fixed pages"> <thead> <th class="check-column table_small_col"></th> <th class="manage-column column-cb check-column table_small_col"><input id="check_all" type="checkbox" onclick="spider_check_all(this)" style="margin:0;" /></th> <th class="table_small_col"> <th class="<API key>">Thumbnail</th> <th class="<API key> <?php if ($image_order_by == 'filename') {echo $order_class;} ?>"> <a onclick="<API key>('task', ''); <API key>('image_order_by', 'filename'); <API key>('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'filename') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_ajax_save('galleries_form');"> <span>Filename</span><span class="sorting-indicator"></span> </a> </th> <th class="<API key> <?php if ($image_order_by == 'alt') {echo $order_class;} ?>"> <a onclick="<API key>('task', ''); <API key>('image_order_by', 'alt'); <API key>('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'alt') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_ajax_save('galleries_form');"> <span>Alt/Title<?php if ($option_row->thumb_click_action != 'open_lightbox') { ?><br />Redirect URL<?php } ?></span><span class="sorting-indicator"></span> </a> </th> <th class="<API key> <?php if ($image_order_by == 'description') {echo $order_class;} ?>"> <a onclick="<API key>('task', ''); <API key>('image_order_by', 'description'); <API key>('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'description') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_ajax_save('galleries_form');"> <span>Description</span><span class="sorting-indicator"></span> </a> </th> <th class="<API key>">Tags</th> <th id="th_order" class="table_medium_col <?php if ($image_order_by == 'order') {echo $order_class;} ?>"> <a onclick="<API key>('task', ''); <API key>('image_order_by', 'order'); <API key>('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'order') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_ajax_save('galleries_form');"> <span>Order</span><span class="sorting-indicator"></span> </a> </th> <th class="table_big_col <?php if ($image_order_by == 'published') {echo $order_class;} ?>"> <a onclick="<API key>('task', ''); <API key>('image_order_by', 'published'); <API key>('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'published') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_ajax_save('galleries_form');"> <span>Published</span><span class="sorting-indicator"></span> </a> </th> <th class="table_big_col">Delete</th> </thead> <tbody id="tbody_arr"> <?php $i = ($page_number - 1) * 20; if ($rows_data) { foreach ($rows_data as $row_data) { $is_video = $row_data->filetype == 'YOUTUBE' || $row_data->filetype == 'VIMEO'; $alternate = (!isset($alternate) || $alternate == 'class="alternate"') ? '' : 'class="alternate"'; $rows_tag_data = $this->model->get_tag_rows_data($row_data->id); $published_image = (($row_data->published) ? 'publish' : 'unpublish'); $published = (($row_data->published) ? 'unpublish' : 'publish'); ?> <tr id="tr_<?php echo $row_data->id; ?>" <?php echo $alternate; ?>> <td class="connectedSortable table_small_col"><div title="Drag to re-order" class="handle" style="margin:5px auto 0 auto;"></div></td> <td class="table_small_col check-column"><input id="check_<?php echo $row_data->id; ?>" name="check_<?php echo $row_data->id; ?>" onclick="spider_check_all(this)" type="checkbox" /></td> <td class="table_small_col"><?php echo ++$i; ?></td> <td class="<API key>"> <a class="thickbox thickbox-preview" title="<?php echo $row_data->alt; ?>" href="<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'display'/*thumb_display*/, 'image_id' => $row_data->id, 'width' => '800', 'height' => '500', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>"> <img id="image_thumb_<?php echo $row_data->id; ?>" class="thumb" src="<?php echo (!$is_video ? site_url() . '/' . $WD_BWG_UPLOAD_DIR : "") . $row_data->thumb_url . '?date=' . date('Y-m-y H:i:s'); ?>"> </a> </td> <td class="<API key>"> <div class="filename" id="filename_<?php echo $row_data->id; ?>"> <strong><a title="<?php echo $row_data->alt; ?>" class="spider_word_wrap thickbox thickbox-preview" href="<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'display', 'image_id' => $row_data->id, 'width' => '800', 'height' => '500', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>"><?php echo $row_data->filename; ?></a></strong> </div> <div class="fileDescription" title="Date modified" id="date_modified_<?php echo $row_data->id; ?>"><?php echo date("d F Y, H:i", strtotime($row_data->date)); ?></div> <div class="fileDescription" title="Image Resolution" id="fileresolution_<?php echo $row_data->id; ?>"><?php echo $row_data->resolution; ?></div> <div class="fileDescription" title="<?php echo (!$is_video ? "Image size" : "Duration")?>" id="filesize_<?php echo $row_data->id; ?>"><?php echo $row_data->size; ?></div> <div class="fileDescription" title="Type" id="filetype_<?php echo $row_data->id; ?>"><?php echo $row_data->filetype; ?></div> <?php if(!$is_video) {?> <div> <span class="edit_thumb"><a class="thickbox thickbox-preview" href="<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'crop', 'image_id' => $row_data->id, 'TB_iframe' => '1', 'width' => '800', 'height' => '500'), admin_url('admin-ajax.php')); ?>">Crop</a></span> | <span class="edit_thumb"><a class="thickbox thickbox-preview" href="<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'rotate', 'image_id' => $row_data->id, 'width' => '800', 'height' => '500', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>">Rotate</a></span> | <span class="edit_thumb"><a onclick="if (confirm('Do you want to reset the image?')) { <API key>('ajax_task', 'recover'); <API key>('image_current_id', '<?php echo $row_data->id; ?>'); spider_ajax_save('galleries_form'); } return false;">Reset</a></span> </div> <?php } ?> <input type="hidden" id="image_url_<?php echo $row_data->id; ?>" name="image_url_<?php echo $row_data->id; ?>" value="<?php echo $row_data->image_url; ?>" /> <input type="hidden" id="thumb_url_<?php echo $row_data->id; ?>" name="thumb_url_<?php echo $row_data->id; ?>" value="<?php echo $row_data->thumb_url; ?>" /> <input type="hidden" id="input_filename_<?php echo $row_data->id; ?>" name="input_filename_<?php echo $row_data->id; ?>" value="<?php echo $row_data->filename; ?>" /> <input type="hidden" id="<API key><?php echo $row_data->id; ?>" name="<API key><?php echo $row_data->id; ?>" value="<?php echo $row_data->date; ?>" /> <input type="hidden" id="input_resolution_<?php echo $row_data->id; ?>" name="input_resolution_<?php echo $row_data->id; ?>" value="<?php echo $row_data->resolution; ?>" /> <input type="hidden" id="input_size_<?php echo $row_data->id; ?>" name="input_size_<?php echo $row_data->id; ?>" value="<?php echo $row_data->size; ?>" /> <input type="hidden" id="input_filetype_<?php echo $row_data->id; ?>" name="input_filetype_<?php echo $row_data->id; ?>" value="<?php echo $row_data->filetype; ?>" /> </td> <td class="<API key>"> <input size="24" type="text" id="image_alt_text_<?php echo $row_data->id; ?>" name="image_alt_text_<?php echo $row_data->id; ?>" value="<?php echo $row_data->alt; ?>" /> <?php if ($option_row->thumb_click_action != 'open_lightbox') { ?> <input size="24" type="text" id="redirect_url_<?php echo $row_data->id; ?>" name="redirect_url_<?php echo $row_data->id; ?>" value="<?php echo $row_data->redirect_url; ?>" /> <?php } ?> </td> <td class="<API key>"> <textarea cols="20" rows="2" id="image_description_<?php echo $row_data->id; ?>" name="image_description_<?php echo $row_data->id; ?>" style="resize:vertical;"><?php echo $row_data->description; ?></textarea> </td> <td class="<API key>"> <a href="<?php echo add_query_arg(array('action' => 'addTags', 'image_id' => $row_data->id, 'width' => '650', 'height' => '500', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>" class="button button-small button-primary thickbox thickbox-preview">Add tag</a> <div class="tags_div" id="tags_div_<?php echo $row_data->id; ?>"> <?php $tags_id_string = ''; if ($rows_tag_data) { foreach($rows_tag_data as $row_tag_data) { ?> <div class="tag_div" id="<?php echo $row_data->id; ?>_tag_<?php echo $row_tag_data->term_id; ?>"> <span class="tag_name"><?php echo $row_tag_data->name; ?></span> <span style="float:right;" class="<API key>" onclick="bwg_remove_tag('<?php echo $row_tag_data->term_id; ?>', '<?php echo $row_data->id; ?>')" /> </div> <?php $tags_id_string .= $row_tag_data->term_id . ','; } } ?> </div> <input type="hidden" value="<?php echo $tags_id_string; ?>" id="tags_<?php echo $row_data->id; ?>" name="tags_<?php echo $row_data->id; ?>"/> </td> <td class="spider_order table_medium_col"><input id="order_input_<?php echo $row_data->id; ?>" name="order_input_<?php echo $row_data->id; ?>" type="text" size="1" value="<?php echo $row_data->order; ?>" /></td> <td class="table_big_col"><a onclick="<API key>('ajax_task', 'image_<?php echo $published; ?>'); <API key>('image_current_id', '<?php echo $row_data->id; ?>'); spider_ajax_save('galleries_form');"><img src="<?php echo WD_BWG_URL . '/images/' . $published_image . '.png'; ?>"></img></a></td> <td class="table_big_col"><a onclick="<API key>('ajax_task', 'image_delete'); <API key>('image_current_id', '<?php echo $row_data->id; ?>'); spider_ajax_save('galleries_form');">Delete</a></td> </tr> <?php $ids_string .= $row_data->id . ','; } } ?> <input id="ids_string" name="ids_string" type="hidden" value="<?php echo $ids_string; ?>" /> <input id="asc_or_desc" name="asc_or_desc" type="hidden" value="asc" /> <input id="image_order_by" name="image_order_by" type="hidden" value="<?php echo $image_order_by; ?>" /> <input id="ajax_task" name="ajax_task" type="hidden" value="" /> <input id="image_current_id" name="image_current_id" type="hidden" value="" /> <input id="<API key>" name="<API key>" type="hidden" value="" /> </tbody> </table> <script> window.onload = <API key>; </script> <?php } // Getters & Setters // // Private Methods // // Listeners // }
package visitors; public interface IVisitedSort extends IVisited { Object accept(ISortVisitor visitor); }
package net.sourceforge.atunes.kernel.modules.navigator; import java.awt.Component; import java.util.List; import javax.swing.Action; import javax.swing.JMenu; import javax.swing.JMenuItem; import net.sourceforge.atunes.kernel.actions.<API key>; import net.sourceforge.atunes.model.IAudioObject; import net.sourceforge.atunes.model.IPlayListHandler; import net.sourceforge.atunes.model.ITreeNode; /** * Enables or disables navigator actions given selection * * @author alex * */ public class <API key> { private IPlayListHandler playListHandler; /** * @param playListHandler */ public void setPlayListHandler(final IPlayListHandler playListHandler) { this.playListHandler = playListHandler; } /** * Enables or disables tree popup actions * * @param rootSelected * @param components * @param nodes */ void <API key>(final boolean rootSelected, final Component[] components, final List<ITreeNode> nodes) { for (Component c : components) { updateMenuComponent(rootSelected, nodes, c); } } /** * Enables or disables table popup actions * * @param rootSelected * @param components * @param selection */ void <API key>(final boolean rootSelected, final Component[] components, final List<IAudioObject> selection) { for (Component c : components) { <API key>(rootSelected, selection, c); } } /** * @param rootSelected * @param selection * @param c */ private void updateMenuComponent(final boolean rootSelected, final List<ITreeNode> selection, final Component c) { if (c != null) { if (c instanceof JMenu) { for (int i = 0; i < ((JMenu) c).getItemCount(); i++) { updateMenuComponent(rootSelected, selection, ((JMenu) c).getItem(i)); } } else if (c instanceof JMenuItem) { updateMenuItem(rootSelected, selection, (JMenuItem) c); } } } /** * @param rootSelected * @param selection * @param c */ private void <API key>(final boolean rootSelected, final List<IAudioObject> selection, final Component c) { if (c != null) { if (c instanceof JMenu) { for (int i = 0; i < ((JMenu) c).getItemCount(); i++) { <API key>(rootSelected, selection, ((JMenu) c).getItem(i)); } } else if (c instanceof JMenuItem) { updateTableMenuItem(rootSelected, selection, (JMenuItem) c); } } } /** * @param rootSelected * @param selection * @param menuItem */ private void updateMenuItem(final boolean rootSelected, final List<ITreeNode> selection, final JMenuItem menuItem) { Action a = menuItem.getAction(); if (a instanceof <API key>) { <API key> customAction = (<API key>) a; if (!customAction.<API key>(this.playListHandler .getVisiblePlayList())) { customAction.setEnabled(false); } else { customAction.setEnabled(customAction .<API key>(rootSelected, selection)); } } } /** * @param rootSelected * @param selection * @param menuItem */ private void updateTableMenuItem(final boolean rootSelected, final List<IAudioObject> selection, final JMenuItem menuItem) { Action a = menuItem.getAction(); if (a instanceof <API key>) { <API key> customAction = (<API key>) a; if (!customAction.<API key>(this.playListHandler .getVisiblePlayList())) { customAction.setEnabled(false); } else { customAction.setEnabled(customAction .<API key>(selection)); } } } }