repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
ribertojunior/Sunshine-Version-2 | app/src/main/java/com/example/android/sunshine/app/DetailActivity.java | 1837 | /*
* Copyright (C) 2014 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.example.android.sunshine.app;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class DetailActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
Bundle args = new Bundle();
args.putParcelable(DetailFragment.DETAIL_URI, getIntent().getData());
args.putBoolean(DetailFragment.DETAIL_TRANSITION_ANIMATION, true);
DetailFragment fragment = new DetailFragment();
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.add(R.id.weather_detail_container, fragment)
.commit();
supportPostponeEnterTransition();
}
}
} | apache-2.0 |
niranjanjee/geun | application/modules/default/views/layout/layout.php | 21535 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<head>
<meta charset="utf-8">
<!--[if IE]>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<![endif]-->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Gemstone</title>
<!-- Favicons Icon -->
<link rel="icon" href="images/flag.png" type="image/x-icon" />
<!-- Mobile Specific -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!-- CSS Style -->
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/front/css/bootstrap.min1.css" />
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/front/css/font-awesome.css" type="text/css">
<link href="<?php echo base_url(); ?>assets/front/css/font.css" rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/front/css/font-awesome/css/font-awesome.min.css" />
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/front/css/revslider.css" type="text/css">
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/front/css/owl.carousel.css" type="text/css">
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/front/css/owl.theme.css" type="text/css">
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/front/css/style.css" type="text/css">
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/front/css/style-me.css" type="text/css">
<script type="text/javascript" src="<?php echo base_url(); ?>assets/front/js/jquery.min.js"></script>
</head>
<body>
<div class="page">
<!-- Header -->
<header class="header-container">
<div class="header-top">
<div class="container">
<div class="row">
<div class="col-xs-2">
<div class="dropdown block-language-wrapper"> <a role="button" class="block-language dropdown-toggle" href="/"> <img src="<?php echo base_url(); ?>/assets/front/images/gem-icon.png" alt="assets/front/images/gem-icon.png"> <span class="hidden-xs">Welcome visitor! </span> </a>
</div>
</div>
<div class="col-xs-10">
<!-- Header Top Links -->
<div class="toplinks">
<div class="links">
<?php if(isset($this->session->user['id'])){?>
<div class="myaccount"><a title="My Account" href="/default/myaccount/dashboard"><i class="fa fa-user"></i></span> My Account </a></div>
<div class="wishlist"><a title="Logout" href="/default/login/logout"><span class="glyphicon glyphicon-lock"></span> Logout </a></div>
<?php }else{
?>
<div class="wishlist"><a title="Login" href="/login"><span class="glyphicon glyphicon-lock"></span> Login </a></div>
<div class="wishlist"><a title="Register" href="/register"> <span class="glyphicon glyphicon-edit"> </span> Register </a></div>
<?php
}?>
<div class="phone hidden-xs"> +1 (00) 86 868 868 666</div>
</div>
</div>
<!-- End Header Top Links -->
</div>
</div>
</div>
</div>
<div class="header container">
<div class="row">
<div class="col-lg-2 col-sm-3 col-md-2 col-xs-12">
<!-- Header Logo -->
<a class="logo" title="" href="/"><img alt="Magento Commerce" src="<?php echo base_url(); ?>/assets/front/images/logo.png"></a>
<!-- End Header Logo -->
</div>
<!-- Top Cart -->
<div class="col-lg-10 col-sm-9 col-md-10 col-xs-12 message">
<div class="signup"><a title="Login" href="#"><span class=" glyphicon glyphicon-user usericon"></span> <span class="hidden-xs"> Welcome User </span></a></div>
<span class="or"> | </span>
<div class="signup"><a title="Login" href="#"><span class="glyphicon glyphicon-heart usericon"></span> <span class="hidden-xs"> Item Watched </span></a></div>
<span class="or"> | </span>
<div class="signup"><a title="Login" href="#"><span class="glyphicon glyphicon-comment usericon"></span> <span class="hidden-xs"> Message </span></a></div>
</div>
<!-- End Top Cart -->
</div>
</div>
</header>
<!-- end header -->
<!-- Navbar -->
<nav>
<div class="container">
<div class="nav-inner">
<!-- mobile-menu -->
<div class="hidden-desktop" id="mobile-menu">
<ul class="navmenu">
<li>
<div class="menutop">
<div class="toggle"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span></div>
<h2>Menu</h2>
</div>
<ul style="display:none;" class="submenu">
<li>
<ul class="topnav">
<li class="level0 nav-9 level-top last parent "> </li>
<li class="level0 nav-7 level-top parent">
<div style="margin-bottom:25px;">
<select name="category_id" class="search_res ">
<option value="37"> <b>Gemstone</b></option>
<option value="42"> Gemstone1</option>
<option value="42"> Gemstone2</option>
<option value="42"> Gemstone3</option>
<option value="42"> Gemstone4</option>
<option value="42"> Gemstone5</option>
</select>
<select name="category_id" class="search_res ">
<option value="37">Shape</option>
<option value="42"> Gemstone1</option>
<option value="42"> Gemstone2</option>
<option value="42"> Gemstone3</option>
<option value="42"> Gemstone4</option>
<option value="42"> Gemstone5</option>
</select>
<select name="category_id" class="search_res ">
<option value="37">Size</option>
<option value="42"> Gemstone1</option>
<option value="42"> Gemstone2</option>
<option value="42"> Gemstone3</option>
<option value="42"> Gemstone4</option>
<option value="42"> Gemstone5</option>
</select>
<select name="category_id" class="search_res ">
<option value="37">Location</option>
<option value="42"> Gemstone1</option>
<option value="42"> Gemstone2</option>
<option value="42"> Gemstone3</option>
<option value="42"> Gemstone4</option>
<option value="42"> Gemstone5</option>
</select>
<button id="Button2" class="search-btn-bg2"><span class="glyphicon glyphicon-search"></span></button>
</div>
</li>
<li class="level0 nav-6 level-top first parent"> <a class="level-top" href="<?php echo base_url()?>"> <span>Home</span> </a>
</li>
<li class="level0 nav-6 level-top"> <a class="level-top" href="#"> <span>Gemstone</span> </a>
</li>
<li class="level0 parent drop-menu"><a href="blog.html"><span>Seller Store</span> </a>
<ul class="level1">
<li class="level1 first"><a href="#"><span> <b>Store By Country</b> </span></a></li>
<li class="level1 first"><a href="blog_posts_table_view.html"><span>Country1</span></a></li>
<li class="level1 nav-10-2"> <a href="blog_single_post.html"> <span>Country2</span> </a> </li>
<li class="level1 first"><a href="blog_posts_table_view.html"><span>Country3</span></a></li>
<li class="level1 nav-10-2"> <a href="blog_single_post.html"> <span>Country4</span> </a> </li>
<li class="level1 first"><a href="#"><span> <b>Store By Location</b> </span></a></li>
<li class="level1 first"><a href="blog_posts_table_view.html"><span>Location1</span></a></li>
<li class="level1 nav-10-2"> <a href="blog_single_post.html"> <span>Location2</span> </a> </li>
<li class="level1 first"><a href="blog_posts_table_view.html"><span>Location3</span></a></li>
<li class="level1 nav-10-2"> <a href="blog_single_post.html"> <span>Location4</span> </a> </li>
</ul>
</li>
<li class="level0 parent drop-menu"><a href="blog.html"><span>Information</span> </a>
<ul class="level1">
<li class="level1 first"><a href="blog_posts_table_view.html"><span>Granding Scale</span></a></li>
<li class="level1 nav-10-2"> <a href="blog_single_post.html"> <span>Gem Certification</span> </a> </li>
<li class="level1 first"><a href="blog_posts_table_view.html"><span>Gemstone Solution</span></a></li>
<li class="level1 nav-10-2"> <a href="blog_single_post.html"> <span>Astrological Use</span> </a> </li>
<li class="level1 first"><a href="#"><span> <b>Store By Location</b> </span></a></li>
<li class="level1 first"><a href="blog_posts_table_view.html"><span>List of Articles</span></a></li>
<li class="level1 nav-10-2"> <a href="blog_single_post.html"> <span>Shipping & Returns</span> </a> </li>
<li class="level1 first"><a href="blog_posts_table_view.html"><span>Privacy Notice</span></a></li>
<li class="level1 nav-10-2"> <a href="blog_single_post.html"> <span>About Us</span> </a> </li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<!--navmenu-->
</div>
<!--End mobile-menu -->
<a class="logo-small" title="Magento Commerce" href="index.html"><img alt="Magento Commerce" src="<?php echo base_url(); ?>/assets/front/images/gem-icon.png"></a>
<ul id="nav" class="hidden-xs">
<li class="level0 parent drop-menu"><a href="<?php echo base_url()?>" class="active1"><span>Home</span> </a>
</li>
<li class="level0 parent drop-menu"><a href="#"><span>Gemstone</span> </a></li>
<li class="level0 nav-5 level-top parent"><a href="grid.html"><span>Seller Store</span> </a>
<div class="level0-wrapper dropdown-6col" style="display: none;">
<div class="level0-wrapper2">
<div class="nav-block nav-block-center">
<ul class="level0">
<li class="level1 nav-6-1 parent item"> <a href="grid.html"><span>Store By Country </span></a>
<!--sub sub category-->
<ul class="level1">
<li class="level2 nav-6-1-1"> <a href="grid.html"><span>Country1</span></a> </li>
<li class="level2 nav-6-1-1"> <a href="grid.html"><span>Country2</span></a> </li>
<li class="level2 nav-6-1-1"> <a href="grid.html"><span>Country3</span></a> </li>
<li class="level2 nav-6-1-1"> <a href="grid.html"><span>Country4</span></a> </li>
</ul>
<!--sub sub category-->
</li>
<li class="level1 nav-6-1 parent item"> <a href="grid.html"><span>Store By Location </span></a>
<!--sub sub category-->
<ul class="level1">
<li class="level2 nav-6-1-1"> <a href="grid.html"><span>Location1</span></a> </li>
<li class="level2 nav-6-1-1"> <a href="grid.html"><span>Location2</span></a> </li>
<li class="level2 nav-6-1-1"> <a href="grid.html"><span>Location3</span></a> </li>
<li class="level2 nav-6-1-1"> <a href="grid.html"><span>Location4</span></a> </li>
</ul>
<!--sub sub category-->
</li>
</ul>
</div>
</div>
<!--level0-wrapper2-->
</div>
</li>
<li class="level0 nav-5 level-top parent"><a href="grid.html"><span>Information</span> </a>
<div class="level0-wrapper dropdown-6col" style="display: none;">
<div class="level0-wrapper2">
<div class="nav-block nav-block-center">
<ul class="level0">
<li class="level1 nav-6-1 parent item"> <a href="grid.html"><span>Store By Country </span></a>
<!--sub sub category-->
<ul class="level1">
<li class="level2 nav-6-1-1"> <a href="grid.html"><span>Country1</span></a> </li>
<li class="level2 nav-6-1-1"> <a href="grid.html"><span>Country2</span></a> </li>
<li class="level2 nav-6-1-1"> <a href="grid.html"><span>Country3</span></a> </li>
<li class="level2 nav-6-1-1"> <a href="grid.html"><span>Country4</span></a> </li>
</ul>
<!--sub sub category-->
</li>
<li class="level1 nav-6-1 parent item"> <a href="grid.html"><span>Store By Location </span></a>
<!--sub sub category-->
<ul class="level1">
<li class="level2 nav-6-1-1"> <a href="grid.html"><span>Location1</span></a> </li>
<li class="level2 nav-6-1-1"> <a href="grid.html"><span>Location2</span></a> </li>
<li class="level2 nav-6-1-1"> <a href="grid.html"><span>Location3</span></a> </li>
<li class="level2 nav-6-1-1"> <a href="grid.html"><span>Location4</span></a> </li>
</ul>
<!--sub sub category-->
</li>
</ul>
</div>
</div>
<!--level0-wrapper2-->
</div>
</li>
<li class="nav-custom-link level0 level-top parent">
<div class="search-box">
<form method="POST" id="Form1" name="Categories">
<select name="category_id" class="cate-dropdown hidden-xs">
<option value="37"> <b>Gemstone</b></option>
<option value="42"> Gemstone1</option>
<option value="42"> Gemstone2</option>
<option value="42"> Gemstone3</option>
<option value="42"> Gemstone4</option>
<option value="42"> Gemstone5</option>
</select>
<select name="category_id" class="cate-dropdown hidden-xs">
<option value="37">Shape</option>
<option value="42"> Gemstone1</option>
<option value="42"> Gemstone2</option>
<option value="42"> Gemstone3</option>
<option value="42"> Gemstone4</option>
<option value="42"> Gemstone5</option>
</select>
<select name="category_id" class="cate-dropdown hidden-xs">
<option value="37">Size</option>
<option value="42"> Gemstone1</option>
<option value="42"> Gemstone2</option>
<option value="42"> Gemstone3</option>
<option value="42"> Gemstone4</option>
<option value="42"> Gemstone5</option>
</select>
<select name="category_id" class="cate-dropdown hidden-xs">
<option value="37">Location</option>
<option value="42"> Gemstone1</option>
<option value="42"> Gemstone2</option>
<option value="42"> Gemstone3</option>
<option value="42"> Gemstone4</option>
<option value="42"> Gemstone5</option>
</select>
<button id="Button1" class="search-btn-bg"><span class="glyphicon glyphicon-search"></span></button>
</form>
</div>
</li>
</ul>
</div>
</div>
</nav>
<!-- end nav -->
<?php echo $content;?>
<!-- Footer -->
<footer class="footer">
<div class="footer-middle container">
<div class="col-md-3 col-sm-4">
<div class="footer-logo">
<a title="" href="/"><img alt="Magento Commerce" src="<?php echo base_url(); ?>/assets/front/images/logo.png"></a>
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus diam arcu. </p>
<div class="payment-accept">
<div>
<img src="<?php echo base_url(); ?>/assets/front/images/payment-1.png" alt="payment">
<img src="<?php echo base_url(); ?>/assets/front/images/payment-2.png" alt="payment">
<img src="<?php echo base_url(); ?>/assets/front/images/payment-3.png" alt="payment">
<img src="<?php echo base_url(); ?>/assets/front/images/payment-4.png" alt="payment">
</div>
</div>
</div>
<div class="col-md-2 col-sm-4">
<h4>Shopping Guide</h4>
<ul class="links">
<li class="first"><a href="#" title="How to buy">How to buy</a></li>
<li><a href="faq.html" title="FAQs">FAQs</a></li>
<li><a href="#" title="Payment">Payment</a></li>
<li><a href="#" title="Shipment</a>">Shipment</a></li>
<li><a href="delivery.html" title="delivery">Delivery</a></li>
<li class="last"><a href="#" title="Return policy">Return policy</a></li>
</ul>
</div>
<div class="col-md-2 col-sm-4">
<h4>Style Advisor</h4>
<ul class="links">
<li class="first"><a title="Your Account" href="login.html">Your Account</a></li>
<li><a title="Information" href="#">Information</a></li>
<li><a title="Addresses" href="#">Addresses</a></li>
<li><a title="Addresses" href="#">Discount</a></li>
<li><a title="Orders History" href="#">Orders History</a></li>
<li class="last"><a title=" Additional Information" href="#">Additional Information</a></li>
</ul>
</div>
<div class="col-md-2 col-sm-4">
<h4>Information</h4>
<ul class="links">
<li class="first"><a href="sitemap.html" title="Site Map">Site Map</a></li>
<li><a href="#/" title="Search Terms">Search Terms</a></li>
<li><a href="#" title="Advanced Search">Advanced Search</a></li>
<li><a href="contact_us.html" title="Contact Us">Contact Us</a></li>
<li><a href="#" title="Suppliers">Suppliers</a></li>
<li class=" last"><a href="#" title="Our stores" class="link-rss">Our stores</a></li>
</ul>
</div>
<div class="col-md-3 col-sm-4">
<h4>Contact us</h4>
<div class="contacts-info">
<address>
<i class="add-icon"> </i>123 Main Street, Anytown, <br>
CA 12345 USA
</address>
<div class="phone-footer"><i class="phone-icon"> </i> +1 800 123 1234</div>
<div class="email-footer"><i class="email-icon"> </i> <a href="mailto:[email protected]">[email protected]</a> </div>
</div>
</div>
</div>
<div class="footer-bottom">
<div class="container">
<div class="col-sm-5 col-xs-12 coppyright"> © 2016 Gemstone. All Rights Reserved. </div>
<div class="col-sm-7 col-xs-12 company-links">
<ul class="links">
<li class="last"><a href="#" title="Magento Extensions">Privacy Policy</a></li>
</ul>
</div>
</div>
</div>
</footer>
<!-- End Footer -->
</div>
<!-- JavaScript -->
<script type="text/javascript" src="<?php echo base_url(); ?>assets/front/js/bootstrap.min.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/front/js/common.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/front/js/owl.carousel.min.js"></script>
<script src="<?php echo base_url(); ?>assets/front/js/jquery.validate.min.js" type="text/javascript"></script>
</body>
</html>
| apache-2.0 |
zoomis/PLCNMS | JavaSource/dpnm/netmsuite/plc/manager/frontend/graph/TestGraphManager.java | 435 | package dpnm.netmsuite.plc.manager.frontend.graph;
import dpnm.netmsuite.plc.manager.frontend.*;
public class TestGraphManager {
public static void main(String argc[]){
IFrontEndManager frontMgr = FrontEndManager.getInstance();
frontMgr.frontEndManagerstart();
IGraphManager graphMgr = GraphManager.getInstance();
graphMgr.getGraph("1111138", 1, 600, 400);
frontMgr.frontEndManagerstop();
}
}
| apache-2.0 |
lvuch/ui | app/volumes/index/controller.js | 1589 | import { alias } from '@ember/object/computed';
import { inject as service } from '@ember/service';
import Controller, { inject as controller } from '@ember/controller';
export default Controller.extend({
scope: service(),
projectController: controller('authenticated.project'),
queryParams: ['sortBy'],
sortBy: 'name',
headers: [
{
name: 'state',
sort: ['sortState', 'displayName'],
searchField: 'displayState',
translationKey: 'generic.state',
width: 120
},
{
name: 'name',
sort: ['displayName', 'id'],
searchField: 'displayName',
translationKey: 'volumesPage.claimName.label',
},
{
name: 'size',
sort: ['sizeBytes'],
search: ['sizeBytes', 'displaySize'],
translationKey: 'generic.size',
width: 120
},
{
name: 'volume',
sort: ['volume.displayName', 'displayName', 'id'],
translationKey: 'volumesPage.volume.label',
searchField: null,
},
{
name: 'storageClass',
sort: ['storageClass.displayName', 'displayName', 'id'],
translationKey: 'volumesPage.storageClass.label',
searchField: null,
},
],
groupTableBy: alias('projectController.groupTableBy'),
expandedInstances: alias('projectController.expandedInstances'),
preSorts: alias('projectController.preSorts'),
rows: alias('model.persistentVolumeClaims'),
});
| apache-2.0 |
emistoolbox/emistoolbox | libs/joriki/src/info/joriki/compression/huffman/HuffmanCode.java | 7979 | /*
* Copyright 2002 Felix Pahl. All rights reserved.
* Use is subject to license terms.
*/
package info.joriki.compression.huffman;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.ArrayList;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Iterator;
import info.joriki.util.General;
import info.joriki.util.Handler;
import info.joriki.util.Assertions;
import info.joriki.util.Traversable;
public class HuffmanCode implements Traversable<HuffmanLeaf>
{
int maxlen;
List<HuffmanLeaf> leaves;
private HuffmanCode () {}
// reads in a Huffman table as coded in JPEG files
public HuffmanCode (InputStream in,int maxlen) throws IOException
{
this.maxlen = maxlen;
final int [] nsymbols = new int [maxlen+1];
for (int i = 1;i <= maxlen;i++)
nsymbols [i] = in.read ();
List<HuffmanLeaf> [] byLength = new List [maxlen+1];
for (int i = 1;i <= maxlen;i++)
{
List<HuffmanLeaf> next = byLength [i] = new ArrayList<HuffmanLeaf> ();
for (int j = 0;j < nsymbols [i];j++)
{
HuffmanLeaf leaf = new HuffmanLeaf ();
leaf.codeLength = i;
leaf.symbol = in.read ();
if ((leaf.symbol & 0xf) > 11)
System.err.println ("??????? big size " +
(leaf.symbol & 0xf));
next.add (leaf);
}
}
makeLeaves (byLength);
}
// builds a huffman code from binary strings
// symbols can be null, in which case the symbols are the indices into binaryStrings
public HuffmanCode (String [] binaryStrings,int [] symbols)
{
if (symbols != null)
Assertions.expect (symbols.length == binaryStrings.length);
leaves = new ArrayList<HuffmanLeaf> (binaryStrings.length);
for (int i = 0;i < binaryStrings.length;i++)
{
int len = binaryStrings [i].length ();
maxlen = Math.max (maxlen,len);
HuffmanLeaf leaf = new HuffmanLeaf ();
leaf.symbol = symbols != null ? symbols [i] : i;
leaf.codeLength = len;
leaf.code = Integer.parseInt (binaryStrings [i],2);
leaves.add (leaf);
}
}
public HuffmanCode (HuffmanCode code)
{
this.maxlen = code.maxlen;
this.leaves = new ArrayList<HuffmanLeaf> (code.leaves);
}
int nodeNumber;
class Node implements Comparable
{
int num = nodeNumber++;
int depth;
int symbol;
int frequency;
Node left;
Node right;
Node (int symbol,int frequency)
{
this.symbol = symbol;
this.frequency = frequency;
this.depth = 1;
}
Node (Node left,Node right)
{
this.left = left;
this.right = right;
this.frequency = left.frequency + right.frequency;
this.depth = Math.max (left.depth,right.depth) + 1;
}
public int compareTo (Object o)
{
Node n = (Node) o;
int dif = frequency - n.frequency;
if (dif != 0)
return dif;
dif = n.depth - depth;
if (dif != 0)
return dif;
dif = num - n.num;
return dif;
}
void traverse (int length)
{
Assertions.expect (right != null,left != null);
if (left != null)
{
left.traverse (length+1);
right.traverse (length+1);
}
else
{
HuffmanLeaf leaf = new HuffmanLeaf ();
leaf.codeLength = length;
leaf.symbol = symbol;
leaves.add (leaf);
maxlen = Math.max (maxlen,length);
}
}
}
// constructs an optimal huffman code
public HuffmanCode (int [] symbols,int [] frequencies)
{
this (symbols,frequencies,Integer.MAX_VALUE);
}
public HuffmanCode (int [] symbols,int [] frequencies,int lengthConstraint)
{
Assertions.expect (symbols == null || symbols.length == frequencies.length);
SortedSet<Node> nodeSet = new TreeSet<Node> ();
for (int i = 0;i < frequencies.length;i++)
if (frequencies [i] != 0)
nodeSet.add (new Node (symbols == null ? i : symbols [i],frequencies [i]));
// dummy symbol to prevent allocation of all-| code
nodeSet.add (new Node (-1,0));
while (nodeSet.size () > 1)
{
Node right = nodeSet.first ();
nodeSet.remove (right);
Node left = nodeSet.first ();
nodeSet.remove (left);
nodeSet.add (new Node (left,right));
}
leaves = new ArrayList<HuffmanLeaf> (frequencies.length + 1);
nodeSet.first ().traverse (0);
// we could assign codes in the traversal,
// but we'd have to make them conform to
// how JPEG assigns them. If the length
// constraint is violated, we go by length
// anyway, so why bother
List<HuffmanLeaf> [] byLength = new List [maxlen+1];
for (int i = 1;i <= maxlen;i++)
byLength [i] = new ArrayList<HuffmanLeaf> ();
Iterator<HuffmanLeaf> iterator = leaves.iterator ();
while (iterator.hasNext ())
{
HuffmanLeaf leaf = iterator.next ();
byLength [leaf.codeLength].add (leaf);
}
while (maxlen > lengthConstraint)
{
iterator = byLength [maxlen--].iterator ();
while (iterator.hasNext ())
{
HuffmanLeaf left = iterator.next ();
HuffmanLeaf right = iterator.next ();
int l = maxlen;
while (byLength [--l].isEmpty ())
;
HuffmanLeaf demotee = General.removeLast (byLength [l]);
byLength [l+1].add (demotee);
byLength [l+1].add (left);
byLength [maxlen].add (right);
}
}
// remove dummy
Assertions.expect ((General.removeLast (byLength [maxlen])).symbol,-1);
makeLeaves (byLength);
}
// generates a list of leaves with codes
// from an array of lists of leaves without codes ordered by length
private void makeLeaves (List<HuffmanLeaf> [] byLength)
{
leaves = new ArrayList<HuffmanLeaf> ();
for (int i = 1,code = 0;i <= maxlen;i++,code <<= 1)
for (int j = 0;j < byLength [i].size ();j++)
{
HuffmanLeaf leaf = byLength [i].get (j);
leaf.codeLength = i;
leaf.code = code++;
leaves.add (leaf);
}
}
// traverses linear vector of leaves.
public void traverse (Handler<HuffmanLeaf> handler)
{
General.traverse (leaves,handler);
}
public void addSymbol (int symbol)
{
// make sure we don't mess things up in another code that
// shares some of our leaves
HuffmanLeaf lastLeaf;
do
lastLeaf = (HuffmanLeaf) (leaves.remove (leaves.size () - 1)).clone ();
while (lastLeaf.codeLength == maxlen);
HuffmanLeaf newLeaf = new HuffmanLeaf ();
lastLeaf.code <<= 1;
newLeaf.code = lastLeaf.code + 1;
newLeaf.codeLength = ++lastLeaf.codeLength;
newLeaf.symbol = symbol;
leaves.add (lastLeaf);
leaves.add (newLeaf);
}
public void writeTo (final OutputStream out) throws IOException
{
final byte [] cnt = new byte [16];
traverse (new Handler<HuffmanLeaf> () {
public void handle (HuffmanLeaf leaf)
{
cnt [leaf.codeLength - 1]++;
}
});
out.write (cnt);
traverse (new Handler<HuffmanLeaf> () {
public void handle (HuffmanLeaf leaf)
{
try {
out.write (leaf.symbol);
} catch (IOException ioe) { ioe.printStackTrace (); }
}
});
}
public static HuffmanCode uniformCode (int nbits)
{
HuffmanCode uniformCode = new HuffmanCode ();
uniformCode.leaves = new ArrayList<HuffmanLeaf> ();
for (int code = 0;code < (1 << nbits) - 1;code++)
{
HuffmanLeaf leaf = new HuffmanLeaf ();
leaf.code = leaf.symbol = code;
leaf.codeLength = nbits;
uniformCode.leaves.add (leaf);
}
uniformCode.maxlen = nbits;
return uniformCode;
}
}
| apache-2.0 |
Lihuanghe/CMPPGate | src/test/java/com/zx/sms/codec/cmpp/TestSpeedError.java | 5503 | package com.zx.sms.codec.cmpp;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.ResourceLeakDetector;
import io.netty.util.ResourceLeakDetector.Level;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.Charset;
import java.util.concurrent.ConcurrentHashMap;
import org.junit.Assert;
import org.junit.Test;
import com.zx.sms.codec.cmpp.msg.CmppSubmitRequestMessage;
import com.zx.sms.codec.cmpp.msg.CmppSubmitResponseMessage;
import com.zx.sms.common.util.MsgId;
import com.zx.sms.connect.manager.cmpp.CMPPClientEndpointEntity;
import com.zx.sms.connect.manager.cmpp.CMPPCodecChannelInitializer;
import com.zx.sms.session.cmpp.SessionStateManager;
public class TestSpeedError {
private short reSendTime = 3;
protected EmbeddedChannel ch = new EmbeddedChannel(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ResourceLeakDetector.setLevel(Level.ADVANCED);
ChannelPipeline pipeline = ch.pipeline();
CMPPCodecChannelInitializer codec = new CMPPCodecChannelInitializer();
pipeline.addLast("serverLog", new LoggingHandler(LogLevel.DEBUG));
pipeline.addLast(codec.pipeName(), codec);
CMPPClientEndpointEntity client = new CMPPClientEndpointEntity();
client.setId("client");
client.setHost("127.0.0.1");
client.setPort(7891);
client.setChartset(Charset.forName("utf-8"));
client.setGroupName("test");
client.setUserName("901782");
client.setPassword("ICP");
client.setMaxChannels((short) 12);
client.setVersion((short) 0x20);
client.setRetryWaitTimeSec(reSendTime);
client.setUseSSL(false);
client.setReSendFailMsg(true);
pipeline.addLast("session", new SessionStateManager(client, new ConcurrentHashMap(), true));
}
});
@Test
public void test() throws InterruptedException {
SessionStateManager sessionhandler = (SessionStateManager) ch.pipeline().get("session");
// 测试超速错误的重发机制
CmppSubmitRequestMessage msg = new CmppSubmitRequestMessage();
msg.setDestterminalId(new String[] { "13800138000" });
msg.setLinkID("0000");
msg.setMsgContent("123");
msg.setServiceId("10086");
msg.setSrcId("10086");
ch.writeOutbound(msg);
// 等待重发
Thread.sleep((reSendTime + 1) * 1000);
// 一共发送了2条MT消息
Assert.assertEquals(2, sessionhandler.getWriteCount());
// 有一条等待发送的消息
Assert.assertEquals(1, sessionhandler.getWaittingResp());
ByteBuf recvMsg = ch.readOutbound();
Assert.assertNotNull(recvMsg);
// 新为上面等待超时,会重发一次,所以这里会收到两条
recvMsg = ch.readOutbound();
Assert.assertNotNull(recvMsg);
// 回复一条超速错误
CmppSubmitResponseMessage resp = new CmppSubmitResponseMessage(msg.getHeader().getSequenceId());
resp.setResult(8L);
ch.writeOutbound(resp); // 把resp转化为ByteBuf
ch.writeInbound(ch.readOutbound());
Thread.sleep(1000);
// 一共发送了3条MT消息
Assert.assertEquals(3, sessionhandler.getWriteCount());
// 收到超速错,会再次重发一次
recvMsg = ch.readOutbound();
Assert.assertNotNull(recvMsg);
// 回复一条正确接收
resp = new CmppSubmitResponseMessage(msg.getHeader().getSequenceId());
resp.setResult(0L);
ch.writeOutbound(resp); // 把resp转化为ByteBuf
ch.writeInbound(ch.readOutbound());
CmppSubmitResponseMessage respret = ch.readInbound();
// System.out.println(respret.getRequest());
Assert.assertSame(msg, respret.getRequest());
Assert.assertNotEquals(respret.getMsgId(), msg.getMsgid());
// 没有等待发送的消息
Assert.assertEquals(0, sessionhandler.getWaittingResp());
// 等待重发超时
Thread.sleep((reSendTime + 1) * 1000);
// 因为已收到response,发送成功了,不会再重发了,因此这次接收的是Null
recvMsg = ch.readOutbound();
Assert.assertNull(recvMsg);
}
@Test
public void testterminated() throws IOException, ClassNotFoundException, InterruptedException {
CmppSubmitRequestMessage msg = new CmppSubmitRequestMessage();
msg.setDestterminalId(new String[] { "13800138000" });
msg.setLinkID("0000");
msg.setMsgContent("123asdf23asdgq5");
msg.setMsgid(new MsgId());
msg.setServiceId("10086");
msg.setSrcId("10086");
// 设置短信的生存时间为2s
msg.setLifeTime(2);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(msg);
byte[] b = bos.toByteArray();
Thread.sleep(3000);
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b));
CmppSubmitRequestMessage result = (CmppSubmitRequestMessage) in.readObject();
ChannelFuture futurn = ch.writeAndFlush(result);
// System.out.println(futurn.isSuccess());
// Thread.sleep(100);
Assert.assertTrue(!futurn.isSuccess());
Assert.assertTrue("Msg Life over".equals(futurn.cause().getMessage()));
}
}
| apache-2.0 |
fugeritaetas/morozko-lib | java14-morozko/org.morozko.java.mod.cmd/src/org/morozko/java/mod/cmd/helpers/LineCMDOutput.java | 1700 | /*****************************************************************
<copyright>
Morozko Java Library org.morozko.java.mod.cmd
Copyright (c) 2006 Morozko
All rights reserved. This program and the accompanying materials
are made available under the terms of the Apache License v2.0
which accompanies this distribution, and is available at
http://www.apache.org/licenses/
(txt version : http://www.apache.org/licenses/LICENSE-2.0.txt
html version : http://www.apache.org/licenses/LICENSE-2.0.html)
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
</copyright>
*****************************************************************/
/*
* @(#)LineCMDOutput.java
*
* @project : org.morozko.java.core
* @package : org.morozko.java.mod.cmd.helpers
* @creation : 21-dic-2004 16.06.05
* @release : xxxx.xx.xx
*/
package org.morozko.java.mod.cmd.helpers;
/**
* <p></p>
*
* @author Matteo Franci a.k.a. TUX2
*/
public class LineCMDOutput extends TableCMDOutput {
private static String[][] toMatrix(String[] line) {
String[][] table = { line };
return table;
}
/**
* <p>Crea un nuovo LineCMDOutput</p>
*
* @param command
* @param table
*/
public LineCMDOutput(String command, String[] line) {
super(command, null, toMatrix(line));
}
/**
* <p>Crea un nuovo LineCMDOutput</p>
*
* @param command
* @param head
* @param table
*/
public LineCMDOutput(String command, String[] head, String[] line) {
super(command, head, toMatrix(line));
}
}
| apache-2.0 |
songshu198907/LeetPractise | src/main/java/algorithm/leet_181_320/Word_Pattern_290.java | 740 | package algorithm.leet_181_320;
import java.util.HashMap;
/**
* Created by songheng on 7/12/16.
*/
public class Word_Pattern_290 {
public boolean wordPattern(String pattern, String str) {
String[] words = str.split("\\s+");
if (words.length != pattern.length()) return false;
HashMap<Character, String> map = new HashMap<>();
for (int i = 0; i < words.length; i++) {
char ch = pattern.charAt(i);
if (!map.containsKey(ch)) {
if (i > 0 && words[i].equals(words[i - 1])) return false;
map.put(ch, words[i]);
} else {
if (!words[i].equals(map.get(ch))) return false;
}
}
return true;
}
}
| apache-2.0 |
deepakddixit/incubator-geode | geode-junit/src/main/java/org/apache/geode/cache/query/data/PositionPdx.java | 5322 | /*
* 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.data;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import org.apache.geode.pdx.PdxReader;
import org.apache.geode.pdx.PdxSerializable;
import org.apache.geode.pdx.PdxWriter;
public class PositionPdx implements Serializable, PdxSerializable, Comparable {
private long avg20DaysVol = 0;
private String bondRating;
private double convRatio;
private String country;
private double delta;
private long industry;
private long issuer;
private double mktValue;
private double qty;
public String secId;
public String secIdIndexed;
private String secLinks;
public String secType;
private double sharesOutstanding;
public String underlyer;
private long volatility;
private int pid;
public static int cnt = 0;
public int portfolioId = 0;
public static int numInstance = 0;
/* public no-arg constructor required for DataSerializable */
public PositionPdx() {
this.numInstance++;
// GemFireCacheImpl.getInstance().getLoggerI18n().fine(new Exception("DEBUG"));
}
public PositionPdx(String id, double out) {
secId = id;
secIdIndexed = secId;
sharesOutstanding = out;
secType = "a";
pid = cnt++;
this.mktValue = cnt;
this.numInstance++;
// GemFireCacheImpl.getInstance().getLoggerI18n().fine(new Exception("DEBUG" + this.secId));
}
@Override
public boolean equals(Object o) {
if (!(o instanceof PositionPdx))
return false;
return this.secId.equals(((PositionPdx) o).secId);
}
@Override
public int hashCode() {
return this.secId.hashCode();
}
public static void resetCounter() {
cnt = 0;
}
public double getMktValue() {
return this.mktValue;
}
public String getSecId() {
return secId;
}
public int getId() {
return pid;
}
public double getSharesOutstanding() {
return sharesOutstanding;
}
public String toString() {
return "PositionPdx [secId=" + this.secId + " out=" + this.sharesOutstanding + " type="
+ this.secType + " id=" + this.pid + " mktValue=" + this.mktValue + "]";
}
public Set getSet(int size) {
Set set = new HashSet();
for (int i = 0; i < size; i++) {
set.add("" + i);
}
return set;
}
public Set getCol() {
Set set = new HashSet();
for (int i = 0; i < 2; i++) {
set.add("" + i);
}
return set;
}
public int getPid() {
return pid;
}
public void fromData(PdxReader in) {
this.avg20DaysVol = in.readLong("avg20DaysVol");
this.bondRating = in.readString("bondRating");
this.convRatio = in.readDouble("convRatio");
this.country = in.readString("country");
this.delta = in.readDouble("delta");
this.industry = in.readLong("industry");
this.issuer = in.readLong("issuer");
this.mktValue = in.readDouble("mktValue");
this.qty = in.readDouble("qty");
this.secId = in.readString("secId");
this.secIdIndexed = in.readString("secIdIndexed");
this.secLinks = in.readString("secLinks");
this.sharesOutstanding = in.readDouble("sharesOutstanding");
this.underlyer = in.readString("underlyer");
this.volatility = in.readLong("volatility");
this.pid = in.readInt("pid");
this.portfolioId = in.readInt("portfolioId");
// GemFireCacheImpl.getInstance().getLoggerI18n().fine(new Exception("DEBUG fromData() " +
// this.secId));
}
public void toData(PdxWriter out) {
out.writeLong("avg20DaysVol", this.avg20DaysVol);
out.writeString("bondRating", this.bondRating);
out.writeDouble("convRatio", this.convRatio);
out.writeString("country", this.country);
out.writeDouble("delta", this.delta);
out.writeLong("industry", this.industry);
out.writeLong("issuer", this.issuer);
out.writeDouble("mktValue", this.mktValue);
out.writeDouble("qty", this.qty);
out.writeString("secId", this.secId);
out.writeString("secIdIndexed", this.secIdIndexed);
out.writeString("secLinks", this.secLinks);
out.writeDouble("sharesOutstanding", this.sharesOutstanding);
out.writeString("underlyer", this.underlyer);
out.writeLong("volatility", this.volatility);
out.writeInt("pid", this.pid);
out.writeInt("portfolioId", this.portfolioId);
// Identity Field.
out.markIdentityField("secId");
}
public int compareTo(Object o) {
if (o == this || ((PositionPdx) o).secId.equals(this.secId)) {
return 0;
} else {
return this.pid < ((PositionPdx) o).pid ? -1 : 1;
}
}
}
| apache-2.0 |
WeTheInternet/collide | client/src/main/java/collide/junit/ArrayTests.java | 4210 | package collide.junit;
import org.junit.Test;
import com.google.gwt.reflect.client.strategy.ReflectionStrategy;
import com.google.gwt.reflect.shared.GwtReflect;
import java.lang.reflect.Array;
import java.util.Arrays;
/**
* @author James X. Nelson ([email protected], @james)
*/
@ReflectionStrategy(magicSupertypes=false, keepCodeSource=true)
public class ArrayTests extends AbstractReflectionTest {
public ArrayTests() {}
@Test
public void testSingleDimPrimitive() {
long[] longs = (long[])Array.newInstance(long.class, 5);
assertEquals(longs.length, 5);
assertEquals(longs.getClass(), long[].class);
longs[0] = 1;
Array.setLong(longs, 1, 2);
Array.setLong(longs, 2, longs[0] + 2);
Array.setLong(longs, 3, Array.getLong(longs, 2) +1);
Array.setLong(longs, 4, Array.getLength(longs));
assertTrue("Arrays not equals", Arrays.equals(longs, new long[] {1,2,3,4,5}));
}
@Test
public void testSingleDimComplex() {
long[][] longs = (long[][])Array.newInstance(long[].class, 5);
assertEquals(longs.length, 5);
assertEquals(longs[0], null);
assertEquals(longs.getClass(), long[][].class);
long[] subArr = longs[0] = new long[3];
subArr[0] = 1;
Array.setLong(subArr, 1, 2);
Array.setLong(subArr, 2, subArr[0] + 2);
Array.set(longs, 1, new long[3]);
subArr = (long[])Array.get(longs, 1);
Array.setLong(subArr, 0, 1);
subArr[1] = Array.getLong(subArr, 0) +1;
Array.setLong(subArr, 2, Array.getLength(subArr));
assertTrue("Arrays not equals", Arrays.deepEquals(longs, new long[][] {
new long[]{1,2,3},new long[]{1,2,3}, null, null, null
}));
}
@Test
public void testArrayEqualsSanity() {
long[][] arrays = new long[][]{
new long[]{1,2}, new long[]{3,4}
}
, arrays2 = new long[][]{
new long[]{0,2}, new long[]{3,4}
};
assertTrue("Arrays not equals", Arrays.deepEquals(arrays, arrays));
assertFalse("Arrays.deepEquals fail", Arrays.deepEquals(arrays, arrays2));
}
@Test
public void testSingleDimObject() {
Long[] longs = (Long[])Array.newInstance(Long.class, 5);
assertEquals(longs.length, 5);
assertEquals(longs.getClass(), Long[].class);
longs[0] = 1L;
Array.set(longs, 1, 2L);
Array.set(longs, 2, longs[0] + 2);
Array.set(longs, 3, (Long)Array.get(longs, 2) +1);
Array.set(longs, 4, new Long(Array.getLength(longs)));
assertTrue("Arrays not equals", Arrays.equals(longs, new Long[] {1L,2L,3L,4L,5L}));
}
@Test
public void testMultiDimPrimitive() {
long[][] longs = (long[][])Array.newInstance(long.class, 2, 3);
assertEquals(longs.length, 2);
assertEquals(longs[0].length, 3);
assertEquals(longs.getClass(), long[][].class);
long[] subArr = longs[0];
subArr[0] = 1;
Array.setLong(subArr, 1, 2);
Array.setLong(subArr, 2, subArr[0] + 2);
subArr = (long[])Array.get(longs, 1);
Array.setLong(subArr, 0, 1);
subArr[1] = Array.getLong(subArr, 0) +1;
Array.setLong(subArr, 2, Array.getLength(subArr));
assertTrue("Arrays not equals", Arrays.deepEquals(longs, new long[][] {
new long[]{1,2,3},new long[]{1,2,3}
}));
}
@Test
public void testMultiDimObject() {
Long[][] longs = (Long[][])Array.newInstance(Long.class, 2, 3);
assertEquals(longs.length, 2);
assertEquals(longs[0].length, 3);
assertEquals(longs.getClass(), Long[][].class);
Long[] subArr = longs[0];
subArr[0] = 1L;
Array.set(subArr, 1, 2L);
Array.set(subArr, 2, subArr[0] + 2);
subArr = (Long[])Array.get(longs, 1);
Array.set(subArr, 0, 1L);
subArr[1] = (Long)Array.get(subArr, 0) +1;
Array.set(subArr, 2, new Long(Array.getLength(subArr)));
assertTrue("Arrays erroneously inequal", Arrays.deepEquals(longs, new Long[][] {
new Long[]{1L,2L,3L},new Long[]{1L,2L,3L}
}));
assertFalse("Arrays erroneously equal", Arrays.deepEquals(longs, new Long[][] {
new Long[]{1L,2L,3L},new Long[]{0L,2L,3L}
}));
}
@Test
public void testComplexDims() {
long[][][][] longs = GwtReflect.newArray(long[][].class, 2, 3);
long[][] one = new long[0][], two = new long[1][], three = new long[2][];
}
}
| apache-2.0 |
serebro/mongo-php-driver-prototype | tests/standalone/server-executeBulkWrite-001.phpt | 2073 | --TEST--
MongoDB\Driver\Server::executeBulkWrite()
--SKIPIF--
<?php require __DIR__ . "/../utils/basic-skipif.inc"; CLEANUP(STANDALONE) ?>
--FILE--
<?php
require_once __DIR__ . "/../utils/basic.inc";
$manager = new MongoDB\Driver\Manager(STANDALONE);
$server = $manager->executeQuery(NS, new MongoDB\Driver\Query(array()))->getServer();
$bulk = new MongoDB\Driver\BulkWrite();
$bulk->insert(array('_id' => 1, 'x' => 1));
$bulk->insert(array('_id' => 2, 'x' => 2));
$bulk->update(array('x' => 2), array('$set' => array('x' => 1)), array("limit" => 1, "upsert" => false));
$bulk->update(array('_id' => 3), array('$set' => array('x' => 3)), array("limit" => 1, "upsert" => true));
$bulk->delete(array('x' => 1), array("limit" => 1));
$result = $server->executeBulkWrite(NS, $bulk);
printf("WriteResult.server is the same: %s\n", $server == $result->getServer() ? 'yes' : 'no');
echo "\n===> WriteResult\n";
printWriteResult($result);
var_dump($result);
echo "\n===> Collection\n";
$cursor = $server->executeQuery(NS, new MongoDB\Driver\Query(array()));
var_dump(iterator_to_array($cursor));
?>
===DONE===
<?php exit(0); ?>
--EXPECTF--
WriteResult.server is the same: yes
===> WriteResult
server: %s:%d
insertedCount: 2
matchedCount: 1
modifiedCount: 1
upsertedCount: 1
deletedCount: 1
upsertedId[3]: int(3)
object(MongoDB\Driver\WriteResult)#%d (%d) {
["nInserted"]=>
int(2)
["nMatched"]=>
int(1)
["nModified"]=>
int(1)
["nRemoved"]=>
int(1)
["nUpserted"]=>
int(1)
["upsertedIds"]=>
array(1) {
[0]=>
object(stdClass)#%d (%d) {
["index"]=>
int(3)
["_id"]=>
int(3)
}
}
["writeErrors"]=>
array(0) {
}
["writeConcernError"]=>
array(0) {
}
["writeConcern"]=>
array(4) {
["wmajority"]=>
bool(false)
["wtimeout"]=>
int(0)
["fsync"]=>
bool(false)
["journal"]=>
bool(false)
}
}
===> Collection
array(2) {
[0]=>
array(2) {
["_id"]=>
int(2)
["x"]=>
int(1)
}
[1]=>
array(2) {
["_id"]=>
int(3)
["x"]=>
int(3)
}
}
===DONE===
| apache-2.0 |
undera/pwe | PWE/Auth/PWEUserAuthController.php | 1698 | <?php
namespace PWE\Auth;
use PWE\Core\PWECore;
use PWE\Core\PWELogger;
use PWE\Exceptions\HTTP5xxException;
use PWE\Lib\Smarty\SmartyAssociative;
use PWE\Modules\PWEModule;
/**
* Description of PWEUserAuthController
*
* @author undera
*/
abstract class PWEUserAuthController extends PWEModule implements SmartyAssociative
{
public static function getSmartyAllowedMethods()
{
return array('getUserID', 'getUserName', 'getLevelsUpToAuthNode');
}
abstract public function getUserID();
abstract public function getUserName();
abstract public function handleAuth();
abstract public function handleLogout();
/**
* @param \PWE\Core\PWECore $pwe
* @return PWEUserAuthController
*/
public static function getAuthControllerInstance(PWECore $pwe)
{
try {
$node = $pwe->getNode();
} catch (HTTP5xxException $e) {
PWELogger::warn('Failed to get pwe node in auth controller: %s', $e);
}
if (!isset($node['!i']['authController']) || $node['!i']['authController'] == 'none')
return new NoneAuthController($pwe);
if ($node['!i']['authController'] != NoneAuthController::getClassName()) {
PWELogger::info('Page requires auth: %s', $node['!i']['authController']);
}
return new $node['!i']['authController']($pwe);
}
public function getLevelsUpToAuthNode()
{
$levels = $this->PWE->getURL()->getParamsCount();
$node = $this->PWE->getNode();
while ($node && !isset($node['!a']['authController'])) {
$node = &$node['!p'];
$levels++;
}
return $levels;
}
}
| apache-2.0 |
ernestp/consulo | platform/projectModel-api/src/com/intellij/openapi/roots/OrderEntryWithTracking.java | 210 | package com.intellij.openapi.roots;
import org.jetbrains.annotations.Nullable;
/**
* @author VISTALL
* @since 22.08.14
*/
public interface OrderEntryWithTracking {
@Nullable
Object getEqualObject();
}
| apache-2.0 |
oriley-me/crate | crate-sample/src/main/java/me/oriley/cratesample/loaders/AssetLoader.java | 1281 | /*
* Copyright (C) 2016 Kane O'Riley
*
* 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 me.oriley.cratesample.loaders;
import android.support.annotation.NonNull;
import me.oriley.crate.Asset;
import me.oriley.crate.Crate;
import me.oriley.twiddle.TwiddleCache;
import me.oriley.twiddle.TwiddleLoader;
@SuppressWarnings("unused")
public abstract class AssetLoader<T, A extends Asset, P> extends TwiddleLoader<T, A, P> {
@NonNull
protected final Crate mCrate;
@NonNull
protected final TwiddleCache<A, P> mCache;
public AssetLoader(@NonNull Crate crate, long loadDelayMillis, int maxCacheSize, boolean lruCache) {
super(loadDelayMillis);
mCrate = crate;
mCache = new TwiddleCache<>(maxCacheSize, lruCache);
}
} | apache-2.0 |
NALSS/Dashboarding | Codeplex.Dashboarding/DecadeVuMeter.xaml.cs | 13536 | //-----------------------------------------------------------------------
// <copyright file="DecadeVuMeter.xaml.cs" company="David Black">
// Copyright 2008 David Black
//
// 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.
// </copyright>
//-----------------------------------------------------------------------
[module: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Scope = "type", Target = "Codeplex.Dashboarding.DecadeVuMeter", MessageId = "Vu", Justification = "Not a typo and not hungarian notation, it was called a Vu Meter")]
namespace Codeplex.Dashboarding
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
/// <summary>
/// Intended to look like a Vu meter from an old cassette deck this thermomter style
/// control displays data on blocks rather than as a continious sweep.
/// </summary>
public partial class DecadeVuMeter : Dashboard
{
#region public static fields
/// <summary>
/// The dependancy property for the Border Color property
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Color", Justification = "We support U.S. naming in a British project")]
public static readonly DependencyProperty BorderColorProperty =
DependencyProperty.Register("BorderColor", typeof(Color), typeof(DecadeVuMeter), new PropertyMetadata(new PropertyChangedCallback(ColorPropertyChanged)));
/// <summary>
/// The dependancy property for the LedOn attached property
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Color", Justification = "We support U.S. naming in a British project")]
public static readonly DependencyProperty LedOnColorProperty =
DependencyProperty.Register("LedOnColor", typeof(Color), typeof(DecadeVuMeter), new PropertyMetadata(new PropertyChangedCallback(ColorPropertyChanged)));
/// <summary>
/// THe dependancy property for the LedOffColor attached property
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Color", Justification = "We support U.S. naming in a British project")]
public static readonly DependencyProperty LedOffColorProperty =
DependencyProperty.Register("LedOffColor", typeof(Color), typeof(DecadeVuMeter), new PropertyMetadata(new PropertyChangedCallback(ColorPropertyChanged)));
#endregion
/// <summary>
/// Number of Leds that are in use
/// </summary>
private const int NumberOfLeds = 10;
/// <summary>
/// Initializes a new instance of the <see cref="DecadeVuMeter"/> class.
/// </summary>
public DecadeVuMeter()
{
InitializeComponent();
this.SetDefaultColours();
this.SetTimerDelay();
}
#region public properties
/// <summary>
/// Gets or sets the color of the border around an led (set to a darker contrasting color).
/// </summary>
/// <value>The color of the border.</value>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Color", Justification = "We support U.S. naming in a British project")]
public Color BorderColor
{
get { return (Color)GetValue(BorderColorProperty); }
set { SetValue(BorderColorProperty, value); }
}
/// <summary>
/// Gets or sets the color of the led when on.
/// </summary>
/// <value>The color of the led on.</value>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Color", Justification = "We support U.S. naming in a British project")]
public Color LedOnColor
{
get { return (Color)GetValue(LedOnColorProperty); }
set { SetValue(LedOnColorProperty, value); }
}
/// <summary>
/// Gets or sets the color of the led when turned off.
/// </summary>
/// <value>The color of the led off.</value>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Color", Justification = "We support U.S. naming in a British project")]
public Color LedOffColor
{
get { return (Color)GetValue(LedOffColorProperty); }
set { SetValue(LedOffColorProperty, value); }
}
#endregion
#region Protected properties
/// <summary>
/// Gets the resource root. This allow us to access the Storyboards in a Silverlight/WPf
/// neutral manner
/// </summary>
/// <value>The resource root.</value>
protected override FrameworkElement ResourceRoot
{
get { return LayoutRoot; }
}
#endregion
#region Private properties
/// <summary>
/// Gets or sets the led on brush, cached for efficiency (Cheers Inferno).
/// </summary>
/// <value>The led on brush.</value>
private SolidColorBrush LedOnBrush { get; set; }
/// <summary>
/// Gets or sets the led off brush, cached for efficiency (Cheers Inferno).
/// </summary>
/// <value>The led on brush.</value>
private SolidColorBrush LedOffBrush { get; set; }
/// <summary>
/// Gets or sets the led off brush, cached for efficiency (Cheers Inferno).
/// </summary>
/// <value>The led on brush.</value>
private SolidColorBrush MeterBorderBrush { get; set; }
#endregion
#region protected methods
/// <summary>
/// Display the control according the the current value. That means
/// lighting the necessary LEDS
/// </summary>
protected override void Animate()
{
_text.Text = Value.ToString();
for (int i = 0; i < NumberOfLeds; i++)
{
Storyboard sb = GetStoryboard("TimelineLed" + (NumberOfLeds - (i + 1))) as Storyboard;
if (sb != null)
{
double pos = ((i + 1) / (double)NumberOfLeds) * 100;
if ((NormalizedValue * 100) >= pos)
{
Start(sb);
}
else
{
sb.Stop();
sb.Seek(TimeSpan.Zero);
}
}
}
}
/// <summary>
/// Update your text colors to that of the TextColor dependancy property
/// </summary>
protected override void UpdateTextColor()
{
_text.Foreground = new SolidColorBrush(ValueTextColor);
}
/// <summary>
/// Set the visibiity of your text according to that of the TextVisibility property
/// </summary>
protected override void UpdateTextVisibility()
{
_text.Visibility = ValueTextVisibility;
}
/// <summary>
/// The format string for the value has changed
/// </summary>
protected override void UpdateTextFormat()
{
}
/// <summary>
/// Requires that the control hounours all appearance setting as specified in the
/// dependancy properties (at least the supported ones). No dependancy property handling
/// is performed until all dependancy properties are set and the control is loaded.
/// </summary>
protected override void ManifestChanges()
{
this.SetAllLedColors();
}
/// <summary>
/// Updates the font style for both face and value text.
/// </summary>
protected override void UpdateFontStyle()
{
}
#endregion
#region private methods
/// <summary>
/// BorderColor property has changed, deal with it
/// </summary>
/// <param name="dependancy">the dependancy object</param>
/// <param name="args">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
private static void ColorPropertyChanged(DependencyObject dependancy, DependencyPropertyChangedEventArgs args)
{
DecadeVuMeter instance = dependancy as DecadeVuMeter;
instance.LedColorChanged();
if (instance != null && instance.DashboardLoaded)
{
instance.SetAllLedColors();
}
}
/// <summary>
/// A Leds color changed, update the brushes used to render them.
/// </summary>
private void LedColorChanged()
{
if (this.LedOnBrush == null || (this.LedOnBrush != null && this.LedOnBrush.Color != this.LedOnColor))
{
this.LedOnBrush = new SolidColorBrush(this.LedOnColor);
Freeze(this.LedOnBrush);
}
if (this.LedOffBrush == null || (this.LedOffBrush != null && this.LedOffBrush.Color != this.LedOffColor))
{
this.LedOffBrush = new SolidColorBrush(this.LedOffColor);
Freeze(this.LedOffBrush);
}
if (this.MeterBorderBrush == null || (this.MeterBorderBrush != null && this.MeterBorderBrush.Color != this.BorderColor))
{
this.MeterBorderBrush = new SolidColorBrush(this.BorderColor);
Freeze(this.MeterBorderBrush);
}
}
/// <summary>
/// Sets all led colors.
/// </summary>
private void SetAllLedColors()
{
for (int i = 0; i < NumberOfLeds; i++)
{
this.SetLedColours(i);
}
}
/// <summary>
/// Sets the default colors into the attached properties
/// </summary>
private void SetDefaultColours()
{
this.LedOffColor = Color.FromArgb(0xFF, 0x26, 0x41, 0x08);
this.LedOnColor = Color.FromArgb(0xFF, 0x96, 0xfb, 0x23);
this.BorderColor = Color.FromArgb(0xFF, 0x27, 0x53, 0x18);
_text.Foreground = new SolidColorBrush(this.LedOnColor);
}
/// <summary>
/// In order to ripple the value up we claculate the time
/// to on for each block
/// </summary>
private void SetTimerDelay()
{
for (int i = 0; i < NumberOfLeds; i++)
{
this.SetLedColours(i);
double time = ((double)NumberOfLeds - i) / (double)NumberOfLeds;
int endMs = (int)(100 * time);
int startMs = (int)(100 * (time - (1 / (double)NumberOfLeds)));
SplineColorKeyFrame start = LayoutRoot.FindName("_startColour" + i) as SplineColorKeyFrame;
SplineColorKeyFrame end = LayoutRoot.FindName("_endColour" + i) as SplineColorKeyFrame;
if (end != null && start != null)
{
start.SetValue(SplineColorKeyFrame.KeyTimeProperty, KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, startMs)));
end.SetValue(SplineColorKeyFrame.KeyTimeProperty, KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, endMs)));
}
}
}
/// <summary>
/// Sets the color according to On or off of a single LED
/// </summary>
/// <param name="i">The index of he led to set the color for</param>
private void SetLedColours(int i)
{
SplineColorKeyFrame start = LayoutRoot.FindName("_startColour" + i) as SplineColorKeyFrame;
if (start != null)
{
start.Value = this.LedOffColor;
}
SplineColorKeyFrame end = LayoutRoot.FindName("_endColour" + i) as SplineColorKeyFrame;
if (end != null)
{
end.Value = this.LedOnColor;
}
Rectangle led = LayoutRoot.FindName("_led" + i) as Rectangle;
if (led != null)
{
led.Stroke = this.MeterBorderBrush;
led.Fill = this.LedOffBrush;
}
}
#endregion
}
}
| apache-2.0 |
juweiping/ocms | src/org/openuap/cms/survey/engine/support/DefaultSurveyAreaEngine.java | 6768 | /*
* Copyright 2002-2006 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 org.openuap.cms.survey.engine.support;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.openuap.cms.node.manager.NodeManager;
import org.openuap.cms.node.model.Node;
import org.openuap.cms.psn.manager.PsnManager;
import org.openuap.cms.survey.engine.SurveyAreaEngine;
import org.openuap.cms.survey.manager.QuestionManager;
import org.openuap.cms.survey.manager.SurveyAreaManager;
import org.openuap.cms.survey.manager.SurveyManager;
import org.openuap.cms.survey.model.QuestionPage;
import org.openuap.cms.survey.model.Survey;
import org.openuap.cms.survey.model.SurveyArea;
import org.openuap.cms.survey.model.SurveyRecord;
import org.openuap.runtime.util.ObjectLocator;
import org.openuap.tpl.engine.TemplateContext;
import org.openuap.tpl.engine.TemplateEngine;
import org.springframework.util.StringUtils;
/**
* <p>
* 缺省调查问卷内容生成引擎
* </p>
*
* <p>
* $Id: DefaultSurveyAreaEngine.java 4017 2011-03-13 13:55:50Z orangeforjava $
* </p>
*
* @author Joseph
* @version 1.0
*/
public class DefaultSurveyAreaEngine implements SurveyAreaEngine {
private SurveyAreaManager surveyAreaManager;
private SurveyManager surveyManager;
protected QuestionManager questionManager;
private NodeManager nodeManager;
private PsnManager psnManager;
private TemplateEngine templateEngine;
public void setTemplateEngine(TemplateEngine templateEngine) {
this.templateEngine = templateEngine;
}
public void setPsnManager(PsnManager psnManager) {
this.psnManager = psnManager;
}
public void setSurveyAreaManager(SurveyAreaManager surveyAreaManager) {
this.surveyAreaManager = surveyAreaManager;
}
public void setSurveyManager(SurveyManager surveyManager) {
this.surveyManager = surveyManager;
}
public String getAreaContent(String areaId, String surveyRecordId,
String type) {
SurveyArea area = surveyAreaManager.getAreaById(new Long(areaId));
StringBuffer rs = new StringBuffer("");
if (area != null) {
Long nodeId = area.getNodeId();
// 获得发布结点
Long rid = new Long(surveyRecordId);
SurveyRecord surveyRecord = surveyManager
.getSurveyRecordById(new Long(rid));
if (surveyRecord != null) {
Long surveyId = surveyRecord.getSurveyId();
QuestionPage qp = questionManager.getQuestionPage(surveyId, 1L);
Survey survey = surveyManager.getSurveyById(surveyId);
List pages = questionManager.getPages(surveyId);
Node node = nodeManager.getNode(nodeId);
TemplateContext context = new TemplateContext();
if (area.getTplType().equals(TPL_TYPE_FILE)) {
context.setTplName(area.getTplPath());
} else {
context.setTplContent(area.getTplContent());
}
List errors = new ArrayList();
Map model = Collections.synchronizedMap(new HashMap());
//
// System.out.println("survey1="+survey);
model.put("survey", survey);
model.put("surveyRecord", surveyRecord);
model.put("questionPage", qp);
model.put("pageId", (1));
model.put("pages", pages);
model.put("sid", surveyId.toString());
model.put("rid", rid.toString());
//
model.put("node", node);
model.put("nodeId", nodeId);
if (type != null && type.equals("inline")) {
// 直接输出内容到页面中
model.put("__direct_out__", "yes");
} else {
// 输出SSI指令
File outFile = getDestSurveyAreaFile(area, node);
model.put("outFile", outFile);
}
context.setModel(model);
getTemplateEngine().renderTemplate(context, errors);
if (type != null && type.equals("inline")) {
String content = context.getTplContent();
rs.append(content);
} else {
String ssiPath = getAreaSSIPath(area, node);
rs.append(ssiPath);
}
if (errors.size() > 0) {
// 调试错误输出
for (Object o : errors) {
// System.out.println("error:" + o);
}
}
}
}
return rs.toString();
}
protected File getDestSurveyAreaFile(SurveyArea area, Node node) {
String selfPsn = area.getSelfPsn();
if (!StringUtils.hasText(selfPsn)) {
selfPsn = node.getContentPsn();
}
String fullPath = psnManager.getFullPath(selfPsn);
String publishFileName = area.getPublishFileName();
if (!StringUtils.hasText(publishFileName)) {
// 需要自动生成文件名
publishFileName = "survey_area_" + area.getId() + "-"
+ area.getLastModifiedDate() + ".html";
}
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
File destFile = new File(publishFileName);
return destFile;
}
public TemplateEngine getTemplateEngine() {
if (templateEngine == null) {
templateEngine = (TemplateEngine) ObjectLocator.lookup(
"templateEngine", "org.openuap.tpl.engine");
}
return templateEngine;
}
public String getAreaSSIPath(SurveyArea area, Node node) {
if (area != null) {
String path = null;
String psnUrl = area.getSelfPsnUrl();
//
String fileName = area.getPublishFileName();
String pattern = "(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)*(:[a-zA-Z0-9]*)?([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?";
String psnUrlInfo = psnManager.getPsnUrlInfo(psnUrl);
Pattern p = Pattern.compile(pattern);
// System.out.println("psnUrlInfo=" + psnUrlInfo);
Matcher m = p.matcher(psnUrlInfo);
boolean found = m.find();
if (found) {
path = m.group(4);
// System.out.println("path="+path);
//
}
if (path == null) {
path = "";
}
path = "/" + path + "/" + fileName;
path = path.replaceAll("\\/\\/", "/");
//
return path;
}
return "";
}
public void setQuestionManager(QuestionManager questionManager) {
this.questionManager = questionManager;
}
public void setNodeManager(NodeManager nodeManager) {
this.nodeManager = nodeManager;
}
}
| apache-2.0 |
erik-wramner/JmsTools | AqJmsProducer/src/main/java/name/wramner/jmstools/producer/AqJmsProducer.java | 5110 | /*
* Copyright 2016 Erik Wramner.
*
* 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 name.wramner.jmstools.producer;
import javax.jms.*;
import org.kohsuke.args4j.Option;
import name.wramner.jmstools.aq.AqJmsUtils;
import name.wramner.jmstools.aq.AqObjectMessageAdapter;
import name.wramner.jmstools.counter.Counter;
import name.wramner.jmstools.messages.ObjectMessageAdapter;
import name.wramner.jmstools.producer.AqJmsProducer.AqProducerConfiguration;
/**
* Command line JMS AQ message producer intended for benchmarks and other tests.
*
* @author Erik Wramner
*/
public class AqJmsProducer extends JmsProducer<AqProducerConfiguration> {
/**
* Program entry point.
*
* @param args Command line.
* @see AqProducerConfiguration
*/
public static void main(String[] args) {
new AqJmsProducer().run(args);
}
/**
* Create configuration specific to the AQ client.
*
* @return configuration instance.
* @see name.wramner.jmstools.producer.JmsProducer#createConfiguration()
*/
@Override
protected AqProducerConfiguration createConfiguration() {
return new AqProducerConfiguration();
}
/**
* AQ producer configuration. It extends the basic JMS producer configuration with AQ-specific settings. Primarily
* that means the JDBC URL, user and password needed in order to connect to the AQ database. In addition it is
* possible to configure a flow controller that polls the queue depth in the database and pauses/resumes the
* producer threads in order to avoid overloading the consumers. For long-running tests where it is difficult to
* predict how many consumer and producer threads that are needed this can be very useful.
*
* @author Erik Wramner
*/
public static class AqProducerConfiguration extends JmsProducerConfiguration {
@Option(name = "-url", aliases = { "--aq-jdbc-url" }, usage = "JDBC URL for AQ database connection", required = true)
private String _aqJdbcUrl;
@Option(name = "-user", aliases = { "--aq-jdbc-user" }, usage = "JDBC user for AQ database connection", required = true)
private String _aqJdbcUser;
@Option(name = "-pw", aliases = { "--aq-jdbc-password" }, usage = "JDBC password for AQ database connection", required = true)
private String _aqJdbcPassword;
@Option(name = "-pause", aliases = { "--flow-control-pause-at" }, usage = "Pause load at given backlog (approximate)")
private Integer _flowControlPauseAtBacklog;
@Option(name = "-resume", aliases = { "--flow-control-resume-at" }, usage = "Resume load at given backlog (approximate)", depends = { "-pause" })
private int _flowControlResumeAtBacklog = 0;
@Option(name = "-flowint", aliases = { "--flow-control-check-interval-seconds" }, usage = "Time between flow control checks")
private int _flowControlCheckIntervalSeconds = 20;
@Override
public Counter createMessageCounter() {
Counter counter = super.createMessageCounter();
if (_flowControlPauseAtBacklog != null) {
return new FlowControllingCounter(counter, new AqFlowController(_aqJdbcUrl, _aqJdbcUser,
_aqJdbcPassword, _flowControlPauseAtBacklog.intValue(), _flowControlResumeAtBacklog,
getDestinationName(), _flowControlCheckIntervalSeconds));
} else {
return counter;
}
}
@Override
public DelayedDeliveryAdapter createDelayedDeliveryAdapter() {
return new DelayedDeliveryAdapter() {
@Override
public void setDelayProperty(Message msg, int seconds) throws JMSException {
msg.setIntProperty("JMS_OracleDelay", seconds);
}
};
}
@Override
public ConnectionFactory createConnectionFactory() throws JMSException {
return AqJmsUtils.createConnectionFactory(_aqJdbcUrl, _aqJdbcUser, _aqJdbcPassword);
}
@Override
public XAConnectionFactory createXAConnectionFactory() throws JMSException {
return AqJmsUtils.createXAConnectionFactory(_aqJdbcUrl, _aqJdbcUser, _aqJdbcPassword);
}
@Override
public ObjectMessageAdapter getObjectMessageAdapter() {
return new AqObjectMessageAdapter();
}
}
}
| apache-2.0 |
aspnet/AspNetCore | src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/RazorEngineBuilderExtensions.cs | 2828 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.Language.IntegrationTests;
using Microsoft.AspNetCore.Razor.Language.Intermediate;
namespace Microsoft.AspNetCore.Razor.Language
{
[Obsolete("This class is obsolete and will be removed in a future version.")]
public static class RazorEngineBuilderExtensions
{
public static IRazorEngineBuilder AddTagHelpers(this IRazorEngineBuilder builder, params TagHelperDescriptor[] tagHelpers)
{
return AddTagHelpers(builder, (IEnumerable<TagHelperDescriptor>)tagHelpers);
}
public static IRazorEngineBuilder AddTagHelpers(this IRazorEngineBuilder builder, IEnumerable<TagHelperDescriptor> tagHelpers)
{
var feature = (TestTagHelperFeature)builder.Features.OfType<ITagHelperFeature>().FirstOrDefault();
if (feature == null)
{
feature = new TestTagHelperFeature();
builder.Features.Add(feature);
}
feature.TagHelpers.AddRange(tagHelpers);
return builder;
}
public static IRazorEngineBuilder ConfigureDocumentClassifier(this IRazorEngineBuilder builder)
{
var feature = builder.Features.OfType<DefaultDocumentClassifierPassFeature>().FirstOrDefault();
if (feature == null)
{
feature = new DefaultDocumentClassifierPassFeature();
builder.Features.Add(feature);
}
feature.ConfigureNamespace.Clear();
feature.ConfigureClass.Clear();
feature.ConfigureMethod.Clear();
feature.ConfigureNamespace.Add((RazorCodeDocument codeDocument, NamespaceDeclarationIntermediateNode node) =>
{
node.Content = "Microsoft.AspNetCore.Razor.Language.IntegrationTests.TestFiles";
});
feature.ConfigureClass.Add((RazorCodeDocument codeDocument, ClassDeclarationIntermediateNode node) =>
{
node.ClassName = IntegrationTestBase.FileName.Replace('/', '_');
node.Modifiers.Clear();
node.Modifiers.Add("public");
});
feature.ConfigureMethod.Add((RazorCodeDocument codeDocument, MethodDeclarationIntermediateNode node) =>
{
node.Modifiers.Clear();
node.Modifiers.Add("public");
node.Modifiers.Add("async");
node.MethodName = "ExecuteAsync";
node.ReturnType = typeof(Task).FullName;
});
return builder;
}
}
}
| apache-2.0 |
fellyvon/wasindoor | wasservice/src/com/waspring/wasservice/net/busii/MutiLoginHandler.java | 1758 | package com.waspring.wasservice.net.busii;
import java.math.BigInteger;
import java.sql.ResultSet;
import com.aiyc.framework.annotation.Requestable;
import com.aiyc.server.standalone.json.GsonFactory;
import com.aiyc.server.standalone.net.IHandler;
import com.aiyc.server.standalone.net.Response;
import com.aiyc.server.standalone.net.Response.Status;
import com.google.gson.JsonElement;
import com.waspring.wasservice.net.dao.LoginDao;
import com.waspring.wasservice.net.model.LoginRepMessage;
import com.waspring.wasservice.net.model.LoginReqMessage;
/**
* ¶à·½µÇ¼
*
* @author felly
*
*/
@Requestable(serverName = "MUTI_LOGIN_REQ")
public class MutiLoginHandler implements IHandler {
public static final String STATUS_LINK = "1";
public static final String STATUS_UNLINK = "0";
public static String md5(String userPass) throws Exception {
java.security.MessageDigest md5 = java.security.MessageDigest
.getInstance("MD5");
md5.update(userPass.getBytes());
byte b[] = md5.digest();
return new BigInteger(b).toString(16);
}
private LoginDao dao = new LoginDao();
public Response handle(JsonElement data) throws Exception {
Response res;
LoginReqMessage loc = GsonFactory.getGsonInstance().fromJson(data,
LoginReqMessage.class);
String clientNo = "";
ResultSet rs = dao.queryUserByOpenID(loc.MESSAGE.OPEN_ID);
LoginRepMessage rm = new LoginRepMessage();
if (rs.next()) {
clientNo = rs.getString("user_id");
rm.STATUS = STATUS_LINK;
} else {
rm.STATUS = STATUS_UNLINK;
}
rm.CLIENTNO = clientNo;
rm.RTN_FLAG = "1";
rm.RTN_MSG = "²Ù×÷³É¹¦£¡";
res = new Response(Status.ok, "²Ù×÷³É¹¦£¡", rm.toJson());
return res;
}
}
| apache-2.0 |
mikemccand/lucene-c-boost | src/c/org/apache/lucene/search/BooleanQueryShouldMustNot.cpp | 11795 | /*
* 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.
*/
#include <math.h>
#include <stdio.h>
#include "common.h"
static void
orMustNotChunk(PostingsState *sub,
int endDoc,
int *docIDs,
unsigned char *skips) {
int nextDocID = sub->nextDocID;
unsigned int *docDeltas = sub->docDeltas;
unsigned int *freqs = sub->freqs;
int blockLastRead = sub->docFreqBlockLastRead;
int blockEnd = sub->docFreqBlockEnd;
while (nextDocID < endDoc) {
//printf(" docID=%d\n", nextDocID);
int slot = nextDocID & MASK;
docIDs[slot] = nextDocID;
skips[slot] = 1;
// Inlined nextDoc:
if (blockLastRead == blockEnd) {
if (sub->docsLeft == 0) {
nextDocID = NO_MORE_DOCS;
break;
} else {
nextDocFreqBlock(sub);
blockLastRead = -1;
blockEnd = sub->docFreqBlockEnd;
}
}
nextDocID += docDeltas[++blockLastRead];
}
sub->nextDocID = nextDocID;
sub->docFreqBlockLastRead = blockLastRead;
}
static int
orChunkDeletesWithSkip(PostingsState *sub,
double *tsCache,
float termWeight,
int endDoc,
unsigned int *filled,
int numFilled,
int *docIDs,
float *scores,
unsigned int *coords,
unsigned char *liveDocBytes,
unsigned char *skips) {
int nextDocID = sub->nextDocID;
unsigned int *docDeltas = sub->docDeltas;
unsigned int *freqs = sub->freqs;
int blockLastRead = sub->docFreqBlockLastRead;
int blockEnd = sub->docFreqBlockEnd;
if (scores == 0) {
//printf("term=%d nextDoc=%d\n", i, sub->nextDocID);
while (nextDocID < endDoc) {
//printf(" docID=%d\n", nextDocID);
if (isSet(liveDocBytes, nextDocID)) {
int slot = nextDocID & MASK;
if (docIDs[slot] != nextDocID) {
docIDs[slot] = nextDocID;
skips[slot] = 0;
filled[numFilled++] = slot;
}
}
// Inlined nextDoc:
if (blockLastRead == blockEnd) {
if (sub->docsLeft == 0) {
nextDocID = NO_MORE_DOCS;
break;
} else {
nextDocFreqBlock(sub);
blockLastRead = -1;
blockEnd = sub->docFreqBlockEnd;
}
}
nextDocID += docDeltas[++blockLastRead];
}
} else {
//printf("term=%d nextDoc=%d\n", i, sub->nextDocID);
while (nextDocID < endDoc) {
//printf(" docID=%d\n", nextDocID);
if (isSet(liveDocBytes, nextDocID)) {
int slot = nextDocID & MASK;
if (docIDs[slot] != nextDocID || skips[slot] == 0) {
int freq = freqs[blockLastRead];
double score;
if (freq < TERM_SCORES_CACHE_SIZE) {
score = tsCache[freq];
} else {
score = sqrt(freq) * termWeight;
}
if (docIDs[slot] != nextDocID) {
docIDs[slot] = nextDocID;
scores[slot] = score;
coords[slot] = 1;
skips[slot] = 0;
filled[numFilled++] = slot;
} else {
scores[slot] += score;
coords[slot]++;
}
}
}
// Inlined nextDoc:
if (blockLastRead == blockEnd) {
if (sub->docsLeft == 0) {
nextDocID = NO_MORE_DOCS;
break;
} else {
nextDocFreqBlock(sub);
blockLastRead = -1;
blockEnd = sub->docFreqBlockEnd;
}
}
nextDocID += docDeltas[++blockLastRead];
}
}
sub->nextDocID = nextDocID;
sub->docFreqBlockLastRead = blockLastRead;
return numFilled;
}
// Like orChunk, but is "aware" of skip (from previous
// MUST_NOT clauses):
static int
orChunkWithSkip(PostingsState *sub,
double *tsCache,
float termWeight,
int endDoc,
unsigned int *filled,
int numFilled,
int *docIDs,
float *scores,
unsigned int *coords,
unsigned char *skips) {
//printf("orChunkWithSkip\n");
int nextDocID = sub->nextDocID;
unsigned int *docDeltas = sub->docDeltas;
unsigned int *freqs = sub->freqs;
int blockLastRead = sub->docFreqBlockLastRead;
int blockEnd = sub->docFreqBlockEnd;
if (scores == 0) {
while (nextDocID < endDoc) {
//printf(" or: docID=%d\n", nextDocID);
int slot = nextDocID & MASK;
if (docIDs[slot] != nextDocID) {
docIDs[slot] = nextDocID;
skips[slot] = 0;
filled[numFilled++] = slot;
}
// Inlined nextDoc:
if (blockLastRead == blockEnd) {
if (sub->docsLeft == 0) {
nextDocID = NO_MORE_DOCS;
break;
} else {
nextDocFreqBlock(sub);
blockLastRead = -1;
blockEnd = sub->docFreqBlockEnd;
}
}
nextDocID += docDeltas[++blockLastRead];
}
} else {
//printf("term=%d nextDoc=%d\n", i, sub->nextDocID);
while (nextDocID < endDoc) {
//printf(" or: docID=%d freq=%d\n", nextDocID, freqs[blockLastRead]);fflush(stdout);
int slot = nextDocID & MASK;
if (docIDs[slot] != nextDocID || skips[slot] == 0) {
int freq = freqs[blockLastRead];
double score;
if (freq < TERM_SCORES_CACHE_SIZE) {
score = tsCache[freq];
} else {
score = sqrt(freq) * termWeight;
}
//printf(" score=%g\n", score);fflush(stdout);
if (docIDs[slot] != nextDocID) {
docIDs[slot] = nextDocID;
scores[slot] = score;
coords[slot] = 1;
skips[slot] = 0;
filled[numFilled++] = slot;
} else {
scores[slot] += score;
coords[slot]++;
}
}
// Inlined nextDoc:
if (blockLastRead == blockEnd) {
if (sub->docsLeft == 0) {
nextDocID = NO_MORE_DOCS;
break;
} else {
nextDocFreqBlock(sub);
blockLastRead = -1;
blockEnd = sub->docFreqBlockEnd;
}
}
nextDocID += docDeltas[++blockLastRead];
}
}
sub->nextDocID = nextDocID;
sub->docFreqBlockLastRead = blockLastRead;
//printf("orChunkWithSkip done\n");
return numFilled;
}
int booleanQueryShouldMustNot(PostingsState* subs,
unsigned char *liveDocsBytes,
double **termScoreCache,
float *termWeights,
int maxDoc,
int topN,
int numScorers,
int docBase,
int numMustNot,
unsigned int *filled,
int *docIDs,
float *scores,
unsigned int *coords,
float *topScores,
int *topDocIDs,
float *coordFactors,
float *normTable,
unsigned char *norms,
unsigned char *skips,
PostingsState *dsSubs,
unsigned int *dsCounts,
unsigned int *dsMissingDims,
unsigned int dsNumDims,
unsigned int *dsTotalHits,
unsigned int *dsTermsPerDim,
unsigned long *dsHitBits,
unsigned long **dsNearMissBits)
{
int docUpto = 0;
int hitCount = 0;
//printf("smn\n");fflush(stdout);
while (docUpto < maxDoc) {
int endDoc = docUpto + CHUNK;
//printf("cycle endDoc=%d dels=%lx\n", endDoc, liveDocBytes);fflush(stdout);
int numFilled = 0;
for(int i=0;i<numMustNot;i++) {
orMustNotChunk(&subs[i], endDoc, docIDs, skips);
}
for(int i=numMustNot;i<numScorers;i++) {
if (liveDocsBytes != 0) {
numFilled = orChunkDeletesWithSkip(&subs[i], termScoreCache[i], termWeights[i], endDoc, filled, numFilled, docIDs, scores, coords,
liveDocsBytes, skips);
} else {
numFilled = orChunkWithSkip(&subs[i], termScoreCache[i], termWeights[i], endDoc, filled, numFilled, docIDs, scores, coords, skips);
}
}
int docChunkBase = docBase + docUpto;
if (dsNumDims > 0) {
hitCount += drillSidewaysCollect(topN,
docBase,
topDocIDs,
topScores,
normTable,
norms,
coordFactors,
coords,
filled,
numFilled,
docIDs,
scores,
dsCounts,
dsMissingDims,
docUpto,
dsSubs,
dsNumDims,
dsTermsPerDim,
dsTotalHits,
dsHitBits,
dsNearMissBits);
} else if (topScores == 0) {
hitCount += numFilled;
for(int i=0;i<numFilled;i++) {
int slot = filled[i];
if (skips[slot]) {
continue;
}
int docID = docChunkBase + slot;
// TODO: we can stop collecting, and tracking filled,
// after chunk once queue is full
if (docID < topDocIDs[1]) {
// Hit is competitive
topDocIDs[1] = docID;
downHeapNoScores(topN, topDocIDs);
//printf(" **\n");fflush(stdout);
}
}
} else {
hitCount += numFilled;
// Collect:
//printf("collect:\n");
for(int i=0;i<numFilled;i++) {
int slot = filled[i];
if (skips[slot]) {
continue;
}
float score = scores[slot] * coordFactors[coords[slot]] * normTable[norms[docIDs[slot]]];
int docID = docChunkBase + slot;
//printf(" docBase=%d doc=%d score=%.5f coord=%d cf=%.5f\n",
//docBase, docID, score, coords[slot], coordFactors[coords[slot]]);
if (score > topScores[1] || (score == topScores[1] && docID < topDocIDs[1])) {
// Hit is competitive
topDocIDs[1] = docID;
topScores[1] = score;
downHeap(topN, topDocIDs, topScores);
//printf(" **\n");fflush(stdout);
}
}
}
docUpto += CHUNK;
}
return hitCount;
}
| apache-2.0 |
blademainer/common_utils | common_helper/src/main/java/com/xiongyingqi/util/xml/package-info.java | 184 |
/**
*
* Miscellaneous utility classes for XML parsing and transformation,
* such as error handlers that log warnings via Commons Logging.
*
*/
package com.xiongyingqi.util.xml;
| apache-2.0 |
blackducksoftware/hub-detect | hub-detect/src/main/groovy/com/blackducksoftware/integration/hub/detect/workflow/project/decisions/ArbitraryNameVersionDecision.java | 2461 | /**
* hub-detect
*
* Copyright (C) 2019 Black Duck Software, Inc.
* http://www.blackducksoftware.com/
*
* 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 com.blackducksoftware.integration.hub.detect.workflow.project.decisions;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import com.blackducksoftware.integration.hub.detect.workflow.project.DetectorProjectInfo;
import com.synopsys.integration.util.NameVersion;
public class ArbitraryNameVersionDecision extends NameVersionDecision {
private final DetectorProjectInfo chosenDetector;
private final List<DetectorProjectInfo> otherDetectors;
public ArbitraryNameVersionDecision(final DetectorProjectInfo chosenDetector, final List<DetectorProjectInfo> otherDetectors) {
this.chosenDetector = chosenDetector;
this.otherDetectors = otherDetectors;
}
@Override
public Optional<NameVersion> getChosenNameVersion() {
return Optional.of(chosenDetector.getNameVersion());
}
@Override
public void printDescription(final Logger logger) {
logger.info("Multiple unique detector types were found.");
logger.info("The following project names were found: ");
for (final DetectorProjectInfo projectNamePossibility : otherDetectors) {
logger.info(projectNamePossibility.getDetectorType().toString() + ": " + projectNamePossibility.getNameVersion().getName());
}
logger.info("Chose to use " + chosenDetector.getDetectorType() + " at depth " + chosenDetector.getDepth() + " for project name and version.");
logger.info("To specify a different detector type you can specify the project type override.");
}
}
| apache-2.0 |
commitd/krill | src/main/java/io/committed/krill/extraction/pdfbox/physical/Word.java | 1547 | package io.committed.krill.extraction.pdfbox.physical;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Represents a word in a {@link Line} of text. */
public class Word extends PositionedStyledContainer<Text> implements Baselined {
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(Word.class);
/** The baseline. */
private final float baseline;
/**
* Create a new {@link Word} from the given ordered list of {@link Text} content.
*
* @param content the {@link Text} content for the word.
*/
public Word(List<Text> content) {
super(content);
this.baseline = deriveBaseline();
}
/**
* Derive baseline.
*
* @return the float
*/
private float deriveBaseline() {
Iterator<Text> iterator = getContents().iterator();
float retval = 0;
if (iterator.hasNext()) {
retval = iterator.next().getBaseline();
}
while (iterator.hasNext()) {
float newCandidate = iterator.next().getBaseline();
if (Float.compare(newCandidate, retval) != 0) {
retval = Math.min(newCandidate, retval);
LOGGER.warn("Inconsistent baseline in word - using smallest value (this may be incorrect)");
}
}
return retval;
}
@Override
public float getBaseline() {
return baseline;
}
@Override
public String toString() {
return getContents().stream().map(Text::toString).collect(Collectors.joining());
}
}
| apache-2.0 |
orientechnologies/orientdb | tests/src/test/java/com/orientechnologies/orient/test/database/base/OrientMultiThreadTest.java | 1103 | /*
* Copyright 2010-2016 OrientDB LTD (http://orientdb.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.test.database.base;
import com.orientechnologies.common.test.SpeedTestMultiThreads;
import com.orientechnologies.common.test.SpeedTestThread;
import org.testng.annotations.Test;
@Test(enabled = false)
public abstract class OrientMultiThreadTest extends SpeedTestMultiThreads {
public OrientMultiThreadTest(
int iCycles, int iThreads, Class<? extends SpeedTestThread> iThreadClass) {
super(iCycles, iThreads, iThreadClass);
}
}
| apache-2.0 |
olw/cdn | milton-api/src/main/java/io/milton/annotations/ModifiedDate.java | 1083 | /*
* Copyright 2013 McEvoy Software Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.milton.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks the method which returns the date the resource was modified
*
* @author brad
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ModifiedDate {
}
| apache-2.0 |
pebble2015/cpoi | ext/stub/java/util/TreeMap_DescendingKeySpliterator-stub.cpp | 2591 | // Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#include <java/util/TreeMap_DescendingKeySpliterator.hpp>
extern void unimplemented_(const char16_t* name);
java::util::TreeMap_DescendingKeySpliterator::TreeMap_DescendingKeySpliterator(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
java::util::TreeMap_DescendingKeySpliterator::TreeMap_DescendingKeySpliterator(TreeMap* tree, TreeMap_Entry* origin, TreeMap_Entry* fence, int32_t side, int32_t est, int32_t expectedModCount)
: TreeMap_DescendingKeySpliterator(*static_cast< ::default_init_tag* >(0))
{
ctor(tree, origin, fence, side, est, expectedModCount);
}
void ::java::util::TreeMap_DescendingKeySpliterator::ctor(TreeMap* tree, TreeMap_Entry* origin, TreeMap_Entry* fence, int32_t side, int32_t est, int32_t expectedModCount)
{ /* stub */
/* super::ctor(); */
unimplemented_(u"void ::java::util::TreeMap_DescendingKeySpliterator::ctor(TreeMap* tree, TreeMap_Entry* origin, TreeMap_Entry* fence, int32_t side, int32_t est, int32_t expectedModCount)");
}
int32_t java::util::TreeMap_DescendingKeySpliterator::characteristics()
{ /* stub */
unimplemented_(u"int32_t java::util::TreeMap_DescendingKeySpliterator::characteristics()");
return 0;
}
void java::util::TreeMap_DescendingKeySpliterator::forEachRemaining(::java::util::function::Consumer* action)
{ /* stub */
unimplemented_(u"void java::util::TreeMap_DescendingKeySpliterator::forEachRemaining(::java::util::function::Consumer* action)");
}
bool java::util::TreeMap_DescendingKeySpliterator::tryAdvance(::java::util::function::Consumer* action)
{ /* stub */
unimplemented_(u"bool java::util::TreeMap_DescendingKeySpliterator::tryAdvance(::java::util::function::Consumer* action)");
return 0;
}
java::util::TreeMap_DescendingKeySpliterator* java::util::TreeMap_DescendingKeySpliterator::trySplit()
{ /* stub */
unimplemented_(u"java::util::TreeMap_DescendingKeySpliterator* java::util::TreeMap_DescendingKeySpliterator::trySplit()");
return 0;
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* java::util::TreeMap_DescendingKeySpliterator::class_()
{
static ::java::lang::Class* c = ::class_(u"java.util.TreeMap.DescendingKeySpliterator", 42);
return c;
}
int64_t java::util::TreeMap_DescendingKeySpliterator::estimateSize()
{
return TreeMap_TreeMapSpliterator::estimateSize();
}
java::lang::Class* java::util::TreeMap_DescendingKeySpliterator::getClass0()
{
return class_();
}
| apache-2.0 |
Roommetro/Friendly.WPFStandardControls | Project/Test/ButtonSearchTest.cs | 10814 | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Codeer.Friendly.Dynamic;
using Codeer.Friendly.Windows;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using RM.Friendly.WPFStandardControls;
using Codeer.Friendly.Windows.Grasp;
using Codeer.Friendly;
using Codeer.Friendly.Windows.NativeStandardControls;
using System.Linq;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Collections.Generic;
namespace Test
{
[TestClass]
public class ButtonSearchTest
{
WindowsAppFriend _app;
dynamic _ctrl;
[TestInitialize]
public void TestInitialize()
{
_app = new WindowsAppFriend(Process.Start("Target.exe"));
WindowsAppExpander.LoadAssembly(_app, GetType().Assembly);
WindowsAppExpander.LoadAssembly(_app, typeof(TestClassAttribute).Assembly);
dynamic main = _app.Type<Application>().Current.MainWindow;
_ctrl = _app.Type(GetType()).Init(main._grid);
}
static ButtonSearchTestControl Init(Grid grid)
{
ButtonSearchTestControl ctrl = new ButtonSearchTestControl();
grid.Children.Add(ctrl);
return ctrl;
}
[TestCleanup]
public void TestCleanup()
{
Process.GetProcessById(_app.ProcessId).CloseMainWindow();
}
[TestMethod]
public void TestByCommand()
{
var buttons = TreeUtility.LogicalTree((AppVar)_ctrl).ByType<Button>();
AppVar button2 = ButtonSearcher.ByCommand(buttons, ApplicationCommands.Close).Single();
Assert.AreEqual(button2, _ctrl._button2);
button2 = ButtonSearcher.ByCommand(buttons, typeof(ApplicationCommands).FullName, "Close").Single();
Assert.AreEqual(button2, _ctrl._button2);
}
[TestMethod]
public void TestByCommandExtensions()
{
var buttons = ((AppVar)_ctrl).LogicalTree().ByType<Button>();
AppVar button2 = buttons.ByCommand(ApplicationCommands.Close).Single();
Assert.AreEqual(button2, _ctrl._button2);
button2 = buttons.ByCommand(typeof(ApplicationCommands).FullName, "Close").Single();
Assert.AreEqual(button2, _ctrl._button2);
}
[TestMethod]
public void TestByCommandInTarget()
{
_app.Type(GetType()).TestByCommandInTarget(_ctrl, _ctrl._button2);
}
static void TestByCommandInTarget(ButtonSearchTestControl ctrl, Button button2Expected)
{
var buttons = TreeUtilityInTarget.LogicalTree(ctrl).ByType<Button>();
var button2 = ButtonSearcherInTarget.ByCommand(buttons, ApplicationCommands.Close).Single();
Assert.AreEqual(button2, button2Expected);
}
[TestMethod]
public void TestByCommandInTargetExtensions()
{
_app.Type(GetType()).TestByCommandInTargetExtensions(_ctrl, _ctrl._button2);
}
static void TestByCommandInTargetExtensions(ButtonSearchTestControl ctrl, Button button2Expected)
{
var buttons = ctrl.LogicalTree().ByType<Button>();
var button2 = buttons.ByCommand(ApplicationCommands.Close).Single();
Assert.AreEqual(button2, button2Expected);
}
[TestMethod]
public void TestByCommandParameter()
{
var buttons = TreeUtility.LogicalTree((AppVar)_ctrl).ByType<Button>();
AppVar button1 = ButtonSearcher.ByCommandParameter(buttons, "button1").Single();
Assert.AreEqual(button1, _ctrl._button1);
button1 = ButtonSearcher.ByCommandParameter(buttons, new ExplicitAppVar(_app.Copy("button1"))).Single();
Assert.AreEqual(button1, _ctrl._button1);
}
[TestMethod]
public void TestByCommandParameterExtensions()
{
var buttons = ((AppVar)_ctrl).LogicalTree().ByType<Button>();
AppVar button1 = buttons.ByCommandParameter("button1").Single();
Assert.AreEqual(button1, _ctrl._button1);
button1 = buttons.ByCommandParameter(new ExplicitAppVar(_app.Copy("button1"))).Single();
Assert.AreEqual(button1, _ctrl._button1);
}
[TestMethod]
public void TestByCommandParameterInTarget()
{
_app.Type(GetType()).TestByCommandParameterInTarget(_ctrl, _ctrl._button3);
}
static void TestByCommandParameterInTarget(ButtonSearchTestControl ctrl, Button button3Expected)
{
var buttons = TreeUtilityInTarget.LogicalTree(ctrl).ByType<Button>();
var button3 = ButtonSearcherInTarget.ByCommandParameter(buttons, "button3").Single();
Assert.AreEqual(button3, button3Expected);
}
[TestMethod]
public void TestByCommandParameterInTargetExtensions()
{
_app.Type(GetType()).TestByCommandParameterInTargetExtensions(_ctrl, _ctrl._button3);
}
static void TestByCommandParameterInTargetExtensions(ButtonSearchTestControl ctrl, Button button3Expected)
{
var buttons = ctrl.LogicalTree().ByType<Button>();
var button3 = buttons.ByCommandParameter("button3").Single();
Assert.AreEqual(button3, button3Expected);
}
[TestMethod]
public void TestByCommandParameterEnum()
{
var buttons = TreeUtility.LogicalTree((AppVar)_ctrl).ByType<Button>();
AppVar button4 = ButtonSearcher.ByCommandParameter(buttons, CommandPrameterType.A).Single();
Assert.AreEqual(button4, _ctrl._button4);
button4 = ButtonSearcher.ByCommandParameter(buttons, new ExplicitAppVar(_app.Copy(CommandPrameterType.A))).Single();
Assert.AreEqual(button4, _ctrl._button4);
}
[TestMethod]
public void TestByCommandParameterEnumExtensions()
{
var buttons = ((AppVar)_ctrl).LogicalTree().ByType<Button>();
AppVar button4 = buttons.ByCommandParameter(CommandPrameterType.A).Single();
Assert.AreEqual(button4, _ctrl._button4);
button4 = buttons.ByCommandParameter(new ExplicitAppVar(_app.Copy(CommandPrameterType.A))).Single();
Assert.AreEqual(button4, _ctrl._button4);
}
[TestMethod]
public void TestByCommandParameterEnumInTarget()
{
_app.Type(GetType()).TestByCommandParameterEnumInTarget(_ctrl, _ctrl._button4);
}
static void TestByCommandParameterEnumInTarget(ButtonSearchTestControl ctrl, Button button4Expected)
{
var buttons = TreeUtilityInTarget.LogicalTree(ctrl).ByType<Button>();
var button4 = ButtonSearcherInTarget.ByCommandParameter(buttons, CommandPrameterType.A).Single();
Assert.AreEqual(button4, button4Expected);
}
[TestMethod]
public void TestByCommandParameterEnumInTargetExtensions()
{
_app.Type(GetType()).TestByCommandParameterEnumInTargetExtensions(_ctrl, _ctrl._button4);
}
static void TestByCommandParameterEnumInTargetExtensions(ButtonSearchTestControl ctrl, Button button4Expected)
{
var buttons = ctrl.LogicalTree().ByType<Button>();
var button4 = buttons.ByCommandParameter(CommandPrameterType.A).Single();
Assert.AreEqual(button4, button4Expected);
}
[TestMethod]
public void TestByCommandParameterText()
{
var buttons = TreeUtility.LogicalTree((AppVar)_ctrl).ByType<Button>();
AppVar button4 = ButtonSearcher.ByCommandParameterText(buttons, "A").Single();
Assert.AreEqual(button4, _ctrl._button4);
}
[TestMethod]
public void TestByCommandParameterTextExtensions()
{
var buttons = ((AppVar)_ctrl).LogicalTree().ByType<Button>();
AppVar button4 = buttons.ByCommandParameterText("A").Single();
Assert.AreEqual(button4, _ctrl._button4);
}
[TestMethod]
public void TestByCommandParameterTextInTarget()
{
_app.Type(GetType()).TestByCommandParameterTextInTarget(_ctrl, _ctrl._button4);
}
static void TestByCommandParameterTextInTarget(ButtonSearchTestControl ctrl, Button button4Expected)
{
var buttons = TreeUtilityInTarget.LogicalTree(ctrl).ByType<Button>();
var button4 = ButtonSearcherInTarget.ByCommandParameterText(buttons, "A").Single();
Assert.AreEqual(button4, button4Expected);
}
[TestMethod]
public void TestByCommandParameterTextInTargetExtensions()
{
_app.Type(GetType()).TestByCommandParameterTextInTargetExtensions(_ctrl, _ctrl._button4);
}
static void TestByCommandParameterTextInTargetExtensions(ButtonSearchTestControl ctrl, Button button4Expected)
{
var buttons = ctrl.LogicalTree().ByType<Button>();
var button4 = buttons.ByCommandParameterText("A").Single();
Assert.AreEqual(button4, button4Expected);
}
[TestMethod]
public void TestByIsCancel()
{
var buttons = TreeUtility.LogicalTree((AppVar)_ctrl).ByType<Button>();
AppVar button5 = ButtonSearcher.ByIsCancel(buttons).Single();
Assert.AreEqual(button5, _ctrl._button5);
}
[TestMethod]
public void TestByIsCancelExtensions()
{
var buttons = ((AppVar)_ctrl).LogicalTree().ByType<Button>();
AppVar button5 = buttons.ByIsCancel().Single();
Assert.AreEqual(button5, _ctrl._button5);
}
[TestMethod]
public void TestByIsCancelInTarget()
{
_app.Type(GetType()).TestByIsCancelInTarget(_ctrl, _ctrl._button5);
}
static void TestByIsCancelInTarget(ButtonSearchTestControl ctrl, Button button5Expected)
{
var buttons = TreeUtilityInTarget.LogicalTree(ctrl).ByType<Button>();
var button5 = ButtonSearcherInTarget.ByIsCancel(buttons).Single();
Assert.AreEqual(button5, button5Expected);
}
[TestMethod]
public void TestByIsCancelInTargetExtensions()
{
_app.Type(GetType()).TestByIsCancelInTargetExtensions(_ctrl, _ctrl._button5);
}
static void TestByIsCancelInTargetExtensions(ButtonSearchTestControl ctrl, Button button5Expected)
{
var buttons = ctrl.LogicalTree().ByType<Button>();
var button5 = buttons.ByIsCancel().Single();
Assert.AreEqual(button5, button5Expected);
}
}
}
| apache-2.0 |
cezarfx/zorba | swig/python/tests/test07.2.py | 2529 | # Copyright 2006-2011 The FLWOR Foundation.
#
# 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 sys
sys.path.insert(0, '@pythonPath@')
import zorba_api
def test(zorba):
xquery = zorba.compileQuery("<a>text-a1<b at1='att1' at2='{1+2}'>text-b1</b>text-a2</a>")
saxHandler = zorba_api.SAX2ContentHandlerProxy()
saxHandler.setStartDocumentHandler(startDocumentHandler);
saxHandler.setEndDocumentHandler(endDocumentHandler);
saxHandler.setStartElementHandler(startElementHandler);
saxHandler.setEndElementHandler(endElementHandler);
saxHandler.setCharactersHandler(charactersHandler);
saxHandler.setProcessingInstructionHandler(processingInstructionHandler);
saxHandler.setIgnorableWhitespaceHandler(ignorableWhitespaceHandler);
saxHandler.setStartPrefixMappingHandler(startPrefixMappingHandler);
saxHandler.setEndPrefixMappingHandler(endPrefixMappingHandler);
saxHandler.setSkippedEntityHandler(skippedEntityHandler);
xquery.executeSAX(saxHandler)
return
def startDocumentHandler():
print "Start Document"
return
def endDocumentHandler():
print "End Document"
return
def startElementHandler(URI, localName, QName, SAXAttributes):
print "Start Element - ", QName
return
def endElementHandler(URI, localName, QName):
print "End Element - ", QName
return
def charactersHandler(text):
print "Characters - ", text
return
def processingInstructionHandler(target, data):
print "Processing Instruction"
return
def ignorableWhitespaceHandler(text):
print "Ignorable Whitespace - ", text
return
def startPrefixMappingHandler(prefix, URI):
print "Start Prefix Mapping - ", prefix
return
def endPrefixMappingHandler(prefix):
print "End Prefix Mapping - ", prefix
return
def skippedEntityHandler(name):
print "Skipped Entity - ", name
return
store = zorba_api.InMemoryStore_getInstance()
zorba = zorba_api.Zorba_getInstance(store)
print "Running: XQuery execute - executeSAX"
test(zorba)
print "Success"
zorba.shutdown()
zorba_api.InMemoryStore_shutdown(store)
| apache-2.0 |
idnspro/IREST | siteadmin/includes/classes/class.Banner.php | 4705 | <?php
class Banner{
var $dbObj;
function Banner(){//class constructor
$this->dbObj = new DB();
$this->dbObj->fun_db_connect();
}
// Get Banner info array by id
function fun_getBannerInfo($banner_id){
$sql = "SELECT * FROM " . TABLE_BANNER . " WHERE banner_id='".$banner_id."'";
$rs = $this->dbObj->createRecordset($sql);
if($this->dbObj->getRecordCount($rs) > 0){
$arr = $this->dbObj->fetchAssoc($rs);
return $arr[0];
} else {
return false;
}
}
// Get Banners array order by id
function fun_getBannerArr($parameter = ''){
$sql = "SELECT A.* FROM " . TABLE_BANNER . " AS A";
if($parameter != ""){
$sql .= $parameter;
} else {
$sql .= " ORDER BY A.banner_id DESC";
}
return $rs = $this->dbObj->createRecordset($sql);
}
// Get Banners array order by id
function fun_getBannerArr4Home(){
$sql = "SELECT * FROM " . TABLE_BANNER . " WHERE banner_type ='1' ORDER BY banner_id";
$rs = $this->dbObj->createRecordset($sql);
if($this->dbObj->getRecordCount($rs) > 0){
return $arr = $this->dbObj->fetchAssoc($rs);
} else {
return false;
}
}
// Get Banner ifo array order by random
function fun_getBannerRandom($banner_type = ''){
$sql = "SELECT * FROM " . TABLE_BANNER . " ";
if($banner_type != "") {
$sql .= " WHERE banner_type ='".$banner_type."' ";
}
$sql .= " ORDER BY RAND() LIMIT 0, 1";
$rs = $this->dbObj->createRecordset($sql);
$arr = $this->dbObj->fetchAssoc($rs);
return $arr[0];
}
// Function for creating array of randam selected banner
function fun_getBannerByRand($banner_type = ''){
$sql = "SELECT * FROM " . TABLE_BANNER . " WHERE start_date <= CURRENT_DATE() AND end_date >= CURRENT_DATE() ";
if($banner_type != "") {
$sql .= " AND banner_type ='".$banner_type."' ";
}
$sql .= " ORDER BY RAND() LIMIT 0, 1";
$rs = $this->dbObj->createRecordset($sql);
$arr = $this->dbObj->fetchAssoc($rs);
return $arr[0];
}
// Function for add Banner
function fun_addBanner($banner_title, $banner_desc, $banner_img, $banner_link, $banner_type, $start_date, $end_date, $active) {
$cur_unixtime = time ();
if(isset($_SESSION['ses_admin_id']) && $_SESSION['ses_admin_id'] !=""){
$cur_user_id = $_SESSION['ses_admin_id'];
} else if(isset($_SESSION['ses_modarator_id']) && $_SESSION['ses_modarator_id'] !=""){
$cur_user_id = $_SESSION['ses_modarator_id'];
} else if(isset($_SESSION['ses_user_id']) && $_SESSION['ses_user_id'] !=""){
$cur_user_id = $_SESSION['ses_user_id'];
} else {
$cur_user_id = "";
}
$strInsQuery = "INSERT INTO " . TABLE_BANNER . "
(banner_id, banner_title, banner_desc, banner_img, banner_link, banner_type, start_date, end_date, created_on, created_by, updated_on, updated_by, active)
VALUES(null, '".fun_db_input($banner_title)."', '".fun_db_input($banner_desc)."', '".$banner_img."', '".$banner_link."', '".$banner_type."', '".$start_date."', '".$end_date."', '".$cur_unixtime."', '".$cur_user_id."', '".$cur_unixtime."', '".$cur_user_id."', '".$active."')";
$this->dbObj->fun_db_query($strInsQuery);
return $this->dbObj->getIdentity();
}
// Function for edit banner
function fun_editBanner($banner_id, $banner_title ='', $banner_desc ='', $banner_img ='', $banner_link ='', $banner_type ='', $start_date ='', $end_date ='', $active ='') {
if($banner_id == '') {
return false;
} else {
$cur_unixtime = time ();
if(isset($_SESSION['ses_admin_id']) && $_SESSION['ses_admin_id'] !=""){
$cur_user_id = $_SESSION['ses_admin_id'];
} else if(isset($_SESSION['ses_modarator_id']) && $_SESSION['ses_modarator_id'] !=""){
$cur_user_id = $_SESSION['ses_modarator_id'];
} else if(isset($_SESSION['ses_user_id']) && $_SESSION['ses_user_id'] !=""){
$cur_user_id = $_SESSION['ses_user_id'];
} else {
$cur_user_id = "";
}
$sqlUpdateQuery = "UPDATE " . TABLE_BANNER . " SET
banner_title = '".fun_db_input($banner_title)."',
banner_desc = '".fun_db_input($banner_desc)."',
banner_img = '".$banner_img."',
banner_link = '".$banner_link."',
banner_type = '".$banner_type."',
start_date = '".$start_date."',
end_date = '".$end_date."',
updated_on = '".$cur_unixtime."',
updated_by = '".$cur_user_id."',
active = '".$active."'
WHERE banner_id='".$banner_id."'";
$this->dbObj->mySqlSafeQuery($sqlUpdateQuery);
return true;
}
}
function fun_delBanner($banner_id){
$delSql = "DELETE FROM " . TABLE_BANNER . " WHERE banner_id='".$banner_id."'";
$this->dbObj->mySqlSafeQuery($delSql);
}
}
?> | apache-2.0 |
diogocezar/dctb-startistics | Api/vendor/davefx/phplot/phplottest/bars-stacked.php | 771 | <?php
# $Id$
# PHPlot test: single row stacked bars should look like regular bars?
require_once 'phplot.php';
$data = array(
array('Jan', 40), array('Feb', 90),
array('Mar', 50), array('Apr', 40),
array('May', 75), array('Jun', 45),
array('Jul', 40), array('Aug', 35),
array('Sep', 50), array('Oct', 45),
array('Nov', 35), array('Dec', 40),
);
$plot = new PHPlot(800, 600);
$plot->SetImageBorderType('plain');
$plot->SetPlotType('stackedbars');
$plot->SetDataType('text-data');
$plot->SetDataValues($data);
$plot->SetTitle("Single-dataset stackedbars\nCompare to unstacked");
$plot->SetShading(0);
$plot->SetXTickLabelPos('none');
$plot->SetXTickPos('none');
# Testing:
#$plot->group_frac_width = 1.0;
#$plot->bar_width_adjust=0.5;
$plot->DrawGraph();
| apache-2.0 |
rspieldenner/msl | core/src/main/javascript/entityauth/X509Store.js | 3145 | /**
* Copyright (c) 2012-2015 Netflix, Inc. 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.
*/
/**
* <p>The X.509 certificate store provides X.509 certificate validation against
* the stored trusted certificates and certificate chains.</p>
*/
var X509Store = util.Class.create({
init: function init() {
/**
* Map of subject names onto trusted X.509 certificates.
* @type {Object.<string,X509>}
*/
var x509certs = {};
// The properties.
var props = {
x509certs: { value: x509certs, writable: false, enumerable: false, configurable: false }
};
Object.defineProperties(this, props);
},
/**
* Adds an X.509 CA certificate to the list of trusted certificates.
*
* @param {X509|string} x509data X.509 certificate or PEM string.
*/
addCert: function addCert(x509data) {
var x509;
if (x509data instanceof X509) {
x509 = x509data;
} else if (typeof x509data === 'string') {
x509 = new X509();
x509.readCertPEM(x509data);
} else {
throw new TypeError('X.509 data must be an X509 instance or a PEM string.');
}
this.x509certs[x509.getSubjectString()] = x509;
},
/**
* Adds an ordered chain of X.509 CA certificates to the list of
* trusted certificates. The first certificate in the chain must be
* self-signed.
*
* @param {Array.<X509|string>} x509data X.509 certificates or PEM
* strings.
*/
addChain: function addChain(x509data) {
if (!(x509data instanceof Array))
throw new TypeError('X.509 data must be an array of X509 instances or PEM strings.');
x509data.forEach(function(certData) {
this.addCert(certData);
}, this);
},
/**
* Verify an X.509 certificate against the trusted CA certificates.
*
* @param {X509} cert X.509 certificate to verify.
* @return {boolean} true if the certificate is trusted.
*/
verify: function verify(cert) {
if (!(cert instanceof X509))
throw new TypeError('Certificate must be an X509 instance.');
var issuer = cert.getIssuerString();
if (!issuer)
return false;
var issuerCert = this.x509certs[issuer];
if (!issuerCert)
return false;
var issuerPublicKey = issuerCert.subjectPublicKeyRSA;
// FIXME verify the certificate somehow.
// issuerPublicKey.verify(uint8array msg, uint8array signature);
return false;
},
});
| apache-2.0 |
eldar258/edzabarov | new_chapter_105/src/test/java/ru/job4j/tdd/MaxMinTest.java | 1937 | package ru.job4j.tdd;
import org.junit.Test;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
public class MaxMinTest {
@Test
public void whenMaxAndListExistOneElThenReturnThisEl() {
MaxMin maxMin = new MaxMin();
List<Integer> list = new ArrayList<>();
int result = 100;
list.add(result);
Integer resultMax = maxMin.max(list, Integer::compareTo);
assertThat(resultMax, is(result));
}
@Test
public void whenMaxAndListExistTwoElThenReturnMax() {
MaxMin maxMin = new MaxMin();
Integer[] array = {1, 99};
Integer[] array2 = {99, 1};
int resultMax = 99;
int resultMin = 1;
List<Integer> list = Arrays.asList(array);
List<Integer> list2 = Arrays.asList(array2);
Integer targetMax = maxMin.max(list, Integer::compareTo);
Integer targetMin = maxMin.min(list, Integer::compareTo);
Integer targetMax2 = maxMin.max(list2, Integer::compareTo);
Integer targetMin2 = maxMin.min(list2, Integer::compareTo);
assertThat(targetMax, is(resultMax));
assertThat(targetMin, is(resultMin));
assertThat(targetMax2, is(resultMax));
assertThat(targetMin2, is(resultMin));
}
@Test
public void whenMaxAndMinAndListExistMoreTwoElThenReturn14AndMinus1() {
MaxMin maxMin = new MaxMin();
Integer[] array = {1, 2, 3, 4, 2, 5, 1, 6, 6, 14, 0, 1, -1};
int resultMax = 14;
int resultMin = -1;
List<Integer> list = Arrays.asList(array);
Integer targetMax = maxMin.max(list, Integer::compareTo);
Integer targetMin = maxMin.min(list, Integer::compareTo);
assertThat(targetMax, is(resultMax));
assertThat(targetMin, is(resultMin));
}
} | apache-2.0 |
rushmin/product-mdm | modules/mobile-agents/android/jax-rs/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/PasswordPolicyBeanWrapper.java | 1261 | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.mdm.services.android.bean.wrapper;
import org.wso2.carbon.mdm.services.android.bean.PasswordPolicy;
import java.util.List;
/**
* This class is used to wrap the PasswordPolicy bean with devices.
*/
public class PasswordPolicyBeanWrapper {
private PasswordPolicy operation;
private List<String> deviceIDs;
public PasswordPolicy getOperation() {
return operation;
}
public void setOperation(PasswordPolicy operation) {
this.operation = operation;
}
public List<String> getDeviceIDs() {
return deviceIDs;
}
public void setDeviceIDs(List<String> deviceIDs) {
this.deviceIDs = deviceIDs;
}
}
| apache-2.0 |
GSTU/oop-examples | GamesLabs/2015/IT-22/Battle/Config.cs | 698 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace battle
{
public class Config
{
public GameConfig PlayerConfig;
public GameConfig AiConfig;
public Color Bgcolor;
public Config(GameConfig player, GameConfig ai, Color bgcolor)
{
PlayerConfig = player;
AiConfig = ai;
Bgcolor = bgcolor;
}
//public override string ToString()
//{
// return String.Format("{0}:{1}\n{2}:{3}", PikeConfig.Speed, PikeConfig.Vision, CarpConfig.Speed, CarpConfig.Vision);
//}
}
}
| apache-2.0 |
SMB-TEC/extended-objects | neo4j/src/test/java/com/buschmais/xo/neo4j/test/id/IdTest.java | 1736 | package com.buschmais.xo.neo4j.test.id;
import com.buschmais.xo.api.CompositeObject;
import com.buschmais.xo.api.XOManager;
import com.buschmais.xo.api.bootstrap.XOUnit;
import com.buschmais.xo.neo4j.test.AbstractNeo4jXOManagerTest;
import com.buschmais.xo.neo4j.test.id.composite.A;
import com.buschmais.xo.neo4j.test.id.composite.A2B;
import com.buschmais.xo.neo4j.test.id.composite.B;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.net.URISyntaxException;
import java.util.Collection;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
@RunWith(Parameterized.class)
public class IdTest extends AbstractNeo4jXOManagerTest {
public IdTest(XOUnit xoUnit) {
super(xoUnit);
}
@Parameterized.Parameters
public static Collection<Object[]> getXOUnits() throws URISyntaxException {
return xoUnits(A.class, B.class, A2B.class);
}
@Test
public void id() {
XOManager xoManager = getXoManager();
xoManager.currentTransaction().begin();
A a = xoManager.create(A.class);
B b = xoManager.create(B.class);
A2B a2b = xoManager.create(a, A2B.class, b);
Object aId = xoManager.getId(a);
assertThat(aId, notNullValue());
assertThat(((CompositeObject) a).getId(), equalTo(aId));
Object bId = xoManager.getId(b);
assertThat(bId, notNullValue());
assertThat(((CompositeObject) b).getId(), equalTo(bId));
Object a2bId = xoManager.getId(a2b);
assertThat(a2bId, notNullValue());
assertThat(((CompositeObject) a2b).getId(), equalTo(a2bId));
}
}
| apache-2.0 |
TechWritingWhiz/indy-node | indy_node/test/pool_config/test_send_pool_config.py | 1928 | import pytest
from indy_node.test.pool_config.helper import ensurePoolConfigSent, checkPoolConfigWritableSet, sendPoolConfig
from stp_core.loop.eventually import eventually
from plenum.test.pool_transactions.helper import disconnect_node_and_ensure_disconnected
def test_send_pool_config_writes_false_force_false(
nodeSet, looper, trustee, trusteeWallet, poolConfigWFFF):
ensurePoolConfigSent(looper, trustee, trusteeWallet, poolConfigWFFF)
checkPoolConfigWritableSet(nodeSet, False)
def test_send_pool_config_writes_true_force_true(
nodeSet, looper, trustee, trusteeWallet, poolConfigWTFT):
ensurePoolConfigSent(looper, trustee, trusteeWallet, poolConfigWTFT)
checkPoolConfigWritableSet(nodeSet, True)
def test_send_pool_config_writes_false_force_true(
nodeSet, looper, trustee, trusteeWallet, poolConfigWFFT):
ensurePoolConfigSent(looper, trustee, trusteeWallet, poolConfigWFFT)
checkPoolConfigWritableSet(nodeSet, False)
def test_send_pool_config_writes_true_force_false(
nodeSet, looper, trustee, trusteeWallet, poolConfigWTFF):
ensurePoolConfigSent(looper, trustee, trusteeWallet, poolConfigWTFF)
checkPoolConfigWritableSet(nodeSet, True)
def test_send_pool_config_2_nodes_can_force_writes_false_force_true(
nodeSet, looper, trustee, trusteeWallet, poolConfigWFFT):
assert len(nodeSet) == 4
node1 = nodeSet[2]
node0 = nodeSet[3]
checkPoolConfigWritableSet(nodeSet, True)
disconnect_node_and_ensure_disconnected(
looper, nodeSet, node0.name, stopNode=False)
looper.removeProdable(node0)
disconnect_node_and_ensure_disconnected(
looper, nodeSet, node1.name, stopNode=False)
looper.removeProdable(node1)
sendPoolConfig(trustee, trusteeWallet, poolConfigWFFT)
looper.run(eventually(checkPoolConfigWritableSet,
nodeSet[0:2], False, retryWait=1, timeout=10))
| apache-2.0 |
srdo/storm | sql/storm-sql-core/src/test/org/apache/storm/sql/compiler/backends/trident/TestPlanCompiler.java | 11584 | /*
* *
* * 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 org.apache.storm.sql.compiler.backends.trident;
import com.google.common.collect.ImmutableMap;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.calcite.DataContext;
import org.apache.calcite.avatica.util.DateTimeUtils;
import org.apache.storm.LocalCluster;
import org.apache.storm.sql.AbstractTridentProcessor;
import org.apache.storm.sql.SqlTestUtil;
import org.apache.storm.sql.TestUtils;
import org.apache.storm.sql.planner.trident.QueryPlanner;
import org.apache.storm.sql.runtime.ISqlTridentDataSource;
import org.apache.storm.trident.TridentTopology;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Values;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.apache.storm.sql.TestUtils.MockState.getCollectedValues;
import static org.junit.Assert.assertEquals;
public class TestPlanCompiler {
private static LocalCluster cluster;
@BeforeClass
public static void staticSetup() throws Exception {
cluster = new LocalCluster();
}
@AfterClass
public static void staticCleanup() {
if (cluster != null) {
cluster.shutdown();
cluster = null;
}
}
@Before
public void setUp() {
getCollectedValues().clear();
}
@Test
public void testCompile() throws Exception {
final int EXPECTED_VALUE_SIZE = 2;
String sql = "SELECT ID FROM FOO WHERE ID > 2";
TestCompilerUtils.CalciteState state = TestCompilerUtils.sqlOverDummyTable(sql);
final Map<String, ISqlTridentDataSource> data = new HashMap<>();
data.put("FOO", new TestUtils.MockSqlTridentDataSource());
QueryPlanner planner = new QueryPlanner(state.schema());
AbstractTridentProcessor proc = planner.compile(data, sql);
final TridentTopology topo = proc.build();
Fields f = proc.outputStream().getOutputFields();
proc.outputStream().partitionPersist(new TestUtils.MockStateFactory(),
f, new TestUtils.MockStateUpdater(), new Fields());
SqlTestUtil.runTridentTopology(cluster, EXPECTED_VALUE_SIZE, proc, topo);
Assert.assertArrayEquals(new Values[]{ new Values(3), new Values(4) }, getCollectedValues().toArray());
}
@Test
public void testInsert() throws Exception {
final int EXPECTED_VALUE_SIZE = 1;
String sql = "INSERT INTO BAR SELECT ID, NAME, ADDR FROM FOO WHERE ID > 3";
TestCompilerUtils.CalciteState state = TestCompilerUtils.sqlOverDummyTable(sql);
final Map<String, ISqlTridentDataSource> data = new HashMap<>();
data.put("FOO", new TestUtils.MockSqlTridentDataSource());
data.put("BAR", new TestUtils.MockSqlTridentDataSource());
QueryPlanner planner = new QueryPlanner(state.schema());
AbstractTridentProcessor proc = planner.compile(data, sql);
final TridentTopology topo = proc.build();
SqlTestUtil.runTridentTopology(cluster, EXPECTED_VALUE_SIZE, proc, topo);
Assert.assertArrayEquals(new Values[]{ new Values(4, "abcde", "y") }, getCollectedValues().toArray());
}
@Test
public void testUdf() throws Exception {
int EXPECTED_VALUE_SIZE = 1;
String sql = "SELECT MYPLUS(ID, 3)" +
"FROM FOO " +
"WHERE ID = 2";
TestCompilerUtils.CalciteState state = TestCompilerUtils.sqlOverDummyTable(sql);
Map<String, ISqlTridentDataSource> data = new HashMap<>();
data.put("FOO", new TestUtils.MockSqlTridentDataSource());
QueryPlanner planner = new QueryPlanner(state.schema());
AbstractTridentProcessor proc = planner.compile(data, sql);
final TridentTopology topo = proc.build();
Fields f = proc.outputStream().getOutputFields();
proc.outputStream().partitionPersist(new TestUtils.MockStateFactory(),
f, new TestUtils.MockStateUpdater(), new Fields());
SqlTestUtil.runTridentTopology(cluster, EXPECTED_VALUE_SIZE, proc, topo);
Assert.assertArrayEquals(new Values[]{ new Values(5) }, getCollectedValues().toArray());
}
@Test
public void testNested() throws Exception {
int EXPECTED_VALUE_SIZE = 1;
String sql = "SELECT ID, MAPFIELD['c'], NESTEDMAPFIELD, ARRAYFIELD " +
"FROM FOO " +
"WHERE NESTEDMAPFIELD['a']['b'] = 2 AND ARRAYFIELD[2] = 200";
TestCompilerUtils.CalciteState state = TestCompilerUtils.sqlOverNestedTable(sql);
final Map<String, ISqlTridentDataSource> data = new HashMap<>();
data.put("FOO", new TestUtils.MockSqlTridentNestedDataSource());
QueryPlanner planner = new QueryPlanner(state.schema());
AbstractTridentProcessor proc = planner.compile(data, sql);
final TridentTopology topo = proc.build();
Fields f = proc.outputStream().getOutputFields();
proc.outputStream().partitionPersist(new TestUtils.MockStateFactory(), f, new TestUtils.MockStateUpdater(), new Fields());
SqlTestUtil.runTridentTopology(cluster, EXPECTED_VALUE_SIZE, proc, topo);
Map<String, Integer> map = ImmutableMap.of("b", 2, "c", 4);
Map<String, Map<String, Integer>> nestedMap = ImmutableMap.of("a", map);
Assert.assertArrayEquals(new Values[]{ new Values(2, 4, nestedMap, Arrays.asList(100, 200, 300)) }, getCollectedValues().toArray());
}
/**
* All the binary literal tests are done here, because Avatica converts the result to byte[] whereas Trident provides the result to
* ByteString which makes different semantic from Trident implementation.
*/
@Test
public void testBinaryStringFunctions() throws Exception {
int EXPECTED_VALUE_SIZE = 1;
String sql = "SELECT x'45F0AB' || x'45F0AB', " +
"POSITION(x'F0' IN x'453423F0ABBC'), " +
"OVERLAY(x'453423F0ABBC45' PLACING x'4534' FROM 3), " +
"SUBSTRING(x'453423F0ABBC' FROM 3), " +
"SUBSTRING(x'453423F0ABBC453423F0ABBC' FROM 3 FOR 4) " +
"FROM FOO " +
"WHERE ID > 0 AND ID < 2";
TestCompilerUtils.CalciteState state = TestCompilerUtils.sqlOverDummyTable(sql);
final Map<String, ISqlTridentDataSource> data = new HashMap<>();
data.put("FOO", new TestUtils.MockSqlTridentDataSource());
QueryPlanner planner = new QueryPlanner(state.schema());
AbstractTridentProcessor proc = planner.compile(data, sql);
final TridentTopology topo = proc.build();
Fields f = proc.outputStream().getOutputFields();
proc.outputStream().partitionPersist(new TestUtils.MockStateFactory(), f, new TestUtils.MockStateUpdater(), new Fields());
SqlTestUtil.runTridentTopology(cluster, EXPECTED_VALUE_SIZE, proc, topo);
List<Object> v = getCollectedValues().get(0);
assertEquals("45f0ab45f0ab", v.get(0).toString());
assertEquals(4, v.get(1));
assertEquals("45344534abbc45", v.get(2).toString());
assertEquals("23f0abbc", v.get(3).toString());
assertEquals("23f0abbc", v.get(4).toString());
}
/**
* All the date/time/timestamp related tests are done here, because Avatica converts the result of date functions to java.sql classes
* whereas Trident provides long type which makes different semantic from Trident implementation.
*/
@Test
public void testDateKeywordsAndFunctions() throws Exception {
int EXPECTED_VALUE_SIZE = 1;
String sql = "SELECT " +
"LOCALTIME, CURRENT_TIME, LOCALTIMESTAMP, CURRENT_TIMESTAMP, CURRENT_DATE, " +
"DATE '1970-05-15' AS datefield, TIME '00:00:00' AS timefield, TIMESTAMP '2016-01-01 00:00:00' as timestampfield, " +
"EXTRACT(MONTH FROM TIMESTAMP '2010-01-23 12:34:56')," +
"FLOOR(DATE '2016-01-23' TO MONTH)," +
"CEIL(TIME '12:34:56' TO MINUTE)," +
"{fn CURDATE()} = CURRENT_DATE, {fn CURTIME()} = LOCALTIME, {fn NOW()} = LOCALTIMESTAMP," +
"{fn QUARTER(DATE '2016-10-07')}, {fn TIMESTAMPADD(MINUTE, 15, TIMESTAMP '2016-10-07 00:00:00')}," +
"{fn TIMESTAMPDIFF(SECOND, TIMESTAMP '2016-10-06 00:00:00', TIMESTAMP '2016-10-07 00:00:00')}," +
"INTERVAL '1-5' YEAR TO MONTH AS intervalfield, " +
"(DATE '1970-01-01', DATE '1970-01-15') AS anchoredinterval_field " +
"FROM FOO " +
"WHERE ID > 0 AND ID < 2";
TestCompilerUtils.CalciteState state = TestCompilerUtils.sqlOverDummyTable(sql);
final Map<String, ISqlTridentDataSource> data = new HashMap<>();
data.put("FOO", new TestUtils.MockSqlTridentDataSource());
QueryPlanner planner = new QueryPlanner(state.schema());
AbstractTridentProcessor proc = planner.compile(data, sql);
final DataContext dataContext = proc.getDataContext();
final TridentTopology topo = proc.build();
Fields f = proc.outputStream().getOutputFields();
proc.outputStream().partitionPersist(new TestUtils.MockStateFactory(), f, new TestUtils.MockStateUpdater(), new Fields());
SqlTestUtil.runTridentTopology(cluster, EXPECTED_VALUE_SIZE, proc, topo);
long utcTimestamp = (long) dataContext.get(DataContext.Variable.UTC_TIMESTAMP.camelName);
long currentTimestamp = (long) dataContext.get(DataContext.Variable.CURRENT_TIMESTAMP.camelName);
long localTimestamp = (long) dataContext.get(DataContext.Variable.LOCAL_TIMESTAMP.camelName);
System.out.println(getCollectedValues());
java.sql.Timestamp timestamp = new java.sql.Timestamp(utcTimestamp);
int dateInt = (int) timestamp.toLocalDateTime().atOffset(ZoneOffset.UTC).toLocalDate().toEpochDay();
int localTimeInt = (int) (localTimestamp % DateTimeUtils.MILLIS_PER_DAY);
int currentTimeInt = (int) (currentTimestamp % DateTimeUtils.MILLIS_PER_DAY);
Assert.assertArrayEquals(new Values[]{
new Values(localTimeInt, currentTimeInt, localTimestamp, currentTimestamp, dateInt,
134, 0, 1451606400000L, 1L, 0L, 45300000, true, true, true, 4L, 1475799300000L, 86400, 17, 0, 14)
},
getCollectedValues().toArray());
}
}
| apache-2.0 |
mlhartme/stool | src/test/java/net/oneandone/stool/kubernetes/EngineIT.java | 6496 | /*
* Copyright 1&1 Internet AG, https://github.com/1and1/
*
* 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 net.oneandone.stool.kubernetes;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.oneandone.stool.util.ITProperties;
import net.oneandone.sushi.fs.World;
import net.oneandone.sushi.fs.file.FileNode;
import net.oneandone.sushi.util.Strings;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
public class EngineIT {
private static final World WORLD;
static {
try {
WORLD = World.create();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private static Engine create() throws IOException {
return Engine.createLocal(new ObjectMapper(), ITProperties.load(WORLD).kubernetes);
}
@Test
public void imageDownload() throws IOException {
FileNode tmp;
try (Engine engine = create()) {
tmp = WORLD.getTemp().createTempDirectory().deleteDirectory();
engine.imageDownload("debian:buster-slim", "/etc", tmp);
assertTrue(tmp.find("**/*").size() > 1);
tmp.deleteTree();
}
}
@Test
public void podUpAndDownload() throws IOException {
String podName;
FileNode in;
FileNode out;
in = WORLD.getTemp().createTempDirectory();
in.join("sub").mkdir().join("file").writeString("hello");
out = WORLD.getTemp().createTempDirectory().deleteDirectory();
podName = UUID.randomUUID().toString();
try (Engine engine = create()) {
engine.podCreate(podName, "debian:buster-slim", 0, "sleep", "3600");
try {
engine.podUpload(podName, Engine.CONTAINER_NAME, in, "/etc/demo");
engine.podExec(podName, Engine.CONTAINER_NAME, "touch", "/etc/demo/touched");
engine.podDownload(podName, Engine.CONTAINER_NAME, "/etc/demo", out);
} finally {
engine.podDelete(podName);
}
}
assertEquals("", out.join("touched").readString());
assertEquals("hello", out.join("sub/file").readString());
}
@Test
public void podExec() throws IOException {
String name = UUID.randomUUID().toString();
String output;
try (Engine engine = create()) {
engine.podCreate(name, "debian:buster-slim", 0, "sleep", "3600");
output = engine.podExec(name, Engine.CONTAINER_NAME, "echo", "hi");
engine.podDelete(name);
}
assertEquals("hi\n", output);
}
@Test
public void podExecFailed() throws IOException {
String name = UUID.randomUUID().toString();
try (Engine engine = create()) {
engine.podCreate(name, "debian:buster-slim", 0, "sleep", "3600");
try {
engine.podExec(name, Engine.CONTAINER_NAME, "no-such-command", "hi");
fail();
} catch (IOException e) {
assertTrue(e.getMessage().startsWith("OCI runtime")); // TODO
}
engine.podDelete(name);
}
}
// @Test TODO: how to detect this!?
public void podExecFalse() throws IOException {
String name = UUID.randomUUID().toString();
try (Engine engine = create()) {
engine.podCreate(name, "debian:buster-slim", 0, "sleep", "3600");
try {
engine.podExec(name, Engine.CONTAINER_NAME, "false");
fail();
} catch (IOException e) {
assertTrue(e.getMessage().startsWith("OCI runtime"));
}
engine.podDelete(name);
}
}
@Test
public void podImplicitHostname() throws IOException {
String name = "pod-implicit";
try (Engine engine = create()) {
engine.podDeleteAwaitOpt(name);
assertFalse(engine.isOpenShift());
assertFalse(engine.podCreate(name, "debian:stretch-slim", 0, "hostname"));
assertEquals(false, engine.podContainerRunning(name, Engine.CONTAINER_NAME));
assertEquals(name + "\n", engine.podLogs(name));
engine.podDelete(name);
}
}
@Test
public void deployment() throws IOException {
String name = "dpl";
Map<String, DeploymentInfo> map;
DeploymentInfo info;
Map<String, PodInfo> pods;
PodInfo pod;
int initialDeployments;
try (Engine engine = create()) {
engine.deploymentDeleteOpt(name);
engine.deploymentAwaitGone(name);
assertNull(engine.deploymentProbe("nosuchdeployment"));
initialDeployments = engine.deploymentList().size();
engine.deploymentCreate(name, Strings.toMap("app", "foo"), Strings.toMap(),
"debian:stretch-slim", new String[] { "sleep", "1000" },
null, Strings.toMap("app", "foo"));
engine.deploymentAwaitAvailable(name);
map = engine.deploymentList();
assertEquals(initialDeployments + 1, map.size());
info = map.get(name);
assertEquals(name, info.name);
assertEquals(1, info.statusAvailable);
pods = engine.podList(Strings.toMap("app", "foo"));
assertEquals(1, pods.size());
pod = pods.values().iterator().next();
assertTrue(pod.isRunning());
engine.deploymentDelete(name);
assertEquals(initialDeployments, engine.deploymentList().size());
engine.podAwaitDeleted(pod.name);
}
}
}
| apache-2.0 |
pooi/Tuetue | app/src/main/java/tk/twpooi/tuetue/SelectInterestActivity.java | 9764 | package tk.twpooi.tuetue;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.wang.avi.AVLoadingIndicatorView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import tk.twpooi.tuetue.util.ParsePHP;
public class SelectInterestActivity extends AppCompatActivity {
private MyHandler handler = new MyHandler();
private final int MSG_MESSAGE_MAKE_LIST = 500;
// UI
private FrameLayout root;
private LinearLayout btnField;
private Button completeBtn;
private TextView notice;
private MaterialEditText editSearch;
private AVLoadingIndicatorView loading;
// Data
private String[] list;
private ArrayList<String> listTemp;
private ArrayList<String> alreadySetItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_interest);
Intent intent = getIntent();
alreadySetItem = intent.getStringArrayListExtra("interest");
if (null == alreadySetItem || alreadySetItem.size() < 0) {
alreadySetItem = new ArrayList<>();
}
init();
HashMap<String, String> map = new HashMap<String, String>();
map.put("service", "getFieldList");
loading.show();
new ParsePHP(Information.MAIN_SERVER_ADDRESS, map) {
@Override
protected void afterThreadFinish(String data) {
try {
// PHP에서 받아온 JSON 데이터를 JSON오브젝트로 변환
JSONObject jObject = new JSONObject(data);
// results라는 key는 JSON배열로 되어있다.
JSONArray results = jObject.getJSONArray("result");
String countTemp = (String) jObject.get("num_result");
int count = Integer.parseInt(countTemp);
list = new String[count];
for (int i = 0; i < count; ++i) {
JSONObject temp = results.getJSONObject(i);
list[i] = (String) temp.get("field");
}
listTemp = new ArrayList<>();
for (String s : list) {
listTemp.add(s);
}
} catch (JSONException e) {
e.printStackTrace();
}
handler.sendMessage(handler.obtainMessage(MSG_MESSAGE_MAKE_LIST));
}
}.start();
}
private void init(){
root = (FrameLayout)findViewById(R.id.root);
root.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
btnField = (LinearLayout) findViewById(R.id.btn_field);
completeBtn = (Button)findViewById(R.id.completeBtn);
completeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
complete();
}
});
notice = (TextView)findViewById(R.id.notice);
editSearch = (MaterialEditText) findViewById(R.id.edit_search);
editSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
searchList(s.toString());
}
@Override
public void afterTextChanged(Editable s) {
}
});
loading = (AVLoadingIndicatorView) findViewById(R.id.loading);
}
private class MyHandler extends Handler {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_MESSAGE_MAKE_LIST:
loading.hide();
makeList();
checkConfident();
break;
default:
break;
}
}
}
private void searchList(String sh) {
listTemp.clear();
for (String s : list) {
int i = s.indexOf(sh);
if (i >= 0) {
listTemp.add(s);
}
}
makeList();
}
private void setText(TextView t, boolean type, boolean addAble) {
String tag = (String) t.getTag();
if(type){
t.setBackgroundResource(R.drawable.round_button_gray);
if (addAble) {
alreadySetItem.remove(tag);
}
}else{
t.setBackgroundResource(R.drawable.round_button_blue);
if (addAble) {
alreadySetItem.add(tag);
}
}
}
private void makeList(){
btnField.removeAllViews();
final float scale =getResources().getDisplayMetrics().density;
int dp5 = (int) (5 * scale + 0.5f);
int dp3 = (int) (3 * scale * 0.5f);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(dp3, dp3, dp3, dp3);
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
float dpWidth = (int) (310 * scale + 0.5f);//displayMetrics.widthPixels;// / displayMetrics.density;
if (listTemp != null) {
LinearLayout mNewLayout = new LinearLayout(this); // Horizontal layout which I am using to add my buttons.
mNewLayout.setOrientation(LinearLayout.HORIZONTAL);
int mButtonsSize = 0;
Rect bounds = new Rect();
for (int i = 0; i < listTemp.size(); i++) {
String mButtonTitle = listTemp.get(i);
final TextView mBtn = new TextView(this);
mBtn.setPadding(dp5*2, dp5, dp5*2, dp5);
mBtn.setTag(mButtonTitle);
mBtn.setBackgroundResource(R.drawable.round_button_gray);
mBtn.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.white));
mBtn.setText(mButtonTitle);
mBtn.setLayoutParams(params);
mBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tag = (String) mBtn.getTag();
setText(mBtn, alreadySetItem.contains(tag), true);
checkConfident();
}
});
setText(mBtn, !alreadySetItem.contains(mButtonTitle), false);
// paint.getTextBounds(buttonText, 0, buttonText.length(), bounds);
// int textWidth = bounds.width();
Paint textPaint = mBtn.getPaint();
textPaint.getTextBounds(mButtonTitle, 0, mButtonTitle.length(), bounds);
int textViewWidth = bounds.width() + dp5*4 + dp3*2;
if(mButtonsSize + textViewWidth < dpWidth - dp3*2 - dp5*2){ // -32 because of extra padding in main layout.
mNewLayout.addView(mBtn);
mButtonsSize += textViewWidth;
} else {
btnField.addView(mNewLayout);
mNewLayout = new LinearLayout(this);
mNewLayout.setOrientation(LinearLayout.HORIZONTAL);
mButtonsSize = textViewWidth;//bounds.width();
mNewLayout.addView(mBtn); // add button to a new layout so it won't be stretched because of it's width.
}
}
btnField.addView(mNewLayout); // add the last layout/ button.
}
}
private void checkConfident(){
if (alreadySetItem.size() >= 3) {
completeBtn.setEnabled(true);
completeBtn.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
notice.setVisibility(View.GONE);
}else{
completeBtn.setEnabled(false);
completeBtn.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_gray));
notice.setVisibility(View.VISIBLE);
}
}
private void complete(){
// ArrayList<String> in = new ArrayList<>();
// for(int i : selectItemIndex){
// in.add(list[i]);
// }
Intent intent = new Intent();
intent.putExtra("interest", alreadySetItem);
setResult(1, intent);
finish();
}
public void showSnackbar(String msg){
Snackbar snackbar = Snackbar.make(getWindow().getDecorView().getRootView(), msg, Snackbar.LENGTH_SHORT);
View view = snackbar.getView();
view.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.snackbar_color));
snackbar.show();
}
}
| apache-2.0 |
wangyixiaohuihui/spark2-annotation | sql/catalyst/src/main/scala/org/apache/spark/sql/Encoder.scala | 3017 | /*
* 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.spark.sql
import scala.annotation.implicitNotFound
import scala.reflect.ClassTag
import org.apache.spark.annotation.{Experimental, InterfaceStability}
import org.apache.spark.sql.types._
/**
* :: Experimental ::
* Used to convert a JVM object of type `T` to and from the internal Spark SQL representation.
*
* == Scala ==
* Encoders are generally created automatically through implicits from a `SparkSession`, or can be
* explicitly created by calling static methods on [[Encoders]].
*
* {{{
* import spark.implicits._
*
* val ds = Seq(1, 2, 3).toDS() // implicitly provided (spark.implicits.newIntEncoder)
* }}}
*
* == Java ==
* Encoders are specified by calling static methods on [[Encoders]].
*
* {{{
* List<String> data = Arrays.asList("abc", "abc", "xyz");
* Dataset<String> ds = context.createDataset(data, Encoders.STRING());
* }}}
*
* Encoders can be composed into tuples:
*
* {{{
* Encoder<Tuple2<Integer, String>> encoder2 = Encoders.tuple(Encoders.INT(), Encoders.STRING());
* List<Tuple2<Integer, String>> data2 = Arrays.asList(new scala.Tuple2(1, "a");
* Dataset<Tuple2<Integer, String>> ds2 = context.createDataset(data2, encoder2);
* }}}
*
* Or constructed from Java Beans:
*
* {{{
* Encoders.bean(MyClass.class);
* }}}
*
* == Implementation ==
* - Encoders are not required to be thread-safe and thus they do not need to use locks to guard
* against concurrent access if they reuse internal buffers to improve performance.
*
* @since 1.6.0
*/
@Experimental
@InterfaceStability.Evolving
@implicitNotFound("Unable to find encoder for type stored in a Dataset. Primitive types " +
"(Int, String, etc) and Product types (case classes) are supported by importing " +
"spark.implicits._ Support for serializing other types will be added in future " +
"releases.")
trait Encoder[T] extends Serializable {
/** Returns the schema of encoding this type of object as a Row. */
def schema: StructType
/**
* A ClassTag that can be used to construct and Array to contain a collection of `T`.
*/
def clsTag: ClassTag[T]
}
| apache-2.0 |
Authpartyio/Authparty | app/api/authparty/api.rb | 3537 | require 'rubygems'
require 'bitcoin-cigs'
require 'uri'
class Authparty::API < Grape::API
version 'v1', using: :path
format :json
BASE_API_URL = ENV['BASE_API_URL']
desc 'Authorize Scanned Interaction'
post :authorize_login do
address = params[:address]
signature = params[:signature]
message = params[:message]
if BitcoinCigs.verify_message(address.to_s, signature.to_s, message.to_s)
puts 'BitcoinCigs: Success!'
@account = Account.find_or_create_from_wallet_address(params[:address])
if @account.broadcast_code == nil
charset = Array('A'..'Z') + Array('a'..'z')
@account.broadcast_code = Array.new(15) { charset.sample }.join
end
if @account.save
if @account.persisted?
notice = 'User was logged in.'
Pusher.trigger(params[:modal_id], 'my_event', {
message: notice,
user: @account.id
})
else
notice = 'User was created.'
Pusher.trigger(params[:modal_id], 'my_event', {
message: notice,
user: @account.id
})
end
if params[:provider] != nil
provider = Provider.find_by(api_key: params[:provider])
provider_exists = false
@account.connections.each do |c|
if c.provider_id = provider.id
provider_exists = true
end
end
if provider_exists == false
connection = @account.connections.new
connection.provider_id = provider.id
connection.connected_on = Time.now
connection.bearer = SecureRandom.hex(32)
provider.number_connected += 1
provider.save
connection.save
end
Pusher.trigger(params[:modal_id], 'my_event', {
message: 'Provider: Authorized',
user: @account.id
})
end
return :success => true
else
# Placeholder for Websocket Errors Alert
return :success => false, :errors => @account.errors
end
else
# Placeholder for Websocket Cannot Confirm Authorization Alert
return :success => false, :errors => 'We could not confirm your authorization.'
Pusher.trigger(params[:modal_id], 'my_event', {
message: 'Provider: We could not confirm your authorization.'
})
end
end
resource :providers do
desc 'Return Provider Information'
get :/ do
providers = []
Provider.all.each do |p|
providers << {
name: p.name,
email: p.contact_email,
logo: p.logo
}
end
return providers
end
get :find do
Provider.find_by(api_key: params[:api_key])
end
get :authorize_url do
return BASE_API_URL + 'providers_login?api_key=' + params['api_key']
end
get :authorize_qrcode do
charset = Array('A'..'Z') + Array('a'..'z')
generated_message = 'Authparty Login ' + Array.new(15) { charset.sample }.join
provider = params[:api_key]
callback = params[:callback_url]
@value = url_encode("counterparty:?method=sign&message=" + URI.escape(generated_message.to_s) + "&provider=" + provider + "&callback=" + url_encode(callback))
return "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=#{@value}"
end
end
end
| apache-2.0 |
Esri/impact-summary-map-template-js | js/ShareDialog.js | 17645 | define([
"dojo/Evented",
"dojo/_base/declare",
"dojo/_base/lang",
"dojo/string",
"dojo/has",
"esri/kernel",
"dijit/_WidgetBase",
"dijit/a11yclick",
"dijit/_TemplatedMixin",
"dojo/on",
// load template
"dojo/text!application/dijit/templates/ShareDialog.html",
"dojo/i18n!application/nls/ShareDialog",
"dojo/dom-class",
"dojo/dom-style",
"dojo/dom-attr",
"dojo/dom-construct",
"esri/request",
"esri/urlUtils",
"dijit/Dialog",
"dojo/_base/event"
],
function (
Evented,
declare,
lang,
string,
has, esriNS,
_WidgetBase, a11yclick, _TemplatedMixin,
on,
dijitTemplate, i18n,
domClass, domStyle, domAttr, domConstruct,
esriRequest,
urlUtils,
Dialog,
event
) {
var Widget = declare("esri.dijit.ShareDialog", [_WidgetBase, _TemplatedMixin, Evented], {
templateString: dijitTemplate,
options: {
theme: "ShareDialog",
visible: true,
dialog: null,
useExtent: false,
map: null,
url: window.location.href,
image: '',
title: window.document.title,
summary: '',
hashtags: '',
mailURL: 'mailto:%20?subject=${title}&body=${summary}%20${url}',
facebookURL: "https://www.facebook.com/sharer/sharer.php?u=${url}",
twitterURL: "https://twitter.com/intent/tweet?url=${url}&text=${title}&hashtags=${hashtags}",
shortenAPI: "https://arcg.is/prod/shorten",
embedSizes: [{
"width": "100%",
"height": "640px"
}, {
"width": "100%",
"height": "480px"
}, {
"width": "100%",
"height": "320px"
}, {
"width": "800px",
"height": "600px"
}, {
"width": "640px",
"height": "480px"
}, {
"width": "480px",
"height": "320px"
}]
},
// lifecycle: 1
constructor: function (options, srcRefNode) {
// mix in settings and defaults
var defaults = lang.mixin({}, this.options, options);
// widget node
this.domNode = srcRefNode;
this._i18n = i18n;
// properties
this.set("theme", defaults.theme);
this.set("url", defaults.url);
this.set("visible", defaults.visible);
this.set("dialog", defaults.dialog);
this.set("embedSizes", defaults.embedSizes);
this.set("embedHeight", defaults.embedHeight);
this.set("embedWidth", defaults.embedWidth);
this.set("mailURL", defaults.mailURL);
this.set("facebookURL", defaults.facebookURL);
this.set("twitterURL", defaults.twitterURL);
this.set("shortenAPI", defaults.shortenAPI);
this.set("image", defaults.image);
this.set("title", defaults.title);
this.set("summary", defaults.summary);
this.set("hashtags", defaults.hashtags);
this.set("useExtent", defaults.useExtent);
// listeners
this.watch("theme", this._updateThemeWatch);
this.watch("url", this._updateUrl);
this.watch("visible", this._visible);
this.watch("embedSizes", this._setSizeOptions);
this.watch("embed", this._updateEmbed);
this.watch("shortenUrl", this._updateshortenUrl);
this.watch("useExtent", this._useExtentChanged);
// classes
this.css = {
container: "button-container",
embed: "embed-page",
button: "toggle-grey",
buttonSelected: "toggle-grey-on",
icon: "icon-share",
linkIcon: "icon-link share-dialog-icon",
facebookIcon: "icon-facebook-squared-1 share-dialog-icon",
twitterIcon: "icon-twitter-1 share-dialog-icon",
emailIcon: "icon-mail share-dialog-icon",
mapSizeLabel: "map-size-label",
shareMapURL: "share-map-url",
iconContainer: "icon-container",
embedMapSizeDropDown: "embed-map-size-dropdown",
shareDialogContent: "dialog-content",
shareDialogSubHeader: "share-dialog-subheader",
shareDialogTextarea: "share-dialog-textarea",
shareDialogExtent: "share-dialog-extent",
mapSizeContainer: "map-size-container",
embedMapSizeClear: "embed-map-size-clear",
iconClear: "icon-clear"
};
},
// bind listener for button to action
postCreate: function () {
this.inherited(arguments);
this._setExtentChecked();
this.own(on(this._buttonNode, a11yclick, lang.hitch(this, this.toggle)));
this.own(on(this._extentInput, a11yclick, lang.hitch(this, this._useExtentUpdate)));
},
// start widget. called by user
startup: function () {
this._init();
},
// connections/subscriptions will be cleaned up during the destroy() lifecycle phase
destroy: function () {
this.inherited(arguments);
},
/* ---------------- */
/* Public Events */
/* ---------------- */
// load
// open
// close
// toggle
/* ---------------- */
/* Public Functions */
/* ---------------- */
show: function () {
this.set("visible", true);
},
hide: function () {
this.set("visible", false);
},
open: function () {
domClass.add(this._buttonNode, this.css.buttonSelected);
this.get("dialog").show();
if (this.get("useExtent")) {
this._updateUrl();
}
this.emit("open", {});
this._shareLink();
},
close: function () {
this.get("dialog").hide();
this.emit("close", {});
},
toggle: function () {
var open = this.get("dialog").get("open");
if (open) {
this.close();
} else {
this.open();
}
this.emit("toggle", {});
},
/* ---------------- */
/* Private Functions */
/* ---------------- */
_stripTags: function (str) {
var text = domConstruct.create("div", {
innerHTML: str
}).textContent;
return text || '';
},
_setExtentChecked: function () {
domAttr.set(this._extentInput, 'checked', this.get("useExtent"));
},
_useExtentUpdate: function () {
var value = domAttr.get(this._extentInput, 'checked');
this.set("useExtent", value);
},
_useExtentChanged: function () {
this._updateUrl();
this._shareLink();
},
_setSizeOptions: function () {
// clear select menu
this._comboBoxNode.innerHTML = '';
// if embed sizes exist
if (this.get("embedSizes") && this.get("embedSizes").length) {
// map sizes
for (var i = 0; i < this.get("embedSizes").length; i++) {
if (i === 0) {
this.set("embedWidth", this.get("embedSizes")[i].width);
this.set("embedHeight", this.get("embedSizes")[i].height);
}
var option = domConstruct.create("option", {
value: i,
innerHTML: this.get("embedSizes")[i].width + " x " + this.get("embedSizes")[i].height
});
domConstruct.place(option, this._comboBoxNode, "last");
}
}
},
_updateUrl: function () {
// nothing currently shortened
this._shortened = null;
// no shorten shortened
this.set("shortenUrl", null);
// vars
var map = this.get("map"),
url = this.get("url"),
useSeparator;
// get url params
var urlObject = urlUtils.urlToObject(window.location.href);
urlObject.query = urlObject.query || {};
// Remove edit=true from the query parameters
if (urlObject.query.edit) {
delete urlObject.query.edit;
}
// remove folder id
if (urlObject.query.folderid) {
delete urlObject.query.folderid;
}
// remove locale
if (urlObject.query.locale) {
delete urlObject.query.locale;
}
// include extent in url
if (this.get("useExtent") && map) {
// get map extent in geographic
var gExtent = map.geographicExtent;
// set extent string
urlObject.query.extent = gExtent.xmin.toFixed(4) + ',' + gExtent.ymin.toFixed(4) + ',' + gExtent.xmax.toFixed(4) + ',' + gExtent.ymax.toFixed(4);
} else {
urlObject.query.extent = null;
}
// create base url
url = 'https://' + window.location.host + window.location.pathname;
// each param
for (var i in urlObject.query) {
if (urlObject.query[i]) {
// use separator
if (useSeparator) {
url += '&';
} else {
url += '?';
useSeparator = true;
}
url += i + '=' + urlObject.query[i];
}
}
// update url
this.set("url", url);
// reset embed code
this._setEmbedCode();
// set url value
domAttr.set(this._shareMapUrlText, "value", url);
domAttr.set(this._linkButton, "href", url);
},
_init: function () {
// set sizes for select box
this._setSizeOptions();
// dialog
if (!this.get("dialog")) {
var dialog = new Dialog({
title: i18n.widgets.ShareDialog.title,
draggable: false
}, this._dialogNode);
this.set("dialog", dialog);
}
// dialog hide
this.own(on(this.get("dialog"), 'hide', lang.hitch(this, function () {
domClass.remove(this._buttonNode, this.css.buttonSelected);
})));
// set visible
this._visible();
// set embed url
this._updateUrl();
// select menu change
this.own(on(this._comboBoxNode, "change", lang.hitch(this, function (evt) {
this.set("embedWidth", this.get("embedSizes")[parseInt(evt.currentTarget.value, 10)].width);
this.set("embedHeight", this.get("embedSizes")[parseInt(evt.currentTarget.value, 10)].height);
this._setEmbedCode();
})));
// facebook click
this.own(on(this._facebookButton, a11yclick, lang.hitch(this, function () {
this._configureShareLink(this.get("facebookURL"));
})));
// twitter click
this.own(on(this._twitterButton, a11yclick, lang.hitch(this, function () {
this._configureShareLink(this.get("twitterURL"));
})));
// email click
this.own(on(this._emailButton, a11yclick, lang.hitch(this, function () {
this._configureShareLink(this.get("mailURL"), true);
})));
// link box click
this.own(on(this._shareMapUrlText, a11yclick, lang.hitch(this, function () {
this._shareMapUrlText.setSelectionRange(0, 9999);
})));
// link box mouseup stop for touch devices
this.own(on(this._shareMapUrlText, 'mouseup', function (evt) {
event.stop(evt);
}));
// embed box click
this.own(on(this._embedNode, a11yclick, lang.hitch(this, function () {
this._embedNode.setSelectionRange(0, 9999);
})));
// embed box mouseup stop for touch devices
this.own(on(this._embedNode, 'mouseup', function (evt) {
event.stop(evt);
}));
// rotate
this.own(on(window, "orientationchange", lang.hitch(this, function () {
var open = this.get("dialog").get("open");
if (open) {
dialog.hide();
dialog.show();
}
})));
// loaded
this.set("loaded", true);
this.emit("load", {});
},
_updateEmbed: function () {
domAttr.set(this._embedNode, "value", this.get("embed"));
},
_setEmbedCode: function () {
var es = '<iframe width="' + this.get("embedWidth") + '" height="' + this.get("embedHeight") + '" src="' + this.get("url") + '" frameborder="0" scrolling="no"></iframe>';
this.set("embed", es);
},
_updateshortenUrl: function () {
var shorten = this.get("shortenUrl");
if (shorten) {
domAttr.set(this._shareMapUrlText, "value", shorten);
domAttr.set(this._linkButton, "href", shorten);
}
},
_shareLink: function () {
var currentUrl = this.get("url");
this._shortened = currentUrl;
// make request
return esriRequest({
url: this.get("shortenAPI"),
callbackParamName: "callback",
content: {
longUrl: currentUrl,
f: "json"
},
load: lang.hitch(this, function (response) {
if (response && response.data && response.data.url) {
this.set("shortenUrl", response.data.url);
this._shareMapUrlText.select();
}
}),
error: function (error) {
console.log(error);
}
});
},
_configureShareLink: function (Link, isMail) {
// replace strings
var fullLink = string.substitute(Link, {
url: encodeURIComponent(this.get("shortenUrl") ? this.get("shortenUrl") : this.get("url")),
image: encodeURIComponent(this.get("image")),
title: encodeURIComponent(this.get("title")),
summary: encodeURIComponent(this._stripTags(this.get("summary"))),
hashtags: encodeURIComponent(this.get("hashtags"))
});
// email link
if (isMail) {
window.location.href = fullLink;
} else {
window.open(fullLink, 'share', true);
}
},
_updateThemeWatch: function () {
var oldVal = arguments[1];
var newVal = arguments[2];
if (this.get("loaded")) {
domClass.remove(this.domNode, oldVal);
domClass.add(this.domNode, newVal);
}
},
_visible: function () {
if (this.get("visible")) {
domStyle.set(this.domNode, 'display', 'block');
} else {
domStyle.set(this.domNode, 'display', 'none');
}
}
});
if (has("extend-esri")) {
lang.setObject("dijit.ShareDialog", Widget, esriNS);
}
return Widget;
}); | apache-2.0 |
iot-salzburg/self-driving-slotcar | computer_vision/main.py | 8074 | import cv2
import numpy as np
from matplotlib import pyplot as plt
from os.path import exists, join
from os import makedirs
import pickle
image_selection = np.array([0, 0], dtype='float32')
OUTPUT_SIZE = [6000, 9000]
def remove_fisheye(img):
K = np.array([[1001.7792, 0., 962.3616],
[0., 1012.7232, 561.2760],
[0., 0., 1.]])
# zero distortion coefficients work well for this image
D = np.array([-0.31331, 0.12965, 0.00073, -0.00022])
# use Knew to scale the output
Knew = K.copy()
Knew[(0, 1), (0, 1)] = 0.4 * Knew[(0, 1), (0, 1)]
# return cv2.fisheye.undistortImage(img, K, D=D, Knew=Knew)
return img
# noinspection PyArgumentList
def compute_transformation(video_file, debug=False):
""" Computes the proper transformation by letting the user select appropriate points in the image """
# noinspection PyCompatibility
def get_coords(select_image):
# noinspection PyCompatibility
def getxy(event, row, col, flags, param):
global image_selection
if event == cv2.EVENT_LBUTTONDOWN:
image_selection = np.vstack([image_selection, np.hstack([row, col])])
cv2.circle(select_image, (row, col), 3, (0, 0, 255), -1)
cv2.imshow('image', select_image)
print("(row, col) = ", (row, col))
# Read the image
# Set mouse CallBack event
cv2.namedWindow('image')
cv2.setMouseCallback('image', getxy)
# show the image
print("Click to select a point OR press ANY KEY to continue...")
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# obtain the matrix of the selected points
selected_points = image_selection[1:, :]
return np.float32(selected_points)
cap = cv2.VideoCapture(video_file)
ret, distorted_img = cap.read()
# remove fisheye distortion
img = remove_fisheye(distorted_img)
plt.figure()
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
# compute corner pairs
original_corners = get_coords(img)
print(np.array(original_corners))
new_corners = np.float32([[0., 0.], [210., 0.], [210., 297.], [0., 297.]]) * 4. + 4200.
# perform homography
transformation = cv2.getPerspectiveTransform(original_corners, new_corners)
dst = cv2.warpPerspective(img, transformation, tuple(OUTPUT_SIZE))
if debug:
plt.figure()
plt.imshow(cv2.cvtColor(distorted_img, cv2.COLOR_BGR2RGB))
plt.figure()
plt.imshow(cv2.cvtColor(dst, cv2.COLOR_BGR2RGB))
plt.show()
cap.release()
cv2.destroyAllWindows()
return transformation
def pre_process_image(img, transformation, largest_contour):
""" processes image for further evalution """
# remove fisheye distortion
frame = remove_fisheye(img)
# apply perspective warping
dst = cv2.warpPerspective(frame, transformation, tuple(OUTPUT_SIZE))
# get region of interest
cropped = dst[1050:-950, 3500:6200]
dst = cropped.copy()
# find largest contour
if largest_contour is None:
hsv = cv2.cvtColor(dst, cv2.COLOR_BGR2HSV)
lower_range = np.array([0, 0, 0], dtype=np.uint8)
upper_range = np.array([255, 255, 70], dtype=np.uint8)
mask = cv2.inRange(hsv, lower_range, upper_range)
# close blobs
kernel = np.ones((40, 40), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
_, contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
largest_contour = max(contours, key=cv2.contourArea)
mask = np.zeros(dst.shape, np.uint8)
cv2.drawContours(mask, [largest_contour], 0, 255, -1)
mask = mask[:, :, 0]
res = cv2.bitwise_and(dst, dst, mask=mask)
return res, cropped, largest_contour
def detect_car(fgbg, frame):
# substract background
fgmask = fgbg.apply(frame)
# close masks
kernel = np.ones((15, 15), np.uint8)
fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
kernel = np.ones((50, 50), np.uint8)
fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_DILATE, kernel)
# find largest contour and compute centroid
cx, cy = (0, 0)
_, contours, _ = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if contours:
largest_contour = max(contours, key=cv2.contourArea)
# compute centroid of contour
moment = cv2.moments(largest_contour)
cx = int(moment['m10'] / moment['m00'])
cy = int(moment['m01'] / moment['m00'])
return (cx, cy), fgmask
def detect_center_coords(img):
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_range = np.array([0, 0, 200], dtype=np.uint8)
upper_range = np.array([255, 255, 255], dtype=np.uint8)
mask = cv2.inRange(hsv, lower_range, upper_range)
_, contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cx, cy = (0, 0)
if contours:
largest_contour = max(contours, key=cv2.contourArea)
# compute centroid of contour
moment = cv2.moments(largest_contour)
cx = int(moment['m10'] / moment['m00'])
cy = int(moment['m01'] / moment['m00'])
return (cx, cy), mask
# noinspection PyArgumentList
def convert_video(video, debug=False):
""" Normalises each frame in the given video files """
makedirs('output', exist_ok=True)
# compute transformation matrix
transformation_file = join('output', 'transformation_' + str(video) + '.pickle')
if exists(transformation_file):
with open(transformation_file, 'rb') as pickle_file:
transformation = pickle.load(pickle_file)
else:
transformation = compute_transformation(video_file=video, debug=debug)
with open(transformation_file, 'wb') as pickle_file:
pickle.dump(transformation, pickle_file)
# output definition
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(join('output', 'result.avi'), fourcc, 1.0, (700, 1000))
fgbg = cv2.createBackgroundSubtractorMOG2()
cap = cv2.VideoCapture(video)
largest_contour = None
center_coords = None
frame_counter = 0
while cap.isOpened():
ret, frame = cap.read()
if ret:
# perform pre-processing
pre_processed_image, cropped_image, largest_contour = pre_process_image(frame,
transformation,
largest_contour)
# detect car
car_coords, car_mask = detect_car(fgbg, pre_processed_image)
# detect coords of center
if center_coords is None:
center_coords, center_mask = detect_center_coords(pre_processed_image)
# show results when ready
if frame_counter > 3:
cv2.line(cropped_image, center_coords, car_coords, (255, 0, 0), 10)
cv2.circle(cropped_image, car_coords, 30, (0, 0, 255), -1)
cv2.circle(cropped_image, center_coords, 30, (0, 255, 255), -1)
to_show = np.concatenate((cropped_image,
pre_processed_image,
cv2.bitwise_and(pre_processed_image, pre_processed_image, mask=center_mask),
cv2.bitwise_and(pre_processed_image, pre_processed_image, mask=car_mask)),
axis=1)
cv2.imshow('converted video', cv2.resize(to_show, (0, 0), fx=0.15, fy=0.15))
if cv2.waitKey(1) & 0xFF == ord('q'):
break
frame_counter += 1
out.write(cv2.resize(to_show, (0, 0), fx=0.1, fy=0.1))
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
convert_video(video=0, debug=True)
| apache-2.0 |
zhcet-amu/zhcet-web | src/main/java/amu/zhcet/auth/password/change/PasswordChangeService.java | 1684 | package amu.zhcet.auth.password.change;
import amu.zhcet.auth.AuthManager;
import amu.zhcet.auth.password.PasswordValidationException;
import amu.zhcet.auth.password.PasswordValidator;
import amu.zhcet.auth.password.PasswordChange;
import amu.zhcet.core.error.ErrorUtils;
import amu.zhcet.data.user.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import javax.transaction.Transactional;
@Slf4j
@Service
public class PasswordChangeService {
private final AuthManager authManager;
private final PasswordValidator passwordValidator;
@Autowired
public PasswordChangeService(AuthManager authManager, PasswordValidator passwordValidator) {
this.authManager = authManager;
this.passwordValidator = passwordValidator;
}
/**
* Changes password of a user
* @param user User whose password is to be changed
* @param passwordChange Password Container
* @throws PasswordValidationException If password is not of correct form
*/
@Transactional
public void changePassword(User user, PasswordChange passwordChange) throws PasswordValidationException {
ErrorUtils.requireNonNullUser(user);
Assert.notNull(passwordChange, "PasswordReset should not be null");
if (!user.isEmailVerified())
throw new PasswordValidationException("Cannot change password for unverified user");
// Validate and set the password
passwordValidator.validateAndSetPasswordChange(user, passwordChange);
authManager.updatePassword(user);
}
}
| apache-2.0 |
brettwooldridge/buck | test/com/facebook/buck/jvm/java/Jsr199JavacIntegrationTest.java | 14841 | /*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.jvm.java;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.facebook.buck.core.model.BuildTargetFactory;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.SourcePathRuleFinder;
import com.facebook.buck.core.rules.impl.FakeBuildRule;
import com.facebook.buck.core.rules.resolver.impl.TestActionGraphBuilder;
import com.facebook.buck.core.sourcepath.PathSourcePath;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolver;
import com.facebook.buck.core.sourcepath.resolver.impl.DefaultSourcePathResolver;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.io.filesystem.TestProjectFilesystems;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.facebook.buck.jvm.java.Javac.Invocation;
import com.facebook.buck.jvm.java.abi.AbiGenerationMode;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.TestExecutionContext;
import com.facebook.buck.testutil.TemporaryPaths;
import com.facebook.buck.util.MockClassLoader;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import javax.lang.model.SourceVersion;
import javax.tools.DiagnosticListener;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
public class Jsr199JavacIntegrationTest {
public static final ImmutableSortedSet<Path> SOURCE_PATHS =
ImmutableSortedSet.of(Paths.get("Example.java"));
@Rule public TemporaryPaths tmp = new TemporaryPaths();
private Path pathToSrcsList;
@Before
public void setUp() {
pathToSrcsList = tmp.getRoot().resolve("srcs_list");
}
@Test
public void testGetDescription() throws IOException {
Jsr199Javac javac = createJavac(/* withSyntaxError */ false);
String pathToOutputDir = tmp.getRoot().resolve("out").toAbsolutePath().toString();
assertEquals(
String.format(
"javac -source %s -target %s -g " + "-d %s " + "-classpath '' " + "@" + pathToSrcsList,
JavacOptions.TARGETED_JAVA_VERSION,
JavacOptions.TARGETED_JAVA_VERSION,
pathToOutputDir),
javac.getDescription(
ImmutableList.of(
"-source",
JavacOptions.TARGETED_JAVA_VERSION,
"-target",
JavacOptions.TARGETED_JAVA_VERSION,
"-g",
"-d",
pathToOutputDir,
"-classpath",
"''"),
SOURCE_PATHS,
pathToSrcsList));
}
@Test
public void testGetShortName() throws IOException {
Jsr199Javac javac = createJavac(/* withSyntaxError */ false);
assertEquals("javac", javac.getShortName());
}
@Test
public void testClassesFile() throws IOException, InterruptedException {
Jsr199Javac javac = createJavac(/* withSyntaxError */ false);
ExecutionContext executionContext = TestExecutionContext.newInstance();
JavacExecutionContext javacExecutionContext =
JavacExecutionContext.of(
new JavacEventSinkToBuckEventBusBridge(executionContext.getBuckEventBus()),
executionContext.getStdErr(),
executionContext.getClassLoaderCache(),
executionContext.getVerbosity(),
executionContext.getCellPathResolver(),
executionContext.getJavaPackageFinder(),
createProjectFilesystem(),
executionContext.getProjectFilesystemFactory(),
executionContext.getEnvironment(),
executionContext.getProcessExecutor());
int exitCode =
javac
.newBuildInvocation(
javacExecutionContext,
DefaultSourcePathResolver.from(
new SourcePathRuleFinder(new TestActionGraphBuilder())),
BuildTargetFactory.newInstance("//some:example"),
ImmutableList.of(),
ImmutableList.of(),
SOURCE_PATHS,
pathToSrcsList,
Paths.get("working"),
false,
false,
null,
null,
AbiGenerationMode.CLASS,
AbiGenerationMode.CLASS,
null)
.buildClasses();
assertEquals("javac should exit with code 0.", exitCode, 0);
assertTrue(Files.exists(pathToSrcsList));
assertTrue(Files.isRegularFile(pathToSrcsList));
assertEquals(
"Example.java",
new String(Files.readAllBytes(pathToSrcsList), StandardCharsets.UTF_8).trim());
}
/**
* There was a bug where `BuildTargetSourcePath` sources were written to the classes file using
* their string representation, rather than their resolved path.
*/
@Test
public void shouldWriteResolvedBuildTargetSourcePathsToClassesFile()
throws IOException, InterruptedException {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
BuildRule rule = new FakeBuildRule("//:fake");
graphBuilder.addToIndex(rule);
Jsr199Javac javac = createJavac(/* withSyntaxError */ false);
ExecutionContext executionContext = TestExecutionContext.newInstance();
JavacExecutionContext javacExecutionContext =
JavacExecutionContext.of(
new JavacEventSinkToBuckEventBusBridge(executionContext.getBuckEventBus()),
executionContext.getStdErr(),
executionContext.getClassLoaderCache(),
executionContext.getVerbosity(),
executionContext.getCellPathResolver(),
executionContext.getJavaPackageFinder(),
createProjectFilesystem(),
executionContext.getProjectFilesystemFactory(),
executionContext.getEnvironment(),
executionContext.getProcessExecutor());
int exitCode =
javac
.newBuildInvocation(
javacExecutionContext,
DefaultSourcePathResolver.from(
new SourcePathRuleFinder(new TestActionGraphBuilder())),
BuildTargetFactory.newInstance("//some:example"),
ImmutableList.of(),
ImmutableList.of(),
SOURCE_PATHS,
pathToSrcsList,
Paths.get("working"),
false,
false,
null,
null,
AbiGenerationMode.CLASS,
AbiGenerationMode.CLASS,
null)
.buildClasses();
assertEquals("javac should exit with code 0.", exitCode, 0);
assertTrue(Files.exists(pathToSrcsList));
assertTrue(Files.isRegularFile(pathToSrcsList));
assertEquals(
"Example.java",
new String(Files.readAllBytes(pathToSrcsList), StandardCharsets.UTF_8).trim());
}
public static final class MockJavac implements JavaCompiler {
public MockJavac() {}
@Override
public Set<SourceVersion> getSourceVersions() {
return ImmutableSet.of(SourceVersion.RELEASE_7);
}
@Override
public int run(InputStream in, OutputStream out, OutputStream err, String... arguments) {
throw new OutOfMemoryError("abcdef");
}
@Override
public int isSupportedOption(String option) {
return -1;
}
@Override
public StandardJavaFileManager getStandardFileManager(
DiagnosticListener<? super JavaFileObject> diagnosticListener,
Locale locale,
Charset charset) {
throw new OutOfMemoryError("abcdef");
}
@Override
public CompilationTask getTask(
Writer out,
JavaFileManager fileManager,
DiagnosticListener<? super JavaFileObject> diagnosticListener,
Iterable<String> options,
Iterable<String> classes,
Iterable<? extends JavaFileObject> compilationUnits) {
throw new OutOfMemoryError("abcdef");
}
}
@Test
public void shouldUseSpecifiedJavacJar() throws Exception {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
BuildRule rule = new FakeBuildRule("//:fake");
graphBuilder.addToIndex(rule);
Path fakeJavacJar = Paths.get("ae036e57-77a7-4356-a79c-0f85b1a3290d", "fakeJavac.jar");
ExecutionContext executionContext = TestExecutionContext.newInstance();
MockClassLoader mockClassLoader =
new MockClassLoader(
ClassLoader.getSystemClassLoader(),
ImmutableMap.of(
ExternalJavacProvider.COM_SUN_TOOLS_JAVAC_API_JAVAC_TOOL, MockJavac.class));
executionContext
.getClassLoaderCache()
.injectClassLoader(
ClassLoader.getSystemClassLoader(),
ImmutableList.of(fakeJavacJar.toUri().toURL()),
mockClassLoader);
Jsr199Javac javac = createJavac(/* withSyntaxError */ false, Optional.of(fakeJavacJar));
JavacExecutionContext javacExecutionContext =
JavacExecutionContext.of(
new JavacEventSinkToBuckEventBusBridge(executionContext.getBuckEventBus()),
executionContext.getStdErr(),
executionContext.getClassLoaderCache(),
executionContext.getVerbosity(),
executionContext.getCellPathResolver(),
executionContext.getJavaPackageFinder(),
createProjectFilesystem(),
executionContext.getProjectFilesystemFactory(),
executionContext.getEnvironment(),
executionContext.getProcessExecutor());
boolean caught = false;
try {
javac
.newBuildInvocation(
javacExecutionContext,
DefaultSourcePathResolver.from(
new SourcePathRuleFinder(new TestActionGraphBuilder())),
BuildTargetFactory.newInstance("//some:example"),
ImmutableList.of(),
ImmutableList.of(),
SOURCE_PATHS,
pathToSrcsList,
Paths.get("working"),
false,
false,
null,
null,
AbiGenerationMode.CLASS,
AbiGenerationMode.CLASS,
null)
.buildClasses();
fail("Did not expect compilation to succeed");
} catch (OutOfMemoryError ex) {
if (ex.toString().contains("abcdef")) {
caught = true;
}
}
assertTrue("mock Java compiler should throw", caught);
}
private Jsr199Javac createJavac(boolean withSyntaxError, Optional<Path> javacJar)
throws IOException {
Path exampleJava = tmp.newFile("Example.java");
Files.write(
exampleJava,
Joiner.on('\n')
.join(
"package com.example;", "", "public class Example {" + (withSyntaxError ? "" : "}"))
.getBytes(Charsets.UTF_8));
Path pathToOutputDirectory = Paths.get("out");
tmp.newFolder(pathToOutputDirectory.toString());
Optional<SourcePath> jar = javacJar.map(p -> PathSourcePath.of(new FakeProjectFilesystem(), p));
if (jar.isPresent()) {
return new JarBackedJavac(
ExternalJavacProvider.COM_SUN_TOOLS_JAVAC_API_JAVAC_TOOL, ImmutableSet.of(jar.get()));
}
return new JdkProvidedInMemoryJavac();
}
private Jsr199Javac createJavac(boolean withSyntaxError) throws IOException {
return createJavac(withSyntaxError, Optional.empty());
}
private ProjectFilesystem createProjectFilesystem() {
return TestProjectFilesystems.createProjectFilesystem(tmp.getRoot());
}
/**
* Behaves like {@link com.facebook.buck.jvm.java.JdkProvidedInMemoryJavac} when JDK is not
* present
*/
private static class JdkNotFoundJavac extends Jsr199Javac {
@Override
protected JavaCompiler createCompiler(
JavacExecutionContext context, SourcePathResolver resolver) {
throw new RuntimeException("JDK is not found");
}
}
@Test
@SuppressWarnings("PMD.EmptyCatchBlock")
public void jdkNotFound() {
Jsr199Javac javac = new JdkNotFoundJavac();
ExecutionContext executionContext = TestExecutionContext.newInstance();
JavacExecutionContext javacExecutionContext =
JavacExecutionContext.of(
new JavacEventSinkToBuckEventBusBridge(executionContext.getBuckEventBus()),
executionContext.getStdErr(),
executionContext.getClassLoaderCache(),
executionContext.getVerbosity(),
executionContext.getCellPathResolver(),
executionContext.getJavaPackageFinder(),
createProjectFilesystem(),
executionContext.getProjectFilesystemFactory(),
executionContext.getEnvironment(),
executionContext.getProcessExecutor());
Invocation buildInvocation =
javac.newBuildInvocation(
javacExecutionContext,
DefaultSourcePathResolver.from(new SourcePathRuleFinder(new TestActionGraphBuilder())),
BuildTargetFactory.newInstance("//some:example"),
ImmutableList.of(),
ImmutableList.of(),
SOURCE_PATHS,
pathToSrcsList,
Paths.get("working"),
false,
false,
null,
null,
AbiGenerationMode.CLASS,
AbiGenerationMode.CLASS,
null);
try {
buildInvocation.buildClasses();
fail();
} catch (Exception e) {
// expected
}
// Make sure `close` works properly
buildInvocation.close();
}
}
| apache-2.0 |
JayStGelais/jrpg-engine | jrpg-engine-core/src/main/java/com/moonlightpixels/jrpg/combat/internal/BattleInfo.java | 935 | package com.moonlightpixels.jrpg.combat.internal;
import com.moonlightpixels.jrpg.combat.Combatant;
import com.moonlightpixels.jrpg.combat.render.BattleBackground;
import lombok.Builder;
import lombok.Data;
import lombok.NonNull;
import lombok.Singular;
import java.util.List;
import java.util.Optional;
@Data
public final class BattleInfo {
private final List<Combatant> party;
private final List<Combatant> enemies;
private final BattleBackground background;
@Builder
public BattleInfo(@NonNull @Singular("playerChracter") final List<Combatant> party,
@NonNull @Singular("enemy") final List<Combatant> enemies,
final BattleBackground background) {
this.party = party;
this.enemies = enemies;
this.background = background;
}
public Optional<BattleBackground> getBackground() {
return Optional.ofNullable(background);
}
}
| apache-2.0 |
pmarks-net/usbnetpower8800 | usbnetpower8800.py | 3203 | #!/usr/bin/env python
# Copyright (C) 2011 Paul Marks http://www.pmarks.net/
#
# 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.
# Project homepage: http://code.google.com/p/usbnetpower8800/
#
# This is a simple command-line tool for controlling the "USB Net Power 8800"
# from Linux (etc.) using Python and PyUSB. It shows up under lsusb as:
#
# ID 067b:2303 Prolific Technology, Inc. PL2303 Serial Port
#
# But, from what I can tell, none of the serial port features are ever used,
# and all you really need is one USB control transfer for reading the current
# state, and another for setting it.
#
# The device is basically a box with a USB port and a switchable power outlet.
# It has the unfortunate property that disconnecting it from USB immediately
# kills the power, which reduces its usefulness.
#
# To install Python and usb.core on Ubuntu:
# $ sudo apt-get install python python-setuptools
# $ sudo easy_install pyusb
#
# If you have a permission error using the script and udev is used on your
# system, it can be used to apply the correct permissions. Example:
# $ cat /etc/udev/rules.d/51-usbpower.rules
# SUBSYSTEM=="usb", ATTR{idVendor}=="067b", MODE="0666", GROUP="plugdev"
import sys
import time
import usb.core
usage = (
"Controller for the USB Net Power 8800\n"
"Usage: %s on|off|toggle|reboot <seconds>|query\n")
class Power(object):
def __init__(self):
# Find the device.
self.dev = usb.core.find(idVendor=0x067b, idProduct=0x2303)
if self.dev is None:
raise ValueError("Device not found")
def IsOn(self):
# Return True if the power is currently switched on.
ret = self.dev.ctrl_transfer(0xc0, 0x01, 0x0081, 0x0000, 0x0001)
return ret[0] == 0xa0
def Set(self, on):
# If True, turn the power on, else turn it off.
code = 0xa0 if on else 0x20
self.dev.ctrl_transfer(0x40, 0x01, 0x0001, code, [])
def main(argv):
try:
cmd = argv[1].lower()
except IndexError:
cmd = ""
power = Power()
if cmd == "on":
power.Set(True)
elif cmd == "off":
power.Set(False)
elif cmd == "toggle":
power.Set(not power.IsOn())
elif cmd == "reboot":
power.Set(False)
try:
time.sleep(float(argv[2]))
except (IndexError, ValueError):
time.sleep(1.0)
power.Set(True)
elif cmd == "query":
on = power.IsOn()
sys.stdout.write("Power: %s\n" % ("on" if on else "off"))
return 0 if on else 1
else:
sys.stdout.write(usage % argv[0])
return -1
return 0
if '__main__' == __name__:
ret = main(sys.argv)
sys.exit(ret)
| apache-2.0 |
mqprichard/gasp-apns-server | src/main/java/com/cloudbees/gasp/services/Config.java | 2506 | /*
* Copyright (c) 2013 Mark Prichard, CloudBees
*
* 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.cloudbees.gasp.services;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class Config implements ServletContextListener {
private static final Logger LOGGER = LoggerFactory.getLogger(Config.class.getName());
private static String p12Pwd;
private static String token;
public static String getP12Pwd() {
return p12Pwd;
}
public static String getToken() {
return token;
}
/**
* Initialize servlet with GCM API Key: for convenience, we will load this from system property,
* environment variable or via the Jenkins build secret plugin (upload file gcm-api-key.env). In
* each case the property/variable is GCM_API_KEY
* Get the API key from http://code.google.com/apis/console
*
* @param event
*/
public void contextInitialized(ServletContextEvent event) {
try {
//TODO: (temporary fix) get device token for testing from environment
//TODO: Devices will register tokens from didRegisterForRemoteNotificationsWithDeviceToken
if ((token = System.getProperty("APNS_TOKEN")) != null) {
Datastore.register(token);
LOGGER.debug("APNS device token: " + token);
}
else {
LOGGER.error("APNS device token not set");
}
//TODO: tidy up and add Jenkins build secret support
if ((p12Pwd = System.getProperty("P12_PWD")) != null) {
LOGGER.debug("Loaded P12_PWD from system property");
}
else {
LOGGER.error("P12_PWD not set");
}
}
catch (Exception e){
e.printStackTrace();
}
}
public void contextDestroyed(ServletContextEvent event) {
}
} | apache-2.0 |
michidk/SimpleTwitchHelper | SimpleTwitchHelper/TMIApi/TMIResponse.cs | 321 | using Newtonsoft.Json;
using TwitchCSharp.Models;
namespace SimpleTwitchHelper.TMIApi
{
public class TMIResponse : TwitchResponse
{
[JsonProperty("chatter_count")]
public long ChatterCount { get; set; }
[JsonProperty("chatters")]
public Chatters Chatters { get; set; }
}
} | apache-2.0 |
ldimaggi/almighty-core | controller/search_spaces_blackbox_test.go | 6260 | package controller_test
import (
"fmt"
"reflect"
"strconv"
"strings"
"testing"
"github.com/almighty/almighty-core/app"
"github.com/almighty/almighty-core/app/test"
"github.com/almighty/almighty-core/application"
. "github.com/almighty/almighty-core/controller"
"github.com/almighty/almighty-core/gormapplication"
"github.com/almighty/almighty-core/gormsupport/cleaner"
"github.com/almighty/almighty-core/gormtestsupport"
"github.com/almighty/almighty-core/resource"
"github.com/almighty/almighty-core/space"
testsupport "github.com/almighty/almighty-core/test"
almtoken "github.com/almighty/almighty-core/token"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/goadesign/goa"
"golang.org/x/net/context"
)
type args struct {
pageOffset *string
pageLimit *int
q string
}
type expect func(*testing.T, okScenario, *app.SearchSpaceList)
type expects []expect
type okScenario struct {
name string
args args
expects expects
}
type TestSearchSpacesREST struct {
gormtestsupport.DBTestSuite
db *gormapplication.GormDB
clean func()
}
func TestRunSearchSpacesREST(t *testing.T) {
resource.Require(t, resource.Database)
suite.Run(t, &TestSearchSpacesREST{DBTestSuite: gormtestsupport.NewDBTestSuite("../config.yaml")})
}
func (rest *TestSearchSpacesREST) SetupTest() {
rest.db = gormapplication.NewGormDB(rest.DB)
rest.clean = cleaner.DeleteCreatedEntities(rest.DB)
}
func (rest *TestSearchSpacesREST) TearDownTest() {
rest.clean()
}
func (rest *TestSearchSpacesREST) SecuredController() (*goa.Service, *SearchController) {
priv, _ := almtoken.ParsePrivateKey([]byte(almtoken.RSAPrivateKey))
svc := testsupport.ServiceAsUser("Search-Service", almtoken.NewManagerWithPrivateKey(priv), testsupport.TestIdentity)
return svc, NewSearchController(svc, rest.db, rest.Configuration)
}
func (rest *TestSearchSpacesREST) UnSecuredController() (*goa.Service, *SearchController) {
svc := goa.New("Search-Service")
return svc, NewSearchController(svc, rest.db, rest.Configuration)
}
func (rest *TestSearchSpacesREST) TestSpacesSearchOK() {
// given
idents, err := createTestData(rest.db)
require.Nil(rest.T(), err)
tests := []okScenario{
{"With uppercase fullname query", args{offset("0"), limit(10), "TEST_AB"}, expects{totalCount(1)}},
{"With lowercase fullname query", args{offset("0"), limit(10), "TEST_AB"}, expects{totalCount(1)}},
{"With uppercase description query", args{offset("0"), limit(10), "DESCRIPTION FOR TEST_AB"}, expects{totalCount(1)}},
{"With lowercase description query", args{offset("0"), limit(10), "description for test_ab"}, expects{totalCount(1)}},
{"with special chars", args{offset("0"), limit(10), "&:\n!#%?*"}, expects{totalCount(0)}},
{"with * to list all", args{offset("0"), limit(10), "*"}, expects{totalCountAtLeast(len(idents))}},
{"with multi page", args{offset("0"), limit(10), "TEST"}, expects{hasLinks("Next")}},
{"with last page", args{offset(strconv.Itoa(len(idents) - 1)), limit(10), "TEST"}, expects{hasNoLinks("Next"), hasLinks("Prev")}},
{"with different values", args{offset("0"), limit(10), "TEST"}, expects{differentValues()}},
}
svc, ctrl := rest.UnSecuredController()
// when/then
for _, tt := range tests {
_, result := test.SpacesSearchOK(rest.T(), svc.Context, svc, ctrl, tt.args.pageLimit, tt.args.pageOffset, tt.args.q)
for _, expect := range tt.expects {
expect(rest.T(), tt, result)
}
}
}
func createTestData(db application.DB) ([]space.Space, error) {
names := []string{"TEST_A", "TEST_AB", "TEST_B", "TEST_C"}
for i := 0; i < 20; i++ {
names = append(names, "TEST_"+strconv.Itoa(i))
}
spaces := []space.Space{}
err := application.Transactional(db, func(app application.Application) error {
for _, name := range names {
space := space.Space{
Name: name,
Description: strings.ToTitle("description for " + name),
}
newSpace, err := app.Spaces().Create(context.Background(), &space)
if err != nil {
return err
}
spaces = append(spaces, *newSpace)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("Failed to insert testdata %v", err)
}
return spaces, nil
}
func totalCount(count int) expect {
return func(t *testing.T, scenario okScenario, result *app.SearchSpaceList) {
if got := result.Meta.TotalCount; got != count {
t.Errorf("%s got = %v, want %v", scenario.name, got, count)
}
}
}
func totalCountAtLeast(count int) expect {
return func(t *testing.T, scenario okScenario, result *app.SearchSpaceList) {
got := result.Meta.TotalCount
if !(got >= count) {
t.Errorf("%s got %v, wanted at least %v", scenario.name, got, count)
}
}
}
func hasLinks(linkNames ...string) expect {
return func(t *testing.T, scenario okScenario, result *app.SearchSpaceList) {
for _, linkName := range linkNames {
link := linkName
if reflect.Indirect(reflect.ValueOf(result.Links)).FieldByName(link).IsNil() {
t.Errorf("%s got empty link, wanted %s", scenario.name, link)
}
}
}
}
func hasNoLinks(linkNames ...string) expect {
return func(t *testing.T, scenario okScenario, result *app.SearchSpaceList) {
for _, linkName := range linkNames {
if !reflect.Indirect(reflect.ValueOf(result.Links)).FieldByName(linkName).IsNil() {
t.Errorf("%s got link, wanted empty %s", scenario.name, linkName)
}
}
}
}
func differentValues() expect {
return func(t *testing.T, scenario okScenario, result *app.SearchSpaceList) {
var prev *app.Space
for i := range result.Data {
s := result.Data[i]
if prev == nil {
prev = s
} else {
if *prev.Attributes.Name == *s.Attributes.Name {
t.Errorf("%s got equal name, wanted different %s", scenario.name, *s.Attributes.Name)
}
if *prev.Attributes.Description == *s.Attributes.Description {
t.Errorf("%s got equal description, wanted different %s", scenario.name, *s.Attributes.Description)
}
if *prev.ID == *s.ID {
t.Errorf("%s got equal ID, wanted different %s", scenario.name, *s.ID)
}
if prev.Type != s.Type {
t.Errorf("%s got non equal Type, wanted same %s", scenario.name, s.Type)
}
}
}
}
}
func limit(n int) *int {
return &n
}
func offset(n string) *string {
return &n
}
| apache-2.0 |
kiritbasu/datacollector | container/src/test/java/com/streamsets/datacollector/store/impl/TestFilePipelineStoreTask.java | 16393 | /**
* 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 com.streamsets.datacollector.store.impl;
import static org.junit.Assert.assertEquals;
import com.streamsets.datacollector.config.DataRuleDefinition;
import com.streamsets.datacollector.config.MetricElement;
import com.streamsets.datacollector.config.MetricType;
import com.streamsets.datacollector.config.MetricsRuleDefinition;
import com.streamsets.datacollector.config.PipelineConfiguration;
import com.streamsets.datacollector.config.RuleDefinitions;
import com.streamsets.datacollector.config.StageConfiguration;
import com.streamsets.datacollector.config.ThresholdType;
import com.streamsets.datacollector.execution.PipelineStateStore;
import com.streamsets.datacollector.main.RuntimeInfo;
import com.streamsets.datacollector.runner.MockStages;
import com.streamsets.datacollector.stagelibrary.StageLibraryTask;
import com.streamsets.datacollector.store.PipelineInfo;
import com.streamsets.datacollector.store.PipelineStoreException;
import com.streamsets.datacollector.store.PipelineStoreTask;
import com.streamsets.datacollector.store.impl.CachePipelineStoreTask;
import com.streamsets.datacollector.store.impl.FilePipelineStoreTask;
import com.streamsets.datacollector.util.ContainerError;
import com.streamsets.datacollector.util.LockCache;
import com.streamsets.datacollector.util.LockCacheModule;
import dagger.ObjectGraph;
import dagger.Provides;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import javax.inject.Singleton;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class TestFilePipelineStoreTask {
private static final String DEFAULT_PIPELINE_NAME = "xyz";
private static final String DEFAULT_PIPELINE_DESCRIPTION = "Default Pipeline";
private static final String SYSTEM_USER = "system";
protected PipelineStoreTask store;
@dagger.Module(injects = {FilePipelineStoreTask.class, LockCache.class},
includes = LockCacheModule.class)
public static class Module {
public Module() {
}
@Provides
@Singleton
public RuntimeInfo provideRuntimeInfo() {
RuntimeInfo mock = Mockito.mock(RuntimeInfo.class);
Mockito.when(mock.getDataDir()).thenReturn("target/" + UUID.randomUUID());
return mock;
}
@Provides
@Singleton
public StageLibraryTask provideStageLibrary() {
return MockStages.createStageLibrary();
}
@Provides
@Singleton
public PipelineStateStore providePipelineStateStore() {
return null;
}
}
@Before
public void setUp() {
ObjectGraph dagger = ObjectGraph.create(new Module());
FilePipelineStoreTask filePipelineStoreTask = dagger.get(FilePipelineStoreTask.class);
store = new CachePipelineStoreTask(filePipelineStoreTask, new LockCache<String>());
}
@After
public void tearDown() {
store = null;
}
@Test
public void testStoreNoDefaultPipeline() throws Exception {
try {
//creating store dir
store.init();
Assert.assertTrue(store.getPipelines().isEmpty());
} finally {
store.stop();
}
try {
//store dir already exists
store.init();
Assert.assertTrue(store.getPipelines().isEmpty());
} finally {
store.stop();
}
}
@Test
public void testCreateDelete() throws Exception {
try {
store.init();
Assert.assertEquals(0, store.getPipelines().size());
store.create("foo", "a", "A");
Assert.assertEquals(1, store.getPipelines().size());
store.save("foo2", "a", "A", "", store.load("a", "0"));
assertEquals("foo2", store.getPipelines().get(0).getLastModifier());
Assert.assertEquals("a", store.getInfo("a").getName());
store.delete("a");
Assert.assertEquals(0, store.getPipelines().size());
} finally {
store.stop();
}
}
@Test(expected = PipelineStoreException.class)
public void testCreateExistingPipeline() throws Exception {
try {
store.init();
store.create("foo", "a", "A");
store.create("foo", "a", "A");
} finally {
store.stop();
}
}
@Test(expected = PipelineStoreException.class)
public void testDeleteNotExisting() throws Exception {
try {
store.init();
store.delete("a");
} finally {
store.stop();
}
}
@Test(expected = PipelineStoreException.class)
public void testSaveNotExisting() throws Exception {
try {
store.init();
createDefaultPipeline(store);
PipelineConfiguration pc = store.load(DEFAULT_PIPELINE_NAME, FilePipelineStoreTask.REV);
store.save("foo", "a", null, null, pc);
} finally {
store.stop();
}
}
@Test(expected = PipelineStoreException.class)
public void testSaveWrongUuid() throws Exception {
try {
store.init();
createDefaultPipeline(store);
PipelineConfiguration pc = store.load(DEFAULT_PIPELINE_NAME, FilePipelineStoreTask.REV);
pc.setUuid(UUID.randomUUID());
store.save("foo", DEFAULT_PIPELINE_NAME, null, null, pc);
} finally {
store.stop();
}
}
@Test(expected = PipelineStoreException.class)
public void testLoadNotExisting() throws Exception {
try {
store.init();
store.load("a", null);
} finally {
store.stop();
}
}
@Test(expected = PipelineStoreException.class)
public void testHistoryNotExisting() throws Exception {
try {
store.init();
store.getHistory("a");
} finally {
store.stop();
}
}
private PipelineConfiguration createPipeline(UUID uuid) {
PipelineConfiguration pc = MockStages.createPipelineConfigurationSourceTarget();
pc.setUuid(uuid);
return pc;
}
@Test
public void testSave() throws Exception {
try {
store.init();
createDefaultPipeline(store);
PipelineInfo info1 = store.getInfo(DEFAULT_PIPELINE_NAME);
PipelineConfiguration pc0 = store.load(DEFAULT_PIPELINE_NAME, FilePipelineStoreTask.REV);
pc0 = createPipeline(pc0.getUuid());
Thread.sleep(5);
store.save("foo", DEFAULT_PIPELINE_NAME, null, null, pc0);
PipelineInfo info2 = store.getInfo(DEFAULT_PIPELINE_NAME);
Assert.assertEquals(info1.getCreated(), info2.getCreated());
Assert.assertEquals(info1.getCreator(), info2.getCreator());
Assert.assertEquals(info1.getName(), info2.getName());
Assert.assertEquals(info1.getLastRev(), info2.getLastRev());
Assert.assertEquals("foo", info2.getLastModifier());
Assert.assertTrue(info2.getLastModified().getTime() > info1.getLastModified().getTime());
} finally {
store.stop();
}
}
@Test
public void testSaveAndLoad() throws Exception {
try {
store.init();
createDefaultPipeline(store);
PipelineConfiguration pc = store.load(DEFAULT_PIPELINE_NAME, FilePipelineStoreTask.REV);
Assert.assertTrue(pc.getStages().isEmpty());
UUID uuid = pc.getUuid();
pc = createPipeline(pc.getUuid());
pc = store.save("foo", DEFAULT_PIPELINE_NAME, null, null, pc);
UUID newUuid = pc.getUuid();
Assert.assertNotEquals(uuid, newUuid);
PipelineConfiguration pc2 = store.load(DEFAULT_PIPELINE_NAME, FilePipelineStoreTask.REV);
Assert.assertFalse(pc2.getStages().isEmpty());
Assert.assertEquals(pc.getUuid(), pc2.getUuid());
PipelineInfo info = store.getInfo(DEFAULT_PIPELINE_NAME);
Assert.assertEquals(pc.getUuid(), info.getUuid());
} finally {
store.stop();
}
}
@Test
public void testStoreAndRetrieveRules() throws PipelineStoreException {
store.init();
createDefaultPipeline(store);
RuleDefinitions ruleDefinitions = store.retrieveRules(DEFAULT_PIPELINE_NAME,
FilePipelineStoreTask.REV);
Assert.assertNotNull(ruleDefinitions);
Assert.assertTrue(ruleDefinitions.getDataRuleDefinitions().isEmpty());
Assert.assertTrue(ruleDefinitions.getMetricsRuleDefinitions().isEmpty());
List<MetricsRuleDefinition> metricsRuleDefinitions = ruleDefinitions.getMetricsRuleDefinitions();
metricsRuleDefinitions.add(new MetricsRuleDefinition("m1", "m1", "a", MetricType.COUNTER,
MetricElement.COUNTER_COUNT, "p", false, true));
metricsRuleDefinitions.add(new MetricsRuleDefinition("m2", "m2", "a", MetricType.TIMER,
MetricElement.TIMER_M15_RATE, "p", false, true));
metricsRuleDefinitions.add(new MetricsRuleDefinition("m3", "m3", "a", MetricType.HISTOGRAM,
MetricElement.HISTOGRAM_MEAN, "p", false, true));
List<DataRuleDefinition> dataRuleDefinitions = ruleDefinitions.getDataRuleDefinitions();
dataRuleDefinitions.add(new DataRuleDefinition("a", "a", "a", 20, 300, "x", true, "c", ThresholdType.COUNT, "200",
1000, true, false, true));
dataRuleDefinitions.add(new DataRuleDefinition("b", "b", "b", 20, 300, "x", true, "c", ThresholdType.COUNT, "200",
1000, true, false, true));
dataRuleDefinitions.add(new DataRuleDefinition("c", "c", "c", 20, 300, "x", true, "c", ThresholdType.COUNT, "200",
1000, true, false, true));
store.storeRules(DEFAULT_PIPELINE_NAME, FilePipelineStoreTask.REV, ruleDefinitions);
RuleDefinitions actualRuleDefinitions = store.retrieveRules(DEFAULT_PIPELINE_NAME,
FilePipelineStoreTask.REV);
Assert.assertTrue(ruleDefinitions == actualRuleDefinitions);
}
@Test
public void testStoreMultipleCopies() throws PipelineStoreException {
/*This test case mimicks a use case where 2 users connect to the same data collector instance
* using different browsers and modify the same rule definition. The user who saves last runs into an exception.
* The user is forced to reload, reapply changes and save*/
store.init();
createDefaultPipeline(store);
RuleDefinitions ruleDefinitions1 = store.retrieveRules(DEFAULT_PIPELINE_NAME,
FilePipelineStoreTask.REV);
RuleDefinitions tempRuleDef = store.retrieveRules(DEFAULT_PIPELINE_NAME,
FilePipelineStoreTask.REV);
//Mimick two different clients [browsers] retrieving from the store
RuleDefinitions ruleDefinitions2 = new RuleDefinitions(tempRuleDef.getMetricsRuleDefinitions(),
tempRuleDef.getDataRuleDefinitions(), tempRuleDef.getEmailIds(), tempRuleDef.getUuid());
List<MetricsRuleDefinition> metricsRuleDefinitions = ruleDefinitions1.getMetricsRuleDefinitions();
metricsRuleDefinitions.add(new MetricsRuleDefinition("m1", "m1", "a", MetricType.COUNTER,
MetricElement.COUNTER_COUNT, "p", false, true));
metricsRuleDefinitions.add(new MetricsRuleDefinition("m2", "m2", "a", MetricType.TIMER,
MetricElement.TIMER_M15_RATE, "p", false, true));
metricsRuleDefinitions.add(new MetricsRuleDefinition("m3", "m3", "a", MetricType.HISTOGRAM,
MetricElement.HISTOGRAM_MEAN, "p", false, true));
List<DataRuleDefinition> dataRuleDefinitions = ruleDefinitions2.getDataRuleDefinitions();
dataRuleDefinitions.add(new DataRuleDefinition("a", "a", "a", 20, 300, "x", true, "c", ThresholdType.COUNT, "200",
1000, true, false, true));
dataRuleDefinitions.add(new DataRuleDefinition("b", "b", "b", 20, 300, "x", true, "c", ThresholdType.COUNT, "200",
1000, true, false, true));
dataRuleDefinitions.add(new DataRuleDefinition("c", "c", "c", 20, 300, "x", true, "c", ThresholdType.COUNT, "200",
1000, true, false, true));
//store ruleDefinition1
store.storeRules(DEFAULT_PIPELINE_NAME, FilePipelineStoreTask.REV, ruleDefinitions1);
//attempt storing rule definition 2, should fail
try {
store.storeRules(DEFAULT_PIPELINE_NAME, FilePipelineStoreTask.REV, ruleDefinitions2);
Assert.fail("Expected PipelineStoreException as the rule definition being saved is not the latest copy.");
} catch (PipelineStoreException e) {
Assert.assertEquals(e.getErrorCode(), ContainerError.CONTAINER_0205);
}
//reload, modify and and then store
ruleDefinitions2 = store.retrieveRules(DEFAULT_PIPELINE_NAME,
FilePipelineStoreTask.REV);
dataRuleDefinitions = ruleDefinitions2.getDataRuleDefinitions();
dataRuleDefinitions.add(new DataRuleDefinition("a", "a", "a", 20, 300, "x", true, "c", ThresholdType.COUNT, "200",
1000, true, false, true));
dataRuleDefinitions.add(new DataRuleDefinition("b", "b", "b", 20, 300, "x", true, "c", ThresholdType.COUNT, "200",
1000, true, false, true));
dataRuleDefinitions.add(new DataRuleDefinition("c", "c", "c", 20, 300, "x", true, "c", ThresholdType.COUNT, "200",
1000, true, false, true));
store.storeRules(DEFAULT_PIPELINE_NAME, FilePipelineStoreTask.REV, ruleDefinitions2);
RuleDefinitions actualRuleDefinitions = store.retrieveRules(DEFAULT_PIPELINE_NAME,
FilePipelineStoreTask.REV);
Assert.assertTrue(ruleDefinitions2 == actualRuleDefinitions);
}
private void createDefaultPipeline(PipelineStoreTask store) throws PipelineStoreException {
store.create(SYSTEM_USER, DEFAULT_PIPELINE_NAME, DEFAULT_PIPELINE_DESCRIPTION);
}
@Test
@SuppressWarnings("unchecked")
public void testUiInfoSave() throws Exception {
try {
store.init();
createDefaultPipeline(store);
PipelineConfiguration pc = store.load(DEFAULT_PIPELINE_NAME, FilePipelineStoreTask.REV);
Assert.assertTrue(pc.getUiInfo().isEmpty());
// add a stage to pipeline
pc.getStages().add(new StageConfiguration("i", "l", "n", 1, Collections.EMPTY_LIST, Collections.EMPTY_MAP,
Collections.EMPTY_LIST, Collections.EMPTY_LIST));
// set some uiInfo at pipeline and stage level and dave
pc.getUiInfo().put("a", "A");
pc.getUiInfo().put("b", "B");
pc.getStages().get(0).getUiInfo().put("ia", "IA");
pc.getStages().get(0).getUiInfo().put("ib", "IB");
pc = store.save("foo", DEFAULT_PIPELINE_NAME, null, null, pc);
// verify uiInfo stays after save
Assert.assertEquals(2, pc.getUiInfo().size());
Assert.assertEquals("A", pc.getUiInfo().get("a"));
Assert.assertEquals("B", pc.getUiInfo().get("b"));
Assert.assertEquals(2, pc.getStages().get(0).getUiInfo().size());
Assert.assertEquals("IA", pc.getStages().get(0).getUiInfo().get("ia"));
Assert.assertEquals("IB", pc.getStages().get(0).getUiInfo().get("ib"));
// load and verify uiInfo stays
pc = store.load(DEFAULT_PIPELINE_NAME, null);
Assert.assertEquals(2, pc.getUiInfo().size());
Assert.assertEquals("A", pc.getUiInfo().get("a"));
Assert.assertEquals("B", pc.getUiInfo().get("b"));
Assert.assertEquals(2, pc.getStages().get(0).getUiInfo().size());
Assert.assertEquals("IA", pc.getStages().get(0).getUiInfo().get("ia"));
Assert.assertEquals("IB", pc.getStages().get(0).getUiInfo().get("ib"));
// extract uiInfo, modify and save uiInfo only
Map<String, Object> uiInfo = FilePipelineStoreTask.extractUiInfo(pc);
((Map)uiInfo.get(":pipeline:")).clear();
((Map)uiInfo.get(":pipeline:")).put("a", "AA");
((Map)uiInfo.get("i")).clear();
((Map)uiInfo.get("i")).put("ia", "IIAA");
store.saveUiInfo(DEFAULT_PIPELINE_NAME, null, uiInfo);
pc = store.load(DEFAULT_PIPELINE_NAME, null);
Assert.assertNotNull(pc.getUiInfo());
Assert.assertEquals(1, pc.getUiInfo().size());
Assert.assertEquals("AA", pc.getUiInfo().get("a"));
Assert.assertEquals(1, pc.getStages().get(0).getUiInfo().size());
Assert.assertEquals("IIAA",pc.getStages().get(0).getUiInfo().get("ia"));
} finally {
store.stop();
}
}
}
| apache-2.0 |
wso2/carbon-identity-framework | components/authentication-framework/org.wso2.carbon.identity.application.authentication.framework/src/main/java/org/wso2/carbon/identity/application/authentication/framework/config/loader/UIBasedConfigurationLoader.java | 15437 | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.identity.application.authentication.framework.config.loader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator;
import org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig;
import org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig;
import org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig;
import org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig;
import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.AuthenticationGraph;
import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsGraphBuilder;
import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsGraphBuilderFactory;
import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext;
import org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException;
import org.wso2.carbon.identity.application.authentication.framework.internal.FrameworkServiceComponent;
import org.wso2.carbon.identity.application.authentication.framework.internal.FrameworkServiceDataHolder;
import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants;
import org.wso2.carbon.identity.application.common.model.AuthenticationStep;
import org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig;
import org.wso2.carbon.identity.application.common.model.IdentityProvider;
import org.wso2.carbon.identity.application.common.model.LocalAndOutboundAuthenticationConfig;
import org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig;
import org.wso2.carbon.identity.application.common.model.RequestPathAuthenticatorConfig;
import org.wso2.carbon.identity.application.common.model.ServiceProvider;
import org.wso2.carbon.identity.application.common.model.script.AuthenticationScriptConfig;
import org.wso2.carbon.identity.application.mgt.ApplicationConstants;
import org.wso2.carbon.idp.mgt.IdentityProviderManagementException;
import org.wso2.carbon.idp.mgt.IdentityProviderManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Sequence Configuration loader, loads the sequence configuration from the database.
* <p>
* History: The main logic was moved from @see
* {@link org.wso2.carbon.identity.application.authentication.framework.config.builder.UIBasedConfigurationBuilder},
* This is one step to move away from Singleton pattern used throughout the code.
* Few other singletons should be removed and passed relevant information as setters or constructor arguments here.
*/
public class UIBasedConfigurationLoader implements SequenceLoader {
private static final Log log = LogFactory.getLog(UIBasedConfigurationLoader.class);
@Override
public SequenceConfig getSequenceConfig(AuthenticationContext context, Map<String, String[]> parameterMap,
ServiceProvider serviceProvider) throws FrameworkException {
String tenantDomain = context.getTenantDomain();
AuthenticationStep[] authenticationSteps = null;
LocalAndOutboundAuthenticationConfig localAndOutboundAuthenticationConfig = serviceProvider
.getLocalAndOutBoundAuthenticationConfig();
if (localAndOutboundAuthenticationConfig.getAuthenticationSteps() != null
&& localAndOutboundAuthenticationConfig.getAuthenticationSteps().length > 0) {
//Use the default steps when there are no chains configured.
authenticationSteps = localAndOutboundAuthenticationConfig.getAuthenticationSteps();
}
SequenceConfig sequenceConfig = getSequence(serviceProvider, tenantDomain, authenticationSteps);
//Use script based evaluation if script is present.
if (isAuthenticationScriptBasedSequence(localAndOutboundAuthenticationConfig)) {
//Clear the sequenceConfig step map, so that it will be re-populated by Dynamic execution
Map<Integer, StepConfig> originalStepConfigMap = new HashMap<>(sequenceConfig.getStepMap());
Map<Integer, StepConfig> stepConfigMapCopy = new HashMap<>();
originalStepConfigMap.forEach((k, v) -> stepConfigMapCopy.put(k, new StepConfig(v)));
sequenceConfig.getStepMap().clear();
JsGraphBuilderFactory jsGraphBuilderFactory = FrameworkServiceDataHolder.getInstance()
.getJsGraphBuilderFactory();
JsGraphBuilder jsGraphBuilder = jsGraphBuilderFactory.createBuilder(context, stepConfigMapCopy);
context.setServiceProviderName(serviceProvider.getApplicationName());
AuthenticationGraph graph = jsGraphBuilder
.createWith(localAndOutboundAuthenticationConfig.getAuthenticationScriptConfig().getContent())
.build();
graph.setEnabled(localAndOutboundAuthenticationConfig.getAuthenticationScriptConfig().isEnabled());
sequenceConfig.setAuthenticationGraph(graph);
graph.setStepMap(originalStepConfigMap);
}
return sequenceConfig;
}
private boolean isAuthenticationScriptBasedSequence(LocalAndOutboundAuthenticationConfig
localAndOutboundAuthenticationConfig) {
if (ApplicationConstants.AUTH_TYPE_FLOW.equals(localAndOutboundAuthenticationConfig.getAuthenticationType()) ||
ApplicationConstants.AUTH_TYPE_DEFAULT.equals(
localAndOutboundAuthenticationConfig.getAuthenticationType())) {
AuthenticationScriptConfig authenticationScriptConfig = localAndOutboundAuthenticationConfig
.getAuthenticationScriptConfig();
return authenticationScriptConfig != null && authenticationScriptConfig.isEnabled();
}
return false;
}
/**
* This is maintained for backward compatibility and should be called form UIBasedConfigurationBuilder only.
*
* @param serviceProvider
* @param tenantDomain
* @return
* @throws FrameworkException
* @see org.wso2.carbon.identity.application.authentication.framework.config.builder.UIBasedConfigurationBuilder
* @deprecated Please do not use this for any development as this is maintained for backward compatibility.
*/
@Deprecated
public SequenceConfig getSequence(ServiceProvider serviceProvider, String tenantDomain) throws FrameworkException {
if (serviceProvider == null) {
throw new FrameworkException("ServiceProvider cannot be null");
}
AuthenticationStep[] authenticationSteps = serviceProvider.getLocalAndOutBoundAuthenticationConfig()
.getAuthenticationSteps();
return getSequence(serviceProvider, tenantDomain, authenticationSteps);
}
/**
* Loads the sequence in the way previous loading mechanism used to work.
* Please do not use this for any new development.
*
* @param serviceProvider
* @param tenantDomain
* @param authenticationSteps
* @return
* @throws FrameworkException
*/
public SequenceConfig getSequence(ServiceProvider serviceProvider, String tenantDomain,
AuthenticationStep[] authenticationSteps) throws FrameworkException {
if (serviceProvider == null) {
throw new FrameworkException("ServiceProvider cannot be null");
}
SequenceConfig sequenceConfig = new SequenceConfig();
sequenceConfig.setApplicationId(serviceProvider.getApplicationName());
sequenceConfig.setApplicationConfig(new ApplicationConfig(serviceProvider));
// setting request path authenticators
loadRequestPathAuthenticators(sequenceConfig, serviceProvider);
int stepOrder = 0;
if (authenticationSteps == null) {
return sequenceConfig;
}
// for each configured step
for (AuthenticationStep authenticationStep : authenticationSteps) {
try {
stepOrder = authenticationStep.getStepOrder();
} catch (NumberFormatException e) {
stepOrder++;
}
// create a step configuration object
StepConfig stepConfig = createStepConfigurationObject(stepOrder, authenticationStep);
// loading Federated Authenticators
loadFederatedAuthenticators(authenticationStep, stepConfig, tenantDomain);
// loading local authenticators
loadLocalAuthenticators(authenticationStep, stepConfig);
sequenceConfig.getStepMap().put(stepOrder, stepConfig);
}
return sequenceConfig;
}
protected StepConfig createStepConfigurationObject(int stepOrder, AuthenticationStep authenticationStep) {
StepConfig stepConfig = new StepConfig();
stepConfig.setOrder(stepOrder);
stepConfig.setSubjectAttributeStep(authenticationStep.isAttributeStep());
stepConfig.setSubjectIdentifierStep(authenticationStep.isSubjectStep());
return stepConfig;
}
protected void loadRequestPathAuthenticators(SequenceConfig sequenceConfig, ServiceProvider serviceProvider) {
if (serviceProvider.getRequestPathAuthenticatorConfigs() != null
&& serviceProvider.getRequestPathAuthenticatorConfigs().length > 0) {
List<AuthenticatorConfig> requestPathAuthenticators = new ArrayList<AuthenticatorConfig>();
RequestPathAuthenticatorConfig[] reqAuths = serviceProvider.getRequestPathAuthenticatorConfigs();
// for each request path authenticator
for (RequestPathAuthenticatorConfig reqAuth : reqAuths) {
AuthenticatorConfig authConfig = new AuthenticatorConfig();
String authenticatorName = reqAuth.getName();
authConfig.setName(authenticatorName);
authConfig.setEnabled(true);
// iterate through each system authentication config
for (ApplicationAuthenticator appAuthenticator : FrameworkServiceComponent.getAuthenticators()) {
if (authenticatorName.equalsIgnoreCase(appAuthenticator.getName())) {
authConfig.setApplicationAuthenticator(appAuthenticator);
break;
}
}
requestPathAuthenticators.add(authConfig);
}
sequenceConfig.setReqPathAuthenticators(requestPathAuthenticators);
}
}
protected void loadFederatedAuthenticators(AuthenticationStep authenticationStep, StepConfig stepConfig,
String tenantDomain) throws FrameworkException {
IdentityProvider[] federatedIDPs = authenticationStep.getFederatedIdentityProviders();
if (federatedIDPs != null) {
// for each idp in the step
for (IdentityProvider federatedIDP : federatedIDPs) {
FederatedAuthenticatorConfig federatedAuthenticator = federatedIDP.getDefaultAuthenticatorConfig();
//When loading the federated IDP configuration from default.xml file in service-providers, we need to
// retrieve the federated IDP and load
if (federatedAuthenticator == null) {
try {
federatedAuthenticator = IdentityProviderManager.getInstance()
.getIdPByName(federatedIDP.getIdentityProviderName(), tenantDomain)
.getDefaultAuthenticatorConfig();
} catch (IdentityProviderManagementException e) {
throw new FrameworkException(
"Failed to load the default authenticator for IDP : " + federatedIDP
.getIdentityProviderName(), e);
}
}
String actualAuthenticatorName = federatedAuthenticator.getName();
// assign it to the step
loadStepAuthenticator(stepConfig, federatedIDP, actualAuthenticatorName);
}
}
}
protected void loadLocalAuthenticators(AuthenticationStep authenticationStep, StepConfig stepConfig) {
LocalAuthenticatorConfig[] localAuthenticators = authenticationStep.getLocalAuthenticatorConfigs();
if (localAuthenticators != null) {
IdentityProvider localIdp = new IdentityProvider();
localIdp.setIdentityProviderName(FrameworkConstants.LOCAL_IDP_NAME);
// assign it to the step
for (LocalAuthenticatorConfig localAuthenticator : localAuthenticators) {
String actualAuthenticatorName = localAuthenticator.getName();
loadStepAuthenticator(stepConfig, localIdp, actualAuthenticatorName);
}
}
}
private void loadStepAuthenticator(StepConfig stepConfig, IdentityProvider idp, String authenticatorName) {
AuthenticatorConfig authenticatorConfig = null;
// check if authenticator already exists
for (AuthenticatorConfig authConfig : stepConfig.getAuthenticatorList()) {
if (authenticatorName.equals(authConfig.getName())) {
authenticatorConfig = authConfig;
break;
}
}
if (authenticatorConfig == null) {
authenticatorConfig = new AuthenticatorConfig();
authenticatorConfig.setName(authenticatorName);
for (ApplicationAuthenticator appAuthenticator : FrameworkServiceComponent.getAuthenticators()) {
if (authenticatorName.equalsIgnoreCase(appAuthenticator.getName())) {
authenticatorConfig.setApplicationAuthenticator(appAuthenticator);
break;
}
}
stepConfig.getAuthenticatorList().add(authenticatorConfig);
}
if (idp != null) {
authenticatorConfig.getIdpNames().add(idp.getIdentityProviderName());
authenticatorConfig.getIdps().put(idp.getIdentityProviderName(), idp);
}
if (!stepConfig.isMultiOption() && (stepConfig.getAuthenticatorList().size() > 1
|| authenticatorConfig.getIdps().size() > 1)) {
stepConfig.setMultiOption(true);
}
}
}
| apache-2.0 |
aramisjohnson/rook | pkg/cephmgr/client/test/image.go | 1188 | /*
Copyright 2016 The Rook 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.
*/
package test
import "github.com/rook/rook/pkg/cephmgr/client"
type MockImage struct {
MockName string
MockStat func() (info *client.ImageInfo, err error)
MockRemove func() error
}
func (i *MockImage) Open(args ...interface{}) error {
return nil
}
func (i *MockImage) Close() error {
return nil
}
func (i *MockImage) Remove() error {
if i.MockRemove != nil {
return i.MockRemove()
}
return nil
}
func (i *MockImage) Stat() (info *client.ImageInfo, err error) {
if i.MockStat != nil {
return i.MockStat()
}
return nil, nil
}
func (i *MockImage) Name() string {
return i.MockName
}
| apache-2.0 |
vikene/parallax | myjava.js | 23266 | /*!
jsAnim: Powerful javascript animation
--------------------------------------------
Copyright 2009 Kevin Dolan
-http://www.thekevindolan.com
Code licensed under the MIT license
-See license.txt
v0.2
*/
//These vars are used to hold all jsAnimManagers
var jsAnimManagers = new Array();
var jsAnimManagerId = 0;
/*! public, accessible
jsAnimManager object constructor
Used by end-user to manage jsAnim objects
Params:
-[timestep] : time between frames, defaults to 40
*/
function jsAnimManager(timestep) {
jsAnimManagers[jsAnimManagerId] = this;
this.myId = jsAnimManagerId;
jsAnimManagerId++;
if(timestep)
this.timestep = timestep;
else
this.timestep = 40;
this.paused = false;
this.animObjects = new Array();
this.index = 0;
//Used internally to process a single frame of all active animations
this.step = function() {
if(!this.paused) {
for(x in this.animObjects) {
this.animObjects[x].step();
}
setTimeout("jsAnimManagers["+this.myId+"].step()",this.timestep);
}
};
//Used internally to kill a jsAnimObject
this.kill = function(id) {
delete this.animObjects[id];
};
/*! public
Called to create a new animation object
Params:
-objId : id of object being controlled
*/
this.createAnimObject = function(objId) {
var el = document.getElementById(objId);
var id = this.index;
this.animObjects[id] = new jsAnimObject(el, id, this);
this.index++;
return this.animObjects[id];
};
/*! public
Called to pause the animation manager
*/
this.pause = function() {
this.paused = true;
};
/*! public
Called to unpause the animation manager
*/
this.resume = function() {
this.paused = false;
this.step();
};
/*! public
Called to set the appropriate style values to allow position to be controlled by jsAnim
Params:
-objId : id of object to be registered
-[fixed] : fixed positioning, false to absolute fixed, defaults to false
*/
this.registerPosition = function(objId, fixed) {
var el = document.getElementById(objId);
var width = el.offsetWidth;
var height = el.offsetHeight;
if(fixed)
el.style.position = "fixed";
else
el.style.position = "absolute";
el.style.top = "0px";
el.style.left = "50%";
el.halfWidth = Math.floor(width/2);
el.halfHeight = Math.floor(height/2);
el.style.marginLeft = (-el.halfWidth)+"px";
el.style.marginTop = (-el.halfHeight)+"px";
el.positionRegistered = true;
/*! public
Called to manually set the position of this object
*/
el.setPosition = function(x, y) {
this.style.marginLeft = (x - this.halfWidth)+"px";
this.style.marginTop = (y - this.halfHeight)+"px";
};
};
this.step();
return true;
}
/*! accesible
jsAnimObject object constructor
Used internally to hold the state of a single animation manager
Params:
-obj : object being animated
*/
function jsAnimObject(obj, id, manager) {
this.id = id;
this.obj = obj;
this.paused = false;
this.animEntries = new Array();
this.animLoops = new Array();
this.current = 0;
this.manager = manager;
this.step = function() {
if(!this.paused) {
//Ugly code to get only the first element in the array
for(x in this.animEntries) {
var finished = this.animEntries[x].step();
if(finished) {
this.animLoops[x]--;
this.animEntries[x].current = 0;
this.animEntries[x].onLoop();
}
if(this.animLoops[x] == 0) {
this.animEntries[x].onComplete();
delete this.animEntries[x];
}
break;
}
}
};
/*! public
Called to add an animation to the chain
Params:
-params : a collection in the containing the following elements
- property : the Prop object to animate
- [from] : optional from value, if unspecified current value is used
- to : the value to animate to
- duration : the length of time this animation should take
- [ease] : the jsAnimEase object to use, if unspecified linear will be used
- [loop] : the number of times to loop the animation, negative values are infinite, if unspecified 1 will be used
- [onLoop] : the callback function for loop completion
- [onComplete] : the callback function for animation completion
*/
this.add = function(params) {
var property = params.property;
var from = params.from
var to = params.to;
var duration = params.duration;
if(params.ease)
var ease = params.ease;
else
var ease = jsAnimEase.linear;
if(params.loop)
var loop = params.loop;
else
var loop = 1;
if(params.onLoop)
var onLoop = params.onLoop;
else
var onLoop = function() {};
if(params.onComplete)
var onComplete = params.onComplete;
else
var onComplete = function() {};
this.animEntries[this.current] = new jsAnimEntry(this.obj, property, from, to, duration, this.manager.timestep, ease, onLoop, onComplete);
this.animLoops[this.current] = loop;
this.current++;
};
/*! public
Called to skip the current animation, can be used to exit an infinite loop
*/
this.skip = function() {
//Ugly code to get only the first element in the array
for(x in this.animEntries) {
delete this.animEntries[x];
break;
}
};
/*! public
Called to pause this animator
*/
this.pause = function() {
this.paused = true;
};
/*! public
Called to resum this animator
*/
this.resume = function() {
this.paused = false;
};
/*! public
Called to kill this animator
*/
this.kill = function() {
this.manager.kill(this.id);
};
return true;
}
/*! public, accesible
Pos object constructor
Called to store an x and y coordinate representing an object's center
according to the jsAnim coordinate system
Params:
-x : x coordinate, 0 is center, negative is left, positive is right
-y : y coordinate, 0 is top, positive id below
*/
function Pos(x, y) {
//public
this.x = x;
//public
this.y = y;
return true;
}
/*! public, accesible
Dim object constructor
Called to store a width/height dimension
Params:
-w : width
-h : height
*/
function Dim(w, h) {
//public
this.w = w;
//public
this.h = h;
return true;
}
/*! public, accesible
Col object constructor
Called to store an RGB color
Params:
-r : red value (0,255)
-g : green value (0,255)
-b : blue value (0,255)
*/
function Col(r, g, b) {
//public
this.r = r;
//public
this.g = g;
//public
this.b = b;
return true;
}
/*!
jsAnimEntry object constructor
Used internally to hold the state of single animation entry
Params:
-property : jsAnimProp object
-from : initial value
-to : end value
-duration : total time of animation (ms)
-ease : jsAnimEase object
-timestep : the timestep value of the animation manager
-onLoop : called after each loop
-onComplete : called after completion
*/
function jsAnimEntry(obj, property, from, to, duration, timestep, ease, onLoop, onComplete) {
this.obj = obj;
this.property = property;
this.from = from;
this.to = to;
this.duration = duration;
this.timestep = timestep;
this.ease = ease;
this.current = 0;
this.onLoop = onLoop;
this.onComplete = onComplete;
/*!
Used internally to move the object one step
Returns : true if this anim entry has completed, false otherwise
*/
this.step = function() {
if(!this.from)
this.from = this.property.current(this.obj);
if(this.current >= this.duration) {
var p = this.ease.transform(1);
this.property.update(this.obj, this.from, this.to, p);
return true;
}
else {
var t = this.current / this.duration;
var p = this.ease.transform(t);
this.property.update(this.obj, this.from, this.to, p);
this.current += this.timestep;
return false;
}
};
return true;
}
/*! public
jsAnimEase objects
Used to control easing
Methods:
transform : Transform a number 0-1 representing a time proportion
to a new number 0-1 representing a progress proportion
*/
var jsAnimEase = {
/*!public
Constant Rate
*/
linear : {
transform : function(t) {
return t;
}
},
/*!public
Starts slow, then speeds up
*/
parabolicPos : {
transform : function(t) {
return t * t;
}
},
/*!public
Starts fast, then slows down
*/
parabolicNeg : {
transform : function(t) {
return 1 - (t-1) * (t-1);
}
},
/*!public
Overshoots target then returns to target
Params:
-g : overshoot amount [0-1]
*/
backout : function(g) {
return {
transform : function(t) {
return (-1 * t * (t + g - 2)) / (1 - g);
}
};
},
/*!public
Backs up a bit then moves to target
Params:
-g : backup amount [0-1]
*/
backin : function(g) {
return {
transform : function(t) {
return 1 + ((t+1-g) * ((t+1-g) + g - 2)) / (1 - g);
}
};
},
/*!public
Goes to target and then back at constant rate
*/
bounceLinear : {
transform : function(t) {
if(t < 0.5)
return 2 * t;
else
return 1 - 2 * (t - 0.5)
}
},
/*!public
Goes to target and then back at variable rate
*/
bounceParabolic : {
transform : function(t) {
return -4 * t * (t-1);
}
},
/*!public
Goes to target and then back smoothly
*/
bounceSmooth : {
transform : function(t) {
return 0.5 - 0.5 * Math.cos(2 * Math.PI * t);
}
}
}
/*!
Utility objects for internal use
*/
var jsAnimUtil = {
interp : function (v1, v2, percent) {
if(isNaN(v1))
v1 = 0;
if(isNaN(v2))
v2 = 0;
var v = v1 + percent * (v2-v1);
return Math.floor(v);
},
getCSS : function (elem, field) {
var css = document.defaultView && document.defaultView.getComputedStyle ?
document.defaultView.getComputedStyle(elem, null)
: elem.currentStyle || elem.style;
return css[field];
},
explode : function ( delimiter, string, limit ) {
// http://kevin.vanzonneveld.net
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: kenneth
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: d3x
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: explode(' ', 'Kevin van Zonneveld');
// * returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
// * example 2: explode('=', 'a=bc=d', 2);
// * returns 2: ['a', 'bc=d']
var emptyArray = { 0: '' };
// third argument is not required
if ( arguments.length < 2 ||
typeof arguments[0] == 'undefined' ||
typeof arguments[1] == 'undefined' )
{
return null;
}
if ( delimiter === '' ||
delimiter === false ||
delimiter === null )
{
return false;
}
if ( typeof delimiter == 'function' ||
typeof delimiter == 'object' ||
typeof string == 'function' ||
typeof string == 'object' )
{
return emptyArray;
}
if ( delimiter === true ) {
delimiter = '1';
}
if (!limit) {
return string.toString().split(delimiter.toString());
} else {
// support for limit argument
var splitted = string.toString().split(delimiter.toString());
var partA = splitted.splice(0, limit - 1);
var partB = splitted.join(delimiter.toString());
partA.push(partB);
return partA;
}
}
}
/*! public
Prop objects
Used to keep track of which property is being controlled
Methods:
update : update the property to where it should be at the given time
current : return a natural representation of the current property
*/
var Prop = {
/*! public
Wait, while doing no animating
*/
wait : {
update : function(obj, from, to, percent) {},
current : function(obj) {return 0;}
},
/*! public
Follows a linear path
*/
position : {
update : function(obj, from, to, percent) {
var x = jsAnimUtil.interp(from.x, to.x, percent);
var y = jsAnimUtil.interp(from.y, to.y, percent);
obj.setPosition(x, y);
},
current : function(obj) {
var left = parseInt(obj.style.marginLeft);
var top = parseInt(obj.style.marginTop);
var x = left + obj.halfWidth;
var y = top + obj.halfHeight;
return new Pos(x,y);
}
},
/*! public
Follows a semicircular path
Params:
-clockwise : True for clockwise, false otherwise
*/
positionSemicircle : function(clockwise) {
return {
update : function(obj, from, to, percent) {
var centerX = (from.x + to.x) / 2;
var centerY = (from.y + to.y) / 2;
var h = centerY - from.y;
var w = from.x - centerX;
var dist = Math.sqrt(h * h + w * w);
if(w == 0) {
if(h > 0)
var initAngle = - Math.PI / 2;
else
var initAngle = Math.PI / 2;
}
else {
var atan = Math.atan(h / Math.abs(w));
if(w > 0)
var initAngle = atan;
else {
var initAngle = Math.PI - atan;
}
}
if(clockwise)
var addAngle = - percent * Math.PI;
else
var addAngle = percent * Math.PI;
var angle = initAngle + addAngle;
var x = Math.floor(centerX + dist * Math.cos(angle));
var y = Math.floor(centerY - dist * Math.sin(angle));
obj.setPosition(x, y);
},
current : function(obj) {
var left = parseInt(obj.style.marginLeft);
var top = parseInt(obj.style.marginTop);
var x = left + obj.halfWidth;
var y = top + obj.halfHeight;
return new Pos(x,y);
}
}
},
/*! public
Follows a circular path through target then back to start
Params:
-clockwise : True for clockwise, false otherwise
*/
positionCircle : function(clockwise) {
return {
update : function(obj, from, to, percent) {
var centerX = (from.x + to.x) / 2;
var centerY = (from.y + to.y) / 2;
var h = centerY - from.y;
var w = from.x - centerX;
var dist = Math.sqrt(h * h + w * w);
if(w == 0) {
if(h > 0)
var initAngle = - Math.PI / 2;
else
var initAngle = Math.PI / 2;
}
else {
var atan = Math.atan(h / Math.abs(w));
if(w > 0)
var initAngle = atan;
else {
var initAngle = Math.PI - atan;
}
}
if(clockwise)
var addAngle = 2 * percent * Math.PI;
else
var addAngle = -2 * percent * Math.PI;
var angle = initAngle + addAngle;
var x = Math.floor(centerX + dist * Math.cos(angle));
var y = Math.floor(centerY + dist * Math.sin(angle));
obj.setPosition(x, y);
},
current : function(obj) {
var left = parseInt(obj.style.marginLeft);
var top = parseInt(obj.style.marginTop);
var x = left + obj.halfWidth;
var y = top + obj.halfHeight;
return new Pos(x,y);
}
}
},
//public
top : {
update : function(obj, from, to, percent) {
obj.style.top = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'top'));
}
},
//public
right : {
update : function(obj, from, to, percent) {
obj.style.right = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'right'));
}
},
//public
bottom : {
update : function(obj, from, to, percent) {
obj.style.bottom = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'bottom'));
}
},
//public
left : {
update : function(obj, from, to, percent) {
obj.style.left = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'left'));
}
},
//public
margin : {
update : function(obj, from, to, percent) {
obj.style.margin = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'margin'));
}
},
//public
marginTop : {
update : function(obj, from, to, percent) {
obj.style.marginTop = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'marginTop'));
}
},
//public
marginRight : {
update : function(obj, from, to, percent) {
obj.style.marginRight = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'marginRight'));
}
},
//public
marginBottom : {
update : function(obj, from, to, percent) {
obj.style.marginBottom = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'marginBottom'));
}
},
//public
marginLeft : {
update : function(obj, from, to, percent) {
obj.style.marginLeft = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'marginLeft'));
}
},
//public
padding : {
update : function(obj, from, to, percent) {
obj.style.padding = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'padding'));
}
},
//public
paddingTop : {
update : function(obj, from, to, percent) {
obj.style.paddingTop = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'paddingTop'));
}
},
//public
paddingRight : {
update : function(obj, from, to, percent) {
obj.style.paddingRight = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'paddingRight'));
}
},
//public
paddingBottom : {
update : function(obj, from, to, percent) {
obj.style.paddingBottom = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'paddingBottom'));
}
},
//public
paddingLeft : {
update : function(obj, from, to, percent) {
obj.style.paddingLeft = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'paddingLeft'));
}
},
//public
borderWidth : {
update : function(obj, from, to, percent) {
obj.style.borderWidth = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'borderWidth'));
}
},
//public
borderTopWidth : {
update : function(obj, from, to, percent) {
obj.style.borderTopWidth = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'borderTopWidth'));
}
},
//public
borderRightWidth : {
update : function(obj, from, to, percent) {
obj.style.borderRightWidth = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'borderRightWidth'));
}
},
//public
borderBottomWidth : {
update : function(obj, from, to, percent) {
obj.style.borderBottomWidth = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'borderBottomWidth'));
}
},
//public
borderLeftWidth : {
update : function(obj, from, to, percent) {
obj.style.borderLeftWidth = jsAnimUtil.interp(from, to, percent) + "px";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'borderLeftWidth'));
}
},
//public
fontSize : {
update : function(obj, from, to, percent) {
obj.style.fontSize = jsAnimUtil.interp(from, to, percent) + "pt";
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'fontSize'));
}
},
//public
height : {
update : function(obj, from, to, percent) {
var v = jsAnimUtil.interp(from, to, percent);
obj.style.height = v + "px";
//Update the position if registered
if(obj.positionRegistered) {
var y = parseInt(obj.style.marginTop) + obj.halfHeight;
obj.halfHeight = Math.floor(obj.offsetHeight/2);
obj.style.marginTop = y - obj.halfHeight + "px";
}
},
current : function(obj) {
var ht = jsAnimUtil.getCSS(obj, 'height');
if(ht == "auto")
return obj.offsetHeight;
else
return parseInt(ht);
}
},
//public
width : {
update : function(obj, from, to, percent) {
var v = jsAnimUtil.interp(from, to, percent);
obj.style.width = v + "px";
//Update the position if registered
if(obj.positionRegistered) {
var x = parseInt(obj.style.marginLeft) + obj.halfWidth;
obj.halfWidth = Math.floor(obj.offsetWidth/2);
obj.style.marginLeft = x - obj.halfWidth + "px";
}
},
current : function(obj) {
return parseInt(jsAnimUtil.getCSS(obj, 'width'));
}
},
//public
dimension : {
update : function(obj, from, to, percent) {
var h = jsAnimUtil.interp(from.h, to.h, percent);
var w = jsAnimUtil.interp(from.w, to.w, percent);
obj.style.height = h + "px";
obj.style.width = w + "px";
//Update the position if registered
if(obj.positionRegistered) {
var y = parseInt(obj.style.marginTop) + obj.halfHeight;
obj.halfHeight = Math.floor(obj.offsetHeight/2);
obj.style.marginTop = (y - obj.halfHeight) + "px";
var x = parseInt(obj.style.marginLeft) + obj.halfWidth;
obj.halfWidth = Math.floor(obj.offsetWidth/2);
obj.style.marginLeft = (x - obj.halfWidth) + "px";
}
},
current : function(obj) {
var ht = jsAnimUtil.getCSS(obj, 'height');
if(ht == "auto")
var h = obj.offsetHeight;
else
var h = parseInt(ht);
var w = parseInt(jsAnimUtil.getCSS(obj, 'width'));
return new Dim(w, h);
}
},
//public
color : {
update : function(obj, from, to, percent) {
r = jsAnimUtil.interp(from.r, to.r, percent);
g = jsAnimUtil.interp(from.g, to.g, percent);
b = jsAnimUtil.interp(from.b, to.b, percent);
obj.style.color = "rgb("+r+","+g+","+b+")";
},
current : function(obj) {
var color = jsAnimUtil.getCSS(obj, 'color');
color = color.substring(4,color.length-1);
var rgb = jsAnimUtil.explode(",",color);
return new Col(parseInt(rgb[0]), parseInt(rgb[1]), parseInt(rgb[2]));
}
},
//public
backgroundColor : {
update : function(obj, from, to, percent) {
r = jsAnimUtil.interp(from.r, to.r, percent);
g = jsAnimUtil.interp(from.g, to.g, percent);
b = jsAnimUtil.interp(from.b, to.b, percent);
obj.style.backgroundColor = "rgb("+r+","+g+","+b+")";
},
current : function(obj) {
var color = jsAnimUtil.getCSS(obj, 'backgroundColor');
color = color.substring(4,color.length-1);
var rgb = jsAnimUtil.explode(",",color);
return new Col(parseInt(rgb[0]), parseInt(rgb[1]), parseInt(rgb[2]));
}
},
//public
borderColor : {
update : function(obj, from, to, percent) {
r = jsAnimUtil.interp(from.r, to.r, percent);
g = jsAnimUtil.interp(from.g, to.g, percent);
b = jsAnimUtil.interp(from.b, to.b, percent);
obj.style.borderColor = "rgb("+r+","+g+","+b+")";
},
current : function(obj) {
var color = jsAnimUtil.getCSS(obj, 'borderColor');
color = color.substring(4,color.length-1);
var rgb = jsAnimUtil.explode(",",color);
return new Col(parseInt(rgb[0]), parseInt(rgb[1]), parseInt(rgb[2]));
}
},
//public
opacity : {
update : function(obj, from, to, percent) {
v = jsAnimUtil.interp(100*from, 100*to, percent);
obj.style.opacity = v / 100;
},
current : function(obj) {
return jsAnimUtil.getCSS(obj, 'opacity');
}
}
} | apache-2.0 |
inversoft/passport-java-client | src/main/java/com/inversoft/passport/domain/Group.java | 2054 | /*
* Copyright (c) 2017-2018, Inversoft Inc., 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 com.inversoft.passport.domain;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import com.inversoft.json.JacksonConstructor;
import com.inversoft.json.ToString;
/**
* @author Tyler Scott
*/
public class Group implements Buildable<Group> {
public GroupData data;
public UUID id;
public String name;
public Map<UUID, List<ApplicationRole>> roles = new HashMap<>();
public UUID tenantId;
@JacksonConstructor
public Group() {
}
public Group(String name) {
this.name = name;
}
public Group(UUID id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Group group = (Group) o;
roles.values().forEach(c -> c.sort(Comparator.comparing(r -> r.id)));
group.roles.values().forEach(c -> c.sort(Comparator.comparing(r -> r.id)));
return Objects.equals(data, group.data) &&
Objects.equals(name, group.name) &&
Objects.equals(roles, group.roles) &&
Objects.equals(tenantId, group.tenantId);
}
@Override
public int hashCode() {
return Objects.hash(data, name, roles, tenantId);
}
@Override
public String toString() {
return ToString.toString(this);
}
}
| apache-2.0 |
aajjbb/contest-files | SPOJPL/CobbledStreets.cpp | 1642 | #include <iostream>
#include <vector>
#include <algorithm>
#include <stdio.h>
using namespace std;
const int MOD = 1000000007;
int test, p, n, m;
struct edge {
int a, b, c;
edge(){}
edge(int _a, int _b, int _c): a(_a), b(_b), c(_c){}
bool operator<(const edge& e) const {
return c < e.c;
}
};
struct UnionFind {
int n, *id, *size;
UnionFind(int _n) {
n = _n;
id = new int[n];
size = new int[n];
for(int i = 0; i < n; i++) {
id[i] = i;
size[i] = 1;
}
}
bool find(int p, int q) {
return root(p) == root(q);
}
int root(int i) {
while(i != id[i]) {
id[i] = id[id[i]];
i = id[i];
}
return i;
}
bool unite(int p, int q) {
int i = root(p);
int j = root(q);
if(i == j) return false;
if(size[i] < size[j]) {
id[i] = j; size[j] += size[i];
} else {
id[j] = i; size[i] += size[j];
}
return true;
}
};
int main(void) {
scanf("%d", &test);
for( ; test-- > 0; ) {
scanf("%d%d%d", &p, &n, &m);
vector<edge> ve(m);
for(int i = 0; i < m; i++) {
scanf("%d%d%d", &ve[i].a, &ve[i].b, &ve[i].c);
}
sort(ve.begin(), ve.end());
int ans = 0;
UnionFind uf(n+1);
for(int i = 0; i < m; i++) {
if(!uf.find(ve[i].a, ve[i].b)) {
uf.unite(ve[i].a, ve[i].b);
ans += ve[i].c;
}
}
printf("%d\n", ans * p);
}
return 0;
}
| apache-2.0 |
Kiryuumaru/IPCS | IPCS/Extension.cs | 1291 | using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace IPCS
{
public static class Extension
{
public static T[] SubArray<T>(this T[] data, int index, int length)
{
T[] result = new T[length];
Array.Copy(data, index, result, 0, length);
return result;
}
public static T[] SubArray<T>(this T[] data, int index)
{
T[] result = new T[data.Length-index];
Array.Copy(data, index, result, 0, data.Length - index);
return result;
}
public static string ObjectToString(object obj)
{
using (MemoryStream ms = new MemoryStream())
{
new BinaryFormatter().Serialize(ms, obj);
return Convert.ToBase64String(ms.ToArray());
}
}
public static object StringToObject(string base64String)
{
byte[] bytes = Convert.FromBase64String(base64String);
using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length))
{
ms.Write(bytes, 0, bytes.Length);
ms.Position = 0;
return new BinaryFormatter().Deserialize(ms);
}
}
}
}
| apache-2.0 |
AyatsujiTsukasa/unitystreamingcaption | unitystreamingcaption.go | 3684 | // unitygooglelivecaption.go
// intended to be used in unity project
// modification of livecaption.go found in https://github.com/GoogleCloudPlatform/golang-samples.git
//
// process requires google service accounts credential file's path
// you can get one in your google cloud console
// ----------------------------------------------------------------//
// livecaption.go
// Copyright 2016 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
// Command livecaption pipes the stdin audio data to
// Google Speech API and outputs the transcript.
package main
import (
"encoding/base64"
"flag"
"fmt"
"io"
"log"
"os"
speech "cloud.google.com/go/speech/apiv1beta1"
"golang.org/x/net/context"
"google.golang.org/api/option"
"google.golang.org/api/transport"
speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1beta1"
)
var (
version = "v0.1"
responcePrefix = "response: "
)
func main() {
log.SetOutput(os.Stderr)
var credentialDir string
var language string
var singleUtteranceEnable bool
var outputAsBase64 bool
flag.StringVar(&credentialDir, "cred", "/path/to/file/", "path of google service account credential json file")
flag.StringVar(&language, "language", "ja-JP", "languagecode of voice")
flag.BoolVar(&singleUtteranceEnable, "s", false, "enable single utterance termination")
flag.BoolVar(&outputAsBase64, "base64", false, "output as base64 Encoding")
flag.Parse()
os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", credentialDir)
ctx := context.Background()
conn, err := transport.DialGRPC(
ctx,
option.WithEndpoint("speech.googleapis.com:443"),
option.WithScopes("https://www.googleapis.com/auth/cloud-platform"),
)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
// [START speech_streaming_mic_recognize]
client, err := speech.NewClient(ctx)
if err != nil {
log.Fatal(err)
}
stream, err := client.StreamingRecognize(ctx)
if err != nil {
log.Fatal(err)
}
// Send the initial configuration message.
if err := stream.Send(&speechpb.StreamingRecognizeRequest{
StreamingRequest: &speechpb.StreamingRecognizeRequest_StreamingConfig{
StreamingConfig: &speechpb.StreamingRecognitionConfig{
Config: &speechpb.RecognitionConfig{
LanguageCode: language,
Encoding: speechpb.RecognitionConfig_LINEAR16,
SampleRate: 16000,
},
InterimResults: true,
SingleUtterance: singleUtteranceEnable,
},
},
}); err != nil {
log.Fatal(err)
}
log.Println("Caption is ready")
go func() {
// Pipe stdin to the API.
buf := make([]byte, 1024)
for {
n, err := os.Stdin.Read(buf)
if err == io.EOF {
return // Nothing else to pipe, return from this goroutine.
}
if err != nil {
log.Printf("Could not read from stdin: %v", err)
continue
}
rqst := &speechpb.StreamingRecognizeRequest{
StreamingRequest: &speechpb.StreamingRecognizeRequest_AudioContent{
AudioContent: buf[:n],
},
}
if err = stream.Send(rqst); err != nil {
log.Printf("Could not send audio: %v", err)
}
}
}()
for {
resp, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
log.Fatalf("Cannot stream results: %v", err)
}
if err := resp.Error; err != nil {
log.Fatalf("Could not recognize: %v", err)
}
for _, result := range resp.Results {
output := result.Alternatives[0].Transcript
if outputAsBase64 {
output = base64.StdEncoding.EncodeToString([]byte(output))
}
if result.IsFinal {
fmt.Println("EOS:" + output)
} else {
fmt.Println(output)
}
}
}
// [END speech_streaming_mic_recognize]
}
| apache-2.0 |
jmaoito/happyCoding | algorithm/sqrt.cpp | 847 | /***************
LeetCode sqrt(x)
Implement int sqrt(int x).
Compute and return the square root of x.
Discussion:
Divide and Conquer. uses binary search.
since the return type is integer, the return value should be smaller or equal
than the real sqrt(x).
time complexity O(logn), space complexity O(1)
****************/
class Solution {
public:
int sqrt(int x) {
int start = 1;
int end = x/2;
int ret;
if (x < 2) return x;
while (start <= end) {
int mid = start + (end - start)/2;
if (x/mid > mid) { // mid * mid will cause overflow
start = mid + 1;
ret = mid;
}
else if (x/mid < mid)
end = mid - 1;
else
return mid;
}
return ret;
}
};
| apache-2.0 |
rene-justin-dado/graphql-nerd-cache | migrations/20170211214816_hero.js | 272 | exports.up = function(knex, Promise) {
return knex.schema.createTable('hero', (table) => {
table.increments('id').primary()
table.string('name')
table.string('race')
})
};
exports.down = function(knex, Promise) {
return knex.schema.dropTable('hero')
};
| apache-2.0 |
syntelos/gwtcc-gwtgl | src/com/googlecode/gwtgl/client/WebGLTexture.java | 978 | /**
* Copyright 2009-2010 Sönke Sothmann, Steffen Schäfer and others
*
* 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.googlecode.gwtgl.client;
import com.google.gwt.core.client.JavaScriptObject;
/**
*
*/
public final class WebGLTexture extends JavaScriptObject {
/**
* Protected standard constructor as specified by
* {@link com.google.gwt.core.client.JavaScriptObject}.
*/
protected WebGLTexture() {
}
}
| apache-2.0 |
liuguogen/Ecstore | app/pam/lib/account.php | 4051 | <?php
/**
* ShopEx licence
*
* @copyright Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
* @license http://ecos.shopex.cn/ ShopEx License
*/
/**
* 该类是所有登录方式验证后写日志和SESSION的类
*/
class pam_account{
/**
* 构造方法
* @param string $type 设置登录体系类型 shopadmin,member等
*/
function __construct($type){
$this->type = $type;
$this->session = kernel::single('base_session')->start();
}
/**
* 检查session id 是否存在
* @return int 当前用户的id
*/
function is_valid(){
return $_SESSION['account'][$this->type];
}
/**
* 检查用户名是否存在(暂时后台)
* @param string $login_name 用户名字段
* @return bool 返回存在与否
*/
function is_exists($login_name){
if(app::get('pam')->model('account')->getList('account_id',array('account_type'=>$this->type,'login_name'=>$login_name)))
return true;
else
return false;
}
/**
* 验证完成后,写入session和记录登录日志
* @param string $module 认证模型
* @param int $module_uid 用户的id account表里的主键
* @param array $auth_data 认证提示信息
* @return bool
*/
function update($module,$module_uid, $auth_data){
if($module!='pam_passport_desktop_basic'){
$auth_model = app::get('pam')->model('auth');
if($row = $auth_model->getlist('*',array(
'module_uid'=>$module_uid,
'module'=>$module,
),0,1)){
$auth_model->update(array('data'=>$auth_data),array(
'module_uid'=>$module_uid,
'module'=>$module,
));
$account_id = $row[0]['account_id'];
}else{
$account = app::get('pam')->model('account');
$login_name = microtime();
while($row = $account->getList('account_id',array('login_name' => $login_name,'account_type' => $this->type)))
{
$login_name = microtime();
}
$data = array(
'login_name' => $login_name,
'login_password' => md5(time()),
'account_type'=>$this->type,
'createtime'=>time(),
);
$account_id = $account->insert($data);
if(!$account_id) return false;
$data = array(
'account_id'=>$account_id,
'module_uid'=>$auth_data['login_name'],
'module'=>$module,
'data'=>$auth_data,
);
$auth_model->insert($data);
}
}else{
$account_id = $module_uid;
}
$_SESSION['account'][$this->type] = $account_id;
return true;
}
/**
* 安装时,注册体系类型
* @access static
* @param string $app_id appid
* @param string $type 传入的体系的值
* @param string $name 体系名称
*/
static function register_account_type($app_id,$type,$name){
$account_types = app::get('pam')->getConf('account_type');
$account_types[$app_id] = array('name' => $name, 'type' => $type);
app::get('pam')->setConf('account_type',$account_types);
}
/**
* 注销体系类型
* @access static
* @param string $app_id appid
*/
static function unregister_account_type($app_id){
$account_types = app::get('pam')->getConf('account_type');
unset($account_types[$app_id]);
app::get('pam')->setConf('account_type',$account_types);
}
/**
* 返回体系类型
* @access static
* @param string $app_id appid
* @return string 返回体系字符串
*/
static function get_account_type($app_id = 'b2c')
{
$aType = app::get('pam')->getConf('account_type');
//todo
return $aType[$app_id]['type'];
//return 'member';
}//End Function
}
| apache-2.0 |
gosu-lang/old-gosu-repo | gosu-core-api/src/main/java/gw/fs/jar/IJarFileDirectory.java | 320 | /*
* Copyright 2013 Guidewire Software, Inc.
*/
package gw.fs.jar;
import gw.fs.IDirectory;
import gw.lang.UnstableAPI;
@UnstableAPI
public interface IJarFileDirectory extends IDirectory {
JarEntryDirectoryImpl getOrCreateDirectory(String relativeName);
JarEntryFileImpl getOrCreateFile(String relativeName);
}
| apache-2.0 |
asakusafw/asakusafw | operator/core/src/main/java/com/asakusafw/operator/util/JavadocHelper.java | 10312 | /**
* Copyright 2011-2021 Asakusa Framework Team.
*
* 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.asakusafw.operator.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.tools.Diagnostic;
import com.asakusafw.operator.CompileEnvironment;
import com.asakusafw.operator.model.OperatorDescription.Document;
import com.asakusafw.operator.model.OperatorDescription.ExternalDocument;
import com.asakusafw.operator.model.OperatorDescription.ParameterReference;
import com.asakusafw.operator.model.OperatorDescription.Reference;
import com.asakusafw.operator.model.OperatorDescription.ReferenceDocument;
import com.asakusafw.operator.model.OperatorDescription.SpecialReference;
import com.asakusafw.operator.model.OperatorDescription.TextDocument;
import com.asakusafw.utils.java.model.syntax.DocBlock;
import com.asakusafw.utils.java.model.syntax.DocElement;
import com.asakusafw.utils.java.model.syntax.DocText;
import com.asakusafw.utils.java.model.syntax.Javadoc;
import com.asakusafw.utils.java.model.syntax.SimpleName;
import com.asakusafw.utils.java.model.util.Models;
import com.asakusafw.utils.java.parser.javadoc.JavadocConverter;
import com.asakusafw.utils.java.parser.javadoc.JavadocParseException;
/**
* Common helper methods about documentation comments.
*/
public class JavadocHelper {
private final CompileEnvironment environment;
private final Map<String, List<List<DocElement>>> blocks = new HashMap<>();
private ExecutableElement executable;
/**
* Creates a new instance.
* @param environment current environment
* @throws IllegalArgumentException if some parameters were {@code null}
*/
public JavadocHelper(CompileEnvironment environment) {
this.environment = Objects.requireNonNull(environment, "environment must not be null"); //$NON-NLS-1$
}
/**
* Put a documented element.
* @param element the documented element
* @throws IllegalArgumentException if some parameters were {@code null}
*/
public void put(Element element) {
Objects.requireNonNull(element, "element must not be null"); //$NON-NLS-1$
if (this.executable == null
&& (element.getKind() == ElementKind.METHOD || element.getKind() == ElementKind.CONSTRUCTOR)) {
this.executable = (ExecutableElement) element;
}
Javadoc javadoc = parseJavadoc(element);
boolean sawSummary = false;
for (DocBlock block : javadoc.getBlocks()) {
String tag = block.getTag();
sawSummary |= tag.isEmpty();
appendBlock(tag, block.getElements());
}
if (sawSummary == false) {
appendBlock("", Collections.emptyList()); //$NON-NLS-1$
}
}
private Javadoc parseJavadoc(Element element) {
assert environment != null;
assert element != null;
String comment = environment.getProcessingEnvironment().getElementUtils().getDocComment(element);
try {
return parseJavadoc(comment);
} catch (JavadocParseException e) {
environment.getProcessingEnvironment().getMessager().printMessage(Diagnostic.Kind.WARNING,
e.getMessage(),
element);
return Models.getModelFactory().newJavadoc(Collections.emptyList());
}
}
private static Javadoc parseJavadoc(String comment) throws JavadocParseException {
if (comment == null) {
return Models.getModelFactory().newJavadoc(Collections.emptyList());
}
String string = comment;
if (comment.startsWith("/**") == false) { //$NON-NLS-1$
string = "/**" + string; //$NON-NLS-1$
}
if (comment.endsWith("*/") == false) { //$NON-NLS-1$
string = string + "*/"; //$NON-NLS-1$
}
return new JavadocConverter(Models.getModelFactory()).convert(string, 0);
}
private void appendBlock(String tag, List<? extends DocElement> elements) {
assert tag != null;
assert elements != null;
List<List<DocElement>> list = blocks.get(tag);
if (list == null) {
list = new ArrayList<>();
blocks.put(tag, list);
}
list.add(new ArrayList<>(elements));
}
/**
* Returns the document elements for the description.
* @param document description
* @return related elements, or an empty list if they are not found
* @throws IllegalArgumentException if some parameters were {@code null}
*/
public List<? extends DocElement> get(Document document) {
Objects.requireNonNull(document, "document must not be null"); //$NON-NLS-1$
switch (document.getKind()) {
case TEXT:
return text(((TextDocument) document).getText());
case REFERENCE:
return reference(((ReferenceDocument) document).getReference());
case EXTERNAL:
return external(((ExternalDocument) document).getElement());
default:
throw new AssertionError(document.getKind());
}
}
/**
* Returns the parameter document elements.
* @param name parameter name
* @return related elements, or an empty list if the parameter does not exist
* @throws IllegalArgumentException if some parameters were {@code null}
*/
public List<? extends DocElement> getParameter(String name) {
Objects.requireNonNull(name, "name must not be null"); //$NON-NLS-1$
List<List<DocElement>> params = blocks.get("@param"); //$NON-NLS-1$
if (params == null) {
return Collections.emptyList();
}
for (List<DocElement> param : params) {
if (param.isEmpty()) {
continue;
}
if (hasName(param.get(0), name)) {
return param.subList(1, param.size());
}
}
return Collections.emptyList();
}
/**
* Returns the type parameter document elements.
* @param name type parameter name
* @return related elements, or an empty list if the type parameter does not exist
* @throws IllegalArgumentException if some parameters were {@code null}
*/
public List<? extends DocElement> getTypeParameter(String name) {
Objects.requireNonNull(name, "name must not be null"); //$NON-NLS-1$
List<List<DocElement>> params = blocks.get("@param"); //$NON-NLS-1$
if (params == null) {
return Collections.emptyList();
}
for (List<DocElement> param : params) {
if (param.size() < 3) {
continue;
}
if (hasName(param.get(0), "<") //$NON-NLS-1$
&& hasName(param.get(1), name)
&& hasName(param.get(2), ">")) { //$NON-NLS-1$
return param.subList(3, param.size());
}
}
return Collections.emptyList();
}
private static boolean hasName(DocElement element, String name) {
assert element != null;
assert name != null;
switch (element.getModelKind()) {
case SIMPLE_NAME:
return name.equals(((SimpleName) element).getToken());
case DOC_TEXT:
return name.equals(((DocText) element).getString());
default:
return false;
}
}
private List<? extends DocElement> text(String text) {
Javadoc javadoc;
try {
javadoc = parseJavadoc(text);
} catch (JavadocParseException e) {
environment.getProcessingEnvironment().getMessager().printMessage(Diagnostic.Kind.WARNING,
e.getMessage(),
executable);
return Collections.emptyList();
}
if (javadoc.getBlocks().isEmpty()) {
return Collections.emptyList();
}
return javadoc.getBlocks().get(0).getElements();
}
private List<? extends DocElement> reference(Reference reference) {
switch (reference.getKind()) {
case METHOD:
return getBlock(""); //$NON-NLS-1$
case RETURN:
return getBlock("@return"); //$NON-NLS-1$
case PARAMETER:
return getParameter(((ParameterReference) reference).getLocation());
case SPECIAL:
return text(((SpecialReference) reference).getInfo());
default:
throw new AssertionError(reference.getKind());
}
}
private List<? extends DocElement> getParameter(int location) {
if (executable == null || location >= executable.getParameters().size()) {
return Collections.emptyList();
}
String name = executable.getParameters().get(location).getSimpleName().toString();
return getParameter(name);
}
private List<? extends DocElement> external(Element element) {
Javadoc javadoc = parseJavadoc(element);
List<? extends DocBlock> elementBlocks = javadoc.getBlocks();
if (elementBlocks.isEmpty()) {
return Collections.emptyList();
}
DocBlock first = elementBlocks.get(0);
if (first.getTag().isEmpty()) {
return first.getElements();
}
return Collections.emptyList();
}
private List<? extends DocElement> getBlock(String tag) {
assert tag != null;
List<List<DocElement>> list = blocks.get(tag);
if (list == null) {
return Collections.emptyList();
}
return list.get(0);
}
}
| apache-2.0 |
b002368/chef-repo | spec/unit/node_map_spec.rb | 6120 | #
# Author:: Lamont Granquist (<[email protected]>)
# Copyright:: Copyright 2014-2016, Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
#
require "spec_helper"
require "chef/node_map"
describe Chef::NodeMap do
let(:node_map) { Chef::NodeMap.new }
let(:node) { Chef::Node.new }
describe "with a bad filter name" do
it "should raise an error" do
expect { node_map.set(node, :thing, on_platform_family: "rhel") }.to raise_error(ArgumentError)
end
end
describe "when no matchers are set at all" do
before do
node_map.set(:thing, :foo)
end
it "returns the value" do
expect(node_map.get(node, :thing)).to eql(:foo)
end
it "returns nil for keys that do not exist" do
expect(node_map.get(node, :other_thing)).to eql(nil)
end
end
describe "filtering by os" do
before do
node_map.set(:thing, :foo, os: ["windows"])
node_map.set(:thing, :bar, os: "linux")
end
it "returns the correct value for windows" do
allow(node).to receive(:[]).with(:os).and_return("windows")
expect(node_map.get(node, :thing)).to eql(:foo)
end
it "returns the correct value for linux" do
allow(node).to receive(:[]).with(:os).and_return("linux")
expect(node_map.get(node, :thing)).to eql(:bar)
end
it "returns nil for a non-matching os" do
allow(node).to receive(:[]).with(:os).and_return("freebsd")
expect(node_map.get(node, :thing)).to eql(nil)
end
end
describe "rejecting an os" do
before do
node_map.set(:thing, :foo, os: "!windows")
end
it "returns nil for windows" do
allow(node).to receive(:[]).with(:os).and_return("windows")
expect(node_map.get(node, :thing)).to eql(nil)
end
it "returns the correct value for linux" do
allow(node).to receive(:[]).with(:os).and_return("linux")
expect(node_map.get(node, :thing)).to eql(:foo)
end
end
describe "filtering by os and platform_family" do
before do
node_map.set(:thing, :bar, os: "linux", platform_family: "rhel")
end
it "returns the correct value when both match" do
allow(node).to receive(:[]).with(:os).and_return("linux")
allow(node).to receive(:[]).with(:platform_family).and_return("rhel")
expect(node_map.get(node, :thing)).to eql(:bar)
end
it "returns nil for a non-matching os" do
allow(node).to receive(:[]).with(:os).and_return("freebsd")
expect(node_map.get(node, :thing)).to eql(nil)
end
it "returns nil when the platform_family does not match" do
allow(node).to receive(:[]).with(:os).and_return("linux")
allow(node).to receive(:[]).with(:platform_family).and_return("debian")
expect(node_map.get(node, :thing)).to eql(nil)
end
end
describe "with a block doing platform_version checks" do
before do
node_map.set(:thing, :foo, platform_family: "rhel") do |node|
node[:platform_version].to_i >= 7
end
end
it "returns the value when the node matches" do
allow(node).to receive(:[]).with(:platform_family).and_return("rhel")
allow(node).to receive(:[]).with(:platform_version).and_return("7.0")
expect(node_map.get(node, :thing)).to eql(:foo)
end
it "returns nil when the block does not match" do
allow(node).to receive(:[]).with(:platform_family).and_return("rhel")
allow(node).to receive(:[]).with(:platform_version).and_return("6.4")
expect(node_map.get(node, :thing)).to eql(nil)
end
it "returns nil when the platform_family filter does not match" do
allow(node).to receive(:[]).with(:platform_family).and_return("debian")
allow(node).to receive(:[]).with(:platform_version).and_return("7.0")
expect(node_map.get(node, :thing)).to eql(nil)
end
it "returns nil when both do not match" do
allow(node).to receive(:[]).with(:platform_family).and_return("debian")
allow(node).to receive(:[]).with(:platform_version).and_return("6.0")
expect(node_map.get(node, :thing)).to eql(nil)
end
context "when there is a less specific definition" do
before do
node_map.set(:thing, :bar, platform_family: "rhel")
end
it "returns the value when the node matches" do
allow(node).to receive(:[]).with(:platform_family).and_return("rhel")
allow(node).to receive(:[]).with(:platform_version).and_return("7.0")
expect(node_map.get(node, :thing)).to eql(:foo)
end
end
end
describe "resource back-compat testing" do
before :each do
Chef::Config[:treat_deprecation_warnings_as_errors] = false
end
it "should handle :on_platforms => :all" do
node_map.set(:chef_gem, :foo, :on_platforms => :all)
allow(node).to receive(:[]).with(:platform).and_return("windows")
expect(node_map.get(node, :chef_gem)).to eql(:foo)
end
it "should handle :on_platforms => [ 'windows' ]" do
node_map.set(:dsc_script, :foo, :on_platforms => [ "windows" ])
allow(node).to receive(:[]).with(:platform).and_return("windows")
expect(node_map.get(node, :dsc_script)).to eql(:foo)
end
it "should handle :on_platform => :all" do
node_map.set(:link, :foo, :on_platform => :all)
allow(node).to receive(:[]).with(:platform).and_return("windows")
expect(node_map.get(node, :link)).to eql(:foo)
end
end
end
| apache-2.0 |
gmind7/java8-training | src/main/java/io/gmind/java8/model/Person.java | 307 | package io.gmind.java8.model;
import lombok.Data;
/**
* Created by gmind on 2014-06-18.
*/
@Data
public class Person {
String firstName;
String lastName;
public Person() {
}
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
| apache-2.0 |
jamaxba/jamax-util | jamax-rest/src/main/java/ba/jamax/util/rest/util/GenericUtils.java | 719 | package ba.jamax.util.rest.util;
import java.lang.reflect.Method;
import org.apache.commons.lang.WordUtils;
public class GenericUtils<T> {
public Method getGetter(Class<T> entityClass, String key) {
Method m = null;
try {
try {
m = entityClass.getMethod(constructGetter(key));
} catch (NoSuchMethodException e) {
// it's not GET
// let's try IS
m = entityClass.getMethod(constructIsGetter(key));
}
} catch (Exception e) {
// skip method - out of the scope
}
return m;
}
private String constructGetter(String strKey) {
return "get" + WordUtils.capitalize(strKey);
}
private String constructIsGetter(String strKey) {
return "is" + WordUtils.capitalize(strKey);
}
}
| apache-2.0 |
drud/ddev | pkg/ddevapp/provider.go | 11404 | package ddevapp
import (
"github.com/drud/ddev/pkg/output"
"os"
"path/filepath"
"fmt"
"github.com/drud/ddev/pkg/fileutil"
"github.com/drud/ddev/pkg/util"
"gopkg.in/yaml.v2"
)
// ProviderCommand defines the shell command to be run for one of the commands (db pull, etc.)
type ProviderCommand struct {
Command string `yaml:"command"`
Service string `yaml:"service,omitempty"`
}
// ProviderInfo defines the provider
type ProviderInfo struct {
EnvironmentVariables map[string]string `yaml:"environment_variables"`
AuthCommand ProviderCommand `yaml:"auth_command"`
DBPullCommand ProviderCommand `yaml:"db_pull_command"`
DBImportCommand ProviderCommand `yaml:"db_import_command"`
FilesPullCommand ProviderCommand `yaml:"files_pull_command"`
FilesImportCommand ProviderCommand `yaml:"files_import_command"`
CodePullCommand ProviderCommand `yaml:"code_pull_command,omitempty"`
DBPushCommand ProviderCommand `yaml:"db_push_command"`
FilesPushCommand ProviderCommand `yaml:"files_push_command"`
}
// Provider provides generic-specific import functionality.
type Provider struct {
ProviderType string `yaml:"provider"`
app *DdevApp `yaml:"-"`
ProviderInfo `yaml:"providers"`
}
// Init handles loading data from saved config.
func (p *Provider) Init(pType string, app *DdevApp) error {
p.app = app
configPath := app.GetConfigPath(filepath.Join("providers", pType+".yaml"))
if !fileutil.FileExists(configPath) {
return fmt.Errorf("no configuration exists for %s provider - it should be at %s", pType, configPath)
}
err := p.Read(configPath)
if err != nil {
return err
}
p.ProviderType = pType
app.ProviderInstance = p
return nil
}
// Pull performs an import of db and files
func (app *DdevApp) Pull(provider *Provider, skipDbArg bool, skipFilesArg bool, skipImportArg bool) error {
var err error
err = app.ProcessHooks("pre-pull")
if err != nil {
return fmt.Errorf("Failed to process pre-pull hooks: %v", err)
}
if app.SiteStatus() != SiteRunning {
util.Warning("Project is not currently running. Starting project before performing pull.")
err = app.Start()
if err != nil {
return err
}
}
if provider.AuthCommand.Command != "" {
output.UserOut.Print("Authenticating...")
err = provider.app.ExecOnHostOrService(provider.AuthCommand.Service, provider.injectedEnvironment()+"; "+provider.AuthCommand.Command)
if err != nil {
return err
}
}
if skipDbArg {
output.UserOut.Println("Skipping database pull.")
} else {
output.UserOut.Println("Obtaining database...")
fileLocation, importPath, err := provider.GetBackup("database")
if err != nil {
return err
}
err = app.MutagenSyncFlush()
if err != nil {
return err
}
if skipImportArg {
output.UserOut.Println("Skipping database import.")
} else {
err = app.MutagenSyncFlush()
if err != nil {
return err
}
output.UserOut.Println("Importing database...")
err = provider.importDatabaseBackup(fileLocation, importPath)
if err != nil {
return err
}
}
}
if skipFilesArg {
output.UserOut.Println("Skipping files pull.")
} else {
output.UserOut.Println("Obtaining files...")
fileLocation, importPath, err := provider.GetBackup("files")
if err != nil {
return err
}
err = app.MutagenSyncFlush()
if err != nil {
return err
}
if skipImportArg {
output.UserOut.Println("Skipping files import.")
} else {
output.UserOut.Println("Importing files...")
err = provider.importFilesBackup(fileLocation, importPath)
if err != nil {
return err
}
}
}
err = app.ProcessHooks("post-pull")
if err != nil {
return fmt.Errorf("Failed to process post-pull hooks: %v", err)
}
return nil
}
// Push pushes db and files up to upstream hosting provider
func (app *DdevApp) Push(provider *Provider, skipDbArg bool, skipFilesArg bool) error {
var err error
err = app.ProcessHooks("pre-push")
if err != nil {
return fmt.Errorf("Failed to process pre-push hooks: %v", err)
}
if app.SiteStatus() != SiteRunning {
util.Warning("Project is not currently running. Starting project before performing push.")
err = app.Start()
if err != nil {
return err
}
}
if provider.AuthCommand.Command != "" {
output.UserOut.Print("Authenticating...")
err := provider.app.ExecOnHostOrService(provider.AuthCommand.Service, provider.injectedEnvironment()+"; "+provider.AuthCommand.Command)
if err != nil {
return err
}
}
if skipDbArg {
output.UserOut.Println("Skipping database push.")
} else {
output.UserOut.Println("Uploading database...")
err = provider.UploadDB()
if err != nil {
return err
}
output.UserOut.Printf("Database uploaded")
}
if skipFilesArg {
output.UserOut.Println("Skipping files push.")
} else {
output.UserOut.Println("Uploading files...")
err = provider.UploadFiles()
if err != nil {
return err
}
output.UserOut.Printf("ProjectFiles uploaded")
}
err = app.ProcessHooks("post-push")
if err != nil {
return fmt.Errorf("Failed to process post-push hooks: %v", err)
}
return nil
}
// GetBackup will create and download a backup
// Valid values for backupType are "database" or "files".
// returns fileURL, importPath, error
func (p *Provider) GetBackup(backupType string) (string, string, error) {
var err error
var filePath string
if backupType != "database" && backupType != "files" {
return "", "", fmt.Errorf("could not get backup: %s is not a valid backup type", backupType)
}
// Set the import path blank to use the root of the archive by default.
importPath := ""
p.prepDownloadDir()
switch backupType {
case "database":
filePath, err = p.getDatabaseBackup()
case "files":
filePath, err = p.getFilesBackup()
default:
return "", "", fmt.Errorf("could not get backup: %s is not a valid backup type", backupType)
}
if err != nil {
return "", "", err
}
return filePath, importPath, nil
}
// UploadDB is used by Push to push the database to hosting provider
func (p *Provider) UploadDB() error {
_ = os.RemoveAll(p.getDownloadDir())
_ = os.Mkdir(p.getDownloadDir(), 0755)
if p.DBPushCommand.Command == "" {
util.Warning("No DBPushCommand is defined for provider %s", p.ProviderType)
return nil
}
err := p.app.ExportDB(p.app.GetConfigPath(".downloads/db.sql.gz"), true, "")
if err != nil {
return err
}
err = p.app.MutagenSyncFlush()
if err != nil {
return err
}
s := p.DBPushCommand.Service
if s == "" {
s = "web"
}
err = p.app.ExecOnHostOrService(s, p.injectedEnvironment()+"; "+p.DBPushCommand.Command)
if err != nil {
util.Failed("Failed to exec %s on %s: %v", p.DBPushCommand.Command, s, err)
}
return nil
}
// UploadFiles is used by Push to push the user-generated files to the hosting provider
func (p *Provider) UploadFiles() error {
_ = os.RemoveAll(p.getDownloadDir())
_ = os.Mkdir(p.getDownloadDir(), 0755)
if p.FilesPushCommand.Command == "" {
util.Warning("No FilesPushCommand is defined for provider %s", p.ProviderType)
return nil
}
s := p.FilesPushCommand.Service
if s == "" {
s = "web"
}
err := p.app.ExecOnHostOrService(s, p.injectedEnvironment()+"; "+p.FilesPushCommand.Command)
if err != nil {
util.Failed("Failed to exec %s on %s: %v", p.FilesPushCommand.Command, s, err)
}
return nil
}
// prepDownloadDir ensures the download cache directories are created and writeable.
func (p *Provider) prepDownloadDir() {
destDir := p.getDownloadDir()
filesDir := filepath.Join(destDir, "files")
_ = os.RemoveAll(destDir)
err := os.MkdirAll(filesDir, 0755)
util.CheckErr(err)
}
func (p *Provider) getDownloadDir() string {
destDir := p.app.GetConfigPath(".downloads")
return destDir
}
func (p *Provider) getFilesBackup() (filename string, error error) {
destDir := filepath.Join(p.getDownloadDir(), "files")
_ = os.RemoveAll(destDir)
_ = os.MkdirAll(destDir, 0755)
if p.FilesPullCommand.Command == "" {
util.Warning("No FilesPullCommand is defined for provider %s", p.ProviderType)
return "", nil
}
s := p.FilesPullCommand.Service
if s == "" {
s = "web"
}
err := p.app.ExecOnHostOrService(s, p.injectedEnvironment()+"; "+p.FilesPullCommand.Command)
if err != nil {
util.Failed("Failed to exec %s on %s: %v", p.FilesPullCommand.Command, s, err)
}
return filepath.Join(p.getDownloadDir(), "files"), nil
}
// getDatabaseBackup retrieves database using `generic backup database`, then
// describe until it appears, then download it.
func (p *Provider) getDatabaseBackup() (filename string, error error) {
_ = os.RemoveAll(p.getDownloadDir())
_ = os.Mkdir(p.getDownloadDir(), 0755)
if p.DBPullCommand.Command == "" {
util.Warning("No DBPullCommand is defined for provider")
return "", nil
}
s := p.DBPullCommand.Service
if s == "" {
s = "web"
}
err := p.app.MutagenSyncFlush()
if err != nil {
return "", err
}
err = p.app.ExecOnHostOrService(s, p.injectedEnvironment()+"; "+p.DBPullCommand.Command)
if err != nil {
return "", fmt.Errorf("Failed to exec %s on %s: %v", p.DBPullCommand.Command, s, err)
}
return filepath.Join(p.getDownloadDir(), "db.sql.gz"), nil
}
// importDatabaseBackup will import a downloaded database
// If a custom importer is provided, that will be used, otherwise
// the default is app.ImportDB()
func (p *Provider) importDatabaseBackup(fileLocation string, importPath string) error {
var err error
if p.DBImportCommand.Command == "" {
err = p.app.ImportDB(fileLocation, importPath, true, false, "db")
} else {
s := p.DBImportCommand.Service
if s == "" {
s = "web"
}
output.UserOut.Printf("Importing database via custom db_import_command")
err = p.app.ExecOnHostOrService(s, p.injectedEnvironment()+"; "+p.DBImportCommand.Command)
}
return err
}
// importFilesBackup will import a downloaded files tarball or directory
// If a custom importer is provided, that will be used, otherwise
// the default is app.ImportFiles()
func (p *Provider) importFilesBackup(fileLocation string, importPath string) error {
var err error
if p.FilesImportCommand.Command == "" {
err = p.app.ImportFiles(fileLocation, importPath)
} else {
s := p.FilesImportCommand.Service
if s == "" {
s = "web"
}
output.UserOut.Printf("Importing files via custom files_import_command")
err = p.app.ExecOnHostOrService(s, p.injectedEnvironment()+"; "+p.FilesImportCommand.Command)
}
return err
}
// Write the generic provider configuration to a specified location on disk.
func (p *Provider) Write(configPath string) error {
return nil
}
// Read generic provider configuration from a specified location on disk.
func (p *Provider) Read(configPath string) error {
source, err := os.ReadFile(configPath)
if err != nil {
return err
}
// Read config values from file.
err = yaml.Unmarshal(source, &p.ProviderInfo)
if err != nil {
return err
}
return nil
}
// Validate ensures that the current configuration is valid (i.e. the configured pantheon site/environment exists)
func (p *Provider) Validate() error {
return nil
}
// injectedEnvironment() returns a string with environment variables that should be injected
// before a command.
func (p *Provider) injectedEnvironment() string {
s := "true"
if len(p.EnvironmentVariables) > 0 {
s = "export "
for k, v := range p.EnvironmentVariables {
s = s + fmt.Sprintf(" %s=%s ", k, v)
}
}
return s
}
| apache-2.0 |
torrances/swtk-commons | commons-dict-wordnet-indexbyid/src/main/java/org/swtk/commons/dict/wordnet/indexbyid/instance/p0/p7/WordnetNounIndexIdInstance0715.java | 12851 | package org.swtk.commons.dict.wordnet.indexbyid.instance.p0.p7; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.TreeMap; import org.swtk.common.dict.dto.wordnet.IndexNoun; import com.trimc.blogger.commons.utils.GsonUtils; public final class WordnetNounIndexIdInstance0715 { private static Map<String, Collection<IndexNoun>> map = new TreeMap<String, Collection<IndexNoun>>(); static { add("07150158", "{\"term\":\"gossiping\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07150158\"]}");
add("07150158", "{\"term\":\"gossipmongering\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07150158\"]}");
add("07150335", "{\"term\":\"scandalmongering\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07150335\"]}");
add("07150442", "{\"term\":\"talk\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"07238645\", \"07255209\", \"00894923\", \"07154024\", \"07150442\"]}");
add("07150442", "{\"term\":\"talking\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07150442\"]}");
add("07150806", "{\"term\":\"cant\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"02836781\", \"07150806\", \"07171981\", \"09236735\", \"06620630\"]}");
add("07150806", "{\"term\":\"pious platitude\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07150806\"]}");
add("07150914", "{\"term\":\"dialog\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"06377836\", \"07023657\", \"07150914\"]}");
add("07150914", "{\"term\":\"dialogue\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"07162900\", \"06377836\", \"07023657\", \"07150914\"]}");
add("07150914", "{\"term\":\"duologue\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"07023808\", \"07150914\"]}");
add("07151023", "{\"term\":\"heart-to-heart\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07151023\"]}");
add("07151177", "{\"term\":\"shmooze\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07151177\"]}");
add("07151286", "{\"term\":\"shop talk\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07151286\"]}");
add("07151419", "{\"term\":\"idle words\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07151419\"]}");
add("07151419", "{\"term\":\"jazz\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"07075016\", \"07076737\", \"07151419\"]}");
add("07151419", "{\"term\":\"malarkey\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07151419\"]}");
add("07151419", "{\"term\":\"malarky\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07151419\"]}");
add("07151419", "{\"term\":\"nothingness\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"07151419\", \"14479148\"]}");
add("07151419", "{\"term\":\"wind\", \"synsetCount\":8, \"upperType\":\"NOUN\", \"ids\":[\"00346467\", \"00841258\", \"04594218\", \"06664322\", \"07151419\", \"00838198\", \"11435606\", \"11546388\"]}");
add("07151648", "{\"term\":\"cackle\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"07142159\", \"07151648\", \"07393037\"]}");
add("07151648", "{\"term\":\"chatter\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"07393381\", \"07393552\", \"07151648\"]}");
add("07151648", "{\"term\":\"yack\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07151648\"]}");
add("07151648", "{\"term\":\"yak\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"02407954\", \"07151648\"]}");
add("07151648", "{\"term\":\"yakety-yak\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07151648\"]}");
add("07151837", "{\"term\":\"blether\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07151837\"]}");
add("07151837", "{\"term\":\"chin music\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07151837\"]}");
add("07151837", "{\"term\":\"idle talk\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07151837\"]}");
add("07151837", "{\"term\":\"prate\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07151837\"]}");
add("07151837", "{\"term\":\"prattle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07151837\"]}");
add("07152023", "{\"term\":\"nothings\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07152023\"]}");
add("07152169", "{\"term\":\"honeyed words\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07152169\"]}");
add("07152169", "{\"term\":\"sweet nothings\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07152169\"]}");
add("07152330", "{\"term\":\"commerce\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"07152330\", \"08146250\", \"01092370\"]}");
add("07152441", "{\"term\":\"colloquy\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"07152441\", \"07157752\"]}");
add("07152515", "{\"term\":\"detail\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"08421506\", \"08260002\", \"07152515\", \"13832132\", \"05825971\"]}");
add("07152658", "{\"term\":\"dilation\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"00366821\", \"07152658\"]}");
add("07152793", "{\"term\":\"discourse\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"07152793\", \"07258497\", \"06295430\"]}");
add("07152793", "{\"term\":\"discussion\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"07155367\", \"07152793\"]}");
add("07152793", "{\"term\":\"treatment\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"07152793\", \"04937153\", \"01137182\", \"00659325\"]}");
add("07153212", "{\"term\":\"indirect discourse\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07153212\"]}");
add("07153444", "{\"term\":\"direct discourse\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07153444\"]}");
add("07153444", "{\"term\":\"direct quotation\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07153444\"]}");
add("07153623", "{\"term\":\"consideration\", \"synsetCount\":6, \"upperType\":\"NOUN\", \"ids\":[\"01232282\", \"13344335\", \"04848589\", \"07153623\", \"05831106\", \"05792836\"]}");
add("07153859", "{\"term\":\"expatiation\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07153859\"]}");
add("07154024", "{\"term\":\"talk\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"07238645\", \"07255209\", \"00894923\", \"07154024\", \"07150442\"]}");
add("07154240", "{\"term\":\"reconsideration\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05798017\", \"07154240\"]}");
add("07154408", "{\"term\":\"exhortation\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"07260696\", \"07154408\"]}");
add("07154581", "{\"term\":\"expression\", \"synsetCount\":9, \"upperType\":\"NOUN\", \"ids\":[\"00359354\", \"06324641\", \"13499408\", \"06744551\", \"07083988\", \"07166088\", \"07154581\", \"06893299\", \"04687095\"]}");
add("07154581", "{\"term\":\"verbal expression\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07154581\"]}");
add("07154581", "{\"term\":\"verbalism\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"07104211\", \"07154581\"]}");
add("07154945", "{\"term\":\"cold turkey\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"00229901\", \"07154945\"]}");
add("07155056", "{\"term\":\"congratulation\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"07155056\", \"06646403\"]}");
add("07155056", "{\"term\":\"felicitation\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"06646403\", \"07155056\"]}");
add("07155367", "{\"term\":\"discussion\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"07155367\", \"07152793\"]}");
add("07155367", "{\"term\":\"give-and-take\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"00040890\", \"06790633\", \"07155367\"]}");
add("07155367", "{\"term\":\"word\", \"synsetCount\":10, \"upperType\":\"NOUN\", \"ids\":[\"06443410\", \"06686933\", \"09560255\", \"13648798\", \"07241961\", \"07155367\", \"07183893\", \"06654787\", \"06750911\", \"06297048\"]}");
add("07155686", "{\"term\":\"argument\", \"synsetCount\":7, \"upperType\":\"NOUN\", \"ids\":[\"05781046\", \"05866365\", \"06367706\", \"06479351\", \"07155686\", \"07197811\", \"06661469\"]}");
add("07155686", "{\"term\":\"argumentation\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05781046\", \"07155686\"]}");
add("07155686", "{\"term\":\"debate\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"07256764\", \"07155686\"]}");
add("07156027", "{\"term\":\"logomachy\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07156027\"]}");
add("07156145", "{\"term\":\"parley\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07156145\"]}");
add("07156245", "{\"term\":\"rap\", \"synsetCount\":6, \"upperType\":\"NOUN\", \"ids\":[\"00134158\", \"07078095\", \"07156245\", \"07403587\", \"07424621\", \"06726691\"]}");
add("07156352", "{\"term\":\"rap session\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07156352\"]}");
add("07156497", "{\"term\":\"second-hand speech\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07156497\"]}");
add("07156630", "{\"term\":\"table talk\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07156630\"]}");
add("07156713", "{\"term\":\"telephone conversation\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07156713\"]}");
add("07156815", "{\"term\":\"tete-a-tete\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"03698800\", \"07156815\"]}");
add("07156950", "{\"term\":\"pillow talk\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07156950\"]}");
add("07157073", "{\"term\":\"deliberation\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"04668508\", \"05069146\", \"05804431\", \"05793072\", \"07157073\"]}");
add("07157274", "{\"term\":\"conference\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"07157274\", \"08248105\", \"08325427\"]}");
add("07157274", "{\"term\":\"group discussion\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07157274\"]}");
add("07157632", "{\"term\":\"bull session\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07157632\"]}");
add("07157752", "{\"term\":\"colloquy\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"07152441\", \"07157752\"]}");
add("07157845", "{\"term\":\"consultation\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"01266543\", \"07157845\", \"07158332\"]}");
add("07158158", "{\"term\":\"sidebar\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"06282056\", \"07158158\"]}");
add("07158332", "{\"term\":\"audience\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"07158332\", \"14508362\", \"08239214\", \"08238818\"]}");
add("07158332", "{\"term\":\"consultation\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"01266543\", \"07157845\", \"07158332\"]}");
add("07158332", "{\"term\":\"interview\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"07158332\", \"07210735\"]}");
add("07158577", "{\"term\":\"panel discussion\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07158577\"]}");
add("07158747", "{\"term\":\"post-mortem\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"00142216\", \"07158747\"]}");
add("07158747", "{\"term\":\"postmortem\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"00142216\", \"07158747\"]}");
add("07158898", "{\"term\":\"public discussion\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07158898\"]}");
add("07158898", "{\"term\":\"ventilation\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"00832852\", \"07158898\", \"04533815\", \"00267489\"]}");
add("07159124", "{\"term\":\"huddle\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"08201357\", \"07159124\"]}");
add("07159124", "{\"term\":\"powwow\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"08339360\", \"07159124\"]}");
add("07159279", "{\"term\":\"backgrounder\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07159279\"]}");
add("07159542", "{\"term\":\"news conference\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07159542\"]}");
add("07159542", "{\"term\":\"press conference\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07159542\"]}");
add("07159734", "{\"term\":\"pretrial\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07159734\"]}");
add("07159734", "{\"term\":\"pretrial conference\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07159734\"]}");
} private static void add(final String ID, final String JSON) { IndexNoun indexNoun = GsonUtils.toObject(JSON, IndexNoun.class); Collection<IndexNoun> list = (map.containsKey(ID)) ? map.get(ID) : new ArrayList<IndexNoun>(); list.add(indexNoun); map.put(ID, list); } public static Collection<IndexNoun> get(final String TERM) { return map.get(TERM); } public static boolean has(final String TERM) { return map.containsKey(TERM); } public static Collection<String> ids() { return map.keySet(); } } | apache-2.0 |
firebase/snippets-web | auth-next/auth-state-persistence.js | 1667 | // [SNIPPET_REGISTRY disabled]
// [SNIPPETS_SEPARATION enabled]
function setPersistenceSession() {
const email = "...";
const password = "...";
// [START auth_set_persistence_session]
const { getAuth, setPersistence, signInWithEmailAndPassword, browserSessionPersistence } = require("firebase/auth");
const auth = getAuth();
setPersistence(auth, browserSessionPersistence)
.then(() => {
// Existing and future Auth states are now persisted in the current
// session only. Closing the window would clear any existing state even
// if a user forgets to sign out.
// ...
// New sign-in will be persisted with session persistence.
return signInWithEmailAndPassword(auth, email, password);
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
});
// [END auth_set_persistence_session]
}
function setPersistenceNone() {
// [START auth_set_persistence_none]
const { getAuth, setPersistence, signInWithRedirect, inMemoryPersistence, GoogleAuthProvider } = require("firebase/auth");
const auth = getAuth();
setPersistence(auth, inMemoryPersistence)
.then(() => {
const provider = new GoogleAuthProvider();
// In memory persistence will be applied to the signed in Google user
// even though the persistence was set to 'none' and a page redirect
// occurred.
return signInWithRedirect(auth, provider);
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
});
// [END auth_set_persistence_none]
}
| apache-2.0 |
ArnaudRabeony/SiteMarchand | model/taille.php | 1294 | <?php
require_once(dirname(__FILE__) . '/../connection.php');
function getIdTailleByName($db, $name)
{
$req = $db->prepare('select idTaille from taille where nomTaille = :nomTaille');
$req->bindValue(':nomTaille', $name);
$req->execute();
$res = $req->fetch(PDO::FETCH_NUM);
return $res[0];
}
function getTailleById($db, $idTaille)
{
$req = $db->prepare('select nomTaille from taille where idTaille = :idTaille');
$req->bindValue(':idTaille', $idTaille);
$req->execute();
$res = $req->fetch(PDO::FETCH_NUM);
return $res[0];
}
function getAllTaille($db)
{
$req = $db->prepare('select * from taille');
$req->execute();
return $req->fetchAll();
}
function getSizeByCategories($db,$idCategorie)
{
$req = $db->prepare('select t.nomTaille from categorie_produit c join taille t on t.idCategorie=c.idCategorie where t.idCategorie=:id');
$req->bindValue(':id', $idCategorie);
$req->execute();
$returned=array();
while($res = $req->fetch(PDO::FETCH_NUM))
$returned[]=$res[0];
return $returned;
}
function getShoeSizes($db)
{
$id=getIdCategorieByName($db,"Chaussures");
return getSizeByCategories($db,$id);
}
function getSizes($db)
{
// $id=getIdCategorieByName($db,);
return getSizeByCategories($db,1);
} | apache-2.0 |
wwitzel3/awx | awx/main/management/commands/cleanup_activitystream.py | 2751 | # Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.
# Python
import datetime
import logging
import six
# Django
from django.core.management.base import BaseCommand
from django.utils.timezone import now
# AWX
from awx.main.models import ActivityStream
class Command(BaseCommand):
'''
Management command to purge old activity stream events.
'''
help = 'Remove old activity stream events from the database'
def add_arguments(self, parser):
parser.add_argument('--days', dest='days', type=int, default=90, metavar='N',
help='Remove activity stream events more than N days old')
parser.add_argument('--dry-run', dest='dry_run', action='store_true',
default=False, help='Dry run mode (show items that would '
'be removed)')
def init_logging(self):
log_levels = dict(enumerate([logging.ERROR, logging.INFO,
logging.DEBUG, 0]))
self.logger = logging.getLogger('awx.main.commands.cleanup_activitystream')
self.logger.setLevel(log_levels.get(self.verbosity, 0))
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(message)s'))
self.logger.addHandler(handler)
self.logger.propagate = False
def cleanup_activitystream(self):
n_deleted_items = 0
pks_to_delete = set()
for asobj in ActivityStream.objects.iterator():
asobj_disp = '"%s" id: %s' % (six.text_type(asobj), asobj.id)
if asobj.timestamp >= self.cutoff:
if self.dry_run:
self.logger.info("would skip %s" % asobj_disp)
else:
if self.dry_run:
self.logger.info("would delete %s" % asobj_disp)
else:
pks_to_delete.add(asobj.pk)
# Cleanup objects in batches instead of deleting each one individually.
if len(pks_to_delete) >= 500:
ActivityStream.objects.filter(pk__in=pks_to_delete).delete()
n_deleted_items += len(pks_to_delete)
pks_to_delete.clear()
if len(pks_to_delete):
ActivityStream.objects.filter(pk__in=pks_to_delete).delete()
n_deleted_items += len(pks_to_delete)
self.logger.log(99, "Removed %d items", n_deleted_items)
def handle(self, *args, **options):
self.verbosity = int(options.get('verbosity', 1))
self.init_logging()
self.days = int(options.get('days', 30))
self.cutoff = now() - datetime.timedelta(days=self.days)
self.dry_run = bool(options.get('dry_run', False))
self.cleanup_activitystream()
| apache-2.0 |
shibing624/similarity | src/main/java/org/xm/similarity/word/clin/CilinCode.java | 2145 | package org.xm.similarity.word.clin;
/**
* 哈工大词林扩展版规则编码表
* 表中编码位从左到右顺序排列,其中,第8位对应的标记位为“=”、“#”和“@”三种符号之一。其中“=”代表常见的“同义”关系,
* “#”代表词语之间的相关关系,“@”则代表词语自我封闭的独立性质,它在词典中既没有同义词,也没有相关词。
*
* @author xuming
*/
public class CilinCode {
public static double[] WEIGHT = new double[]{1.2, 1.2, 1.0, 1.0, 0.8, 0.4};
public static double TOTAL_WEIGHT = 5.6;
public static String getCodeLevel(String code, int level) {
switch (level) {
case 1:
return code.substring(0, 1);
case 2:
return code.substring(1, 2);
case 3:
return code.substring(2, 4);
case 4:
return code.substring(4, 5);
case 5:
return code.substring(5, 7);
case 6:
return code.substring(7);
}
return "";
}
/**
* 获取共同部分编码的权重
*
* @param code1
* @param code2
* @return
*/
public static double calculateCommonWeight(String code1, String code2) {
double weight = 0.0;
for (int i = 1; i <= 6; i++) {
String c1 = getCodeLevel(code1, i);
String c2 = getCodeLevel(code2, i);
if (c1.equals(c2)) {
weight += WEIGHT[i - 1];
} else {
break;
}
}
return weight;
}
/**
* 打印
*
* @param code
* @return
*/
public static String printCoding(String code) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 6; i++) {
if (i == 1) {
sb.append("[LEVEL_" + i);
} else {
sb.append(", LEVEL_" + i);
}
sb.append(": ");
sb.append(getCodeLevel(code, i));
}
sb.append("]");
return sb.toString();
}
}
| apache-2.0 |
bozimmerman/CoffeeMud | com/planet_ink/coffee_mud/Abilities/Specializations/Familiarity_Hammer.java | 1896 | package com.planet_ink.coffee_mud.Abilities.Specializations;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2018-2022 Bo Zimmerman
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.
*/
public class Familiarity_Hammer extends Familiarity_Weapon
{
@Override
public String ID()
{
return "Familiarity_Hammer";
}
private final static String localizedName = CMLib.lang().L("Hammer Familiarity");
@Override
public String name()
{
return localizedName;
}
public Familiarity_Hammer()
{
super();
weaponClass=Weapon.CLASS_HAMMER;
}
}
| apache-2.0 |
aj-jaswanth/gocd | server/webapp/WEB-INF/rails.new/spec/new_javascripts/views/agents/agents_widget_spec.js | 11206 | /*
* Copyright 2016 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
define(["jquery", "mithril", 'models/agents/agents', "views/agents/agents_widget"], function ($, m, Agents, AgentsWidget) {
describe("Agents Widget", function () {
var $root = $('#mithril-mount-point'), root = $root.get(0);
var agents;
beforeAll(function () {
jasmine.Ajax.install();
jasmine.Ajax.stubRequest(/\/api\/agents/).andReturn({
"responseText": JSON.stringify(agentsData),
"status": 200
});
});
beforeEach(function () {
mount();
});
afterEach(function () {
unmount();
});
afterAll(function () {
jasmine.Ajax.uninstall();
});
it('should contain the agents state count information', function () {
var agentStateCount = $root.find('.search-summary')[0];
var stateCountInfo = "Total2Pending0Enabled0Disabled2";
expect($(agentStateCount).text()).toBe(stateCountInfo);
});
it('should contain the agent rows equal to the number of agents', function () {
var agentRows = $root.find('table tbody tr');
expect(agentRows.length).toBe(2);
});
it('should contain the agent row information', function () {
var agentInfo = $root.find('table tbody tr')[0];
var firstAgentInfo = $(agentInfo).find('td');
expect(firstAgentInfo.length).toBe(9);
expect($(firstAgentInfo[0]).html()).toBe('<input type="checkbox">');
expect($(firstAgentInfo[1]).text()).toBe('host-1');
expect($(firstAgentInfo[2]).text()).toBe('usr/local/foo');
expect($(firstAgentInfo[3]).text()).toBe('Linux');
expect($(firstAgentInfo[4]).text()).toBe('10.12.2.200');
expect($(firstAgentInfo[5]).text()).toBe('Disabled');
expect($(firstAgentInfo[6]).text()).toBe('Unknown');
expect($(firstAgentInfo[7]).text()).toBe('Firefox');
expect($(firstAgentInfo[8]).text()).toBe('Dev, Test');
});
it('should select all the agents when selectAll checkbox is selected', function () {
var allBoxes = $root.find('tbody :checkbox');
var selectAllCheckbox = $root.find('thead :checkbox');
expect(selectAllCheckbox[0].checked).toBe(false);
expect(allBoxes[0].checked).toBe(false);
$(selectAllCheckbox).click();
m.redraw(true);
expect(selectAllCheckbox[0].checked).toBe(true);
expect(allBoxes[0].checked).toBe(true);
});
it('should hide all dropdown on click of the body', function () {
var selectAllCheckbox = $root.find('thead :checkbox');
$(selectAllCheckbox).click();
m.redraw(true);
var resourceButton = $root.find("button:contains('Resources')");
resourceButton.click();
m.redraw(true);
expect($(resourceButton).parent().attr('class')).toContain('is-open');
var body = $root.find('.search-panel');
$(body).click();
m.redraw(true);
expect($(resourceButton).parent().attr('class')).not.toContain('is-open');
});
it('should not hide dropdown on click of dropdown list', function () {
var selectAllCheckbox = $root.find('thead :checkbox');
selectAllCheckbox.click();
var resourceButton = $root.find("button:contains('Resources')");
$(resourceButton).click();
m.redraw(true);
expect($(resourceButton).parent().attr('class')).toContain('is-open');
$(resourceButton).parent().click();
expect($(resourceButton).parent().attr('class')).toContain('is-open');
var disableButton = $root.find("button:contains('Disable')");
$(disableButton).click();
});
it('should show message after disabling the agents', function () {
var agents_checkbox = $root.find('.go-table thead tr input[type="checkbox"]');
$(agents_checkbox[0]).click();
m.redraw(true);
var disableButton = $root.find("button:contains('Disable')");
var message = $root.find('.alert-box');
expect(message.length).toBe(0);
$(disableButton).click();
m.redraw(true);
var message = $root.find('.callout');
expect(message.text()).toBe('Disabled 2 agents');
});
it('should show message after enabling the agents', function () {
var agents_checkbox = $root.find('.go-table thead tr input[type="checkbox"]');
$(agents_checkbox[0]).click();
m.redraw(true);
var buttons = $root.find('.agent-button-group button');
var message = $root.find('.callout');
expect(message.length).toBe(0);
buttons[2].click();
m.redraw(true);
var message = $root.find('.callout');
expect(message.text()).toBe('Enabled 2 agents');
});
it('should show message after deleting the agents', function () {
var agents_checkbox = $root.find('.go-table thead tr input[type="checkbox"]');
var delete_button = $root.find('.agent-button-group button')[0];
$(agents_checkbox[0]).click();
m.redraw(true);
expect(delete_button.disabled).toBe(false);
delete_button.click();
m.redraw(true);
var message = $root.find('.callout');
expect(message.text()).toBe('Deleted 2 agents');
expect(delete_button.disabled).toBe(true);
});
it('should show message after updating resource of the agents', function () {
var resource = $root.find('.add-resource');
var agents_checkbox = $root.find('.go-table thead tr input[type="checkbox"]');
var apply_resource = resource.find('button')[1];
$(agents_checkbox[0]).click();
m.redraw(true);
apply_resource.click();
m.redraw(true);
var message = $root.find('.callout');
expect(message.text()).toBe('Resources modified on 2 agents');
});
it('should show message after updating environment of the agents', function () {
var environment = $root.find('.env-dropdown');
var agents_checkbox = $root.find('.go-table thead tr input[type="checkbox"]');
var apply_environment = environment.find('button');
$(agents_checkbox[0]).click();
m.redraw(true);
apply_environment.click();
m.redraw(true);
var message = $root.find('.callout');
expect(message.text()).toBe('Environment modified on 2 agents');
});
it('should show only filtered agents after inserting filter text', function () {
var search_field = $root.find('#filter-agent')[0];
var no_of_agents_on_page = $root.find('table tbody tr');
expect(no_of_agents_on_page.length).toBe(2);
$(search_field).val('host-2').trigger('input');
m.redraw(true);
expect($(search_field).val()).toBe('host-2');
no_of_agents_on_page = $root.find('table tbody tr');
expect(no_of_agents_on_page.length).toBe(1);
});
it('should filter the agents based on filter text value', function () {
var search_field = $root.find('#filter-agent')[0];
$(search_field).val('').trigger('input');
m.redraw(true);
var no_of_agents_on_page = $root.find('table tbody tr');
expect(no_of_agents_on_page.length).toBe(2);
$(search_field).val('invalidtextnotvalid').trigger('input');
m.redraw(true);
expect($(search_field).val()).toBe('invalidtextnotvalid');
no_of_agents_on_page = $root.find('table tbody tr');
expect(no_of_agents_on_page.length).toBe(0);
$(search_field).val('').trigger('input');
m.redraw(true);
expect($(search_field).val()).toBe('');
no_of_agents_on_page = $root.find('table tbody tr');
expect(no_of_agents_on_page.length).toBe(2);
});
it('should preserve the selection of agents during filter', function () {
var search_field = $root.find('#filter-agent')[0];
$(search_field).val('host-1').trigger('input');
m.redraw(true);
var allBoxes = $root.find('.go-table tbody tr input[type="checkbox"]');
expect(allBoxes.length).toBe(1);
$(allBoxes[0]).prop('checked', true).trigger('input');
expect(allBoxes[0].checked).toBe(true);
$(search_field).val('').trigger('input');
m.redraw(true);
var allBoxes = $root.find('.go-table tbody tr input[type="checkbox"]');
expect(allBoxes.length).toBe(2);
expect(allBoxes[0].checked).toBe(true);
expect(allBoxes[1].checked).toBe(false);
});
var mount = function () {
m.mount(root,
m.component(AgentsWidget)
);
m.redraw(true);
};
var unmount = function () {
m.mount(root, null);
m.redraw(true);
};
var agentsData = {
"_embedded": {
"agents": [
{
"_links": {
"self": {
"href": "https://ci.example.com/go/api/agents/dfdbe0b1-4521-4a52-ac2f-ca0cf6bdaa3e"
},
"doc": {
"href": "http://api.go.cd/#agents"
},
"find": {
"href": "https://ci.example.com/go/api/agents/:uuid"
}
},
"uuid": "dfdbe0b1-4521-4a52-ac2f-ca0cf6bdaa3e",
"hostname": "host-1",
"ip_address": "10.12.2.200",
"sandbox": "usr/local/foo",
"operating_system": "Linux",
"free_space": "unknown",
"agent_config_state": "Disabled",
"agent_state": "Missing",
"build_state": "Unknown",
"resources": [
"Firefox"
],
"environments": [
"Dev",
"Test"
]
},
{
"_links": {
"self": {
"href": "https://ci.example.com/go/api/agents/dfdbe0b1-aa31-4a52-ac42d-ca0cf6bdaa3e"
},
"doc": {
"href": "http://api.go.cd/#agents"
},
"find": {
"href": "https://ci.example.com/go/api/agents/:uuid"
}
},
"uuid": "dfdbe0b1-aa31-4a52-ac42d-ca0cf6bdaa3e",
"hostname": "host-2",
"ip_address": "10.12.2.201",
"sandbox": "usr/local/bin",
"operating_system": "Linux",
"free_space": "unknown",
"agent_config_state": "Disabled",
"agent_state": "Missing",
"build_state": "Unknown",
"resources": [
"Chrome"
],
"environments": [
"Test"
]
}
]
}
};
});
});
| apache-2.0 |
JavaUAM2016/PracticasOCA | Practica4/fesrton/javaApp4/src/mx/edu/uam/practica4/factory/SystemaFactory.java | 945 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mx.edu.uam.practica4.factory;
/**
*
* @author ferso
*/
public abstract class SystemaFactory {
public static AbastractFactory getFactory(String choice) {
AbastractFactory factoryType = null;
switch (choice) {
case "CONTROL":
factoryType = new ControlFactory();
break;
case "ELECTRODOMESTICO":
factoryType = new ElectrodomesticoFactory() {};
break;
case "FAMILIAR":
factoryType = new FamiliarFactory() {};
break;
default:
System.err.println("Error no hay fabrica para el Componente solicitada: "+choice);
}
return factoryType;
}
}
| apache-2.0 |
yukuai518/gobblin | gobblin-data-management/src/main/java/gobblin/data/management/partition/StaticFileSet.java | 688 | package gobblin.data.management.partition;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import gobblin.data.management.copy.CopyEntity;
import gobblin.dataset.Dataset;
/**
* A non-lazy {@link FileSet} where the copy entities are a static, eagerly computed list of {@link CopyEntity}s.
* @param <T>
*/
public class StaticFileSet<T extends CopyEntity> extends FileSet<T> {
private final List<T> files;
public StaticFileSet(String name, Dataset dataset, List<T> files) {
super(name, dataset);
this.files = files;
}
@Override
protected Collection<T> generateCopyEntities()
throws IOException {
return this.files;
}
}
| apache-2.0 |
pegasus-isi/pegasus | src/edu/isi/pegasus/planner/catalog/classes/CatalogEntryJsonDeserializer.java | 1314 | /*
*
* Copyright 2007-2008 University Of Southern California
*
* 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 edu.isi.pegasus.planner.catalog.classes;
import edu.isi.pegasus.planner.catalog.CatalogException;
import edu.isi.pegasus.planner.common.PegasusJsonDeserializer;
/**
* Abstract Class for Deserializers for parsing Catalog Data Objects
*
* @author Karan Vahi
* @param <T> class
*/
public abstract class CatalogEntryJsonDeserializer<T> extends PegasusJsonDeserializer<T> {
/**
* The exception to be thrown while deserializing on error
*
* @param message the error message
* @return RuntimeException
*/
@Override
public RuntimeException getException(String message) {
return new CatalogException(message);
}
}
| apache-2.0 |
sasquatch-mc/zelo | src/org/zelo/ast/expression/essential_functions/LowerThan.java | 99 | package org.zelo.ast.expression.essential_functions;
public class LowerThan extends Essential {
}
| apache-2.0 |
veritone/veritone-sdk | packages/veritone-react-common/src/components/FormBuilder/helpers.test.js | 2906 | import * as formHelpers from './helpers';
describe('Validate empty helper', () => {
it('Should return error if required but no data', () => {
expect(formHelpers.validateEmpty({
data: { firstName: '' },
settings: { name: 'firstName', required: true }
}))
.toBe('FIRSTNAME is required')
})
it('Should return empty if not required', () => {
expect(formHelpers.validateEmpty({
data: { firstName: '' },
settings: { name: 'firstName', required: false }
}))
.toBe(undefined)
})
it('Should return empty if not required and not empty', () => {
expect(formHelpers.validateEmpty({
data: { firstName: 'veritoneClient' },
settings: { name: 'firstName', required: true }
}))
.toBe('')
})
})
describe('Validate email helper', () => {
it('Should return error if not an email', () => {
expect(formHelpers.validateEmail({
data: { email: 'abc' },
settings: { name: 'email' }
}))
.toBe('Please enter a valid email address')
})
it('Should not return error if is an email', () => {
expect(formHelpers.validateEmail({
data: { email: '[email protected]' },
settings: { name: 'email' }
}))
.toBe('')
})
})
describe('Validate range helper', () => {
it('Should return an error if larger than max', () => {
expect(formHelpers.validateRange({
data: { number: 6 },
settings: { max: 5, name: 'number' }
}))
.toBe('Maximum number can be 5')
})
it('Should return an error if larger than max', () => {
expect(formHelpers.validateRange({
data: { number: 1 },
settings: { min: 3, name: 'number' }
}))
.toBe('Minimum required number is 3')
})
it('Should return an error if not in range', () => {
expect(formHelpers.validateRange({
data: { number: 2 },
settings: { min: 3, max: 5, name: 'number' }
}))
.toBe('number must be between 3 and 5')
})
it('Empty error if in range', () => {
expect(formHelpers.validateRange({
data: { number: 4 },
settings: { min: 3, max: 5, name: 'number' }
}))
.toBe('')
})
})
describe('errorChain', () => {
const inputObject = { data: {}, settings: {} };
const errorFunc = formHelpers.errorChain(inputObject);
it('when input is a function', () => {
const mockFunc = jest.fn();
errorFunc(mockFunc);
expect(mockFunc).toHaveBeenCalledWith(inputObject);
})
it('when input is an array of function', () => {
const mockFunc1 = jest.fn();
const mockFunc2 = jest.fn();
const mockFunc3 = jest.fn();
mockFunc2.mockReturnValue('error');
expect(errorFunc([mockFunc1, mockFunc2, mockFunc3])).toBe('error');
expect(mockFunc1).toHaveBeenCalledWith(inputObject);
expect(mockFunc2).toHaveBeenCalledWith(inputObject);
expect(mockFunc3).not.toHaveBeenCalled(); // Short circuit if found an error
})
})
| apache-2.0 |
qwerty4030/elasticsearch | test/framework/src/main/java/org/elasticsearch/test/AbstractQueryTestCase.java | 53333 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.test;
import com.fasterxml.jackson.core.io.JsonStringEncoder;
import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.spans.SpanBoostQuery;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.IOUtils;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.action.termvectors.MultiTermVectorsRequest;
import org.elasticsearch.action.termvectors.MultiTermVectorsResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.Writeable.Reader;
import org.elasticsearch.common.settings.IndexScopedSettings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.xcontent.DeprecationHandler;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentGenerator;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.analysis.IndexAnalyzers;
import org.elasticsearch.index.cache.bitset.BitsetFilterCache;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.fielddata.IndexFieldDataCache;
import org.elasticsearch.index.fielddata.IndexFieldDataService;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryRewriteContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.Rewriteable;
import org.elasticsearch.index.query.support.QueryParsers;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.similarity.SimilarityService;
import org.elasticsearch.indices.IndicesModule;
import org.elasticsearch.indices.analysis.AnalysisModule;
import org.elasticsearch.indices.breaker.NoneCircuitBreakerService;
import org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache;
import org.elasticsearch.indices.mapper.MapperRegistry;
import org.elasticsearch.node.InternalSettingsPreparer;
import org.elasticsearch.plugins.MapperPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.plugins.PluginsService;
import org.elasticsearch.plugins.ScriptPlugin;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.SearchModule;
import org.elasticsearch.search.internal.SearchContext;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import java.util.stream.Stream;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
import static org.elasticsearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.either;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.instanceOf;
public abstract class AbstractQueryTestCase<QB extends AbstractQueryBuilder<QB>> extends ESTestCase {
public static final String STRING_FIELD_NAME = "mapped_string";
protected static final String STRING_FIELD_NAME_2 = "mapped_string_2";
protected static final String INT_FIELD_NAME = "mapped_int";
protected static final String INT_RANGE_FIELD_NAME = "mapped_int_range";
protected static final String DOUBLE_FIELD_NAME = "mapped_double";
protected static final String BOOLEAN_FIELD_NAME = "mapped_boolean";
protected static final String DATE_FIELD_NAME = "mapped_date";
protected static final String DATE_RANGE_FIELD_NAME = "mapped_date_range";
protected static final String OBJECT_FIELD_NAME = "mapped_object";
protected static final String GEO_POINT_FIELD_NAME = "mapped_geo_point";
protected static final String GEO_SHAPE_FIELD_NAME = "mapped_geo_shape";
protected static final String[] MAPPED_FIELD_NAMES = new String[]{STRING_FIELD_NAME, INT_FIELD_NAME, INT_RANGE_FIELD_NAME,
DOUBLE_FIELD_NAME, BOOLEAN_FIELD_NAME, DATE_FIELD_NAME, DATE_RANGE_FIELD_NAME, OBJECT_FIELD_NAME, GEO_POINT_FIELD_NAME,
GEO_SHAPE_FIELD_NAME};
private static final String[] MAPPED_LEAF_FIELD_NAMES = new String[]{STRING_FIELD_NAME, INT_FIELD_NAME, INT_RANGE_FIELD_NAME,
DOUBLE_FIELD_NAME, BOOLEAN_FIELD_NAME, DATE_FIELD_NAME, DATE_RANGE_FIELD_NAME, GEO_POINT_FIELD_NAME, };
private static final int NUMBER_OF_TESTQUERIES = 20;
protected static Version indexVersionCreated;
private static ServiceHolder serviceHolder;
private static int queryNameId = 0;
private static Settings nodeSettings;
private static Index index;
private static String[] currentTypes;
private static String[] randomTypes;
protected static Index getIndex() {
return index;
}
protected static String[] getCurrentTypes() {
return currentTypes;
}
protected Collection<Class<? extends Plugin>> getPlugins() {
return Collections.emptyList();
}
protected void initializeAdditionalMappings(MapperService mapperService) throws IOException {
}
@BeforeClass
public static void beforeClass() {
nodeSettings = Settings.builder()
.put("node.name", AbstractQueryTestCase.class.toString())
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir())
.build();
index = new Index(randomAlphaOfLengthBetween(1, 10), "_na_");
// Set a single type in the index
switch (random().nextInt(3)) {
case 0:
currentTypes = new String[0]; // no types
break;
default:
currentTypes = new String[] { "_doc" };
break;
}
randomTypes = getRandomTypes();
}
protected Settings indexSettings() {
// we have to prefer CURRENT since with the range of versions we support it's rather unlikely to get the current actually.
indexVersionCreated = randomBoolean() ? Version.CURRENT
: VersionUtils.randomVersionBetween(random(), null, Version.CURRENT);
return Settings.builder()
.put(IndexMetaData.SETTING_VERSION_CREATED, indexVersionCreated)
.build();
}
@AfterClass
public static void afterClass() throws Exception {
IOUtils.close(serviceHolder);
serviceHolder = null;
}
@Before
public void beforeTest() throws IOException {
if (serviceHolder == null) {
serviceHolder = new ServiceHolder(nodeSettings, indexSettings(), getPlugins(), this);
}
serviceHolder.clientInvocationHandler.delegate = this;
}
private static SearchContext getSearchContext(String[] types, QueryShardContext context) {
TestSearchContext testSearchContext = new TestSearchContext(context) {
@Override
public MapperService mapperService() {
return serviceHolder.mapperService; // need to build / parse inner hits sort fields
}
@Override
public <IFD extends IndexFieldData<?>> IFD getForField(MappedFieldType fieldType) {
return serviceHolder.indexFieldDataService.getForField(fieldType); // need to build / parse inner hits sort fields
}
};
testSearchContext.getQueryShardContext().setTypes(types);
return testSearchContext;
}
@After
public void afterTest() {
serviceHolder.clientInvocationHandler.delegate = null;
}
public final QB createTestQueryBuilder() {
QB query = doCreateTestQueryBuilder();
//we should not set boost and query name for queries that don't parse it
if (supportsBoostAndQueryName()) {
if (randomBoolean()) {
query.boost(2.0f / randomIntBetween(1, 20));
}
if (randomBoolean()) {
query.queryName(createUniqueRandomName());
}
}
return query;
}
/**
* make sure query names are unique by suffixing them with increasing counter
*/
private static String createUniqueRandomName() {
String queryName = randomAlphaOfLengthBetween(1, 10) + queryNameId;
queryNameId++;
return queryName;
}
/**
* Create the query that is being tested
*/
protected abstract QB doCreateTestQueryBuilder();
/**
* Generic test that creates new query from the test query and checks both for equality
* and asserts equality on the two queries.
*/
public void testFromXContent() throws IOException {
for (int runs = 0; runs < NUMBER_OF_TESTQUERIES; runs++) {
QB testQuery = createTestQueryBuilder();
XContentType xContentType = randomFrom(XContentType.values());
BytesReference shuffledXContent = toShuffledXContent(testQuery, xContentType, ToXContent.EMPTY_PARAMS, randomBoolean(),
shuffleProtectedFields());
assertParsedQuery(createParser(xContentType.xContent(), shuffledXContent), testQuery);
for (Map.Entry<String, QB> alternateVersion : getAlternateVersions().entrySet()) {
String queryAsString = alternateVersion.getKey();
assertParsedQuery(createParser(JsonXContent.jsonXContent, queryAsString), alternateVersion.getValue());
}
}
}
/**
* Subclasses can override this method and return an array of fieldnames which should be protected from
* recursive random shuffling in the {@link #testFromXContent()} test case
*/
protected String[] shuffleProtectedFields() {
return Strings.EMPTY_ARRAY;
}
/**
* Test that unknown field trigger ParsingException.
* To find the right position in the root query, we add a marker as `queryName` which
* all query builders support. The added bogus field after that should trigger the exception.
* Queries that allow arbitrary field names at this level need to override this test.
*/
public void testUnknownField() {
String marker = "#marker#";
QB testQuery;
do {
testQuery = createTestQueryBuilder();
} while (testQuery.toString().contains(marker));
testQuery.queryName(marker); // to find root query to add additional bogus field there
String queryAsString = testQuery.toString().replace("\"" + marker + "\"", "\"" + marker + "\", \"bogusField\" : \"someValue\"");
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(queryAsString));
// we'd like to see the offending field name here
assertThat(e.getMessage(), containsString("bogusField"));
}
/**
* Test that adding an additional object within each object of the otherwise correct query always triggers some kind of
* parse exception. Some specific objects do not cause any exception as they can hold arbitrary content; they can be
* declared by overriding {@link #getObjectsHoldingArbitraryContent()}.
*/
public final void testUnknownObjectException() throws IOException {
Set<String> candidates = new HashSet<>();
// Adds the valid query to the list of queries to modify and test
candidates.add(createTestQueryBuilder().toString());
// Adds the alternates versions of the query too
candidates.addAll(getAlternateVersions().keySet());
List<Tuple<String, Boolean>> testQueries = alterateQueries(candidates, getObjectsHoldingArbitraryContent());
for (Tuple<String, Boolean> testQuery : testQueries) {
boolean expectedException = testQuery.v2();
try {
parseQuery(testQuery.v1());
if (expectedException) {
fail("some parsing exception expected for query: " + testQuery);
}
} catch (ParsingException | ElasticsearchParseException e) {
// different kinds of exception wordings depending on location
// of mutation, so no simple asserts possible here
if (expectedException == false) {
throw new AssertionError("unexpected exception when parsing query:\n" + testQuery, e);
}
} catch (IllegalArgumentException e) {
if (expectedException == false) {
throw new AssertionError("unexpected exception when parsing query:\n" + testQuery, e);
}
assertThat(e.getMessage(), containsString("unknown field [newField], parser not found"));
}
}
}
/**
* Traverses the json tree of the valid query provided as argument and mutates it one or more times by adding one object within each
* object encountered.
*
* For instance given the following valid term query:
* {
* "term" : {
* "field" : {
* "value" : "foo"
* }
* }
* }
*
* The following two mutations will be generated, and an exception is expected when trying to parse them:
* {
* "term" : {
* "newField" : {
* "field" : {
* "value" : "foo"
* }
* }
* }
* }
*
* {
* "term" : {
* "field" : {
* "newField" : {
* "value" : "foo"
* }
* }
* }
* }
*
* Every mutation is then added to the list of results with a boolean flag indicating if a parsing exception is expected or not
* for the mutation. Some specific objects do not cause any exception as they can hold arbitrary content; they are passed using the
* arbitraryMarkers parameter.
*/
static List<Tuple<String, Boolean>> alterateQueries(Set<String> queries, Set<String> arbitraryMarkers) throws IOException {
List<Tuple<String, Boolean>> results = new ArrayList<>();
// Indicate if a part of the query can hold any arbitrary content
boolean hasArbitraryContent = (arbitraryMarkers != null && arbitraryMarkers.isEmpty() == false);
for (String query : queries) {
// Track the number of query mutations
int mutation = 0;
while (true) {
boolean expectException = true;
BytesStreamOutput out = new BytesStreamOutput();
try (
XContentGenerator generator = XContentType.JSON.xContent().createGenerator(out);
XContentParser parser = JsonXContent.jsonXContent
.createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, query);
) {
int objectIndex = -1;
Deque<String> levels = new LinkedList<>();
// Parse the valid query and inserts a new object level called "newField"
XContentParser.Token token;
while ((token = parser.nextToken()) != null) {
if (token == XContentParser.Token.START_ARRAY) {
levels.addLast(parser.currentName());
} else if (token == XContentParser.Token.START_OBJECT) {
objectIndex++;
levels.addLast(parser.currentName());
if (objectIndex == mutation) {
// We reached the place in the object tree where we want to insert a new object level
generator.writeStartObject();
generator.writeFieldName("newField");
XContentHelper.copyCurrentStructure(generator, parser);
generator.writeEndObject();
if (hasArbitraryContent) {
// The query has one or more fields that hold arbitrary content. If the current
// field is one (or a child) of those, no exception is expected when parsing the mutated query.
for (String marker : arbitraryMarkers) {
if (levels.contains(marker)) {
expectException = false;
break;
}
}
}
// Jump to next token
continue;
}
} else if (token == XContentParser.Token.END_OBJECT || token == XContentParser.Token.END_ARRAY) {
levels.removeLast();
}
// We are walking through the object tree, so we can safely copy the current node
XContentHelper.copyCurrentEvent(generator, parser);
}
if (objectIndex < mutation) {
// We did not reach the insertion point, there's no more mutations to try
break;
} else {
// We reached the expected insertion point, so next time we'll try one step further
mutation++;
}
}
results.add(new Tuple<>(out.bytes().utf8ToString(), expectException));
}
}
return results;
}
/**
* Returns a set of object names that won't trigger any exception (uncluding their children) when testing that unknown
* objects cause parse exceptions through {@link #testUnknownObjectException()}. Default is an empty set. Can be overridden
* by subclasses that test queries which contain objects that get parsed on the data nodes (e.g. score functions) or objects
* that can contain arbitrary content (e.g. documents for percolate or more like this query, params for scripts). In such
* cases no exception would get thrown.
*/
protected Set<String> getObjectsHoldingArbitraryContent() {
return Collections.emptySet();
}
/**
* Test that wraps the randomly generated query into an array as follows: { "query_name" : [{}]}
* This causes unexpected situations in parser code that may not be handled properly.
*/
public final void testQueryWrappedInArray() {
QB queryBuilder = createTestQueryBuilder();
String queryName = queryBuilder.getName();
String validQuery = queryBuilder.toString();
queryWrappedInArrayTest(queryName, validQuery);
for (String query : getAlternateVersions().keySet()) {
queryWrappedInArrayTest(queryName, query);
}
}
private void queryWrappedInArrayTest(String queryName, String validQuery) {
int i = validQuery.indexOf("\"" + queryName + "\"");
assertThat(i, greaterThan(0));
int insertionPosition;
for (insertionPosition = i; insertionPosition < validQuery.length(); insertionPosition++) {
if (validQuery.charAt(insertionPosition) == ':') {
break;
}
}
insertionPosition++;
int endArrayPosition;
for (endArrayPosition = validQuery.length() - 1; endArrayPosition >= 0; endArrayPosition--) {
if (validQuery.charAt(endArrayPosition) == '}') {
break;
}
}
String testQuery = validQuery.substring(0, insertionPosition) + "[" +
validQuery.substring(insertionPosition, endArrayPosition) + "]" +
validQuery.substring(endArrayPosition, validQuery.length());
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(testQuery));
assertEquals("[" + queryName + "] query malformed, no start_object after query name", e.getMessage());
}
/**
* Returns alternate string representation of the query that need to be tested as they are never used as output
* of {@link QueryBuilder#toXContent(XContentBuilder, ToXContent.Params)}. By default there are no alternate versions.
*/
protected Map<String, QB> getAlternateVersions() {
return Collections.emptyMap();
}
/**
* Parses the query provided as string argument and compares it with the expected result provided as argument as a {@link QueryBuilder}
*/
protected void assertParsedQuery(String queryAsString, QueryBuilder expectedQuery) throws IOException {
QueryBuilder newQuery = parseQuery(queryAsString);
assertNotSame(newQuery, expectedQuery);
assertEquals(expectedQuery, newQuery);
assertEquals(expectedQuery.hashCode(), newQuery.hashCode());
}
/**
* Parses the query provided as bytes argument and compares it with the expected result provided as argument as a {@link QueryBuilder}
*/
private static void assertParsedQuery(XContentParser parser, QueryBuilder expectedQuery) throws IOException {
QueryBuilder newQuery = parseQuery(parser);
assertNotSame(newQuery, expectedQuery);
assertEquals(expectedQuery, newQuery);
assertEquals(expectedQuery.hashCode(), newQuery.hashCode());
}
protected QueryBuilder parseQuery(AbstractQueryBuilder<?> builder) throws IOException {
BytesReference bytes = XContentHelper.toXContent(builder, XContentType.JSON, false);
return parseQuery(createParser(JsonXContent.jsonXContent, bytes));
}
protected QueryBuilder parseQuery(String queryAsString) throws IOException {
XContentParser parser = createParser(JsonXContent.jsonXContent, queryAsString);
return parseQuery(parser);
}
protected static QueryBuilder parseQuery(XContentParser parser) throws IOException {
QueryBuilder parseInnerQueryBuilder = parseInnerQueryBuilder(parser);
assertNull(parser.nextToken());
return parseInnerQueryBuilder;
}
/**
* Whether the queries produced by this builder are expected to be cacheable.
*/
protected boolean builderGeneratesCacheableQueries() {
return true;
}
/**
* Test creates the {@link Query} from the {@link QueryBuilder} under test and delegates the
* assertions being made on the result to the implementing subclass.
*/
public void testToQuery() throws IOException {
for (int runs = 0; runs < NUMBER_OF_TESTQUERIES; runs++) {
QueryShardContext context = createShardContext();
assert context.isCachable();
context.setAllowUnmappedFields(true);
QB firstQuery = createTestQueryBuilder();
QB controlQuery = copyQuery(firstQuery);
SearchContext searchContext = getSearchContext(randomTypes, context);
/* we use a private rewrite context here since we want the most realistic way of asserting that we are cacheable or not.
* We do it this way in SearchService where
* we first rewrite the query with a private context, then reset the context and then build the actual lucene query*/
QueryBuilder rewritten = rewriteQuery(firstQuery, new QueryShardContext(context));
Query firstLuceneQuery = rewritten.toQuery(context);
if (isCachable(firstQuery)) {
assertTrue("query was marked as not cacheable in the context but this test indicates it should be cacheable: "
+ firstQuery.toString(), context.isCachable());
} else {
assertFalse("query was marked as cacheable in the context but this test indicates it should not be cacheable: "
+ firstQuery.toString(), context.isCachable());
}
assertNotNull("toQuery should not return null", firstLuceneQuery);
assertLuceneQuery(firstQuery, firstLuceneQuery, searchContext);
//remove after assertLuceneQuery since the assertLuceneQuery impl might access the context as well
assertTrue(
"query is not equal to its copy after calling toQuery, firstQuery: " + firstQuery + ", secondQuery: " + controlQuery,
firstQuery.equals(controlQuery));
assertTrue("equals is not symmetric after calling toQuery, firstQuery: " + firstQuery + ", secondQuery: " + controlQuery,
controlQuery.equals(firstQuery));
assertThat("query copy's hashcode is different from original hashcode after calling toQuery, firstQuery: " + firstQuery
+ ", secondQuery: " + controlQuery, controlQuery.hashCode(), equalTo(firstQuery.hashCode()));
QB secondQuery = copyQuery(firstQuery);
// query _name never should affect the result of toQuery, we randomly set it to make sure
if (randomBoolean()) {
secondQuery.queryName(secondQuery.queryName() == null ? randomAlphaOfLengthBetween(1, 30) : secondQuery.queryName()
+ randomAlphaOfLengthBetween(1, 10));
}
searchContext = getSearchContext(randomTypes, context);
Query secondLuceneQuery = rewriteQuery(secondQuery, context).toQuery(context);
assertNotNull("toQuery should not return null", secondLuceneQuery);
assertLuceneQuery(secondQuery, secondLuceneQuery, searchContext);
if (builderGeneratesCacheableQueries()) {
assertEquals("two equivalent query builders lead to different lucene queries",
rewrite(secondLuceneQuery), rewrite(firstLuceneQuery));
}
if (supportsBoostAndQueryName()) {
secondQuery.boost(firstQuery.boost() + 1f + randomFloat());
Query thirdLuceneQuery = rewriteQuery(secondQuery, context).toQuery(context);
assertNotEquals("modifying the boost doesn't affect the corresponding lucene query", rewrite(firstLuceneQuery),
rewrite(thirdLuceneQuery));
}
// check that context#isFilter is not changed by invoking toQuery/rewrite
boolean filterFlag = randomBoolean();
context.setIsFilter(filterFlag);
rewriteQuery(firstQuery, context).toQuery(context);
assertEquals("isFilter should be unchanged", filterFlag, context.isFilter());
}
}
private QueryBuilder rewriteQuery(QB queryBuilder, QueryRewriteContext rewriteContext) throws IOException {
QueryBuilder rewritten = rewriteAndFetch(queryBuilder, rewriteContext);
// extra safety to fail fast - serialize the rewritten version to ensure it's serializable.
assertSerialization(rewritten);
return rewritten;
}
protected boolean isCachable(QB queryBuilder) {
return true;
}
/**
* Few queries allow you to set the boost and queryName on the java api, although the corresponding parser
* doesn't parse them as they are not supported. This method allows to disable boost and queryName related tests for those queries.
* Those queries are easy to identify: their parsers don't parse `boost` and `_name` as they don't apply to the specific query:
* wrapper query and match_none
*/
protected boolean supportsBoostAndQueryName() {
return true;
}
/**
* Checks the result of {@link QueryBuilder#toQuery(QueryShardContext)} given the original {@link QueryBuilder}
* and {@link QueryShardContext}. Verifies that named queries and boost are properly handled and delegates to
* {@link #doAssertLuceneQuery(AbstractQueryBuilder, Query, SearchContext)} for query specific checks.
*/
private void assertLuceneQuery(QB queryBuilder, Query query, SearchContext context) throws IOException {
if (queryBuilder.queryName() != null) {
Query namedQuery = context.getQueryShardContext().copyNamedQueries().get(queryBuilder.queryName());
assertThat(namedQuery, equalTo(query));
}
if (query != null) {
if (queryBuilder.boost() != AbstractQueryBuilder.DEFAULT_BOOST) {
assertThat(query, either(instanceOf(BoostQuery.class)).or(instanceOf(SpanBoostQuery.class)));
if (query instanceof SpanBoostQuery) {
SpanBoostQuery spanBoostQuery = (SpanBoostQuery) query;
assertThat(spanBoostQuery.getBoost(), equalTo(queryBuilder.boost()));
query = spanBoostQuery.getQuery();
} else {
BoostQuery boostQuery = (BoostQuery) query;
assertThat(boostQuery.getBoost(), equalTo(queryBuilder.boost()));
query = boostQuery.getQuery();
}
}
}
doAssertLuceneQuery(queryBuilder, query, context);
}
/**
* Checks the result of {@link QueryBuilder#toQuery(QueryShardContext)} given the original {@link QueryBuilder}
* and {@link QueryShardContext}. Contains the query specific checks to be implemented by subclasses.
*/
protected abstract void doAssertLuceneQuery(QB queryBuilder, Query query, SearchContext context) throws IOException;
protected static void assertTermOrBoostQuery(Query query, String field, String value, float fieldBoost) {
if (fieldBoost != AbstractQueryBuilder.DEFAULT_BOOST) {
assertThat(query, instanceOf(BoostQuery.class));
BoostQuery boostQuery = (BoostQuery) query;
assertThat(boostQuery.getBoost(), equalTo(fieldBoost));
query = boostQuery.getQuery();
}
assertTermQuery(query, field, value);
}
protected static void assertTermQuery(Query query, String field, String value) {
assertThat(query, instanceOf(TermQuery.class));
TermQuery termQuery = (TermQuery) query;
assertThat(termQuery.getTerm().field(), equalTo(field));
assertThat(termQuery.getTerm().text().toLowerCase(Locale.ROOT), equalTo(value.toLowerCase(Locale.ROOT)));
}
/**
* Test serialization and deserialization of the test query.
*/
public void testSerialization() throws IOException {
for (int runs = 0; runs < NUMBER_OF_TESTQUERIES; runs++) {
QB testQuery = createTestQueryBuilder();
assertSerialization(testQuery);
}
}
protected static QueryBuilder assertSerialization(QueryBuilder testQuery) throws IOException {
return assertSerialization(testQuery, Version.CURRENT);
}
/**
* Serialize the given query builder and asserts that both are equal
*/
protected static QueryBuilder assertSerialization(QueryBuilder testQuery, Version version) throws IOException {
try (BytesStreamOutput output = new BytesStreamOutput()) {
output.setVersion(version);
output.writeNamedWriteable(testQuery);
try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), serviceHolder.namedWriteableRegistry)) {
in.setVersion(version);
QueryBuilder deserializedQuery = in.readNamedWriteable(QueryBuilder.class);
assertEquals(testQuery, deserializedQuery);
assertEquals(testQuery.hashCode(), deserializedQuery.hashCode());
assertNotSame(testQuery, deserializedQuery);
return deserializedQuery;
}
}
}
public void testEqualsAndHashcode() {
for (int runs = 0; runs < NUMBER_OF_TESTQUERIES; runs++) {
// TODO we only change name and boost, we should extend by any sub-test supplying a "mutate" method that randomly changes one
// aspect of the object under test
checkEqualsAndHashCode(createTestQueryBuilder(), this::copyQuery, this::changeNameOrBoost);
}
}
/**
* Generic test that checks that the <code>Strings.toString()</code> method
* renders the XContent correctly.
*/
public void testValidOutput() throws IOException {
for (int runs = 0; runs < NUMBER_OF_TESTQUERIES; runs++) {
QB testQuery = createTestQueryBuilder();
XContentType xContentType = XContentType.JSON;
String toString = Strings.toString(testQuery);
assertParsedQuery(createParser(xContentType.xContent(), toString), testQuery);
BytesReference bytes = XContentHelper.toXContent(testQuery, xContentType, false);
assertParsedQuery(createParser(xContentType.xContent(), bytes), testQuery);
}
}
private QB changeNameOrBoost(QB original) throws IOException {
QB secondQuery = copyQuery(original);
if (randomBoolean()) {
secondQuery.queryName(secondQuery.queryName() == null ? randomAlphaOfLengthBetween(1, 30) : secondQuery.queryName()
+ randomAlphaOfLengthBetween(1, 10));
} else {
secondQuery.boost(original.boost() + 1f + randomFloat());
}
return secondQuery;
}
//we use the streaming infra to create a copy of the query provided as argument
@SuppressWarnings("unchecked")
private QB copyQuery(QB query) throws IOException {
Reader<QB> reader = (Reader<QB>) serviceHolder.namedWriteableRegistry.getReader(QueryBuilder.class, query.getWriteableName());
return copyWriteable(query, serviceHolder.namedWriteableRegistry, reader);
}
/**
* @return a new {@link QueryShardContext} based on the base test index and queryParserService
*/
protected static QueryShardContext createShardContext() {
return serviceHolder.createShardContext();
}
/**
* create a random value for either {@link AbstractQueryTestCase#BOOLEAN_FIELD_NAME}, {@link AbstractQueryTestCase#INT_FIELD_NAME},
* {@link AbstractQueryTestCase#DOUBLE_FIELD_NAME}, {@link AbstractQueryTestCase#STRING_FIELD_NAME} or
* {@link AbstractQueryTestCase#DATE_FIELD_NAME}, or a String value by default
*/
protected static Object getRandomValueForFieldName(String fieldName) {
Object value;
switch (fieldName) {
case STRING_FIELD_NAME:
if (rarely()) {
// unicode in 10% cases
JsonStringEncoder encoder = JsonStringEncoder.getInstance();
value = new String(encoder.quoteAsString(randomUnicodeOfLength(10)));
} else {
value = randomAlphaOfLengthBetween(1, 10);
}
break;
case INT_FIELD_NAME:
value = randomIntBetween(0, 10);
break;
case DOUBLE_FIELD_NAME:
value = 1 + randomDouble() * 9;
break;
case BOOLEAN_FIELD_NAME:
value = randomBoolean();
break;
case DATE_FIELD_NAME:
value = new DateTime(System.currentTimeMillis(), DateTimeZone.UTC).toString();
break;
default:
value = randomAlphaOfLengthBetween(1, 10);
}
return value;
}
protected static String getRandomQueryText() {
int terms = randomIntBetween(0, 3);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < terms; i++) {
builder.append(randomAlphaOfLengthBetween(1, 10)).append(" ");
}
return builder.toString().trim();
}
/**
* Helper method to return a mapped or a random field
*/
protected static String getRandomFieldName() {
// if no type is set then return a random field name
if (currentTypes.length == 0 || randomBoolean()) {
return randomAlphaOfLengthBetween(1, 10);
}
return randomFrom(MAPPED_LEAF_FIELD_NAMES);
}
/**
* Helper method to return a random rewrite method
*/
protected static String getRandomRewriteMethod() {
String rewrite;
if (randomBoolean()) {
rewrite = randomFrom(QueryParsers.CONSTANT_SCORE,
QueryParsers.SCORING_BOOLEAN,
QueryParsers.CONSTANT_SCORE_BOOLEAN).getPreferredName();
} else {
rewrite = randomFrom(QueryParsers.TOP_TERMS,
QueryParsers.TOP_TERMS_BOOST,
QueryParsers.TOP_TERMS_BLENDED_FREQS).getPreferredName() + "1";
}
return rewrite;
}
private static String[] getRandomTypes() {
String[] types;
if (currentTypes.length > 0 && randomBoolean()) {
int numberOfQueryTypes = randomIntBetween(1, currentTypes.length);
types = new String[numberOfQueryTypes];
for (int i = 0; i < numberOfQueryTypes; i++) {
types[i] = randomFrom(currentTypes);
}
} else {
if (randomBoolean()) {
types = new String[]{MetaData.ALL};
} else {
types = new String[0];
}
}
return types;
}
protected static Fuzziness randomFuzziness(String fieldName) {
switch (fieldName) {
case INT_FIELD_NAME:
return Fuzziness.build(randomIntBetween(3, 100));
case DOUBLE_FIELD_NAME:
return Fuzziness.build(1 + randomFloat() * 10);
case DATE_FIELD_NAME:
return Fuzziness.build(randomTimeValue());
default:
if (randomBoolean()) {
return Fuzziness.fromEdits(randomIntBetween(0, 2));
}
return Fuzziness.AUTO;
}
}
protected static String randomAnalyzer() {
return randomFrom("simple", "standard", "keyword", "whitespace");
}
protected static String randomMinimumShouldMatch() {
return randomFrom("1", "-1", "75%", "-25%", "2<75%", "2<-25%");
}
private static class ClientInvocationHandler implements InvocationHandler {
AbstractQueryTestCase<?> delegate;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.equals(Client.class.getMethod("get", GetRequest.class, ActionListener.class))){
GetResponse getResponse = delegate.executeGet((GetRequest) args[0]);
ActionListener<GetResponse> listener = (ActionListener<GetResponse>) args[1];
if (randomBoolean()) {
listener.onResponse(getResponse);
} else {
new Thread(() -> listener.onResponse(getResponse)).start();
}
return null;
} else if (method.equals(Client.class.getMethod
("multiTermVectors", MultiTermVectorsRequest.class))) {
return new PlainActionFuture<MultiTermVectorsResponse>() {
@Override
public MultiTermVectorsResponse get() throws InterruptedException, ExecutionException {
return delegate.executeMultiTermVectors((MultiTermVectorsRequest) args[0]);
}
};
} else if (method.equals(Object.class.getMethod("toString"))) {
return "MockClient";
}
throw new UnsupportedOperationException("this test can't handle calls to: " + method);
}
}
/**
* Override this to handle {@link Client#get(GetRequest)} calls from parsers / builders
*/
protected GetResponse executeGet(GetRequest getRequest) {
throw new UnsupportedOperationException("this test can't handle GET requests");
}
/**
* Override this to handle {@link Client#get(GetRequest)} calls from parsers / builders
*/
protected MultiTermVectorsResponse executeMultiTermVectors(MultiTermVectorsRequest mtvRequest) {
throw new UnsupportedOperationException("this test can't handle MultiTermVector requests");
}
/**
* Call this method to check a valid json string representing the query under test against
* it's generated json.
*
* Note: By the time of this writing (Nov 2015) all queries are taken from the query dsl
* reference docs mirroring examples there. Here's how the queries were generated:
*
* <ul>
* <li> Take a reference documentation example.
* <li> Stick it into the createParseableQueryJson method of the respective query test.
* <li> Manually check that what the QueryBuilder generates equals the input json ignoring default options.
* <li> Put the manual checks into the assertQueryParsedFromJson method.
* <li> Now copy the generated json including default options into createParseableQueryJson
* <li> By now the roundtrip check for the json should be happy.
* </ul>
**/
public static void checkGeneratedJson(String expected, QueryBuilder source) throws IOException {
// now assert that we actually generate the same JSON
XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint();
source.toXContent(builder, ToXContent.EMPTY_PARAMS);
assertEquals(
msg(expected, builder.string()),
expected.replaceAll("\\s+", ""),
builder.string().replaceAll("\\s+", ""));
}
private static String msg(String left, String right) {
int size = Math.min(left.length(), right.length());
StringBuilder builder = new StringBuilder("size: " + left.length() + " vs. " + right.length());
builder.append(" content: <<");
for (int i = 0; i < size; i++) {
if (left.charAt(i) == right.charAt(i)) {
builder.append(left.charAt(i));
} else {
builder.append(">> ").append("until offset: ").append(i)
.append(" [").append(left.charAt(i)).append(" vs.").append(right.charAt(i))
.append("] [").append((int) left.charAt(i)).append(" vs.").append((int) right.charAt(i)).append(']');
return builder.toString();
}
}
if (left.length() != right.length()) {
int leftEnd = Math.max(size, left.length()) - 1;
int rightEnd = Math.max(size, right.length()) - 1;
builder.append(">> ").append("until offset: ").append(size)
.append(" [").append(left.charAt(leftEnd)).append(" vs.").append(right.charAt(rightEnd))
.append("] [").append((int) left.charAt(leftEnd)).append(" vs.").append((int) right.charAt(rightEnd)).append(']');
return builder.toString();
}
return "";
}
/**
* This test ensures that queries that need to be rewritten have dedicated tests.
* These queries must override this method accordingly.
*/
public void testMustRewrite() throws IOException {
QueryShardContext context = createShardContext();
context.setAllowUnmappedFields(true);
QB queryBuilder = createTestQueryBuilder();
queryBuilder.toQuery(context);
}
protected Query rewrite(Query query) throws IOException {
return query;
}
@Override
protected NamedXContentRegistry xContentRegistry() {
return serviceHolder.xContentRegistry;
}
private static class ServiceHolder implements Closeable {
private final IndexFieldDataService indexFieldDataService;
private final SearchModule searchModule;
private final NamedWriteableRegistry namedWriteableRegistry;
private final NamedXContentRegistry xContentRegistry;
private final ClientInvocationHandler clientInvocationHandler = new ClientInvocationHandler();
private final IndexSettings idxSettings;
private final SimilarityService similarityService;
private final MapperService mapperService;
private final BitsetFilterCache bitsetFilterCache;
private final ScriptService scriptService;
private final Client client;
private final long nowInMillis = randomNonNegativeLong();
ServiceHolder(Settings nodeSettings, Settings indexSettings,
Collection<Class<? extends Plugin>> plugins, AbstractQueryTestCase<?> testCase) throws IOException {
Environment env = InternalSettingsPreparer.prepareEnvironment(nodeSettings);
PluginsService pluginsService;
pluginsService = new PluginsService(nodeSettings, null, env.modulesFile(), env.pluginsFile(), plugins);
client = (Client) Proxy.newProxyInstance(
Client.class.getClassLoader(),
new Class[]{Client.class},
clientInvocationHandler);
ScriptModule scriptModule = createScriptModule(pluginsService.filterPlugins(ScriptPlugin.class));
List<Setting<?>> additionalSettings = pluginsService.getPluginSettings();
additionalSettings.add(InternalSettingsPlugin.VERSION_CREATED);
SettingsModule settingsModule = new SettingsModule(nodeSettings, additionalSettings, pluginsService.getPluginSettingsFilter());
searchModule = new SearchModule(nodeSettings, false, pluginsService.filterPlugins(SearchPlugin.class));
IndicesModule indicesModule = new IndicesModule(pluginsService.filterPlugins(MapperPlugin.class));
List<NamedWriteableRegistry.Entry> entries = new ArrayList<>();
entries.addAll(indicesModule.getNamedWriteables());
entries.addAll(searchModule.getNamedWriteables());
namedWriteableRegistry = new NamedWriteableRegistry(entries);
xContentRegistry = new NamedXContentRegistry(Stream.of(
searchModule.getNamedXContents().stream()
).flatMap(Function.identity()).collect(toList()));
IndexScopedSettings indexScopedSettings = settingsModule.getIndexScopedSettings();
idxSettings = IndexSettingsModule.newIndexSettings(index, indexSettings, indexScopedSettings);
AnalysisModule analysisModule = new AnalysisModule(TestEnvironment.newEnvironment(nodeSettings), emptyList());
IndexAnalyzers indexAnalyzers = analysisModule.getAnalysisRegistry().build(idxSettings);
scriptService = scriptModule.getScriptService();
similarityService = new SimilarityService(idxSettings, null, Collections.emptyMap());
MapperRegistry mapperRegistry = indicesModule.getMapperRegistry();
mapperService = new MapperService(idxSettings, indexAnalyzers, xContentRegistry, similarityService, mapperRegistry,
this::createShardContext);
IndicesFieldDataCache indicesFieldDataCache = new IndicesFieldDataCache(nodeSettings, new IndexFieldDataCache.Listener() {
});
indexFieldDataService = new IndexFieldDataService(idxSettings, indicesFieldDataCache,
new NoneCircuitBreakerService(), mapperService);
bitsetFilterCache = new BitsetFilterCache(idxSettings, new BitsetFilterCache.Listener() {
@Override
public void onCache(ShardId shardId, Accountable accountable) {
}
@Override
public void onRemoval(ShardId shardId, Accountable accountable) {
}
});
for (String type : currentTypes) {
mapperService.merge(type, new CompressedXContent(PutMappingRequest.buildFromSimplifiedDef(type,
STRING_FIELD_NAME, "type=text",
STRING_FIELD_NAME_2, "type=keyword",
INT_FIELD_NAME, "type=integer",
INT_RANGE_FIELD_NAME, "type=integer_range",
DOUBLE_FIELD_NAME, "type=double",
BOOLEAN_FIELD_NAME, "type=boolean",
DATE_FIELD_NAME, "type=date",
DATE_RANGE_FIELD_NAME, "type=date_range",
OBJECT_FIELD_NAME, "type=object",
GEO_POINT_FIELD_NAME, "type=geo_point",
GEO_SHAPE_FIELD_NAME, "type=geo_shape"
).string()), MapperService.MergeReason.MAPPING_UPDATE);
// also add mappings for two inner field in the object field
mapperService.merge(type, new CompressedXContent("{\"properties\":{\"" + OBJECT_FIELD_NAME + "\":{\"type\":\"object\","
+ "\"properties\":{\"" + DATE_FIELD_NAME + "\":{\"type\":\"date\"},\"" +
INT_FIELD_NAME + "\":{\"type\":\"integer\"}}}}}"),
MapperService.MergeReason.MAPPING_UPDATE);
}
testCase.initializeAdditionalMappings(mapperService);
}
@Override
public void close() throws IOException {
}
QueryShardContext createShardContext() {
return new QueryShardContext(0, idxSettings, bitsetFilterCache, indexFieldDataService::getForField, mapperService,
similarityService, scriptService, xContentRegistry, namedWriteableRegistry, this.client, null, () -> nowInMillis, null);
}
ScriptModule createScriptModule(List<ScriptPlugin> scriptPlugins) {
if (scriptPlugins == null || scriptPlugins.isEmpty()) {
return newTestScriptModule();
}
return new ScriptModule(Settings.EMPTY, scriptPlugins);
}
}
protected QueryBuilder rewriteAndFetch(QueryBuilder builder, QueryRewriteContext context) throws IOException {
PlainActionFuture<QueryBuilder> future = new PlainActionFuture<>();
Rewriteable.rewriteAndFetch(builder, context, future);
return future.actionGet();
}
}
| apache-2.0 |
webadvancedservicescom/magento | app/code/Magento/Checkout/data/checkout_setup/data-install-2.0.0.php | 22183 | <?php
/**
* @copyright Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com)
*/
/* @var $installer \Magento\Checkout\Model\Resource\Setup */
$installer = $this;
$installer->startSetup();
$setup = $installer->getConnection();
$select = $setup->select()->from(
$installer->getTable('core_config_data'),
'COUNT(*)'
)->where(
'path=?',
'customer/address/prefix_show'
)->where(
'value NOT LIKE ?',
'0'
);
$showPrefix = (bool)$installer->getCustomerAddress()->getConfig('prefix_show') || $setup->fetchOne($select) > 0;
$select = $setup->select()->from(
$installer->getTable('core_config_data'),
'COUNT(*)'
)->where(
'path=?',
'customer/address/middlename_show'
)->where(
'value NOT LIKE ?',
'0'
);
$showMiddlename = (bool)$installer->getCustomerAddress()->getConfig(
'middlename_show'
) || $setup->fetchOne(
$select
) > 0;
$select = $setup->select()->from(
$installer->getTable('core_config_data'),
'COUNT(*)'
)->where(
'path=?',
'customer/address/suffix_show'
)->where(
'value NOT LIKE ?',
'0'
);
$showSuffix = (bool)$installer->getCustomerAddress()->getConfig('suffix_show') || $setup->fetchOne($select) > 0;
$select = $setup->select()->from(
$installer->getTable('core_config_data'),
'COUNT(*)'
)->where(
'path=?',
'customer/address/dob_show'
)->where(
'value NOT LIKE ?',
'0'
);
$showDob = (bool)$installer->getCustomerAddress()->getConfig('dob_show') || $setup->fetchOne($select) > 0;
$select = $setup->select()->from(
$installer->getTable('core_config_data'),
'COUNT(*)'
)->where(
'path=?',
'customer/address/taxvat_show'
)->where(
'value NOT LIKE ?',
'0'
);
$showTaxVat = (bool)$installer->getCustomerAddress()->getConfig('taxvat_show') || $setup->fetchOne($select) > 0;
$customerEntityTypeId = $installer->getEntityTypeId('customer');
$addressEntityTypeId = $installer->getEntityTypeId('customer_address');
/**
*****************************************************************************
* checkout/onepage/register
*****************************************************************************
*/
$setup->insert(
$installer->getTable('eav_form_type'),
[
'code' => 'checkout_onepage_register',
'label' => 'checkout_onepage_register',
'is_system' => 1,
'theme' => '',
'store_id' => 0
]
);
$formTypeId = $setup->lastInsertId($installer->getTable('eav_form_type'));
$setup->insert(
$installer->getTable('eav_form_type_entity'),
['type_id' => $formTypeId, 'entity_type_id' => $customerEntityTypeId]
);
$setup->insert(
$installer->getTable('eav_form_type_entity'),
['type_id' => $formTypeId, 'entity_type_id' => $addressEntityTypeId]
);
$elementSort = 0;
if ($showPrefix) {
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'prefix'),
'sort_order' => $elementSort++
]
);
}
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'firstname'),
'sort_order' => $elementSort++
]
);
if ($showMiddlename) {
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'middlename'),
'sort_order' => $elementSort++
]
);
}
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'lastname'),
'sort_order' => $elementSort++
]
);
if ($showSuffix) {
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'suffix'),
'sort_order' => $elementSort++
]
);
}
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'company'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($customerEntityTypeId, 'email'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'street'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'city'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'region'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'postcode'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'country_id'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'telephone'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'fax'),
'sort_order' => $elementSort++
]
);
if ($showDob) {
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($customerEntityTypeId, 'dob'),
'sort_order' => $elementSort++
]
);
}
if ($showTaxVat) {
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($customerEntityTypeId, 'taxvat'),
'sort_order' => $elementSort++
]
);
}
/**
*****************************************************************************
* checkout/onepage/register_guest
*****************************************************************************
*/
$setup->insert(
$installer->getTable('eav_form_type'),
[
'code' => 'checkout_onepage_register_guest',
'label' => 'checkout_onepage_register_guest',
'is_system' => 1,
'theme' => '',
'store_id' => 0
]
);
$formTypeId = $setup->lastInsertId($installer->getTable('eav_form_type'));
$setup->insert(
$installer->getTable('eav_form_type_entity'),
['type_id' => $formTypeId, 'entity_type_id' => $customerEntityTypeId]
);
$setup->insert(
$installer->getTable('eav_form_type_entity'),
['type_id' => $formTypeId, 'entity_type_id' => $addressEntityTypeId]
);
$elementSort = 0;
if ($showPrefix) {
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'prefix'),
'sort_order' => $elementSort++
]
);
}
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'firstname'),
'sort_order' => $elementSort++
]
);
if ($showMiddlename) {
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'middlename'),
'sort_order' => $elementSort++
]
);
}
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'lastname'),
'sort_order' => $elementSort++
]
);
if ($showSuffix) {
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'suffix'),
'sort_order' => $elementSort++
]
);
}
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'company'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($customerEntityTypeId, 'email'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'street'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'city'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'region'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'postcode'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'country_id'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'telephone'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'fax'),
'sort_order' => $elementSort++
]
);
if ($showDob) {
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($customerEntityTypeId, 'dob'),
'sort_order' => $elementSort++
]
);
}
if ($showTaxVat) {
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($customerEntityTypeId, 'taxvat'),
'sort_order' => $elementSort++
]
);
}
/**
*****************************************************************************
* checkout/onepage/billing_address
*****************************************************************************
*/
$setup->insert(
$installer->getTable('eav_form_type'),
[
'code' => 'checkout_onepage_billing_address',
'label' => 'checkout_onepage_billing_address',
'is_system' => 1,
'theme' => '',
'store_id' => 0
]
);
$formTypeId = $setup->lastInsertId($installer->getTable('eav_form_type'));
$setup->insert(
$installer->getTable('eav_form_type_entity'),
['type_id' => $formTypeId, 'entity_type_id' => $addressEntityTypeId]
);
$elementSort = 0;
if ($showPrefix) {
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'prefix'),
'sort_order' => $elementSort++
]
);
}
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'firstname'),
'sort_order' => $elementSort++
]
);
if ($showMiddlename) {
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'middlename'),
'sort_order' => $elementSort++
]
);
}
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'lastname'),
'sort_order' => $elementSort++
]
);
if ($showSuffix) {
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'suffix'),
'sort_order' => $elementSort++
]
);
}
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'company'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'street'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'city'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'region'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'postcode'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'country_id'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'telephone'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'fax'),
'sort_order' => $elementSort++
]
);
/**
*****************************************************************************
* checkout/onepage/shipping_address
*****************************************************************************
*/
$setup->insert(
$installer->getTable('eav_form_type'),
[
'code' => 'checkout_onepage_shipping_address',
'label' => 'checkout_onepage_shipping_address',
'is_system' => 1,
'theme' => '',
'store_id' => 0
]
);
$formTypeId = $setup->lastInsertId($installer->getTable('eav_form_type'));
$setup->insert(
$installer->getTable('eav_form_type_entity'),
['type_id' => $formTypeId, 'entity_type_id' => $addressEntityTypeId]
);
$elementSort = 0;
if ($showPrefix) {
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'prefix'),
'sort_order' => $elementSort++
]
);
}
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'firstname'),
'sort_order' => $elementSort++
]
);
if ($showMiddlename) {
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'middlename'),
'sort_order' => $elementSort++
]
);
}
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'lastname'),
'sort_order' => $elementSort++
]
);
if ($showSuffix) {
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'suffix'),
'sort_order' => $elementSort++
]
);
}
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'company'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'street'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'city'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'region'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'postcode'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'country_id'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'telephone'),
'sort_order' => $elementSort++
]
);
$setup->insert(
$installer->getTable('eav_form_element'),
[
'type_id' => $formTypeId,
'fieldset_id' => null,
'attribute_id' => $installer->getAttributeId($addressEntityTypeId, 'fax'),
'sort_order' => $elementSort++
]
);
$table = $installer->getTable('core_config_data');
$select = $setup->select()->from(
$table,
['config_id', 'value']
)->where(
'path = ?',
'checkout/options/onepage_checkout_disabled'
);
$data = $setup->fetchAll($select);
if ($data) {
try {
$setup->beginTransaction();
foreach ($data as $value) {
$bind = ['path' => 'checkout/options/onepage_checkout_enabled', 'value' => !(bool)$value['value']];
$where = 'config_id = ' . $value['config_id'];
$setup->update($table, $bind, $where);
}
$setup->commit();
} catch (\Exception $e) {
$setup->rollback();
throw $e;
}
}
$installer->endSetup();
| apache-2.0 |
wido/cloudstack | api/src/main/java/org/apache/cloudstack/api/command/admin/vm/MigrateVirtualMachineWithVolumeCmd.java | 8018 | // 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.cloudstack.api.command.admin.vm;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseAsyncCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ResponseObject.ResponseView;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.HostResponse;
import org.apache.cloudstack.api.response.UserVmResponse;
import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ManagementServerException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.exception.VirtualMachineMigrationException;
import com.cloud.host.Host;
import com.cloud.user.Account;
import com.cloud.uservm.UserVm;
import com.cloud.vm.VirtualMachine;
@APICommand(name = "migrateVirtualMachineWithVolume",
description = "Attempts Migration of a VM with its volumes to a different host",
responseObject = UserVmResponse.class, entityType = {VirtualMachine.class},
requestHasSensitiveInfo = false,
responseHasSensitiveInfo = true)
public class MigrateVirtualMachineWithVolumeCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(MigrateVMCmd.class.getName());
private static final String s_name = "migratevirtualmachinewithvolumeresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Parameter(name = ApiConstants.HOST_ID,
type = CommandType.UUID,
entityType = HostResponse.class,
required = true,
description = "Destination Host ID to migrate VM to.")
private Long hostId;
@Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID,
type = CommandType.UUID,
entityType = UserVmResponse.class,
required = true,
description = "the ID of the virtual machine")
private Long virtualMachineId;
@Parameter(name = ApiConstants.MIGRATE_TO,
type = CommandType.MAP,
required = false,
description = "Storage to pool mapping. This parameter specifies the mapping between a volume and a pool where you want to migrate that volume. Format of this " +
"parameter: migrateto[volume-index].volume=<uuid>&migrateto[volume-index].pool=<uuid>Where, [volume-index] indicates the index to identify the volume that you " +
"want to migrate, volume=<uuid> indicates the UUID of the volume that you want to migrate, and pool=<uuid> indicates the UUID of the pool where you want to " +
"migrate the volume. Example: migrateto[0].volume=<71f43cd6-69b0-4d3b-9fbc-67f50963d60b>&migrateto[0].pool=<a382f181-3d2b-4413-b92d-b8931befa7e1>&" +
"migrateto[1].volume=<88de0173-55c0-4c1c-a269-83d0279eeedf>&migrateto[1].pool=<95d6e97c-6766-4d67-9a30-c449c15011d1>&migrateto[2].volume=" +
"<1b331390-59f2-4796-9993-bf11c6e76225>&migrateto[2].pool=<41fdb564-9d3b-447d-88ed-7628f7640cbc>")
private Map migrateVolumeTo;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Long getHostId() {
return hostId;
}
public Long getVirtualMachineId() {
return virtualMachineId;
}
public Map<String, String> getVolumeToPool() {
Map<String, String> volumeToPoolMap = new HashMap<String, String>();
if (migrateVolumeTo != null && !migrateVolumeTo.isEmpty()) {
Collection<?> allValues = migrateVolumeTo.values();
Iterator<?> iter = allValues.iterator();
while (iter.hasNext()) {
HashMap<String, String> volumeToPool = (HashMap<String, String>)iter.next();
String volume = volumeToPool.get("volume");
String pool = volumeToPool.get("pool");
volumeToPoolMap.put(volume, pool);
}
}
return volumeToPoolMap;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() {
UserVm userVm = _entityMgr.findById(UserVm.class, getVirtualMachineId());
if (userVm != null) {
return userVm.getAccountId();
}
return Account.ACCOUNT_ID_SYSTEM;
}
@Override
public String getEventType() {
return EventTypes.EVENT_VM_MIGRATE;
}
@Override
public String getEventDescription() {
return "Attempting to migrate VM Id: " + this._uuidMgr.getUuid(VirtualMachine.class, getVirtualMachineId()) + " to host Id: " + this._uuidMgr.getUuid(Host.class, getHostId());
}
@Override
public void execute() {
UserVm userVm = _userVmService.getUserVm(getVirtualMachineId());
if (userVm == null) {
throw new InvalidParameterValueException("Unable to find the VM by id=" + getVirtualMachineId());
}
Host destinationHost = _resourceService.getHost(getHostId());
if (destinationHost == null) {
throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id =" + getHostId());
}
try {
VirtualMachine migratedVm = _userVmService.migrateVirtualMachineWithVolume(getVirtualMachineId(), destinationHost, getVolumeToPool());
if (migratedVm != null) {
UserVmResponse response = _responseGenerator.createUserVmResponse(ResponseView.Full, "virtualmachine", (UserVm)migratedVm).get(0);
response.setResponseName(getCommandName());
setResponseObject(response);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to migrate vm");
}
} catch (ResourceUnavailableException ex) {
s_logger.warn("Exception: ", ex);
throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage());
} catch (ConcurrentOperationException e) {
s_logger.warn("Exception: ", e);
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
} catch (ManagementServerException e) {
s_logger.warn("Exception: ", e);
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
} catch (VirtualMachineMigrationException e) {
s_logger.warn("Exception: ", e);
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
}
}
}
| apache-2.0 |
wmedvede/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-backend/src/main/java/org/kie/workbench/common/stunner/bpmn/backend/converters/fromstunner/properties/ThrowEventPropertyWriter.java | 2929 | /*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.workbench.common.stunner.bpmn.backend.converters.fromstunner.properties;
import java.util.Objects;
import java.util.stream.Stream;
import org.eclipse.bpmn2.EventDefinition;
import org.eclipse.bpmn2.ThrowEvent;
import org.kie.workbench.common.stunner.bpmn.backend.converters.customproperties.ParsedAssignmentsInfo;
import org.kie.workbench.common.stunner.bpmn.definition.property.dataio.AssignmentsInfo;
import static org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.properties.AssignmentsInfos.isReservedIdentifier;
public class ThrowEventPropertyWriter extends EventPropertyWriter {
private final ThrowEvent throwEvent;
public ThrowEventPropertyWriter(ThrowEvent flowElement, VariableScope variableScope) {
super(flowElement, variableScope);
this.throwEvent = flowElement;
}
@Override
public void setAssignmentsInfo(AssignmentsInfo info) {
ParsedAssignmentsInfo assignmentsInfo = ParsedAssignmentsInfo.of(info);
assignmentsInfo
.getInputs().getDeclarations()
.stream()
.filter(varDecl -> !isReservedIdentifier(varDecl.getIdentifier()))
.map(varDecl -> new DeclarationWriter(flowElement.getId(), varDecl))
.peek(dw -> {
this.addItemDefinition(dw.getItemDefinition());
throwEvent.setInputSet(dw.getInputSet());
throwEvent.getDataInputs().add(dw.getDataInput());
})
.flatMap(dw -> toInputAssignmentStream(assignmentsInfo, dw))
.forEach(dia -> {
throwEvent.getDataInputAssociation().add(dia.getAssociation());
});
}
private Stream<InputAssignmentWriter> toInputAssignmentStream(ParsedAssignmentsInfo assignmentsInfo, DeclarationWriter dw) {
return assignmentsInfo.getAssociations().lookupInput(dw.getVarId())
.map(targetVar -> variableScope.lookup(targetVar.getSource()))
.filter(Objects::nonNull)
.map(targetVar -> new InputAssignmentWriter(dw, targetVar));
}
@Override
protected void addEventDefinition(EventDefinition eventDefinition) {
this.throwEvent.getEventDefinitions().add(eventDefinition);
}
}
| apache-2.0 |
leszekuchacz/SPS | app/AppKernel.php | 1656 | <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle(),
new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new AppBundle\AppBundle(),
new SpsBundle\SpsBundle(),
new Ivory\GoogleMapBundle\IvoryGoogleMapBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}
}
| apache-2.0 |
mz213310111/ite220 | first-game-cont-cont-cont_cont/js/menu.js | 928 | var menuState = {
create: function(){
game.add.image(0,0,'background');
var nameLabel = game.add.text(game.width/2, -50, 'Super Coin Box', {font: '50px Arial', fill: '#ffffff'});
nameLabel.anchor.setTo(0.5, 0.5);
game.add.tween(nameLabel).to({y: 80}, 1000).easing(Phaser.Easing.Bounce.Out).start();
var scoreLabel = game.add.text(game.width/2, game.height/2, 'score: ' + game.global.score, {font: '25px Arial', fill: '#ffffff'});
scoreLabel.anchor.setTo(0.5,0.5);
var startLabel = game.add.text(game.width/2, game.height-80, 'press the up arrow key to start', {font: '25px Arial', fill: '#ffffff'});
startLabel.anchor.setTo(0.5,0.5);
game.add.tween(startLabel).to({angle: -2}, 500).to({angle: 2}, 1000).to({angle: 0}, 500).loop().start();
var upKey = game.input.keyboard.addKey(Phaser.Keyboard.UP);
upKey.onDown.add(this.start, this);
},
start: function(){
game.state.start('play');
},
}; | apache-2.0 |
lukehutch/gribbit | src/gribbit/model/field/annotation/NoTrim.java | 1160 | /**
* This file is part of the Gribbit Web Framework.
*
* https://github.com/lukehutch/gribbit
*
* @author Luke Hutchison
*
* --
*
* @license Apache 2.0
*
* Copyright 2015 Luke Hutchison
*
* 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 gribbit.model.field.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** Prevents a field from having whitespace trimmed when it is bound from an HTTP request */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface NoTrim {
}
| apache-2.0 |
cui-liqiang/rest-rpc-play | src/main/scala/com/thoughtworks/microbuilder/play/MainController.scala | 2528 | package com.thoughtworks.microbuilder.play
import java.io.ByteArrayOutputStream
import jsonStream.JsonStream
import jsonStream.io.PrettyTextPrinter
import jsonStream.rpc.{IJsonResponseHandler, IJsonService}
import com.thoughtworks.microbuilder.core.IRouteConfiguration
import haxe.io.Output
import play.api.http.Writeable
import play.api.mvc._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Promise
case class RpcEntry(routeConfiguration: IRouteConfiguration, incomingServiceProxy: IJsonService)
class MainController(rpcImplementations: Seq[RpcEntry]) extends Controller {
def rpc(uri: String) = Action.async { request =>
val bodyJsonStream:Option[JsonStream] = request.body.asText match {
case None => None
case Some(jsonStream) => Some(JsonStream.STRING(jsonStream))
}
val promise = Promise[Result]
rpcImplementations.map(rpcImplementation => {
rpcImplementation.routeConfiguration.matchUri(request.method, uri, bodyJsonStream.getOrElse(null), request.contentType.getOrElse(null)) match {
case null => {
promise.success(NotFound)
println("null")
}
case jsonStream: JsonStream => {
val resp: IJsonResponseHandler = new IJsonResponseHandler {
override def onFailure(jsonStream: JsonStream): Unit = {
println("failed")
promise success Ok(jsonStream)(new Writeable[JsonStream]({ jsonStream =>
val javaStream = new ByteArrayOutputStream()
PrettyTextPrinter.print(new Output {
override def writeByte(b: Int) = {
javaStream.write(b)
}
}, jsonStream, 0)
javaStream.toByteArray
}, Some("application/JsonStream")))
}
override def onSuccess(jsonStream: JsonStream): Unit = {
promise success (Ok(jsonStream)(new Writeable[JsonStream]({ jsonStream =>
println("success")
val javaStream = new ByteArrayOutputStream()
PrettyTextPrinter.print(new Output {
override def writeByte(b: Int) = {
javaStream.write(b)
}
}, jsonStream, 0)
javaStream.toByteArray
}, Some("application/JsonStream"))))
}
}
rpcImplementation.incomingServiceProxy.apply(jsonStream, resp)
}
}
})
promise.future
}
}
| apache-2.0 |
melvinodsa/odsatransform | Documents/Documentation/html/odsautil_8h.js | 1958 | var odsautil_8h =
[
[ "input_data_structure", "odsautil_8h.html#structinput__data__structure", [
[ "index_jump_map", "odsautil_8h.html#a9a800523656d0d0b320e3b227085205b", null ],
[ "index_output_map", "odsautil_8h.html#af69b768bd4f930e534e5fd697c4fec8d", null ],
[ "input_text", "odsautil_8h.html#a497fdbd693ea54a1e40ddb21e8b330a8", null ],
[ "just_appended", "odsautil_8h.html#a41a7e3baa3524781b6c5d25ee031dcc1", null ],
[ "last_buffer_length", "odsautil_8h.html#a58b02a85d41375f435685469735406a4", null ],
[ "letter_jump_map", "odsautil_8h.html#a1d69d6800743dd5cf473f8d06044b635", null ],
[ "letter_output_map", "odsautil_8h.html#a3a2e01ebc37de522d74081de9ec265b7", null ]
] ],
[ "input_data", "odsautil_8h.html#ade4f0da9c721091ec1fa39dcb4976c2a", null ],
[ "output_map_index", "group___output-_map.html#ga3b41b9ad3b82219cccdb96e65a1455f0", null ],
[ "output_map_letter", "group___output-_map.html#gae9514db3e5e0b817b8eccf7f438a4628", null ],
[ "bool", "odsautil_8h.html#af6a258d8f3ee5206d682d799316314b1", [
[ "false", "odsautil_8h.html#af6a258d8f3ee5206d682d799316314b1ae9de385ef6fe9bf3360d1038396b884c", null ],
[ "true", "odsautil_8h.html#af6a258d8f3ee5206d682d799316314b1a08f175a5505a10b9ed657defeb050e4b", null ]
] ],
[ "reading_status", "odsautil_8h.html#a02d7e048e2a023ef5774bb18702eede3", [
[ "LETTER_OUTPUT", "odsautil_8h.html#a02d7e048e2a023ef5774bb18702eede3ade7ef34bbc4b0da7a1141a91f67dd568", null ],
[ "INDEX_OUTPUT", "odsautil_8h.html#a02d7e048e2a023ef5774bb18702eede3a890065937be27fa76ee9ee8e929cd365", null ],
[ "LETTER_JUMP", "odsautil_8h.html#a02d7e048e2a023ef5774bb18702eede3ac20d7dd3c54177403d042280e7f74bb6", null ],
[ "INDEX_JUMP", "odsautil_8h.html#a02d7e048e2a023ef5774bb18702eede3afb1161383e516d2acffe75cf19c95d1c", null ]
] ],
[ "MAX_JUMP_LENGTH", "odsautil_8h.html#a6fe75319add6900b39e235b47ebae7b1", null ]
]; | apache-2.0 |
open-telemetry/opentelemetry-go | sdk/resource/os_windows_test.go | 1901 | // Copyright The OpenTelemetry 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 resource_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sys/windows/registry"
"go.opentelemetry.io/otel/sdk/resource"
)
func TestPlatformOSDescription(t *testing.T) {
osDescription, err := resource.PlatformOSDescription()
require.NoError(t, err)
require.Regexp(t, `^(\w+\s)+\(\d+\)\s\[Version\s\d+(\.\d+){3}\]$`, osDescription)
}
func TestReadRegistryValues(t *testing.T) {
k, err := registry.OpenKey(
registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, registry.QUERY_VALUE)
require.NoError(t, err, "should open Windows CurrentVersion registry key")
defer k.Close()
assert.NotEmpty(t, resource.ReadProductName(k), "should read ProductName")
assert.NotEmpty(t, resource.ReadReleaseID(k), "should read ReleaseID")
assert.NotEmpty(t, resource.ReadCurrentMajorVersionNumber(k), "should read CurrentMajorVersionNumber")
assert.NotEmpty(t, resource.ReadCurrentMinorVersionNumber(k), "should read CurrentMinorVersionNumber")
assert.NotEmpty(t, resource.ReadCurrentBuildNumber(k), "should read CurrentBuildNumber")
assert.NotEmpty(t, resource.ReadUBR(k), "should read UBR")
assert.NotPanics(t, func() { resource.ReadDisplayVersion(k) }, "should not panic when reading DisplayVersion")
}
| apache-2.0 |
BitGo/BitGoJS | modules/utxo-lib/src/bitgo/wallet/WalletUnspentSigner.ts | 2035 | import * as bip32 from 'bip32';
import { DerivedWalletKeys, eqPublicKey, RootWalletKeys, WalletKeys } from './WalletKeys';
import { Triple } from '../types';
export class WalletUnspentSigner<T extends WalletKeys> {
public readonly walletKeys: T;
static from(
walletKeys: RootWalletKeys,
signer: bip32.BIP32Interface,
cosigner: bip32.BIP32Interface
): WalletUnspentSigner<RootWalletKeys> {
return new WalletUnspentSigner<RootWalletKeys>(walletKeys, signer, cosigner);
}
constructor(
walletKeys: WalletKeys | Triple<bip32.BIP32Interface>,
public signer: bip32.BIP32Interface,
public cosigner: bip32.BIP32Interface
) {
if (Array.isArray(walletKeys)) {
walletKeys = new RootWalletKeys(walletKeys);
}
if (!walletKeys.triple.some((k) => eqPublicKey(k, signer))) {
throw new Error(`signer not part of walletKeys`);
}
if (!walletKeys.triple.some((k) => eqPublicKey(k, cosigner))) {
throw new Error(`cosigner not part of walletKeys`);
}
this.walletKeys = walletKeys as T;
if (eqPublicKey(signer, cosigner)) {
throw new Error(`signer must not equal cosigner`);
}
if (signer.isNeutered()) {
throw new Error(`signer must have private key`);
}
}
/**
* @param chain
* @param index
* @return WalletUnspentSigner that contains keys for generating output scripts and signatures.
*/
deriveForChainAndIndex(chain: number, index: number): WalletUnspentSigner<DerivedWalletKeys> {
if (this.walletKeys instanceof DerivedWalletKeys) {
throw new Error(`cannot derive again from DerivedWalletKeys`);
}
if (this.walletKeys instanceof RootWalletKeys) {
return new WalletUnspentSigner(
this.walletKeys.deriveForChainAndIndex(chain, index),
this.signer.derivePath(this.walletKeys.getDerivationPath(this.signer, chain, index)),
this.cosigner.derivePath(this.walletKeys.getDerivationPath(this.cosigner, chain, index))
);
}
throw new Error(`invalid state`);
}
}
| apache-2.0 |
FG-SE/iviewx-java | src/main/java/de/unihannover/se/iviewxjava/iviewxapi/SpeedModeStruct.java | 2003 | package de.unihannover.se.iviewxjava.iviewxapi;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import java.util.Arrays;
import java.util.List;
/**
* @struct SpeedModeStruct
<br>
* <br>
* @brief This struct provides information about the speed modes used and supported by the connected iView eye tracking server.
<br>
* To update information in @ref SpeedModeStruct use function @ref iV_GetSpeedModes.<br>
* <i>native declaration : C:\Program Files\SMI\iView X SDK\include\iViewXAPI.h:380</i><br>
* This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br>
* a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br>
* For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>.
*/
public class SpeedModeStruct extends Structure {
public int version;
public int speedMode;
public int numberOfSpeedModes;
/** C type : int[16] */
public int[] speedModes = new int[16];
public SpeedModeStruct() {
super();
}
protected List<? > getFieldOrder() {
return Arrays.asList("version", "speedMode", "numberOfSpeedModes", "speedModes");
}
/** @param speedModes C type : int[16] */
public SpeedModeStruct(int version, int speedMode, int numberOfSpeedModes, int speedModes[]) {
super();
this.version = version;
this.speedMode = speedMode;
this.numberOfSpeedModes = numberOfSpeedModes;
if ((speedModes.length != this.speedModes.length))
throw new IllegalArgumentException("Wrong array size !");
this.speedModes = speedModes;
}
public SpeedModeStruct(Pointer peer) {
super(peer);
}
public static class ByReference extends SpeedModeStruct implements Structure.ByReference {
};
public static class ByValue extends SpeedModeStruct implements Structure.ByValue {
};
}
| apache-2.0 |
E-System/common-lib | src/main/java/com/es/lib/common/number/NumberFormatter.java | 3086 | package com.es.lib.common.number;
import com.es.lib.common.Constant;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
public class NumberFormatter {
private final int minDecimalCount;
private final int maxDecimalCount;
private final boolean chopZeroes;
private final String decimalSymbol;
private final Integer groupingSize;
public String format(short value) {
return format(value * 1.0d);
}
public String format(int value) {
return format(value * 1.0d);
}
public String format(long value) {
return format(value * 1.0f);
}
public String format(float value) {
return format(value * 1.0d);
}
public String format(double value) {
return chop(createFormat().format(value));
}
/**
* Divide by 100.0d before format
*
* @param value Money count in pennies
* @return Money in roubles
*/
public String money(short value) {
return money(value * 1.0d);
}
/**
* Divide by 100.0d before format
*
* @param value Money count in pennies
* @return Money in roubles
*/
public String money(int value) {
return money(value * 1.0d);
}
/**
* Divide by 100.0d before format
*
* @param value Money count in pennies
* @return Money in roubles
*/
public String money(long value) {
return money(value * 1.0d);
}
/**
* Divide by 100.0d before format
*
* @param value Money count in pennies
* @return Money in roubles
*/
public String money(float value) {
return money(value * 1.0d);
}
/**
* Divide by 100.0d before format
*
* @param value Money count in pennies
* @return Money in roubles
*/
public String money(double value) {
return format(value / 100.0d);
}
private DecimalFormat createFormat() {
DecimalFormat result = new DecimalFormat();
boolean groupingUsed = groupingSize != null && groupingSize > 0;
result.setGroupingUsed(groupingUsed);
result.setGroupingSize(groupingUsed ? groupingSize : Constant.DEFAULT_GROUPING_SIZE);
result.setMinimumFractionDigits(minDecimalCount);
result.setMaximumFractionDigits(maxDecimalCount);
if (StringUtils.isNotBlank(decimalSymbol)) {
DecimalFormatSymbols dfs = result.getDecimalFormatSymbols();
dfs.setDecimalSeparator(decimalSymbol.charAt(0));
result.setDecimalFormatSymbols(dfs);
}
return result;
}
private String chop(String value) {
if (value == null || value.isEmpty() || minDecimalCount != maxDecimalCount) {
return value;
}
if (chopZeroes) {
return value.replace(decimalSymbol + StringUtils.repeat('0', maxDecimalCount), "");
}
return value;
}
}
| apache-2.0 |
Adriano72/BIHWR2015 | Resources/iphone/alloy/widgets/com.mp5systems.rippleeffect/styles/widget.js | 1606 | function WPATH(s) {
var index = s.lastIndexOf("/");
var path = -1 === index ? "com.mp5systems.rippleeffect/" + s : s.substring(0, index) + "/com.mp5systems.rippleeffect/" + s.substring(index + 1);
return path;
}
module.exports = [ {
isApi: true,
priority: 1101.0005999999998,
key: "Label",
style: {
font: {
fontFamily: "ExpoSansPro-Regular"
}
}
}, {
isClass: true,
priority: 10000.0002,
key: "leftNavImg",
style: {
image: "/images/doves_title.png",
height: 30
}
}, {
isClass: true,
priority: 10000.0009,
key: "titolo",
style: {
height: "100%",
width: Ti.UI.SIZE,
font: {
fontFamily: "ExpoSansPro-Regular",
fontSize: "16dp"
},
color: "#FFF"
}
}, {
isClass: true,
priority: 10101.0001,
key: "topBar",
style: {
barColor: "#B00909",
top: Alloy.Globals.winTopHeight,
statusBarStyle: Titanium.UI.iPhone.StatusBar.LIGHT_CONTENT,
orientationModes: [ Ti.UI.PORTRAIT ]
}
}, {
isClass: true,
priority: 10101.0003,
key: "expoSansPro",
style: {
font: {
fontFamily: "ExpoSansPro-Regular"
}
}
}, {
isClass: true,
priority: 10101.0004,
key: "expoSansProBold",
style: {
font: {
fontFamily: "ExpoSansPro-Bold"
}
}
}, {
isId: true,
priority: 100000.0011,
key: "ripple",
style: {
backgroundColor: "rgba(255,255,255,0.40)",
zIndex: 999,
opacity: 0
}
} ]; | apache-2.0 |
hairlun/customer-visit-web | src/com/jude/dao/TaskDaoImpl.java | 6653 | package com.jude.dao;
import com.jude.dao.VisitRecordDaoImpl.VisitRecordRowMapper;
import com.jude.entity.Customer;
import com.jude.entity.CustomerManager;
import com.jude.entity.RecordDetail;
import com.jude.entity.Task;
import com.jude.entity.VisitRecord;
import com.jude.util.IdUtil;
import com.jude.util.PagingHelper;
import com.jude.util.PagingSet;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
@Repository("taskDao")
public class TaskDaoImpl implements TaskDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private VisitRecordDao recordDao;
private static SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
private static SimpleDateFormat ssf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
public void addTasks(List<Task> tasks, List<RecordDetail> cs) {
for (Task task : tasks) {
addTask(task);
VisitRecord record = new VisitRecord();
record.setId(IdUtil.getId());
record.setTaskId(task.getId());
record.setCustomer(task.getCustomer());
record.setCustomerManager(task.getManager());
record.setContent(task.getContent());
record.setType(0);
this.recordDao.addVisitRecord(record, cs);
}
}
public void delete(long taskId) {
this.jdbcTemplate.update("delete from task where id = ?", new Object[] { Long.valueOf(taskId) });
}
public List<Task> getManagerTask(String username) {
String sql = "select t.complete, t.reply, t.content, t.start_time, t.end_time, t.create_time, t.id, c.id, c.name, c.sell_number, c.phone_number, c.backup_number, m.id from task t left join customer c on t.customer = c.id left join customer_manager m on t.manager = m.id where m.username = ?";
return this.jdbcTemplate.query(sql, new Object[] { username }, new TaskRowMapper());
}
public Task getTask(long taskId) {
List list = this.jdbcTemplate
.query("select t.complete, t.reply, t.content, t.start_time, t.end_time, t.create_time, t.id, c.id, c.name, c.sell_number, c.phone_number, c.backup_number, m.id from task t left join customer c on t.customer = c.id left join customer_manager m on t.manager = m.id where t.id = "
+ taskId, new TaskRowMapper());
if ((list == null) || (list.size() == 0)) {
return null;
}
return (Task) list.get(0);
}
public void addTask(Task task) {
StringBuffer sb = new StringBuffer(
"insert into task(id, start_time, end_time, manager, customer, content, create_time) values");
sb.append("(").append(task.getId()).append(",").append(sf.format(task.getStart()))
.append(",").append(sf.format(task.getEnd())).append(",")
.append(task.getManager().getId()).append(",").append(task.getCustomer().getId())
.append(",'").append(task.getContent()).append("','")
.append(ssf.format(new Date())).append("')");
this.jdbcTemplate.update(sb.toString());
}
public List<Task> getManagerTask(long managerId) {
String sql = "select t.complete, t.reply, t.content, t.start_time, t.end_time, t.create_time, t.id, c.id, c.name, c.sell_number, c.phone_number, c.backup_number, m.id from task t left join customer c on t.customer = c.id left join customer_manager m on t.manager = m.id where m.id = ?";
return this.jdbcTemplate.query(sql, new Object[] { Long.valueOf(managerId) },
new TaskRowMapper());
}
public PagingSet<Task> getManagerTask(long managerId, int start, int limit, int type, String keyword,
String startTime, String endTime) {
StringBuffer sb = new StringBuffer();
sb.append("select t.complete, t.reply, t.content, t.start_time, t.end_time, t.create_time, t.id, c.id, c.name, c.sell_number, c.phone_number, c.backup_number, m.id from task t left join customer c on t.customer = c.id left join customer_manager m on t.manager = m.id where m.id = ").append(managerId);
sb.append(" and (t.complete = ").append(type).append(" or t.reject = 1)");
if (!StringUtils.isBlank(keyword)) {
sb.append(" and (c.name like '%").append(keyword).append("%'");
sb.append(" or c.sell_number like '%").append(keyword).append("%'");
sb.append(" or c.phone_number like '%").append(keyword).append("%'");
sb.append(" or c.backup_number like '%").append(keyword).append("%')");
}
PagingHelper h = new PagingHelper(this.jdbcTemplate);
h.setInParameters(sb.toString(), start, limit);
PagingSet<Task> pageSet = h.handle(new TaskRowMapper());
return pageSet;
}
public List<Task> getTasksByVisitRecordIds(String vids) {
String sql = "select t.complete, t.reply, t.content, t.start_time, t.end_time, t.create_time, t.id, c.id, c.name, c.sell_number, c.phone_number, c.backup_number, m.id, v.id from task t left join customer c on t.customer = c.id left join customer_manager m on t.manager = m.id left join visit_record v on t.id = v.task_id where v.id in ("
+ vids + ")";
return this.jdbcTemplate.query(sql, new TaskRowMapper());
}
public void reject(String taskIds, String reason) {
this.jdbcTemplate.update(
"update task set complete = 0, reject = 1, reply = ? where id in (" + taskIds + ")",
new Object[] { reason });
}
public void complete(long taskId) {
this.jdbcTemplate.update(
"update task set complete = 1, reject = 0 where id = ?",
new Object[] { Long.valueOf(taskId) });
}
public static class TaskRowMapper implements RowMapper<Task> {
public Task mapRow(ResultSet rs, int rowNum) throws SQLException {
Task task = new Task();
task.setId(rs.getLong("t.id"));
task.setContent(rs.getString("t.content"));
task.setStart(rs.getDate("t.start_time"));
task.setEnd(rs.getDate("t.end_time"));
task.setCreate(rs.getTimestamp("t.create_time"));
task.setComplete(rs.getInt("t.complete"));
task.setReply(rs.getString("t.reply"));
Customer customer = new Customer();
customer.setId(Long.valueOf(rs.getLong("c.id")));
customer.setName(rs.getString("c.name"));
customer.setSellNumber(rs.getString("c.sell_number"));
customer.setPhoneNumber(rs.getString("c.phone_number"));
customer.setBackupNumber(rs.getString("c.backup_number"));
task.setCustomer(customer);
CustomerManager manager = new CustomerManager();
manager.setId(Long.valueOf(rs.getLong("m.id")));
task.setManager(manager);
return task;
}
}
} | apache-2.0 |
GoogleCloudPlatform/ubbagent | pipeline/builder/builder_test.go | 2503 | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 builder
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/GoogleCloudPlatform/ubbagent/config"
"github.com/GoogleCloudPlatform/ubbagent/metrics"
"github.com/GoogleCloudPlatform/ubbagent/persistence"
"github.com/GoogleCloudPlatform/ubbagent/stats"
"github.com/GoogleCloudPlatform/ubbagent/util"
)
// TestBuild tests that a Pipeline can be created and shutdown successfully.
func TestBuild(t *testing.T) {
tmpdir, err := ioutil.TempDir("", "build_test")
if err != nil {
t.Fatalf("Unable to create temp directory: %+v", err)
}
defer os.RemoveAll(tmpdir)
p, err := persistence.NewDiskPersistence(filepath.Join(tmpdir, "state"))
if err != nil {
t.Fatalf("Unable to create disk persistence: %+v", err)
}
cfg := &config.Config{
Metrics: config.Metrics{
{
Definition: metrics.Definition{
Name: "int-metric",
Type: "int",
},
Aggregation: &config.Aggregation{
BufferSeconds: 10,
},
Endpoints: []config.MetricEndpoint{
{Name: "on_disk"},
},
},
{
Definition: metrics.Definition{
Name: "double-metric",
Type: "double",
},
Aggregation: &config.Aggregation{
BufferSeconds: 10,
},
Endpoints: []config.MetricEndpoint{
{Name: "on_disk"},
},
},
},
Endpoints: []config.Endpoint{
{
Name: "on_disk",
Disk: &config.DiskEndpoint{
ReportDir: filepath.Join(tmpdir, "reports"),
ExpireSeconds: 3600,
},
},
},
Sources: []config.Source{
{
Name: "instance-seconds",
Heartbeat: &config.Heartbeat{
Metric: "int-metric",
IntervalSeconds: 10,
Value: metrics.MetricValue{
Int64Value: util.NewInt64(10),
},
Labels: map[string]string{"foo": "bar"},
},
},
},
}
a, err := Build(cfg, p, stats.NewNoopRecorder())
if err != nil {
t.Fatalf("unexpected error creating App: %+v", err)
}
a.Release()
}
| apache-2.0 |
couchbaselabs/ep-engine | blackhole-kvstore/blackhole.hh | 2341 | /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#ifndef BLACKHOLE_KVSTORE_H
#define BLACKHOLE_KVSTORE_H 1
#include "kvstore.hh"
#include "item.hh"
#include "stats.hh"
#include "configuration.hh"
class EventuallyPersistentEngine;
class EPStats;
class MCKVStoreTestEnvironment;
class MemcachedEngine;
/**
* A black hole kv-store
*/
class BlackholeKVStore : public KVStore {
public:
/**
* Build it!
*/
BlackholeKVStore(EventuallyPersistentEngine &theEngine);
/**
* Cleanup.
*/
virtual ~BlackholeKVStore();
/**
* Reset database to a clean state.
*/
void reset(void);
/**
* Begin a transaction (if not already in one).
*/
bool begin(void);
/**
* Commit a transaction (unless not currently in one).
*
* Returns false if the commit fails.
*/
bool commit(void);
/**
* Rollback a transaction (unless not currently in one).
*/
void rollback(void);
/**
* Query the properties of the underlying storage.
*/
StorageProperties getStorageProperties(void);
/**
* Overrides set().
*/
void set(const Item &item, uint16_t vb_version, Callback<mutation_result> &cb);
/**
* Overrides get().
*/
void get(const std::string &key, uint64_t rowid,
uint16_t vb, uint16_t vbver, Callback<GetValue> &cb);
/**
* Overrides del().
*/
void del(const Item &itm, uint64_t rowid,
uint16_t vbver, Callback<int> &cb);
bool delVBucket(uint16_t vbucket, uint16_t vb_version);
bool delVBucket(uint16_t vbucket, uint16_t vb_version,
std::pair<int64_t, int64_t> row_range);
vbucket_map_t listPersistedVbuckets(void);
/**
* Take a snapshot of the stats in the main DB.
*/
bool snapshotStats(const std::map<std::string, std::string> &m);
/**
* Take a snapshot of the vbucket states in the main DB.
*/
bool snapshotVBuckets(const vbucket_map_t &m);
/**
* Overrides dump
*/
void dump(shared_ptr<Callback<GetValue> > cb);
void dump(uint16_t vb, shared_ptr<Callback<GetValue> > cb);
void destroyInvalidVBuckets(bool destroyOnlyOne = false) {
(void) destroyOnlyOne;
}
private:
};
#endif /* Blackhole_KVSTORE_H */
| apache-2.0 |
rish1988/spring-tutorials | spring-tutorial-25/src/com/caveofprogramming/spring/Logger.java | 829 | package com.caveofprogramming.spring;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Logger {
@Autowired(required=false)
private ConsoleWriter consoleWriter;
@Autowired
private FileWriter fileWriter;
public ConsoleWriter getConsoleWriter() {
return consoleWriter;
}
public LogWriter getFileWriter() {
return fileWriter;
}
public void writeFile(String text) {
fileWriter.write(text);
}
public void writeConsole(String text) {
if (consoleWriter != null)
consoleWriter.write(text);
}
@PostConstruct
public void init() {
System.out.println("Init");
}
@PreDestroy
public void destroy() {
System.out.println("destroy");
}
}
| apache-2.0 |
rossella/neutron | tools/check_i18n.py | 5358 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack 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 compiler
import imp
import os.path
import sys
def is_localized(node):
""" Check message wrapped by _() """
if isinstance(node.parent, compiler.ast.CallFunc):
if isinstance(node.parent.node, compiler.ast.Name):
if node.parent.node.name == '_':
return True
return False
class ASTWalker(compiler.visitor.ASTVisitor):
def default(self, node, *args):
for child in node.getChildNodes():
child.parent = node
compiler.visitor.ASTVisitor.default(self, node, *args)
class Visitor(object):
def __init__(self, filename, i18n_msg_predicates,
msg_format_checkers, debug):
self.filename = filename
self.debug = debug
self.error = 0
self.i18n_msg_predicates = i18n_msg_predicates
self.msg_format_checkers = msg_format_checkers
with open(filename) as f:
self.lines = f.readlines()
def visitConst(self, node):
if not isinstance(node.value, str):
return
if is_localized(node):
for (checker, msg) in self.msg_format_checkers:
if checker(node):
print >> sys.stderr, (
'%s:%d %s: %s' %
(self.filename, node.lineno,
self.lines[node.lineno - 1][:-1],
"Error: %s" % msg))
self.error = 1
return
if debug:
print ('%s:%d %s: %s' %
(self.filename, node.lineno,
self.lines[node.lineno - 1][:-1],
"Pass"))
else:
for (predicate, action, msg) in self.i18n_msg_predicates:
if predicate(node):
if action == 'skip':
if debug:
print ('%s:%d %s: %s' %
(self.filename, node.lineno,
self.lines[node.lineno - 1][:-1],
"Pass"))
return
elif action == 'error':
print >> sys.stderr, (
'%s:%d %s: %s' %
(self.filename, node.lineno,
self.lines[node.lineno - 1][:-1],
"Error: %s" % msg))
self.error = 1
return
elif action == 'warn':
print ('%s:%d %s: %s' %
(self.filename, node.lineno,
self.lines[node.lineno - 1][:-1],
"Warn: %s" % msg))
return
print >> sys.stderr, 'Predicate with wrong action!'
def is_file_in_black_list(black_list, f):
for f in black_list:
if os.path.abspath(input_file).startswith(
os.path.abspath(f)):
return True
return False
def check_i18n(input_file, i18n_msg_predicates, msg_format_checkers, debug):
input_mod = compiler.parseFile(input_file)
v = compiler.visitor.walk(input_mod,
Visitor(input_file,
i18n_msg_predicates,
msg_format_checkers,
debug),
ASTWalker())
return v.error
if __name__ == '__main__':
input_path = sys.argv[1]
cfg_path = sys.argv[2]
try:
cfg_mod = imp.load_source('', cfg_path)
except:
print >> sys.stderr, "Load cfg module failed"
sys.exit(1)
i18n_msg_predicates = cfg_mod.i18n_msg_predicates
msg_format_checkers = cfg_mod.msg_format_checkers
black_list = cfg_mod.file_black_list
debug = False
if len(sys.argv) > 3:
if sys.argv[3] == '-d':
debug = True
if os.path.isfile(input_path):
sys.exit(check_i18n(input_path,
i18n_msg_predicates,
msg_format_checkers,
debug))
error = 0
for dirpath, dirs, files in os.walk(input_path):
for f in files:
if not f.endswith('.py'):
continue
input_file = os.path.join(dirpath, f)
if is_file_in_black_list(black_list, input_file):
continue
if check_i18n(input_file,
i18n_msg_predicates,
msg_format_checkers,
debug):
error = 1
sys.exit(error)
| apache-2.0 |
lvdongbing/python-bileanclient | bileanclient/openstack/common/cliutils.py | 8038 | # Copyright 2012 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
# W0603: Using the global statement
# W0621: Redefining name %s from outer scope
# pylint: disable=W0603,W0621
from __future__ import print_function
import getpass
import inspect
import os
import sys
import textwrap
from oslo_utils import encodeutils
from oslo_utils import strutils
import prettytable
import six
from six import moves
from bileanclient.openstack.common._i18n import _
class MissingArgs(Exception):
"""Supplied arguments are not sufficient for calling a function."""
def __init__(self, missing):
self.missing = missing
msg = _("Missing arguments: %s") % ", ".join(missing)
super(MissingArgs, self).__init__(msg)
def validate_args(fn, *args, **kwargs):
"""Check that the supplied args are sufficient for calling a function.
>>> validate_args(lambda a: None)
Traceback (most recent call last):
...
MissingArgs: Missing argument(s): a
>>> validate_args(lambda a, b, c, d: None, 0, c=1)
Traceback (most recent call last):
...
MissingArgs: Missing argument(s): b, d
:param fn: the function to check
:param arg: the positional arguments supplied
:param kwargs: the keyword arguments supplied
"""
argspec = inspect.getargspec(fn)
num_defaults = len(argspec.defaults or [])
required_args = argspec.args[:len(argspec.args) - num_defaults]
def isbound(method):
return getattr(method, '__self__', None) is not None
if isbound(fn):
required_args.pop(0)
missing = [arg for arg in required_args if arg not in kwargs]
missing = missing[len(args):]
if missing:
raise MissingArgs(missing)
def arg(*args, **kwargs):
"""Decorator for CLI args.
Example:
>>> @arg("name", help="Name of the new entity")
... def entity_create(args):
... pass
"""
def _decorator(func):
add_arg(func, *args, **kwargs)
return func
return _decorator
def env(*args, **kwargs):
"""Returns the first environment variable set.
If all are empty, defaults to '' or keyword arg `default`.
"""
for arg in args:
value = os.environ.get(arg)
if value:
return value
return kwargs.get('default', '')
def add_arg(func, *args, **kwargs):
"""Bind CLI arguments to a shell.py `do_foo` function."""
if not hasattr(func, 'arguments'):
func.arguments = []
# NOTE(sirp): avoid dups that can occur when the module is shared across
# tests.
if (args, kwargs) not in func.arguments:
# Because of the semantics of decorator composition if we just append
# to the options list positional options will appear to be backwards.
func.arguments.insert(0, (args, kwargs))
def unauthenticated(func):
"""Adds 'unauthenticated' attribute to decorated function.
Usage:
>>> @unauthenticated
... def mymethod(f):
... pass
"""
func.unauthenticated = True
return func
def isunauthenticated(func):
"""Checks if the function does not require authentication.
Mark such functions with the `@unauthenticated` decorator.
:returns: bool
"""
return getattr(func, 'unauthenticated', False)
def print_list(objs, fields, formatters=None, sortby_index=0,
mixed_case_fields=None, field_labels=None):
"""Print a list of objects as a table, one row per object.
:param objs: iterable of :class:`Resource`
:param fields: attributes that correspond to columns, in order
:param formatters: `dict` of callables for field formatting
:param sortby_index: index of the field for sorting table rows
:param mixed_case_fields: fields corresponding to object attributes that
have mixed case names (e.g., 'serverId')
:param field_labels: Labels to use in the heading of the table, default to
fields.
"""
formatters = formatters or {}
mixed_case_fields = mixed_case_fields or []
field_labels = field_labels or fields
if len(field_labels) != len(fields):
raise ValueError(_("Field labels list %(labels)s has different number "
"of elements than fields list %(fields)s"),
{'labels': field_labels, 'fields': fields})
if sortby_index is None:
kwargs = {}
else:
kwargs = {'sortby': field_labels[sortby_index]}
pt = prettytable.PrettyTable(field_labels)
pt.align = 'l'
for o in objs:
row = []
for field in fields:
if field in formatters:
row.append(formatters[field](o))
else:
if field in mixed_case_fields:
field_name = field.replace(' ', '_')
else:
field_name = field.lower().replace(' ', '_')
data = getattr(o, field_name, '')
row.append(data)
pt.add_row(row)
if six.PY3:
print(encodeutils.safe_encode(pt.get_string(**kwargs)).decode())
else:
print(encodeutils.safe_encode(pt.get_string(**kwargs)))
def print_dict(dct, dict_property="Property", wrap=0, dict_value='Value'):
"""Print a `dict` as a table of two columns.
:param dct: `dict` to print
:param dict_property: name of the first column
:param wrap: wrapping for the second column
:param dict_value: header label for the value (second) column
"""
pt = prettytable.PrettyTable([dict_property, dict_value])
pt.align = 'l'
for k, v in sorted(dct.items()):
# convert dict to str to check length
if isinstance(v, dict):
v = six.text_type(v)
if wrap > 0:
v = textwrap.fill(six.text_type(v), wrap)
# if value has a newline, add in multiple rows
# e.g. fault with stacktrace
if v and isinstance(v, six.string_types) and r'\n' in v:
lines = v.strip().split(r'\n')
col1 = k
for line in lines:
pt.add_row([col1, line])
col1 = ''
else:
pt.add_row([k, v])
if six.PY3:
print(encodeutils.safe_encode(pt.get_string()).decode())
else:
print(encodeutils.safe_encode(pt.get_string()))
def get_password(max_password_prompts=3):
"""Read password from TTY."""
verify = strutils.bool_from_string(env("OS_VERIFY_PASSWORD"))
pw = None
if hasattr(sys.stdin, "isatty") and sys.stdin.isatty():
# Check for Ctrl-D
try:
for __ in moves.range(max_password_prompts):
pw1 = getpass.getpass("OS Password: ")
if verify:
pw2 = getpass.getpass("Please verify: ")
else:
pw2 = pw1
if pw1 == pw2 and pw1:
pw = pw1
break
except EOFError:
pass
return pw
def service_type(stype):
"""Adds 'service_type' attribute to decorated function.
Usage:
.. code-block:: python
@service_type('volume')
def mymethod(f):
...
"""
def inner(f):
f.service_type = stype
return f
return inner
def get_service_type(f):
"""Retrieves service type from function."""
return getattr(f, 'service_type', None)
def pretty_choice_list(l):
return ', '.join("'%s'" % i for i in l)
def exit(msg=''):
if msg:
print (msg, file=sys.stderr)
sys.exit(1)
| apache-2.0 |
Subsets and Splits