code
stringlengths
4
1.01M
language
stringclasses
2 values
# Eucalyptus laevis L.A.S. Johnson & K.D. Hill SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Sarcophyllis J.G. Agardh, 1876 GENUS #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Melasmia spiralis Petr. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Sydowia 7(1-4): 149 (1953) #### Original name Melasmia spiralis Petr. ### Remarks null
Java
# Sylphia cabellensis (Rchb.f.) Luer SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Eucalyptus hawkeri Rule SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
# Agaricus croceo-caeruleus Pers. SPECIES #### Status SYNONYM #### According to Index Fungorum #### Published in null #### Original name Agaricus croceo-caeruleus Pers. ### Remarks null
Java
# Flotowia Endl. GENUS #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
# Scindapsus cuscuaria (Aubl.) C.Presl SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Urera aurantiaca Wedd. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
# Decaneurum epilejum DC. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
<!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_45) on Wed Aug 28 02:24:21 PDT 2013 --> <TITLE> ActivityChooserModel.ActivitySorter </TITLE> <META NAME="date" CONTENT="2013-08-28"> <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="ActivityChooserModel.ActivitySorter"; } } </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="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ActivityChooserModel.ActivitySorter.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&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;<A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.ActivityResolveInfo.html" title="class in android.support.v7.internal.widget"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.HistoricalRecord.html" title="class in android.support.v7.internal.widget"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?android/support/v7/internal/widget/ActivityChooserModel.ActivitySorter.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ActivityChooserModel.ActivitySorter.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> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> android.support.v7.internal.widget</FONT> <BR> Interface ActivityChooserModel.ActivitySorter</H2> <DL> <DT><B>Enclosing class:</B><DD><A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.html" title="class in android.support.v7.internal.widget">ActivityChooserModel</A></DD> </DL> <HR> <DL> <DT><PRE>public static interface <B>ActivityChooserModel.ActivitySorter</B></DL> </PRE> <P> Defines a sorter that is responsible for sorting the activities based on the provided historical choices and an intent. <P> <P> <HR> <P> <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.ActivitySorter.html#sort(Intent, java.util.List, java.util.List)">sort</A></B>(Intent&nbsp;intent, java.util.List&lt;<A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.ActivityResolveInfo.html" title="class in android.support.v7.internal.widget">ActivityChooserModel.ActivityResolveInfo</A>&gt;&nbsp;activities, java.util.List&lt;<A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.HistoricalRecord.html" title="class in android.support.v7.internal.widget">ActivityChooserModel.HistoricalRecord</A>&gt;&nbsp;historicalRecords)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sorts the <code>activities</code> in descending order of relevance based on previous history and an intent.</TD> </TR> </TABLE> &nbsp; <P> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="sort(Intent, java.util.List, java.util.List)"><!-- --></A><H3> sort</H3> <PRE> void <B>sort</B>(Intent&nbsp;intent, java.util.List&lt;<A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.ActivityResolveInfo.html" title="class in android.support.v7.internal.widget">ActivityChooserModel.ActivityResolveInfo</A>&gt;&nbsp;activities, java.util.List&lt;<A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.HistoricalRecord.html" title="class in android.support.v7.internal.widget">ActivityChooserModel.HistoricalRecord</A>&gt;&nbsp;historicalRecords)</PRE> <DL> <DD>Sorts the <code>activities</code> in descending order of relevance based on previous history and an intent. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>intent</CODE> - The <CODE>Intent</CODE>.<DD><CODE>activities</CODE> - Activities to be sorted.<DD><CODE>historicalRecords</CODE> - Historical records.</DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <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="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ActivityChooserModel.ActivitySorter.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&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;<A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.ActivityResolveInfo.html" title="class in android.support.v7.internal.widget"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.HistoricalRecord.html" title="class in android.support.v7.internal.widget"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?android/support/v7/internal/widget/ActivityChooserModel.ActivitySorter.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ActivityChooserModel.ActivitySorter.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> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
Java
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>AdminLTE 2 | Editors</title> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <!-- Bootstrap 3.3.6 --> <link rel="stylesheet" href="../../bootstrap/css/bootstrap.min.css"> <!-- Font Awesome --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css"> <!-- Ionicons --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css"> <!-- Theme style --> <link rel="stylesheet" href="../../dist/css/AdminLTE.min.css"> <!-- AdminLTE Skins. Choose a skin from the css/skins folder instead of downloading all of them to reduce the load. --> <link rel="stylesheet" href="../../dist/css/skins/_all-skins.min.css"> <!-- bootstrap wysihtml5 - text editor --> <link rel="stylesheet" href="../../plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body class="hold-transition skin-blue sidebar-mini"> <div class="wrapper"> <header class="main-header"> <!-- Logo --> <a href="../../index2.html" class="logo"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><b>A</b>LT</span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><b>Admin</b>LTE</span> </a> <!-- Header Navbar: style can be found in header.less --> <nav class="navbar navbar-static-top"> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <div class="navbar-custom-menu"> <ul class="nav navbar-nav"> <!-- Messages: style can be found in dropdown.less--> <li class="dropdown messages-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-envelope-o"></i> <span class="label label-success">4</span> </a> <ul class="dropdown-menu"> <li class="header">You have 4 messages</li> <li> <!-- inner menu: contains the actual data --> <ul class="menu"> <li><!-- start message --> <a href="#"> <div class="pull-left"> <img src="../../dist/img/user2-160x160.jpg" class="img-circle" alt="User Image"> </div> <h4> Support Team <small><i class="fa fa-clock-o"></i> 5 mins</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> <!-- end message --> <li> <a href="#"> <div class="pull-left"> <img src="../../dist/img/user3-128x128.jpg" class="img-circle" alt="User Image"> </div> <h4> AdminLTE Design Team <small><i class="fa fa-clock-o"></i> 2 hours</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> <li> <a href="#"> <div class="pull-left"> <img src="../../dist/img/user4-128x128.jpg" class="img-circle" alt="User Image"> </div> <h4> Developers <small><i class="fa fa-clock-o"></i> Today</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> <li> <a href="#"> <div class="pull-left"> <img src="../../dist/img/user3-128x128.jpg" class="img-circle" alt="User Image"> </div> <h4> Sales Department <small><i class="fa fa-clock-o"></i> Yesterday</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> <li> <a href="#"> <div class="pull-left"> <img src="../../dist/img/user4-128x128.jpg" class="img-circle" alt="User Image"> </div> <h4> Reviewers <small><i class="fa fa-clock-o"></i> 2 days</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> </ul> </li> <li class="footer"><a href="#">See All Messages</a></li> </ul> </li> <!-- Notifications: style can be found in dropdown.less --> <li class="dropdown notifications-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-bell-o"></i> <span class="label label-warning">10</span> </a> <ul class="dropdown-menu"> <li class="header">You have 10 notifications</li> <li> <!-- inner menu: contains the actual data --> <ul class="menu"> <li> <a href="#"> <i class="fa fa-users text-aqua"></i> 5 new members joined today </a> </li> <li> <a href="#"> <i class="fa fa-warning text-yellow"></i> Very long description here that may not fit into the page and may cause design problems </a> </li> <li> <a href="#"> <i class="fa fa-users text-red"></i> 5 new members joined </a> </li> <li> <a href="#"> <i class="fa fa-shopping-cart text-green"></i> 25 sales made </a> </li> <li> <a href="#"> <i class="fa fa-user text-red"></i> You changed your username </a> </li> </ul> </li> <li class="footer"><a href="#">View all</a></li> </ul> </li> <!-- Tasks: style can be found in dropdown.less --> <li class="dropdown tasks-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-flag-o"></i> <span class="label label-danger">9</span> </a> <ul class="dropdown-menu"> <li class="header">You have 9 tasks</li> <li> <!-- inner menu: contains the actual data --> <ul class="menu"> <li><!-- Task item --> <a href="#"> <h3> Design some buttons <small class="pull-right">20%</small> </h3> <div class="progress xs"> <div class="progress-bar progress-bar-aqua" style="width: 20%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">20% Complete</span> </div> </div> </a> </li> <!-- end task item --> <li><!-- Task item --> <a href="#"> <h3> Create a nice theme <small class="pull-right">40%</small> </h3> <div class="progress xs"> <div class="progress-bar progress-bar-green" style="width: 40%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">40% Complete</span> </div> </div> </a> </li> <!-- end task item --> <li><!-- Task item --> <a href="#"> <h3> Some task I need to do <small class="pull-right">60%</small> </h3> <div class="progress xs"> <div class="progress-bar progress-bar-red" style="width: 60%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">60% Complete</span> </div> </div> </a> </li> <!-- end task item --> <li><!-- Task item --> <a href="#"> <h3> Make beautiful transitions <small class="pull-right">80%</small> </h3> <div class="progress xs"> <div class="progress-bar progress-bar-yellow" style="width: 80%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">80% Complete</span> </div> </div> </a> </li> <!-- end task item --> </ul> </li> <li class="footer"> <a href="#">View all tasks</a> </li> </ul> </li> <!-- User Account: style can be found in dropdown.less --> <li class="dropdown user user-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <img src="../../dist/img/user2-160x160.jpg" class="user-image" alt="User Image"> <span class="hidden-xs">Alexander Pierce</span> </a> <ul class="dropdown-menu"> <!-- User image --> <li class="user-header"> <img src="../../dist/img/user2-160x160.jpg" class="img-circle" alt="User Image"> <p> Alexander Pierce - Web Developer <small>Member since Nov. 2012</small> </p> </li> <!-- Menu Body --> <li class="user-body"> <div class="row"> <div class="col-xs-4 text-center"> <a href="#">Followers</a> </div> <div class="col-xs-4 text-center"> <a href="#">Sales</a> </div> <div class="col-xs-4 text-center"> <a href="#">Friends</a> </div> </div> <!-- /.row --> </li> <!-- Menu Footer--> <li class="user-footer"> <div class="pull-left"> <a href="#" class="btn btn-default btn-flat">Profile</a> </div> <div class="pull-right"> <a href="#" class="btn btn-default btn-flat">Sign out</a> </div> </li> </ul> </li> <!-- Control Sidebar Toggle Button --> <li> <a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a> </li> </ul> </div> </nav> </header> <!-- Left side column. contains the logo and sidebar --> <aside class="main-sidebar"> <!-- sidebar: style can be found in sidebar.less --> <section class="sidebar"> <!-- Sidebar user panel --> <div class="user-panel"> <div class="pull-left image"> <img src="../../dist/img/user2-160x160.jpg" class="img-circle" alt="User Image"> </div> <div class="pull-left info"> <p>Alexander Pierce</p> <a href="#"><i class="fa fa-circle text-success"></i> Online</a> </div> </div> <!-- search form --> <form action="#" method="get" class="sidebar-form"> <div class="input-group"> <input type="text" name="q" class="form-control" placeholder="Search..."> <span class="input-group-btn"> <button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i> </button> </span> </div> </form> <!-- /.search form --> <!-- sidebar menu: : style can be found in sidebar.less --> <ul class="sidebar-menu"> <li class="header">MAIN NAVIGATION</li> <li class="treeview"> <a href="#"> <i class="fa fa-dashboard"></i> <span>Dashboard</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="../../index.html"><i class="fa fa-circle-o"></i> Dashboard v1</a></li> <li><a href="../../index2.html"><i class="fa fa-circle-o"></i> Dashboard v2</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-files-o"></i> <span>Layout Options</span> <span class="pull-right-container"> <span class="label label-primary pull-right">4</span> </span> </a> <ul class="treeview-menu"> <li><a href="../layout/top-nav.html"><i class="fa fa-circle-o"></i> Top Navigation</a></li> <li><a href="../layout/boxed.html"><i class="fa fa-circle-o"></i> Boxed</a></li> <li><a href="../layout/fixed.html"><i class="fa fa-circle-o"></i> Fixed</a></li> <li><a href="../layout/collapsed-sidebar.html"><i class="fa fa-circle-o"></i> Collapsed Sidebar</a></li> </ul> </li> <li> <a href="../widgets.html"> <i class="fa fa-th"></i> <span>Widgets</span> <span class="pull-right-container"> <small class="label pull-right bg-green">new</small> </span> </a> </li> <li class="treeview"> <a href="#"> <i class="fa fa-pie-chart"></i> <span>Charts</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="../charts/chartjs.html"><i class="fa fa-circle-o"></i> ChartJS</a></li> <li><a href="../charts/morris.html"><i class="fa fa-circle-o"></i> Morris</a></li> <li><a href="../charts/flot.html"><i class="fa fa-circle-o"></i> Flot</a></li> <li><a href="../charts/inline.html"><i class="fa fa-circle-o"></i> Inline charts</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-laptop"></i> <span>UI Elements</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="../UI/general.html"><i class="fa fa-circle-o"></i> General</a></li> <li><a href="../UI/icons.html"><i class="fa fa-circle-o"></i> Icons</a></li> <li><a href="../UI/buttons.html"><i class="fa fa-circle-o"></i> Buttons</a></li> <li><a href="../UI/sliders.html"><i class="fa fa-circle-o"></i> Sliders</a></li> <li><a href="../UI/timeline.html"><i class="fa fa-circle-o"></i> Timeline</a></li> <li><a href="../UI/modals.html"><i class="fa fa-circle-o"></i> Modals</a></li> </ul> </li> <li class="treeview active"> <a href="#"> <i class="fa fa-edit"></i> <span>Forms</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="general.html"><i class="fa fa-circle-o"></i> General Elements</a></li> <li><a href="advanced.html"><i class="fa fa-circle-o"></i> Advanced Elements</a></li> <li class="active"><a href="editors.html"><i class="fa fa-circle-o"></i> Editors</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-table"></i> <span>Tables</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="../tables/simple.html"><i class="fa fa-circle-o"></i> Simple tables</a></li> <li><a href="../tables/data.html"><i class="fa fa-circle-o"></i> Data tables</a></li> </ul> </li> <li> <a href="../calendar.html"> <i class="fa fa-calendar"></i> <span>Calendar</span> <span class="pull-right-container"> <small class="label pull-right bg-red">3</small> <small class="label pull-right bg-blue">17</small> </span> </a> </li> <li> <a href="../mailbox/mailbox.html"> <i class="fa fa-envelope"></i> <span>Mailbox</span> <span class="pull-right-container"> <small class="label pull-right bg-yellow">12</small> <small class="label pull-right bg-green">16</small> <small class="label pull-right bg-red">5</small> </span> </a> </li> <li class="treeview"> <a href="#"> <i class="fa fa-folder"></i> <span>Examples</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="../examples/invoice.html"><i class="fa fa-circle-o"></i> Invoice</a></li> <li><a href="../examples/profile.html"><i class="fa fa-circle-o"></i> Profile</a></li> <li><a href="../examples/login.html"><i class="fa fa-circle-o"></i> Login</a></li> <li><a href="../examples/register.html"><i class="fa fa-circle-o"></i> Register</a></li> <li><a href="../examples/lockscreen.html"><i class="fa fa-circle-o"></i> Lockscreen</a></li> <li><a href="../examples/404.html"><i class="fa fa-circle-o"></i> 404 Error</a></li> <li><a href="../examples/500.html"><i class="fa fa-circle-o"></i> 500 Error</a></li> <li><a href="../examples/blank.html"><i class="fa fa-circle-o"></i> Blank Page</a></li> <li><a href="../examples/pace.html"><i class="fa fa-circle-o"></i> Pace Page</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-share"></i> <span>Multilevel</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o"></i> Level One</a></li> <li> <a href="#"><i class="fa fa-circle-o"></i> Level One <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o"></i> Level Two</a></li> <li> <a href="#"><i class="fa fa-circle-o"></i> Level Two <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o"></i> Level Three</a></li> <li><a href="#"><i class="fa fa-circle-o"></i> Level Three</a></li> </ul> </li> </ul> </li> <li><a href="#"><i class="fa fa-circle-o"></i> Level One</a></li> </ul> </li> <li><a href="../../documentation/index.html"><i class="fa fa-book"></i> <span>Documentation</span></a></li> <!-- 文章管理 --> <li class="treeview"> <a href="#"> <i class="glyphicon glyphicon-list-alt"></i> <span>文章管理</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="../tables/article.html"><i class="fa fa-circle-o"></i>文章管理</a></li> <li><a href="#"><i class="fa fa-circle-o"></i>铝锭走势分析</a></li> <li><a href="#"><i class="fa fa-circle-o"></i>国际铝行情</a></li> <li><a href="#"><i class="fa fa-circle-o"></i>上海铝协动态</a></li> </ul> </li> <li class="header">LABELS</li> <li><a href="#"><i class="fa fa-circle-o text-red"></i> <span>Important</span></a></li> <li><a href="#"><i class="fa fa-circle-o text-yellow"></i> <span>Warning</span></a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> <span>Information</span></a></li> </ul> </section> <!-- /.sidebar --> </aside> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Text Editors <small>Advanced form element</small> </h1> <ol class="breadcrumb"> <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li> <li><a href="#">Forms</a></li> <li class="active">Editors</li> </ol> </section> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-md-12"> <div class="box box-info"> <div class="box-header"> <h3 class="box-title">CK Editor <small>Advanced and full of features</small> </h3> <!-- tools box --> <div class="pull-right box-tools"> <button type="button" class="btn btn-info btn-sm" data-widget="collapse" data-toggle="tooltip" title="Collapse"> <i class="fa fa-minus"></i></button> <button type="button" class="btn btn-info btn-sm" data-widget="remove" data-toggle="tooltip" title="Remove"> <i class="fa fa-times"></i></button> </div> <!-- /. tools --> </div> <!-- /.box-header --> <div class="box-body pad"> <form> <textarea id="editor1" name="editor1" rows="10" cols="80"> This is my textarea to be replaced with CKEditor. </textarea> </form> </div> </div> <!-- /.box --> <div class="box"> <div class="box-header"> <h3 class="box-title">Bootstrap WYSIHTML5 <small>Simple and fast</small> </h3> <!-- tools box --> <div class="pull-right box-tools"> <button type="button" class="btn btn-default btn-sm" data-widget="collapse" data-toggle="tooltip" title="Collapse"> <i class="fa fa-minus"></i></button> <button type="button" class="btn btn-default btn-sm" data-widget="remove" data-toggle="tooltip" title="Remove"> <i class="fa fa-times"></i></button> </div> <!-- /. tools --> </div> <!-- /.box-header --> <div class="box-body pad"> <form> <textarea class="textarea" placeholder="Place some text here" style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea> </form> </div> </div> </div> <!-- /.col--> </div> <!-- ./row --> </section> <!-- /.content --> </div> <!-- /.content-wrapper --> <footer class="main-footer"> <div class="pull-right hidden-xs"> <b>Version</b> 2.3.6 </div> <strong>Copyright &copy; 2014-2016 <a href="http://almsaeedstudio.com">Almsaeed Studio</a>.</strong> All rights reserved. </footer> <!-- Control Sidebar --> <aside class="control-sidebar control-sidebar-dark"> <!-- Create the tabs --> <ul class="nav nav-tabs nav-justified control-sidebar-tabs"> <li><a href="#control-sidebar-home-tab" data-toggle="tab"><i class="fa fa-home"></i></a></li> <li><a href="#control-sidebar-settings-tab" data-toggle="tab"><i class="fa fa-gears"></i></a></li> </ul> <!-- Tab panes --> <div class="tab-content"> <!-- Home tab content --> <div class="tab-pane" id="control-sidebar-home-tab"> <h3 class="control-sidebar-heading">Recent Activity</h3> <ul class="control-sidebar-menu"> <li> <a href="javascript:void(0)"> <i class="menu-icon fa fa-birthday-cake bg-red"></i> <div class="menu-info"> <h4 class="control-sidebar-subheading">Langdon's Birthday</h4> <p>Will be 23 on April 24th</p> </div> </a> </li> <li> <a href="javascript:void(0)"> <i class="menu-icon fa fa-user bg-yellow"></i> <div class="menu-info"> <h4 class="control-sidebar-subheading">Frodo Updated His Profile</h4> <p>New phone +1(800)555-1234</p> </div> </a> </li> <li> <a href="javascript:void(0)"> <i class="menu-icon fa fa-envelope-o bg-light-blue"></i> <div class="menu-info"> <h4 class="control-sidebar-subheading">Nora Joined Mailing List</h4> <p>nora@example.com</p> </div> </a> </li> <li> <a href="javascript:void(0)"> <i class="menu-icon fa fa-file-code-o bg-green"></i> <div class="menu-info"> <h4 class="control-sidebar-subheading">Cron Job 254 Executed</h4> <p>Execution time 5 seconds</p> </div> </a> </li> </ul> <!-- /.control-sidebar-menu --> <h3 class="control-sidebar-heading">Tasks Progress</h3> <ul class="control-sidebar-menu"> <li> <a href="javascript:void(0)"> <h4 class="control-sidebar-subheading"> Custom Template Design <span class="label label-danger pull-right">70%</span> </h4> <div class="progress progress-xxs"> <div class="progress-bar progress-bar-danger" style="width: 70%"></div> </div> </a> </li> <li> <a href="javascript:void(0)"> <h4 class="control-sidebar-subheading"> Update Resume <span class="label label-success pull-right">95%</span> </h4> <div class="progress progress-xxs"> <div class="progress-bar progress-bar-success" style="width: 95%"></div> </div> </a> </li> <li> <a href="javascript:void(0)"> <h4 class="control-sidebar-subheading"> Laravel Integration <span class="label label-warning pull-right">50%</span> </h4> <div class="progress progress-xxs"> <div class="progress-bar progress-bar-warning" style="width: 50%"></div> </div> </a> </li> <li> <a href="javascript:void(0)"> <h4 class="control-sidebar-subheading"> Back End Framework <span class="label label-primary pull-right">68%</span> </h4> <div class="progress progress-xxs"> <div class="progress-bar progress-bar-primary" style="width: 68%"></div> </div> </a> </li> </ul> <!-- /.control-sidebar-menu --> </div> <!-- /.tab-pane --> <!-- Stats tab content --> <div class="tab-pane" id="control-sidebar-stats-tab">Stats Tab Content</div> <!-- /.tab-pane --> <!-- Settings tab content --> <div class="tab-pane" id="control-sidebar-settings-tab"> <form method="post"> <h3 class="control-sidebar-heading">General Settings</h3> <div class="form-group"> <label class="control-sidebar-subheading"> Report panel usage <input type="checkbox" class="pull-right" checked> </label> <p> Some information about this general settings option </p> </div> <!-- /.form-group --> <div class="form-group"> <label class="control-sidebar-subheading"> Allow mail redirect <input type="checkbox" class="pull-right" checked> </label> <p> Other sets of options are available </p> </div> <!-- /.form-group --> <div class="form-group"> <label class="control-sidebar-subheading"> Expose author name in posts <input type="checkbox" class="pull-right" checked> </label> <p> Allow the user to show his name in blog posts </p> </div> <!-- /.form-group --> <h3 class="control-sidebar-heading">Chat Settings</h3> <div class="form-group"> <label class="control-sidebar-subheading"> Show me as online <input type="checkbox" class="pull-right" checked> </label> </div> <!-- /.form-group --> <div class="form-group"> <label class="control-sidebar-subheading"> Turn off notifications <input type="checkbox" class="pull-right"> </label> </div> <!-- /.form-group --> <div class="form-group"> <label class="control-sidebar-subheading"> Delete chat history <a href="javascript:void(0)" class="text-red pull-right"><i class="fa fa-trash-o"></i></a> </label> </div> <!-- /.form-group --> </form> </div> <!-- /.tab-pane --> </div> </aside> <!-- /.control-sidebar --> <!-- Add the sidebar's background. This div must be placed immediately after the control sidebar --> <div class="control-sidebar-bg"></div> </div> <!-- ./wrapper --> <!-- jQuery 2.2.3 --> <script src="../../plugins/jQuery/jquery-2.2.3.min.js"></script> <!-- Bootstrap 3.3.6 --> <script src="../../bootstrap/js/bootstrap.min.js"></script> <!-- FastClick --> <script src="../../plugins/fastclick/fastclick.js"></script> <!-- AdminLTE App --> <script src="../../dist/js/app.min.js"></script> <!-- AdminLTE for demo purposes --> <script src="../../dist/js/demo.js"></script> <!-- CK Editor --> <script src="https://cdn.ckeditor.com/4.5.7/standard/ckeditor.js"></script> <!-- Bootstrap WYSIHTML5 --> <script src="../../plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script> <script> $(function () { // Replace the <textarea id="editor1"> with a CKEditor // instance, using default configuration. CKEDITOR.replace('editor1'); //bootstrap WYSIHTML5 - text editor $(".textarea").wysihtml5(); }); </script> </body> </html>
Java
# coding=utf-8 # Copyright 2022 The Tensor2Tensor Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Base classes and utilities for image datasets.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import io import os import numpy as np from tensor2tensor.data_generators import generator_utils from tensor2tensor.data_generators import problem from tensor2tensor.data_generators import text_encoder from tensor2tensor.layers import common_layers from tensor2tensor.layers import modalities from tensor2tensor.utils import contrib from tensor2tensor.utils import metrics import tensorflow.compat.v1 as tf def matplotlib_pyplot(): import matplotlib # pylint: disable=g-import-not-at-top matplotlib.use("agg") import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top return plt def image_to_tf_summary_value(image, tag): """Converts a NumPy image to a tf.Summary.Value object. Args: image: 3-D NumPy array. tag: name for tf.Summary.Value for display in tensorboard. Returns: image_summary: A tf.Summary.Value object. """ curr_image = np.asarray(image, dtype=np.uint8) height, width, n_channels = curr_image.shape # If monochrome image, then reshape to [height, width] if n_channels == 1: curr_image = np.reshape(curr_image, [height, width]) s = io.BytesIO() matplotlib_pyplot().imsave(s, curr_image, format="png") img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(), height=height, width=width, colorspace=n_channels) return tf.Summary.Value(tag=tag, image=img_sum) def convert_predictions_to_image_summaries(hook_args): """Optionally converts images from hooks_args to image summaries. Args: hook_args: DecodeHookArgs namedtuple Returns: summaries: list of tf.Summary values if hook_args.decode_hpara """ decode_hparams = hook_args.decode_hparams if not decode_hparams.display_decoded_images: return [] predictions = hook_args.predictions[0] # Display ten random inputs and outputs so that tensorboard does not hang. all_summaries = [] rand_predictions = np.random.choice(predictions, size=10) for ind, prediction in enumerate(rand_predictions): output_summary = image_to_tf_summary_value( prediction["outputs"], tag="%d_output" % ind) input_summary = image_to_tf_summary_value( prediction["inputs"], tag="%d_input" % ind) all_summaries.append(input_summary) all_summaries.append(output_summary) return all_summaries def resize_by_area(img, size): """image resize function used by quite a few image problems.""" return tf.to_int64( tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA)) def make_multiscale(image, resolutions, resize_method=tf.image.ResizeMethod.BICUBIC, num_channels=3): """Returns list of scaled images, one for each resolution. Args: image: Tensor of shape [height, height, num_channels]. resolutions: List of heights that image's height is resized to. resize_method: tf.image.ResizeMethod. num_channels: Number of channels in image. Returns: List of Tensors, one for each resolution with shape given by [resolutions[i], resolutions[i], num_channels]. """ scaled_images = [] for height in resolutions: scaled_image = tf.image.resize_images( image, size=[height, height], # assuming that height = width method=resize_method) scaled_image = tf.to_int64(scaled_image) scaled_image.set_shape([height, height, num_channels]) scaled_images.append(scaled_image) return scaled_images def make_multiscale_dilated(image, resolutions, num_channels=3): """Returns list of scaled images, one for each resolution. Resizes by skipping every nth pixel. Args: image: Tensor of shape [height, height, num_channels]. resolutions: List of heights that image's height is resized to. The function assumes VALID padding, so the original image's height must be divisible by each resolution's height to return the exact resolution size. num_channels: Number of channels in image. Returns: List of Tensors, one for each resolution with shape given by [resolutions[i], resolutions[i], num_channels] if resolutions properly divide the original image's height; otherwise shape height and width is up to valid skips. """ image_height = common_layers.shape_list(image)[0] scaled_images = [] for height in resolutions: dilation_rate = image_height // height # assuming height = width scaled_image = image[::dilation_rate, ::dilation_rate] scaled_image = tf.to_int64(scaled_image) scaled_image.set_shape([None, None, num_channels]) scaled_images.append(scaled_image) return scaled_images class ImageProblem(problem.Problem): """Base class for problems with images.""" @property def num_channels(self): """Number of color channels.""" return 3 @property def vocab_size(self): """Number of pixel values.""" return 256 def example_reading_spec(self): data_fields = { "image/encoded": tf.FixedLenFeature((), tf.string), "image/format": tf.FixedLenFeature((), tf.string), } data_items_to_decoders = { "inputs": contrib.slim().tfexample_decoder.Image( image_key="image/encoded", format_key="image/format", channels=self.num_channels), } return data_fields, data_items_to_decoders def preprocess_example(self, example, mode, hparams): if not self._was_reversed: example["inputs"] = tf.image.per_image_standardization(example["inputs"]) return example def eval_metrics(self): eval_metrics = [ metrics.Metrics.ACC, metrics.Metrics.ACC_TOP5, metrics.Metrics.ACC_PER_SEQ, metrics.Metrics.NEG_LOG_PERPLEXITY ] if self._was_reversed: eval_metrics += [metrics.Metrics.IMAGE_SUMMARY] return eval_metrics @property def decode_hooks(self): return [convert_predictions_to_image_summaries] class Image2ClassProblem(ImageProblem): """Base class for image classification problems.""" @property def is_small(self): raise NotImplementedError() @property def num_classes(self): raise NotImplementedError() @property def train_shards(self): raise NotImplementedError() @property def dev_shards(self): return 1 @property def class_labels(self): return ["ID_%d" % i for i in range(self.num_classes)] def feature_encoders(self, data_dir): del data_dir return { "inputs": text_encoder.ImageEncoder(channels=self.num_channels), "targets": text_encoder.ClassLabelEncoder(self.class_labels) } def generator(self, data_dir, tmp_dir, is_training): raise NotImplementedError() def example_reading_spec(self): label_key = "image/class/label" data_fields, data_items_to_decoders = ( super(Image2ClassProblem, self).example_reading_spec()) data_fields[label_key] = tf.FixedLenFeature((1,), tf.int64) data_items_to_decoders["targets"] = contrib.slim().tfexample_decoder.Tensor( label_key) return data_fields, data_items_to_decoders def hparams(self, defaults, unused_model_hparams): p = defaults p.modality = {"inputs": modalities.ModalityType.IMAGE, "targets": modalities.ModalityType.CLASS_LABEL} p.vocab_size = {"inputs": 256, "targets": self.num_classes} p.batch_size_multiplier = 4 if self.is_small else 256 p.loss_multiplier = 3.0 if self.is_small else 1.0 if self._was_reversed: p.loss_multiplier = 1.0 p.input_space_id = problem.SpaceID.IMAGE p.target_space_id = problem.SpaceID.IMAGE_LABEL def generate_data(self, data_dir, tmp_dir, task_id=-1): generator_utils.generate_dataset_and_shuffle( self.generator(data_dir, tmp_dir, True), self.training_filepaths(data_dir, self.train_shards, shuffled=False), self.generator(data_dir, tmp_dir, False), self.dev_filepaths(data_dir, self.dev_shards, shuffled=False)) def encode_images_as_png(images): """Yield images encoded as pngs.""" if tf.executing_eagerly(): for image in images: yield tf.image.encode_png(image).numpy() else: (height, width, channels) = images[0].shape with tf.Graph().as_default(): image_t = tf.placeholder(dtype=tf.uint8, shape=(height, width, channels)) encoded_image_t = tf.image.encode_png(image_t) with tf.Session() as sess: for image in images: enc_string = sess.run(encoded_image_t, feed_dict={image_t: image}) yield enc_string def image_generator(images, labels): """Generator for images that takes image and labels lists and creates pngs. Args: images: list of images given as [width x height x channels] numpy arrays. labels: list of ints, same length as images. Yields: A dictionary representing the images with the following fields: * image/encoded: the string encoding the image as PNG, * image/format: the string "png" representing image format, * image/class/label: an integer representing the label, * image/height: an integer representing the height, * image/width: an integer representing the width. Every field is actually a singleton list of the corresponding type. Raises: ValueError: if images is an empty list. """ if not images: raise ValueError("Must provide some images for the generator.") width, height, _ = images[0].shape for (enc_image, label) in zip(encode_images_as_png(images), labels): yield { "image/encoded": [enc_image], "image/format": ["png"], "image/class/label": [int(label)], "image/height": [height], "image/width": [width] } class Image2TextProblem(ImageProblem): """Base class for image-to-text problems.""" @property def is_character_level(self): raise NotImplementedError() @property def vocab_problem(self): raise NotImplementedError() # Not needed if self.is_character_level. @property def target_space_id(self): raise NotImplementedError() @property def train_shards(self): raise NotImplementedError() @property def dev_shards(self): raise NotImplementedError() def generator(self, data_dir, tmp_dir, is_training): raise NotImplementedError() def example_reading_spec(self): label_key = "image/class/label" data_fields, data_items_to_decoders = ( super(Image2TextProblem, self).example_reading_spec()) data_fields[label_key] = tf.VarLenFeature(tf.int64) data_items_to_decoders["targets"] = contrib.slim().tfexample_decoder.Tensor( label_key) return data_fields, data_items_to_decoders def feature_encoders(self, data_dir): if self.is_character_level: encoder = text_encoder.ByteTextEncoder() else: vocab_filename = os.path.join( data_dir, self.vocab_problem.vocab_filename) encoder = text_encoder.SubwordTextEncoder(vocab_filename) input_encoder = text_encoder.ImageEncoder(channels=self.num_channels) return {"inputs": input_encoder, "targets": encoder} def hparams(self, defaults, unused_model_hparams): p = defaults p.modality = {"inputs": modalities.ModalityType.IMAGE, "targets": modalities.ModalityType.SYMBOL} p.vocab_size = {"inputs": 256, "targets": self._encoders["targets"].vocab_size} p.batch_size_multiplier = 256 p.loss_multiplier = 1.0 p.input_space_id = problem.SpaceID.IMAGE p.target_space_id = self.target_space_id def generate_data(self, data_dir, tmp_dir, task_id=-1): generator_utils.generate_dataset_and_shuffle( self.generator(data_dir, tmp_dir, True), self.training_filepaths(data_dir, self.train_shards, shuffled=False), self.generator(data_dir, tmp_dir, False), self.dev_filepaths(data_dir, self.dev_shards, shuffled=False)) def image_augmentation(images, do_colors=False, crop_size=None): """Image augmentation: cropping, flipping, and color transforms.""" if crop_size is None: crop_size = [299, 299] images = tf.random_crop(images, crop_size + [3]) images = tf.image.random_flip_left_right(images) if do_colors: # More augmentation, but might be slow. images = tf.image.random_brightness(images, max_delta=32. / 255.) images = tf.image.random_saturation(images, lower=0.5, upper=1.5) images = tf.image.random_hue(images, max_delta=0.2) images = tf.image.random_contrast(images, lower=0.5, upper=1.5) return images def cifar_image_augmentation(images): """Image augmentation suitable for CIFAR-10/100. As described in https://arxiv.org/pdf/1608.06993v3.pdf (page 5). Args: images: a Tensor. Returns: Tensor of the same shape as images. """ images = tf.image.resize_image_with_crop_or_pad(images, 40, 40) images = tf.random_crop(images, [32, 32, 3]) images = tf.image.random_flip_left_right(images) return images def random_shift(image, wsr=0.1, hsr=0.1): """Apply random horizontal and vertical shift to images. This is the default data-augmentation strategy used on CIFAR in Glow. Args: image: a 3-D Tensor wsr: Width shift range, as a float fraction of the width. hsr: Height shift range, as a float fraction of the width. Returns: images: images translated by the provided wsr and hsr. """ height, width, _ = common_layers.shape_list(image) width_range, height_range = wsr*width, hsr*height height_translations = tf.random_uniform((1,), -height_range, height_range) width_translations = tf.random_uniform((1,), -width_range, width_range) translations = tf.concat((height_translations, width_translations), axis=0) return contrib.image().translate(image, translations=translations)
Java
/// <reference path='fourslash.ts' /> // @BaselineFile: bpSpan_interface.baseline // @Filename: bpSpan_interface.ts ////interface I { //// property: string; //// method(): number; //// (a: string): string; //// new (a: string): I; //// [a: number]: number; ////} ////module m { //// interface I1 { //// property: string; //// method(): number; //// (a: string): string; //// new (a: string): I; //// [a: number]: number; //// } //// export interface I2 { //// property: string; //// method(): number; //// (a: string): string; //// new (a: string): I; //// [a: number]: number; //// } ////} verify.baselineCurrentFileBreakpointLocations();
Java
package main.java; public class SelectionSort9 { public static <T extends Comparable<T>> void sort(final T[] a) { for (int i = 0; i < a.length - 1; i++) { int min = i; for (int j = i + 1; j < a.length; j++) { if (a[j].compareTo(a[min]) < 0) { min = j; } } if (i != min) { final T tmp = a[min]; a[min] = a[i]; a[i] = tmp; } } } }
Java
package com.sequenceiq.environment.api.v1.environment.model.response; import java.io.Serializable; import com.sequenceiq.environment.api.doc.environment.EnvironmentModelDescription; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel("EnvironmentAuthenticationV1Response") public class EnvironmentAuthenticationResponse implements Serializable { @ApiModelProperty(EnvironmentModelDescription.PUBLIC_KEY) private String publicKey; @ApiModelProperty(EnvironmentModelDescription.PUBLIC_KEY_ID) private String publicKeyId; @ApiModelProperty(EnvironmentModelDescription.LOGIN_USER_NAME) private String loginUserName; public String getPublicKey() { return publicKey; } public void setPublicKey(String publicKey) { this.publicKey = publicKey; } public String getPublicKeyId() { return publicKeyId; } public void setPublicKeyId(String publicKeyId) { this.publicKeyId = publicKeyId; } public String getLoginUserName() { return loginUserName; } public void setLoginUserName(String loginUserName) { this.loginUserName = loginUserName; } public static Builder builder() { return new Builder(); } @Override public String toString() { return "EnvironmentAuthenticationResponse{" + "publicKey='" + publicKey + '\'' + ", publicKeyId='" + publicKeyId + '\'' + ", loginUserName='" + loginUserName + '\'' + '}'; } public static class Builder { private String publicKey; private String publicKeyId; private String loginUserName; private Builder() { } public Builder withPublicKey(String publicKey) { this.publicKey = publicKey; return this; } public Builder withPublicKeyId(String publicKeyId) { this.publicKeyId = publicKeyId; return this; } public Builder withLoginUserName(String loginUserName) { this.loginUserName = loginUserName; return this; } public EnvironmentAuthenticationResponse build() { EnvironmentAuthenticationResponse response = new EnvironmentAuthenticationResponse(); response.setLoginUserName(loginUserName); response.setPublicKey(publicKey); response.setPublicKeyId(publicKeyId); return response; } } }
Java
/* * This file is part of "lunisolar-magma". * * (C) Copyright 2014-2022 Lunisolar (http://lunisolar.eu/). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.lunisolar.magma.func.predicate; import javax.annotation.Nonnull; // NOSONAR import javax.annotation.Nullable; // NOSONAR import javax.annotation.concurrent.NotThreadSafe; // NOSONAR import java.util.Comparator; // NOSONAR import java.util.Objects; // NOSONAR import eu.lunisolar.magma.basics.*; //NOSONAR import eu.lunisolar.magma.basics.builder.*; // NOSONAR import eu.lunisolar.magma.basics.exceptions.*; // NOSONAR import eu.lunisolar.magma.basics.meta.*; // NOSONAR import eu.lunisolar.magma.basics.meta.aType.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR import eu.lunisolar.magma.func.IA; import eu.lunisolar.magma.func.SA; import eu.lunisolar.magma.func.*; // NOSONAR import eu.lunisolar.magma.func.tuple.*; // NOSONAR import java.util.concurrent.*; // NOSONAR import java.util.function.*; // NOSONAR import java.util.*; // NOSONAR import java.lang.reflect.*; // NOSONAR import eu.lunisolar.magma.func.action.*; // NOSONAR import eu.lunisolar.magma.func.consumer.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR import eu.lunisolar.magma.func.function.*; // NOSONAR import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR import eu.lunisolar.magma.func.function.from.*; // NOSONAR import eu.lunisolar.magma.func.function.to.*; // NOSONAR import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR import eu.lunisolar.magma.func.predicate.*; // NOSONAR import eu.lunisolar.magma.func.supplier.*; // NOSONAR /** * Non-throwing functional interface (lambda) LBiObjLongPredicate for Java 8. * * Type: predicate * * Domain (lvl: 3): T1 a1,T2 a2,long a3 * * Co-domain: boolean * */ @FunctionalInterface @SuppressWarnings("UnusedDeclaration") public interface LBiObjLongPredicate<T1, T2> extends MetaPredicate, MetaInterface.NonThrowing, Codomain<aBool>, Domain3<a<T1>, a<T2>, aLong> { // NOSONAR String DESCRIPTION = "LBiObjLongPredicate: boolean test(T1 a1,T2 a2,long a3)"; // boolean test(T1 a1,T2 a2,long a3) ; default boolean test(T1 a1, T2 a2, long a3) { // return nestingTest(a1,a2,a3); try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call test(T1 a1,T2 a2,long a3) */ boolean testX(T1 a1, T2 a2, long a3) throws Throwable; default boolean tupleTest(LBiObjLongTriple<T1, T2> args) { return test(args.first(), args.second(), args.third()); } /** Function call that handles exceptions according to the instructions. */ default boolean handlingTest(T1 a1, T2 a2, long a3, HandlingInstructions<Throwable, RuntimeException> handling) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handler.handleOrNest(e, handling); } } default LBiObjLongPredicate<T1, T2> handling(HandlingInstructions<Throwable, RuntimeException> handling) { return (a1, a2, a3) -> handlingTest(a1, a2, a3, handling); } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage); } } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage, param1); } } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage, param1, param2); } } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage, param1, param2, param3); } } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage); } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage, param1); } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage, param1, param1); } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage, param1, param2, param3); } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWF<RuntimeException> factory) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory); } } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWF<RuntimeException> factory) { return (a1, a2, a3) -> test(a1, a2, a3, factory); } default boolean testThen(T1 a1, T2 a2, long a3, @Nonnull LPredicate<Throwable> handler) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR Handling.handleErrors(e); return handler.test(e); } } default LBiObjLongPredicate<T1, T2> tryingThen(@Nonnull LPredicate<Throwable> handler) { return (a1, a2, a3) -> testThen(a1, a2, a3, handler); } /** Function call that handles exceptions by always nesting checked exceptions and propagating the others as is. */ default boolean nestingTest(T1 a1, T2 a2, long a3) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** Function call that handles exceptions by always propagating them as is, even when they are undeclared checked ones. */ default boolean shovingTest(T1 a1, T2 a2, long a3) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.shoveIt(e); } } static <T1, T2> boolean shovingTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.shovingTest(a1, a2, a3); } static <T1, T2> boolean handlingTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, HandlingInstructions<Throwable, RuntimeException> handling) { // <- Null.nonNullArg(func, "func"); return func.handlingTest(a1, a2, a3, handling); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.nestingTest(a1, a2, a3); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage, param1); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage, param1, param2); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage, param1, param2, param3); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWF<RuntimeException> factory) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory); } static <T1, T2> boolean tryTestThen(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull LPredicate<Throwable> handler) { Null.nonNullArg(func, "func"); return func.testThen(a1, a2, a3, handler); } default boolean failSafeTest(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<T1, T2> failSafe) { try { return test(a1, a2, a3); } catch (Throwable e) { // NOSONAR Handling.handleErrors(e); return failSafe.test(a1, a2, a3); } } static <T1, T2> boolean failSafeTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull LBiObjLongPredicate<T1, T2> failSafe) { Null.nonNullArg(failSafe, "failSafe"); if (func == null) { return failSafe.test(a1, a2, a3); } else { return func.failSafeTest(a1, a2, a3, failSafe); } } static <T1, T2> LBiObjLongPredicate<T1, T2> failSafe(LBiObjLongPredicate<T1, T2> func, @Nonnull LBiObjLongPredicate<T1, T2> failSafe) { Null.nonNullArg(failSafe, "failSafe"); return (a1, a2, a3) -> failSafeTest(a1, a2, a3, func, failSafe); } default boolean doIf(T1 a1, T2 a2, long a3, LAction action) { Null.nonNullArg(action, "action"); if (test(a1, a2, a3)) { action.execute(); return true; } else { return false; } } static <T1, T2> boolean doIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<T1, T2> predicate, @Nonnull LAction action) { Null.nonNullArg(predicate, "predicate"); return predicate.doIf(a1, a2, a3, action); } static <T1, T2> boolean doIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<T1, T2> predicate, @Nonnull LBiObjLongConsumer<? super T1, ? super T2> consumer) { Null.nonNullArg(predicate, "predicate"); return predicate.doIf(a1, a2, a3, consumer); } default boolean doIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongConsumer<? super T1, ? super T2> consumer) { Null.nonNullArg(consumer, "consumer"); if (test(a1, a2, a3)) { consumer.accept(a1, a2, a3); return true; } else { return false; } } /** Just to mirror the method: Ensures the result is not null */ default boolean nonNullTest(T1 a1, T2 a2, long a3) { return test(a1, a2, a3); } /** For convenience, where "test()" makes things more confusing than "applyAsBoolean()". */ default boolean doApplyAsBoolean(T1 a1, T2 a2, long a3) { return test(a1, a2, a3); } /** Returns description of the functional interface. */ @Nonnull default String functionalInterfaceDescription() { return LBiObjLongPredicate.DESCRIPTION; } /** From-To. Intended to be used with non-capturing lambda. */ public static <T1, T2> void fromTo(long min_a3, long max_a3, T1 a1, T2 a2, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); if (min_a3 <= max_a3) { for (long a3 = min_a3; a3 <= max_a3; a3++) { func.test(a1, a2, a3); } } else { for (long a3 = min_a3; a3 >= max_a3; a3--) { func.test(a1, a2, a3); } } } /** From-To. Intended to be used with non-capturing lambda. */ public static <T1, T2> void fromTill(long min_a3, long max_a3, T1 a1, T2 a2, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); if (min_a3 <= max_a3) { for (long a3 = min_a3; a3 < max_a3; a3++) { func.test(a1, a2, a3); } } else { for (long a3 = min_a3; a3 > max_a3; a3--) { func.test(a1, a2, a3); } } } /** From-To. Intended to be used with non-capturing lambda. */ public static <T1, T2> void times(long max_a3, T1 a1, T2 a2, @Nonnull LBiObjLongPredicate<T1, T2> func) { if (max_a3 < 0) return; fromTill(0, max_a3, a1, a2, func); } /** Extract and apply function. */ public static <M, K, V, T2> boolean from(@Nonnull M container, LBiFunction<M, K, V> extractor, K key, T2 a2, long a3, @Nonnull LBiObjLongPredicate<V, T2> function) { Null.nonNullArg(container, "container"); Null.nonNullArg(function, "function"); V value = extractor.apply(container, key); if (value != null) { return function.test(value, a2, a3); } return false; } default LObjLongPredicate<T2> lShrink(@Nonnull LObjLongFunction<T2, T1> left) { Null.nonNullArg(left, "left"); return (a2, a3) -> test(left.apply(a2, a3), a2, a3); } default LObjLongPredicate<T2> lShrink_(T1 a1) { return (a2, a3) -> test(a1, a2, a3); } public static <T2, T1> LObjLongPredicate<T2> lShrunken(@Nonnull LObjLongFunction<T2, T1> left, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(left, "left"); Null.nonNullArg(func, "func"); return func.lShrink(left); } public static <T2, T1> LObjLongPredicate<T2> lShrunken_(T1 a1, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.lShrink_(a1); } default LBiPredicate<T1, T2> rShrink(@Nonnull LToLongBiFunction<T1, T2> right) { Null.nonNullArg(right, "right"); return (a1, a2) -> test(a1, a2, right.applyAsLong(a1, a2)); } default LBiPredicate<T1, T2> rShrink_(long a3) { return (a1, a2) -> test(a1, a2, a3); } public static <T1, T2> LBiPredicate<T1, T2> rShrunken(@Nonnull LToLongBiFunction<T1, T2> right, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(right, "right"); Null.nonNullArg(func, "func"); return func.rShrink(right); } public static <T1, T2> LBiPredicate<T1, T2> rShrunken_(long a3, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.rShrink_(a3); } /** */ public static <T1, T2> LBiObjLongPredicate<T1, T2> uncurry(@Nonnull LFunction<T1, LFunction<T2, LLongPredicate>> func) { Null.nonNullArg(func, "func"); return (T1 a1, T2 a2, long a3) -> func.apply(a1).apply(a2).test(a3); } /** Cast that removes generics. */ default LBiObjLongPredicate untyped() { return this; } /** Cast that replace generics. */ default <V2, V3> LBiObjLongPredicate<V2, V3> cast() { return untyped(); } /** Cast that replace generics. */ public static <V2, V3> LBiObjLongPredicate<V2, V3> cast(LBiObjLongPredicate<?, ?> function) { return (LBiObjLongPredicate) function; } /** Change function to consumer that ignores output. */ default LBiObjLongConsumer<T1, T2> toConsumer() { return this::test; } /** Calls domain consumer before main function. */ default LBiObjLongPredicate<T1, T2> beforeDo(@Nonnull LBiObjLongConsumer<T1, T2> before) { Null.nonNullArg(before, "before"); return (T1 a1, T2 a2, long a3) -> { before.accept(a1, a2, a3); return test(a1, a2, a3); }; } /** Calls codomain consumer after main function. */ default LBiObjLongPredicate<T1, T2> afterDo(@Nonnull LBoolConsumer after) { Null.nonNullArg(after, "after"); return (T1 a1, T2 a2, long a3) -> { final boolean retval = test(a1, a2, a3); after.accept(retval); return retval; }; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (!pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (!pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(msg, a1, a2, a3) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2, param3) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(msg, a1, a2, a3) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2, param3) + ' ' + m); } return a1; } /** Captures arguments but delays the evaluation. */ default LBoolSupplier capture(T1 a1, T2 a2, long a3) { return () -> this.test(a1, a2, a3); } /** Creates function that always returns the same value. */ static <T1, T2> LBiObjLongPredicate<T1, T2> constant(boolean r) { return (a1, a2, a3) -> r; } /** Captures single parameter function into this interface where only 1st parameter will be used. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> test1st(@Nonnull LPredicate<T1> func) { return (a1, a2, a3) -> func.test(a1); } /** Captures single parameter function into this interface where only 2nd parameter will be used. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> test2nd(@Nonnull LPredicate<T2> func) { return (a1, a2, a3) -> func.test(a2); } /** Captures single parameter function into this interface where only 3rd parameter will be used. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> test3rd(@Nonnull LLongPredicate func) { return (a1, a2, a3) -> func.test(a3); } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPred(final @Nonnull LBiObjLongPredicate<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** A completely inconvenient method in case lambda expression and generic arguments are ambiguous for the compiler. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPred(@Nullable Class<T1> c1, @Nullable Class<T2> c2, final @Nonnull LBiObjLongPredicate<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } final class S<T1, T2> implements LBiObjLongPredicate<T1, T2> { private LBiObjLongPredicate<T1, T2> target = null; @Override public boolean testX(T1 a1, T2 a2, long a3) throws Throwable { return target.testX(a1, a2, a3); } } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> recursive(final @Nonnull LFunction<LBiObjLongPredicate<T1, T2>, LBiObjLongPredicate<T1, T2>> selfLambda) { final S<T1, T2> single = new S(); LBiObjLongPredicate<T1, T2> func = selfLambda.apply(single); single.target = func; return func; } public static <T1, T2> M<T1, T2> mementoOf(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> function) { var initialValue = function.test(a1, a2, a3); return initializedMementoOf(initialValue, function); } public static <T1, T2> M<T1, T2> initializedMementoOf(boolean initialValue, LBiObjLongPredicate<T1, T2> function) { return memento(initialValue, initialValue, function, (m, x1, x2) -> x2); } public static <T1, T2> M<T1, T2> deltaOf(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> function, LLogicalBinaryOperator deltaFunction) { var initialValue = function.test(a1, a2, a3); return initializedDeltaOf(initialValue, function, deltaFunction); } public static <T1, T2> M<T1, T2> deltaOf(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> function) { var initialValue = function.test(a1, a2, a3); return initializedDeltaOf(initialValue, function, (x1, x2) -> x1 != x2); } public static <T1, T2> M<T1, T2> initializedDeltaOf(boolean initialValue, LBiObjLongPredicate<T1, T2> function, LLogicalBinaryOperator deltaFunction) { return memento(initialValue, deltaFunction.apply(initialValue, initialValue), function, (m, x1, x2) -> deltaFunction.apply(x1, x2)); } public static <T1, T2> M<T1, T2> memento(boolean initialBaseValue, boolean initialValue, LBiObjLongPredicate<T1, T2> baseFunction, LLogicalTernaryOperator mementoFunction) { return new M(initialBaseValue, initialValue, baseFunction, mementoFunction); } /** * Implementation that allows to create derivative functions (do not confuse it with math concepts). Very short name is intended to be used with parent (LBiObjLongPredicate.M) */ @NotThreadSafe final class M<T1, T2> implements LBiObjLongPredicate<T1, T2> { private final LBiObjLongPredicate<T1, T2> baseFunction; private boolean lastBaseValue; private boolean lastValue; private final LLogicalTernaryOperator mementoFunction; private M(boolean lastBaseValue, boolean lastValue, LBiObjLongPredicate<T1, T2> baseFunction, LLogicalTernaryOperator mementoFunction) { this.baseFunction = baseFunction; this.lastBaseValue = lastBaseValue; this.lastValue = lastValue; this.mementoFunction = mementoFunction; } @Override public boolean testX(T1 a1, T2 a2, long a3) throws Throwable { boolean x1 = lastBaseValue; boolean x2 = lastBaseValue = baseFunction.testX(a1, a2, a3); return lastValue = mementoFunction.apply(lastValue, x1, x2); } public boolean lastValue() { return lastValue; }; public boolean lastBaseValue() { return lastBaseValue; }; } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPredThrowing(final @Nonnull ExF<Throwable> exF) { Null.nonNullArg(exF, "exF"); return (a1, a2, a3) -> { throw exF.produce(); }; } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPredThrowing(final String message, final @Nonnull ExMF<Throwable> exF) { Null.nonNullArg(exF, "exF"); return (a1, a2, a3) -> { throw exF.produce(message); }; } // <editor-fold desc="wrap variants"> /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T1, T2> LBiObjLongPredicate.LObj0Long2Obj1Pred<T1, T2> obj0Long2Obj1Pred(final @Nonnull LBiObjLongPredicate.LObj0Long2Obj1Pred<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T2, T1> LBiObjLongPredicate.LObj1Obj0Long2Pred<T2, T1> obj1Obj0Long2Pred(final @Nonnull LBiObjLongPredicate.LObj1Obj0Long2Pred<T2, T1> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T2, T1> LBiObjLongPredicate.LObj1Long2Obj0Pred<T2, T1> obj1Long2Obj0Pred(final @Nonnull LBiObjLongPredicate.LObj1Long2Obj0Pred<T2, T1> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T1, T2> LBiObjLongPredicate.LLong2Obj0Obj1Pred<T1, T2> long2Obj0Obj1Pred(final @Nonnull LBiObjLongPredicate.LLong2Obj0Obj1Pred<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T2, T1> LBiObjLongPredicate.LLong2Obj1Obj0Pred<T2, T1> long2Obj1Obj0Pred(final @Nonnull LBiObjLongPredicate.LLong2Obj1Obj0Pred<T2, T1> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } // </editor-fold> static <T1, T2> boolean call(T1 a1, T2 a2, long a3, final @Nonnull LBiObjLongPredicate<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda.test(a1, a2, a3); } // <editor-fold desc="wrap"> // </editor-fold> // <editor-fold desc="predicate"> /** * Returns a predicate that represents the logical negation of this predicate. * * @see {@link java.util.function.Predicate#negate} */ @Nonnull default LBiObjLongPredicate<T1, T2> negate() { return (a1, a2, a3) -> !test(a1, a2, a3); } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> not(@Nonnull LBiObjLongPredicate<T1, T2> pred) { Null.nonNullArg(pred, "pred"); return pred.negate(); } /** * Returns a predicate that represents the logical AND of evaluation of this predicate and the argument one. * @see {@link java.util.function.Predicate#and()} */ @Nonnull default LBiObjLongPredicate<T1, T2> and(@Nonnull LBiObjLongPredicate<? super T1, ? super T2> other) { Null.nonNullArg(other, "other"); return (a1, a2, a3) -> test(a1, a2, a3) && other.test(a1, a2, a3); } @Nonnull public static <T1, T2> LBiObjLongPredicate<T1, T2> and(@Nonnull LBiObjLongPredicate<? super T1, ? super T2>... predicates) { Null.nonNullArg(predicates, "predicates"); return (a1, a2, a3) -> { for (LBiObjLongPredicate<? super T1, ? super T2> p : predicates) { if (!p.test(a1, a2, a3)) { return false; } } return true; }; } /** * Returns a predicate that represents the logical OR of evaluation of this predicate and the argument one. * @see {@link java.util.function.Predicate#or} */ @Nonnull default LBiObjLongPredicate<T1, T2> or(@Nonnull LBiObjLongPredicate<? super T1, ? super T2> other) { Null.nonNullArg(other, "other"); return (a1, a2, a3) -> test(a1, a2, a3) || other.test(a1, a2, a3); } @Nonnull public static <T1, T2> LBiObjLongPredicate<T1, T2> or(@Nonnull LBiObjLongPredicate<? super T1, ? super T2>... predicates) { Null.nonNullArg(predicates, "predicates"); return (a1, a2, a3) -> { for (LBiObjLongPredicate<? super T1, ? super T2> p : predicates) { if (p.test(a1, a2, a3)) { return true; } } return false; }; } /** * Returns a predicate that represents the logical XOR of evaluation of this predicate and the argument one. * @see {@link java.util.function.Predicate#or} */ @Nonnull default LBiObjLongPredicate<T1, T2> xor(@Nonnull LBiObjLongPredicate<? super T1, ? super T2> other) { Null.nonNullArg(other, "other"); return (a1, a2, a3) -> test(a1, a2, a3) ^ other.test(a1, a2, a3); } /** * Creates predicate that evaluates if an object is equal with the argument one. * @see {@link java.util.function.Predicate#isEqual() */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> isEqual(T1 v1, T2 v2, long v3) { return (a1, a2, a3) -> (a1 == null ? v1 == null : a1.equals(v1)) && (a2 == null ? v2 == null : a2.equals(v2)) && (a3 == v3); } // </editor-fold> // <editor-fold desc="compose (functional)"> /** Allows to manipulate the domain of the function. */ @Nonnull default <V1, V2> LBiObjLongPredicate<V1, V2> compose(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LLongUnaryOperator before3) { Null.nonNullArg(before1, "before1"); Null.nonNullArg(before2, "before2"); Null.nonNullArg(before3, "before3"); return (v1, v2, v3) -> this.test(before1.apply(v1), before2.apply(v2), before3.applyAsLong(v3)); } public static <V1, V2, T1, T2> LBiObjLongPredicate<V1, V2> composed(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LLongUnaryOperator before3, LBiObjLongPredicate<T1, T2> after) { return after.compose(before1, before2, before3); } /** Allows to manipulate the domain of the function. */ @Nonnull default <V1, V2, V3> LTriPredicate<V1, V2, V3> biObjLongPredCompose(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LToLongFunction<? super V3> before3) { Null.nonNullArg(before1, "before1"); Null.nonNullArg(before2, "before2"); Null.nonNullArg(before3, "before3"); return (v1, v2, v3) -> this.test(before1.apply(v1), before2.apply(v2), before3.applyAsLong(v3)); } public static <V1, V2, V3, T1, T2> LTriPredicate<V1, V2, V3> composed(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LToLongFunction<? super V3> before3, LBiObjLongPredicate<T1, T2> after) { return after.biObjLongPredCompose(before1, before2, before3); } // </editor-fold> // <editor-fold desc="then (functional)"> /** Combines two functions together in a order. */ @Nonnull default <V> LBiObjLongFunction<T1, T2, V> boolToBiObjLongFunc(@Nonnull LBoolFunction<? extends V> after) { Null.nonNullArg(after, "after"); return (a1, a2, a3) -> after.apply(this.test(a1, a2, a3)); } /** Combines two functions together in a order. */ @Nonnull default LBiObjLongPredicate<T1, T2> boolToBiObjLongPred(@Nonnull LLogicalOperator after) { Null.nonNullArg(after, "after"); return (a1, a2, a3) -> after.apply(this.test(a1, a2, a3)); } // </editor-fold> // <editor-fold desc="variant conversions"> // </editor-fold> // <editor-fold desc="interface variants"> /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LObj0Long2Obj1Pred<T1, T2> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call test(T1 a1,T2 a2,long a3) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testObj0Long2Obj1(a1, a3, a2); } // boolean testObj0Long2Obj1(T1 a1,long a3,T2 a2) ; default boolean testObj0Long2Obj1(T1 a1, long a3, T2 a2) { // return nestingTestObj0Long2Obj1(a1,a3,a2); try { return this.testObj0Long2Obj1X(a1, a3, a2); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testObj0Long2Obj1(T1 a1,long a3,T2 a2) */ boolean testObj0Long2Obj1X(T1 a1, long a3, T2 a2) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LObj1Obj0Long2Pred<T2, T1> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testObj0Long2Obj1(T1 a1,long a3,T2 a2) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testObj1Obj0Long2(a2, a1, a3); } // boolean testObj1Obj0Long2(T2 a2,T1 a1,long a3) ; default boolean testObj1Obj0Long2(T2 a2, T1 a1, long a3) { // return nestingTestObj1Obj0Long2(a2,a1,a3); try { return this.testObj1Obj0Long2X(a2, a1, a3); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testObj1Obj0Long2(T2 a2,T1 a1,long a3) */ boolean testObj1Obj0Long2X(T2 a2, T1 a1, long a3) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LObj1Long2Obj0Pred<T2, T1> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testObj1Obj0Long2(T2 a2,T1 a1,long a3) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testObj1Long2Obj0(a2, a3, a1); } // boolean testObj1Long2Obj0(T2 a2,long a3,T1 a1) ; default boolean testObj1Long2Obj0(T2 a2, long a3, T1 a1) { // return nestingTestObj1Long2Obj0(a2,a3,a1); try { return this.testObj1Long2Obj0X(a2, a3, a1); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testObj1Long2Obj0(T2 a2,long a3,T1 a1) */ boolean testObj1Long2Obj0X(T2 a2, long a3, T1 a1) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LLong2Obj0Obj1Pred<T1, T2> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testObj1Long2Obj0(T2 a2,long a3,T1 a1) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testLong2Obj0Obj1(a3, a1, a2); } // boolean testLong2Obj0Obj1(long a3,T1 a1,T2 a2) ; default boolean testLong2Obj0Obj1(long a3, T1 a1, T2 a2) { // return nestingTestLong2Obj0Obj1(a3,a1,a2); try { return this.testLong2Obj0Obj1X(a3, a1, a2); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testLong2Obj0Obj1(long a3,T1 a1,T2 a2) */ boolean testLong2Obj0Obj1X(long a3, T1 a1, T2 a2) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LLong2Obj1Obj0Pred<T2, T1> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testLong2Obj0Obj1(long a3,T1 a1,T2 a2) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testLong2Obj1Obj0(a3, a2, a1); } // boolean testLong2Obj1Obj0(long a3,T2 a2,T1 a1) ; default boolean testLong2Obj1Obj0(long a3, T2 a2, T1 a1) { // return nestingTestLong2Obj1Obj0(a3,a2,a1); try { return this.testLong2Obj1Obj0X(a3, a2, a1); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testLong2Obj1Obj0(long a3,T2 a2,T1 a1) */ boolean testLong2Obj1Obj0X(long a3, T2 a2, T1 a1) throws Throwable; } // </editor-fold> // >>> LBiObjLongPredicate<T1,T2> /** Returns TRUE. */ public static <T1, T2> boolean alwaysTrue(T1 a1, T2 a2, long a3) { return true; } /** Returns FALSE. */ public static <T1, T2> boolean alwaysFalse(T1 a1, T2 a2, long a3) { return false; } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, C3> void filterForEach(IndexedRead<C1, a<T1>> ia1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); size = Integer.min(size, ia2.size(source2)); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); size = Integer.min(size, ia3.size(source3)); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; for (; i < size; i++) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = oiFunc2.apply(source2, i); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, I1, C2, C3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); int size = ia2.size(source2); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); size = Integer.min(size, ia3.size(source3)); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; while (testFunc1.test(iterator1) && i < size) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = oiFunc2.apply(source2, i); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, I2, C3> void filterIterate(IndexedRead<C1, a<T1>> ia1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); size = Integer.min(size, ia3.size(source3)); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; while (i < size && testFunc2.test(iterator2)) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = nextFunc2.apply(iterator2); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, I1, C2, I2, C3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); int size = ia3.size(source3); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; while (testFunc1.test(iterator1) && testFunc2.test(iterator2) && i < size) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = nextFunc2.apply(iterator2); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, C3, I3> void filterIterate(IndexedRead<C1, a<T1>> ia1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); size = Integer.min(size, ia2.size(source2)); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); int i = 0; while (i < size && testFunc3.test(iterator3)) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = oiFunc2.apply(source2, i); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, I1, C2, C3, I3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); int size = ia2.size(source2); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); int i = 0; while (testFunc1.test(iterator1) && i < size && testFunc3.test(iterator3)) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = oiFunc2.apply(source2, i); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, I2, C3, I3> void filterIterate(IndexedRead<C1, a<T1>> ia1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); int i = 0; while (i < size && testFunc2.test(iterator2) && testFunc3.test(iterator3)) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = nextFunc2.apply(iterator2); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method depends highly on the arguments. */ default <C1, I1, C2, I2, C3, I3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); while (testFunc1.test(iterator1) && testFunc2.test(iterator2) && testFunc3.test(iterator3)) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = nextFunc2.apply(iterator2); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); } } }
Java
/* * Copyright 2012-2018 Christophe Friederich * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.devacfr.maven.skins.reflow.context; import static java.util.Objects.requireNonNull; import java.util.List; import java.util.Map; import java.util.Optional; import javax.annotation.Nonnull; import org.apache.commons.lang.builder.ToStringBuilder; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.devacfr.maven.skins.reflow.HtmlTool; import org.devacfr.maven.skins.reflow.ISkinConfig; import org.devacfr.maven.skins.reflow.model.Component; import org.devacfr.maven.skins.reflow.model.Footer; import org.devacfr.maven.skins.reflow.model.NavSideMenu; import org.devacfr.maven.skins.reflow.model.Navbar; import org.devacfr.maven.skins.reflow.model.ScrollTop; import org.devacfr.maven.skins.reflow.model.SideNavMenuItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; /** * The base class of all contexts depending type of page. * * @author Christophe Friederich * @since 2.0 * @param <T> * type of inherrit context object. */ public abstract class Context<T extends Context<?>> extends Component { /** map containing the equivalence of font awesome characters with image found in report pages. */ private static final Map<String, String> ICON_REPLACEMENTS = ImmutableMap.<String, String> builder() .put("img[src$=images/add.gif]", "<i class=\"fas fa-plus\"></i>") .put("img[src$=images/remove.gif]", "<i class=\"fas fa-minus\"></i>") .put("img[src$=images/fix.gif]", "<i class=\"fas fa-wrench\"></i>") .put("img[src$=images/update.gif]", "<i class=\"fas fa-redo\"></i>") .put("img[src$=images/icon_help_sml.gif]", "<i class=\"fas fa-question\"></i>") .put("img[src$=images/icon_success_sml.gif]", "<i class=\"fas fa-check-circle\"></i>") .put("img[src$=images/icon_warning_sml.gif]", "<i class=\"fas fa-exclamation-triangle\"></i>") .put("img[src$=images/icon_error_sml.gif]", "<i class=\"fas fa-exclamation-circle\"></i>") .put("img[src$=images/icon_info_sml.gif]", "<i class=\"fas fa-info\"></i>") .build(); /** */ private static final Logger LOGGER = LoggerFactory.getLogger(Context.class); /** */ private ContextType type; /** */ private final Navbar navbar; /** */ private final Footer footer; /** */ private final ScrollTop scrollTop; /** * Build a context depending of current type of page. * * @param config * a config (can not be {@code null}). * @return Returns a new instance of {@link Context} depending of current page. */ @Nonnull public static Context<?> buildContext(@Nonnull final ISkinConfig config) { requireNonNull(config); ContextType type = ContextType.page; final List<SideNavMenuItem> allSideNaveMenuItems = NavSideMenu.findAllSideNavMenuItems(config); if (LOGGER.isTraceEnabled()) { LOGGER.trace("findAllSideNavMenuItems: " + allSideNaveMenuItems); } final Xpp3Dom pageProperties = config.getPageProperties(); final String fileId = config.getFileId(); if (pageProperties != null) { if (pageProperties.getAttribute("type") != null) { type = ContextType.valueOf(pageProperties.getAttribute("type")); } // frame type whether page associates to document page if (allSideNaveMenuItems.stream().filter(item -> fileId.equals(item.getSlugName())).count() > 0) { type = ContextType.frame; } } // if (type== null) { // type = ContextType.page; // } Context<?> context = null; switch (type) { case doc: context = new DocumentContext(config); break; case frame: // search the parent document page final Optional<SideNavMenuItem> menuItem = allSideNaveMenuItems.stream() .filter(item -> fileId.equals(item.getSlugName())) .findFirst(); final SideNavMenuItem item = menuItem.get(); final String documentParent = item.getParent(); context = new FrameContext(config, documentParent); break; case body: context = new BodyContext(config); break; case page: default: context = new PageContext(config); break; } return context; } /** * Default constructor. * * @param config * a config (can not be {@code null}). * @param type * the type of context (can not be {@code null}). */ public Context(@Nonnull final ISkinConfig config, @Nonnull final ContextType type) { requireNonNull(config); this.withType(requireNonNull(type)); this.navbar = new Navbar(config); this.scrollTop = new ScrollTop(config); this.footer = new Footer(config); this.initialize(config); // the ordering is important for execute preRender method this.addChildren(this.navbar, this.scrollTop, this.footer); } /** * Allows to initialize the context. * @param config * a config (can not be {@code null}). */ protected void initialize(@Nonnull final ISkinConfig config) { // enable AnchorJS if(!config.not("anchorJS")) { this.addCssOptions("anchorjs-enabled"); } } /** * Allows to execute action before rendering of component. * * @param skinConfig * a config (can <b>not</b> be {@code null}). * @return Returns the {@link String} representing the transformed body content. * @since 2.1 */ public String preRender(@Nonnull final ISkinConfig skinConfig) { return onPreRender(skinConfig, getBodyContent(skinConfig)); } @Override protected String onPreRender(final ISkinConfig skinConfig, final String bodyContent) { final HtmlTool htmlTool = getHtmlTool(skinConfig); String content = bodyContent; if (!skinConfig.not("imgLightbox")) { // lightbox is enabled by default, so check for false and negate content = htmlTool.setAttr(content, "a[href$=jpg], a[href$=JPG], a[href$=jpeg], a[href$=JPEG], " + "a[href$=png], a[href$=gif],a[href$=bmp]:has(img)", "data-lightbox", "page"); } if (!skinConfig.not("imgLightbox")) { // lightbox is enabled by default, so check for false and negate content = htmlTool.setAttr(content, "a[href$=jpg], a[href$=JPG], a[href$=jpeg], a[href$=JPEG], " + "a[href$=png], a[href$=gif], a[href$=bmp]:has(img)", "data-lightbox", "page"); } if (!skinConfig.not("html5Anchor")) { // HTML5-style anchors are enabled by default, so check for false and negate content = htmlTool.headingAnchorToId(content); } if (!skinConfig.not("bootstrapCss")) { // Bootstrap CSS class conversion is enabled by default, so check for false and negate content = htmlTool .addClass(content, "table.bodyTable", Lists.newArrayList("table", "table-striped", "table-hover")); // image is responsive by default content = htmlTool.addClass(content, "img", Lists.newArrayList("img-fluid")); content = htmlTool.fixTableHeads(content); } if (!skinConfig.not("bootstrapIcons")) { // Bootstrap Icons are enabled by default, so check for false and negate content = htmlTool.replaceAll(content, ICON_REPLACEMENTS); // The <tt> tag is not supported in HTML5 (see https://www.w3schools.com/tags/tag_tt.asp). content = htmlTool.replaceWith(content, "tt", "<code class=\"literal\">"); } return super.onPreRender(skinConfig, content); } /** * @return Returns the {@link Navbar}. */ public Navbar getNavbar() { return navbar; } /** * @return Returns the {@link ScrollTop}. */ public ScrollTop getScrollTop() { return scrollTop; } /** * @return Returns the {@link Footer}. */ public Footer getFooter() { return footer; } /** * Sets the type of context. * * @param type * the of context. * @return Returns the fluent instance context. */ protected T withType(final ContextType type) { this.type = type; return self(); } /** * @return Returns the type of context of page. */ public String getType() { return type.name(); } /** * @return Returns the fluent instance. */ @SuppressWarnings("unchecked") protected T self() { return (T) this; } /** * {@inheritDoc} */ @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.ssl; import org.apache.activemq.artemis.api.core.ActiveMQSecurityException; import org.apache.activemq.artemis.api.core.QueueConfiguration; import org.apache.activemq.artemis.api.core.RoutingType; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; import org.apache.activemq.artemis.api.core.client.ClientConsumer; import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientProducer; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl; import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; import org.apache.activemq.artemis.core.security.Role; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.settings.HierarchicalRepository; import org.apache.activemq.artemis.spi.core.security.ActiveMQJAASSecurityManager; import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManager; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.RetryRule; import org.apache.hadoop.minikdc.MiniKdc; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.File; import java.lang.management.ManagementFactory; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class CoreClientOverOneWaySSLKerb5Test extends ActiveMQTestBase { @Rule public RetryRule retryRule = new RetryRule(2); public static final SimpleString QUEUE = new SimpleString("QueueOverKrb5SSL"); public static final String CLIENT_PRINCIPAL = "client"; public static final String SNI_HOST = "sni.host"; public static final String SERVICE_PRINCIPAL = "host/" + SNI_HOST; static { String path = System.getProperty("java.security.auth.login.config"); if (path == null) { URL resource = CoreClientOverOneWaySSLKerb5Test.class.getClassLoader().getResource("login.config"); if (resource != null) { path = resource.getFile(); System.setProperty("java.security.auth.login.config", path); } } } private MiniKdc kdc; private ActiveMQServer server; private TransportConfiguration tc; private TransportConfiguration inVMTc; private String userPrincipal; @Test public void testOneWaySSLWithGoodClientCipherSuite() throws Exception { // hard coded match, default_keytab_name in minikdc-krb5.conf template File userKeyTab = new File("target/test.krb5.keytab"); kdc.createPrincipal(userKeyTab, CLIENT_PRINCIPAL, SERVICE_PRINCIPAL); createCustomSslServer(); tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true); tc.getParams().put(TransportConstants.ENABLED_CIPHER_SUITES_PROP_NAME, getSuitableCipherSuite()); tc.getParams().put(TransportConstants.SNIHOST_PROP_NAME, SNI_HOST); // static service name rather than dynamic machine name tc.getParams().put(TransportConstants.SSL_KRB5_CONFIG_PROP_NAME, "core-tls-krb5-client"); final ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); ClientSessionFactory sf = null; try { sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); session.createQueue(new QueueConfiguration(CoreClientOverOneWaySSLKerb5Test.QUEUE).setRoutingType(RoutingType.ANYCAST)); ClientProducer producer = session.createProducer(CoreClientOverOneWaySSLKerb5Test.QUEUE); final String text = RandomUtil.randomString(); ClientMessage message = createTextMessage(session, text); producer.send(message); ClientConsumer consumer = session.createConsumer(CoreClientOverOneWaySSLKerb5Test.QUEUE); session.start(); ClientMessage m = consumer.receive(1000); Assert.assertNotNull(m); Assert.assertEquals(text, m.getReadOnlyBodyBuffer().readString()); System.err.println("m:" + m + ", user:" + m.getValidatedUserID()); Assert.assertNotNull("got validated user", m.getValidatedUserID()); Assert.assertTrue("krb id in validated user", m.getValidatedUserID().contains(CLIENT_PRINCIPAL)); } finally { if (sf != null) { sf.close(); } locator.close(); } // validate only ssl creds work, try and fake the principal w/o ssl final ServerLocator inVmLocator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(inVMTc)); ClientSessionFactory inVmSf = null; try { inVmSf = createSessionFactory(inVmLocator); inVmSf.createSession(userPrincipal, "", false, false, false, false, 10); fail("supposed to throw exception"); } catch (ActiveMQSecurityException e) { // expected } finally { if (inVmSf != null) { inVmSf.close(); } inVmLocator.close(); } } public String getSuitableCipherSuite() throws Exception { return "TLS_KRB5_WITH_3DES_EDE_CBC_SHA"; } // Package protected --------------------------------------------- @Override @Before public void setUp() throws Exception { super.setUp(); kdc = new MiniKdc(MiniKdc.createConf(), temporaryFolder.newFolder("kdc")); kdc.start(); } @Override @After public void tearDown() throws Exception { try { kdc.stop(); } finally { super.tearDown(); } } private void createCustomSslServer() throws Exception { Map<String, Object> params = new HashMap<>(); params.put(TransportConstants.SSL_ENABLED_PROP_NAME, true); params.put(TransportConstants.ENABLED_CIPHER_SUITES_PROP_NAME, getSuitableCipherSuite()); params.put(TransportConstants.SSL_KRB5_CONFIG_PROP_NAME, "core-tls-krb5-server"); ConfigurationImpl config = createBasicConfig().addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params, "nettySSL")); config.setPopulateValidatedUser(true); // so we can verify the kerb5 id is present config.setSecurityEnabled(true); config.addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)); ActiveMQSecurityManager securityManager = new ActiveMQJAASSecurityManager("Krb5Plus"); server = addServer(ActiveMQServers.newActiveMQServer(config, ManagementFactory.getPlatformMBeanServer(), securityManager, false)); HierarchicalRepository<Set<Role>> securityRepository = server.getSecurityRepository(); final String roleName = "ALLOW_ALL"; Role role = new Role(roleName, true, true, true, true, true, true, true, true, true, true); Set<Role> roles = new HashSet<>(); roles.add(role); securityRepository.addMatch(QUEUE.toString(), roles); server.start(); waitForServerToStart(server); // note kerberos user does not exist on the broker save as a role member in dual-authentication-roles.properties userPrincipal = CLIENT_PRINCIPAL + "@" + kdc.getRealm(); tc = new TransportConfiguration(NETTY_CONNECTOR_FACTORY); inVMTc = new TransportConfiguration(INVM_CONNECTOR_FACTORY); } }
Java
# 3rd Year Main Project # Design Document Check out the [Wiki](https://github.com/ianburkeixiv/ThirdYearProject/wiki) for the design document # Video Click [here](https://youtu.be/jd0N7RG_bnA) to check out the video I uploaded on Youtube showing how to run the application. # Installation and Configuration Manual Download the [Install&ConfigManual](https://github.com/ianburkeixiv/ThirdYearProject/raw/master/Install%26ConfigManual.docx) word document above to install the various technologies used in this project. # User Guide Once the installation and configuration is done. Here are the following steps on how to run the the database, server and the ionic app together. Download [MyApp2/](https://github.com/ianburkeixiv/ThirdYearProject/tree/master/myApp2) folder and [Server folder](https://github.com/ianburkeixiv/ThirdYearProject/tree/master/server) above. ### Step 1: Launch MongoDB server To launch the MongoDB server, we must locate the executable files in the MongoDB Server binary folder. Open a command terminal and enter the following: ```sh $ cd/ ``` ![](https://cloud.githubusercontent.com/assets/22341150/25337063/212c8628-28f2-11e7-962a-9c059f93e79c.PNG) Cd/ will change back to the root directory. Once in the root directory, we need to go into the Program Files directory ```sh $ cd "Program Files" ``` ![](https://cloud.githubusercontent.com/assets/22341150/25337079/332561f6-28f2-11e7-87e6-18631152e20e.PNG) *A shortcut to this is typing the first few words like "pro" and then press the tab button to bring up the full word*. Once in the Program Files directory, we must go into the MongoDB directory. ```sh $ cd MongoDB ``` ![](https://cloud.githubusercontent.com/assets/22341150/25337082/3b1766b6-28f2-11e7-9ad9-79dc5891b573.PNG) Then cd into the server directory.. ```sh $ cd server ``` Use version 3.4.. ```sh $ cd 3.4 ``` cd into the bin folder which contains all the executable files. ```sh $ cd bin ``` ![](https://cloud.githubusercontent.com/assets/22341150/25337087/40f7ad0c-28f2-11e7-9a68-6b90a57805c6.PNG) Once you are inside the bin folder, enter mongod command to launch the server. ```sh $ mongod ``` ![](https://cloud.githubusercontent.com/assets/22341150/25337073/2a85d936-28f2-11e7-928a-14e1e75f4b88.PNG) ### Step 2: Launch the Node Server In the [Server](https://github.com/ianburkeixiv/ThirdYearProject/tree/master/server) folder there are two files. The package.json file is used to specify dependencies to be installed by NPM (Node Package Manager). Server.js is the actual server file. To launch the server, open up another command terminal and locate the server directory using the cd (change directory) command. Once you are in the server directory, enter the following command to launch the server: ```sh $ node server.js ``` ![](https://cloud.githubusercontent.com/assets/22341150/25339672/597db4ee-28fb-11e7-936a-90813a85b947.PNG) Once the MongoDB server and the Node server are running, we can now launch the Ionic 2 app. ### Step 3: Launh Ionic 2 First you must locate the MyApp2 directory containing the Ionic 2 project. Open up another (No.3) command terminal and cd into MyApp2 directory. Once you are inside the directory, enter the following command to run the Ionic app: - *Note: 'ionic serve' command will run the app on your local browser* - We will be using 'ionic lab'. This feature makes it easy to run the app in a phone frame and with iOS and Android platforms side by side. ```sh $ ionic lab ``` ![](https://cloud.githubusercontent.com/assets/22341150/25341218/0d8f87a6-2900-11e7-9cc2-2de0ce364e6a.PNG) 'Once the Ionic app is running, you can test it out!' ![](https://cloud.githubusercontent.com/assets/22341150/25342669/9d58dd02-2904-11e7-9af2-092630a6def2.PNG) ![](https://cloud.githubusercontent.com/assets/22341150/25342685/a46b6b46-2904-11e7-9325-7f7d3b0559ec.PNG)
Java
""" Generate a toy dataset for the matrix factorisation case, and store it. We use dimensions 100 by 50 for the dataset, and 10 latent factors. As the prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """ import sys, os project_location = os.path.dirname(__file__)+"/../../../" sys.path.append(project_location) from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def generate_dataset(I,J,K,lambdaU,lambdaV,tau): # Generate U, V U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R) def add_noise(true_R,tau): if numpy.isinf(tau): return numpy.copy(true_R) (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R def try_generate_M(I,J,fraction_unknown,attempts): for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown) print "Took %s attempts to generate M." % attempt return M except AssertionError: pass raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown)) ########## if __name__ == "__main__": output_folder = project_location+"BNMTF/data_toy/bnmf/" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000) # Store all matrices in text files numpy.savetxt(open(output_folder+"U.txt",'w'),U) numpy.savetxt(open(output_folder+"V.txt",'w'),V) numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R) numpy.savetxt(open(output_folder+"R.txt",'w'),R) numpy.savetxt(open(output_folder+"M.txt",'w'),M) print "Mean R: %s. Variance R: %s. Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()
Java
/* Copyright IBM Corp. 2016 All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package deliver import ( "fmt" "io" "testing" "time" mockpolicies "github.com/hyperledger/fabric/common/mocks/policies" "github.com/hyperledger/fabric/common/policies" "github.com/hyperledger/fabric/common/tools/configtxgen/provisional" "github.com/hyperledger/fabric/orderer/common/ledger" ramledger "github.com/hyperledger/fabric/orderer/common/ledger/ram" cb "github.com/hyperledger/fabric/protos/common" ab "github.com/hyperledger/fabric/protos/orderer" "github.com/hyperledger/fabric/protos/utils" logging "github.com/op/go-logging" "github.com/stretchr/testify/assert" "google.golang.org/grpc" ) var genesisBlock = cb.NewBlock(0, nil) var systemChainID = "systemChain" const ledgerSize = 10 func init() { logging.SetLevel(logging.DEBUG, "") } type mockD struct { grpc.ServerStream recvChan chan *cb.Envelope sendChan chan *ab.DeliverResponse } func newMockD() *mockD { return &mockD{ recvChan: make(chan *cb.Envelope), sendChan: make(chan *ab.DeliverResponse), } } func (m *mockD) Send(br *ab.DeliverResponse) error { m.sendChan <- br return nil } func (m *mockD) Recv() (*cb.Envelope, error) { msg, ok := <-m.recvChan if !ok { return msg, io.EOF } return msg, nil } type erroneousRecvMockD struct { grpc.ServerStream } func (m *erroneousRecvMockD) Send(br *ab.DeliverResponse) error { return nil } func (m *erroneousRecvMockD) Recv() (*cb.Envelope, error) { // The point here is to simulate an error other than EOF. // We don't bother to create a new custom error type. return nil, io.ErrUnexpectedEOF } type erroneousSendMockD struct { grpc.ServerStream recvVal *cb.Envelope } func (m *erroneousSendMockD) Send(br *ab.DeliverResponse) error { // The point here is to simulate an error other than EOF. // We don't bother to create a new custom error type. return io.ErrUnexpectedEOF } func (m *erroneousSendMockD) Recv() (*cb.Envelope, error) { return m.recvVal, nil } type mockSupportManager struct { chains map[string]*mockSupport } func (mm *mockSupportManager) GetChain(chainID string) (Support, bool) { cs, ok := mm.chains[chainID] return cs, ok } type mockSupport struct { ledger ledger.ReadWriter policyManager *mockpolicies.Manager erroredChan chan struct{} configSeq uint64 } func (mcs *mockSupport) Errored() <-chan struct{} { return mcs.erroredChan } func (mcs *mockSupport) Sequence() uint64 { return mcs.configSeq } func (mcs *mockSupport) PolicyManager() policies.Manager { return mcs.policyManager } func (mcs *mockSupport) Reader() ledger.Reader { return mcs.ledger } func NewRAMLedger() ledger.ReadWriter { rlf := ramledger.New(ledgerSize + 1) rl, _ := rlf.GetOrCreate(provisional.TestChainID) rl.Append(genesisBlock) return rl } func initializeDeliverHandler() Handler { mm := newMockMultichainManager() for i := 1; i < ledgerSize; i++ { l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } return NewHandlerImpl(mm) } func newMockMultichainManager() *mockSupportManager { rl := NewRAMLedger() mm := &mockSupportManager{ chains: make(map[string]*mockSupport), } mm.chains[systemChainID] = &mockSupport{ ledger: rl, policyManager: &mockpolicies.Manager{Policy: &mockpolicies.Policy{}}, erroredChan: make(chan struct{}), } return mm } var seekOldest = &ab.SeekPosition{Type: &ab.SeekPosition_Oldest{Oldest: &ab.SeekOldest{}}} var seekNewest = &ab.SeekPosition{Type: &ab.SeekPosition_Newest{Newest: &ab.SeekNewest{}}} func seekSpecified(number uint64) *ab.SeekPosition { return &ab.SeekPosition{Type: &ab.SeekPosition_Specified{Specified: &ab.SeekSpecified{Number: number}}} } func makeSeek(chainID string, seekInfo *ab.SeekInfo) *cb.Envelope { return &cb.Envelope{ Payload: utils.MarshalOrPanic(&cb.Payload{ Header: &cb.Header{ ChannelHeader: utils.MarshalOrPanic(&cb.ChannelHeader{ ChannelId: chainID, }), SignatureHeader: utils.MarshalOrPanic(&cb.SignatureHeader{}), }, Data: utils.MarshalOrPanic(seekInfo), }), } } func TestWholeChainSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekOldest, Stop: seekNewest, Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) count := uint64(0) for { select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { if deliverReply.GetStatus() != cb.Status_SUCCESS { t.Fatalf("Received an error on the reply channel") } if count != ledgerSize { t.Fatalf("Expected %d blocks but got %d", ledgerSize, count) } return } if deliverReply.GetBlock().Header.Number != count { t.Fatalf("Expected block %d but got block %d", count, deliverReply.GetBlock().Header.Number) } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } count++ } } func TestNewestSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekNewest, Stop: seekNewest, Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { t.Fatalf("Received an error on the reply channel") } if deliverReply.GetBlock().Header.Number != uint64(ledgerSize-1) { t.Fatalf("Expected only the most recent block") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestSpecificSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) specifiedStart := uint64(3) specifiedStop := uint64(7) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(specifiedStart), Stop: seekSpecified(specifiedStop), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) count := uint64(0) for { select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { if deliverReply.GetStatus() != cb.Status_SUCCESS { t.Fatalf("Received an error on the reply channel") } return } if expected := specifiedStart + count; deliverReply.GetBlock().Header.Number != expected { t.Fatalf("Expected block %d but got block %d", expected, deliverReply.GetBlock().Header.Number) } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } count++ } } func TestUnauthorizedSeek(t *testing.T) { mm := newMockMultichainManager() for i := 1; i < ledgerSize; i++ { l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } mm.chains[systemChainID].policyManager.Policy.Err = fmt.Errorf("Fail to evaluate policy") m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(0)), Stop: seekSpecified(uint64(0)), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetStatus() != cb.Status_FORBIDDEN { t.Fatalf("Received wrong error on the reply channel") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestRevokedAuthorizationSeek(t *testing.T) { mm := newMockMultichainManager() for i := 1; i < ledgerSize; i++ { l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(ledgerSize - 1)), Stop: seekSpecified(ledgerSize), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: assert.NotNil(t, deliverReply.GetBlock(), "First should succeed") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } mm.chains[systemChainID].policyManager.Policy.Err = fmt.Errorf("Fail to evaluate policy") mm.chains[systemChainID].configSeq++ l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", ledgerSize+1))}})) select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_FORBIDDEN, deliverReply.GetStatus(), "Second should been forbidden ") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestOutOfBoundSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(3 * ledgerSize)), Stop: seekSpecified(uint64(3 * ledgerSize)), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetStatus() != cb.Status_NOT_FOUND { t.Fatalf("Received wrong error on the reply channel") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestFailFastSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(ledgerSize - 1)), Stop: seekSpecified(ledgerSize), Behavior: ab.SeekInfo_FAIL_IF_NOT_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { t.Fatalf("Expected to receive first block") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } select { case deliverReply := <-m.sendChan: if deliverReply.GetStatus() != cb.Status_NOT_FOUND { t.Fatalf("Expected to receive failure for second block") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestBlockingSeek(t *testing.T) { mm := newMockMultichainManager() for i := 1; i < ledgerSize; i++ { l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(ledgerSize - 1)), Stop: seekSpecified(ledgerSize), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { t.Fatalf("Expected to receive first block") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get first block") } select { case <-m.sendChan: t.Fatalf("Should not have delivered an error or second block") case <-time.After(50 * time.Millisecond): } l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", ledgerSize+1))}})) select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { t.Fatalf("Expected to receive new block") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get new block") } select { case deliverReply := <-m.sendChan: if deliverReply.GetStatus() != cb.Status_SUCCESS { t.Fatalf("Expected delivery to complete") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestErroredSeek(t *testing.T) { mm := newMockMultichainManager() ms := mm.chains[systemChainID] l := ms.ledger close(ms.erroredChan) for i := 1; i < ledgerSize; i++ { l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(ledgerSize - 1)), Stop: seekSpecified(ledgerSize), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_SERVICE_UNAVAILABLE, deliverReply.GetStatus(), "Mock support errored") case <-time.After(time.Second): t.Fatalf("Timed out waiting for error response") } } func TestErroredBlockingSeek(t *testing.T) { mm := newMockMultichainManager() ms := mm.chains[systemChainID] l := ms.ledger for i := 1; i < ledgerSize; i++ { l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(ledgerSize - 1)), Stop: seekSpecified(ledgerSize), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: assert.NotNil(t, deliverReply.GetBlock(), "Expected first block") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get first block") } close(ms.erroredChan) select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_SERVICE_UNAVAILABLE, deliverReply.GetStatus(), "Mock support errored") case <-time.After(time.Second): t.Fatalf("Timed out waiting for error response") } } func TestSGracefulShutdown(t *testing.T) { m := newMockD() ds := NewHandlerImpl(nil) close(m.recvChan) assert.NoError(t, ds.Handle(m), "Expected no error for hangup") } func TestReversedSeqSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) specifiedStart := uint64(7) specifiedStop := uint64(3) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(specifiedStart), Stop: seekSpecified(specifiedStop), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetStatus() != cb.Status_BAD_REQUEST { t.Fatalf("Received wrong error on the reply channel") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestBadStreamRecv(t *testing.T) { bh := NewHandlerImpl(nil) assert.Error(t, bh.Handle(&erroneousRecvMockD{}), "Should catch unexpected stream error") } func TestBadStreamSend(t *testing.T) { m := &erroneousSendMockD{recvVal: makeSeek(systemChainID, &ab.SeekInfo{Start: seekNewest, Stop: seekNewest, Behavior: ab.SeekInfo_BLOCK_UNTIL_READY})} ds := initializeDeliverHandler() assert.Error(t, ds.Handle(m), "Should catch unexpected stream error") } func TestOldestSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekOldest, Stop: seekOldest, Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: assert.NotEqual(t, nil, deliverReply.GetBlock(), "Received an error on the reply channel") assert.Equal(t, uint64(0), deliverReply.GetBlock().Header.Number, "Expected only the most recent block") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestNoPayloadSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- &cb.Envelope{Payload: []byte("Foo")} select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_BAD_REQUEST, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestNilPayloadHeaderSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- &cb.Envelope{Payload: utils.MarshalOrPanic(&cb.Payload{})} select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_BAD_REQUEST, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestBadChannelHeader(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- &cb.Envelope{Payload: utils.MarshalOrPanic(&cb.Payload{ Header: &cb.Header{ChannelHeader: []byte("Foo")}, })} select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_BAD_REQUEST, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestChainNotFound(t *testing.T) { mm := &mockSupportManager{ chains: make(map[string]*mockSupport), } m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekNewest, Stop: seekNewest, Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_NOT_FOUND, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestBadSeekInfoPayload(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- &cb.Envelope{ Payload: utils.MarshalOrPanic(&cb.Payload{ Header: &cb.Header{ ChannelHeader: utils.MarshalOrPanic(&cb.ChannelHeader{ ChannelId: systemChainID, }), SignatureHeader: utils.MarshalOrPanic(&cb.SignatureHeader{}), }, Data: []byte("Foo"), }), } select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_BAD_REQUEST, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestMissingSeekPosition(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- &cb.Envelope{ Payload: utils.MarshalOrPanic(&cb.Payload{ Header: &cb.Header{ ChannelHeader: utils.MarshalOrPanic(&cb.ChannelHeader{ ChannelId: systemChainID, }), SignatureHeader: utils.MarshalOrPanic(&cb.SignatureHeader{}), }, Data: nil, }), } select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_BAD_REQUEST, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } }
Java
using Artemis.System; using IHateRectangles.Screens; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace IHateRectangles { public class MenuScreen : Screen { private SpriteBatch _spriteBatch; private SpriteFont _menuFont; private ContentManager _contentManager; public event ScreenFinished OnScreenFinished; public void Initialize() { _contentManager = EntitySystem.BlackBoard.GetEntry<ContentManager>("ContentManager"); _menuFont = _contentManager.Load<SpriteFont>(@"Fonts\Hud"); _spriteBatch = EntitySystem.BlackBoard.GetEntry<SpriteBatch>("SpriteBatch"); } public void Update() { if (Keyboard.GetState().GetPressedKeys().Length > 0) if (OnScreenFinished != null) OnScreenFinished(new GameScreen()); } public void Draw() { var viewport = EntitySystem.BlackBoard.GetEntry<GraphicsDevice>("GraphicsDevice").Viewport; _spriteBatch.Begin(); _spriteBatch.DrawString(_menuFont, "I Hate Rectangles", new Vector2(viewport.Width / 2 - 100, viewport.Height / 2 - 200), Color.White); _spriteBatch.DrawString(_menuFont, "Press any key to continue.", new Vector2(viewport.Width / 2 - 138, viewport.Height / 2 - 100), Color.White); _spriteBatch.End(); } public void Destroy() { } } }
Java
############################################################################### ## ## Description: ## Test with ibv_rc_pingpong, perf and rping between 2 Guests on the same Hosts ## ## Revision: ## v1.0.0 - ldu - 12/04/2018 - Build the script ## ############################################################################### <# .Synopsis Test with ibv_rc_pingpong, perf and rping between 2 Guests on the different Hosts .Description .Parameter vmName Name of the test VM. .Parameter testParams Semicolon separated list of test parameters. #> param([String] $vmName, [String] $hvServer, [String] $testParams) # # Checking the input arguments # if (-not $vmName) { "Error: VM name cannot be null!" exit 100 } if (-not $hvServer) { "Error: hvServer cannot be null!" exit 100 } if (-not $testParams) { Throw "Error: No test parameters specified" } # # Output test parameters so they are captured in log file # "TestParams : '${testParams}'" # # Parse the test parameters # $rootDir = $null $sshKey = $null $ipv4 = $null $dstHost6_7 = $null $dstHost6_5 = $null $dstDatastore = $null $params = $testParams.Split(";") foreach ($p in $params) { $fields = $p.Split("=") switch ($fields[0].Trim()) { "sshKey" { $sshKey = $fields[1].Trim() } "rootDir" { $rootDir = $fields[1].Trim() } "ipv4" { $ipv4 = $fields[1].Trim() } "dstHost6.7" { $dstHost6_7 = $fields[1].Trim()} "dstHost6.5" { $dstHost6_5 = $fields[1].Trim()} "dstDatastore" { $dstDatastore = $fields[1].Trim() } "tool" { $tool = $fields[1].Trim() } default {} } } # # Check all parameters are valid # if (-not $rootDir) { "Warn : no rootdir was specified" } else { if ( (Test-Path -Path "${rootDir}") ) { Set-Location $rootDir } else { "Warn : rootdir '${rootDir}' does not exist" } } if ($null -eq $sshKey) { "FAIL: Test parameter sshKey was not specified" return $False } if ($null -eq $ipv4) { "FAIL: Test parameter ipv4 was not specified" return $False } if ($null -eq $dstDatastore) { "FAIL: Test parameter dstDatastore was not specified" return $False } if (-not $dstHost6_7 -or -not $dstHost6_5) { "INFO: dstHost 6.7 is $dstHost6_7" "INFO: dstHost 6.5 is $dstHost6_5" "Warn : dstHost was not specified" return $false } # # Source the tcutils.ps1 file # . .\setupscripts\tcutils.ps1 PowerCLIImport ConnectToVIServer $env:ENVVISIPADDR ` $env:ENVVISUSERNAME ` $env:ENVVISPASSWORD ` $env:ENVVISPROTOCOL ############################################################################### # # Main Body # ############################################################################### $retVal = $Failed $vmObj = Get-VMHost -Name $hvServer | Get-VM -Name $vmName if (-not $vmObj) { LogPrint "ERROR: Unable to Get-VM with $vmName" DisconnectWithVIServer return $Aborted } # Specify dst host $dstHost = FindDstHost -hvServer $hvServer -Host6_5 $dstHost6_5 -Host6_7 $dstHost6_7 if ($null -eq $dstHost) { LogPrint "ERROR: Cannot find required Host" DisconnectWithVIServer return $Aborted } LogPrint "INFO: Destination Host is $dstHost" # Get the Guest version $DISTRO = GetLinuxDistro ${ipv4} ${sshKey} LogPrint "DEBUG: DISTRO: $DISTRO" if (-not $DISTRO) { LogPrint "ERROR: Guest OS version is NULL" DisconnectWithVIServer return $Aborted } LogPrint "INFO: Guest OS version is $DISTRO" # Different Guest DISTRO if ($DISTRO -ne "RedHat7" -and $DISTRO -ne "RedHat8" -and $DISTRO -ne "RedHat6") { LogPrint "ERROR: Guest OS ($DISTRO) isn't supported, MUST UPDATE in Framework / XML / Script" DisconnectWithVIServer return $Skipped } # Start another VM $GuestBName = $vmObj.Name.Split('-') # Get another VM by change Name $GuestBName[-1] = "B" $GuestBName = $GuestBName -join "-" $GuestB = Get-VMHost -Name $hvServer | Get-VM -Name $GuestBName # Add RDMA NIC for Guest B $status = AddPVrdmaNIC $GuestBName $hvServer if ( -not $status[-1]) { LogPrint "ERROR: RDMA NIC adds failed" DisconnectWithVIServer return $Aborted } # Start GuestB Start-VM -VM $GuestB -Confirm:$false -RunAsync:$true -ErrorAction SilentlyContinue if (-not $?) { LogPrint "ERROR : Cannot start VM" DisconnectWithVIServer return $Aborted } # Wait for GuestB SSH ready if ( -not (WaitForVMSSHReady $GuestBName $hvServer $sshKey 300)) { LogPrint "ERROR : Cannot start SSH" DisconnectWithVIServer return $Aborted } LogPrint "INFO: Ready SSH" # Get another VM IP addr $ipv4Addr_B = GetIPv4 -vmName $GuestBName -hvServer $hvServer $GuestB = Get-VMHost -Name $hvServer | Get-VM -Name $GuestBName # Find out new add RDMA nic for Guest B $nics += @($(FindAllNewAddNIC $ipv4Addr_B $sshKey)) if ($null -eq $nics) { LogPrint "ERROR: Cannot find new add RDMA NIC" DisconnectWithVIServer return $Failed } else { $rdmaNIC = $nics[-1] } LogPrint "INFO: New NIC is $rdmaNIC" # Config RDMA NIC IP addr for Guest B $IPAddr_guest_B = "172.31.1." + (Get-Random -Maximum 254 -Minimum 125) if ( -not (ConfigIPforNewDevice $ipv4Addr_B $sshKey $rdmaNIC ($IPAddr_guest_B + "/24"))) { LogPrint "ERROR : Guest B Config IP Failed" DisconnectWithVIServer return $Failed } LogPrint "INFO: Guest B RDMA NIC IP add is $IPAddr_guest_B" # Find out new add RDMA nic for Guest A $nics += @($(FindAllNewAddNIC $ipv4 $sshKey)) if ($null -eq $nics) { LogPrint "ERROR: Cannot find new add rdma NIC" DisconnectWithVIServer return $Failed } else { $rdmaNIC = $nics[-1] } LogPrint "INFO: New NIC is $rdmaNIC" # Config RDMA NIC IP addr for Guest A $IPAddr_guest_A = "172.31.1." + (Get-Random -Maximum 124 -Minimum 2) if ( -not (ConfigIPforNewDevice $ipv4 $sshKey $rdmaNIC ($IPAddr_guest_A + "/24"))) { LogPrint "ERROR : Guest A Config IP Failed" DisconnectWithVIServer return $Failed } LogPrint "INFO: Guest A RDMA NIC IP add is $IPAddr_guest_A" # Check can we ping GuestA from GuestB via RDMA NIC $Command = "ping $IPAddr_guest_A -c 10 -W 15 | grep ttl > /dev/null" $status = SendCommandToVM $ipv4Addr_B $sshkey $command if (-not $status) { LogPrint "ERROR : Ping test Failed" $retVal = $Failed } else { LogPrint "Pass : Ping test passed" } #For RHEL8 and RHEL7 install different package. if ($DISTRO -eq "RedHat8") { $command1 = "yum install -y opensm rdma libibverbs librdmacm librdmacm-utils ibacm libibverbs-utils infiniband-diags perftest qperf libcxgb4 libmlx4 libmlx5 rdma-core" } else { $command1 = "yum install -y opensm rdma libibverbs librdmacm librdmacm-utils ibacm libibverbs-utils infiniband-diags ibutils perftest qperf infinipath-psm libcxgb3 libcxgb4 libehca libipathverbs libmthca libmlx4 libmlx5 libnes libocrdma dapl dapl-devel dapl-utils dapl dapl-devel dapl-utils" } #install dependency package on guest B. $status = SendCommandToVM $ipv4Addr_B $sshkey $command1 if (-not $status) { LogPrint "ERROR : install package Failed" return $Aborted } #load ib related modules $command2 = "modprobe ib_umad" $status = SendCommandToVM $ipv4Addr_B $sshkey $command2 if (-not $status) { LogPrint "ERROR : load modules Failed" return $Aborted } #install dependency package on guest A. $status = SendCommandToVM $ipv4 $sshkey $command1 if (-not $status) { LogPrint "ERROR : install package Failed" return $Aborted } #load ib related modules $status = SendCommandToVM $ipv4 $sshkey $command2 if (-not $status) { LogPrint "ERROR : load modules Failed" return $Aborted } #check the test tools used for test. LogPrint "test is $tool" write-host -F Red "Test tool is $tool" if ( $tool -eq "perf" ) { #array for perftest command $perf_guestB = @("ib_send_lat -x 0 -a","ib_send_bw -x 0 -a","ib_read_lat -x 0 -a","ib_read_bw -x 0 -a","ib_write_lat -x 0 -a","ib_write_bw -x 0 -a" ) $perf_guestA = @("ib_send_lat -x 0 -a $IPAddr_guest_B","ib_send_bw -x 0 -a $IPAddr_guest_B","ib_read_lat -x 0 -a $IPAddr_guest_B","ib_read_bw -x 0 -a $IPAddr_guest_B","ib_write_lat -x 0 -a $IPAddr_guest_B","ib_write_bw -x 0 -a $IPAddr_guest_B" ) foreach($i in $perf_guestB) { $Process = Start-Process bin\plink -ArgumentList "-i ssh\${sshKey} root@${ipv4Addr_B} ${i}" -PassThru -WindowStyle Hidden write-host -F Red "the process1 id is $($Process.id) and $i" $index = $perf_guestB.IndexOf($i) $commandA = $perf_guestA[$index] $status = SendCommandToVM $ipv4 $sshkey $commandA if (-not $status) { LogPrint "ERROR : $commandA test Failed" return $Failed } else { $retVal = $Passed LogPrint "pass : $commandA test passed" } } } else { if ( $tool -eq "ibvrc" ) { $commandA = "ibv_rc_pingpong -s 1 -g 1 $IPAddr_guest_B" $commandB = "ibv_rc_pingpong -s 1 -g 1" } else { $commandA = "rping -c -a $IPAddr_guest_B -v -C 1" $commandB = "rping -s -v -V -C 1 -a $IPAddr_guest_B" } #Run test on guest B first,because guest B is test as server. $Process1 = Start-Process bin\plink -ArgumentList "-i ssh\${sshKey} root@${ipv4Addr_B} ${commandB}" -PassThru -WindowStyle Hidden write-host -F Red "$($Process1.id)" #Then run test on guest A, guest A as client. $a = "touch /root/aa" $status = SendCommandToVM $ipv4 $sshkey $a $status = SendCommandToVM $ipv4 $sshkey $commandA if (-not $status) { LogPrint "ERROR : test $commandA test Failed" DisconnectWithVIServer $retVal = $Failed } else { $retVal = $Passed LogPrint "pass : test $commandA test passed" } } DisconnectWithVIServer return $retVal
Java
package org.easyaccess.nist; import java.io.File; import java.util.HashMap; import java.util.Locale; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.speech.tts.TextToSpeech.OnInitListener; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.Toast; public class HomeScreenActivity extends Activity implements OnInitListener { private static final String TAG = "HomeScreenActivity"; boolean isButtonPressed = false; int gFocusPosition = 1; int gMaxFocusableItem = 2; Context gContext = null; String gTTsOnStart = null; SpeakManager gTTS = null; Button gBtnScan = null, gBtnSkipScan = null; View rootView = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_ballotstart); gContext = this; rootView = findViewById(R.id.alrt_root_view); gBtnScan = (Button) findViewById(R.id.btn_scan); gBtnSkipScan = (Button) findViewById(R.id.btn_skip_scan); gBtnScan.setBackgroundColor(getResources().getColor(R.color.bg_button)); gBtnScan.setTextColor(getResources().getColor(android.R.color.white)); gBtnSkipScan.setBackgroundColor(getResources().getColor(R.color.bg_button)); gBtnSkipScan.setTextColor(getResources().getColor(android.R.color.white)); gBtnScan.isInTouchMode(); File directory = new File(Constants.NIST_VOTING_PROTOTYPE_DIRECTORY); if (!directory.exists()) { directory.mkdir(); } File sampleFile = new File(directory, Constants.NIST_VOTING_PROTOTYPE_FILE_SP); if (!sampleFile.exists()) { StringBuilder builder = Utils.readFile(gContext, this.getResources().openRawResource(R.raw.election_info_sp)); Utils.writeToFile(builder.toString(), directory + File.separator + Constants.NIST_VOTING_PROTOTYPE_FILE_SP, false); } sampleFile = new File(directory, Constants.NIST_VOTING_PROTOTYPE_FILE_EN); if (!sampleFile.exists()) { StringBuilder builder = Utils.readFile(gContext, this.getResources().openRawResource(R.raw.election_info_en)); Utils.writeToFile(builder.toString(), directory + File.separator + Constants.NIST_VOTING_PROTOTYPE_FILE_EN, false); } } private OnClickListener sOnClickListener = new OnClickListener() { Intent intent = null; @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_scan: launchScan(); break; case R.id.btn_skip_scan: skipScan(); break; case R.id.alrt_root_view: speakWord("", null, false); break; } } private void skipScan() { resetPreferences(); intent = new Intent(gContext, ContestActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } private void launchScan() { resetPreferences(); intent = new Intent(gContext, ScannerActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } }; private void resetPreferences() { Constants.SETTING_LANGUAGE = Constants.DEFAULT_LANG_SETTING; Constants.SETTING_TOUCH_PRESENT = Constants.DEFAULT_TOUCH_PRESENT_SETTING; Constants.SETTING_FONT_SIZE = Constants.FONT_SIZE_STD; Constants.SETTING_REVERSE_SCREEN = Constants.DEFAULT_REVERSE_SCREEN_SETTING; Constants.SETTING_TTS_VOICE = Constants.DEFAULT_TTS_VOICE; Constants.SETTING_TTS_SPEED = Constants.TTS_SPEED_STD; Constants.SETTING_SCAN_MODE = Constants.DEFAULT_SCAN_MODE_SETTING; Constants.SETTING_SCAN_MODE_SPEED = Constants.DEFAULT_SCAN_SPEED_SETTING; SharedPreferences preferences = getSharedPreferences( Constants.PREFERENCE_NAME, Context.MODE_PRIVATE); Editor editor = preferences.edit(); editor.clear(); editor.commit(); } private OnTouchListener gOnTouchListener = new OnTouchListener() { /** * on touch down announce the info if it represent text. on touch up * perform the action */ @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition = 0; switch (v.getId()) { case R.id.btn_scan: v.setBackground(getResources().getDrawable( R.drawable.focused)); if (HeadsetListener.isHeadsetConnected) { speakWord(gBtnScan.getText().toString(), null, true); } break; case R.id.btn_skip_scan: v.setBackground(getResources().getDrawable( R.drawable.focused)); if (HeadsetListener.isHeadsetConnected) { speakWord(gBtnSkipScan.getText().toString(), null, true); } break; } } else if (event.getAction() == MotionEvent.ACTION_UP) { switch (v.getId()) { case R.id.btn_scan: v.setBackground(null); // v.performClick(); break; case R.id.btn_skip_scan: v.setBackground(null); // v.performClick(); break; } } return false; } }; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (!isButtonPressed) { int keyPressed = -1; if (keyCode == KeyEvent.KEYCODE_UNKNOWN) { keyPressed = event.getScanCode(); } else { keyPressed = keyCode; } switch (keyPressed) { case KeyEvent.KEYCODE_TAB: if(event.isShiftPressed()){ navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition--; if (gFocusPosition <= 0) { gFocusPosition = gMaxFocusableItem; } navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM); }else{ navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition++; if (gFocusPosition > gMaxFocusableItem) { gFocusPosition = 1; } navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM); } break; case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_BUTTON_1: navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition--; if (gFocusPosition <= 0) { gFocusPosition = gMaxFocusableItem; } navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM); break; case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_BUTTON_2: navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition++; if (gFocusPosition > gMaxFocusableItem) { gFocusPosition = 1; } navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM); break; case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_BUTTON_3: selectCurrentFocusItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); break; } } isButtonPressed = true; return true; } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { isButtonPressed = false; int keyPressed = -1; if (keyCode == KeyEvent.KEYCODE_UNKNOWN) { keyPressed = event.getScanCode(); } else { keyPressed = keyCode; } switch (keyPressed) { case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_BUTTON_3: // selectCurrentFocusItem(gFocusPosition, // Constants.JUMP_FROM_CURRENT_ITEM); break; } return true; } public void selectCurrentFocusItem(int focusPosition, int pressed_released) { switch (pressed_released) { case Constants.REACH_NEW_ITEM: break; case Constants.JUMP_FROM_CURRENT_ITEM: if (gFocusPosition == 1) { gBtnScan.performClick(); } else if (gFocusPosition == 2) { gBtnSkipScan.performClick(); } break; } } public void navigateToOtherItem(int focusPosition, int reach_jump) { View view = getCurrentFocus(); Log.d(TAG, " from navigation method focus position = " + focusPosition + ", current focus = " + view ); // + ", next focus down id = " // + view.getNextFocusDownId() // + ", next focus forward id = " + view.getNextFocusForwardId() // + ", next focus left id = " + view.getNextFocusLeftId() // + ", next focus right id = " + view.getNextFocusRightId() // + ", next focus up id = " + view.getNextFocusUpId()); switch (reach_jump) { case Constants.JUMP_FROM_CURRENT_ITEM: if (focusPosition == 1) { // gBtnScan.setBackground(null); } else if (focusPosition == 2) { // gBtnSkipScan.setBackground(null); } break; case Constants.REACH_NEW_ITEM: if (focusPosition == 1) { gBtnScan.setFocusableInTouchMode(true);// for handling the ez-keypad focus gBtnSkipScan.setFocusableInTouchMode(false);// for handling the ez-keypad focus gBtnScan.requestFocus();// for handling the focus when come out of touch mode // gBtnScan.setBackground(getResources().getDrawable( // R.drawable.focused)); if (HeadsetListener.isHeadsetConnected) { speakWord(gBtnScan.getText().toString() + Constants.COMMA_SPACE + getString(R.string.button), null, true); } } else if (focusPosition == 2) { gBtnScan.setFocusableInTouchMode(false);// for handling the ez-keypad focus gBtnSkipScan.setFocusableInTouchMode(true);// for handling the ez-keypad focus gBtnSkipScan.requestFocus();// for handling the focus when come out of touch mode // gBtnSkipScan.setBackground(getResources().getDrawable( // R.drawable.focused)); if (HeadsetListener.isHeadsetConnected) { speakWord(gBtnSkipScan.getText().toString() + Constants.COMMA_SPACE + getString(R.string.button), null, true); } } break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.d(TAG,"resultCode = " + resultCode); if (requestCode == Constants.TTS_DATA_CHECK_CODE) { if (resultCode == SpeakManager.Engine.CHECK_VOICE_DATA_PASS) { Log.d(TAG,"Setting speak manager"); if (Constants.SETTING_TTS_VOICE == Constants.DEFAULT_TTS_VOICE) { gTTS = new SpeakManager(gContext, this, "com.svox.classic"); } else { gTTS = new SpeakManager(gContext, this, "com.ivona.tts"); } } else { Log.d(TAG,"launching intent for installing tts"); Intent ttsInstallIntent = new Intent(); ttsInstallIntent .setAction(SpeakManager.Engine.ACTION_INSTALL_TTS_DATA); startActivity(ttsInstallIntent); } } } @Override public void onInit(int status) { if (status == SpeakManager.SUCCESS) { if (Constants.SETTING_LANGUAGE == Constants.DEFAULT_LANG_SETTING) { gTTS.setLanguage(Locale.US); } else { gTTS.setLanguage(new Locale("spa", "ESP")); } gTTS.setSpeechRate(Constants.SETTING_TTS_SPEED); speakWord(gTTsOnStart, null, true); } else if (status == SpeakManager.ERROR) { Toast.makeText(gContext, getString(R.string.failed), Toast.LENGTH_SHORT).show(); } } public void speakWord(String word, HashMap<String, String> utteranceId, boolean shouldRepeat) { if (gTTS != null) { gTTS.speak(word, SpeakManager.QUEUE_FLUSH, utteranceId, shouldRepeat); } } @Override protected void onStop() { super.onStop(); if (gTTS != null) { gTTS.stop(); gTTS.shutdown(); } } @Override protected void onStart() { super.onStart(); Intent checkTTSIntent = new Intent(); checkTTSIntent.setAction(SpeakManager.Engine.ACTION_CHECK_TTS_DATA); startActivityForResult(checkTTSIntent, Constants.TTS_DATA_CHECK_CODE); gBtnScan.setText(R.string.scan_barcode); gBtnSkipScan.setText(R.string.skip_barcode); gBtnScan.setTextSize(Constants.SETTING_FONT_SIZE); gBtnSkipScan.setTextSize(Constants.SETTING_FONT_SIZE); gBtnScan.setOnClickListener(sOnClickListener); // gBtnScan.setOnTouchListener(gOnTouchListener); gBtnSkipScan.setOnClickListener(sOnClickListener); // gBtnSkipScan.setOnTouchListener(gOnTouchListener); rootView.setOnClickListener(sOnClickListener); gBtnSkipScan.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus){ // gBtnSkipScan.setFocusableInTouchMode(true); }else{ // gBtnSkipScan.setFocusableInTouchMode(false); } } }); gBtnScan.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus){ // gBtnScan.setFocusableInTouchMode(true); }else{ // gBtnScan.setFocusableInTouchMode(false); } } }); gTTsOnStart = getString(R.string.scan_barcode) + Constants.COMMA_SPACE + getString(R.string.button); // View view = getCurrentFocus(); // Log.d(TAG, "current focus = " + view // + ", next focus down id = " // + view.getNextFocusDownId() // + ", next focus forward id = " + view.getNextFocusForwardId() // + ", next focus left id = " + view.getNextFocusLeftId() // + ", next focus right id = " + view.getNextFocusRightId() // + ", next focus up id = " + view.getNextFocusUpId()); // gBtnScan.setBackgroundResource(R.drawable.focused); gBtnScan.setFocusableInTouchMode(true);// for showing focus initially gBtnScan.requestFocus(); // view = getCurrentFocus(); // Log.d(TAG, "current focus = " + view // + ", next focus down id = " // + view.getNextFocusDownId() // + ", next focus forward id = " + view.getNextFocusForwardId() // + ", next focus left id = " + view.getNextFocusLeftId() // + ", next focus right id = " + view.getNextFocusRightId() // + ", next focus up id = " + view.getNextFocusUpId()); } }
Java
// // ÀÌ ÆÄÀÏÀº JAXB(JavaTM Architecture for XML Binding) ÂüÁ¶ ±¸Çö 2.2.8-b130911.1802 ¹öÀüÀ» ÅëÇØ »ý¼ºµÇ¾ú½À´Ï´Ù. // <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>¸¦ ÂüÁ¶ÇϽʽÿÀ. // ÀÌ ÆÄÀÏÀ» ¼öÁ¤ÇÏ¸é ¼Ò½º ½ºÅ°¸¶¸¦ ÀçÄÄÆÄÀÏÇÒ ¶§ ¼öÁ¤ »çÇ×ÀÌ ¼Õ½ÇµË´Ï´Ù. // »ý¼º ³¯Â¥: 2015.07.30 ½Ã°£ 02:38:18 PM KST // package org.gs1.source.tsd; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>TSD_AttributeValuePairListType complex type¿¡ ´ëÇÑ Java Ŭ·¡½ºÀÔ´Ï´Ù. * * <p>´ÙÀ½ ½ºÅ°¸¶ ´ÜÆíÀÌ ÀÌ Å¬·¡½º¿¡ Æ÷ÇԵǴ ÇÊ¿äÇÑ ÄÜÅÙÃ÷¸¦ ÁöÁ¤ÇÕ´Ï´Ù. * * <pre> * &lt;complexType name="TSD_AttributeValuePairListType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="stringAVP" type="{urn:gs1:tsd:tsd_common:xsd:1}TSD_StringAttributeValuePairType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TSD_AttributeValuePairListType", namespace = "urn:gs1:tsd:tsd_common:xsd:1", propOrder = { "stringAVP" }) public class TSDAttributeValuePairListType { @XmlElement(required = true) protected List<TSDStringAttributeValuePairType> stringAVP; /** * Gets the value of the stringAVP property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the stringAVP property. * * <p> * For example, to add a new item, do as follows: * <pre> * getStringAVP().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TSDStringAttributeValuePairType } * * */ public List<TSDStringAttributeValuePairType> getStringAVP() { if (stringAVP == null) { stringAVP = new ArrayList<TSDStringAttributeValuePairType>(); } return this.stringAVP; } }
Java
dwtest ====== dwtest
Java
<!-- This comment will put IE 6, 7 and 8 in quirks mode --> <!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"/> <title>GraphBuilder 2.0 (alpha): Class Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javaScript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body onload='searchBox.OnSelectItem(0);'> <!-- Generated by Doxygen 1.6.1 --> <script type="text/javascript"><!-- var searchBox = new SearchBox("searchBox", "search",false,'Search'); --></script> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <img id="MSearchSelect" src="search/search.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </div> </li> </ul> </div> <div class="tabs"> <ul> <li><a href="annotated.html"><span>Class&nbsp;List</span></a></li> <li><a href="classes.html"><span>Class&nbsp;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&nbsp;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Class&nbsp;Members</span></a></li> </ul> </div> <div class="tabs"> <ul> <li class="current"><a href="functions.html"><span>All</span></a></li> <li><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> <li><a href="functions_enum.html"><span>Enumerations</span></a></li> </ul> </div> <div class="tabs"> <ul> <li><a href="functions.html#index_["><span>[</span></a></li> <li><a href="functions_0x5f.html#index__"><span>_</span></a></li> <li><a href="functions_0x61.html#index_a"><span>a</span></a></li> <li><a href="functions_0x62.html#index_b"><span>b</span></a></li> <li><a href="functions_0x63.html#index_c"><span>c</span></a></li> <li><a href="functions_0x64.html#index_d"><span>d</span></a></li> <li><a href="functions_0x65.html#index_e"><span>e</span></a></li> <li><a href="functions_0x66.html#index_f"><span>f</span></a></li> <li><a href="functions_0x67.html#index_g"><span>g</span></a></li> <li><a href="functions_0x68.html#index_h"><span>h</span></a></li> <li><a href="functions_0x69.html#index_i"><span>i</span></a></li> <li><a href="functions_0x6b.html#index_k"><span>k</span></a></li> <li><a href="functions_0x6c.html#index_l"><span>l</span></a></li> <li><a href="functions_0x6d.html#index_m"><span>m</span></a></li> <li><a href="functions_0x6e.html#index_n"><span>n</span></a></li> <li><a href="functions_0x6f.html#index_o"><span>o</span></a></li> <li><a href="functions_0x70.html#index_p"><span>p</span></a></li> <li><a href="functions_0x72.html#index_r"><span>r</span></a></li> <li><a href="functions_0x73.html#index_s"><span>s</span></a></li> <li><a href="functions_0x74.html#index_t"><span>t</span></a></li> <li class="current"><a href="functions_0x75.html#index_u"><span>u</span></a></li> <li><a href="functions_0x76.html#index_v"><span>v</span></a></li> <li><a href="functions_0x77.html#index_w"><span>w</span></a></li> <li><a href="functions_0x78.html#index_x"><span>x</span></a></li> <li><a href="functions_0x7a.html#index_z"><span>z</span></a></li> </ul> </div> </div> <div class="contents"> Here is a list of all class members with links to the classes they belong to: <h3><a class="anchor" id="index_u">- u -</a></h3><ul> <li>UNIQUE : <a class="el" href="classcom_1_1intel_1_1hadoop_1_1graphbuilder_1_1pipeline_1_1output_1_1titan_1_1TitanCommandLineOptions.html#a2b3b842380c2d672ce0af1107cb8ae68">com::intel::hadoop::graphbuilder::pipeline::output::titan::TitanCommandLineOptions</a> </li> <li>updateConfigurationForMapper() : <a class="el" href="interfacecom_1_1intel_1_1hadoop_1_1graphbuilder_1_1pipeline_1_1input_1_1InputConfiguration.html#a3c55b3652544452cf23a87e7c59d7c3c">com::intel::hadoop::graphbuilder::pipeline::input::InputConfiguration</a> </li> <li>updateJobForMapper() : <a class="el" href="interfacecom_1_1intel_1_1hadoop_1_1graphbuilder_1_1pipeline_1_1input_1_1InputConfiguration.html#aef237afe76e81124a0d0c83d46777a0d">com::intel::hadoop::graphbuilder::pipeline::input::InputConfiguration</a> </li> <li>usesHBase() : <a class="el" href="interfacecom_1_1intel_1_1hadoop_1_1graphbuilder_1_1pipeline_1_1input_1_1InputConfiguration.html#a9763d6094f09f379fa063297634f88b7">com::intel::hadoop::graphbuilder::pipeline::input::InputConfiguration</a> </li> </ul> </div> <!--- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&nbsp;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&nbsp;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&nbsp;</span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&nbsp;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&nbsp;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&nbsp;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&nbsp;</span>Enumerations</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <hr size="1"/><address style="text-align: right;"><small>Generated on 26 Dec 2013 for GraphBuilder 2.0 (alpha) by&nbsp; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.6.1 </small></address> </body> </html>
Java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.co.yahoo.dataplatform.mds.hadoop.hive.io.vector; import java.io.IOException; import org.apache.hadoop.hive.ql.exec.vector.DoubleColumnVector; import jp.co.yahoo.dataplatform.schema.objects.PrimitiveObject; public interface IDecimalPrimitiveSetter{ void set( final PrimitiveObject[] primitiveObjectArray , final DoubleColumnVector columnVector , final int index ) throws IOException; }
Java
using System; namespace Benchy.Framework { /// <summary> /// Represents a breakdown of TimeSpan values. /// </summary> public interface IDataBreakout { /// <summary> /// The minimum value of the breakout. /// </summary> TimeSpan RangeMinValue { get; set; } /// <summary> /// The maximum value of the breakout. /// </summary> TimeSpan RangeMaxValue { get; set; } /// <summary> /// The number of items that fit between that breakout. /// </summary> int Occurences { get; set; } /// <summary> /// Represents a way to render it textually. /// </summary> /// <returns>A string representing the Breakout.</returns> string GetText(); } }
Java
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.fileTypes.impl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.ExtensionFileNameMatcher; import com.intellij.openapi.fileTypes.FileNameMatcher; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.util.InvalidDataException; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; final class RemovedMappingTracker { private static final Logger LOG = Logger.getInstance(RemovedMappingTracker.class); static final class RemovedMapping { private final FileNameMatcher myFileNameMatcher; private final String myFileTypeName; private final boolean myApproved; private RemovedMapping(@NotNull FileNameMatcher matcher, @NotNull String fileTypeName, boolean approved) { myFileNameMatcher = matcher; myFileTypeName = fileTypeName; myApproved = approved; } @NotNull FileNameMatcher getFileNameMatcher() { return myFileNameMatcher; } @NotNull String getFileTypeName() { return myFileTypeName; } boolean isApproved() { return myApproved; } @Override public String toString() { return "Removed mapping '" + myFileNameMatcher + "' -> " + myFileTypeName; } // must not look at myApproved @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RemovedMapping mapping = (RemovedMapping)o; if (!myFileNameMatcher.equals(mapping.myFileNameMatcher)) return false; return myFileTypeName.equals(mapping.myFileTypeName); } @Override public int hashCode() { int result = myFileNameMatcher.hashCode(); result = 31 * result + myFileTypeName.hashCode(); return result; } } private final MultiMap<FileNameMatcher, RemovedMapping> myRemovedMappings = new MultiMap<>(); @NonNls private static final String ELEMENT_REMOVED_MAPPING = "removed_mapping"; /** Applied for removed mappings approved by user */ @NonNls private static final String ATTRIBUTE_APPROVED = "approved"; @NonNls private static final String ATTRIBUTE_TYPE = "type"; void clear() { myRemovedMappings.clear(); } @NotNull RemovedMapping add(@NotNull FileNameMatcher matcher, @NotNull String fileTypeName, boolean approved) { RemovedMapping mapping = new RemovedMapping(matcher, fileTypeName, approved); List<RemovedMapping> mappings = (List<RemovedMapping>)myRemovedMappings.getModifiable(matcher); boolean found = false; for (int i = 0; i < mappings.size(); i++) { RemovedMapping removedMapping = mappings.get(i); if (removedMapping.getFileTypeName().equals(fileTypeName)) { mappings.set(i, mapping); found = true; break; } } if (!found) { mappings.add(mapping); } return mapping; } void load(@NotNull Element e) { myRemovedMappings.clear(); List<RemovedMapping> removedMappings = readRemovedMappings(e); Set<RemovedMapping> uniques = new LinkedHashSet<>(removedMappings.size()); for (RemovedMapping mapping : removedMappings) { if (!uniques.add(mapping)) { LOG.warn(new InvalidDataException("Duplicate <removed_mapping> tag for " + mapping)); } } for (RemovedMapping mapping : uniques) { myRemovedMappings.putValue(mapping.myFileNameMatcher, mapping); } } @NotNull static List<RemovedMapping> readRemovedMappings(@NotNull Element e) { List<Element> children = e.getChildren(ELEMENT_REMOVED_MAPPING); if (children.isEmpty()) { return Collections.emptyList(); } List<RemovedMapping> result = new ArrayList<>(); for (Element mapping : children) { String ext = mapping.getAttributeValue(AbstractFileType.ATTRIBUTE_EXT); FileNameMatcher matcher = ext == null ? FileTypeManager.parseFromString(mapping.getAttributeValue(AbstractFileType.ATTRIBUTE_PATTERN)) : new ExtensionFileNameMatcher(ext); boolean approved = Boolean.parseBoolean(mapping.getAttributeValue(ATTRIBUTE_APPROVED)); String fileTypeName = mapping.getAttributeValue(ATTRIBUTE_TYPE); if (fileTypeName == null) continue; RemovedMapping removedMapping = new RemovedMapping(matcher, fileTypeName, approved); result.add(removedMapping); } return result; } void save(@NotNull Element element) { List<RemovedMapping> removedMappings = new ArrayList<>(myRemovedMappings.values()); removedMappings.sort(Comparator.comparing((RemovedMapping mapping) -> mapping.getFileNameMatcher().getPresentableString()).thenComparing(RemovedMapping::getFileTypeName)); for (RemovedMapping mapping : removedMappings) { Element content = writeRemovedMapping(mapping.myFileTypeName, mapping.myFileNameMatcher, true, mapping.myApproved); if (content != null) { element.addContent(content); } } } void saveRemovedMappingsForFileType(@NotNull Element map, @NotNull String fileTypeName, @NotNull Collection<? extends FileNameMatcher> associations, boolean specifyTypeName) { for (FileNameMatcher matcher : associations) { Element content = writeRemovedMapping(fileTypeName, matcher, specifyTypeName, isApproved(matcher, fileTypeName)); if (content != null) { map.addContent(content); } } } boolean hasRemovedMapping(@NotNull FileNameMatcher matcher) { return myRemovedMappings.containsKey(matcher); } private boolean isApproved(@NotNull FileNameMatcher matcher, @NotNull String fileTypeName) { RemovedMapping mapping = ContainerUtil.find(myRemovedMappings.get(matcher), m -> m.getFileTypeName().equals(fileTypeName)); return mapping != null && mapping.isApproved(); } @NotNull List<RemovedMapping> getRemovedMappings() { return new ArrayList<>(myRemovedMappings.values()); } @NotNull List<FileNameMatcher> getMappingsForFileType(@NotNull String fileTypeName) { return myRemovedMappings.values().stream() .filter(mapping -> mapping.myFileTypeName.equals(fileTypeName)) .map(mapping -> mapping.myFileNameMatcher) .collect(Collectors.toList()); } @NotNull List<RemovedMapping> removeIf(@NotNull Predicate<? super RemovedMapping> predicate) { List<RemovedMapping> result = new ArrayList<>(); for (Iterator<Map.Entry<FileNameMatcher, Collection<RemovedMapping>>> iterator = myRemovedMappings.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<FileNameMatcher, Collection<RemovedMapping>> entry = iterator.next(); Collection<RemovedMapping> mappings = entry.getValue(); mappings.removeIf(mapping -> { boolean toRemove = predicate.test(mapping); if (toRemove) { result.add(mapping); } return toRemove; }); if (mappings.isEmpty()) { iterator.remove(); } } return result; } void approveUnapprovedMappings() { for (RemovedMapping mapping : new ArrayList<>(myRemovedMappings.values())) { if (!mapping.isApproved()) { myRemovedMappings.remove(mapping.getFileNameMatcher(), mapping); myRemovedMappings.putValue(mapping.getFileNameMatcher(), new RemovedMapping(mapping.getFileNameMatcher(), mapping.getFileTypeName(), true)); } } } private static Element writeRemovedMapping(@NotNull String fileTypeName, @NotNull FileNameMatcher matcher, boolean specifyTypeName, boolean approved) { Element mapping = new Element(ELEMENT_REMOVED_MAPPING); if (!AbstractFileType.writePattern(matcher, mapping)) { return null; } if (approved) { mapping.setAttribute(ATTRIBUTE_APPROVED, "true"); } if (specifyTypeName) { mapping.setAttribute(ATTRIBUTE_TYPE, fileTypeName); } return mapping; } }
Java
<!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_11) on Fri Apr 30 11:06:46 CST 2010 --> <TITLE> com.siemens.cmiv.avt.mvt.io </TITLE> <META NAME="date" CONTENT="2010-04-30"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="com.siemens.cmiv.avt.mvt.io"; } } </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="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&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;<A HREF="../../../../../../com/siemens/cmiv/avt/mvt/datatype/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../com/siemens/cmiv/avt/mvt/outlier/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?com/siemens/cmiv/avt/mvt/io/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.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> <H2> Package com.siemens.cmiv.avt.mvt.io </H2> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Interface Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../com/siemens/cmiv/avt/mvt/io/SubjectList.html" title="interface in com.siemens.cmiv.avt.mvt.io">SubjectList</A></B></TD> <TD>&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../com/siemens/cmiv/avt/mvt/io/SubjectListFactory.html" title="class in com.siemens.cmiv.avt.mvt.io">SubjectListFactory</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../com/siemens/cmiv/avt/mvt/io/SubjectListXml.html" title="class in com.siemens.cmiv.avt.mvt.io">SubjectListXml</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../com/siemens/cmiv/avt/mvt/io/XMLComputationList.html" title="class in com.siemens.cmiv.avt.mvt.io">XMLComputationList</A></B></TD> <TD>Parses XML document.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../com/siemens/cmiv/avt/mvt/io/XMLMeasurement.html" title="class in com.siemens.cmiv.avt.mvt.io">XMLMeasurement</A></B></TD> <TD>Parses XML document.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../com/siemens/cmiv/avt/mvt/io/XMLSubjectList.html" title="class in com.siemens.cmiv.avt.mvt.io">XMLSubjectList</A></B></TD> <TD>Parses XML document.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../com/siemens/cmiv/avt/mvt/io/XMLSubjectListImpl.html" title="class in com.siemens.cmiv.avt.mvt.io">XMLSubjectListImpl</A></B></TD> <TD>Parses XML document.</TD> </TR> </TABLE> &nbsp; <P> <DL> </DL> <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="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&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;<A HREF="../../../../../../com/siemens/cmiv/avt/mvt/datatype/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../com/siemens/cmiv/avt/mvt/outlier/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?com/siemens/cmiv/avt/mvt/io/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.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>
Java
{% extends "soc/models/edit.html" %} {% comment %} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. {% endcomment %} {% load forms_helpers %} {% block scripts %} {{ block.super }} {% if gmaps_api_key %} <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key={{ gmaps_api_key }}" type="text/javascript"></script> <script type="text/javascript" src="/soc/content/js/map-090420.js"></script> {% endif %} {% endblock %} {% block body_tag %} {% if gmaps_api_key %} <body onLoad="role_profile_gmap.map_load()" onunload="GUnload()"> {% else %} {{ block.super }} {% endif %} {% endblock %} {% block instructions %} {{ block.super }} {% if not gmaps_api_key %} <br /><span class="error">Google Maps API key not present. Please insert your key in <a href="/site/edit">Site Settings</a>, Google Maps field. </span> {% endif %} {% endblock %} {% block form_table %} {{ block.super }} {% if gmaps_api_key %} <tr title="your location"> <td class="formfieldlabel"> <label for="id_location">Location:</label> </td> <td> <div id="role_profile_map"></div> </td> <td></td> <td></td> <td></td> </tr> {% endif %} {% endblock %}
Java
# Phoma capreae (DC.) Höhn., 1917 SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name Sphaeria capreae DC., 1815 ### Remarks null
Java
# -*- coding: utf-8 -*- # Copyright 2014, 2015 Metaswitch Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ felix.test.stub_utils ~~~~~~~~~~~~ Test utilities. """ import logging import random from collections import namedtuple CommandOutput = namedtuple('CommandOutput', ['stdout', 'stderr']) # Logger log = logging.getLogger(__name__) # The current time. test_time = 0 def set_time(value): global test_time test_time = value log.debug("Time now set to : %d" % test_time) def get_time(): return test_time def get_mac(): """ Gets a random mac address. """ mac = ("%02x:%02x:%02x:%02x:%02x:%02x" % (random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff))) return mac # Exception raised when tests reach the end. class TestOverException(Exception): pass
Java
/******************************************************************************* * Copyright [2016] [Quirino Brizi (quirino.brizi@gmail.com)] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package org.actio.modeler.domain.repository; import java.util.List; import org.actio.commons.message.model.ModelMessage; /** * @author quirino.brizi * */ public interface ModelRepository { ModelMessage add(ModelMessage model); List<ModelMessage> getAllModels(); ModelMessage getModel(String modelKey); }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.scheduler.declarative.allocator; import org.apache.flink.runtime.clusterframework.types.AllocationID; import org.apache.flink.runtime.clusterframework.types.ResourceProfile; import org.apache.flink.runtime.jobmaster.SlotInfo; import org.apache.flink.runtime.taskmanager.LocalTaskManagerLocation; import org.apache.flink.runtime.taskmanager.TaskManagerLocation; /** Test {@link SlotInfo} implementation. */ class TestSlotInfo implements SlotInfo { private final AllocationID allocationId = new AllocationID(); @Override public AllocationID getAllocationId() { return allocationId; } @Override public TaskManagerLocation getTaskManagerLocation() { return new LocalTaskManagerLocation(); } @Override public int getPhysicalSlotNumber() { return 0; } @Override public ResourceProfile getResourceProfile() { return ResourceProfile.ANY; } @Override public boolean willBeOccupiedIndefinitely() { return false; } }
Java
<?php include("inc_header.php"); ?> <?php include("inc_lang_detect.php"); ?> <!-- Inner Page 4404 Error --> <div class="container"> <div class="inner-error"> <h3><strong>HTTP 404<strong></h3> <?php if (getDefaultLanguage() == "pt-br") { ?> <h3 >Objeto n&atilde;o encontrado!</h3> <p>A URL requisitada n&atilde;o foi encontrada neste servidor.</p> <p>Se o endere&ccedil;o (URL) foi digitado manualmente, pedimos a gentileza de verificar novamente a sintaxe do endere&ccedil;o.</p> <?php } else { ?> <h3 >Object not found!</h3> <p>The requested URL was not found on this server.</p> <p>If you entered the URL manually please check your spelling and try again.</p> <?php } ?> </div> </div> </div> <!-- Inner Page Content End --> <?php include("inc_footer.php"); ?>
Java
# Sarcodia platycarpa Harvey ex Grunow SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package beans; import java.io.Serializable; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * * @author Chema */ @Component public class Persona implements Serializable { @Value("#{p.nombre}") private String nombre; @Value("#{p.apellido}") private String apellido; public Persona() { } public Persona(String nombre, String apellido) { this.nombre = nombre; this.apellido = apellido; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } }
Java
# Carex tristis M.Bieb. SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Fl. taur. -caucas. 3:615. 1819 #### Original name null ### Remarks null
Java
import { Component } from '@angular/core'; import {ROUTER_DIRECTIVES, RouteData} from '@angular/router-deprecated'; import {TravelFormComponent} from "./travel-form.component"; import {NavbarComponent} from '../../shared/index'; @Component({ selector: "home", templateUrl: 'app/home/components/home.component.html', styleUrls: ['app/home/components/home.component.css'], directives: [ROUTER_DIRECTIVES, TravelFormComponent, NavbarComponent] }) export class HomeComponent{ signInOnly: boolean; constructor(private _data: RouteData) { //when arriving directly from /login URL this.signInOnly = this._data.get('signInOnly') || true; // set default to false to re-activate the destination form } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package delsh.livy; /** * The enumeration types for session kind. */ public enum SessionKind { // Possible values are the following. SPARK("spark"), PYSPARK("pyspark"), SPARKR("sparkr"); private String kind; private SessionKind(String skind) { kind = skind; } public String toString() { return kind; } /** * This class finds enum value that is equivalent to a given string. * @param kind Session kind. * @return Enum value */ public static SessionKind getEnum(String str) { SessionKind[] array = SessionKind.values(); for(SessionKind enumStr : array) { if(str.equals(enumStr.kind.toString())) { return enumStr; } } return null; } }
Java
package com.openthinks.libs.utilities.lookup; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import com.openthinks.libs.utilities.Checker; import com.openthinks.libs.utilities.InstanceUtilities; import com.openthinks.libs.utilities.InstanceUtilities.InstanceWrapper; import com.openthinks.libs.utilities.exception.CheckerNoPassException; import com.openthinks.libs.utilities.pools.object.ObjectPool; /** * ClassName: LookupPool <br> * Function: It is used for store shared object instances and find other SPI<br> * Reason: follow the design pattern of fly weight to reduce instantiate new object. <br> * Notice: avoid store or find those object which include its own state and will be changed;<br> * Usage:<br> * * <pre> * <code> * //get gloabl instance of LookupPool * LookupPool lookupPool = LookupPools.gloabl(); * * //get a named instance of LookupPool * lookupPool = LookupPools.get("pool-1"); * * // instance by class directly * LookupInterfaceImpl instanceImpl1 = lookupPool.lookup(LookupInterfaceImpl.class); * * // instance by customized implementation class * LookupInterface instanceImpl2 = lookupPool.lookup(LookupInterface.class,InstanceWrapper.build(LookupInterfaceImpl.class)); * * // lookup shared object already existed * LookupInterface instanceImpl3 = lookupPool.lookup(LookupInterface.class); * assert instanceImpl2==instanceImpl3 ; * * // register a shared object by name * lookupPool.register("beanName1",instanceImpl1); * // lookup shared object by name * LookupInterface instanceImpl4 = lookupPool.lookup("beanName1"); * * assert instanceImpl1==instanceImpl4 ; * * // clear all shared objects and mappings * lookupPool.cleanUp(); * * </code> * </pre> * * date: Sep 8, 2017 3:15:29 PM <br> * * @author dailey.yet@outlook.com * @version 1.0 * @since JDK 1.8 */ public abstract class LookupPool { protected final ObjectPool objectPool; protected final ReadWriteLock lock; public abstract String name(); protected LookupPool() { objectPool = new ObjectPool(); lock = new ReentrantReadWriteLock(); } /** * lookup a object by its type, if not find firstly, try to instance by instanceType and * constructor parameters args * * @param <T> lookup object type * @param type Class lookup key type * @param args Object[] instance constructor parameters * @return T lookup object or null */ public <T> T lookup(Class<T> type, Object... args) { return lookup(type, null, args); } /** * lookup a object by its type, if not find firstly, try to instance by instanceType and * constructor parameters args * * @param <T> lookup object type * @param <E> lookup object type * @param searchType Class lookup key type * @param instancewrapper Class instance type when not lookup the key * @param args Object[] instance constructor parameters * @return T lookup object or null */ public <T, E extends T> T lookup(final Class<T> searchType, InstanceWrapper<E> instancewrapper, Object... args) { T object = null; lock.readLock().lock(); try { object = objectPool.get(searchType); } finally { lock.readLock().unlock(); } if (object == null) { lock.writeLock().lock(); try { object = InstanceUtilities.create(searchType, instancewrapper, args); register(searchType, object); } finally { lock.writeLock().unlock(); } } return object; } /** * look up object by its bean name * * @param <T> lookup object type * @param beanName String lookup object mapping name * @return T lookup object or null */ public <T> T lookup(String beanName) { lock.readLock().lock(); try { return objectPool.get(beanName); } finally { lock.readLock().unlock(); } } /** * lookup a optional object by its type, if not find firstly, try to instance by instanceType and * constructor parameters args * * @param <T> lookup object type * @param type Class lookup key type * @param args Object[] instance constructor parameters * @return Optional of lookup object */ public <T> Optional<T> lookupIf(Class<T> type, Object... args) { return Optional.ofNullable(lookup(type, args)); } /** * lookup a optional object by its type, if not find firstly, try to instance by instanceType and * constructor parameters args * * @param <T> lookup object type * @param <E> lookup object type * @param searchType Class lookup key type * @param instancewrapper Class instance type when not lookup the key * @param args Object[] instance constructor parameters * @return Optional of lookup object */ public <T, E extends T> Optional<T> lookupIf(final Class<T> searchType, InstanceWrapper<E> instancewrapper, Object... args) { return Optional.ofNullable(lookup(searchType, instancewrapper, args)); } /** * look up optional object by its bean name * * @param <T> lookup object type * @param beanName String lookup object mapping name * @return Optional of lookup object */ public <T> Optional<T> lookupIf(String beanName) { return Optional.ofNullable(lookup(beanName)); } /** * * lookupSPI:this will used {@link ServiceLoader} to load SPI which defined in folder * <B>META-INF/services</B>. <br> * It will first to try to load instance from cached {@link ObjectPool}, if not found, then try to * load SPI class and instantiate it.<br> * Notice: only load and instantiate first SPI class in defined file<br> * * @param <T> lookup SPI interface class * @param spiInterface SPI interface or abstract class type * @param args constructor arguments * @return implementation of parameter spiInterface */ public <T> T lookupSPI(Class<T> spiInterface, Object... args) { return lookupFocusSPI(spiInterface, null, args); } /** * * lookupFocusSPI:this will used {@link ServiceLoader} to load SPI which defined in folder * <B>META-INF/services</B>. <br> * It will first to try to load instance from cached {@link ObjectPool}, if not found, then try to * load SPI class and instantiate it.<br> * Notice: only load and instantiate focused SPI class in defined file<br> * * @param <T> lookup SPI interface class * @param spiInterface SPI interface or abstract class type * @param focusClassName focused SPI implementation class aname * @param args constructor arguments * @return implementation of parameter spiInterface * */ public <T> T lookupFocusSPI(Class<T> spiInterface, String focusClassName, Object... args) { T object = null; lock.readLock().lock(); try { object = objectPool.get(spiInterface); } finally { lock.readLock().unlock(); } if (object == null) { lock.writeLock().lock(); try { ServiceLoader<T> serviceLoader = ServiceLoader.load(spiInterface, focusClassName, args); object = serviceLoader.iterator().next(); Checker.require(object).notNull("Cannot found SPI implementation for " + spiInterface); register(spiInterface, object); } finally { lock.writeLock().unlock(); } } return object; } /** * * lookupSPISkipCache:this will used {@link ServiceLoader} to load SPI which defined in folder * <B>META-INF/services</B>. <br> * It will do load SPI skip cache each time, not try to lookup from cache firstly.<br> * Notice: only load and instantiate first SPI class in defined file<br> * * @param <T> lookup SPI interface class * @param spiInterface SPI interface or abstract class type * @param args constructor arguments * @return implementation of parameter spiInterface * @throws CheckerNoPassException when not found implementation SPI */ public <T> T lookupSPISkipCache(Class<T> spiInterface, Object... args) { return lookupFocusSPISkipCache(spiInterface, null, args); } /** * * lookupFocusSPISkipCache:this will used {@link ServiceLoader} to load SPI which defined in * folder <B>META-INF/services</B>. <br> * It will do load SPI skip cache each time, not try to lookup from cache firstly.<br> * Notice: only load and instantiate focused SPI class in defined file<br> * * @param <T> lookup SPI interface class * @param spiInterface SPI interface or abstract class type * @param focusClassName focused SPI implementation class name * @param args constructor arguments * @return implementation of parameter spiInterface * * @throws CheckerNoPassException when not found implementation SPI */ public <T> T lookupFocusSPISkipCache(Class<T> spiInterface, String focusClassName, Object... args) { T object = null; ServiceLoader<T> serviceLoader = ServiceLoader.load(spiInterface, focusClassName, args); object = serviceLoader.iterator().next(); Checker.require(object).notNull("Cannot found SPI implementation for " + spiInterface); return object; } /** * * lookupAllSPI:fina all instance of SPI implementation. <br> * Notice:<BR> * <ul> * <li>all implementation need default constructor.</li> * <li>do not search from cache</li> * </ul> * * @param <T> SPI type * @param spiInterface SPI interface or abstract class type * @return list of all SPI implementation instance */ public <T> List<T> lookupAllSPI(Class<T> spiInterface) { List<T> list = new ArrayList<>(); ServiceLoader<T> serviceLoader = ServiceLoader.load(spiInterface); Iterator<T> iterator = serviceLoader.iterator(); while (iterator.hasNext()) { try { list.add(iterator.next()); } catch (Exception e) { // ignore } } return list; } /** * * register an instance, which key is object.getClass(). <br> * * @param <T> registered object class type * @param object instance which need registered */ public <T> void register(T object) { if (object != null) { lock.writeLock().tryLock(); try { objectPool.put(object.getClass(), object); } finally { lock.writeLock().unlock(); } } } /** * register an instance, which key is given parameter classType * * @param <T> registered object class type * @param classType Class as the key for registered instance * @param object instance which need registered */ public <T> void register(Class<T> classType, T object) { if (object != null) { lock.writeLock().tryLock(); try { objectPool.put(classType, object); } finally { lock.writeLock().unlock(); } } } /** * register object and mapping it to given bean name * * @param <T> register object type * @param beanName String bean name * @param object register object */ public <T> void register(String beanName, T object) { if (object != null) { lock.writeLock().lock(); try { objectPool.put(beanName, object); } finally { lock.writeLock().unlock(); } } } protected void cleanUp() { lock.writeLock().lock(); try { objectPool.cleanUp(); } finally { lock.writeLock().unlock(); } } }
Java
package com.arges.sepan.argmusicplayer.Callbacks; import com.arges.sepan.argmusicplayer.Models.ArgAudio; //Interfaces public interface OnPreparedListener { void onPrepared(ArgAudio audio, int duration); }
Java
package io.monocycle.agent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; @Configuration @EnableAutoConfiguration @ComponentScan @EnableAsync @EnableScheduling public class AgentApplication { private static final Logger LOGGER = LoggerFactory.getLogger(AgentApplication.class); public static void main(String[] args) { LOGGER.debug("Starting Monocycle Agent..."); SpringApplication.run(AgentApplication.class, args); } }
Java
#device-check, #landing-device-check { background: #000000; } /****** landing start ******/ .landing-logo-container { width: 100%; height: 140px; margin: 0 auto 10px auto; padding-top: 15px; background: rgba(0, 0, 0, 0.5); } .landing-logo { width: 130px; height: 125px; } .landing-social-container { position: absolute; display: inline-block; width: 100%; margin: 0 auto; padding: 0 0 20px 0; bottom: 0; left: 0; text-align: center; } .landing-social-container input { height: 40px; font-size: 0.6em; font-weight: 300; padding-left: 10px; padding-right: 30px; width: 250px; text-align: center; border: none; background: rgba(0, 0, 0, 0.5); } .landing-social-container > img { display: inline-block; height: 34px; width: 30px; padding: 3px 5px; margin-left: -45px; vertical-align: bottom; cursor: pointer; background: rgba(0, 0, 0, 0.5); opacity: 0.5; } .landing-social-container > img:hover { opacity: 1; } .landing-social-container > a > img.social-icon { width: 50px; height: 50px; margin: 15px 5px 0 5px; opacity: 0.3; } .landing-social-container > a > img.social-icon:hover { opacity: 1; } /****** landing end ******/ .container { width: 100%; } .container > .logo-container > input { width: 60%; height: 50px; margin-top: 8px; } .container > .logo-container .withLeftMargin { margin-left: 5%; } nav, nav > ul, nav > ul > li { height: 50px; } nav > ul > li { padding-top: 30px; } nav > ul > li > img { width: 25px; height: 25px; } nav > ul > li.special > img { width: 32px; height: 23px; margin-top: 2px; } .container > section.page-container { height: 350px; padding-top: 30px; } .container > button { height: 70px; } .container > button > img { width: 40px; height: 30px; margin-top: 5px; } /* info page */ div#page4 #address-icon { margin-top: 25px; } div#page4 hr { margin-bottom: 10px; } div#page4 input { width: 60%; font-size: 0.8em; }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file mkldnn_batch_norm.cc * \brief * \author Tao Lv */ #ifndef MXNET_OPERATOR_NN_MKLDNN_MKLDNN_BATCH_NORM_INL_H_ #define MXNET_OPERATOR_NN_MKLDNN_MKLDNN_BATCH_NORM_INL_H_ #if MXNET_USE_MKLDNN == 1 #include <vector> #include <utility> #include <mkldnn.hpp> #include "../batch_norm-inl.h" #include "./mkldnn_ops-inl.h" #include "./mkldnn_base-inl.h" #define VARIANCE_TO_INVSTD(__var$, __eps$) (1.0/sqrt((__var$) + DType(__eps$))) #define INVSTD_TO_VARIANCE(__invstd$, __eps$) ((1.0 / ((__invstd$) * (__invstd$))) - (__eps$)) namespace mxnet { namespace op { typedef mkldnn::batch_normalization_forward::primitive_desc t_bn_f_pdesc; typedef mkldnn::batch_normalization_forward::desc t_bn_f_desc; typedef mkldnn::batch_normalization_backward::primitive_desc t_bn_b_pdesc; typedef mkldnn::batch_normalization_backward::desc t_bn_b_desc; using mkldnn::use_global_stats; using mkldnn::use_scale_shift; using mkldnn::forward_training; using mkldnn::forward_inference; inline static unsigned _GetFlags(const std::vector<NDArray> &in_data, const std::vector<NDArray> &aux_states, const BatchNormParam &param, bool is_train) { unsigned flags = 0U; if (in_data.size() == 3U) { flags |= use_scale_shift; } // aux_states[0]: inMean // aux_states[1]: inVariance if (aux_states.size() == 2U && !is_train) { flags |= use_global_stats; } return flags; } template <typename DType> inline static t_bn_f_pdesc _GetFwd(const mkldnn::memory &data_mem, bool is_train, DType eps, unsigned flags) { auto data_mpd = data_mem.get_primitive_desc(); auto data_md = data_mpd.desc(); auto engine = CpuEngine::Get()->get_engine(); if (is_train) { t_bn_f_desc bnFwd_desc(forward_training, data_md, eps, flags); return t_bn_f_pdesc(bnFwd_desc, engine); } else { t_bn_f_desc bnFwd_desc(forward_inference, data_md, eps, flags); return t_bn_f_pdesc(bnFwd_desc, engine); } } template <typename DType> inline static t_bn_b_pdesc _GetBwd(const mkldnn::memory &data_mem, const mkldnn::memory &diff_mem, DType eps, unsigned flags) { auto data_mpd = data_mem.get_primitive_desc(); auto data_md = data_mpd.desc(); auto diff_mpd = diff_mem.get_primitive_desc(); auto diff_md = diff_mpd.desc(); auto engine = CpuEngine::Get()->get_engine(); t_bn_b_desc bnBwd_desc(mkldnn::prop_kind::backward, diff_md, data_md, eps, flags); return t_bn_b_pdesc(bnBwd_desc, engine, _GetFwd(data_mem, true, eps, flags)); } typedef ParamOpSign<BatchNormParam> MKLDNNBNSignature; class MKLDNNBNForward { std::shared_ptr<const mkldnn::memory> data_m; std::shared_ptr<const mkldnn::memory> weight_m; std::shared_ptr<const mkldnn::memory> out_m; std::shared_ptr<const mkldnn::memory> mean_m; std::shared_ptr<const mkldnn::memory> var_m; std::shared_ptr<mkldnn::batch_normalization_forward> fwd; bool is_train; t_bn_f_pdesc pd; public: MKLDNNBNForward(const t_bn_f_pdesc &_pd, bool is_train): pd(_pd) { weight_m.reset(new mkldnn::memory(pd.weights_primitive_desc())); this->is_train = is_train; } const mkldnn::memory &GetWeight() const { return *weight_m; } const t_bn_f_pdesc &GetPd() const { return pd; } const mkldnn::memory &GetMean() const { return *mean_m; } const mkldnn::memory &GetVar() const { return *var_m; } void SetDataHandle(const NDArray &data, const NDArray &mean, const NDArray &var, const mkldnn::memory &out) { auto _data = data.GetMKLDNNData(); if (data_m) { data_m->set_data_handle(_data->get_data_handle()); } else { data_m.reset(new mkldnn::memory(_data->get_primitive_desc(), _data->get_data_handle())); } if (out_m) { out_m->set_data_handle(out.get_data_handle()); } else { out_m.reset(new mkldnn::memory(out.get_primitive_desc(), out.get_data_handle())); } auto mean_ptr = mean.data().dptr_; if (mean_m) { mean_m->set_data_handle(mean_ptr); } else { mean_m.reset(new mkldnn::memory(pd.mean_primitive_desc(), mean_ptr)); } auto var_ptr = var.data().dptr_; if (var_m) { var_m->set_data_handle(var_ptr); } else { var_m.reset(new mkldnn::memory(pd.variance_primitive_desc(), var_ptr)); } if (fwd == nullptr) { if (!is_train) fwd.reset(new mkldnn::batch_normalization_forward( pd, *data_m, mkldnn::primitive::at(*mean_m), mkldnn::primitive::at(*var_m), *weight_m, *out_m)); else fwd.reset(new mkldnn::batch_normalization_forward( pd, mkldnn::primitive::at(*data_m), mkldnn::primitive::at(*weight_m), *out_m, *mean_m, *var_m)); } } const mkldnn::batch_normalization_forward &GetFwd() const { return *fwd; } }; template<typename DType> static MKLDNNBNForward &GetBNForward(const BatchNormParam& param, const OpContext &ctx, const NDArray &in_data, unsigned flags) { static thread_local std::unordered_map<MKLDNNBNSignature, MKLDNNBNForward, OpHash> fwds; MKLDNNBNSignature key(param); key.AddSign(ctx.is_train); key.AddSign(in_data); auto it = fwds.find(key); if (it == fwds.end()) { auto fwd_pd = _GetFwd(*in_data.GetMKLDNNData(), ctx.is_train, (DType) param.eps, flags); MKLDNNBNForward fwd(fwd_pd, ctx.is_train); auto ins_ret = fwds.insert(std::pair<MKLDNNBNSignature, MKLDNNBNForward>( key, fwd)); CHECK(ins_ret.second); it = ins_ret.first; } return it->second; } template <typename DType> void MKLDNNBatchNormForward(const OpContext &ctx, const BatchNormParam &param, const std::vector<NDArray> &in_data, const std::vector<OpReqType> &req, const std::vector<NDArray> &out_data, const std::vector<NDArray> &aux_states) { TmpMemMgr::Get()->Init(ctx.requested[batchnorm::kTempSpace]); unsigned flags = _GetFlags(in_data, aux_states, param, ctx.is_train); const NDArray &data = in_data[batchnorm::kData]; auto &fwd = GetBNForward<DType>(param, ctx, data, flags); const NDArray &out = out_data[batchnorm::kOut]; // for output memory auto out_mem = const_cast<NDArray &>(out).CreateMKLDNNData(fwd.GetPd().dst_primitive_desc()); // mxnet will always use scale shift. // But if fix_gamma is true, then all scale elements will be set to 1.0f if (flags & use_scale_shift) { const NDArray &gamma = in_data[batchnorm::kGamma]; const NDArray &beta = in_data[batchnorm::kBeta]; CHECK_EQ(gamma.storage_type(), mxnet::kDefaultStorage); CHECK_EQ(beta.storage_type(), mxnet::kDefaultStorage); const mkldnn::memory &weight_mem = fwd.GetWeight(); DType* weight_buf = reinterpret_cast<DType *>(weight_mem.get_data_handle()); nnvm::dim_t channels_ = data.shape()[1]; CHECK(weight_mem.get_primitive_desc().get_size() == channels_ * sizeof(DType) * 2); DType* weight_ptr = gamma.data().dptr<DType>(); DType* bias_ptr = beta.data().dptr<DType>(); if (!param.fix_gamma) { #pragma omp parallel for for (int i = 0; i < channels_; i++) { weight_buf[i] = weight_ptr[i]; weight_buf[channels_ + i] = bias_ptr[i]; // bias } } else if (IsBNWriting(req[batchnorm::kGamma])) { #pragma omp parallel for for (int i = 0; i < channels_; i++) { weight_buf[i] = (DType)1.0f; weight_ptr[i] = (DType)1.0f; weight_buf[channels_ + i] = bias_ptr[i]; // bias } } else { #pragma omp parallel for for (int i = 0; i < channels_; i++) { weight_buf[i] = (DType)1.0f; weight_buf[channels_ + i] = bias_ptr[i]; // bias } } if (!ctx.is_train) { DType* omean = out_data[batchnorm::kMean].data().dptr<DType>(); DType* ovar = out_data[batchnorm::kVar].data().dptr<DType>(); DType* inmean = aux_states[batchnorm::kMovingMean].data().dptr<DType>(); DType* invar = aux_states[batchnorm::kMovingVar].data().dptr<DType>(); // to align with origin implmentation: batch_norm.cc: L164 #pragma omp parallel for for (int i = 0; i < channels_; i++) { omean[i] = inmean[i]; ovar[i] = VARIANCE_TO_INVSTD(invar[i], param.eps); } fwd.SetDataHandle(data, aux_states[batchnorm::kMovingMean], aux_states[batchnorm::kMovingVar], *out_mem); MKLDNNStream::Get()->RegisterPrim(fwd.GetFwd()); MKLDNNStream::Get()->Submit(); } else { // training const NDArray &outMean = out_data[batchnorm::kMean]; const NDArray &outVar = out_data[batchnorm::kVar]; DType* omean = outMean.data().dptr<DType>(); DType* ovar = outVar.data().dptr<DType>(); fwd.SetDataHandle(data, outMean, outVar, *out_mem); MKLDNNStream::Get()->RegisterPrim(fwd.GetFwd()); MKLDNNStream::Get()->Submit(); DType* mean_mem_ptr = reinterpret_cast<DType*>(fwd.GetMean().get_data_handle()); DType* var_mem_ptr = reinterpret_cast<DType*>(fwd.GetVar().get_data_handle()); #pragma omp parallel for for (int i = 0; i < channels_; i++) { omean[i] = mean_mem_ptr[i]; ovar[i] = VARIANCE_TO_INVSTD(var_mem_ptr[i], param.eps); } } } else { // no input gamma and beta LOG(FATAL) << "MKLDNN batch normalization: should not reach here ..."; } } template <typename DType> void MKLDNNBatchNormBackward(const OpContext &ctx, const BatchNormParam &param, const std::vector<NDArray> &out_grad, const std::vector<NDArray> &in_data, const std::vector<NDArray> &out_data, const std::vector<OpReqType> &req, const std::vector<NDArray> &in_grad, const std::vector<NDArray> &aux_states) { TmpMemMgr::Get()->Init(ctx.requested[batchnorm::kTempSpace]); CHECK_EQ(out_grad.size(), 1U); CHECK_EQ(in_data.size(), 3U); CHECK_EQ(out_data.size(), 3U); CHECK_EQ(in_grad.size(), 3U); unsigned flags = _GetFlags(in_data, aux_states, param, ctx.is_train); const NDArray &data = in_data[batchnorm::kData]; const NDArray &diff = out_grad[batchnorm::kOut]; const NDArray &gradIn = in_grad[batchnorm::kData]; const NDArray &moving_mean = aux_states[batchnorm::kMovingMean]; const NDArray &moving_var = aux_states[batchnorm::kMovingVar]; const NDArray &out_mean = out_data[batchnorm::kMean]; const NDArray &out_var = out_data[batchnorm::kVar]; CHECK(out_mean.IsDefaultData()); CHECK(out_var.IsDefaultData()); CHECK(moving_mean.IsDefaultData()); CHECK(moving_var.IsDefaultData()); auto data_mem = data.GetMKLDNNData(); auto diff_mem = diff.GetMKLDNNData(); // MKLDNN batchnorm should run on special layouts. If one of them isn't, we // should reorder them. if (data.IsDefaultData()) data_mem = data.GetMKLDNNDataReorder(diff_mem->get_primitive_desc()); else if (diff.IsDefaultData()) diff_mem = diff.GetMKLDNNDataReorder(data_mem->get_primitive_desc()); auto bwd_pd = _GetBwd(*data_mem, *diff_mem, param.eps, flags); auto gradi_mem = const_cast<NDArray &>(gradIn).CreateMKLDNNData(data_mem->get_primitive_desc()); if (flags & use_scale_shift) { const NDArray &gamma = in_data[batchnorm::kGamma]; const NDArray &beta = in_data[batchnorm::kBeta]; // TODO(tao): how to reuse this memory? std::shared_ptr<const mkldnn::memory> weight_mem( new mkldnn::memory(bwd_pd.weights_primitive_desc())); DType* weight_buf = reinterpret_cast<DType *>(weight_mem->get_data_handle()); nnvm::dim_t channels_ = data.shape()[1]; for (int i = 0; i < channels_; i++) { if (!param.fix_gamma) weight_buf[i] = (gamma.data().dptr<DType>())[i]; // weight else weight_buf[i] = (DType)1.0f; } for (int i = 0; i < channels_; i++) { weight_buf[channels_ + i] = (beta.data().dptr<DType>())[i]; // bias } std::shared_ptr<const mkldnn::memory> gradw_mem( new mkldnn::memory(bwd_pd.diff_weights_primitive_desc())); // training but no input mean and variance if (ctx.is_train && !param.use_global_stats) { DType* moving_mean_ptr = reinterpret_cast<DType *>(moving_mean.data().dptr<DType>()); DType* moving_var_ptr = reinterpret_cast<DType *>(moving_var.data().dptr<DType>()); DType* out_mean_ptr = reinterpret_cast<DType *>(out_mean.data().dptr<DType>()); DType* out_var_ptr = reinterpret_cast<DType *>(out_var.data().dptr<DType>()); mkldnn::memory var_mem(bwd_pd.variance_primitive_desc()); DType *tmp_var_ptr = reinterpret_cast<DType *>(var_mem.get_data_handle()); DType minus_mom = (1.0f - param.momentum); for (int i = 0; i < channels_; i++) { moving_mean_ptr[i] = moving_mean_ptr[i] * param.momentum + out_mean_ptr[i] * minus_mom; float variance = INVSTD_TO_VARIANCE(out_var_ptr[i], param.eps); tmp_var_ptr[i] = variance; moving_var_ptr[i] = moving_var_ptr[i] * param.momentum + variance * minus_mom; } std::shared_ptr<const mkldnn::memory> out_mean_mem( new mkldnn::memory(bwd_pd.mean_primitive_desc(), out_mean_ptr)); std::shared_ptr<const mkldnn::memory> out_var_mem( new mkldnn::memory(bwd_pd.variance_primitive_desc(), out_var_ptr)); auto bn_bwd = mkldnn::batch_normalization_backward(bwd_pd, *data_mem, mkldnn::primitive::at(*out_mean_mem), mkldnn::primitive::at(var_mem), *diff_mem, *weight_mem, *gradi_mem, *gradw_mem); MKLDNNStream::Get()->RegisterPrim(bn_bwd); MKLDNNStream::Get()->Submit(); } else { std::shared_ptr<const mkldnn::memory> imean_mem( new mkldnn::memory(bwd_pd.mean_primitive_desc(), moving_mean.data().dptr<DType>())); std::shared_ptr<const mkldnn::memory> ivar_mem( new mkldnn::memory(bwd_pd.variance_primitive_desc(), moving_var.data().dptr<DType>())); auto bn_bwd = mkldnn::batch_normalization_backward(bwd_pd, *data_mem, mkldnn::primitive::at(*imean_mem), mkldnn::primitive::at(*ivar_mem), *diff_mem, *weight_mem, *gradi_mem, *gradw_mem); MKLDNNStream::Get()->RegisterPrim(bn_bwd); MKLDNNStream::Get()->Submit(); } // copy data from gradw_mem to in_grad[1] and in_grad[2] DType* gw_buf = reinterpret_cast<DType *>(gradw_mem->get_data_handle()); for (int i = 0; i < channels_; i++) { if (!param.fix_gamma) (in_grad[1].data().dptr<DType>())[i] = gw_buf[i]; else (in_grad[1].data().dptr<DType>())[i] = 0.0f; } for (int i = 0; i < channels_; i++) { (in_grad[2].data().dptr<DType>())[i] = gw_buf[i + channels_]; } } else { LOG(FATAL) << "MKLDNN batch normalization backward: should not reach here ..."; } } } // namespace op } // namespace mxnet #endif // MXNET_USE_MKLDNN #endif // MXNET_OPERATOR_NN_MKLDNN_MKLDNN_BATCH_NORM_INL_H_
Java
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.239 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.App.My.MySettings Get Return Global.App.My.MySettings.Default End Get End Property End Module End Namespace
Java
/* * Copyright 2014 Waratek Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.waratek.spiracle.sql.servlet.oracle; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.waratek.spiracle.sql.servlet.util.ParameterNullFix; import com.waratek.spiracle.sql.util.SelectUtil; /** * Servlet implementation class Get_string_no_quote */ @WebServlet({"/Get_string_no_quote", "/MsSql_Get_string_no_quote", "/MySql_Get_string_no_quote"}) public class Get_string_no_quote extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Get_string_no_quote() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { executeRequest(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { executeRequest(request, response); } private void executeRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { ServletContext application = this.getServletConfig().getServletContext(); List<String> queryStringList = new ArrayList<String>(); queryStringList.add("name"); Map<String, String> nullSanitizedMap = ParameterNullFix.sanitizeNull(queryStringList, request); String name = nullSanitizedMap.get("name"); String sql = "SELECT * FROM users WHERE name = " + name; Boolean showErrors = true; Boolean allResults = true; Boolean showOutput = true; SelectUtil.executeQuery(sql, application, request, response, showErrors, allResults, showOutput); } }
Java
module.exports = function(fancyRequire) { fancyRequire('merchant_row'); };
Java
package fr.xebia.unittestwithdagger; import android.widget.TextView; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import fr.xebia.unittestwithdagger.internal.CustomRobolectricTestRunner; import static junit.framework.Assert.assertEquals; import static org.mockito.BDDMockito.given; /** * Created by florentchampigny on 12/11/2015. */ @RunWith(CustomRobolectricTestRunner.class) @Config(application = MyTestApplication.class, constants = BuildConfig.class, sdk=21) public class UserActivityTest { UserActivity activity; UserStorage userStorage; @Before public void setUp() throws Exception { activity = Robolectric.buildActivity(UserActivity.class).create().get(); userStorage = MyApplication.get().component().userStorage(); } @Test public void displayLoggedUserShoulDisplayFlorent(){ given(userStorage.loadUser()).willReturn(new User("florent")); TextView textView = (TextView)activity.findViewById(R.id.text); activity.displayLoggedUser(); assertEquals("florent", textView.getText().toString()); } }
Java
great_rsd(p1,ee1). great_rsd(g1,dd1). great_rsd(e1,x1). great_rsd(e1,f1). great_rsd(t1,m1). great_rsd(u1,t1). great_rsd(w1,dd1). great_rsd(p1,m1). great_rsd(p1,h1). great_rsd(ee1,g1). great_rsd(ee1,dd1). great_rsd(f1,hh1). great_rsd(w1,m1). great_rsd(u1,q1). great_rsd(q1,ee1). great_rsd(cc1,dd1). great_rsd(f1,g1). great_rsd(q1,c1). great_rsd(aa1,x1). great_rsd(dd1,x1). great_rsd(cc1,u1). great_rsd(p1,cc1). great_rsd(ee1,x1). great_rsd(v1,x1). great_rsd(p1,ff1). great_rsd(k1,l1). great_rsd(a1,t1). great_rsd(f1,a1). great_rsd(a1,h1). great_rsd(p1,x1). great_rsd(cc1,kk1). great_rsd(f1,kk1). great_rsd(e1,dd1). great_rsd(jj1,dd1). great_rsd(p1,kk1). great_rsd(t1,h1). great_rsd(v1,hh1). great_rsd(c1,x1). great_rsd(c1,jj1). great_rsd(v1,g1). great_rsd(p1,w1). great_rsd(u1,g1). great_rsd(u1,ee1). great_rsd(e1,p1). great_rsd(f1,ee1). great_rsd(v1,aa1). great_rsd(k1,dd1). great_rsd(cc1,z1). great_rsd(q1,ff1). great_rsd(e1,k1). great_rsd(z1,jj1). great_rsd(p1,dd1). great_rsd(e1,c1). great_rsd(e1,q1). great_rsd(l1,jj1). great_rsd(aa1,ii1). great_rsd(f1,ii1). great_rsd(p1,v1). great_rsd(k1,kk1). great_rsd(ee1,ii1). great_rsd(cc1,ff1). great_rsd(c1,z1). great_rsd(q1,h1). great_rsd(cc1,ee1). great_rsd(v1,dd1). great_rsd(f1,jj1). great_rsd(u1,hh1). great_rsd(q1,ii1). great_rsd(cc1,l1). great_rsd(u1,l1). great_rsd(h1,x1). great_rsd(cc1,c1). great_rsd(w1,ff1). great_rsd(u1,ii1). great_rsd(e1,l1). great_rsd(ee1,hh1). great_rsd(aa1,z1). great_rsd(a1,x1). great_rsd(hh1,jj1). great_rsd(cc1,ii1). great_rsd(t1,z1). great_rsd(w1,kk1). great_rsd(aa1,h1). great_rsd(v1,ff1). great_rsd(ee1,m1). great_rsd(f1,t1). great_rsd(t1,ii1).
Java
import { PluginMeta } from '@savantly/sprout-api'; export const validatePluginJson = (pluginJson: any) => { if (!pluginJson.id) { throw new Error('Plugin id is missing in plugin.json'); } if (!pluginJson.info) { throw new Error('Plugin info node is missing in plugin.json'); } if (!pluginJson.info.version) { throw new Error('Plugin info.version is missing in plugin.json'); } const types = ['panel', 'datasource', 'app']; const type = pluginJson.type; if (!types.includes(type)) { throw new Error('Invalid plugin type in plugin.json: ' + type); } if (!pluginJson.id.endsWith('-' + type)) { throw new Error('[plugin.json] id should end with: -' + type); } }; export const getPluginJson = (path: string): PluginMeta => { let pluginJson; try { pluginJson = require(path); } catch (e) { throw new Error('Unable to find: ' + path); } validatePluginJson(pluginJson); return pluginJson as PluginMeta; };
Java
body { color: #2a2d2b; background-color: lightgrey; } h1 { color: #2a2d2b; } h2 { color: #336699; } h3 { color: #2a2d2b; } .link { color: #336699; } a:hover, .link:hover { font-weight: bold; text-decoration: underline; } ul { padding-left: 5px; } div#header { background-color: #fff; padding: 15px 15px; color: #2a2d2b; } button, div#header button { color: #ffffff; } .btn, div#header .btn, div#content div#sidebar .btn, ul.dropdown-menu { font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Geneva, Verdana, sans-serif; } div#header .alert { margin: 5px 0px; text-align: left; } .alert { color: #fff; } .alert-info, .alert-success, .brand-info, .btn-success { background-color: #4a9e43; } .alert-danger, .brand-danger { background-color: #ff2a00; } .brand-primary, .btn-primary { background-color: #336699; } .btn { color: #fff; } .btn-default { background-color: #444547; } .btn-default:hover { background-color: #444547; border-color: #2a2d2b; color: #fff; } .sycned { color: #4a9e43; } .unsycned { color: #ff2a00; } div#message { margin: 0px 5px; } .divider { border: 10px solid #2a2d2b; } #content { min-height: 450px; padding: 0px; box-shadow: 0px 5px 5px #888888; background-color: #fff; } #content .divider { border: 3px solid #2a2d2b; margin: 20px -50px; } #content h2, #content li>h3, #content li>h4 { display: inline-block; margin-right: 10px; } #content .btn { vertical-align: baseline; } #footer { font-size: 12px; text-align: center; margin: 10px 0px; } ul.alert { padding-left: 30px; } .spacing-top { margin-top: 10px; } div#sitemenu { text-align: right; color: #ffffff; } button#headerDropdownMenu { background-color: #404040; border: 0px; color: #ffffff; } div#sidebar { background-color: #444547; min-height: 450px; } div#sidebar h1, div#sidebar h2, div#sidebar h3, div#sidebar a { color: #fff; } li>h1, li>h2, li>h3, li>h4 { margin-top: 5px; margin-bottom: 5px; } div#center { background-color: #fff; min-height: 450px; padding: 30px 50px; } div.button-group-center { text-align: center; margin: 30px; } div.button-group-right { float: right; } .modal-footer { border-top: 0px; } .fa { margin-right: 10px; font-size: 24px; } li.folder, li.file { list-style: none; margin-left: 36px; } .row-flex { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; } ul.abn-tree { padding-left: 30px; } ul.abn-tree li.abn-tree-row a { color: #2a2d2b; font-size: 18px; } ul.nav.abn-tree i { font-size: 18px; } .spinner { float: right; position: relative; left: -50%; text-align: left; z-index: 1000; color: #ff2a00; } .spinner > .child { position: relative; left: 50%; float: right; z-index: 1000; } .fa-spin { font-size: 80px; width: 0px; margin: 0px; } .nav, .pagination, .carousel, .panel-title a { cursor: pointer; } #progressBar { background-color: #444547; display: table; height: 450px; width: 100%; } #progressBar > div { display: table-cell; vertical-align: middle; } #progressBar > div { margin-left: auto; margin-right: auto; width: 200px; } .progress { height: 30px; } .progress span { font-size: 25px; line-height: 20px; } .progress-bar { padding: 3px; } .deploy-errors { border: 2px solid red; padding: 10px; background-color: #333; color: white; } .deploy-errors h3 { color: white; margin: 0px 0px 10px 0px; } .error-msg { font-weight: bold; } .error-loc { margin-left: 20px; } .modal-sm { width: 600px; } .modal-content { width:inherit; height:inherit; margin: 0 auto; } .tree-scroller-cust1 { height: 200px; overflow-y: auto; border-color: #ddd; } /* The starting CSS styles for the enter animation */ .fade.ng-enter { transition:0.5s linear all; opacity:0; } /* The finishing CSS styles for the enter animation */ .fade.ng-enter.ng-enter-active { opacity:1; } /* now the element will fade out before it is removed from the DOM */ .fade.ng-leave { transition:0.5s linear all; opacity:1; } .fade.ng-leave.ng-leave-active { opacity:0; } .caption { font-style: italic; font-weight: normal; } .hint { color: #666; } .code { font-weight: normal; font-family: sans-serif; } .copy-icon { font-size: 14px; margin-left: 10px; cursor: pointer; } .code textarea { border: none; width: 100%; resize: none; } .code textarea:focus { outline: none; } section { border: 1px solid #ccc; padding: 6px 12px; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075); box-shadow: inset 0 1px 1px rgba(0,0,0,.075); } .navbar-default { background-color: #2a2d2b; color: white; } /* This is specifically for Swagger UI */ .swagger-validator { display: none; } div.api-doc > div { padding: 15px; } #img_logo { margin: 0pt 10px; height: 50px; }
Java
<div id="silverlightControlHost"> <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="800px" height="600px" id="silverlightObject"> <param name="source" value="static/sl/Overlay.xap"/> <param name="onError" value="onSilverlightError" /> <param name="background" value="white" /> <param name="windowless" value="false" /> <!-- <param name="background" value="transparent" /> <param name="windowless" value="true" /> --> <param name="minRuntimeVersion" value="3.0.40624.0" /> <param name="autoUpgrade" value="true" /> <param name="onLoad" value="pluginLoaded" /> <!--a href="http://go.microsoft.com/fwlink/?LinkID=149156&amp;v=5.0.61118.0" style="text-decoration:none"> <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none" /> </a--> </object> </div>
Java
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.analytics.data_v1alpha.types import analytics_data_api from .base import AlphaAnalyticsDataTransport, DEFAULT_CLIENT_INFO from .grpc import AlphaAnalyticsDataGrpcTransport class AlphaAnalyticsDataGrpcAsyncIOTransport(AlphaAnalyticsDataTransport): """gRPC AsyncIO backend transport for AlphaAnalyticsData. Google Analytics reporting data service. This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation and call it. It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ _grpc_channel: aio.Channel _stubs: Dict[str, Callable] = {} @classmethod def create_channel( cls, host: str = "analyticsdata.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. credentials (Optional[~.Credentials]): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. quota_project_id (Optional[str]): An optional project to use for billing and quota. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: aio.Channel: A gRPC AsyncIO channel object. """ return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, **kwargs, ) def __init__( self, *, host: str = "analyticsdata.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. channel (Optional[aio.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for the grpc channel. It is ignored if ``channel`` is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, both in PEM format. It is used to configure a mutual TLS channel. It is ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. always_use_jwt_access (Optional[bool]): Whether self signed JWT should be used for service account credentials. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) if client_cert_source: warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: # Ignore credentials if a channel was passed. credentials = False # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None else: if api_mtls_endpoint: host = api_mtls_endpoint # Create SSL credentials with client_cert_source or application # default SSL credentials. if client_cert_source: cert, key = client_cert_source() self._ssl_channel_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) else: self._ssl_channel_credentials = SslCredentials().ssl_credentials else: if client_cert_source_for_mtls and not ssl_channel_credentials: cert, key = client_cert_source_for_mtls() self._ssl_channel_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) # The base transport sets the host, credentials and scopes super().__init__( host=host, credentials=credentials, credentials_file=credentials_file, scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, credentials=self._credentials, credentials_file=credentials_file, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) # Wrap messages. This must be done after self._grpc_channel exists self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: """Create the channel designed to connect to this service. This property caches on the instance; repeated calls return the same channel. """ # Return the channel from cache. return self._grpc_channel @property def run_report( self, ) -> Callable[ [analytics_data_api.RunReportRequest], Awaitable[analytics_data_api.RunReportResponse], ]: r"""Return a callable for the run report method over gRPC. Returns a customized report of your Google Analytics event data. Reports contain statistics derived from data collected by the Google Analytics tracking code. The data returned from the API is as a table with columns for the requested dimensions and metrics. Metrics are individual measurements of user activity on your property, such as active users or event count. Dimensions break down metrics across some common criteria, such as country or event name. Returns: Callable[[~.RunReportRequest], Awaitable[~.RunReportResponse]]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "run_report" not in self._stubs: self._stubs["run_report"] = self.grpc_channel.unary_unary( "/google.analytics.data.v1alpha.AlphaAnalyticsData/RunReport", request_serializer=analytics_data_api.RunReportRequest.serialize, response_deserializer=analytics_data_api.RunReportResponse.deserialize, ) return self._stubs["run_report"] @property def run_pivot_report( self, ) -> Callable[ [analytics_data_api.RunPivotReportRequest], Awaitable[analytics_data_api.RunPivotReportResponse], ]: r"""Return a callable for the run pivot report method over gRPC. Returns a customized pivot report of your Google Analytics event data. Pivot reports are more advanced and expressive formats than regular reports. In a pivot report, dimensions are only visible if they are included in a pivot. Multiple pivots can be specified to further dissect your data. Returns: Callable[[~.RunPivotReportRequest], Awaitable[~.RunPivotReportResponse]]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "run_pivot_report" not in self._stubs: self._stubs["run_pivot_report"] = self.grpc_channel.unary_unary( "/google.analytics.data.v1alpha.AlphaAnalyticsData/RunPivotReport", request_serializer=analytics_data_api.RunPivotReportRequest.serialize, response_deserializer=analytics_data_api.RunPivotReportResponse.deserialize, ) return self._stubs["run_pivot_report"] @property def batch_run_reports( self, ) -> Callable[ [analytics_data_api.BatchRunReportsRequest], Awaitable[analytics_data_api.BatchRunReportsResponse], ]: r"""Return a callable for the batch run reports method over gRPC. Returns multiple reports in a batch. All reports must be for the same Entity. Returns: Callable[[~.BatchRunReportsRequest], Awaitable[~.BatchRunReportsResponse]]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "batch_run_reports" not in self._stubs: self._stubs["batch_run_reports"] = self.grpc_channel.unary_unary( "/google.analytics.data.v1alpha.AlphaAnalyticsData/BatchRunReports", request_serializer=analytics_data_api.BatchRunReportsRequest.serialize, response_deserializer=analytics_data_api.BatchRunReportsResponse.deserialize, ) return self._stubs["batch_run_reports"] @property def batch_run_pivot_reports( self, ) -> Callable[ [analytics_data_api.BatchRunPivotReportsRequest], Awaitable[analytics_data_api.BatchRunPivotReportsResponse], ]: r"""Return a callable for the batch run pivot reports method over gRPC. Returns multiple pivot reports in a batch. All reports must be for the same Entity. Returns: Callable[[~.BatchRunPivotReportsRequest], Awaitable[~.BatchRunPivotReportsResponse]]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "batch_run_pivot_reports" not in self._stubs: self._stubs["batch_run_pivot_reports"] = self.grpc_channel.unary_unary( "/google.analytics.data.v1alpha.AlphaAnalyticsData/BatchRunPivotReports", request_serializer=analytics_data_api.BatchRunPivotReportsRequest.serialize, response_deserializer=analytics_data_api.BatchRunPivotReportsResponse.deserialize, ) return self._stubs["batch_run_pivot_reports"] @property def get_metadata( self, ) -> Callable[ [analytics_data_api.GetMetadataRequest], Awaitable[analytics_data_api.Metadata] ]: r"""Return a callable for the get metadata method over gRPC. Returns metadata for dimensions and metrics available in reporting methods. Used to explore the dimensions and metrics. In this method, a Google Analytics GA4 Property Identifier is specified in the request, and the metadata response includes Custom dimensions and metrics as well as Universal metadata. For example if a custom metric with parameter name ``levels_unlocked`` is registered to a property, the Metadata response will contain ``customEvent:levels_unlocked``. Universal metadata are dimensions and metrics applicable to any property such as ``country`` and ``totalUsers``. Returns: Callable[[~.GetMetadataRequest], Awaitable[~.Metadata]]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_metadata" not in self._stubs: self._stubs["get_metadata"] = self.grpc_channel.unary_unary( "/google.analytics.data.v1alpha.AlphaAnalyticsData/GetMetadata", request_serializer=analytics_data_api.GetMetadataRequest.serialize, response_deserializer=analytics_data_api.Metadata.deserialize, ) return self._stubs["get_metadata"] @property def run_realtime_report( self, ) -> Callable[ [analytics_data_api.RunRealtimeReportRequest], Awaitable[analytics_data_api.RunRealtimeReportResponse], ]: r"""Return a callable for the run realtime report method over gRPC. The Google Analytics Realtime API returns a customized report of realtime event data for your property. These reports show events and usage from the last 30 minutes. Returns: Callable[[~.RunRealtimeReportRequest], Awaitable[~.RunRealtimeReportResponse]]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "run_realtime_report" not in self._stubs: self._stubs["run_realtime_report"] = self.grpc_channel.unary_unary( "/google.analytics.data.v1alpha.AlphaAnalyticsData/RunRealtimeReport", request_serializer=analytics_data_api.RunRealtimeReportRequest.serialize, response_deserializer=analytics_data_api.RunRealtimeReportResponse.deserialize, ) return self._stubs["run_realtime_report"] __all__ = ("AlphaAnalyticsDataGrpcAsyncIOTransport",)
Java
/** * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package org.politaktiv.map.model.impl; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.model.CacheModel; import org.politaktiv.map.model.Layer; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Date; /** * The cache model class for representing Layer in entity cache. * * @author Paul Butenko * @see Layer * @generated */ public class LayerCacheModel implements CacheModel<Layer>, Externalizable { @Override public String toString() { StringBundler sb = new StringBundler(11); sb.append("{layerId="); sb.append(layerId); sb.append(", createDate="); sb.append(createDate); sb.append(", label="); sb.append(label); sb.append(", userId="); sb.append(userId); sb.append(", portletInstance="); sb.append(portletInstance); sb.append("}"); return sb.toString(); } @Override public Layer toEntityModel() { LayerImpl layerImpl = new LayerImpl(); layerImpl.setLayerId(layerId); if (createDate == Long.MIN_VALUE) { layerImpl.setCreateDate(null); } else { layerImpl.setCreateDate(new Date(createDate)); } if (label == null) { layerImpl.setLabel(StringPool.BLANK); } else { layerImpl.setLabel(label); } layerImpl.setUserId(userId); if (portletInstance == null) { layerImpl.setPortletInstance(StringPool.BLANK); } else { layerImpl.setPortletInstance(portletInstance); } layerImpl.resetOriginalValues(); return layerImpl; } @Override public void readExternal(ObjectInput objectInput) throws IOException { layerId = objectInput.readLong(); createDate = objectInput.readLong(); label = objectInput.readUTF(); userId = objectInput.readLong(); portletInstance = objectInput.readUTF(); } @Override public void writeExternal(ObjectOutput objectOutput) throws IOException { objectOutput.writeLong(layerId); objectOutput.writeLong(createDate); if (label == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(label); } objectOutput.writeLong(userId); if (portletInstance == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(portletInstance); } } public long layerId; public long createDate; public String label; public long userId; public String portletInstance; }
Java
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/operators/optimizers/rmsprop_op.h" namespace paddle { namespace operators { class RmspropOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext *ctx) const override { PADDLE_ENFORCE_EQ(ctx->HasInput("Param"), true, platform::errors::NotFound( "Input(Param) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasInput("MeanSquare"), true, platform::errors::NotFound( "Input(MeanSquare) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasInput("LearningRate"), true, platform::errors::NotFound( "Input(LearningRate) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ(ctx->HasInput("Grad"), true, platform::errors::NotFound( "Input(Grad) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ(ctx->HasInput("Moment"), true, platform::errors::NotFound( "Input(Moment) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ(ctx->GetInputsVarType("Param").front(), framework::proto::VarType::LOD_TENSOR, platform::errors::InvalidArgument( "The input var's type in RmspropOp should be " "LoDTensor, but the received is %s", ctx->GetInputsVarType("Param").front())); PADDLE_ENFORCE_EQ( ctx->HasOutput("ParamOut"), true, platform::errors::NotFound( "Output(param_out) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasOutput("MomentOut"), true, platform::errors::NotFound( "Output(MomentOut) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasOutput("MeanSquareOut"), true, platform::errors::NotFound( "Output(MeanSquareOut) of RmspropOp should not be null.")); if (ctx->Attrs().Get<bool>("centered")) { PADDLE_ENFORCE_EQ( ctx->HasOutput("MeanGradOut"), true, platform::errors::NotFound( "Output(MeanGradOut) of RmspropOp should not be null.")); } auto param_dim = ctx->GetInputDim("Param"); PADDLE_ENFORCE_EQ( param_dim, ctx->GetInputDim("Grad"), platform::errors::InvalidArgument( "Param and grad input of RmspropOp should have the same dimension. " "But received Param's dim [%s] and Grad's dim [%s].", param_dim, ctx->GetInputDim("Grad"))); PADDLE_ENFORCE_EQ(param_dim, ctx->GetInputDim("Moment"), platform::errors::InvalidArgument( "Param and Momentum input of RmspropOp " "should have the same dimension. But received " "Param's dim [%s] and Moment [%s]", param_dim, ctx->GetInputDim("Moment"))); PADDLE_ENFORCE_EQ(param_dim, ctx->GetInputDim("MeanSquare"), platform::errors::InvalidArgument( "Param and Momentum input of RmspropOp " "should have the same dimension. But received " "Param's dim [%s] and MeanSquare [%s]", param_dim, ctx->GetInputDim("MeanSquare"))); auto lr_dim = ctx->GetInputDim("LearningRate"); PADDLE_ENFORCE_EQ(phi::product(lr_dim), 1, platform::errors::InvalidArgument( "Learning Rate of RmspropOp should be a scalar. But " "received LearningRate's dim [%s]", phi::product(lr_dim))); ctx->SetOutputDim("ParamOut", param_dim); ctx->SetOutputDim("MomentOut", param_dim); ctx->SetOutputDim("MeanSquareOut", param_dim); if (ctx->Attrs().Get<bool>("centered")) { ctx->SetOutputDim("MeanGradOut", param_dim); } } }; class RmspropOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("Param", "(Tensor, default Tensor<float>) " "Input parameter value that has to be updated."); AddInput("MeanSquare", "(Tensor, default Tensor<float>)" " The mean square value that gets updated."); AddInput("MeanGrad", "(Tensor, default Tensor<float>)" " The moving average of gradient") .AsDispensable(); AddInput("LearningRate", "(Tensor, default Tensor<float>) " "The learning rate should be a tensor of size 1."); AddInput("Grad", "(Tensor, default Tensor<float>) " "Input gradient of the parameter."); AddInput("Moment", "(Tensor, default Tensor<float>) The moment that gets updated."); AddOutput("ParamOut", "(Tensor) Output updated parameter value."); AddOutput("MomentOut", "(Tensor) Output updated moment."); AddOutput("MeanSquareOut", "(Tensor) Output Mean squared updated value."); AddOutput("MeanGradOut", "(Tensor) Output moving average of gradient updated value."); AddAttr<float>("epsilon", "(float, default 1e-10) Constant " "for numerical stability.") .SetDefault(1.0e-10f); AddAttr<float>("decay", "(float, default 0.9) " "Discounting factor for coming gradient.") .SetDefault(0.9f); AddAttr<float>("momentum", "(float, default 0.0) Constant value.") .SetDefault(0.0f); AddAttr<bool>("centered", "(bool, default false) use centered rmsprop.") .SetDefault(false); AddComment(R"DOC( Rmsprop Optimizer. $$ MeanSquareOut = decay * MeanSquare + (1 - decay) * Grad * Grad \\ MomentOut = momentum * Moment + \frac{LearningRate * Grad}{\sqrt{MeanSquareOut + epsilon}} \\ ParamOut = Param - MomentOut $$ if centered is true: mean_grad = decay * mean_square{t-1} + (1-decay) * gradient mean_square = decay * mean_square{t-1} + (1-decay) * gradient ** 2 mom = momentum * mom{t-1} + learning_rate * g_t / sqrt(mean_square - mean_grad**2 + epsilon) param -= mom The original slides that proposed Rmsprop: Slide 29 of http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf) )DOC"); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_WITHOUT_GRADIENT(rmsprop, ops::RmspropOp, ops::RmspropOpMaker); REGISTER_OP_CPU_KERNEL( rmsprop, ops::RmspropOpKernel<paddle::platform::CPUDeviceContext, float>, ops::RmspropOpKernel<paddle::platform::CPUDeviceContext, double>);
Java
package main import ( "encoding/json" "fmt" "github.com/codegangsta/cli" "github.com/olekukonko/tablewriter" "github.com/zero-os/0-core/base/pm" "gopkg.in/yaml.v2" "os" "sort" "strconv" "strings" ) type containerData struct { Container struct { Arguments struct { Root string `json:"root"` Hostname string `json:"hostname"` Tags []string `json:"tags"` } `json:"arguments"` PID int `json:"pid"` Root string `json:"root"` } `json:"container"` } func containers(t Transport, c *cli.Context) { var tags []string if c.Args().Present() { tags = append(tags, c.Args().First()) tags = append(tags, c.Args().Tail()...) } response, err := t.Run(Command{ Sync: true, Content: pm.Command{ Command: "corex.find", Arguments: pm.MustArguments(M{ "tags": tags, }), }, }) if err != nil { log.Fatal(err) } response.ValidateResultOrExit() var containers map[string]containerData if err := json.Unmarshal([]byte(response.Data), &containers); err != nil { log.Fatal(err) } table := tablewriter.NewWriter(os.Stdout) table.SetBorders(tablewriter.Border{}) table.SetAlignment(tablewriter.ALIGN_LEFT) table.SetHeader([]string{"ID", "FLIST", "HOSTNAME", "TAGS"}) ids := make([]int, 0, len(containers)) for id := range containers { iid, _ := strconv.ParseInt(id, 10, 32) ids = append(ids, int(iid)) } sort.Ints(ids) for _, id := range ids { sid := fmt.Sprintf("%d", id) container := containers[sid] table.Append([]string{ sid, container.Container.Arguments.Root, container.Container.Arguments.Hostname, strings.Join(container.Container.Arguments.Tags, ", "), }) } table.Render() } func containerInspect(t Transport, c *cli.Context) { id := c.Args().First() if id == "" { log.Fatal("missing container id") } response, err := t.Run(Command{ Sync: true, Content: pm.Command{ Command: "corex.list", Arguments: pm.MustArguments(M{}), }, }) if err != nil { log.Fatal(err) } response.ValidateResultOrExit() var containers map[string]interface{} if err := json.Unmarshal([]byte(response.Data), &containers); err != nil { log.Fatal(err) } container, ok := containers[id] if !ok { log.Fatalf("no container with id: %s", id) } data, _ := yaml.Marshal(container) fmt.Println(string(data)) }
Java
package org.poormanscastle.studies.compilers.grammar.grammar3_1.astparser.ast; import org.poormanscastle.studies.compilers.utils.grammartools.ast.CodePosition; /** * Created by georg on 15.01.16. */ public class OperatorExpression extends AbstractAstItem implements Expression { private final Expression leftOperand, rightOperand; private final Operator operator; public OperatorExpression(CodePosition codePosition, Expression leftOperand, Operator operator, Expression rightOperand) { super(codePosition); this.leftOperand = leftOperand; this.rightOperand = rightOperand; this.operator = operator; } public Expression getLeftOperand() { return leftOperand; } public Expression getRightOperand() { return rightOperand; } public Operator getOperator() { return operator; } @Override public boolean handleProceedWith(AstItemVisitor visitor) { return visitor.proceedWithOperatorExpression(this); } @Override public void accept(AstItemVisitor visitor) { visitor.visitOperatorExpression(this); if (leftOperand.handleProceedWith(visitor)) { leftOperand.accept(visitor); } if (rightOperand.handleProceedWith(visitor)) { rightOperand.accept(visitor); } visitor.leaveOperatorExpression(this); } }
Java
using Microsoft.AspNetCore.Http; using System.Collections.Generic; namespace OAuth.AspNet.AuthServer { /// <summary> /// Provides context information used in handling an OAuth resource owner grant. /// </summary> public class OAuthGrantResourceOwnerCredentialsContext : BaseValidatingTicketContext<OAuthAuthorizationServerOptions> { /// <summary> /// Initializes a new instance of the <see cref="OAuthGrantResourceOwnerCredentialsContext"/> class /// </summary> /// <param name="context"></param> /// <param name="options"></param> /// <param name="clientId"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="scope"></param> public OAuthGrantResourceOwnerCredentialsContext(HttpContext context, OAuthAuthorizationServerOptions options, string clientId, string userName, string password, IList<string> scope) : base(context, options, null) { ClientId = clientId; UserName = userName; Password = password; Scope = scope; } /// <summary> /// OAuth client id. /// </summary> public string ClientId { get; private set; } /// <summary> /// Resource owner username. /// </summary> public string UserName { get; private set; } /// <summary> /// Resource owner password. /// </summary> public string Password { get; private set; } /// <summary> /// List of scopes allowed by the resource owner. /// </summary> public IList<string> Scope { get; private set; } } }
Java
# Generated by Django 2.1.7 on 2019-04-30 13:20 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.AlterField( model_name='publishablemodel', name='id', field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False), ), ]
Java
<!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_45) on Thu Mar 26 16:48:34 UTC 2015 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> com.hazelcast.queue.impl.operations (Hazelcast Root 3.4.2 API) </TITLE> <META NAME="date" CONTENT="2015-03-26"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../../../com/hazelcast/queue/impl/operations/package-summary.html" target="classFrame">com.hazelcast.queue.impl.operations</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="AddAllBackupOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">AddAllBackupOperation</A> <BR> <A HREF="AddAllOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">AddAllOperation</A> <BR> <A HREF="CheckAndEvictOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">CheckAndEvictOperation</A> <BR> <A HREF="ClearBackupOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">ClearBackupOperation</A> <BR> <A HREF="ClearOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">ClearOperation</A> <BR> <A HREF="CompareAndRemoveBackupOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">CompareAndRemoveBackupOperation</A> <BR> <A HREF="CompareAndRemoveOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">CompareAndRemoveOperation</A> <BR> <A HREF="ContainsOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">ContainsOperation</A> <BR> <A HREF="DrainBackupOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">DrainBackupOperation</A> <BR> <A HREF="DrainOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">DrainOperation</A> <BR> <A HREF="IsEmptyOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">IsEmptyOperation</A> <BR> <A HREF="IteratorOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">IteratorOperation</A> <BR> <A HREF="OfferBackupOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">OfferBackupOperation</A> <BR> <A HREF="OfferOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">OfferOperation</A> <BR> <A HREF="PeekOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">PeekOperation</A> <BR> <A HREF="PollBackupOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">PollBackupOperation</A> <BR> <A HREF="PollOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">PollOperation</A> <BR> <A HREF="QueueBackupAwareOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">QueueBackupAwareOperation</A> <BR> <A HREF="QueueOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">QueueOperation</A> <BR> <A HREF="QueueReplicationOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">QueueReplicationOperation</A> <BR> <A HREF="RemainingCapacityOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">RemainingCapacityOperation</A> <BR> <A HREF="RemoveBackupOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">RemoveBackupOperation</A> <BR> <A HREF="RemoveOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">RemoveOperation</A> <BR> <A HREF="SizeOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">SizeOperation</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="ro"> <head> <!-- Generated by javadoc (version 1.7.0_07) on Tue May 27 14:37:25 EEST 2014 --> <title>Uses of Interface net.sf.jasperreports.engine.util.BigDecimalHandler (JasperReports 5.6.0 API)</title> <meta name="date" content="2014-05-27"> <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="Uses of Interface net.sf.jasperreports.engine.util.BigDecimalHandler (JasperReports 5.6.0 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><a href="../../../../../../net/sf/jasperreports/engine/util/BigDecimalHandler.html" title="interface in net.sf.jasperreports.engine.util">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?net/sf/jasperreports/engine/util/class-use/BigDecimalHandler.html" target="_top">Frames</a></li> <li><a href="BigDecimalHandler.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface net.sf.jasperreports.engine.util.BigDecimalHandler" class="title">Uses of Interface<br>net.sf.jasperreports.engine.util.BigDecimalHandler</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../net/sf/jasperreports/engine/util/BigDecimalHandler.html" title="interface in net.sf.jasperreports.engine.util">BigDecimalHandler</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#net.sf.jasperreports.engine.util">net.sf.jasperreports.engine.util</a></td> <td class="colLast"> <div class="block">Contains utility classes for the core library.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="net.sf.jasperreports.engine.util"> <!-- --> </a> <h3>Uses of <a href="../../../../../../net/sf/jasperreports/engine/util/BigDecimalHandler.html" title="interface in net.sf.jasperreports.engine.util">BigDecimalHandler</a> in <a href="../../../../../../net/sf/jasperreports/engine/util/package-summary.html">net.sf.jasperreports.engine.util</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../net/sf/jasperreports/engine/util/package-summary.html">net.sf.jasperreports.engine.util</a> that implement <a href="../../../../../../net/sf/jasperreports/engine/util/BigDecimalHandler.html" title="interface in net.sf.jasperreports.engine.util">BigDecimalHandler</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/util/Java14BigDecimalHandler.html" title="class in net.sf.jasperreports.engine.util">Java14BigDecimalHandler</a></strong></code> <div class="block"><a href="../../../../../../net/sf/jasperreports/engine/util/BigDecimalHandler.html" title="interface in net.sf.jasperreports.engine.util"><code>BigDecimalHandler</code></a> implementation used on Java 1.4.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/util/Java15BigDecimalHandler.html" title="class in net.sf.jasperreports.engine.util">Java15BigDecimalHandler</a></strong></code> <div class="block"><a href="../../../../../../net/sf/jasperreports/engine/util/BigDecimalHandler.html" title="interface in net.sf.jasperreports.engine.util"><code>BigDecimalHandler</code></a> implementation used on Java 1.5 or newer.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= 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><a href="../../../../../../net/sf/jasperreports/engine/util/BigDecimalHandler.html" title="interface in net.sf.jasperreports.engine.util">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?net/sf/jasperreports/engine/util/class-use/BigDecimalHandler.html" target="_top">Frames</a></li> <li><a href="BigDecimalHandler.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color:#000000;">&copy; 2001-2010 Jaspersoft Corporation <a href="http://www.jaspersoft.com" target="_blank" style="color:#000000;">www.jaspersoft.com</a></span> </small></p> </body> </html>
Java
package uk.ac.ebi.ddi.extservices.entrez.ncbiresult; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author Yasset Perez-Riverol (ypriverol@gmail.com) * @date 18/05/2015 */ @JsonIgnoreProperties(ignoreUnknown = true) public class NCBITaxResult { @JsonProperty("header") NCBIHeader header; @JsonProperty("esearchresult") NCBIEResult result; public NCBIHeader getHeader() { return header; } public void setHeader(NCBIHeader header) { this.header = header; } public NCBIEResult getResult() { return result; } public void setResult(NCBIEResult result) { this.result = result; } public String[] getNCBITaxonomy() { if (getResult() != null && getResult().getIdList() != null && getResult().getIdList().length == 1) { return getResult().getIdList(); } return null; } }
Java
// Copyright 2018, OpenCensus Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "opencensus/stats/internal/measure_data.h" #include <algorithm> #include <cmath> #include <numeric> #include <vector> #include "absl/types/span.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "opencensus/stats/bucket_boundaries.h" #include "opencensus/stats/distribution.h" #include "opencensus/stats/testing/test_utils.h" namespace opencensus { namespace stats { namespace { TEST(MeasureDataTest, SmallSequence) { MeasureData data({}); data.Add(-6); data.Add(0); data.Add(3); EXPECT_EQ(data.count(), 3); EXPECT_DOUBLE_EQ(data.sum(), -3); } TEST(MeasureDataTest, MultipleHistograms) { std::vector<BucketBoundaries> buckets = {BucketBoundaries::Explicit({0, 10}), BucketBoundaries::Explicit({}), BucketBoundaries::Explicit({5})}; MeasureData data(buckets); data.Add(-1); data.Add(1); data.Add(8); Distribution distribution1 = testing::TestUtils::MakeDistribution(&buckets[0]); data.AddToDistribution(&distribution1); EXPECT_THAT(distribution1.bucket_counts(), ::testing::ElementsAre(1, 2, 0)); Distribution distribution2 = testing::TestUtils::MakeDistribution(&buckets[2]); data.AddToDistribution(&distribution2); EXPECT_THAT(distribution2.bucket_counts(), ::testing::ElementsAre(2, 1)); } TEST(MeasureDataTest, DistributionStatistics) { BucketBoundaries buckets = BucketBoundaries::Explicit({}); MeasureData data(absl::MakeSpan(&buckets, 1)); const std::vector<int> samples{91, 18, 63, 98, 87, 77, 14, 97, 10, 35, 12, 5, 75, 41, 49, 38, 40, 20, 55, 83}; const double expected_mean = static_cast<double>(std::accumulate(samples.begin(), samples.end(), 0)) / samples.size(); double expected_sum_of_squared_deviation = 0; for (const auto sample : samples) { data.Add(sample); expected_sum_of_squared_deviation += pow(sample - expected_mean, 2); } Distribution distribution = testing::TestUtils::MakeDistribution(&buckets); data.AddToDistribution(&distribution); EXPECT_EQ(distribution.count(), samples.size()); EXPECT_DOUBLE_EQ(distribution.mean(), expected_mean); EXPECT_DOUBLE_EQ(distribution.sum_of_squared_deviation(), expected_sum_of_squared_deviation); EXPECT_DOUBLE_EQ(distribution.min(), *std::min_element(samples.begin(), samples.end())); EXPECT_DOUBLE_EQ(distribution.max(), *std::max_element(samples.begin(), samples.end())); } TEST(MeasureDataTest, BatchedAddToDistribution) { // Tests that batching values in the MeasureData is equivalent to sequentially // adding to the distribution. BucketBoundaries buckets = BucketBoundaries::Exponential(7, 2, 2); MeasureData data(absl::MakeSpan(&buckets, 1)); Distribution base_distribution = testing::TestUtils::MakeDistribution(&buckets); // Add some preexisting data to fully test the merge. testing::TestUtils::AddToDistribution(&base_distribution, 20); testing::TestUtils::AddToDistribution(&base_distribution, 10); Distribution expected_distribution = base_distribution; const double tolerance = 1.0 / 1000000000; const int max = 100; for (int i = 0; i <= max; ++i) { data.Add(i); testing::TestUtils::AddToDistribution(&expected_distribution, i); Distribution actual_distribution = base_distribution; data.AddToDistribution(&actual_distribution); EXPECT_EQ(expected_distribution.count(), actual_distribution.count()); EXPECT_DOUBLE_EQ(expected_distribution.mean(), actual_distribution.mean()); EXPECT_NEAR(expected_distribution.sum_of_squared_deviation(), actual_distribution.sum_of_squared_deviation(), tolerance); EXPECT_DOUBLE_EQ(expected_distribution.min(), actual_distribution.min()); EXPECT_DOUBLE_EQ(expected_distribution.max(), actual_distribution.max()); EXPECT_THAT( actual_distribution.bucket_counts(), ::testing::ElementsAreArray(expected_distribution.bucket_counts())); } } TEST(MeasureDataDeathTest, AddToDistributionWithUnknownBuckets) { BucketBoundaries buckets = BucketBoundaries::Explicit({0, 10}); MeasureData data(absl::MakeSpan(&buckets, 1)); data.Add(1); BucketBoundaries distribution_buckets = BucketBoundaries::Explicit({0}); Distribution distribution = testing::TestUtils::MakeDistribution(&distribution_buckets); EXPECT_DEBUG_DEATH( { data.AddToDistribution(&distribution); EXPECT_THAT(distribution.bucket_counts(), ::testing::ElementsAre(1, 0)); }, "No matching BucketBoundaries in AddToDistribution"); } } // namespace } // namespace stats } // namespace opencensus
Java
package peng.zhang.mobilesafe01.servicer; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.util.Log; public class GPSService extends Service { private LocationManager lm; private MyLocationListener listener; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); lm=(LocationManager) getSystemService(LOCATION_SERVICE); /** * List<String> providers=lm.getAllProviders(); for(String pv :providers){ Log.d(TAG, pv); } */ //ΪÄÚÈÝÌṩÕßÉèÖÃÌõ¼þ Criteria criteria=new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); //ÉèÖòÎÊýϸ»¯£º //criteria.setAccuracy(Criteria.ACCURACY_FINE);//ÉèÖÃΪ×î´ó¾«¶È //criteria.setAltitudeRequired(false);//²»ÒªÇ󺣰ÎÐÅÏ¢ //criteria.setBearingRequired(false);//²»ÒªÇó·½Î»ÐÅÏ¢ //criteria.setCostAllowed(true);//ÊÇ·ñÔÊÐí¸¶·Ñ //criteria.setPowerRequirement(Criteria.POWER_LOW);//¶ÔµçÁ¿µÄÒªÇó //ÉèÖÃλÖøüмàÌýÆ÷£¬ÐèÒª´«Èë²ÎÊýΪ¶¨Î»·½Ê½¡¢¸üÐÂʱ¼ä£¨Ò»°ãÒ»·ÖÖÓ£©£¬¸üоàÀ루һ°ã50Ã×£©£¬¼àÌýÆ÷ //ÉèÖûñÈ¡×îºÃµÄλÖÃÌṩÆ÷ listener =new MyLocationListener(); String provider=lm.getBestProvider(criteria, true); lm.requestLocationUpdates(provider,0, 0, listener); Log.d("Location", "Location0"+"Æô¶¯·þÎñ"); } //·þÎñÏú»Ù£¬È¡Ïû×¢²á @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); lm.removeUpdates(listener); listener=null; } class MyLocationListener implements LocationListener{ /** * µ±Î»ÖøıäµÄʱºò»Øµ÷ */ @Override public void onLocationChanged(Location location) { Log.d("Location", "Location1"+"MyLocationListenerÖ´ÐÐÁË"); String longitude = "jj:" + location.getLongitude() + "\n"; String latitude = "w:" + location.getLatitude() + "\n"; String accuracy = "a" + location.getAccuracy() + "\n"; Log.d("Location", "Location1"+longitude); //½«±ê×¼×ø±êת»»Îª»ðÐÇ×ø±ê //ʵÀý»¯ModifyOffsetÐèÒªÊäÈëÒ»¸öÊäÈëÁ÷£¬Õâ¸öÊäÈëÁ÷¼ÈÊǶÁÈ¡Êý¾Ý¿âÁ÷ // InputStream in = null; // try { // in=getResources().getAssets().open("axisoffset.dat"); // ModifyOffset offset=ModifyOffset.getInstance(in); // //½«±ê×¼×ø±êת»»Îª»ðÐÇ×ø±ê // PointDouble double1=offset.s2c(new PointDouble(location.getLongitude(), location.getLatitude())); // //ת»»Íê³É£¬È¡³ö×ø±ê // longitude ="j:" + offset.X+ "\n"; // latitude = "w:" +offset.Y+ "\n"; // } catch (IOException e) { // e.printStackTrace(); // } catch (Exception e) { // e.printStackTrace(); // } //¶ÔµÃµ½µÄ¾­Î³¶È½øÐб£´æ SharedPreferences sp=getSharedPreferences("config", MODE_PRIVATE); Editor editor=sp.edit(); editor.putString("lastlocation", longitude + latitude + accuracy); editor.commit(); } /** * µ±×´Ì¬·¢Éú¸Ä±äµÄʱºò»Øµ÷ ¿ªÆô--¹Ø±Õ £»¹Ø±Õ--¿ªÆô */ @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } /** * ijһ¸öλÖÃÌṩÕß¿ÉÒÔʹÓÃÁË */ @Override public void onProviderEnabled(String provider) { } /** * ijһ¸öλÖÃÌṩÕß²»¿ÉÒÔʹÓÃÁË */ @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } } }
Java
package com.ty.activity; import com.ty.app.R; import com.ty.service.AutoUpdateService; import com.ty.util.HttpCallbackListener; import com.ty.util.HttpUtil; import com.ty.util.Utility; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class WeatherActivity extends Activity implements OnClickListener{ private LinearLayout weatherInfoLayout; /** * 用于显示城市名 */ private TextView cityNameText; /** * 用于显示发布时间 */ private TextView publishText; /** * 用于显示天气描述信息 */ private TextView weatherDespText; /** * 用于显示气温1 */ private TextView temp1Text; /** * 用于显示气温2 */ private TextView temp2Text; /** * 用于显示当前日期 */ private TextView currentDateText; /** * 切换城市按钮 */ private Button switchCity; /** * 更新天气按钮 */ private Button refreshWeather; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.weather_layout); // 初始化各控件 weatherInfoLayout = (LinearLayout) findViewById(R.id.tyweather_info_layout); cityNameText = (TextView) findViewById(R.id.tycity_name); publishText = (TextView) findViewById(R.id.typublish_text); weatherDespText = (TextView) findViewById(R.id.tyweather_desp); temp1Text = (TextView) findViewById(R.id.tytemp1); temp2Text = (TextView) findViewById(R.id.tytemp2); currentDateText = (TextView) findViewById(R.id.tycurrent_date); switchCity = (Button) findViewById(R.id.tyswitch_city); refreshWeather = (Button) findViewById(R.id.tyrefresh_weather); String countyCode = getIntent().getStringExtra("county_code"); if (!TextUtils.isEmpty(countyCode)) { // 有县级代号时就去查询天气 publishText.setText("同步中..."); weatherInfoLayout.setVisibility(View.INVISIBLE); cityNameText.setVisibility(View.INVISIBLE); queryWeatherCode(countyCode); } else { // 没有县级代号时就直接显示本地天气 showWeather(); } switchCity.setOnClickListener(this); refreshWeather.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tycity_name: Intent intent = new Intent(this, ChooseAreaActivity.class); intent.putExtra("from_weather_activity", true); startActivity(intent); finish(); break; case R.id.tyrefresh_weather: publishText.setText("同步中..."); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String weatherCode = prefs.getString("weather_code", ""); if (!TextUtils.isEmpty(weatherCode)) { queryWeatherInfo(weatherCode); } break; default: break; } } /** * 查询县级代号所对应的天气代号。 */ private void queryWeatherCode(String countyCode) { String address = "http://www.weather.com.cn/data/list3/city" + countyCode + ".xml"; queryFromServer(address, "countyCode"); } /** * 查询天气代号所对应的天气。 */ private void queryWeatherInfo(String weatherCode) { String address = "http://www.weather.com.cn/data/cityinfo/" + weatherCode + ".html"; queryFromServer(address, "weatherCode"); } /** * 根据传入的地址和类型去向服务器查询天气代号或者天气信息。 */ private void queryFromServer(final String address, final String type) { HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinish(final String response) { if ("countyCode".equals(type)) { if (!TextUtils.isEmpty(response)) { // 从服务器返回的数据中解析出天气代号 String[] array = response.split("\\|"); if (array != null && array.length == 2) { String weatherCode = array[1]; queryWeatherInfo(weatherCode); } } } else if ("weatherCode".equals(type)) { // 处理服务器返回的天气信息 Utility.handleWeatherResponse(WeatherActivity.this, response); runOnUiThread(new Runnable() { @Override public void run() { showWeather(); } }); } } @Override public void onError(Exception e) { runOnUiThread(new Runnable() { @Override public void run() { publishText.setText("同步失败"); } }); } }); } /** * 从SharedPreferences文件中读取存储的天气信息,并显示到界面上。 */ private void showWeather() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); cityNameText.setText( prefs.getString("city_name", "")); temp1Text.setText(prefs.getString("temp1", "")); temp2Text.setText(prefs.getString("temp2", "")); weatherDespText.setText(prefs.getString("weather_desp", "")); publishText.setText("今天" + prefs.getString("publish_time", "") + "发布"); currentDateText.setText(prefs.getString("current_date", "")); weatherInfoLayout.setVisibility(View.VISIBLE); cityNameText.setVisibility(View.VISIBLE); Intent intent = new Intent(this, AutoUpdateService.class); startService(intent); } }
Java
# Coprotus dhofarensis Gené, El Shafie & Guarro SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Mycotaxon 46: 276 (1993) #### Original name Coprotus dhofarensis Gené, El Shafie & Guarro ### Remarks null
Java
// Generated from /POI/java/org/apache/poi/hssf/record/DBCellRecord.java #pragma once #include <fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <org/apache/poi/hssf/record/fwd-POI.hpp> #include <org/apache/poi/util/fwd-POI.hpp> #include <org/apache/poi/hssf/record/StandardRecord.hpp> #include <java/lang/Cloneable.hpp> struct default_init_tag; class poi::hssf::record::DBCellRecord final : public StandardRecord , public ::java::lang::Cloneable { public: typedef StandardRecord super; static constexpr int16_t sid { int16_t(215) }; static constexpr int32_t BLOCK_SIZE { int32_t(32) }; private: int32_t field_1_row_offset { }; ::int16_tArray* field_2_cell_offsets { }; protected: void ctor(int32_t rowOffset, ::int16_tArray* cellOffsets); void ctor(RecordInputStream* in); public: ::java::lang::String* toString() override; void serialize(::poi::util::LittleEndianOutput* out) override; public: /* protected */ int32_t getDataSize() override; public: int16_t getSid() override; DBCellRecord* clone() override; // Generated public: /* package */ DBCellRecord(int32_t rowOffset, ::int16_tArray* cellOffsets); public: DBCellRecord(RecordInputStream* in); protected: DBCellRecord(const ::default_init_tag&); public: static ::java::lang::Class *class_(); int32_t serialize(int32_t offset, ::int8_tArray* data); ::int8_tArray* serialize(); private: virtual ::java::lang::Class* getClass0(); friend class DBCellRecord_Builder; };
Java
<HTML> <HEAD> <meta charset="UTF-8"> <title>Box2DLevel.engine - core</title> <link rel="stylesheet" href="..\..\..\style.css"> </HEAD> <BODY> <a href="../../index.html">core</a>&nbsp;/&nbsp;<a href="../index.html">io.github.restioson.kettle.level</a>&nbsp;/&nbsp;<a href="index.html">Box2DLevel</a>&nbsp;/&nbsp;<a href=".">engine</a><br/> <br/> <h1>engine</h1> <a name="io.github.restioson.kettle.level.Box2DLevel$engine"></a> <code><span class="keyword">val </span><span class="identifier">engine</span><span class="symbol">: </span><span class="identifier">Kettle</span></code> <a href="https://github.com/Restioson/kettle-engine/tree/master/core/src/kotlin/io/github/restioson/kettle/level/Box2DLevel.kt#L10">(source)</a> </BODY> </HTML>
Java
import { Pipe, PipeTransform } from '@angular/core'; import { Project } from 'app/models/project'; @Pipe({ name: 'operatorFilter' }) export class OperatorFilterPipe implements PipeTransform { transform(value: Project[], q: string) { if (!q) { return value; } return value.filter(item => -1 < item.operator.toLowerCase().indexOf(q.toLowerCase())); } }
Java
//===--- CGDeclCXX.cpp - Emit LLVM Code for C++ declarations --------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This contains code dealing with code generation of C++ declarations // //===----------------------------------------------------------------------===// #include "CodeGenFunction.h" #include "CGCXXABI.h" #include "CGObjCRuntime.h" #include "CGOpenMPRuntime.h" #include "clang/Basic/CodeGenOptions.h" #include "llvm/ADT/StringExtras.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/MDBuilder.h" #include "llvm/Support/Path.h" using namespace clang; using namespace CodeGen; static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D, ConstantAddress DeclPtr) { assert( (D.hasGlobalStorage() || (D.hasLocalStorage() && CGF.getContext().getLangOpts().OpenCLCPlusPlus)) && "VarDecl must have global or local (in the case of OpenCL) storage!"); assert(!D.getType()->isReferenceType() && "Should not call EmitDeclInit on a reference!"); QualType type = D.getType(); LValue lv = CGF.MakeAddrLValue(DeclPtr, type); const Expr *Init = D.getInit(); switch (CGF.getEvaluationKind(type)) { case TEK_Scalar: { CodeGenModule &CGM = CGF.CGM; if (lv.isObjCStrong()) CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init), DeclPtr, D.getTLSKind()); else if (lv.isObjCWeak()) CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init), DeclPtr); else CGF.EmitScalarInit(Init, &D, lv, false); return; } case TEK_Complex: CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true); return; case TEK_Aggregate: CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed, AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased, AggValueSlot::DoesNotOverlap)); return; } llvm_unreachable("bad evaluation kind"); } /// Emit code to cause the destruction of the given variable with /// static storage duration. static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D, ConstantAddress Addr) { // Honor __attribute__((no_destroy)) and bail instead of attempting // to emit a reference to a possibly nonexistent destructor, which // in turn can cause a crash. This will result in a global constructor // that isn't balanced out by a destructor call as intended by the // attribute. This also checks for -fno-c++-static-destructors and // bails even if the attribute is not present. if (D.isNoDestroy(CGF.getContext())) return; CodeGenModule &CGM = CGF.CGM; // FIXME: __attribute__((cleanup)) ? QualType Type = D.getType(); QualType::DestructionKind DtorKind = Type.isDestructedType(); switch (DtorKind) { case QualType::DK_none: return; case QualType::DK_cxx_destructor: break; case QualType::DK_objc_strong_lifetime: case QualType::DK_objc_weak_lifetime: case QualType::DK_nontrivial_c_struct: // We don't care about releasing objects during process teardown. assert(!D.getTLSKind() && "should have rejected this"); return; } llvm::FunctionCallee Func; llvm::Constant *Argument; // Special-case non-array C++ destructors, if they have the right signature. // Under some ABIs, destructors return this instead of void, and cannot be // passed directly to __cxa_atexit if the target does not allow this // mismatch. const CXXRecordDecl *Record = Type->getAsCXXRecordDecl(); bool CanRegisterDestructor = Record && (!CGM.getCXXABI().HasThisReturn( GlobalDecl(Record->getDestructor(), Dtor_Complete)) || CGM.getCXXABI().canCallMismatchedFunctionType()); // If __cxa_atexit is disabled via a flag, a different helper function is // generated elsewhere which uses atexit instead, and it takes the destructor // directly. bool UsingExternalHelper = !CGM.getCodeGenOpts().CXAAtExit; if (Record && (CanRegisterDestructor || UsingExternalHelper)) { assert(!Record->hasTrivialDestructor()); CXXDestructorDecl *Dtor = Record->getDestructor(); Func = CGM.getAddrAndTypeOfCXXStructor(GlobalDecl(Dtor, Dtor_Complete)); Argument = llvm::ConstantExpr::getBitCast( Addr.getPointer(), CGF.getTypes().ConvertType(Type)->getPointerTo()); // Otherwise, the standard logic requires a helper function. } else { Func = CodeGenFunction(CGM) .generateDestroyHelper(Addr, Type, CGF.getDestroyer(DtorKind), CGF.needsEHCleanup(DtorKind), &D); Argument = llvm::Constant::getNullValue(CGF.Int8PtrTy); } CGM.getCXXABI().registerGlobalDtor(CGF, D, Func, Argument); } /// Emit code to cause the variable at the given address to be considered as /// constant from this point onwards. static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D, llvm::Constant *Addr) { return CGF.EmitInvariantStart( Addr, CGF.getContext().getTypeSizeInChars(D.getType())); } void CodeGenFunction::EmitInvariantStart(llvm::Constant *Addr, CharUnits Size) { // Do not emit the intrinsic if we're not optimizing. if (!CGM.getCodeGenOpts().OptimizationLevel) return; // Grab the llvm.invariant.start intrinsic. llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start; // Overloaded address space type. llvm::Type *ObjectPtr[1] = {Int8PtrTy}; llvm::Function *InvariantStart = CGM.getIntrinsic(InvStartID, ObjectPtr); // Emit a call with the size in bytes of the object. uint64_t Width = Size.getQuantity(); llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(Int64Ty, Width), llvm::ConstantExpr::getBitCast(Addr, Int8PtrTy)}; Builder.CreateCall(InvariantStart, Args); } void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr, bool PerformInit) { const Expr *Init = D.getInit(); QualType T = D.getType(); // The address space of a static local variable (DeclPtr) may be different // from the address space of the "this" argument of the constructor. In that // case, we need an addrspacecast before calling the constructor. // // struct StructWithCtor { // __device__ StructWithCtor() {...} // }; // __device__ void foo() { // __shared__ StructWithCtor s; // ... // } // // For example, in the above CUDA code, the static local variable s has a // "shared" address space qualifier, but the constructor of StructWithCtor // expects "this" in the "generic" address space. unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(T); unsigned ActualAddrSpace = DeclPtr->getType()->getPointerAddressSpace(); if (ActualAddrSpace != ExpectedAddrSpace) { llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(T); llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace); DeclPtr = llvm::ConstantExpr::getAddrSpaceCast(DeclPtr, PTy); } ConstantAddress DeclAddr(DeclPtr, getContext().getDeclAlign(&D)); if (!T->isReferenceType()) { if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd && D.hasAttr<OMPThreadPrivateDeclAttr>()) { (void)CGM.getOpenMPRuntime().emitThreadPrivateVarDefinition( &D, DeclAddr, D.getAttr<OMPThreadPrivateDeclAttr>()->getLocation(), PerformInit, this); } if (PerformInit) EmitDeclInit(*this, D, DeclAddr); if (CGM.isTypeConstant(D.getType(), true)) EmitDeclInvariant(*this, D, DeclPtr); else EmitDeclDestroy(*this, D, DeclAddr); return; } assert(PerformInit && "cannot have constant initializer which needs " "destruction for reference"); RValue RV = EmitReferenceBindingToExpr(Init); EmitStoreOfScalar(RV.getScalarVal(), DeclAddr, false, T); } /// Create a stub function, suitable for being passed to atexit, /// which passes the given address to the given destructor function. llvm::Function *CodeGenFunction::createAtExitStub(const VarDecl &VD, llvm::FunctionCallee dtor, llvm::Constant *addr) { // Get the destructor function type, void(*)(void). llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false); SmallString<256> FnName; { llvm::raw_svector_ostream Out(FnName); CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out); } const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction(); llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction( ty, FnName.str(), FI, VD.getLocation()); CodeGenFunction CGF(CGM); CGF.StartFunction(GlobalDecl(&VD, DynamicInitKind::AtExit), CGM.getContext().VoidTy, fn, FI, FunctionArgList()); llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr); // Make sure the call and the callee agree on calling convention. if (llvm::Function *dtorFn = dyn_cast<llvm::Function>(dtor.getCallee()->stripPointerCasts())) call->setCallingConv(dtorFn->getCallingConv()); CGF.FinishFunction(); return fn; } /// Register a global destructor using the C atexit runtime function. void CodeGenFunction::registerGlobalDtorWithAtExit(const VarDecl &VD, llvm::FunctionCallee dtor, llvm::Constant *addr) { // Create a function which calls the destructor. llvm::Constant *dtorStub = createAtExitStub(VD, dtor, addr); registerGlobalDtorWithAtExit(dtorStub); } void CodeGenFunction::registerGlobalDtorWithAtExit(llvm::Constant *dtorStub) { // extern "C" int atexit(void (*f)(void)); llvm::FunctionType *atexitTy = llvm::FunctionType::get(IntTy, dtorStub->getType(), false); llvm::FunctionCallee atexit = CGM.CreateRuntimeFunction(atexitTy, "atexit", llvm::AttributeList(), /*Local=*/true); if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit.getCallee())) atexitFn->setDoesNotThrow(); EmitNounwindRuntimeCall(atexit, dtorStub); } void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, bool PerformInit) { // If we've been asked to forbid guard variables, emit an error now. // This diagnostic is hard-coded for Darwin's use case; we can find // better phrasing if someone else needs it. if (CGM.getCodeGenOpts().ForbidGuardVariables) CGM.Error(D.getLocation(), "this initialization requires a guard variable, which " "the kernel does not support"); CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit); } void CodeGenFunction::EmitCXXGuardedInitBranch(llvm::Value *NeedsInit, llvm::BasicBlock *InitBlock, llvm::BasicBlock *NoInitBlock, GuardKind Kind, const VarDecl *D) { assert((Kind == GuardKind::TlsGuard || D) && "no guarded variable"); // A guess at how many times we will enter the initialization of a // variable, depending on the kind of variable. static const uint64_t InitsPerTLSVar = 1024; static const uint64_t InitsPerLocalVar = 1024 * 1024; llvm::MDNode *Weights; if (Kind == GuardKind::VariableGuard && !D->isLocalVarDecl()) { // For non-local variables, don't apply any weighting for now. Due to our // use of COMDATs, we expect there to be at most one initialization of the // variable per DSO, but we have no way to know how many DSOs will try to // initialize the variable. Weights = nullptr; } else { uint64_t NumInits; // FIXME: For the TLS case, collect and use profiling information to // determine a more accurate brach weight. if (Kind == GuardKind::TlsGuard || D->getTLSKind()) NumInits = InitsPerTLSVar; else NumInits = InitsPerLocalVar; // The probability of us entering the initializer is // 1 / (total number of times we attempt to initialize the variable). llvm::MDBuilder MDHelper(CGM.getLLVMContext()); Weights = MDHelper.createBranchWeights(1, NumInits - 1); } Builder.CreateCondBr(NeedsInit, InitBlock, NoInitBlock, Weights); } llvm::Function *CodeGenModule::CreateGlobalInitOrDestructFunction( llvm::FunctionType *FTy, const Twine &Name, const CGFunctionInfo &FI, SourceLocation Loc, bool TLS) { llvm::Function *Fn = llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage, Name, &getModule()); if (!getLangOpts().AppleKext && !TLS) { // Set the section if needed. if (const char *Section = getTarget().getStaticInitSectionSpecifier()) Fn->setSection(Section); } SetInternalFunctionAttributes(GlobalDecl(), Fn, FI); Fn->setCallingConv(getRuntimeCC()); if (!getLangOpts().Exceptions) Fn->setDoesNotThrow(); if (getLangOpts().Sanitize.has(SanitizerKind::Address) && !isInSanitizerBlacklist(SanitizerKind::Address, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::SanitizeAddress); if (getLangOpts().Sanitize.has(SanitizerKind::KernelAddress) && !isInSanitizerBlacklist(SanitizerKind::KernelAddress, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::SanitizeAddress); if (getLangOpts().Sanitize.has(SanitizerKind::HWAddress) && !isInSanitizerBlacklist(SanitizerKind::HWAddress, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress); if (getLangOpts().Sanitize.has(SanitizerKind::KernelHWAddress) && !isInSanitizerBlacklist(SanitizerKind::KernelHWAddress, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress); if (getLangOpts().Sanitize.has(SanitizerKind::Thread) && !isInSanitizerBlacklist(SanitizerKind::Thread, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::SanitizeThread); if (getLangOpts().Sanitize.has(SanitizerKind::Memory) && !isInSanitizerBlacklist(SanitizerKind::Memory, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::SanitizeMemory); if (getLangOpts().Sanitize.has(SanitizerKind::KernelMemory) && !isInSanitizerBlacklist(SanitizerKind::KernelMemory, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::SanitizeMemory); if (getLangOpts().Sanitize.has(SanitizerKind::SafeStack) && !isInSanitizerBlacklist(SanitizerKind::SafeStack, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::SafeStack); if (getLangOpts().Sanitize.has(SanitizerKind::ShadowCallStack) && !isInSanitizerBlacklist(SanitizerKind::ShadowCallStack, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::ShadowCallStack); auto RASignKind = getCodeGenOpts().getSignReturnAddress(); if (RASignKind != CodeGenOptions::SignReturnAddressScope::None) { Fn->addFnAttr("sign-return-address", RASignKind == CodeGenOptions::SignReturnAddressScope::All ? "all" : "non-leaf"); auto RASignKey = getCodeGenOpts().getSignReturnAddressKey(); Fn->addFnAttr("sign-return-address-key", RASignKey == CodeGenOptions::SignReturnAddressKeyValue::AKey ? "a_key" : "b_key"); } if (getCodeGenOpts().BranchTargetEnforcement) Fn->addFnAttr("branch-target-enforcement"); return Fn; } /// Create a global pointer to a function that will initialize a global /// variable. The user has requested that this pointer be emitted in a specific /// section. void CodeGenModule::EmitPointerToInitFunc(const VarDecl *D, llvm::GlobalVariable *GV, llvm::Function *InitFunc, InitSegAttr *ISA) { llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable( TheModule, InitFunc->getType(), /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr"); PtrArray->setSection(ISA->getSection()); addUsedGlobal(PtrArray); // If the GV is already in a comdat group, then we have to join it. if (llvm::Comdat *C = GV->getComdat()) PtrArray->setComdat(C); } void CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D, llvm::GlobalVariable *Addr, bool PerformInit) { // According to E.2.3.1 in CUDA-7.5 Programming guide: __device__, // __constant__ and __shared__ variables defined in namespace scope, // that are of class type, cannot have a non-empty constructor. All // the checks have been done in Sema by now. Whatever initializers // are allowed are empty and we just need to ignore them here. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDASharedAttr>())) return; if (getLangOpts().OpenMP && getOpenMPRuntime().emitDeclareTargetVarDefinition(D, Addr, PerformInit)) return; // Check if we've already initialized this decl. auto I = DelayedCXXInitPosition.find(D); if (I != DelayedCXXInitPosition.end() && I->second == ~0U) return; llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false); SmallString<256> FnName; { llvm::raw_svector_ostream Out(FnName); getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out); } // Create a variable initialization function. llvm::Function *Fn = CreateGlobalInitOrDestructFunction(FTy, FnName.str(), getTypes().arrangeNullaryFunction(), D->getLocation()); auto *ISA = D->getAttr<InitSegAttr>(); CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr, PerformInit); llvm::GlobalVariable *COMDATKey = supportsCOMDAT() && D->isExternallyVisible() ? Addr : nullptr; if (D->getTLSKind()) { // FIXME: Should we support init_priority for thread_local? // FIXME: We only need to register one __cxa_thread_atexit function for the // entire TU. CXXThreadLocalInits.push_back(Fn); CXXThreadLocalInitVars.push_back(D); } else if (PerformInit && ISA) { EmitPointerToInitFunc(D, Addr, Fn, ISA); } else if (auto *IPA = D->getAttr<InitPriorityAttr>()) { OrderGlobalInits Key(IPA->getPriority(), PrioritizedCXXGlobalInits.size()); PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn)); } else if (isTemplateInstantiation(D->getTemplateSpecializationKind()) || getContext().GetGVALinkageForVariable(D) == GVA_DiscardableODR) { // C++ [basic.start.init]p2: // Definitions of explicitly specialized class template static data // members have ordered initialization. Other class template static data // members (i.e., implicitly or explicitly instantiated specializations) // have unordered initialization. // // As a consequence, we can put them into their own llvm.global_ctors entry. // // If the global is externally visible, put the initializer into a COMDAT // group with the global being initialized. On most platforms, this is a // minor startup time optimization. In the MS C++ ABI, there are no guard // variables, so this COMDAT key is required for correctness. AddGlobalCtor(Fn, 65535, COMDATKey); if (getTarget().getCXXABI().isMicrosoft() && COMDATKey) { // In The MS C++, MS add template static data member in the linker // drective. addUsedGlobal(COMDATKey); } } else if (D->hasAttr<SelectAnyAttr>()) { // SelectAny globals will be comdat-folded. Put the initializer into a // COMDAT group associated with the global, so the initializers get folded // too. AddGlobalCtor(Fn, 65535, COMDATKey); } else { I = DelayedCXXInitPosition.find(D); // Re-do lookup in case of re-hash. if (I == DelayedCXXInitPosition.end()) { CXXGlobalInits.push_back(Fn); } else if (I->second != ~0U) { assert(I->second < CXXGlobalInits.size() && CXXGlobalInits[I->second] == nullptr); CXXGlobalInits[I->second] = Fn; } } // Remember that we already emitted the initializer for this global. DelayedCXXInitPosition[D] = ~0U; } void CodeGenModule::EmitCXXThreadLocalInitFunc() { getCXXABI().EmitThreadLocalInitFuncs( *this, CXXThreadLocals, CXXThreadLocalInits, CXXThreadLocalInitVars); CXXThreadLocalInits.clear(); CXXThreadLocalInitVars.clear(); CXXThreadLocals.clear(); } void CodeGenModule::EmitCXXGlobalInitFunc() { while (!CXXGlobalInits.empty() && !CXXGlobalInits.back()) CXXGlobalInits.pop_back(); if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty()) return; llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false); const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction(); // Create our global initialization function. if (!PrioritizedCXXGlobalInits.empty()) { SmallVector<llvm::Function *, 8> LocalCXXGlobalInits; llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(), PrioritizedCXXGlobalInits.end()); // Iterate over "chunks" of ctors with same priority and emit each chunk // into separate function. Note - everything is sorted first by priority, // second - by lex order, so we emit ctor functions in proper order. for (SmallVectorImpl<GlobalInitData >::iterator I = PrioritizedCXXGlobalInits.begin(), E = PrioritizedCXXGlobalInits.end(); I != E; ) { SmallVectorImpl<GlobalInitData >::iterator PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp()); LocalCXXGlobalInits.clear(); unsigned Priority = I->first.priority; // Compute the function suffix from priority. Prepend with zeroes to make // sure the function names are also ordered as priorities. std::string PrioritySuffix = llvm::utostr(Priority); // Priority is always <= 65535 (enforced by sema). PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix; llvm::Function *Fn = CreateGlobalInitOrDestructFunction( FTy, "_GLOBAL__I_" + PrioritySuffix, FI); for (; I < PrioE; ++I) LocalCXXGlobalInits.push_back(I->second); CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits); AddGlobalCtor(Fn, Priority); } PrioritizedCXXGlobalInits.clear(); } // Include the filename in the symbol name. Including "sub_" matches gcc and // makes sure these symbols appear lexicographically behind the symbols with // priority emitted above. SmallString<128> FileName = llvm::sys::path::filename(getModule().getName()); if (FileName.empty()) FileName = "<null>"; for (size_t i = 0; i < FileName.size(); ++i) { // Replace everything that's not [a-zA-Z0-9._] with a _. This set happens // to be the set of C preprocessing numbers. if (!isPreprocessingNumberBody(FileName[i])) FileName[i] = '_'; } llvm::Function *Fn = CreateGlobalInitOrDestructFunction( FTy, llvm::Twine("_GLOBAL__sub_I_", FileName), FI); CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits); AddGlobalCtor(Fn); // In OpenCL global init functions must be converted to kernels in order to // be able to launch them from the host. // FIXME: Some more work might be needed to handle destructors correctly. // Current initialization function makes use of function pointers callbacks. // We can't support function pointers especially between host and device. // However it seems global destruction has little meaning without any // dynamic resource allocation on the device and program scope variables are // destroyed by the runtime when program is released. if (getLangOpts().OpenCL) { GenOpenCLArgMetadata(Fn); Fn->setCallingConv(llvm::CallingConv::SPIR_KERNEL); } CXXGlobalInits.clear(); } void CodeGenModule::EmitCXXGlobalDtorFunc() { if (CXXGlobalDtors.empty()) return; llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false); // Create our global destructor function. const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction(); llvm::Function *Fn = CreateGlobalInitOrDestructFunction(FTy, "_GLOBAL__D_a", FI); CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors); AddGlobalDtor(Fn); } /// Emit the code necessary to initialize the given global variable. void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, const VarDecl *D, llvm::GlobalVariable *Addr, bool PerformInit) { // Check if we need to emit debug info for variable initializer. if (D->hasAttr<NoDebugAttr>()) DebugInfo = nullptr; // disable debug info indefinitely for this function CurEHLocation = D->getBeginLoc(); StartFunction(GlobalDecl(D, DynamicInitKind::Initializer), getContext().VoidTy, Fn, getTypes().arrangeNullaryFunction(), FunctionArgList(), D->getLocation(), D->getInit()->getExprLoc()); // Use guarded initialization if the global variable is weak. This // occurs for, e.g., instantiated static data members and // definitions explicitly marked weak. // // Also use guarded initialization for a variable with dynamic TLS and // unordered initialization. (If the initialization is ordered, the ABI // layer will guard the whole-TU initialization for us.) if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage() || (D->getTLSKind() == VarDecl::TLS_Dynamic && isTemplateInstantiation(D->getTemplateSpecializationKind()))) { EmitCXXGuardedInit(*D, Addr, PerformInit); } else { EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit); } FinishFunction(); } void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn, ArrayRef<llvm::Function *> Decls, ConstantAddress Guard) { { auto NL = ApplyDebugLocation::CreateEmpty(*this); StartFunction(GlobalDecl(), getContext().VoidTy, Fn, getTypes().arrangeNullaryFunction(), FunctionArgList()); // Emit an artificial location for this function. auto AL = ApplyDebugLocation::CreateArtificial(*this); llvm::BasicBlock *ExitBlock = nullptr; if (Guard.isValid()) { // If we have a guard variable, check whether we've already performed // these initializations. This happens for TLS initialization functions. llvm::Value *GuardVal = Builder.CreateLoad(Guard); llvm::Value *Uninit = Builder.CreateIsNull(GuardVal, "guard.uninitialized"); llvm::BasicBlock *InitBlock = createBasicBlock("init"); ExitBlock = createBasicBlock("exit"); EmitCXXGuardedInitBranch(Uninit, InitBlock, ExitBlock, GuardKind::TlsGuard, nullptr); EmitBlock(InitBlock); // Mark as initialized before initializing anything else. If the // initializers use previously-initialized thread_local vars, that's // probably supposed to be OK, but the standard doesn't say. Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard); // The guard variable can't ever change again. EmitInvariantStart( Guard.getPointer(), CharUnits::fromQuantity( CGM.getDataLayout().getTypeAllocSize(GuardVal->getType()))); } RunCleanupsScope Scope(*this); // When building in Objective-C++ ARC mode, create an autorelease pool // around the global initializers. if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) { llvm::Value *token = EmitObjCAutoreleasePoolPush(); EmitObjCAutoreleasePoolCleanup(token); } for (unsigned i = 0, e = Decls.size(); i != e; ++i) if (Decls[i]) EmitRuntimeCall(Decls[i]); Scope.ForceCleanup(); if (ExitBlock) { Builder.CreateBr(ExitBlock); EmitBlock(ExitBlock); } } FinishFunction(); } void CodeGenFunction::GenerateCXXGlobalDtorsFunc( llvm::Function *Fn, const std::vector<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH, llvm::Constant *>> &DtorsAndObjects) { { auto NL = ApplyDebugLocation::CreateEmpty(*this); StartFunction(GlobalDecl(), getContext().VoidTy, Fn, getTypes().arrangeNullaryFunction(), FunctionArgList()); // Emit an artificial location for this function. auto AL = ApplyDebugLocation::CreateArtificial(*this); // Emit the dtors, in reverse order from construction. for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) { llvm::FunctionType *CalleeTy; llvm::Value *Callee; llvm::Constant *Arg; std::tie(CalleeTy, Callee, Arg) = DtorsAndObjects[e - i - 1]; llvm::CallInst *CI = Builder.CreateCall(CalleeTy, Callee, Arg); // Make sure the call and the callee agree on calling convention. if (llvm::Function *F = dyn_cast<llvm::Function>(Callee)) CI->setCallingConv(F->getCallingConv()); } } FinishFunction(); } /// generateDestroyHelper - Generates a helper function which, when /// invoked, destroys the given object. The address of the object /// should be in global memory. llvm::Function *CodeGenFunction::generateDestroyHelper( Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray, const VarDecl *VD) { FunctionArgList args; ImplicitParamDecl Dst(getContext(), getContext().VoidPtrTy, ImplicitParamDecl::Other); args.push_back(&Dst); const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, args); llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction( FTy, "__cxx_global_array_dtor", FI, VD->getLocation()); CurEHLocation = VD->getBeginLoc(); StartFunction(VD, getContext().VoidTy, fn, FI, args); emitDestroy(addr, type, destroyer, useEHCleanupForArray); FinishFunction(); return fn; }
Java
# Builders ARG BUNDLE_IMAGE=fission-workflows-bundle ARG BUNDLE_TAG=latest ARG FISSION_BUILDER_IMAGE=fission/builder ARG FISSION_TAG=latest FROM $BUNDLE_IMAGE:$BUNDLE_TAG as workflows-bundle FROM scratch COPY --from=workflows-bundle /fission-workflows-bundle /fission-workflows-bundle EXPOSE 8888 EXPOSE 8080 ENV FNENV_FISSION_CONTROLLER http://controller.fission ENV FNENV_FISSION_EXECUTOR http://executor.fission ENV ES_NATS_URL nats://defaultFissionAuthToken@nats-streaming.fission:4222 ENV ES_NATS_CLUSTER fissionMQTrigger # Remove APIs when components stabilize ENTRYPOINT ["/fission-workflows-bundle", \ "--nats", \ "--fission", \ "--internal", \ "--controller", \ "--api-http", \ "--api-workflow-invocation", \ "--api-workflow", \ "--api-admin", \ "--metrics"]
Java
# Dilsea californica (J. Agardh) Kuntze SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Penicillium rufulum (Bainier) Sacc. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Syll. fung. (Abellini) 22: 1275 (1913) #### Original name Scopulariopsis rufulus Bainier ### Remarks null
Java
// Copyright (c) 2018 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package m3ql //go:generate peg -inline -switch src/query/parser/m3ql/grammar.peg import ( "fmt" "io" "math" "os" "sort" "strconv" ) const endSymbol rune = 1114112 /* The rule types inferred from the grammar are below. */ type pegRule uint8 const ( ruleUnknown pegRule = iota ruleGrammar ruleMacroDef rulePipeline ruleExpression ruleFunctionCall ruleArgument ruleKeywordSpecifier ruleNesting ruleSpacing ruleSpace ruleEOL ruleComment ruleCommentStart ruleIdentifier ruleIdentifierStart ruleIdentifierChars ruleOperator ruleOperatorSymbols ruleBoolean ruleTrue ruleFalse ruleNumber ruleIntegralNumber ruleFloatingNumber ruleMinus ruleStringLiteral ruleQuoteChar rulePattern rulePatternChars ruleGlobSymbols ruleSemicolon ruleEquals rulePipe ruleLParenthesis ruleRParenthesis ruleColon ruleEOF ruleAction0 ruleAction1 ruleAction2 ruleAction3 ruleAction4 ruleAction5 ruleAction6 ruleAction7 ruleAction8 ruleAction9 rulePegText ) var rul3s = [...]string{ "Unknown", "Grammar", "MacroDef", "Pipeline", "Expression", "FunctionCall", "Argument", "KeywordSpecifier", "Nesting", "Spacing", "Space", "EOL", "Comment", "CommentStart", "Identifier", "IdentifierStart", "IdentifierChars", "Operator", "OperatorSymbols", "Boolean", "True", "False", "Number", "IntegralNumber", "FloatingNumber", "Minus", "StringLiteral", "QuoteChar", "Pattern", "PatternChars", "GlobSymbols", "Semicolon", "Equals", "Pipe", "LParenthesis", "RParenthesis", "Colon", "EOF", "Action0", "Action1", "Action2", "Action3", "Action4", "Action5", "Action6", "Action7", "Action8", "Action9", "PegText", } type token32 struct { pegRule begin, end uint32 } func (t *token32) String() string { return fmt.Sprintf("\x1B[34m%v\x1B[m %v %v", rul3s[t.pegRule], t.begin, t.end) } type node32 struct { token32 up, next *node32 } func (node *node32) print(w io.Writer, pretty bool, buffer string) { var print func(node *node32, depth int) print = func(node *node32, depth int) { for node != nil { for c := 0; c < depth; c++ { fmt.Printf(" ") } rule := rul3s[node.pegRule] quote := strconv.Quote(string(([]rune(buffer)[node.begin:node.end]))) if !pretty { fmt.Fprintf(w, "%v %v\n", rule, quote) } else { fmt.Fprintf(w, "\x1B[34m%v\x1B[m %v\n", rule, quote) } if node.up != nil { print(node.up, depth+1) } node = node.next } } print(node, 0) } func (node *node32) Print(w io.Writer, buffer string) { node.print(w, false, buffer) } func (node *node32) PrettyPrint(w io.Writer, buffer string) { node.print(w, true, buffer) } type tokens32 struct { tree []token32 } func (t *tokens32) Trim(length uint32) { t.tree = t.tree[:length] } func (t *tokens32) Print() { for _, token := range t.tree { fmt.Println(token.String()) } } func (t *tokens32) AST() *node32 { type element struct { node *node32 down *element } tokens := t.Tokens() var stack *element for _, token := range tokens { if token.begin == token.end { continue } node := &node32{token32: token} for stack != nil && stack.node.begin >= token.begin && stack.node.end <= token.end { stack.node.next = node.up node.up = stack.node stack = stack.down } stack = &element{node: node, down: stack} } if stack != nil { return stack.node } return nil } func (t *tokens32) PrintSyntaxTree(buffer string) { t.AST().Print(os.Stdout, buffer) } func (t *tokens32) WriteSyntaxTree(w io.Writer, buffer string) { t.AST().Print(w, buffer) } func (t *tokens32) PrettyPrintSyntaxTree(buffer string) { t.AST().PrettyPrint(os.Stdout, buffer) } func (t *tokens32) Add(rule pegRule, begin, end, index uint32) { if tree := t.tree; int(index) >= len(tree) { expanded := make([]token32, 2*len(tree)) copy(expanded, tree) t.tree = expanded } t.tree[index] = token32{ pegRule: rule, begin: begin, end: end, } } func (t *tokens32) Tokens() []token32 { return t.tree } type m3ql struct { scriptBuilder Buffer string buffer []rune rules [49]func() bool parse func(rule ...int) error reset func() Pretty bool tokens32 } func (p *m3ql) Parse(rule ...int) error { return p.parse(rule...) } func (p *m3ql) Reset() { p.reset() } type textPosition struct { line, symbol int } type textPositionMap map[int]textPosition func translatePositions(buffer []rune, positions []int) textPositionMap { length, translations, j, line, symbol := len(positions), make(textPositionMap, len(positions)), 0, 1, 0 sort.Ints(positions) search: for i, c := range buffer { if c == '\n' { line, symbol = line+1, 0 } else { symbol++ } if i == positions[j] { translations[positions[j]] = textPosition{line, symbol} for j++; j < length; j++ { if i != positions[j] { continue search } } break search } } return translations } type parseError struct { p *m3ql max token32 } func (e *parseError) Error() string { tokens, error := []token32{e.max}, "\n" positions, p := make([]int, 2*len(tokens)), 0 for _, token := range tokens { positions[p], p = int(token.begin), p+1 positions[p], p = int(token.end), p+1 } translations := translatePositions(e.p.buffer, positions) format := "parse error near %v (line %v symbol %v - line %v symbol %v):\n%v\n" if e.p.Pretty { format = "parse error near \x1B[34m%v\x1B[m (line %v symbol %v - line %v symbol %v):\n%v\n" } for _, token := range tokens { begin, end := int(token.begin), int(token.end) error += fmt.Sprintf(format, rul3s[token.pegRule], translations[begin].line, translations[begin].symbol, translations[end].line, translations[end].symbol, strconv.Quote(string(e.p.buffer[begin:end]))) } return error } func (p *m3ql) PrintSyntaxTree() { if p.Pretty { p.tokens32.PrettyPrintSyntaxTree(p.Buffer) } else { p.tokens32.PrintSyntaxTree(p.Buffer) } } func (p *m3ql) WriteSyntaxTree(w io.Writer) { p.tokens32.WriteSyntaxTree(w, p.Buffer) } func (p *m3ql) Execute() { buffer, _buffer, text, begin, end := p.Buffer, p.buffer, "", 0, 0 for _, token := range p.Tokens() { switch token.pegRule { case rulePegText: begin, end = int(token.begin), int(token.end) text = string(_buffer[begin:end]) case ruleAction0: p.newMacro(text) case ruleAction1: p.newPipeline() case ruleAction2: p.endPipeline() case ruleAction3: p.newExpression(text) case ruleAction4: p.endExpression() case ruleAction5: p.newBooleanArgument(text) case ruleAction6: p.newNumericArgument(text) case ruleAction7: p.newPatternArgument(text) case ruleAction8: p.newStringLiteralArgument(text) case ruleAction9: p.newKeywordArgument(text) } } _, _, _, _, _ = buffer, _buffer, text, begin, end } func (p *m3ql) Init() { var ( max token32 position, tokenIndex uint32 buffer []rune ) p.reset = func() { max = token32{} position, tokenIndex = 0, 0 p.buffer = []rune(p.Buffer) if len(p.buffer) == 0 || p.buffer[len(p.buffer)-1] != endSymbol { p.buffer = append(p.buffer, endSymbol) } buffer = p.buffer } p.reset() _rules := p.rules tree := tokens32{tree: make([]token32, math.MaxInt16)} p.parse = func(rule ...int) error { r := 1 if len(rule) > 0 { r = rule[0] } matches := p.rules[r]() p.tokens32 = tree if matches { p.Trim(tokenIndex) return nil } return &parseError{p, max} } add := func(rule pegRule, begin uint32) { tree.Add(rule, begin, position, tokenIndex) tokenIndex++ if begin != position && position > max.end { max = token32{rule, begin, position} } } matchDot := func() bool { if buffer[position] != endSymbol { position++ return true } return false } /*matchChar := func(c byte) bool { if buffer[position] == c { position++ return true } return false }*/ /*matchRange := func(lower byte, upper byte) bool { if c := buffer[position]; c >= lower && c <= upper { position++ return true } return false }*/ _rules = [...]func() bool{ nil, /* 0 Grammar <- <(Spacing (MacroDef Semicolon)* Pipeline EOF)> */ func() bool { position0, tokenIndex0 := position, tokenIndex { position1 := position if !_rules[ruleSpacing]() { goto l0 } l2: { position3, tokenIndex3 := position, tokenIndex { position4 := position if !_rules[ruleIdentifier]() { goto l3 } { add(ruleAction0, position) } { position6 := position if buffer[position] != rune('=') { goto l3 } position++ if !_rules[ruleSpacing]() { goto l3 } add(ruleEquals, position6) } if !_rules[rulePipeline]() { goto l3 } add(ruleMacroDef, position4) } { position7 := position if buffer[position] != rune(';') { goto l3 } position++ if !_rules[ruleSpacing]() { goto l3 } add(ruleSemicolon, position7) } goto l2 l3: position, tokenIndex = position3, tokenIndex3 } if !_rules[rulePipeline]() { goto l0 } { position8 := position { position9, tokenIndex9 := position, tokenIndex if !matchDot() { goto l9 } goto l0 l9: position, tokenIndex = position9, tokenIndex9 } add(ruleEOF, position8) } add(ruleGrammar, position1) } return true l0: position, tokenIndex = position0, tokenIndex0 return false }, /* 1 MacroDef <- <(Identifier Action0 Equals Pipeline)> */ nil, /* 2 Pipeline <- <(Action1 Expression (Pipe Expression)* Action2)> */ func() bool { position11, tokenIndex11 := position, tokenIndex { position12 := position { add(ruleAction1, position) } if !_rules[ruleExpression]() { goto l11 } l14: { position15, tokenIndex15 := position, tokenIndex { position16 := position if buffer[position] != rune('|') { goto l15 } position++ if !_rules[ruleSpacing]() { goto l15 } add(rulePipe, position16) } if !_rules[ruleExpression]() { goto l15 } goto l14 l15: position, tokenIndex = position15, tokenIndex15 } { add(ruleAction2, position) } add(rulePipeline, position12) } return true l11: position, tokenIndex = position11, tokenIndex11 return false }, /* 3 Expression <- <(FunctionCall / Nesting)> */ func() bool { position18, tokenIndex18 := position, tokenIndex { position19 := position { position20, tokenIndex20 := position, tokenIndex { position22 := position { position23, tokenIndex23 := position, tokenIndex if !_rules[ruleIdentifier]() { goto l24 } goto l23 l24: position, tokenIndex = position23, tokenIndex23 { position25 := position { position26 := position { position27 := position { position28, tokenIndex28 := position, tokenIndex if buffer[position] != rune('<') { goto l29 } position++ if buffer[position] != rune('=') { goto l29 } position++ goto l28 l29: position, tokenIndex = position28, tokenIndex28 if buffer[position] != rune('>') { goto l30 } position++ if buffer[position] != rune('=') { goto l30 } position++ goto l28 l30: position, tokenIndex = position28, tokenIndex28 { switch buffer[position] { case '>': if buffer[position] != rune('>') { goto l21 } position++ break case '!': if buffer[position] != rune('!') { goto l21 } position++ if buffer[position] != rune('=') { goto l21 } position++ break case '=': if buffer[position] != rune('=') { goto l21 } position++ if buffer[position] != rune('=') { goto l21 } position++ break default: if buffer[position] != rune('<') { goto l21 } position++ break } } } l28: add(ruleOperatorSymbols, position27) } add(rulePegText, position26) } if !_rules[ruleSpacing]() { goto l21 } add(ruleOperator, position25) } } l23: { add(ruleAction3, position) } l33: { position34, tokenIndex34 := position, tokenIndex { position35 := position { position36, tokenIndex36 := position, tokenIndex { position38 := position if !_rules[ruleIdentifier]() { goto l36 } { add(ruleAction9, position) } { position40 := position if buffer[position] != rune(':') { goto l36 } position++ if !_rules[ruleSpacing]() { goto l36 } add(ruleColon, position40) } add(ruleKeywordSpecifier, position38) } goto l37 l36: position, tokenIndex = position36, tokenIndex36 } l37: { position41, tokenIndex41 := position, tokenIndex { position43 := position { position44 := position { position45, tokenIndex45 := position, tokenIndex { position47 := position { position48, tokenIndex48 := position, tokenIndex if buffer[position] != rune('t') { goto l49 } position++ goto l48 l49: position, tokenIndex = position48, tokenIndex48 if buffer[position] != rune('T') { goto l46 } position++ } l48: { position50, tokenIndex50 := position, tokenIndex if buffer[position] != rune('r') { goto l51 } position++ goto l50 l51: position, tokenIndex = position50, tokenIndex50 if buffer[position] != rune('R') { goto l46 } position++ } l50: { position52, tokenIndex52 := position, tokenIndex if buffer[position] != rune('u') { goto l53 } position++ goto l52 l53: position, tokenIndex = position52, tokenIndex52 if buffer[position] != rune('U') { goto l46 } position++ } l52: { position54, tokenIndex54 := position, tokenIndex if buffer[position] != rune('e') { goto l55 } position++ goto l54 l55: position, tokenIndex = position54, tokenIndex54 if buffer[position] != rune('E') { goto l46 } position++ } l54: add(ruleTrue, position47) } goto l45 l46: position, tokenIndex = position45, tokenIndex45 { position56 := position { position57, tokenIndex57 := position, tokenIndex if buffer[position] != rune('f') { goto l58 } position++ goto l57 l58: position, tokenIndex = position57, tokenIndex57 if buffer[position] != rune('F') { goto l42 } position++ } l57: { position59, tokenIndex59 := position, tokenIndex if buffer[position] != rune('a') { goto l60 } position++ goto l59 l60: position, tokenIndex = position59, tokenIndex59 if buffer[position] != rune('A') { goto l42 } position++ } l59: { position61, tokenIndex61 := position, tokenIndex if buffer[position] != rune('l') { goto l62 } position++ goto l61 l62: position, tokenIndex = position61, tokenIndex61 if buffer[position] != rune('L') { goto l42 } position++ } l61: { position63, tokenIndex63 := position, tokenIndex if buffer[position] != rune('s') { goto l64 } position++ goto l63 l64: position, tokenIndex = position63, tokenIndex63 if buffer[position] != rune('S') { goto l42 } position++ } l63: { position65, tokenIndex65 := position, tokenIndex if buffer[position] != rune('e') { goto l66 } position++ goto l65 l66: position, tokenIndex = position65, tokenIndex65 if buffer[position] != rune('E') { goto l42 } position++ } l65: add(ruleFalse, position56) } } l45: add(rulePegText, position44) } { position67, tokenIndex67 := position, tokenIndex if !_rules[rulePatternChars]() { goto l67 } goto l42 l67: position, tokenIndex = position67, tokenIndex67 } if !_rules[ruleSpacing]() { goto l42 } add(ruleBoolean, position43) } { add(ruleAction5, position) } goto l41 l42: position, tokenIndex = position41, tokenIndex41 { position70 := position { position71 := position { position72, tokenIndex72 := position, tokenIndex { position74 := position if buffer[position] != rune('-') { goto l72 } position++ add(ruleMinus, position74) } goto l73 l72: position, tokenIndex = position72, tokenIndex72 } l73: { position75, tokenIndex75 := position, tokenIndex { position77 := position { position78, tokenIndex78 := position, tokenIndex if !_rules[ruleIntegralNumber]() { goto l78 } goto l79 l78: position, tokenIndex = position78, tokenIndex78 } l79: if buffer[position] != rune('.') { goto l76 } position++ if !_rules[ruleIntegralNumber]() { goto l76 } add(ruleFloatingNumber, position77) } goto l75 l76: position, tokenIndex = position75, tokenIndex75 if !_rules[ruleIntegralNumber]() { goto l69 } } l75: add(rulePegText, position71) } { position80, tokenIndex80 := position, tokenIndex if !_rules[rulePatternChars]() { goto l80 } goto l69 l80: position, tokenIndex = position80, tokenIndex80 } if !_rules[ruleSpacing]() { goto l69 } add(ruleNumber, position70) } { add(ruleAction6, position) } goto l41 l69: position, tokenIndex = position41, tokenIndex41 { switch buffer[position] { case '(': if !_rules[ruleNesting]() { goto l34 } break case '"': { position83 := position if !_rules[ruleQuoteChar]() { goto l34 } { position84 := position l85: { position86, tokenIndex86 := position, tokenIndex { position87, tokenIndex87 := position, tokenIndex if buffer[position] != rune('"') { goto l87 } position++ goto l86 l87: position, tokenIndex = position87, tokenIndex87 } if !matchDot() { goto l86 } goto l85 l86: position, tokenIndex = position86, tokenIndex86 } add(rulePegText, position84) } if !_rules[ruleQuoteChar]() { goto l34 } if !_rules[ruleSpacing]() { goto l34 } add(ruleStringLiteral, position83) } { add(ruleAction8, position) } break default: { position89 := position { position90 := position if !_rules[rulePatternChars]() { goto l34 } l91: { position92, tokenIndex92 := position, tokenIndex if !_rules[rulePatternChars]() { goto l92 } goto l91 l92: position, tokenIndex = position92, tokenIndex92 } add(rulePegText, position90) } if !_rules[ruleSpacing]() { goto l34 } add(rulePattern, position89) } { add(ruleAction7, position) } break } } } l41: add(ruleArgument, position35) } goto l33 l34: position, tokenIndex = position34, tokenIndex34 } { add(ruleAction4, position) } add(ruleFunctionCall, position22) } goto l20 l21: position, tokenIndex = position20, tokenIndex20 if !_rules[ruleNesting]() { goto l18 } } l20: add(ruleExpression, position19) } return true l18: position, tokenIndex = position18, tokenIndex18 return false }, /* 4 FunctionCall <- <((Identifier / Operator) Action3 Argument* Action4)> */ nil, /* 5 Argument <- <(KeywordSpecifier? ((Boolean Action5) / (Number Action6) / ((&('(') Nesting) | (&('"') (StringLiteral Action8)) | (&('$' | '*' | ',' | '-' | '.' | '/' | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '?' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z' | '[' | '\\' | ']' | '^' | '_' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z' | '{' | '}') (Pattern Action7)))))> */ nil, /* 6 KeywordSpecifier <- <(Identifier Action9 Colon)> */ nil, /* 7 Nesting <- <(LParenthesis Pipeline RParenthesis)> */ func() bool { position98, tokenIndex98 := position, tokenIndex { position99 := position { position100 := position if buffer[position] != rune('(') { goto l98 } position++ if !_rules[ruleSpacing]() { goto l98 } add(ruleLParenthesis, position100) } if !_rules[rulePipeline]() { goto l98 } { position101 := position if buffer[position] != rune(')') { goto l98 } position++ if !_rules[ruleSpacing]() { goto l98 } add(ruleRParenthesis, position101) } add(ruleNesting, position99) } return true l98: position, tokenIndex = position98, tokenIndex98 return false }, /* 8 Spacing <- <((&('#') Comment) | (&('\n' | '\r') EOL) | (&('\t' | ' ') Space))*> */ func() bool { { position103 := position l104: { position105, tokenIndex105 := position, tokenIndex { switch buffer[position] { case '#': { position107 := position { position108 := position if buffer[position] != rune('#') { goto l105 } position++ add(ruleCommentStart, position108) } l109: { position110, tokenIndex110 := position, tokenIndex { position111, tokenIndex111 := position, tokenIndex if !_rules[ruleEOL]() { goto l111 } goto l110 l111: position, tokenIndex = position111, tokenIndex111 } if !matchDot() { goto l110 } goto l109 l110: position, tokenIndex = position110, tokenIndex110 } add(ruleComment, position107) } break case '\n', '\r': if !_rules[ruleEOL]() { goto l105 } break default: { position112 := position { position113, tokenIndex113 := position, tokenIndex if buffer[position] != rune(' ') { goto l114 } position++ goto l113 l114: position, tokenIndex = position113, tokenIndex113 if buffer[position] != rune('\t') { goto l105 } position++ } l113: add(ruleSpace, position112) } break } } goto l104 l105: position, tokenIndex = position105, tokenIndex105 } add(ruleSpacing, position103) } return true }, /* 9 Space <- <(' ' / '\t')> */ nil, /* 10 EOL <- <(('\r' '\n') / '\n' / '\r')> */ func() bool { position116, tokenIndex116 := position, tokenIndex { position117 := position { position118, tokenIndex118 := position, tokenIndex if buffer[position] != rune('\r') { goto l119 } position++ if buffer[position] != rune('\n') { goto l119 } position++ goto l118 l119: position, tokenIndex = position118, tokenIndex118 if buffer[position] != rune('\n') { goto l120 } position++ goto l118 l120: position, tokenIndex = position118, tokenIndex118 if buffer[position] != rune('\r') { goto l116 } position++ } l118: add(ruleEOL, position117) } return true l116: position, tokenIndex = position116, tokenIndex116 return false }, /* 11 Comment <- <(CommentStart (!EOL .)*)> */ nil, /* 12 CommentStart <- <'#'> */ nil, /* 13 Identifier <- <(<(IdentifierStart IdentifierChars*)> Spacing)> */ func() bool { position123, tokenIndex123 := position, tokenIndex { position124 := position { position125 := position if !_rules[ruleIdentifierStart]() { goto l123 } l126: { position127, tokenIndex127 := position, tokenIndex if !_rules[ruleIdentifierChars]() { goto l127 } goto l126 l127: position, tokenIndex = position127, tokenIndex127 } add(rulePegText, position125) } if !_rules[ruleSpacing]() { goto l123 } add(ruleIdentifier, position124) } return true l123: position, tokenIndex = position123, tokenIndex123 return false }, /* 14 IdentifierStart <- <((&('_') '_') | (&('A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z') [A-Z]) | (&('a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z') [a-z]))> */ func() bool { position128, tokenIndex128 := position, tokenIndex { position129 := position { switch buffer[position] { case '_': if buffer[position] != rune('_') { goto l128 } position++ break case 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z': if c := buffer[position]; c < rune('A') || c > rune('Z') { goto l128 } position++ break default: if c := buffer[position]; c < rune('a') || c > rune('z') { goto l128 } position++ break } } add(ruleIdentifierStart, position129) } return true l128: position, tokenIndex = position128, tokenIndex128 return false }, /* 15 IdentifierChars <- <((&('\\') '\\') | (&('/') '/') | (&('-') '-') | (&('.') '.') | (&('0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9') [0-9]) | (&('A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z' | '_' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z') IdentifierStart))> */ func() bool { position131, tokenIndex131 := position, tokenIndex { position132 := position { switch buffer[position] { case '\\': if buffer[position] != rune('\\') { goto l131 } position++ break case '/': if buffer[position] != rune('/') { goto l131 } position++ break case '-': if buffer[position] != rune('-') { goto l131 } position++ break case '.': if buffer[position] != rune('.') { goto l131 } position++ break case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': if c := buffer[position]; c < rune('0') || c > rune('9') { goto l131 } position++ break default: if !_rules[ruleIdentifierStart]() { goto l131 } break } } add(ruleIdentifierChars, position132) } return true l131: position, tokenIndex = position131, tokenIndex131 return false }, /* 16 Operator <- <(<OperatorSymbols> Spacing)> */ nil, /* 17 OperatorSymbols <- <(('<' '=') / ('>' '=') / ((&('>') '>') | (&('!') ('!' '=')) | (&('=') ('=' '=')) | (&('<') '<')))> */ nil, /* 18 Boolean <- <(<(True / False)> !PatternChars Spacing)> */ nil, /* 19 True <- <(('t' / 'T') ('r' / 'R') ('u' / 'U') ('e' / 'E'))> */ nil, /* 20 False <- <(('f' / 'F') ('a' / 'A') ('l' / 'L') ('s' / 'S') ('e' / 'E'))> */ nil, /* 21 Number <- <(<(Minus? (FloatingNumber / IntegralNumber))> !PatternChars Spacing)> */ nil, /* 22 IntegralNumber <- <[0-9]+> */ func() bool { position140, tokenIndex140 := position, tokenIndex { position141 := position if c := buffer[position]; c < rune('0') || c > rune('9') { goto l140 } position++ l142: { position143, tokenIndex143 := position, tokenIndex if c := buffer[position]; c < rune('0') || c > rune('9') { goto l143 } position++ goto l142 l143: position, tokenIndex = position143, tokenIndex143 } add(ruleIntegralNumber, position141) } return true l140: position, tokenIndex = position140, tokenIndex140 return false }, /* 23 FloatingNumber <- <(IntegralNumber? '.' IntegralNumber)> */ nil, /* 24 Minus <- <'-'> */ nil, /* 25 StringLiteral <- <(QuoteChar <(!'"' .)*> QuoteChar Spacing)> */ nil, /* 26 QuoteChar <- <'"'> */ func() bool { position147, tokenIndex147 := position, tokenIndex { position148 := position if buffer[position] != rune('"') { goto l147 } position++ add(ruleQuoteChar, position148) } return true l147: position, tokenIndex = position147, tokenIndex147 return false }, /* 27 Pattern <- <(<PatternChars+> Spacing)> */ nil, /* 28 PatternChars <- <(IdentifierChars / GlobSymbols)> */ func() bool { position150, tokenIndex150 := position, tokenIndex { position151 := position { position152, tokenIndex152 := position, tokenIndex if !_rules[ruleIdentifierChars]() { goto l153 } goto l152 l153: position, tokenIndex = position152, tokenIndex152 { position154 := position { switch buffer[position] { case '$': if buffer[position] != rune('$') { goto l150 } position++ break case '^': if buffer[position] != rune('^') { goto l150 } position++ break case ',': if buffer[position] != rune(',') { goto l150 } position++ break case '?': if buffer[position] != rune('?') { goto l150 } position++ break case '*': if buffer[position] != rune('*') { goto l150 } position++ break case ']': if buffer[position] != rune(']') { goto l150 } position++ break case '[': if buffer[position] != rune('[') { goto l150 } position++ break case '}': if buffer[position] != rune('}') { goto l150 } position++ break default: if buffer[position] != rune('{') { goto l150 } position++ break } } add(ruleGlobSymbols, position154) } } l152: add(rulePatternChars, position151) } return true l150: position, tokenIndex = position150, tokenIndex150 return false }, /* 29 GlobSymbols <- <((&('$') '$') | (&('^') '^') | (&(',') ',') | (&('?') '?') | (&('*') '*') | (&(']') ']') | (&('[') '[') | (&('}') '}') | (&('{') '{'))> */ nil, /* 30 Semicolon <- <(';' Spacing)> */ nil, /* 31 Equals <- <('=' Spacing)> */ nil, /* 32 Pipe <- <('|' Spacing)> */ nil, /* 33 LParenthesis <- <('(' Spacing)> */ nil, /* 34 RParenthesis <- <(')' Spacing)> */ nil, /* 35 Colon <- <(':' Spacing)> */ nil, /* 36 EOF <- <!.> */ nil, /* 38 Action0 <- <{ p.newMacro(text) }> */ nil, /* 39 Action1 <- <{ p.newPipeline() }> */ nil, /* 40 Action2 <- <{ p.endPipeline() }> */ nil, /* 41 Action3 <- <{ p.newExpression(text) }> */ nil, /* 42 Action4 <- <{ p.endExpression() }> */ nil, /* 43 Action5 <- <{ p.newBooleanArgument(text) }> */ nil, /* 44 Action6 <- <{ p.newNumericArgument(text) }> */ nil, /* 45 Action7 <- <{ p.newPatternArgument(text) }> */ nil, /* 46 Action8 <- <{ p.newStringLiteralArgument(text) }> */ nil, /* 47 Action9 <- <{ p.newKeywordArgument(text) }> */ nil, nil, } p.rules = _rules }
Java
<?php /** * The Campaigns endpoint. This is a campaign of type SMS. * * @link https://github.com/PortaText/docs/wiki/REST-API#api_campaigns Campaigns endpoint. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache 2.0 * @author Marcelo Gornstein <marcelog@portatext.com> * @copyright 2015 PortaText */ namespace PortaText\Command\Api; use PortaText\Command\Base; /** * The Campaigns endpoint. This is a campaign of type SMS. */ class SmsCampaign extends Campaigns { /** * Specifies source sms service. * * @param string $serviceId SMS Service ID. * * @return PortaText\Command\ICommand */ public function fromService($serviceId) { return $this->setArgument("service_id", $serviceId); } /** * Sets the template id to use. * * @param integer $templateId Use the given template as the message body. * @param array $variables Variables to use in template. * * @return PortaText\Command\ICommand */ public function useTemplate($templateId, array $variables = array()) { $this->setSetting("template_id", $templateId); return $this->setSetting("variables", $variables); } /** * Sets the message text. * * @param string $text Message text. * * @return PortaText\Command\ICommand */ public function text($text) { return $this->setSetting("text", $text); } /** * Standard constructor. * */ public function __construct() { parent::__construct(); $this->setArgument("type", "sms"); } }
Java
/** Copyright 2017 Andrea "Stock" Stocchero Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * Contains the {@link org.pepstock.charba.client.annotation.AnnotationPlugin#ID} plugin elements interfaces to use in the callbacks and events. * * @author Andrea "Stock" Stocchero * */ package org.pepstock.charba.client.annotation.elements;
Java
# # Copyright (C) 2010-2016 dtk contributors # # This file is part of the dtk project. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module DTK::Client; class Operation::Service::TaskStatus::StreamMode class Element class TaskStart < self def self.get(task_status_handle, opts = {}) opts_get = { :start_index => 0, :end_index => 0 }.merge(opts) get_task_status_elements(task_status_handle, :task_start, opts_get) end def render return if @ignore_stage_level_info msg = "start '#{field?(:display_name) || 'Workflow'}'" render_line msg, :bracket => true, :started_at => field?(:started_at) render_empty_lines 2 end end end end; end
Java
/* Copyright 2016, 2020 Nationale-Nederlanden, 2020-2021 WeAreFrank! Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package nl.nn.adapterframework.pipes; import java.io.ByteArrayOutputStream; import java.io.IOException; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.Adapter; import nl.nn.adapterframework.core.PipeLineSession; import nl.nn.adapterframework.core.PipeRunException; import nl.nn.adapterframework.core.PipeRunResult; import nl.nn.adapterframework.doc.IbisDoc; import nl.nn.adapterframework.http.RestListenerUtils; import nl.nn.adapterframework.soap.WsdlGenerator; import nl.nn.adapterframework.stream.Message; import nl.nn.adapterframework.util.StreamUtil; /** * Generate WSDL of parent or specified adapter. * * @author Jaco de Groot */ public class WsdlGeneratorPipe extends FixedForwardPipe { private String from = "parent"; @Override public void configure() throws ConfigurationException { super.configure(); if (!"parent".equals(getFrom()) && !"input".equals(getFrom())) { throw new ConfigurationException("from should either be parent or input"); } } @Override public PipeRunResult doPipe(Message message, PipeLineSession session) throws PipeRunException { String result = null; Adapter adapter; try { if ("input".equals(getFrom())) { String adapterName = message.asString(); adapter = getAdapter().getConfiguration().getIbisManager().getRegisteredAdapter(adapterName); if (adapter == null) { throw new PipeRunException(this, "Could not find adapter: " + adapterName); } } else { adapter = getPipeLine().getAdapter(); } } catch (IOException e) { throw new PipeRunException(this, "Could not determine adapter name", e); } try { String generationInfo = "at " + RestListenerUtils.retrieveRequestURL(session); WsdlGenerator wsdl = new WsdlGenerator(adapter.getPipeLine(), generationInfo); wsdl.init(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); wsdl.wsdl(outputStream, null); result = outputStream.toString(StreamUtil.DEFAULT_INPUT_STREAM_ENCODING); } catch (Exception e) { throw new PipeRunException(this, "Could not generate WSDL for adapter [" + adapter.getName() + "]", e); } return new PipeRunResult(getSuccessForward(), result); } public String getFrom() { return from; } @IbisDoc({"either parent (adapter of pipeline which contains this pipe) or input (name of adapter specified by input of pipe)", "parent"}) public void setFrom(String from) { this.from = from; } }
Java
/* * #%L * Diana UI Core * %% * Copyright (C) 2014 Diana UI * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.dianaui.universal.core.client.ui.html; import com.dianaui.universal.core.client.ui.base.AbstractTextWidget; import com.dianaui.universal.core.client.ui.constants.ElementTags; import com.google.gwt.dom.client.Document; /** * Simple {@code <strong>} tag to emphasize words * * @author Joshua Godi */ public class Strong extends AbstractTextWidget { public Strong() { super(Document.get().createElement(ElementTags.STRONG)); } public Strong(final String text) { this(); setHTML(text); } }
Java
/* * #%L * Diana UI Core * %% * Copyright (C) 2014 Diana UI * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.dianaui.universal.core.client.ui.constants; import com.dianaui.universal.core.client.ui.base.helper.EnumHelper; import com.google.gwt.dom.client.Style; /** * Only relevant to horizontal forms * * @author Xiaodong Sun */ public enum FormGroupSize implements Size, Style.HasCssName { LARGE("form-group-lg"), DEFAULT(""), SMALL("form-group-sm"),; private final String cssClass; private FormGroupSize(final String cssClass) { this.cssClass = cssClass; } @Override public String getCssName() { return cssClass; } public static FormGroupSize fromStyleName(final String styleName) { return EnumHelper.fromStyleName(styleName, FormGroupSize.class, DEFAULT); } }
Java
# frozen_string_literal: true require 'github_request' class GithubPostReceiveHook SUBSCRIBE_NAME = "web" def initialize(repository, oauth_token) @repository = repository @oauth_token = oauth_token @root_url = "#{repository.base_api_url}/hooks" @hook_url = "#{repository.base_api_url}/hooks/#{repository.github_post_receive_hook_id}" @receive_url = Rails.application.routes.url_helpers.pull_request_build_url @interested_events = @repository.interested_github_events @subscribe_args = {:name => "web", :config => {:url => @receive_url}, :events => @interested_events, :active => true} end def subscribe! if @repository.github_post_receive_hook_id update_repository_hook! else synchronize_or_create! end end private def update_repository_hook! begin GithubRequest.patch(@hook_url, @subscribe_args, @oauth_token) rescue GithubRequest::ResponseError => e if e.response.class == Net::HTTPNotFound create_hook else raise e end end end def synchronize_or_create! begin response_body = GithubRequest.get(@root_url, @oauth_token) existing_hooks = JSON.parse(response_body) existing_subscription = existing_hooks.detect do |hook| hook["active"] && hook["events"] == @interested_events && hook["config"]["url"] == @receive_url end if existing_subscription @repository.update_attributes(:github_post_receive_hook_id => existing_subscription["id"]) return response_body end rescue GithubRequest::ResponseError Rails.logger.info("Failed to get hooks for #{@root_url}") end create_hook end def create_hook GithubRequest.post(@root_url, @subscribe_args, @oauth_token) end end
Java
package org.swtk.commons.dict.wiktionary.generated.a.u.v; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.swtk.common.dict.dto.wiktionary.Entry; import com.trimc.blogger.commons.utils.GsonUtils; public class WiktionaryAUV000 { private static Map<String, Entry> map = new HashMap<String, Entry>(); static { add("auvergne", "{\"term\":\"auvergne\", \"etymology\":{\"influencers\":[], \"languages\":[], \"text\":\"{{rfe|lang\u003den}}\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"A region and historical province of France\", \"priority\":1}]}, \"synonyms\":{}}"); } private static void add(String term, String json) { map.put(term, GsonUtils.toObject(json, Entry.class)); } public static Entry get(String term) { return map.get(term); } public static boolean has(String term) { return null != get(term); } public static Collection<String> terms() { return map.keySet(); } }
Java
# frozen_string_literal: true # rubocop:disable Layout/LineLength # == Schema Information # # Table name: form_items # # id :uuid not null, primary key # all_levels_required :boolean default(FALSE), not null # ancestry :text # ancestry_depth :integer not null # default :string # disabled :boolean default(FALSE), not null # display_if :string default("always"), not null # group_hint_translations :jsonb # group_item_name_translations :jsonb # group_name_translations :jsonb # hidden :boolean default(FALSE), not null # one_screen :boolean # rank :integer not null # read_only :boolean # repeatable :boolean # required :boolean default(FALSE), not null # type :string(255) not null # created_at :datetime not null # updated_at :datetime not null # form_id :uuid not null # form_old_id :integer # mission_id :uuid # old_id :integer # question_id :uuid # question_old_id :integer # # Indexes # # index_form_items_on_ancestry (ancestry) # index_form_items_on_form_id (form_id) # index_form_items_on_form_id_and_question_id (form_id,question_id) UNIQUE # index_form_items_on_mission_id (mission_id) # index_form_items_on_question_id (question_id) # # Foreign Keys # # form_items_form_id_fkey (form_id => forms.id) ON DELETE => restrict ON UPDATE => restrict # form_items_mission_id_fkey (mission_id => missions.id) ON DELETE => restrict ON UPDATE => restrict # form_items_question_id_fkey (question_id => questions.id) ON DELETE => restrict ON UPDATE => restrict # # rubocop:enable Layout/LineLength require "rails_helper" describe Questioning do it "mission should get copied from question on creation" do f = create(:form, question_types: %w[integer], mission: get_mission) expect(f.questionings[0].mission).to eq(get_mission) end describe "normalization" do # Run valid? to trigger normalization let(:q_attrs) { {} } let(:question) { create(:question, q_attrs) } let(:qing) { build(:questioning, submitted.merge(question: question)).tap(&:valid?) } subject { submitted.keys.index_with { |k| qing.send(k) }.to_h } describe "hidden/disabled/required/read_only" do context do let(:submitted) { {hidden: true, disabled: false, required: true, read_only: false} } it { is_expected.to eq(hidden: true, disabled: false, required: false, read_only: false) } end context do let(:submitted) { {hidden: false, disabled: true, required: true, read_only: false} } it { is_expected.to eq(hidden: false, disabled: true, required: true, read_only: false) } end context do let(:submitted) { {hidden: true, disabled: true, required: false, read_only: false} } it { is_expected.to eq(hidden: true, disabled: true, required: false, read_only: false) } end context do let(:submitted) { {hidden: false, disabled: false, required: true, read_only: false} } it { is_expected.to eq(hidden: false, disabled: false, required: true, read_only: false) } end context do let(:submitted) { {hidden: false, disabled: false, required: true, read_only: true} } it { is_expected.to eq(hidden: false, disabled: false, required: false, read_only: true) } end context do let(:submitted) { {hidden: false, disabled: false, required: false, read_only: true} } it { is_expected.to eq(hidden: false, disabled: false, required: false, read_only: true) } end end describe "preload_last_saved and default" do context do let(:submitted) { {preload_last_saved: false, default: "foo"} } it { is_expected.to eq(preload_last_saved: false, default: "foo") } end context do let(:submitted) { {preload_last_saved: true, default: "foo"} } it { is_expected.to eq(preload_last_saved: true, default: nil) } end end describe "question metadata and hidden/disabled/required" do context do let(:q_attrs) { {qtype_name: "datetime", metadata_type: "formstart"} } let(:submitted) { {required: true, hidden: false, disabled: false} } it { is_expected.to eq(required: false, hidden: true, disabled: false) } end context do let(:q_attrs) { {qtype_name: "datetime", metadata_type: "formstart"} } let(:submitted) { {required: "", hidden: true, disabled: true} } it { is_expected.to eq(required: false, hidden: true, disabled: true) } end context do let(:q_attrs) { {qtype_name: "datetime", metadata_type: ""} } let(:submitted) { {required: true, disabled: false} } it { is_expected.to eq(required: true, disabled: false) } end end describe "question metadata and condition" do let(:condition) { build(:condition) } context "not adding a metadata_type" do let(:q_attrs) { {qtype_name: "datetime", metadata_type: nil} } let(:submitted) { {display_conditions: [condition]} } it "should not destroy existing conditions" do is_expected.to eq(display_conditions: [condition]) end end context "add a metadata_type with an existing condition" do let(:q_attrs) { {qtype_name: "datetime", metadata_type: "formstart"} } let(:submitted) { {display_conditions: [condition]} } it "should destroy existing conditions" do is_expected.to eq(display_conditions: []) expect(condition).to be_destroyed end end context "add a metadata_type with no existing conditions" do let(:q_attrs) { {qtype_name: "datetime", metadata_type: "formstart"} } let(:submitted) { {display_conditions: []} } it "should not change the display conditions" do is_expected.to eq(display_conditions: []) end end end describe "all_levels_required" do let(:question) { form.c[0].question } context "multilevel, required question" do let(:form) { create(:form, question_types: %w[multilevel_select_one]) } let(:submitted) { {all_levels_required: true, required: true} } it "should leave all_levels_required alone" do is_expected.to eq(all_levels_required: true, required: true) end end context "multilevel, non-required question" do let(:form) { create(:form, question_types: %w[multilevel_select_one]) } let(:submitted) { {all_levels_required: true, required: false} } it "should reset all_levels_required" do is_expected.to eq(all_levels_required: false, required: false) end end context "non-multilevel question" do let(:form) { create(:form, question_types: %w[select_one]) } let(:submitted) { {all_levels_required: true, required: true} } it "should reset all_levels_required" do is_expected.to eq(all_levels_required: false, required: true) end end context "non-select question" do let(:form) { create(:form, question_types: %w[integer]) } let(:submitted) { {all_levels_required: true, required: true} } it "should reset all_levels_required" do is_expected.to eq(all_levels_required: false, required: true) end end end end describe "validation" do let(:questioning) { build(:questioning, default: "Item: calc($Foo + 4) ") } # Detailed testing of this validator is in own file. describe "DynamicPatternValidator" do it "is hooked up properly" do expect(questioning).to be_invalid expect(questioning.errors[:default].join).to match(/must surround/) end end it "should fail properly when there is no qtype" do questioning.qtype_name = nil expect { questioning.save }.not_to raise_error end end end
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package fixture.simple; import java.util.List; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.MemberOrder; import org.apache.isis.applib.annotation.Named; import org.apache.isis.applib.annotation.Prototype; import org.apache.isis.applib.fixturescripts.FixtureResult; import org.apache.isis.applib.fixturescripts.FixtureScript; import org.apache.isis.applib.fixturescripts.FixtureScripts; import org.apache.isis.applib.fixturescripts.SimpleFixtureScript; /** * Enables fixtures to be installed from the application. */ @Named("Prototyping") @DomainService(menuOrder = "20") public class SimpleObjectsFixturesService extends FixtureScripts { public SimpleObjectsFixturesService() { super("fixture.simple"); } //@Override // compatibility with core 1.5.0 public FixtureScript default0RunFixtureScript() { return findFixtureScriptFor(SimpleFixtureScript.class); } /** * Raising visibility to <tt>public</tt> so that choices are available for first param * of {@link #runFixtureScript(FixtureScript, String)}. */ @Override public List<FixtureScript> choices0RunFixtureScript() { return super.choices0RunFixtureScript(); } // ////////////////////////////////////// @Prototype @MemberOrder(sequence="20") public Object installFixturesAndReturnFirst() { final List<FixtureResult> run = findFixtureScriptFor(SimpleObjectsFixture.class).run(null); return run.get(0).getObject(); } @Prototype @MemberOrder(sequence="20") public Object instalarFixturesAlumnos() { final List<FixtureResult> run = findFixtureScriptFor(AlumnosFixture.class).run(null); return run.get(0).getObject(); } @Prototype @MemberOrder(sequence="20") public Object instalarFixturesCursos() { final List<FixtureResult> run = findFixtureScriptFor(CursosFixture.class).run(null); return run.get(0).getObject(); } }
Java
package org.qcri.rheem.basic.operators; import org.apache.commons.lang3.Validate; import org.qcri.rheem.core.api.Configuration; import org.qcri.rheem.core.function.DistinctPredicateDescriptor; import org.qcri.rheem.core.function.PredicateDescriptor; import org.qcri.rheem.core.optimizer.OptimizationContext; import org.qcri.rheem.core.optimizer.ProbabilisticDoubleInterval; import org.qcri.rheem.core.optimizer.cardinality.CardinalityEstimate; import org.qcri.rheem.core.optimizer.cardinality.CardinalityEstimator; import org.qcri.rheem.core.optimizer.cardinality.DefaultCardinalityEstimator; import org.qcri.rheem.core.plan.rheemplan.UnaryToUnaryOperator; import org.qcri.rheem.core.types.DataSetType; import java.util.Optional; /** * This operator returns the distinct elements in this dataset. */ public class DistinctOperator<Type> extends UnaryToUnaryOperator<Type, Type> { protected final DistinctPredicateDescriptor<Type> predicateDescriptor; /** * Creates a new instance. * * @param type type of the dataunit elements */ public DistinctOperator(DataSetType<Type> type) { super(type, type, false); this.predicateDescriptor = null; } public DistinctOperator(DataSetType<Type> type, DistinctPredicateDescriptor<Type> predicateDescriptor) { super(type, type, false); this.predicateDescriptor = predicateDescriptor; } /** * Creates a new instance. * * @param typeClass type of the dataunit elements */ public DistinctOperator(Class<Type> typeClass) { this(DataSetType.createDefault(typeClass)); } /** * Copies an instance (exclusive of broadcasts). * * @param that that should be copied */ public DistinctOperator(DistinctOperator<Type> that) { super(that); this.predicateDescriptor = that.getPredicateDescriptor(); } public DistinctPredicateDescriptor<Type> getPredicateDescriptor() { return this.predicateDescriptor; } public String getSelectKeyString(){ if (this.getPredicateDescriptor() != null && this.getPredicateDescriptor().getUdfSelectivity() != null){ return this.getPredicateDescriptor().getUdfSelectivityKeyString(); } else { return ""; } } // // Assume with a confidence of 0.7 that 70% of the data quanta are pairwise distinct. // return Optional.of(new DefaultCardinalityEstimator(0.7d, 1, this.isSupportingBroadcastInputs(), // inputCards -> (long) (inputCards[0] * 0.7d))); // TODO JRK: Do not make baseline worse @Override public Optional<org.qcri.rheem.core.optimizer.cardinality.CardinalityEstimator> createCardinalityEstimator( final int outputIndex, final Configuration configuration) { Validate.inclusiveBetween(0, this.getNumOutputs() - 1, outputIndex); return Optional.of(new DistinctOperator.CardinalityEstimator(configuration)); } private class CardinalityEstimator implements org.qcri.rheem.core.optimizer.cardinality.CardinalityEstimator { /** * The expected selectivity to be applied in this instance. */ private final ProbabilisticDoubleInterval selectivity; Configuration configuration; public CardinalityEstimator(Configuration configuration) { this.selectivity = configuration.getUdfSelectivityProvider().provideFor(DistinctOperator.this.predicateDescriptor); this.configuration = configuration; } @Override public CardinalityEstimate estimate(OptimizationContext optimizationContext, CardinalityEstimate... inputEstimates) { Validate.isTrue(inputEstimates.length == DistinctOperator.this.getNumInputs()); final CardinalityEstimate inputEstimate = inputEstimates[0]; String mode = this.configuration.getStringProperty("rheem.optimizer.sr.mode", "best"); if (mode.equals("best")){ mode = this.selectivity.getBest(); } if (mode.equals("lin")) { return new CardinalityEstimate( (long) Math.max(0, ((inputEstimate.getLowerEstimate() * this.selectivity.getCoeff() + this.selectivity.getIntercept()) * inputEstimate.getLowerEstimate())), (long) Math.max(0, ((inputEstimate.getUpperEstimate() * this.selectivity.getCoeff() + this.selectivity.getIntercept()) * inputEstimate.getUpperEstimate())), inputEstimate.getCorrectnessProbability() * this.selectivity.getCorrectnessProbability() ); } else if (mode.equals("log")) { return new CardinalityEstimate( (long) Math.max(0, ((Math.log(inputEstimate.getLowerEstimate()) * this.selectivity.getLog_coeff() + this.selectivity.getLog_intercept()) * inputEstimate.getLowerEstimate())), (long) Math.max(0, ((Math.log(inputEstimate.getUpperEstimate()) * this.selectivity.getLog_coeff() + this.selectivity.getLog_intercept()) * inputEstimate.getUpperEstimate())), inputEstimate.getCorrectnessProbability() * this.selectivity.getCorrectnessProbability() ); } else { return new CardinalityEstimate( (long) Math.max(0, (inputEstimate.getLowerEstimate() * this.selectivity.getLowerEstimate())), (long) Math.max(0, (inputEstimate.getUpperEstimate() * this.selectivity.getUpperEstimate())), inputEstimate.getCorrectnessProbability() * this.selectivity.getCorrectnessProbability() ); } } } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.phonemetra.turbo.launcher; import com.phonemetra.turbo.launcher.R; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.Region; import android.graphics.Region.Op; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.TypedValue; import android.view.MotionEvent; import android.widget.TextView; public class BubbleTextView extends TextView { static final float SHADOW_LARGE_RADIUS = 4.0f; static final float SHADOW_SMALL_RADIUS = 1.75f; static final float SHADOW_Y_OFFSET = 2.0f; static final int SHADOW_LARGE_COLOUR = 0xDD000000; static final int SHADOW_SMALL_COLOUR = 0xCC000000; static final float PADDING_H = 8.0f; static final float PADDING_V = 3.0f; private int mPrevAlpha = -1; private HolographicOutlineHelper mOutlineHelper; private final Canvas mTempCanvas = new Canvas(); private final Rect mTempRect = new Rect(); private boolean mDidInvalidateForPressedState; private Bitmap mPressedOrFocusedBackground; private int mFocusedOutlineColor; private int mFocusedGlowColor; private int mPressedOutlineColor; private int mPressedGlowColor; private int mTextColor; private boolean mShadowsEnabled = true; private boolean mIsTextVisible; private boolean mBackgroundSizeChanged; private Drawable mBackground; private boolean mStayPressed; private CheckLongPressHelper mLongPressHelper; public BubbleTextView(Context context) { super(context); init(); } public BubbleTextView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public BubbleTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public void onFinishInflate() { super.onFinishInflate(); LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); setTextSize(TypedValue.COMPLEX_UNIT_PX, grid.iconTextSizePx); setTextColor(getResources().getColor(R.color.workspace_icon_text_color)); } private void init() { mLongPressHelper = new CheckLongPressHelper(this); mBackground = getBackground(); mOutlineHelper = HolographicOutlineHelper.obtain(getContext()); final Resources res = getContext().getResources(); mFocusedOutlineColor = mFocusedGlowColor = mPressedOutlineColor = mPressedGlowColor = res.getColor(R.color.outline_color); setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR); } public void applyFromShortcutInfo(ShortcutInfo info, IconCache iconCache) { LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); Bitmap b = info.getIcon(iconCache); setCompoundDrawables(null, Utilities.createIconDrawable(b), null, null); setCompoundDrawablePadding(grid.iconDrawablePaddingPx); setText(info.title); setTag(info); } @Override protected boolean setFrame(int left, int top, int right, int bottom) { if (getLeft() != left || getRight() != right || getTop() != top || getBottom() != bottom) { mBackgroundSizeChanged = true; } return super.setFrame(left, top, right, bottom); } @Override protected boolean verifyDrawable(Drawable who) { return who == mBackground || super.verifyDrawable(who); } @Override public void setTag(Object tag) { if (tag != null) { LauncherModel.checkItemInfo((ItemInfo) tag); } super.setTag(tag); } @Override protected void drawableStateChanged() { if (isPressed()) { // In this case, we have already created the pressed outline on ACTION_DOWN, // so we just need to do an invalidate to trigger draw if (!mDidInvalidateForPressedState) { setCellLayoutPressedOrFocusedIcon(); } } else { // Otherwise, either clear the pressed/focused background, or create a background // for the focused state final boolean backgroundEmptyBefore = mPressedOrFocusedBackground == null; if (!mStayPressed) { mPressedOrFocusedBackground = null; } if (isFocused()) { if (getLayout() == null) { // In some cases, we get focus before we have been layed out. Set the // background to null so that it will get created when the view is drawn. mPressedOrFocusedBackground = null; } else { mPressedOrFocusedBackground = createGlowingOutline( mTempCanvas, mFocusedGlowColor, mFocusedOutlineColor); } mStayPressed = false; setCellLayoutPressedOrFocusedIcon(); } final boolean backgroundEmptyNow = mPressedOrFocusedBackground == null; if (!backgroundEmptyBefore && backgroundEmptyNow) { setCellLayoutPressedOrFocusedIcon(); } } Drawable d = mBackground; if (d != null && d.isStateful()) { d.setState(getDrawableState()); } super.drawableStateChanged(); } /** * Draw this BubbleTextView into the given Canvas. * * @param destCanvas the canvas to draw on * @param padding the horizontal and vertical padding to use when drawing */ private void drawWithPadding(Canvas destCanvas, int padding) { final Rect clipRect = mTempRect; getDrawingRect(clipRect); // adjust the clip rect so that we don't include the text label clipRect.bottom = getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V + getLayout().getLineTop(0); // Draw the View into the bitmap. // The translate of scrollX and scrollY is necessary when drawing TextViews, because // they set scrollX and scrollY to large values to achieve centered text destCanvas.save(); destCanvas.scale(getScaleX(), getScaleY(), (getWidth() + padding) / 2, (getHeight() + padding) / 2); destCanvas.translate(-getScrollX() + padding / 2, -getScrollY() + padding / 2); destCanvas.clipRect(clipRect, Op.REPLACE); draw(destCanvas); destCanvas.restore(); } public void setGlowColor(int color) { mFocusedOutlineColor = mFocusedGlowColor = mPressedOutlineColor = mPressedGlowColor = color; } /** * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. * Responsibility for the bitmap is transferred to the caller. */ private Bitmap createGlowingOutline(Canvas canvas, int outlineColor, int glowColor) { final int padding = mOutlineHelper.mMaxOuterBlurRadius; final Bitmap b = Bitmap.createBitmap( getWidth() + padding, getHeight() + padding, Bitmap.Config.ARGB_8888); canvas.setBitmap(b); drawWithPadding(canvas, padding); mOutlineHelper.applyExtraThickExpensiveOutlineWithBlur(b, canvas, glowColor, outlineColor); canvas.setBitmap(null); return b; } @Override public boolean onTouchEvent(MotionEvent event) { // Call the superclass onTouchEvent first, because sometimes it changes the state to // isPressed() on an ACTION_UP boolean result = super.onTouchEvent(event); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // So that the pressed outline is visible immediately when isPressed() is true, // we pre-create it on ACTION_DOWN (it takes a small but perceptible amount of time // to create it) if (mPressedOrFocusedBackground == null) { mPressedOrFocusedBackground = createGlowingOutline( mTempCanvas, mPressedGlowColor, mPressedOutlineColor); } // Invalidate so the pressed state is visible, or set a flag so we know that we // have to call invalidate as soon as the state is "pressed" if (isPressed()) { mDidInvalidateForPressedState = true; setCellLayoutPressedOrFocusedIcon(); } else { mDidInvalidateForPressedState = false; } mLongPressHelper.postCheckForLongPress(); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: // If we've touched down and up on an item, and it's still not "pressed", then // destroy the pressed outline if (!isPressed()) { mPressedOrFocusedBackground = null; } mLongPressHelper.cancelLongPress(); break; } return result; } void setStayPressed(boolean stayPressed) { mStayPressed = stayPressed; if (!stayPressed) { mPressedOrFocusedBackground = null; } setCellLayoutPressedOrFocusedIcon(); } void setCellLayoutPressedOrFocusedIcon() { if (getParent() instanceof ShortcutAndWidgetContainer) { ShortcutAndWidgetContainer parent = (ShortcutAndWidgetContainer) getParent(); if (parent != null) { CellLayout layout = (CellLayout) parent.getParent(); layout.setPressedOrFocusedIcon((mPressedOrFocusedBackground != null) ? this : null); } } } void clearPressedOrFocusedBackground() { mPressedOrFocusedBackground = null; setCellLayoutPressedOrFocusedIcon(); } Bitmap getPressedOrFocusedBackground() { return mPressedOrFocusedBackground; } int getPressedOrFocusedBackgroundPadding() { return mOutlineHelper.mMaxOuterBlurRadius / 2; } @Override public void draw(Canvas canvas) { if (!mShadowsEnabled) { super.draw(canvas); return; } final Drawable background = mBackground; if (background != null) { final int scrollX = getScrollX(); final int scrollY = getScrollY(); if (mBackgroundSizeChanged) { background.setBounds(0, 0, getRight() - getLeft(), getBottom() - getTop()); mBackgroundSizeChanged = false; } if ((scrollX | scrollY) == 0) { background.draw(canvas); } else { canvas.translate(scrollX, scrollY); background.draw(canvas); canvas.translate(-scrollX, -scrollY); } } // If text is transparent, don't draw any shadow if (getCurrentTextColor() == getResources().getColor(android.R.color.transparent)) { getPaint().clearShadowLayer(); super.draw(canvas); return; } // We enhance the shadow by drawing the shadow twice getPaint().setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR); super.draw(canvas); canvas.save(Canvas.CLIP_SAVE_FLAG); canvas.clipRect(getScrollX(), getScrollY() + getExtendedPaddingTop(), getScrollX() + getWidth(), getScrollY() + getHeight(), Region.Op.INTERSECT); getPaint().setShadowLayer(SHADOW_SMALL_RADIUS, 0.0f, 0.0f, SHADOW_SMALL_COLOUR); super.draw(canvas); canvas.restore(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (mBackground != null) mBackground.setCallback(this); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mBackground != null) mBackground.setCallback(null); } @Override public void setTextColor(int color) { mTextColor = color; super.setTextColor(color); } public void setShadowsEnabled(boolean enabled) { mShadowsEnabled = enabled; getPaint().clearShadowLayer(); invalidate(); } public void setTextVisibility(boolean visible) { Resources res = getResources(); if (visible) { super.setTextColor(mTextColor); } else { super.setTextColor(res.getColor(android.R.color.transparent)); } mIsTextVisible = visible; } public boolean isTextVisible() { return mIsTextVisible; } @Override protected boolean onSetAlpha(int alpha) { if (mPrevAlpha != alpha) { mPrevAlpha = alpha; super.onSetAlpha(alpha); } return true; } @Override public void cancelLongPress() { super.cancelLongPress(); mLongPressHelper.cancelLongPress(); } }
Java
# Scutellaria ovata subsp. bracteata (Benth.) Epling SUBSPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
/* * Licensed to Crate.IO GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate licenses * this file to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.operation.merge; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.SettableFuture; import io.crate.core.collections.ArrayBucket; import io.crate.core.collections.Bucket; import io.crate.core.collections.BucketPage; import io.crate.core.collections.Row; import io.crate.core.collections.Row1; import io.crate.core.collections.SingleRowBucket; import io.crate.operation.PageConsumeListener; import io.crate.operation.projectors.RowReceiver; import io.crate.test.integration.CrateUnitTest; import io.crate.testing.CollectingRowReceiver; import io.crate.testing.TestingHelpers; import org.elasticsearch.common.breaker.CircuitBreakingException; import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.Mockito; import javax.annotation.Nonnull; import java.util.concurrent.Executor; import static org.hamcrest.core.Is.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class IteratorPageDownstreamTest extends CrateUnitTest { public static final PageConsumeListener PAGE_CONSUME_LISTENER = new PageConsumeListener() { @Override public void needMore() { } @Override public void finish() { } }; @Mock PagingIterator<Row> mockedPagingIterator; @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testMergeOnPagingIteratorIsCalledAfterALLBucketsAreReady() throws Exception { IteratorPageDownstream downstream = new IteratorPageDownstream( new CollectingRowReceiver(), mockedPagingIterator, Optional.<Executor>absent()); SettableFuture<Bucket> b1 = SettableFuture.create(); SettableFuture<Bucket> b2 = SettableFuture.create(); downstream.nextPage(new BucketPage(ImmutableList.of(b1, b2)), PAGE_CONSUME_LISTENER); verify(mockedPagingIterator, times(0)).merge(Mockito.<Iterable<? extends NumberedIterable<Row>>>any()); b1.set(Bucket.EMPTY); verify(mockedPagingIterator, times(0)).merge(Mockito.<Iterable<? extends NumberedIterable<Row>>>any()); b2.set(Bucket.EMPTY); verify(mockedPagingIterator, times(1)).merge(Mockito.<Iterable<? extends NumberedIterable<Row>>>any()); } @Test public void testFailingNextRowIsHandled() throws Exception { expectedException.expect(CircuitBreakingException.class); class FailingRowReceiver extends CollectingRowReceiver { @Override public boolean setNextRow(Row row) { throw new CircuitBreakingException("foo"); } } CollectingRowReceiver rowReceiver = new FailingRowReceiver(); IteratorPageDownstream downstream = new IteratorPageDownstream( rowReceiver, PassThroughPagingIterator.<Row>oneShot(), Optional.<Executor>absent()); SettableFuture<Bucket> b1 = SettableFuture.create(); downstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); b1.set(new SingleRowBucket(new Row1(42))); rowReceiver.result(); } @Test public void testBucketFailureIsPassedToDownstream() throws Exception { IllegalStateException dummy = new IllegalStateException("dummy"); expectedException.expect(IllegalStateException.class); CollectingRowReceiver rowReceiver = new CollectingRowReceiver(); IteratorPageDownstream downstream = new IteratorPageDownstream( rowReceiver, mockedPagingIterator, Optional.<Executor>absent()); SettableFuture<Bucket> b1 = SettableFuture.create(); downstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); b1.setException(dummy); rowReceiver.result(); } @Test public void testMultipleFinishPropagatesOnlyOnceToDownstream() throws Exception { RowReceiver rowReceiver = mock(RowReceiver.class); IteratorPageDownstream downstream = new IteratorPageDownstream( rowReceiver, mockedPagingIterator, Optional.<Executor>absent()); downstream.finish(); downstream.finish(); verify(rowReceiver, times(1)).finish(); } @Test public void testFinishDoesNotEmitRemainingRow() throws Exception { CollectingRowReceiver rowReceiver = CollectingRowReceiver.withLimit(1); IteratorPageDownstream downstream = new IteratorPageDownstream( rowReceiver, PassThroughPagingIterator.<Row>oneShot(), Optional.<Executor>absent() ); SettableFuture<Bucket> b1 = SettableFuture.create(); b1.set(new ArrayBucket( new Object[][]{ new Object[]{"a"}, new Object[]{"b"}, new Object[]{"c"} } )); downstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); downstream.finish(); assertThat(rowReceiver.result().size(), is(1)); } @Test public void testRejectedExecutionDoesNotCauseBucketMergerToGetStuck() throws Exception { expectedException.expect(EsRejectedExecutionException.class); final CollectingRowReceiver rowReceiver = new CollectingRowReceiver(); IteratorPageDownstream pageDownstream = new IteratorPageDownstream( rowReceiver, PassThroughPagingIterator.<Row>oneShot(), Optional.<Executor>of(new Executor() { @Override public void execute(@Nonnull Runnable command) { throw new EsRejectedExecutionException("HAHA !"); } })); SettableFuture<Bucket> b1 = SettableFuture.create(); b1.set(Bucket.EMPTY); pageDownstream.nextPage(new BucketPage(ImmutableList.of(b1)), new PageConsumeListener() { @Override public void needMore() { rowReceiver.finish(); } @Override public void finish() { rowReceiver.finish(); } }); rowReceiver.result(); } @Test public void testRepeat() throws Exception { CollectingRowReceiver rowReceiver = new CollectingRowReceiver(); IteratorPageDownstream pageDownstream = new IteratorPageDownstream( rowReceiver, PassThroughPagingIterator.<Row>repeatable(), Optional.<Executor>absent()); SettableFuture<Bucket> b1 = SettableFuture.create(); b1.set(new ArrayBucket( new Object[][] { new Object[] {"a"}, new Object[] {"b"}, new Object[] {"c"} } )); pageDownstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); pageDownstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); pageDownstream.finish(); rowReceiver.repeatUpstream(); pageDownstream.finish(); assertThat(TestingHelpers.printedTable(rowReceiver.result()), is( "a\n" + "b\n" + "c\n" + "a\n" + "b\n" + "c\n" + "a\n" + "b\n" + "c\n" + "a\n" + "b\n" + "c\n")); } @Test public void testPauseAndResume() throws Exception { CollectingRowReceiver rowReceiver = CollectingRowReceiver.withPauseAfter(2); IteratorPageDownstream pageDownstream = new IteratorPageDownstream( rowReceiver, PassThroughPagingIterator.<Row>repeatable(), Optional.<Executor>absent()); SettableFuture<Bucket> b1 = SettableFuture.create(); b1.set(new ArrayBucket( new Object[][] { new Object[] {"a"}, new Object[] {"b"}, new Object[] {"c"} } )); pageDownstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); assertThat(rowReceiver.rows.size(), is(2)); rowReceiver.resumeUpstream(false); assertThat(rowReceiver.rows.size(), is(3)); pageDownstream.finish(); rowReceiver.repeatUpstream(); assertThat(TestingHelpers.printedTable(rowReceiver.result()), is( "a\n" + "b\n" + "c\n" + "a\n" + "b\n" + "c\n")); } }
Java
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.frauddetector.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.frauddetector.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * DeleteEventsByEventTypeRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DeleteEventsByEventTypeRequestProtocolMarshaller implements Marshaller<Request<DeleteEventsByEventTypeRequest>, DeleteEventsByEventTypeRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("AWSHawksNestServiceFacade.DeleteEventsByEventType").serviceName("AmazonFraudDetector").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public DeleteEventsByEventTypeRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<DeleteEventsByEventTypeRequest> marshall(DeleteEventsByEventTypeRequest deleteEventsByEventTypeRequest) { if (deleteEventsByEventTypeRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<DeleteEventsByEventTypeRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller( SDK_OPERATION_BINDING, deleteEventsByEventTypeRequest); protocolMarshaller.startMarshalling(); DeleteEventsByEventTypeRequestMarshaller.getInstance().marshall(deleteEventsByEventTypeRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
Java
import Future = require("fibers/future"); import * as npm from "npm"; interface INpmOpts { config?: any; subCommandName?: string; path?: string; } export class NodePackageManager implements INodePackageManager { constructor(private $childProcess: IChildProcess, private $logger: ILogger, private $options: IOptions) { } public getCache(): string { return npm.cache; } public load(config?: any): IFuture<void> { if (npm.config.loaded) { let data = npm.config.sources.cli.data; Object.keys(data).forEach(k => delete data[k]); if (config) { _.assign(data, config); } return Future.fromResult(); } else { let future = new Future<void>(); npm.load(config, (err: Error) => { if (err) { future.throw(err); } else { future.return(); } }); return future; } } public install(packageName: string, pathToSave: string, config?: any): IFuture<any> { return (() => { if (this.$options.disableNpmInstall) { return; } if (this.$options.ignoreScripts) { config = config || {}; config["ignore-scripts"] = true; } try { return this.loadAndExecute("install", [pathToSave, packageName], { config: config }).wait(); } catch (err) { if (err.code === "EPEERINVALID") { // Not installed peer dependencies are treated by npm 2 as errors, but npm 3 treats them as warnings. // We'll show them as warnings and let the user install them in case they are needed. // The strucutre of the error object in such case is: // { [Error: The package @angular/core@2.1.0-beta.0 does not satisfy its siblings' peerDependencies requirements!] // code: 'EPEERINVALID', // packageName: '@angular/core', // packageVersion: '2.1.0-beta.0', // peersDepending: // { '@angular/common@2.1.0-beta.0': '2.1.0-beta.0', // '@angular/compiler@2.1.0-beta.0': '2.1.0-beta.0', // '@angular/forms@2.1.0-beta.0': '2.1.0-beta.0', // '@angular/http@2.1.0-beta.0': '2.1.0-beta.0', // '@angular/platform-browser@2.1.0-beta.0': '2.1.0-beta.0', // '@angular/platform-browser-dynamic@2.1.0-beta.0': '2.1.0-beta.0', // '@angular/platform-server@2.1.0-beta.0': '2.1.0-beta.0', // '@angular/router@3.1.0-beta.0': '2.1.0-beta.0', // '@ngrx/effects@2.0.0': '^2.0.0', // '@ngrx/store@2.2.1': '^2.0.0', // 'ng2-translate@2.5.0': '~2.0.0' } } this.$logger.warn(err.message); this.$logger.trace("Required peerDependencies are: ", err.peersDepending); } else { // All other errors should be handled by the caller code. throw err; } } }).future<any>()(); } public uninstall(packageName: string, config?: any, path?: string): IFuture<any> { return this.loadAndExecute("uninstall", [[packageName]], { config, path }); } public search(filter: string[], silent: boolean): IFuture<any> { let args = (<any[]>([filter] || [])).concat(silent); return this.loadAndExecute("search", args); } public cache(packageName: string, version: string, config?: any): IFuture<IDependencyData> { // function cache (pkg, ver, where, scrub, cb) return this.loadAndExecute("cache", [packageName, version, undefined, false], { subCommandName: "add", config: config }); } public cacheUnpack(packageName: string, version: string, unpackTarget?: string): IFuture<void> { // function unpack (pkg, ver, unpackTarget, dMode, fMode, uid, gid, cb) return this.loadAndExecute("cache", [packageName, version, unpackTarget, null, null, null, null], { subCommandName: "unpack" }); } public view(packageName: string, propertyName: string): IFuture<any> { return this.loadAndExecute("view", [[packageName, propertyName], [false]]); } public executeNpmCommand(npmCommandName: string, currentWorkingDirectory: string): IFuture<any> { return this.$childProcess.exec(npmCommandName, { cwd: currentWorkingDirectory }); } private loadAndExecute(commandName: string, args: any[], opts?: INpmOpts): IFuture<any> { return (() => { opts = opts || {}; this.load(opts.config).wait(); return this.executeCore(commandName, args, opts).wait(); }).future<any>()(); } private executeCore(commandName: string, args: any[], opts?: INpmOpts): IFuture<any> { let future = new Future<any>(); let oldNpmPath: string = undefined; let callback = (err: Error, data: any) => { if (oldNpmPath) { npm.prefix = oldNpmPath; } if (err) { future.throw(err); } else { future.return(data); } }; args.push(callback); if (opts && opts.path) { oldNpmPath = npm.prefix; npm.prefix = opts.path; } let subCommandName: string = opts.subCommandName; let command = subCommandName ? npm.commands[commandName][subCommandName] : npm.commands[commandName]; command.apply(this, args); return future; } } $injector.register("npm", NodePackageManager);
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.sling; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import javax.jcr.Repository; import org.apache.jackrabbit.oak.api.ContentRepository; import org.apache.jackrabbit.oak.spi.security.SecurityProvider; import org.apache.sling.jcr.api.SlingRepository; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; public class Activator implements BundleActivator, ServiceTrackerCustomizer { private BundleContext context; private ScheduledExecutorService executor; private SecurityProvider securityProvider; private ServiceTracker tracker; private final Map<ServiceReference, ServiceRegistration> jcrRepositories = new HashMap<ServiceReference, ServiceRegistration>(); private final Map<ServiceReference, ServiceRegistration> slingRepositories = new HashMap<ServiceReference, ServiceRegistration>(); //-----------------------------------------------------< BundleActivator >-- @Override public void start(BundleContext bundleContext) throws Exception { context = bundleContext; executor = Executors.newScheduledThreadPool(1); securityProvider = null; // TODO tracker = new ServiceTracker( context, ContentRepository.class.getName(), this); tracker.open(); } @Override public void stop(BundleContext bundleContext) throws Exception { tracker.close(); executor.shutdown(); } //--------------------------------------------< ServiceTrackerCustomizer >-- @Override public Object addingService(ServiceReference reference) { Object service = context.getService(reference); if (service instanceof ContentRepository) { SlingRepository repository = new SlingRepositoryImpl( (ContentRepository) service, executor, securityProvider); jcrRepositories.put(reference, context.registerService( Repository.class.getName(), repository, new Properties())); slingRepositories.put(reference, context.registerService( SlingRepository.class.getName(), repository, new Properties())); return service; } else { context.ungetService(reference); return null; } } @Override public void modifiedService(ServiceReference reference, Object service) { } @Override public void removedService(ServiceReference reference, Object service) { slingRepositories.get(reference).unregister(); jcrRepositories.get(reference).unregister(); context.ungetService(reference); } }
Java
/* * Copyright 1999-2101 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.fastjson.parser; /** * @author wenshao[szujobs@hotmail.com] */ public class JSONToken { // public final static int ERROR = 1; // public final static int LITERAL_INT = 2; // public final static int LITERAL_FLOAT = 3; // public final static int LITERAL_STRING = 4; // public final static int LITERAL_ISO8601_DATE = 5; public final static int TRUE = 6; // public final static int FALSE = 7; // public final static int NULL = 8; // public final static int NEW = 9; // public final static int LPAREN = 10; // ("("), // public final static int RPAREN = 11; // (")"), // public final static int LBRACE = 12; // ("{"), // public final static int RBRACE = 13; // ("}"), // public final static int LBRACKET = 14; // ("["), // public final static int RBRACKET = 15; // ("]"), // public final static int COMMA = 16; // (","), // public final static int COLON = 17; // (":"), // public final static int IDENTIFIER = 18; // public final static int FIELD_NAME = 19; public final static int EOF = 20; public final static int SET = 21; public final static int TREE_SET = 22; public final static int UNDEFINED = 23; // undefined public static String name(int value) { switch (value) { case ERROR: return "error"; case LITERAL_INT: return "int"; case LITERAL_FLOAT: return "float"; case LITERAL_STRING: return "string"; case LITERAL_ISO8601_DATE: return "iso8601"; case TRUE: return "true"; case FALSE: return "false"; case NULL: return "null"; case NEW: return "new"; case LPAREN: return "("; case RPAREN: return ")"; case LBRACE: return "{"; case RBRACE: return "}"; case LBRACKET: return "["; case RBRACKET: return "]"; case COMMA: return ","; case COLON: return ":"; case IDENTIFIER: return "ident"; case FIELD_NAME: return "fieldName"; case EOF: return "EOF"; case SET: return "Set"; case TREE_SET: return "TreeSet"; case UNDEFINED: return "undefined"; default: return "Unkown"; } } }
Java
package com.github.obourgain.elasticsearch.http.response.parser; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.elasticsearch.common.xcontent.XContentParser; import com.github.obourgain.elasticsearch.http.response.entity.Indices; import com.github.obourgain.elasticsearch.http.response.entity.ShardFailure; import com.github.obourgain.elasticsearch.http.response.entity.Shards; import lombok.Getter; @Getter public class IndicesParser { private static List<ShardFailure> failures; public static Indices parse(XContentParser parser) { Map<String, Shards> result = new HashMap<>(); try { XContentParser.Token token; String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { failures = ShardFailure.parse(parser); } else if (token == XContentParser.Token.START_OBJECT) { Shards shards = new Shards().parse(parser); result.put(currentFieldName, shards); } } return Indices.fromMap(result); } catch (IOException e) { throw new RuntimeException("Unable to parse source", e); } } }
Java
/* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.carlomicieli.nerdmovies.controllers; import com.github.carlomicieli.nerdmovies.services.MovieService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * @author Carlo Micieli */ @Controller @RequestMapping("/") public class HomeController { private MovieService movieService; @Autowired public HomeController(MovieService movieService) { this.movieService = movieService; } @RequestMapping(value = {"/", "/home"}, method = RequestMethod.GET) public String index(Model model) { model.addAttribute("movies", movieService.getRecentMovies(10)); return "home/index"; } @RequestMapping(value = "/about", method = RequestMethod.GET) public String about() { return "home/about"; } @RequestMapping(value = "/default", method = RequestMethod.GET) public String defaultPage() { return "home/index"; } }
Java
package com.camillepradel.movierecommender.utils; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; public class CsvToMySql { static final String pathToCsvFiles = "D:\\MovieRecommender\\src\\main\\java\\com\\camillepradel\\movierecommender\\utils\\"; static final String usersCsvFile = pathToCsvFiles + "users.csv"; static final String moviesCsvFile = pathToCsvFiles + "movies.csv"; static final String genresCsvFile = pathToCsvFiles + "genres.csv"; static final String movGenreCsvFile = pathToCsvFiles + "mov_genre.csv"; static final String ratingsCsvFile = pathToCsvFiles + "ratings.csv"; static final String friendsCsvFile = pathToCsvFiles + "friends.csv"; static final String cvsSplitBy = ","; private static void commitUsers(Connection connection) throws SQLException { System.out.println(usersCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS users (\n" + " id int(11) NOT NULL AUTO_INCREMENT,\n" + " age int(11) NOT NULL,\n" + " sex varchar(1) NOT NULL,\n" + " occupation varchar(60) NOT NULL,\n" + " zip varchar(6) NOT NULL,\n" + " PRIMARY KEY (`id`)\n" + ");"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(usersCsvFile))) { String insertQuery = "INSERT INTO users (id, age, sex, occupation, zip) VALUES (?, ?, ?, ?, ?)"; PreparedStatement insertUsers = null; try { connection.setAutoCommit(false); insertUsers = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); insertUsers.setInt(1, Integer.parseInt(values[0])); insertUsers.setInt(2, Integer.parseInt(values[1])); insertUsers.setString(3, values[2]); insertUsers.setString(4, values[3]); insertUsers.setString(5, values[4]); insertUsers.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertUsers != null) { insertUsers.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } private static void commitMovies(Connection connection) throws SQLException { // movies.csv System.out.println(moviesCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS movies (\n" + " id int(11) NOT NULL AUTO_INCREMENT,\n" + " title varchar(200) NOT NULL,\n" + " date date NOT NULL,\n" + " PRIMARY KEY (`id`)\n" + ");"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(moviesCsvFile))) { String insertQuery = "INSERT INTO movies (id, title, date) VALUES (?, ?, ?)"; PreparedStatement insertMovies = null; try { connection.setAutoCommit(false); insertMovies = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); int movieId = Integer.parseInt(values[0]); String title = String.join(",", Arrays.copyOfRange(values, 1, values.length - 1)); Date date = new Date(Long.parseLong(values[values.length - 1]) * 1000); insertMovies.setInt(1, movieId); insertMovies.setString(2, title); insertMovies.setDate(3, date); insertMovies.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertMovies != null) { insertMovies.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } private static void commitGenres(Connection connection) throws SQLException { // genres.csv System.out.println(genresCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS genres (\n" + " name varchar(60) NOT NULL,\n" + " id int(11) NOT NULL AUTO_INCREMENT,\n" + " PRIMARY KEY (`id`)\n" + ");"); // necessary to make mySQL accept 0 as a valid id value for genre unknown statement.execute("SET SESSION sql_mode='NO_AUTO_VALUE_ON_ZERO';"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(genresCsvFile))) { String insertQuery = "INSERT INTO genres (name, id) VALUES (?, ?)"; PreparedStatement insertGenres = null; try { connection.setAutoCommit(false); insertGenres = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); String name = values[0]; int genreId = Integer.parseInt(values[1]); insertGenres.setString(1, name); insertGenres.setInt(2, genreId); insertGenres.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertGenres != null) { insertGenres.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } private static void commitMovieGenre(Connection connection) throws SQLException { // mov_genre.csv System.out.println(movGenreCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS movie_genre (\n" + " movie_id int(11) NOT NULL,\n" + " genre_id int(11) NOT NULL,\n" + " KEY movie_id (movie_id),\n" + " KEY genre_id (genre_id)\n" + ");"); statement.executeUpdate("ALTER TABLE movie_genre\n" + " ADD CONSTRAINT movie_genre_to_movie FOREIGN KEY (movie_id) REFERENCES movies(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); statement.executeUpdate("ALTER TABLE movie_genre\n" + " ADD CONSTRAINT movie_genre_to_genre FOREIGN KEY (genre_id) REFERENCES genres(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(movGenreCsvFile))) { String insertQuery = "INSERT INTO movie_genre (movie_id, genre_id) VALUES (?, ?)"; PreparedStatement insertMovieGenre = null; try { connection.setAutoCommit(false); insertMovieGenre = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); int movieId = Integer.parseInt(values[0]); int genreId = Integer.parseInt(values[1]); insertMovieGenre.setInt(1, movieId); insertMovieGenre.setInt(2, genreId); insertMovieGenre.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertMovieGenre != null) { insertMovieGenre.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } private static void commitRatings(Connection connection) throws SQLException { // ratings.csv System.out.println(ratingsCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS ratings (\n" + " user_id int(11) NOT NULL,\n" + " movie_id int(11) NOT NULL,\n" + " rating int(11) NOT NULL,\n" + " date date NOT NULL,\n" + " KEY user_id (user_id),\n" + " KEY movie_id (movie_id)\n" + ");"); statement.executeUpdate("ALTER TABLE ratings\n" + " ADD CONSTRAINT ratings_to_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); statement.executeUpdate("ALTER TABLE ratings\n" + " ADD CONSTRAINT ratings_to_movie FOREIGN KEY (movie_id) REFERENCES movies(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); statement.executeUpdate("ALTER TABLE ratings\n" + " ADD UNIQUE unique_index(user_id, movie_id);\n"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(ratingsCsvFile))) { String insertQuery = "INSERT INTO ratings (user_id, movie_id, rating, date) VALUES (?, ?, ?, ?)"; PreparedStatement insertRatings = null; try { connection.setAutoCommit(false); insertRatings = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); int userId = Integer.parseInt(values[0]); int movieId = Integer.parseInt(values[1]); int ratingValue = Integer.parseInt(values[2]); Date date = new Date(Long.parseLong(values[3]) * 1000); insertRatings.setInt(1, userId); insertRatings.setInt(2, movieId); insertRatings.setInt(3, ratingValue); insertRatings.setDate(4, date); insertRatings.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertRatings != null) { insertRatings.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } private static void commitFriends(Connection connection) throws SQLException { // friends.csv System.out.println(friendsCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS friends (\n" + " user1_id int(11) NOT NULL,\n" + " user2_id int(11) NOT NULL,\n" + " KEY user1_id (user1_id),\n" + " KEY user2_id (user2_id)\n" + ");"); statement.executeUpdate("ALTER TABLE friends\n" + " ADD CONSTRAINT friends_to_user1 FOREIGN KEY (user1_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); statement.executeUpdate("ALTER TABLE friends\n" + " ADD CONSTRAINT friends_to_user2 FOREIGN KEY (user2_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(friendsCsvFile))) { String insertQuery = "INSERT INTO friends (user1_id, user2_id) VALUES (?, ?)"; PreparedStatement insertFriends = null; try { connection.setAutoCommit(false); insertFriends = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); int user1Id = Integer.parseInt(values[0]); int user2Id = Integer.parseInt(values[1]); insertFriends.setInt(1, user1Id); insertFriends.setInt(2, user2Id); insertFriends.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertFriends != null) { insertFriends.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { // load JDBC driver try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } // db connection info String url = "jdbc:mysql://localhost:3306" + "?zeroDateTimeBehavior=convertToNull&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"; String login = "admin"; String password = "Q86PhnJRiEa7"; Connection connection = null; try { connection = DriverManager.getConnection(url, login, password); Statement statement = connection.createStatement(); // create database statement.executeUpdate("DROP DATABASE IF EXISTS movie_recommender;"); statement.executeUpdate("CREATE DATABASE movie_recommender;"); statement.executeUpdate("USE movie_recommender;"); commitUsers(connection); commitMovies(connection); commitGenres(connection); commitMovieGenre(connection); commitRatings(connection); commitFriends(connection); } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException ignore) { // exception occured while closing connexion -> nothing else can be done } } } System.out.println("done"); } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.cache.query.internal; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.geode.annotations.internal.MakeNotStatic; import org.apache.geode.cache.EntryDestroyedException; import org.apache.geode.cache.Region; import org.apache.geode.cache.query.AmbiguousNameException; import org.apache.geode.cache.query.FunctionDomainException; import org.apache.geode.cache.query.NameResolutionException; import org.apache.geode.cache.query.QueryInvocationTargetException; import org.apache.geode.cache.query.QueryService; import org.apache.geode.cache.query.TypeMismatchException; import org.apache.geode.internal.InternalDataSerializer; import org.apache.geode.internal.cache.PartitionedRegion; import org.apache.geode.pdx.PdxInstance; import org.apache.geode.pdx.PdxSerializationException; import org.apache.geode.pdx.internal.InternalPdxInstance; import org.apache.geode.pdx.internal.PdxString; /** * Class Description * * @version $Revision: 1.1 $ */ public class CompiledOperation extends AbstractCompiledValue { private final CompiledValue receiver; // may be null if implicit to scope private final String methodName; private final List args; @MakeNotStatic private static final ConcurrentMap cache = new ConcurrentHashMap(); // receiver is an ID or PATH that contains the operation name public CompiledOperation(CompiledValue receiver, String methodName, List args) { this.receiver = receiver; this.methodName = methodName; this.args = args; } @Override public List getChildren() { List list = new ArrayList(); if (this.receiver != null) { list.add(this.receiver); } list.addAll(this.args); return list; } public String getMethodName() { return this.methodName; } public List getArguments() { return this.args; } @Override public int getType() { return METHOD_INV; } public CompiledValue getReceiver(ExecutionContext cxt) { // receiver may be cached in execution context if (this.receiver == null && cxt != null) { return (CompiledValue) cxt.cacheGet(this); } return this.receiver; } @Override public boolean hasIdentifierAtLeafNode() { if (this.receiver.getType() == Identifier) { return true; } else { return this.receiver.hasIdentifierAtLeafNode(); } } @Override public CompiledValue getReceiver() { return this.getReceiver(null); } @Override public Object evaluate(ExecutionContext context) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException { CompiledValue rcvr = getReceiver(context); Object result; Object evalRcvr; if (rcvr == null) { // must be intended as implicit iterator operation // see if it's an implicit operation name RuntimeIterator rcvrItr = context.resolveImplicitOperationName(this.methodName, this.args.size(), true); evalRcvr = rcvrItr.evaluate(context); /* * // evaluate on current iteration of collection if (rcvrItr != null) { result = * eval0(rcvrItr.evaluate(context), rcvrItr.getElementType().resolveClass(), context); } * * // function call: no functions implemented except keywords in the grammar throw new * TypeMismatchException("Could not resolve method named 'xyz'") */ } else { // if not null, then explicit receiver evalRcvr = rcvr.evaluate(context); } // short circuit null immediately if (evalRcvr == null) { return QueryService.UNDEFINED; } if (context.isCqQueryContext() && evalRcvr instanceof Region.Entry) { Region.Entry re = (Region.Entry) evalRcvr; if (re.isDestroyed()) { return QueryService.UNDEFINED; } try { evalRcvr = re.getValue(); } catch (EntryDestroyedException ede) { // Even though isDestory() check is made, the entry could // throw EntryDestroyedException if the value becomes null. return QueryService.UNDEFINED; } } // check if the receiver is the iterator, in which // case we resolve the method on the constraint rather // than the runtime type of the receiver Class resolveClass = null; // commented out because we currently always resolve the method // on the runtime types // CompiledValue rcvrVal = rcvrPath.getReceiver(); // if (rcvrVal.getType() == ID) // { // CompiledValue resolvedID = context.resolve(((CompiledID)rcvrVal).getId()); // if (resolvedID.getType() == ITERATOR) // { // resolveClass = ((RuntimeIterator)resolvedID).getBaseCollection().getConstraint(); // } // } // if (resolveClass == null) if (evalRcvr instanceof PdxInstance) { String className = ((PdxInstance) evalRcvr).getClassName(); try { resolveClass = InternalDataSerializer.getCachedClass(className); } catch (ClassNotFoundException cnfe) { throw new QueryInvocationTargetException(cnfe); } } else if (evalRcvr instanceof PdxString) { resolveClass = String.class; } else { resolveClass = evalRcvr.getClass(); } result = eval0(evalRcvr, resolveClass, context); // } // check for PR substitution // check for BucketRegion substitution PartitionedRegion pr = context.getPartitionedRegion(); if (pr != null && (result instanceof Region)) { if (pr.getFullPath().equals(((Region) result).getFullPath())) { result = context.getBucketRegion(); } } return result; } @Override public Set computeDependencies(ExecutionContext context) throws TypeMismatchException, AmbiguousNameException, NameResolutionException { List args = this.args; Iterator i = args.iterator(); while (i.hasNext()) { context.addDependencies(this, ((CompiledValue) i.next()).computeDependencies(context)); } CompiledValue rcvr = getReceiver(context); if (rcvr == null) // implicit iterator operation { // see if it's an implicit operation name RuntimeIterator rcvrItr = context.resolveImplicitOperationName(this.methodName, this.args.size(), true); if (rcvrItr == null) { // no receiver resolved // function call: no functions implemented except keywords in the grammar throw new TypeMismatchException( String.format("Could not resolve method named ' %s '", this.methodName)); } // cache the receiver so we don't have to resolve it again context.cachePut(this, rcvrItr); return context.addDependency(this, rcvrItr); } // receiver is explicit return context.addDependencies(this, rcvr.computeDependencies(context)); } @edu.umd.cs.findbugs.annotations.SuppressWarnings( value = "RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED", justification = "Does not matter if the methodDispatch that isn't stored in the map is used") private Object eval0(Object receiver, Class resolutionType, ExecutionContext context) throws TypeMismatchException, FunctionDomainException, NameResolutionException, QueryInvocationTargetException { if (receiver == null || receiver == QueryService.UNDEFINED) return QueryService.UNDEFINED; List args = new ArrayList(); List argTypes = new ArrayList(); Iterator i = this.args.iterator(); while (i.hasNext()) { CompiledValue arg = (CompiledValue) i.next(); Object o = arg.evaluate(context); // undefined arg produces undefines method result if (o == QueryService.UNDEFINED) return QueryService.UNDEFINED; args.add(o); // pass in null for the type if the runtime value is null if (o == null) argTypes.add(null); // commented out because we currently always use the runtime type for args // else if (arg.getType() == Identifier) // { // CompiledValue resolved = context.resolve(((CompiledID)arg).getId()); // if (resolved != null && resolved.getType() == ITERATOR) // argTypes.add(((RuntimeIterator)resolved).getBaseCollection().getConstraint()); // else // argTypes.add(o.getClass()); // } else argTypes.add(o.getClass()); // otherwise use the runtime type } // see if in cache MethodDispatch methodDispatch; List key = Arrays.asList(new Object[] {resolutionType, this.methodName, argTypes}); methodDispatch = (MethodDispatch) CompiledOperation.cache.get(key); if (methodDispatch == null) { try { methodDispatch = new MethodDispatch(context.getCache().getQueryService().getMethodInvocationAuthorizer(), resolutionType, this.methodName, argTypes); } catch (NameResolutionException nre) { if (!org.apache.geode.cache.query.Struct.class.isAssignableFrom(resolutionType) && (DefaultQueryService.QUERY_HETEROGENEOUS_OBJECTS || DefaultQueryService.TEST_QUERY_HETEROGENEOUS_OBJECTS)) { return QueryService.UNDEFINED; } else { throw nre; } } // cache CompiledOperation.cache.putIfAbsent(key, methodDispatch); } if (receiver instanceof InternalPdxInstance) { try { receiver = ((InternalPdxInstance) receiver).getCachedObject(); } catch (PdxSerializationException ex) { throw new QueryInvocationTargetException(ex); } } else if (receiver instanceof PdxString) { receiver = ((PdxString) receiver).toString(); } return methodDispatch.invoke(receiver, args); } // Asif :Function for generating from clause @Override public void generateCanonicalizedExpression(StringBuilder clauseBuffer, ExecutionContext context) throws AmbiguousNameException, TypeMismatchException, NameResolutionException { // Asif: if the method name starts with getABC & argument list is empty // then canonicalize it to aBC int len; if (this.methodName.startsWith("get") && (len = this.methodName.length()) > 3 && (this.args == null || this.args.isEmpty())) { clauseBuffer.insert(0, len > 4 ? this.methodName.substring(4) : ""); clauseBuffer.insert(0, Character.toLowerCase(this.methodName.charAt(3))); } else if (this.args == null || this.args.isEmpty()) { clauseBuffer.insert(0, "()").insert(0, this.methodName); } else { // The method contains arguments which need to be canonicalized clauseBuffer.insert(0, ')'); CompiledValue cv = null; for (int j = this.args.size(); j > 0;) { cv = (CompiledValue) this.args.get(--j); cv.generateCanonicalizedExpression(clauseBuffer, context); clauseBuffer.insert(0, ','); } clauseBuffer.deleteCharAt(0).insert(0, '(').insert(0, this.methodName); } clauseBuffer.insert(0, '.'); CompiledValue rcvr = this.receiver; if (rcvr == null) { // must be intended as implicit iterator operation // see if it's an implicit operation name. The receiver will now be RuntimeIterator rcvr = context.resolveImplicitOperationName(this.methodName, this.args.size(), true); } rcvr.generateCanonicalizedExpression(clauseBuffer, context); } }
Java