repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
toulouseSoWine/toulouseSoWine.github.io
bower_components/angular-material/modules/js/list/list.js
8180
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v0.10.1-rc5-master-f5a9101 */ (function( window, angular, undefined ){ "use strict"; /** * @ngdoc module * @name material.components.list * @description * List module */ angular.module('material.components.list', [ 'material.core' ]) .controller('MdListController', MdListController) .directive('mdList', mdListDirective) .directive('mdListItem', mdListItemDirective); /** * @ngdoc directive * @name mdList * @module material.components.list * * @restrict E * * @description * The `<md-list>` directive is a list container for 1..n `<md-list-item>` tags. * * @usage * <hljs lang="html"> * <md-list> * <md-list-item class="md-2-line" ng-repeat="item in todos"> * <md-checkbox ng-model="item.done"></md-checkbox> * <div class="md-list-item-text"> * <h3>{{item.title}}</h3> * <p>{{item.description}}</p> * </div> * </md-list-item> * </md-list> * </hljs> */ function mdListDirective($mdTheming) { return { restrict: 'E', compile: function(tEl) { tEl[0].setAttribute('role', 'list'); return $mdTheming; } }; } mdListDirective.$inject = ["$mdTheming"]; /** * @ngdoc directive * @name mdListItem * @module material.components.list * * @restrict E * * @description * The `<md-list-item>` directive is a container intended for row items in a `<md-list>` container. * * @usage * <hljs lang="html"> * <md-list> * <md-list-item> * Item content in list * </md-list-item> * </md-list> * </hljs> * */ function mdListItemDirective($mdAria, $mdConstant, $timeout) { var proxiedTypes = ['md-checkbox', 'md-switch']; return { restrict: 'E', controller: 'MdListController', compile: function(tEl, tAttrs) { // Check for proxy controls (no ng-click on parent, and a control inside) var secondaryItem = tEl[0].querySelector('.md-secondary'); var hasProxiedElement; var proxyElement; tEl[0].setAttribute('role', 'listitem'); if (!tAttrs.ngClick) { for (var i = 0, type; type = proxiedTypes[i]; ++i) { if (proxyElement = tEl[0].querySelector(type)) { hasProxiedElement = true; break; } } if (hasProxiedElement) { wrapIn('div'); } else if (!tEl[0].querySelector('md-button')) { tEl.addClass('md-no-proxy'); } } else { wrapIn('button'); } setupToggleAria(); function setupToggleAria() { var toggleTypes = ['md-switch', 'md-checkbox']; var toggle; for (var i = 0, toggleType; toggleType = toggleTypes[i]; ++i) { if (toggle = tEl.find(toggleType)[0]) { if (!toggle.hasAttribute('aria-label')) { var p = tEl.find('p')[0]; if (!p) return; toggle.setAttribute('aria-label', 'Toggle ' + p.textContent); } } } } function wrapIn(type) { var container; if (type == 'div') { container = angular.element('<div class="md-no-style md-list-item-inner">'); container.append(tEl.contents()); tEl.addClass('md-proxy-focus'); } else { container = angular.element('<md-button class="md-no-style"><div class="md-list-item-inner"></div></md-button>'); var copiedAttrs = ['ng-click', 'aria-label', 'ng-disabled']; angular.forEach(copiedAttrs, function(attr) { if (tEl[0].hasAttribute(attr)) { container[0].setAttribute(attr, tEl[0].getAttribute(attr)); tEl[0].removeAttribute(attr); } }); container.children().eq(0).append(tEl.contents()); } tEl[0].setAttribute('tabindex', '-1'); tEl.append(container); if (secondaryItem && secondaryItem.hasAttribute('ng-click')) { $mdAria.expect(secondaryItem, 'aria-label'); var buttonWrapper = angular.element('<md-button class="md-secondary-container md-icon-button">'); buttonWrapper.attr('ng-click', secondaryItem.getAttribute('ng-click')); secondaryItem.removeAttribute('ng-click'); secondaryItem.setAttribute('tabindex', '-1'); secondaryItem.classList.remove('md-secondary'); buttonWrapper.append(secondaryItem); secondaryItem = buttonWrapper[0]; } // Check for a secondary item and move it outside if ( secondaryItem && ( secondaryItem.hasAttribute('ng-click') || ( tAttrs.ngClick && isProxiedElement(secondaryItem) ) )) { tEl.addClass('md-with-secondary'); tEl.append(secondaryItem); } } function isProxiedElement(el) { return proxiedTypes.indexOf(el.nodeName.toLowerCase()) != -1; } return postLink; function postLink($scope, $element, $attr, ctrl) { var proxies = [], firstChild = $element[0].firstElementChild, hasClick = firstChild && firstChild.hasAttribute('ng-click'); computeProxies(); computeClickable(); if ($element.hasClass('md-proxy-focus') && proxies.length) { angular.forEach(proxies, function(proxy) { proxy = angular.element(proxy); $scope.mouseActive = false; proxy.on('mousedown', function() { $scope.mouseActive = true; $timeout(function(){ $scope.mouseActive = false; }, 100); }) .on('focus', function() { if ($scope.mouseActive === false) { $element.addClass('md-focused'); } proxy.on('blur', function proxyOnBlur() { $element.removeClass('md-focused'); proxy.off('blur', proxyOnBlur); }); }); }); } function computeProxies() { var children = $element.children(); if (children.length && !children[0].hasAttribute('ng-click')) { angular.forEach(proxiedTypes, function(type) { angular.forEach(firstChild.querySelectorAll(type), function(child) { proxies.push(child); }); }); } } function computeClickable() { if (proxies.length || hasClick) { $element.addClass('md-clickable'); ctrl.attachRipple($scope, angular.element($element[0].querySelector('.md-no-style'))); } } if (!hasClick && !proxies.length) { firstChild && firstChild.addEventListener('keypress', function(e) { if (e.target.nodeName != 'INPUT' && e.target.nodeName != 'TEXTAREA') { var keyCode = e.which || e.keyCode; if (keyCode == $mdConstant.KEY_CODE.SPACE) { if (firstChild) { firstChild.click(); e.preventDefault(); e.stopPropagation(); } } } }); } $element.off('click'); $element.off('keypress'); if (proxies.length && firstChild) { $element.children().eq(0).on('click', function(e) { if (firstChild.contains(e.target)) { angular.forEach(proxies, function(proxy) { if (e.target !== proxy && !proxy.contains(e.target)) { angular.element(proxy).triggerHandler('click'); } }); } }); } } } }; } mdListItemDirective.$inject = ["$mdAria", "$mdConstant", "$timeout"]; /* * @private * @ngdoc controller * @name MdListController * @module material.components.list * */ function MdListController($scope, $element, $mdListInkRipple) { var ctrl = this; ctrl.attachRipple = attachRipple; function attachRipple (scope, element) { var options = {}; $mdListInkRipple.attach(scope, element, options); } } MdListController.$inject = ["$scope", "$element", "$mdListInkRipple"]; })(window, window.angular);
apache-2.0
lemonJun/TakinRPC
takinrpc-raft/src/main/java/org/robotninjas/protobuf/netty/InvalidRpcRequestException.java
1619
/* * Copyright (c) 2009 Stephen Tu <stephen_tu@berkeley.edu> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.robotninjas.protobuf.netty; import org.robotninjas.protobuf.netty.NettyRpcProto.RpcRequest; @SuppressWarnings("serial") public class InvalidRpcRequestException extends RpcException { public InvalidRpcRequestException(Throwable t, NettyRpcProto.RpcRequest request, String message) { super(t, request, message); } public InvalidRpcRequestException(NettyRpcProto.RpcRequest request, String message) { super(request, message); } }
apache-2.0
zion64/spring-ldap
samples/user-admin/src/main/java/com/zeiv/emp/repo/EmployeesAllAttrViewHome.java
6051
package com.zeiv.emp.repo; // Generated 2014. 5. 4 오전 12:22:02 by Hibernate Tools 4.0.0 import java.util.List; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Example; import org.hibernate.criterion.Restrictions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ldap.samples.useradmin.util.GenericUtil; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.zeiv.emp.domain.EmployeesAllAttrView; /** * Home object for domain model class EmployeesAllAttrView. * @see com.zeiv.emp.util.EmployeesAllAttrView * @author Hibernate Tools */ @Repository(value="employeesAllAttrViewHome") @Transactional(propagation = Propagation.SUPPORTS) public class EmployeesAllAttrViewHome { private static final Logger log = LoggerFactory.getLogger(EmployeesAllAttrViewHome.class); @Autowired private SessionFactory sessionFactory; public void persist(EmployeesAllAttrView transientInstance) { log.debug("persisting EmployeesAllAttrView instance"); try { sessionFactory.getCurrentSession().persist(transientInstance); log.debug("persist successful"); } catch (RuntimeException re) { log.error("persist failed", re); throw re; } } public void attachDirty(EmployeesAllAttrView instance) { log.debug("attaching dirty EmployeesAllAttrView instance"); try { sessionFactory.getCurrentSession().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } @SuppressWarnings("deprecation") public void attachClean(EmployeesAllAttrView instance) { log.debug("attaching clean EmployeesAllAttrView instance"); try { sessionFactory.getCurrentSession().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void delete(EmployeesAllAttrView persistentInstance) { log.debug("deleting EmployeesAllAttrView instance"); try { sessionFactory.getCurrentSession().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public EmployeesAllAttrView merge(EmployeesAllAttrView detachedInstance) { log.debug("merging EmployeesAllAttrView instance"); try { EmployeesAllAttrView result = (EmployeesAllAttrView) sessionFactory.getCurrentSession() .merge(detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public EmployeesAllAttrView findById(int id) { log.debug("getting EmployeesAllAttrView instance with id: " + id); try { EmployeesAllAttrView instance = (EmployeesAllAttrView) sessionFactory.getCurrentSession() .get("com.zeiv.emp.domain.EmployeesAllAttrView", id); if (instance == null) { log.debug("get successful, no instance found"); } else { log.debug("get successful, instance found"); } return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List<EmployeesAllAttrView> findByExample(EmployeesAllAttrView instance) { log.debug("finding EmployeesAllAttrView instance by example"); try { List<EmployeesAllAttrView> results = GenericUtil.castList(EmployeesAllAttrView.class, sessionFactory.getCurrentSession() .createCriteria("com.zeiv.emp.util.EmployeesAllAttrView") .add(Example.create(instance)) .list()); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } @Transactional public List<EmployeesAllAttrView> findAll(int start, int limit) { log.debug("finding Employees instance by example"); try { List<EmployeesAllAttrView> results = GenericUtil.castList(EmployeesAllAttrView.class, sessionFactory.getCurrentSession().createCriteria("com.zeiv.emp.domain.EmployeesAllAttrView") .setFirstResult(start) .setMaxResults(limit) .list()); log.info("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } @Transactional public List<EmployeesAllAttrView> findAll() { log.info("finding EmployeesAllAttrView instance by findAll"); try { List<EmployeesAllAttrView> results = GenericUtil.castList(EmployeesAllAttrView.class, sessionFactory.getCurrentSession().createCriteria("com.zeiv.emp.domain.EmployeesAllAttrView").list()); log.info("findAll successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("EmployeesAllAttrView failed", re); throw re; } } @Transactional public List<EmployeesAllAttrView> findAll(String deptNo) { log.info("finding EmployeesAllAttrView instance by findAll"); try { List<EmployeesAllAttrView> results = GenericUtil.castList(EmployeesAllAttrView.class, sessionFactory.getCurrentSession().createCriteria("com.zeiv.emp.domain.EmployeesAllAttrView").add(Restrictions.eq("deptNo",deptNo)).list()); log.info("findAll successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("EmployeesAllAttrView failed", re); throw re; } } public Number getTotalCountOfEmployeesAllAttrView() { Session session = sessionFactory.getCurrentSession(); try { return ((Number) session.createSQLQuery("select count(*) from employees_all_attr_view").uniqueResult()).longValue(); } catch (HibernateException e) { e.printStackTrace(); throw e; } finally { } } }
apache-2.0
dorzey/assertj-core
src/test/java/org/assertj/core/api/bytearray/ByteArrayAssert_containsExactlyInAnyOrder_Test.java
1597
/** * 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 2012-2016 the original author or authors. */ package org.assertj.core.api.bytearray; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.test.ByteArrays.arrayOf; import static org.mockito.Mockito.verify; import org.assertj.core.api.ByteArrayAssert; import org.assertj.core.api.ByteArrayAssertBaseTest; import org.junit.Test; /** * Tests for <code>{@link org.assertj.core.api.ByteArrayAssert#containsExactlyInAnyOrder(byte...)}</code>. */ public class ByteArrayAssert_containsExactlyInAnyOrder_Test extends ByteArrayAssertBaseTest { @Override protected ByteArrayAssert invoke_api_method() { return assertions.containsExactlyInAnyOrder((byte) 1, (byte) 2); } @Override protected void verify_internal_effects() { verify(arrays).assertContainsExactlyInAnyOrder(getInfo(assertions), getActual(assertions), arrayOf(1, 2)); } @Test public void invoke_api_like_user() { assertThat(new byte[] { 1, 2, 2 }).containsExactlyInAnyOrder((byte) 2, (byte) 2, (byte) 1); } }
apache-2.0
stdlib-js/stdlib
lib/node_modules/@stdlib/repl/lib/is_scope.js
1098
/** * @license Apache-2.0 * * Copyright (c) 2019 The Stdlib 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. */ 'use strict'; // MAIN // /** * Tests whether an AST node defines a scope. * * @private * @param {Node} node - AST node * @returns {boolean} boolean indicating whether an AST node defines a scope */ function isScope( node ) { return ( // Function scopes: node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration' || node.type === 'ArrowFunctionExpression' || // Global scope: node.type === 'Program' ); } // EXPORTS // module.exports = isScope;
apache-2.0
mpi2/PhenotypeArchive
src/main/java/org/mousephenotype/www/testing/model/SearchImpcImageTable.java
2014
/******************************************************************************* * Copyright 2015 EMBL - European Bioinformatics Institute * * 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.mousephenotype.www.testing.model; import java.util.HashMap; import java.util.Map; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; /** * * @author mrelac * * This class encapsulates the code and data necessary to represent the important * components of a search page 'imagesGrid' HTML table common to all Image facet * views. */ public class SearchImpcImageTable extends SearchImageTable { private final static Map<TableComponent, By> map = new HashMap(); static { map.put(TableComponent.BY_TABLE, By.xpath("//table[@id='impc_imagesGrid']")); map.put(TableComponent.BY_TABLE_TR, By.xpath("//table[@id='impc_imagesGrid']/tbody/tr")); map.put(TableComponent.BY_SELECT_GRID_LENGTH, By.xpath("//select[@name='impc_imagesGrid_length']")); } /** * Creates a new <code>SearchImageTable</code> instance. * @param driver A <code>WebDriver</code> instance pointing to the search * facet table with thead and tbody definitions. * @param timeoutInSeconds The <code>WebDriver</code> timeout, in seconds */ public SearchImpcImageTable(WebDriver driver, int timeoutInSeconds) { super(driver, timeoutInSeconds, map); } }
apache-2.0
ulaval/modul-components
src/components/plus/plus.sandbox.ts
1314
import Vue, { PluginObject } from 'vue'; import { Component } from 'vue-property-decorator'; import ButtonPlugin from '../button/button'; import { PLUS_NAME } from '../component-names'; import PlusPlugin from './plus'; import WithRender from './plus.sandbox.html'; @WithRender @Component export class MPlusSandbox extends Vue { private example1Open: boolean = false; private exemple1Disabled: boolean = false; private exemple1Large: boolean = false; private exemple1Border: boolean = false; private exemple1SkinLight: boolean = false; private exemple1ToggleOpen(): void { this.example1Open = !this.example1Open; } private exemple1ToggleDisabled(): void { this.exemple1Disabled = !this.exemple1Disabled; } private exemple1ToggleLarge(): void { this.exemple1Large = !this.exemple1Large; } private exemple1ToggleBorder(): void { this.exemple1Border = !this.exemple1Border; } private exemple1ToggleSkinLight(): void { this.exemple1SkinLight = !this.exemple1SkinLight; } } const PlusSandboxPlugin: PluginObject<any> = { install(v, options): void { v.use(PlusPlugin); v.use(ButtonPlugin); v.component(`${PLUS_NAME}-sandbox`, MPlusSandbox); } }; export default PlusSandboxPlugin;
apache-2.0
chenUT/spookystuff
core/src/test/scala/org/tribbloid/spookystuff/expression/TestExprView.scala
1516
package org.tribbloid.spookystuff.expression import org.tribbloid.spookystuff.SpookyEnvSuite import org.tribbloid.spookystuff.actions.Wget import org.tribbloid.spookystuff.entity.PageRow import org.tribbloid.spookystuff.expressions.NamedFunction1 /** * Created by peng on 12/3/14. */ class TestExprView extends SpookyEnvSuite { import org.tribbloid.spookystuff.dsl._ lazy val page = ( Wget("http://www.wikipedia.org/") :: Nil ).resolve(spooky) lazy val row = PageRow(pageLikes = page) .select($"title".head.text.~('abc)) .head test("symbol as Expr"){ assert('abc.apply(row) === Some("Wikipedia")) } test("andThen"){ val fun = 'abc.andThen(_.map(_.toString)) assert(fun.name === "abc.<function1>") assert(fun(row) === Some("Wikipedia")) val fun2 = 'abc.andThen(NamedFunction1(_.map(_.toString),"after")) assert(fun2.name === "abc.after") assert(fun(row) === Some("Wikipedia")) } test("andMap"){ val fun = 'abc.andMap(_.toString) assert(fun.name === "abc.<function1>") assert(fun(row) === Some("Wikipedia")) val fun2 = 'abc.andMap(_.toString, "after") assert(fun2.name === "abc.after") assert(fun(row) === Some("Wikipedia")) } test("andFlatMap"){ val fun = 'abc.andFlatMap(_.toString.headOption) assert(fun.name === "abc.<function1>") assert(fun(row) === Some('W')) val fun2 = 'abc.andFlatMap(_.toString.headOption, "after") assert(fun2.name === "abc.after") assert(fun(row) === Some('W')) } }
apache-2.0
StevenWard94/java-dev
csci-2903/Module10/WardCheckBoxes/src/WardCheckBoxes.java
6082
/** * Steven Ward * WardCheckBoxes.java | Check Boxes Project * * This file defines the WardCheckBoxes GUI class, which is described below. * * Due Date: November 6, 2016 * */ import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.WindowConstants; /** * Defines the GUI to be used as this program's primary input/ouput interface. * * Creates a window derived from JFrame that contains two child components, both of which are * JCheckBox objects. One checkbox is labeled "BLUE" and the other is labeled "ORANGE". A unique * color combination for the background and foreground of a WardCheckBoxes object is defined for * each combination of "BLUE" and "ORANGE" selections/deselections: * DESELCT BLUE, DESELECT ORANGE : Black Foreground on Gray Background * SELECT BLUE, DESELECT ORANGE : Yellow Foreground on Blue Background * DESELECT BLUE, SELECT ORANGE : White Foreground on Orange Background * SELECT BLUE, SELECT ORANGE : Orange Foreground on Blue Background * * This class also defines a 'main' method to serve as the entry point of the WardCheckBoxes * application. * * @see javax.swing.JFrame * @see java.awt.GridBagLayout * @see javax.swing.JCheckBox * @see java.awt.event.ItemListener * @see java.awt.Color */ public class WardCheckBoxes extends JFrame { private static final long serialVersionUID = 0L; private static final int MIN_WIN_WIDTH = 800; private static final int MIN_WIN_HEIGHT = 600; private static final String DEFAULT_TITLE = "Black on Gray"; private static final String BLUE_TITLE = "Yellow on Blue"; private static final String ORANGE_TITLE = "White on Orange"; private static final String BLUE_ORANGE_TITLE = "Orange on Blue"; private JPanel checkboxPanel; private JCheckBox blueCheckBox, orangeCheckBox; private ItemListener checkboxListener; private GridBagConstraints layoutConstraints; private class ColorChangeListener implements ItemListener { @Override public void itemStateChanged(ItemEvent event) { final int blue = WardCheckBoxes.this.blueCheckBox.isSelected() ? 1 : 0; final int orange = WardCheckBoxes.this.orangeCheckBox.isSelected() ? 2 : 0; final int state = blue + orange; Color bg_Co; Color fg_Co; String title; switch (blue + orange) { case 1: bg_Co = Color.BLUE; fg_Co = Color.YELLOW; title = WardCheckBoxes.BLUE_TITLE; break; case 2: bg_Co = Color.ORANGE; fg_Co = Color.WHITE; title = WardCheckBoxes.ORANGE_TITLE; break; case 3: bg_Co = Color.BLUE; fg_Co = Color.ORANGE; title = WardCheckBoxes.BLUE_ORANGE_TITLE; break; default: bg_Co = Color.GRAY; fg_Co = Color.BLACK; title = WardCheckBoxes.DEFAULT_TITLE; break; } WardCheckBoxes.this.updateCheckBoxes(bg_Co, fg_Co); WardCheckBoxes.this.checkboxPanel.setBackground(bg_Co); WardCheckBoxes.this.checkboxPanel.setForeground(fg_Co); WardCheckBoxes.this.setTitle(title); WardCheckBoxes.this.checkboxPanel.revalidate(); WardCheckBoxes.this.checkboxPanel.repaint(); WardCheckBoxes.this.revalidate(); WardCheckBoxes.this.repaint(); } } private void updateCheckBoxes(Color backgroundColor, Color foregroundColor) { blueCheckBox.setBackground(backgroundColor); blueCheckBox.setForeground(foregroundColor); blueCheckBox.revalidate(); blueCheckBox.repaint(); orangeCheckBox.setBackground(backgroundColor); orangeCheckBox.setForeground(foregroundColor); orangeCheckBox.revalidate(); orangeCheckBox.repaint(); } public static void main(String[] args) { WardCheckBoxes mainWindow = new WardCheckBoxes(); mainWindow.setVisible(true); } public WardCheckBoxes( ) { super(DEFAULT_TITLE); this.setMinimumSize(new Dimension(MIN_WIN_WIDTH, MIN_WIN_HEIGHT)); this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent event) { int confirmExit = JOptionPane.showConfirmDialog(null, "Leaving so soon?", "Close Application?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (confirmExit == JOptionPane.YES_OPTION) { System.exit(0); } } }); this.checkboxPanel = new JPanel(); this.checkboxListener = new ColorChangeListener(); this.blueCheckBox = new JCheckBox("BLUE"); this.orangeCheckBox = new JCheckBox("ORANGE"); this.setLayout(new GridBagLayout()); checkboxPanel.setLayout(new GridBagLayout()); checkboxPanel.setPreferredSize(this.getSize()); layoutConstraints = new GridBagConstraints(); blueCheckBox.setFont(blueCheckBox.getFont().deriveFont(Font.BOLD, 48.0f)); blueCheckBox.addItemListener(checkboxListener); orangeCheckBox.setFont(orangeCheckBox.getFont().deriveFont(Font.BOLD, 48.0f)); orangeCheckBox.addItemListener(checkboxListener); layoutConstraints.anchor = GridBagConstraints.CENTER; layoutConstraints.fill = GridBagConstraints.BOTH; layoutConstraints.ipadx = 2; layoutConstraints.gridx = 0; layoutConstraints.gridy = 0; checkboxPanel.add(blueCheckBox, layoutConstraints); layoutConstraints.gridx = 1; checkboxPanel.add(orangeCheckBox, layoutConstraints); layoutConstraints.ipadx = 0; layoutConstraints.gridx = 0; this.add(checkboxPanel, layoutConstraints); } }
apache-2.0
ArvinDevel/incubator-pulsar
pulsar-client-cpp/tests/BinaryLookupServiceTest.cc
5275
/** * 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 <BinaryProtoLookupService.h> #include <pulsar/Client.h> #include <gtest/gtest.h> #include <boost/shared_ptr.hpp> #include <boost/make_shared.hpp> #include <Future.h> #include <Utils.h> #include "ConnectionPool.h" #include "HttpHelper.h" #include <pulsar/Authentication.h> #include <boost/exception/all.hpp> DECLARE_LOG_OBJECT() using namespace pulsar; TEST(BinaryLookupServiceTest, basicLookup) { ExecutorServiceProviderPtr service = boost::make_shared<ExecutorServiceProvider>(1); AuthenticationPtr authData = AuthFactory::Disabled(); std::string url = "pulsar://localhost:6650"; ClientConfiguration conf; ExecutorServiceProviderPtr ioExecutorProvider_(boost::make_shared<ExecutorServiceProvider>(1)); ConnectionPool pool_(conf, ioExecutorProvider_, authData, true); BinaryProtoLookupService lookupService(pool_, url); TopicNamePtr topicName = TopicName::get("topic"); Future<Result, LookupDataResultPtr> partitionFuture = lookupService.getPartitionMetadataAsync(topicName); LookupDataResultPtr lookupData; Result result = partitionFuture.get(lookupData); ASSERT_TRUE(lookupData != NULL); ASSERT_EQ(0, lookupData->getPartitions()); Future<Result, LookupDataResultPtr> future = lookupService.lookupAsync("topic"); result = future.get(lookupData); ASSERT_EQ(ResultOk, result); ASSERT_TRUE(lookupData != NULL); ASSERT_EQ(url, lookupData->getBrokerUrl()); } TEST(BinaryLookupServiceTest, basicGetNamespaceTopics) { std::string url = "pulsar://localhost:6650"; std::string adminUrl = "http://localhost:8080/"; Result result; // 1. create some topics under same namespace Client client(url); std::string topicName1 = "persistent://public/default/basicGetNamespaceTopics1"; std::string topicName2 = "persistent://public/default/basicGetNamespaceTopics2"; std::string topicName3 = "persistent://public/default/basicGetNamespaceTopics3"; // This is not in same namespace. std::string topicName4 = "persistent://public/default-2/basicGetNamespaceTopics4"; // call admin api to make topics partitioned std::string url1 = adminUrl + "admin/v2/persistent/public/default/basicGetNamespaceTopics1/partitions"; std::string url2 = adminUrl + "admin/v2/persistent/public/default/basicGetNamespaceTopics2/partitions"; std::string url3 = adminUrl + "admin/v2/persistent/public/default/basicGetNamespaceTopics3/partitions"; int res = makePutRequest(url1, "2"); ASSERT_FALSE(res != 204 && res != 409); res = makePutRequest(url2, "3"); ASSERT_FALSE(res != 204 && res != 409); res = makePutRequest(url3, "4"); ASSERT_FALSE(res != 204 && res != 409); Producer producer1; result = client.createProducer(topicName1, producer1); ASSERT_EQ(ResultOk, result); Producer producer2; result = client.createProducer(topicName2, producer2); ASSERT_EQ(ResultOk, result); Producer producer3; result = client.createProducer(topicName3, producer3); ASSERT_EQ(ResultOk, result); Producer producer4; result = client.createProducer(topicName4, producer4); ASSERT_EQ(ResultOk, result); // 2. call getTopicsOfNamespaceAsync ExecutorServiceProviderPtr service = boost::make_shared<ExecutorServiceProvider>(1); AuthenticationPtr authData = AuthFactory::Disabled(); ClientConfiguration conf; ExecutorServiceProviderPtr ioExecutorProvider_(boost::make_shared<ExecutorServiceProvider>(1)); ConnectionPool pool_(conf, ioExecutorProvider_, authData, true); BinaryProtoLookupService lookupService(pool_, url); TopicNamePtr topicName = TopicName::get(topicName1); NamespaceNamePtr nsName = topicName->getNamespaceName(); Future<Result, NamespaceTopicsPtr> getTopicsFuture = lookupService.getTopicsOfNamespaceAsync(nsName); NamespaceTopicsPtr topicsData; result = getTopicsFuture.get(topicsData); ASSERT_EQ(ResultOk, result); ASSERT_TRUE(topicsData != NULL); // 3. verify result contains first 3 topic ASSERT_TRUE(std::find(topicsData->begin(), topicsData->end(), topicName1) != topicsData->end()); ASSERT_TRUE(std::find(topicsData->begin(), topicsData->end(), topicName2) != topicsData->end()); ASSERT_TRUE(std::find(topicsData->begin(), topicsData->end(), topicName3) != topicsData->end()); ASSERT_FALSE(std::find(topicsData->begin(), topicsData->end(), topicName4) != topicsData->end()); client.shutdown(); }
apache-2.0
luartmg/WMA
WMA/src/factorypack/Parser.java
54
package factorypack; public class Parser { }
apache-2.0
hdinsight/hdinsight-storm-examples
EventCountExample/EventCountHybridTopology/SqlDb.cs
2806
using Microsoft.SCP; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EventCountHybridTopology { public class SqlDb { private SqlConnection con = null; private SqlCommand comm = null; public SqlDb(String connectionStr) { try { // Establish the connection. Context.Logger.Info("connectionStr: " + connectionStr); con = new SqlConnection(connectionStr); con.Open(); } catch (Exception e) { Context.Logger.Error("Exception: {0}", e); } } public void createTable() { Context.Logger.Info("createTable"); String SQL = "CREATE TABLE EventCountHybridTopology(timestamp bigint PRIMARY KEY, eventCount bigint)"; // Create and execute an SQL statement that returns some data. try { comm = con.CreateCommand(); comm.CommandText = SQL; comm.ExecuteNonQuery(); } catch (Exception e) { Context.Logger.Error("Exception: {0}", e); } } public void dropTable() { Context.Logger.Info("dropTable"); String SQL = "IF OBJECT_ID (N'dbo.EventCountHybridTopology', N'U') IS NOT NULL DROP TABLE dbo.EventCountHybridTopology"; try { comm = con.CreateCommand(); comm.CommandText = SQL; comm.ExecuteNonQuery(); } catch (Exception e) { Context.Logger.Error("Exception: {0}", e); } } public void insertValue(long timestamp, long count) { String SQL = "INSERT INTO EventCountHybridTopology " + "VALUES (" + timestamp + "," + count + ");"; try { comm = con.CreateCommand(); comm.CommandText = SQL; comm.ExecuteNonQuery(); } catch (Exception e) { Context.Logger.Error("Exception: {0}", e); } } public void resetTable() { Context.Logger.Info("resetTable"); String SQL = "Truncate Table EventCountHybridTopology"; try { comm = con.CreateCommand(); comm.CommandText = SQL; comm.ExecuteNonQuery(); } catch (Exception e) { Context.Logger.Error("Exception: {0}", e); } } } }
apache-2.0
bigamasta/chess-challenge
src/actions/TileActions.js
160
/** * Created by BigaMasta on 3/5/16. */ import alt from '../alt'; export default alt.generateActions( 'create', 'highlightTilesAt', 'unhighlightTiles' );
apache-2.0
neo4j/neo4j-dotnet-driver
Neo4j.Driver/Neo4j.Driver/Internal/Messaging/RecordMessage.cs
1307
// Copyright (c) "Neo4j" // Neo4j Sweden AB [http://neo4j.com] // // This file is part of Neo4j. // // 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. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Neo4j.Driver.Internal.MessageHandling; namespace Neo4j.Driver.Internal.Messaging { internal class RecordMessage : IResponseMessage { public RecordMessage(object[] fields) { Fields = fields; } public object[] Fields { get; } public override string ToString() { return $"RECORD {Fields.ToContentString()}"; } public void Dispatch(IResponsePipeline pipeline) { pipeline.OnRecord(Fields); } } }
apache-2.0
ViDA-NYU/ache
ache/src/test/java/achecrawler/link/frontier/selector/MultiLevelLinkSelectorTest.java
1277
package achecrawler.link.frontier.selector; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import java.util.List; import org.junit.Test; import achecrawler.link.frontier.LinkRelevance; public class MultiLevelLinkSelectorTest { @Test public void shouldSelectLinks() throws Exception { // given MultiLevelLinkSelector selector = new MultiLevelLinkSelector(); List<LinkRelevance> frontier = asList( new LinkRelevance("http://localhost/299", 299), new LinkRelevance("http://localhost/199", 199), new LinkRelevance("http://localhost/099", 99), new LinkRelevance("http://localhost/001", 1) ); int numberOfLinks = 3; // when selector.startSelection(numberOfLinks); for(LinkRelevance link : frontier) { selector.evaluateLink(link); } List<LinkRelevance> links = selector.getSelectedLinks(); // then assertThat(links, is(notNullValue())); assertThat(links.size(), is(numberOfLinks)); assertThat(links.get(0).getRelevance(), is(299d)); } }
apache-2.0
sriramsa/gosiege
state/clusterevents.go
253
// A list of cluster events package state // Holds a generic command. Used for sending across channels type ClusterEvent struct { Cmd interface{} } type AddNode struct { Concurrent, Delay, Host string } type RemoveNode struct { SessionId string }
apache-2.0
andreh7/rfwsutils
wsGraphVizPath.py
6897
#!/usr/bin/env python # rfwsutils - utilities for manipulating RooFit workspaces from the command line # # Copyright 2013-2015 University of California, San Diego # # 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, os, wsutils #---------------------------------------------------------------------- def findObjectsOnPaths(ws, srcObj, destObj): """ looks for all objects which can be 'reached' from srcObj and from which one can 'reach' destObj, i.e. all objects which are (indirect) clients of srcObj and (indirect) servers of destObj @param srcObj is assumed to be 'lower' than destObj in the tree, i.e. a (possibly indirect) server of destObj. """ # names of nodes from which one can definitively NOT reach destObj badNodeNames = set() # names of nodes from which we can definitively reach destObj # (and which we have reached starting from srcObj, so we # can return goodNodes) goodNodeNames = set() goodNodes = [] # probably not the most efficient implementation # but should at least be easy to understand def isGoodNode(node): nodeName = node.GetName() # query the cache if nodeName in goodNodeNames: return True if nodeName in badNodeNames: return False # check if we have reached the destination if nodeName == destObj.GetName(): # we've reached the destination # add to the cache if not nodeName in goodNodeNames: goodNodes.append(node) goodNodeNames.add(nodeName) return True # we don't know if the node is good (can reach destObj) # or bad (can't read destObj for sure) # # so we look at the node's clients #---------- # get all clients #---------- clients = wsutils.getClients(node) #---------- # if this node has no clients at this point, # we will not be able to reach destObj if not clients: badNodeNames.add(nodeName) return False isGood = False for client in clients: # do a depth first search: go higher up before # visiting the other clients if isGoodNode(client): # client can reach the destination so we can as well if not nodeName in goodNodeNames: goodNodes.append(node) goodNodeNames.add(nodeName) isGood = True # note that we also want to find paths to the same destination # via other clients so we don't immediately return here if not isGood: # none of the clients could reach destObj so neither can we badNodeNames.add(nodeName) return isGood # walk on the graph isGoodNode(srcObj) return goodNodes #---------------------------------------------------------------------- # main #---------------------------------------------------------------------- from optparse import OptionParser parser = OptionParser(""" usage: %prog [options] input_file member1 member2 searches for all possible paths between member1 and member2 in the graph, assuming there are no loops. Both directions are tried (i.e. the graph is considered as undirected) """ ) wsutils.addCommonOptions(parser) parser.add_option("--exclude", dest="exclude", default = [], action = "append", help="fnmatch pattern of nodes to exclude from the graph. Option can be specified multiple times", ) (options, ARGV) = parser.parse_args() #---------------------------------------- # check the command line options #---------------------------------------- wsutils.checkCommonOptions(options) if len(ARGV) != 3: print >> sys.stderr,"expected exactly three positional arguments" sys.exit(1) #---------------------------------------- import ROOT wsutils.loadLibraries(options) fname = ARGV.pop(0) fin = ROOT.TFile.Open(fname) if fin == None or not fin.IsOpen(): print >> sys.stderr,"problems opening file " + fname sys.exit(1) # insist that there is a single workspace in this file workspace = wsutils.findSingleWorkspace(fin, options) srcObj = wsutils.getObj(workspace, ARGV.pop(0)) destObj = wsutils.getObj(workspace, ARGV.pop(0)) # assume that there are no cycles in the object graph, # so if one direction finds a path, the other will not nodes = findObjectsOnPaths(workspace, srcObj, destObj) if not nodes: # try the reverse direction nodes = findObjectsOnPaths(workspace, destObj, srcObj) if not(nodes): print >> sys.stderr,"no path found beween %s and %s" % (srcObj.GetName(), destObj.GetName()) sys.exit(1) # print [ node.GetName() for node in nodes ] #---------- # apply list of exclusion patterns #---------- import fnmatch for excludePattern in options.exclude: newNodes = [] for node in nodes: if not fnmatch.fnmatch(node.GetName(), excludePattern): newNodes.append(node) nodes = newNodes #---------- # get names of (remaining) good nodes so that we can later on check # which edges to draw #---------- nodeNames = set([ node.GetName() for node in nodes ]) #---------- # produce graphviz code #---------- fout = sys.stdout print >> fout, "digraph G {" # make sure the root node is at the top # despite the fact that it has only incoming # vertices print >> fout, " rankdir = BT;" for node in nodes: # print attributes of node first print >> fout,'%s [label="%s\\n%s"]' % (node.GetName(), node.ClassName(), node.GetName()) print >> fout # draw edges for node in nodes: clients = wsutils.getClients(node) for client in clients: # note that not all clients are 'good' nodes # (i.e. they may not have a path to the upper level # object if not client.GetName() in nodeNames: continue # make arrows point 'upwards' in the sense # 'A -> B' means 'A influences B' print >> fout,"%s->%s" % (node.GetName(), client.GetName()) print >> fout,"}" # digraph
apache-2.0
IAMTJW/Tomcat-8.5.20
tomcat-8.5.20/test/org/apache/tomcat/util/threads/TestLimitLatch.java
7830
/* * 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.tomcat.util.threads; import org.junit.Assert; import org.junit.Test; public class TestLimitLatch { // This should be plenty of time, even on slow systems. private static final long THREAD_WAIT_TIME = 60000; @Test public void testNoThreads() throws Exception { LimitLatch latch = new LimitLatch(0); Assert.assertFalse("No threads should be waiting", latch.hasQueuedThreads()); } @Test public void testOneThreadNoWait() throws Exception { LimitLatch latch = new LimitLatch(1); Object lock = new Object(); checkWaitingThreadCount(latch, 0); TestThread testThread = new TestThread(latch, lock); testThread.start(); if (!waitForThreadToStart(testThread)) { Assert.fail("Test thread did not start"); } checkWaitingThreadCount(latch, 0); if (!waitForThreadToStop(testThread, lock)) { Assert.fail("Test thread did not stop"); } checkWaitingThreadCount(latch, 0); } @Test public void testOneThreadWaitCountDown() throws Exception { LimitLatch latch = new LimitLatch(1); Object lock = new Object(); checkWaitingThreadCount(latch, 0); TestThread testThread = new TestThread(latch, lock); latch.countUpOrAwait(); testThread.start(); if (!waitForThreadToStart(testThread)) { Assert.fail("Test thread did not start"); } checkWaitingThreadCount(latch, 1); latch.countDown(); if (!waitForThreadToStop(testThread, lock)) { Assert.fail("Test thread did not stop"); } checkWaitingThreadCount(latch, 0); } @Test public void testOneRelease() throws Exception { LimitLatch latch = new LimitLatch(1); Object lock = new Object(); checkWaitingThreadCount(latch, 0); TestThread testThread = new TestThread(latch, lock); latch.countUpOrAwait(); testThread.start(); if (!waitForThreadToStart(testThread)) { Assert.fail("Test thread did not start"); } checkWaitingThreadCount(latch, 1); latch.releaseAll(); if (!waitForThreadToStop(testThread, lock)) { Assert.fail("Test thread did not stop"); } checkWaitingThreadCount(latch, 0); } @Test public void testTenWait() throws Exception { LimitLatch latch = new LimitLatch(10); Object lock = new Object(); checkWaitingThreadCount(latch, 0); TestThread[] testThreads = new TestThread[30]; for (int i = 0; i < 30; i++) { testThreads[i] = new TestThread(latch, lock); testThreads[i].start(); } // Should have 10 threads in stage 2 and 20 in stage 1 for (int i = 0; i < 30; i++) { if (!waitForThreadToStart(testThreads[i])) { Assert.fail("Test thread [" + i + "] did not start"); } } if (!waitForThreadsToReachStage(testThreads, 20, 10, 0)) { Assert.fail("Failed at 20-10-00"); } checkWaitingThreadCount(latch, 20); synchronized (lock) { lock.notifyAll(); } if (!waitForThreadsToReachStage(testThreads, 10, 10, 10)) { Assert.fail("Failed at 10-10-10"); } checkWaitingThreadCount(latch, 10); synchronized (lock) { lock.notifyAll(); } if (!waitForThreadsToReachStage(testThreads, 0, 10, 20)) { Assert.fail("Failed at 00-10-20"); } checkWaitingThreadCount(latch, 0); synchronized (lock) { lock.notifyAll(); } if (!waitForThreadsToReachStage(testThreads, 0, 0, 30)) { Assert.fail("Failed at 00-00-30"); } } private boolean waitForThreadToStart(TestThread t) throws InterruptedException { long wait = 0; while (t.getStage() == 0 && wait < THREAD_WAIT_TIME) { Thread.sleep(100); wait += 100; } return t.getStage() > 0; } private boolean waitForThreadToStop(TestThread t, Object lock) throws InterruptedException { long wait = 0; while (t.getStage() < 3 && wait < THREAD_WAIT_TIME) { Thread.sleep(100); wait += 100; synchronized (lock) { lock.notifyAll(); } } return t.getStage() == 3; } private void checkWaitingThreadCount(LimitLatch latch, int target) throws InterruptedException { long wait = 0; while (latch.getQueuedThreads().size() != target && wait < THREAD_WAIT_TIME) { Thread.sleep(100); wait += 100; } Assert.assertEquals(target, latch.getQueuedThreads().size()); } private boolean waitForThreadsToReachStage(TestThread[] testThreads, int stage1Target, int stage2Target, int stage3Target) throws InterruptedException { long wait = 0; int stage1 = 0; int stage2 = 0; int stage3 = 0; while((stage1 != stage1Target || stage2 != stage2Target || stage3 != stage3Target) && wait < THREAD_WAIT_TIME) { stage1 = 0; stage2 = 0; stage3 = 0; for (TestThread testThread : testThreads) { switch(testThread.getStage()){ case 1: stage1++; break; case 2: stage2++; break; case 3: stage3++; break; } } Thread.sleep(100); wait += 100; } return stage1 == stage1Target && stage2 == stage2Target && stage3 == stage3Target; } private static class TestThread extends Thread { private final Object lock; private final LimitLatch latch; private volatile int stage = 0; public TestThread(LimitLatch latch, Object lock) { this.latch = latch; this.lock = lock; } public int getStage() { return stage; } @Override public void run() { try { stage = 1; latch.countUpOrAwait(); stage = 2; if (lock != null) { synchronized (lock) { lock.wait(); } } latch.countDown(); stage = 3; } catch (InterruptedException x) { x.printStackTrace(); } } } }
apache-2.0
aayaffe/SailingRaceCourseManager
app/src/main/java/com/aayaffe/sailingracecoursemanager/events/Event.java
2018
package com.aayaffe.sailingracecoursemanager.events; import com.aayaffe.sailingracecoursemanager.calclayer.DBObject; import com.google.firebase.database.Exclude; import java.util.HashMap; import java.util.List; import java.util.Random; import java.util.UUID; /** * Avi Marine Innovations - www.avimarine.in * * Created by Amit Y. on 19/02/2016. */ public class Event { private String name; @Exclude private UUID _uuid; private int lastBuoyId; private String eventManager; private HashMap<String,DBObject> boats; private HashMap<String,DBObject> buoys; public HashMap<String,List<String>> Assignments; public int yearStart; public int yearEnd; public int monthStart; public int monthEnd; public int dayStart; public int dayEnd; public String accessCode; public Event(){ _uuid = UUID.randomUUID(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getLastBuoyId() { return lastBuoyId; } public void setLastBuoyId(int lastBuoyId) { this.lastBuoyId = lastBuoyId; } public HashMap<String, DBObject> getBoats() { return boats; } public void setBoats(HashMap<String, DBObject> boats) { this.boats = boats; } public HashMap<String, DBObject> getBuoys() { return buoys; } public void setBuoys(HashMap<String, DBObject> buoys) { this.buoys = buoys; } public String getUuid() { return _uuid.toString(); } public void setUuid(String uuid) { this._uuid = UUID.fromString(uuid); } public String getManagerUuid() { return eventManager; } public void setManagerUuid(String uuid) { this.eventManager = uuid; } public static String generateAccessCode() { Random rand = new Random(); int n = rand.nextInt(899999) + 100000; return String.valueOf(n); } }
apache-2.0
rali-udem/JSrealB
demos/UDregenerator/utils.js
2314
// useful auxiliary functions // add elements of list l2 to the end of l1 and return l1 // because I have problem remembering this trick taken from // https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/push function appendTo(l1,l2){ if (Array.isArray(l2)){ Array.prototype.push.apply(l1,l2); } else { l1.push(l2) } return l1; } function fixPunctuation(str){ str=str.replace(/ +([-,.?!:%])/g,"$1"); str=str.replace(/\( /,"("); str=str.replace(/ \)/,")"); return str; } // check if two tokens are equal (taking some exception into account) function equalToks(jTok,tTok){ jTok=jTok.trim().toLowerCase(); tTok=tTok.trim().toLowerCase(); if (jTok==tTok)return true; if (jTok=="is" && (tTok=="ai" || tTok=="'s"))return true; if (jTok=="not" && (tTok=="n't" || tTok=="nt"))return true; if (jTok=="will" && tTok=="'ll")return true; return false } // realize each group and compare with the original text // show differences on the Javascript console function compareAll(){ let nb=0,nbDiffs=0; for (let g of groups){ nb++; const text=g.depsInfo.deps.map(d=>d.form).join(" ").trim(); const jsr=g.jsrReal; const sentId=g.depsInfo.sentId; let jsrTokens=jsr.split(/([\w']+)/).filter(t=>!/^ *$/.test(t)); let textTokens=text.split(/([\w']+)/).filter(t=>!/^ *$/.test(t)); if (textTokens[textTokens.length-1].trim()!="."){ if (textTokens[textTokens.length-1].trim()!=jsrTokens[jsrTokens.length-1].trim()) jsrTokens.pop() } if (jsrTokens.length != textTokens.length){ console.log(sentId+":"+text+":"+jsr); nbDiffs++; } else { for (i in textTokens){ if (!equalToks(jsrTokens[i],textTokens[i])){ console.log(sentId+":"+text+":"+jsr); nbDiffs++; break; } } } } console.log("%d structures processed; %d difference%s",nb,nbDiffs,nbDiffs>1?"s":"") } if (typeof module !== 'undefined' && module.exports) { // called as a node.js module exports.appendTo=appendTo; exports.fixPunctuation=fixPunctuation; exports.compareAll=compareAll; }
apache-2.0
sejoker/nodeschool-challenges
functional-js/duckCount.js
219
/* globals module */ 'use strict'; module.exports = function duckCount(){ var args = [].slice.call(arguments); return args.filter(function(current){ return {}.hasOwnProperty.call(current, 'quack'); }).length; };
apache-2.0
avantassel/json-api-response
tests/Data/Post.php
709
<?php namespace Neomerx\JsonApi\Tests\Data; /** * Copyright 2015 info@neomerx.com (www.neomerx.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. */ use \stdClass; class Post extends stdClass { }
apache-2.0
957651480/thinkphpsite
App/Modules/Admin/Model/GroupModel.class.php
326
<?php // 配置类型模型 class GroupModel extends CommonModel { protected $_validate = array( array('name','require','名称必须'), ); protected $_auto = array( array('status',1,self::MODEL_INSERT,'string'), array('create_time','time',self::MODEL_INSERT,'function'), ); }
apache-2.0
legend0702/zhq
zhq-core/src/test/java/cn/zhuhongqing/reflect/SetMapAdapter.java
2303
package cn.zhuhongqing.reflect; import java.util.AbstractSet; import java.util.Iterator; import java.util.Map; /** * Map adapter for a set provides an easy way to have a Set from various map * implementations. */ public abstract class SetMapAdapter<E> extends AbstractSet<E> { protected Map<E, Object> map; // Dummy value to associate with an Object in the backing Map private static final Object DUMMY_VALUE = new Object(); /** * Constructs a new, empty set; the backing <code>HashMap</code> instance * has default initial capacity (16) and load factor (0.75). */ protected SetMapAdapter(Map<E, Object> mapImplementation) { this.map = mapImplementation; } /** * Returns an iterator over the elements in this set. The elements are * returned in no particular order. * * @return an Iterator over the elements in this set. */ @Override public Iterator<E> iterator() { return map.keySet().iterator(); } /** * Returns the number of elements in this set (its cardinality). */ @Override public int size() { return map.size(); } /** * Returns <code>true</code> if this set contains no elements. */ @Override public boolean isEmpty() { return map.isEmpty(); } /** * Returns <code>true</code> if this set contains the specified element. * * @param o * element whose presence in this set is to be tested. * @return <code>true</code> if this set contains the specified element. */ @Override public boolean contains(Object o) { return map.containsKey(o); } /** * Adds the specified element to this set if it is not already present. * * @param o * element to be added to this set. * @return <code>true</code> if the set did not already contain the * specified element. */ @Override public boolean add(E o) { return map.put(o, DUMMY_VALUE) == null; } /** * Removes the specified element from this set if it is present. * * @param o * object to be removed from this set, if present. * @return <code>true</code> if the set contained the specified element. */ @Override public boolean remove(Object o) { return map.remove(o) == DUMMY_VALUE; } /** * Removes all of the elements from this set. */ @Override public void clear() { map.clear(); } }
apache-2.0
Q115/Goalie_Android
app/src/main/java/com/github/q115/goalie_android/ui/main/MainActivityPagerAdapter.java
3459
package com.github.q115.goalie_android.ui.main; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.view.ViewGroup; import com.github.q115.goalie_android.R; import com.github.q115.goalie_android.ui.main.feeds.FeedsFragment; import com.github.q115.goalie_android.ui.main.feeds.FeedsPresenter; import com.github.q115.goalie_android.ui.main.my_goals.MyGoalsFragment; import com.github.q115.goalie_android.ui.main.my_goals.MyGoalsPresenter; import com.github.q115.goalie_android.ui.main.requests.RequestsFragment; import com.github.q115.goalie_android.ui.main.requests.RequestsPresenter; /* * Copyright 2017 Qi Li * * 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 MainActivityPagerAdapter extends FragmentPagerAdapter { private MyGoalsPresenter mMyGoalsPresenter; private RequestsPresenter mRequestsPresenter; private FeedsPresenter mFeedsPresenter; private final String[] mTitles; public MainActivityPagerAdapter(Context context, FragmentManager fm) { super(fm); mTitles = new String[]{ context.getString(R.string.tab_my_goal), context.getString(R.string.tab_requests), context.getString(R.string.tab_feeds)}; } @Override public Object instantiateItem(ViewGroup container, int position) { Fragment createdFragment = (Fragment) super.instantiateItem(container, position); // save the appropriate reference depending on position switch (position) { case 0: mMyGoalsPresenter = new MyGoalsPresenter((MyGoalsFragment) createdFragment); break; case 1: mRequestsPresenter = new RequestsPresenter((RequestsFragment) createdFragment); break; case 2: mFeedsPresenter = new FeedsPresenter((FeedsFragment) createdFragment); break; } return createdFragment; } @Override public Fragment getItem(int position) { switch (position) { case 0: return MyGoalsFragment.newInstance(); case 1: return RequestsFragment.newInstance(); case 2: return FeedsFragment.newInstance(); } return null; } @Override public int getCount() { return mTitles.length; } @Override public CharSequence getPageTitle(int position) { if (position < mTitles.length) return mTitles[position]; return null; } public MyGoalsPresenter getMyGoalsPresenter() { return mMyGoalsPresenter; } public RequestsPresenter getRequestsPresenter() { return mRequestsPresenter; } public FeedsPresenter getFeedsPresenter() { return mFeedsPresenter; } }
apache-2.0
vsavkin/csw-catalog
test/unit/service/describe_record_handler_test.rb
887
require "test_helper" module Catalog::Service class DescribeRecordHandlerTest < ActiveSupport::TestCase include Catalog::Test::XmlTestUtil include Catalog::Test::HandlerTestUtil def setup @handler_clazz = DescribeRecordHandler @default_input = {:service => 'CSW', :version => '2.0.2'} end test 'schema language must be xml schema' do invalid :schemalanguage => 'BOO' valid :schemalanguage => 'XMLSCHEMA' end test 'output format must be application/xml' do invalid :outputformat => 'BOO' valid :outputformat => 'application/xml' end test 'namespace argument must be well formatted' do invalid :namespace => 'booms' valid :namespace => "xmlns(uri)" end test 'always return empty rsults' do xml = request({}) check_xml_structure xml, ['DescribeRecordResponse'] end end end
apache-2.0
aws/aws-sdk-java
aws-java-sdk-health/src/main/java/com/amazonaws/services/health/model/transform/EventFilterMarshaller.java
5669
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.health.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.health.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * EventFilterMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class EventFilterMarshaller { private static final MarshallingInfo<List> EVENTARNS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("eventArns").build(); private static final MarshallingInfo<List> EVENTTYPECODES_BINDING = MarshallingInfo.builder(MarshallingType.LIST) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("eventTypeCodes").build(); private static final MarshallingInfo<List> SERVICES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("services").build(); private static final MarshallingInfo<List> REGIONS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("regions").build(); private static final MarshallingInfo<List> AVAILABILITYZONES_BINDING = MarshallingInfo.builder(MarshallingType.LIST) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("availabilityZones").build(); private static final MarshallingInfo<List> STARTTIMES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("startTimes").build(); private static final MarshallingInfo<List> ENDTIMES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("endTimes").build(); private static final MarshallingInfo<List> LASTUPDATEDTIMES_BINDING = MarshallingInfo.builder(MarshallingType.LIST) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("lastUpdatedTimes").build(); private static final MarshallingInfo<List> ENTITYARNS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("entityArns").build(); private static final MarshallingInfo<List> ENTITYVALUES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("entityValues").build(); private static final MarshallingInfo<List> EVENTTYPECATEGORIES_BINDING = MarshallingInfo.builder(MarshallingType.LIST) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("eventTypeCategories").build(); private static final MarshallingInfo<List> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("tags").build(); private static final MarshallingInfo<List> EVENTSTATUSCODES_BINDING = MarshallingInfo.builder(MarshallingType.LIST) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("eventStatusCodes").build(); private static final EventFilterMarshaller instance = new EventFilterMarshaller(); public static EventFilterMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(EventFilter eventFilter, ProtocolMarshaller protocolMarshaller) { if (eventFilter == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(eventFilter.getEventArns(), EVENTARNS_BINDING); protocolMarshaller.marshall(eventFilter.getEventTypeCodes(), EVENTTYPECODES_BINDING); protocolMarshaller.marshall(eventFilter.getServices(), SERVICES_BINDING); protocolMarshaller.marshall(eventFilter.getRegions(), REGIONS_BINDING); protocolMarshaller.marshall(eventFilter.getAvailabilityZones(), AVAILABILITYZONES_BINDING); protocolMarshaller.marshall(eventFilter.getStartTimes(), STARTTIMES_BINDING); protocolMarshaller.marshall(eventFilter.getEndTimes(), ENDTIMES_BINDING); protocolMarshaller.marshall(eventFilter.getLastUpdatedTimes(), LASTUPDATEDTIMES_BINDING); protocolMarshaller.marshall(eventFilter.getEntityArns(), ENTITYARNS_BINDING); protocolMarshaller.marshall(eventFilter.getEntityValues(), ENTITYVALUES_BINDING); protocolMarshaller.marshall(eventFilter.getEventTypeCategories(), EVENTTYPECATEGORIES_BINDING); protocolMarshaller.marshall(eventFilter.getTags(), TAGS_BINDING); protocolMarshaller.marshall(eventFilter.getEventStatusCodes(), EVENTSTATUSCODES_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
Palleiro/HCTControl
app/src/main/java/com/hctrom/romcontrol/prefs/MyListPreference.java
7814
package com.hctrom.romcontrol.prefs; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.content.res.TypedArray; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.preference.ListPreference; import android.support.v4.app.FragmentActivity; import android.text.TextUtils; import android.util.AttributeSet; import android.util.TypedValue; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import com.hctrom.romcontrol.R; import com.hctrom.romcontrol.alertas.DialogoAlertaReiniciar; import com.hctrom.romcontrol.alertas.DialogoAlertaReiniciarSystemUI; /* Created by Roberto Mariani and Anna Berkovitch, 08/06/15 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/>.*/ public class MyListPreference extends ListPreference { ArrayAdapter<CharSequence> adapter; private int mClickedDialogEntryIndex; private String mValue; private boolean mValueSet; private CharSequence[] mEntries; private CharSequence[] mEntryValues; private ContentResolver mContentResolver; private boolean mIsRestartSystemUI, mIsRebootRequired; private static FragmentActivity myContext; public MyListPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public MyListPreference(Context context, AttributeSet attrs) { super(context, attrs); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.Preference); mIsRestartSystemUI = typedArray.getBoolean(R.styleable.Preference_restartSystemUI, true); mIsRebootRequired = typedArray.getBoolean(R.styleable.Preference_rebootDevice, false); mContentResolver = context.getContentResolver(); } public void setValue(String value) { // Always persist/notify the first time. final boolean changed = !TextUtils.equals(mValue, value); if (changed || !mValueSet) { mValue = value; mValueSet = true; persistString(value); if (changed) { notifyChanged(); } } } @Override protected void onPrepareDialogBuilder(AlertDialog.Builder builder) { mEntries = getEntries(); mEntryValues = getEntryValues(); adapter = new ArrayAdapter<>(getContext(), R.layout.simple_list_item_single_choice, mEntries); super.onPrepareDialogBuilder(builder); mClickedDialogEntryIndex = getValueIndex(); builder.setSingleChoiceItems(adapter, mClickedDialogEntryIndex, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mClickedDialogEntryIndex = which; MyListPreference.this.onClick(dialog, DialogInterface.BUTTON_POSITIVE); dialog.dismiss(); } }) ; } private int getValueIndex() { return findIndexOfValue(mValue); } @Override protected void showDialog(Bundle state) { super.showDialog(state); TypedValue typedValue = new TypedValue(); Resources.Theme theme = getContext().getTheme(); theme.resolveAttribute(R.attr.colorAccent, typedValue, true); AlertDialog dialog = (AlertDialog) getDialog(); dialog.show(); Button cancel = dialog.getButton(AlertDialog.BUTTON_NEGATIVE); cancel.setTextColor(typedValue.data); dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_bg); ListView lv = dialog.getListView(); int padding = Math.round(getContext().getResources().getDimension(R.dimen.dialog_listView_top_padding)); lv.setPadding(0, padding, 0, 0); } @Override protected void onDialogClosed(boolean positiveResult) { super.onDialogClosed(positiveResult); if (positiveResult && mClickedDialogEntryIndex >= 0 && mEntryValues != null) { String value = mEntryValues[mClickedDialogEntryIndex].toString(); if (callChangeListener(value)) { setValue(value); } } if (mIsRestartSystemUI) { if (mIsRebootRequired) { // no hacer nada } else{ //Utils.showRebootRequiredDialog(getContext()); myContext = (FragmentActivity) getContext(); final DialogoAlertaReiniciarSystemUI dialogo = new DialogoAlertaReiniciarSystemUI(); dialogo.show(myContext.getSupportFragmentManager(), "tagAlerta"); } } if (mIsRebootRequired) { //Utils.showRebootRequiredDialog(getContext()); myContext = (FragmentActivity) getContext(); final DialogoAlertaReiniciar dialogo = new DialogoAlertaReiniciar(); dialogo.show(myContext.getSupportFragmentManager(), "tagAlerta"); } } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return a.getString(index); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { setValue(restoreValue ? getPersistedString(mValue) : (String) defaultValue); } @Override protected Parcelable onSaveInstanceState() { final Parcelable superState = super.onSaveInstanceState(); if (isPersistent()) { // No need to save instance state since it's persistent return superState; } final SavedState myState = new SavedState(superState); myState.value = getValue(); return myState; } @Override protected void onRestoreInstanceState(Parcelable state) { if (state == null || !state.getClass().equals(SavedState.class)) { // Didn't save state for us in onSaveInstanceState super.onRestoreInstanceState(state); return; } SavedState myState = (SavedState) state; super.onRestoreInstanceState(myState.getSuperState()); setValue(myState.value); } private static class SavedState extends BaseSavedState { String value; public SavedState(Parcel source) { super(source); value = source.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeString(value); } public SavedState(Parcelable superState) { super(superState); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
apache-2.0
grozeille/Spring.Fluent
Spring.Fluent.Tests/IRepository.cs
855
#region License /* * Copyright © 2002-2005 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. */ #endregion #region Using using System; using System.Collections.Generic; using System.Text; #endregion namespace Spring.Fluent.Tests { public interface IRepository { string SayHello(); } }
apache-2.0
scholzj/barnabas
systemtest/src/main/java/io/strimzi/systemtest/utils/kubeUtils/controllers/StatefulSetUtils.java
13723
/* * Copyright Strimzi authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.strimzi.systemtest.utils.kubeUtils.controllers; import io.fabric8.kubernetes.api.model.LabelSelector; import io.fabric8.kubernetes.api.model.apps.StatefulSet; import io.strimzi.operator.common.model.Labels; import io.strimzi.systemtest.Constants; import io.strimzi.systemtest.resources.ResourceManager; import io.strimzi.systemtest.resources.ResourceOperation; import io.strimzi.systemtest.resources.crd.KafkaResource; import io.strimzi.systemtest.utils.kubeUtils.objects.PodUtils; import io.strimzi.test.TestUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.Map; import java.util.TreeMap; import static io.strimzi.test.k8s.KubeClusterResource.cmdKubeClient; import static io.strimzi.test.k8s.KubeClusterResource.kubeClient; public class StatefulSetUtils { private static final Logger LOGGER = LogManager.getLogger(StatefulSetUtils.class); private static final long READINESS_TIMEOUT = ResourceOperation.getTimeoutForResourceReadiness(Constants.STATEFUL_SET); private static final long DELETION_TIMEOUT = ResourceOperation.getTimeoutForResourceDeletion(Constants.STATEFUL_SET); private StatefulSetUtils() { } /** * Returns a map of pod name to resource version for the pods currently in the given statefulset. * @param namespaceName Namespace name * @param name The StatefulSet name * @return A map of pod name to resource version for pods in the given StatefulSet. */ public static Map<String, String> ssSnapshot(String namespaceName, String name) { StatefulSet statefulSet = kubeClient(namespaceName).getStatefulSet(namespaceName, name); LabelSelector selector = statefulSet.getSpec().getSelector(); return PodUtils.podSnapshot(namespaceName, selector); } public static Map<String, String> ssSnapshot(String name) { return ssSnapshot(kubeClient().getNamespace(), name); } /** * Method to check that all pods for expected StatefulSet were rolled * @param namespaceName Namespace name * @param name StatefulSet name * @param snapshot Snapshot of pods for StatefulSet before the rolling update * @return true when the pods for StatefulSet are recreated */ public static boolean ssHasRolled(String namespaceName, String name, Map<String, String> snapshot) { boolean log = true; if (log) { LOGGER.debug("Existing snapshot: {}", new TreeMap<>(snapshot)); } LabelSelector selector = null; int times = 60; do { selector = kubeClient(namespaceName).getStatefulSetSelectors(namespaceName, name); if (selector == null) { if (times-- == 0) { throw new RuntimeException("Retry failed"); } try { Thread.sleep(1_000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } while (selector == null); Map<String, String> map = PodUtils.podSnapshot(namespaceName, selector); if (log) { LOGGER.debug("Current snapshot: {}", new TreeMap<>(map)); } // rolled when all the pods in snapshot have a different version in map map.keySet().retainAll(snapshot.keySet()); if (log) { LOGGER.debug("Pods in common: {}", new TreeMap<>(map)); } for (Map.Entry<String, String> e : map.entrySet()) { String currentResourceVersion = e.getValue(); String resourceName = e.getKey(); String oldResourceVersion = snapshot.get(resourceName); if (oldResourceVersion.equals(currentResourceVersion)) { if (log) { LOGGER.debug("At least {} hasn't rolled", resourceName); } return false; } } if (log) { LOGGER.debug("All pods seem to have rolled"); } return true; } public static boolean ssHasRolled(String name, Map<String, String> snapshot) { return ssHasRolled(kubeClient().getNamespace(), name, snapshot); } /** * Method to wait when StatefulSet will be recreated after rolling update * @param namespaceName Namespace name * @param name StatefulSet name * @param snapshot Snapshot of pods for StatefulSet before the rolling update * @return The snapshot of the StatefulSet after rolling update with Uid for every pod */ public static Map<String, String> waitTillSsHasRolled(String namespaceName, String name, Map<String, String> snapshot) { LOGGER.info("Waiting for StatefulSet {} rolling update", name); TestUtils.waitFor("StatefulSet " + name + " rolling update", Constants.WAIT_FOR_ROLLING_UPDATE_INTERVAL, ResourceOperation.timeoutForPodsOperation(snapshot.size()), () -> { try { return ssHasRolled(namespaceName, name, snapshot); } catch (Exception e) { e.printStackTrace(); return false; } }); LOGGER.info("StatefulSet {} rolling update finished", name); return ssSnapshot(namespaceName, name); } public static Map<String, String> waitTillSsHasRolled(String name, Map<String, String> snapshot) { return waitTillSsHasRolled(kubeClient().getNamespace(), name, snapshot); } /** * Method to wait when StatefulSet will be recreated after rolling update with wait for all pods ready * @param namespaceName Namespace name * @param name StatefulSet name * @param expectedPods Expected number of pods * @param snapshot Snapshot of pods for StatefulSet before the rolling update * @return The snapshot of the StatefulSet after rolling update with Uid for every pod */ public static Map<String, String> waitTillSsHasRolled(String namespaceName, String name, int expectedPods, Map<String, String> snapshot) { waitTillSsHasRolled(namespaceName, name, snapshot); waitForAllStatefulSetPodsReady(namespaceName, name, expectedPods, READINESS_TIMEOUT); return ssSnapshot(namespaceName, name); } public static Map<String, String> waitTillSsHasRolled(String name, int expectedPods, Map<String, String> snapshot) { return waitTillSsHasRolled(kubeClient().getNamespace(), name, expectedPods, snapshot); } /** * Wait until the STS is ready and all of its Pods are also ready with custom timeout. * * @param namespaceName Namespace name * @param statefulSetName The name of the StatefulSet * @param expectPods The number of pods expected. */ public static void waitForAllStatefulSetPodsReady(String namespaceName, String statefulSetName, int expectPods, long timeout) { String resourceName = statefulSetName.contains("-kafka") ? statefulSetName.replace("-kafka", "") : statefulSetName.replace("-zookeeper", ""); LOGGER.info("Waiting for StatefulSet {} to be ready", statefulSetName); TestUtils.waitFor("StatefulSet " + statefulSetName + " to be ready", Constants.POLL_INTERVAL_FOR_RESOURCE_READINESS, timeout, () -> kubeClient(namespaceName).getStatefulSetStatus(namespaceName, statefulSetName), () -> ResourceManager.logCurrentResourceStatus(KafkaResource.kafkaClient().inNamespace(namespaceName).withName(resourceName).get())); LOGGER.info("Waiting for {} Pod(s) of StatefulSet {} to be ready", expectPods, statefulSetName); PodUtils.waitForPodsReady(namespaceName, kubeClient(namespaceName).getStatefulSetSelectors(namespaceName, statefulSetName), expectPods, true, () -> ResourceManager.logCurrentResourceStatus(KafkaResource.kafkaClient().inNamespace(namespaceName).withName(resourceName).get())); LOGGER.info("StatefulSet {} is ready", statefulSetName); } public static void waitForAllStatefulSetPodsReady(String statefulSetName, int expectPods, long timeout) { waitForAllStatefulSetPodsReady(kubeClient().getNamespace(), statefulSetName, expectPods, timeout); } /** * Wait until the STS is ready and all of its Pods are also ready with default timeout. * * @param statefulSetName The name of the StatefulSet * @param expectPods The number of pods expected. */ public static void waitForAllStatefulSetPodsReady(String statefulSetName, int expectPods) { waitForAllStatefulSetPodsReady(statefulSetName, expectPods, READINESS_TIMEOUT); } /** * Wait until the given StatefulSet has been deleted. * @param namespaceName Namespace name * @param name The name of the StatefulSet. */ public static void waitForStatefulSetDeletion(String namespaceName, String name) { LOGGER.debug("Waiting for StatefulSet {} deletion", name); TestUtils.waitFor("StatefulSet " + name + " to be deleted", Constants.POLL_INTERVAL_FOR_RESOURCE_DELETION, DELETION_TIMEOUT, () -> { if (kubeClient(namespaceName).getStatefulSet(namespaceName, name) == null) { return true; } else { LOGGER.warn("StatefulSet {} is not deleted yet! Triggering force delete by cmd client!", name); cmdKubeClient(namespaceName).deleteByName("statefulset", name); return false; } }); LOGGER.debug("StatefulSet {} was deleted", name); } public static void waitForStatefulSetDeletion(String name) { waitForStatefulSetDeletion(kubeClient().getNamespace(), name); } /** * Wait until the given StatefulSet has been recovered. * @param name The name of the StatefulSet. */ public static void waitForStatefulSetRecovery(String name, String statefulSetUid) { LOGGER.info("Waiting for StatefulSet {}-{} recovery in namespace {}", name, statefulSetUid, kubeClient().getNamespace()); TestUtils.waitFor("StatefulSet " + name + " to be recovered", Constants.POLL_INTERVAL_FOR_RESOURCE_READINESS, Constants.TIMEOUT_FOR_RESOURCE_RECOVERY, () -> !kubeClient().getStatefulSetUid(name).equals(statefulSetUid)); LOGGER.info("StatefulSet {} was recovered", name); } public static void waitForStatefulSetLabelsChange(String namespaceName, String statefulSetName, Map<String, String> labels) { for (Map.Entry<String, String> entry : labels.entrySet()) { boolean isK8sTag = entry.getKey().equals("controller-revision-hash") || entry.getKey().equals("statefulset.kubernetes.io/pod-name"); boolean isStrimziTag = entry.getKey().startsWith(Labels.STRIMZI_DOMAIN); // ignoring strimzi.io and k8s labels if (!(isStrimziTag || isK8sTag)) { LOGGER.info("Waiting for Stateful set label change {} -> {}", entry.getKey(), entry.getValue()); TestUtils.waitFor("Waits for StatefulSet label change " + entry.getKey() + " -> " + entry.getValue(), Constants.POLL_INTERVAL_FOR_RESOURCE_READINESS, Constants.GLOBAL_TIMEOUT, () -> kubeClient(namespaceName).getStatefulSet(namespaceName, statefulSetName).getMetadata().getLabels().get(entry.getKey()).equals(entry.getValue()) ); } } } public static void waitForStatefulSetLabelsChange(String statefulSetName, Map<String, String> labels) { waitForStatefulSetLabelsChange(kubeClient().getNamespace(), statefulSetName, labels); } public static void waitForStatefulSetLabelsDeletion(String namespaceName, String statefulSetName, String... labelKeys) { for (final String labelKey : labelKeys) { LOGGER.info("Waiting for StatefulSet label {} change to {}", labelKey, null); TestUtils.waitFor("Waiting for StatefulSet label" + labelKey + " change to " + null, Constants.POLL_INTERVAL_FOR_RESOURCE_READINESS, DELETION_TIMEOUT, () -> kubeClient(namespaceName).getStatefulSet(namespaceName, statefulSetName).getMetadata().getLabels().get(labelKey) == null ); LOGGER.info("StatefulSet label {} change to {}", labelKey, null); } } public static void waitForNoRollingUpdate(String namespaceName, String statefulSetName, Map<String, String> pods) { // alternative to sync hassling AtomicInteger one could use an integer array instead // not need to be final because reference to the array does not get another array assigned int[] i = {0}; TestUtils.waitFor("Waiting for stability of rolling update will be not triggered", Constants.GLOBAL_POLL_INTERVAL, Constants.GLOBAL_TIMEOUT, () -> { if (!StatefulSetUtils.ssHasRolled(namespaceName, statefulSetName, pods)) { LOGGER.info("{} pods didn't roll. Remaining seconds for stability: {}", pods.toString(), Constants.GLOBAL_RECONCILIATION_COUNT - i[0]); return i[0]++ == Constants.GLOBAL_RECONCILIATION_COUNT; } else { throw new RuntimeException(pods.toString() + " pods are rolling!"); } } ); } public static void waitForNoRollingUpdate(String statefulSetName, Map<String, String> pods) { waitForNoRollingUpdate(kubeClient().getNamespace(), statefulSetName, pods); } }
apache-2.0
sqyljw/web
case/phoneapp/js/move1.js
4096
window.onload=function(){ top1(); setPro(); setCity(document.getElementById("pro").value); setArea(); cityb(); cityc(); a(); b(); c(); joba(); jobb(); ja(); jb(); anniu(); } function top1(){ document.getElementById("top1").onclick=function(){ window.history.go(-1); } } var pca={ "浙江省":{ "杭州市":["上城区","下城区","西湖区"], "舟山市":["临城区","定海区"], "温州市":[" 鹿城区","龙湾区","瓯海区"], "宁波市":["北仑区"," 鄞州区","海曙区","江东区","江北区"] }, "直辖市":{ "北京市":["东城区","西城区","朝阳区"], "上海市":["浦东新区","徐汇"], "天津市":[" 和平区","河东区","河西区"], "重庆市":["万州区"," 涪陵区","渝中区","大渡口区"] }, "广东省":{ "深圳市":["南山区","宝安区"], "广州市":["越秀区","海珠区","荔湾区","天河区"], "东莞市":["莞城","东城","南城","万江"] }, "安徽省":{ "合肥市":["蜀山区","高新区","滨湖新区"], "芜湖市":["镜湖区","三山区"] }, "江西省":{ "南昌市":["东湖区","西湖区"], "景德镇市":["珠山区","昌江区"] } }; function setPro(){ for(var key in pca){ var opE=new Option(key,key); document.getElementById("pro").add(opE); } } function setCity(seletedPro){ document.getElementById("city").innerHTML=""; for(var key in pca[seletedPro]){ var opS="<option value='"+key+"'>"+key+"</option>"; document.getElementById("city").innerHTML+=opS; } setArea(); } function setArea(){ document.getElementById("area").length=0; var seletedPro=document.getElementById("pro").value var seletedCity=document.getElementById("city").value for(i=0;i<pca[seletedPro][seletedCity].length;i++){ var opE=new Option(pca[seletedPro][seletedCity][i],pca[seletedPro][seletedCity][i]); document.getElementById("area").add(opE); } } function cityb(){//点击显示 document.getElementById("input_city").onclick=function(){ document.getElementById("city_2").className="citya"; } } function cityc(){//点击显示 document.getElementById("city_s").onclick=function(){ document.getElementById("input_city").value=document.getElementById("pro").value+document.getElementById("city").value+document.getElementById("area").value; document.getElementById("city_2").className="city"; } } function a(){//选择后隐藏 var sex=document.getElementsByClassName("x_sex_n"); for(var i=0;i<sex.length;i++){ sex[i].onclick=function(){ document.getElementById("sex").value=this.innerHTML; document.getElementById("sex_s").className="x_sex"; } } } function b(){//点击显示 document.getElementById("sex").onclick=function(){ document.getElementById("sex_s").className="disb"; } } function c(){//点击取消隐藏 var cc=document.getElementById("x_sex_q"); cc.onclick=function(){ document.getElementById("sex_s").className="x_sex"; } } function joba(){//选择后隐藏 var sex=document.getElementsByClassName("x_job_x"); for(var i=0;i<sex.length;i++){ sex[i].onclick=function(){ document.getElementById("input_job").value=this.innerHTML; document.getElementById("job_s").className="job"; } } } function jobb(){//点击显示 document.getElementById("input_job").onclick=function(){ document.getElementById("job_s").className="disb"; } } function ja(){//选择后隐藏 var sex=document.getElementsByClassName("x_j_x"); for(var i=0;i<sex.length;i++){ sex[i].onclick=function(){ document.getElementById("input_j").value=this.innerHTML; document.getElementById("j_s").className="j_"; } } } function jb(){//点击显示 document.getElementById("input_j").onclick=function(){ document.getElementById("j_s").className="disb"; } } function anniu(){ document.getElementById("anniu").onclick=function(){ alert("您好!后续页面,在我们加入贵公司,您将会看到更加完好的效果") }; }
apache-2.0
glasperfan/thesis
bach_code/eval_sm.lua
3151
-- eval_sum.lua --[[ Experiment 2C: Softmax --]] -- Other libraries require 'nn' require 'hdf5' --- Neural network --- function make_model(max_index, output_size) -- Embedding sequence local embedding = nn.Sequential() embedding:add(nn.LookupTable(max_index, embedding_size)) embedding:add(nn.Sum(1)) -- Feed forward sequence local model = nn.Sequential() model:add(embedding) model:add(nn.Linear(embedding_size, hidden_size)) model:add(nn.Tanh()) -- model:add(nn.Dropout(dropout)) model:add(nn.Linear(hidden_size, hidden_size)) model:add(nn.Tanh()) -- model:add(nn.Dropout(dropout)) model:add(nn.Linear(hidden_size, output_size)) model:add(nn.LogSoftMax()) -- Criterion: negative log likelihood local criterion = nn.ClassNLLCriterion() return model, criterion end --- Train the Model --- function train(Xtrain, ytrain, Xtest, ytest, model, criterion) model:training() last_nll = 999999 epoch = 1 while true do nll = 0 for j = 1, Xtrain:size(1) do -- Forward local out = model:forward(Xtrain[j]) nll = nll + criterion:forward(out, ytrain[j]) -- Backward model:zeroGradParameters() local deriv = criterion:backward(out, ytrain[j]) model:backward(Xtrain[j], deriv) model:updateParameters(learning_rate) model:zeroGradParameters() end -- print(torch.mean(nll_arr)) print("Epoch:", epoch, nll / Xtrain:size(1)) model:evaluate() eval(Xtrain, ytrain, model, criterion) eval(Xtest, ytest, model, criterion) model:training() if last_nll < nll then break end last_nll = nll epoch = epoch + 1 end end -- Evaluation numeral subtask -- function eval(Xtest, ytest, model, criterion) -- Collect numeral predictions local nll_arr = torch.Tensor(Xtest:size(1)) local pred = torch.IntTensor(ytest:size(1)) for j = 1, Xtest:size(1) do out = model:forward(Xtest[j]) expout = torch.Tensor(out:size(1)):copy(out):exp() -- print(out[ytest[j]], expout[ytest[j]]) _ , argmax = torch.max(out, 1) pred[j] = argmax[1] nll_arr[j] = criterion:forward(out, ytest[j]) end -- Evaluation local correct = torch.sum(torch.eq(pred, ytest)) local count = pred:size(1) -- Print some output -- -- for i = count - 100, count do print(pred[i], ytest[i]) end -- Results -- print(string.format("Average nll: %.3f", torch.mean(nll_arr))) print(string.format("Percentage correct: %.2f%%", correct / count * 100.0)) end function main() -- Contants embedding_size = 200 hidden_size = 200 learning_rate = 0.01 dropout = 0.0 print("hidden size", hidden_size) print("learning rate", learning_rate) print("dropout", dropout) -- Load data local f = hdf5.open("data/chorales_sm.hdf5") local Xtrain = f:read('Xtrain'):all() local Xtest = f:read('Xtest'):all() local ytrain = f:read('ytrain'):all() local ytest = f:read('ytest'):all() local Xall = torch.cat(Xtrain, Xtest, 1) local yall = torch.cat(ytrain, ytest, 1) f:close() local max_index = torch.max(Xall) local output_size = torch.max(yall) -- Create global models and criterion model, criterion = make_model(max_index, output_size) -- Train train(Xtrain, ytrain, Xtest, ytest, model, criterion) end main()
apache-2.0
trasa/aws-sdk-java
aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/LimitExceededException.java
1110
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.devicefarm.model; import com.amazonaws.AmazonServiceException; /** * <p> * A limit was exceeded. * </p> */ public class LimitExceededException extends AmazonServiceException { private static final long serialVersionUID = 1L; /** * Constructs a new LimitExceededException with the specified error message. * * @param message * Describes the error encountered. */ public LimitExceededException(String message) { super(message); } }
apache-2.0
aelij/roslyn
src/Features/Core/Portable/GenerateMember/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.State.cs
4633
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember { internal partial class AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> { internal abstract class State { public INamedTypeSymbol ContainingType { get; protected set; } public INamedTypeSymbol TypeToGenerateIn { get; protected set; } public bool IsStatic { get; protected set; } public bool IsContainedInUnsafeType { get; protected set; } // Just the name of the method. i.e. "Goo" in "X.Goo" or "X.Goo()" public SyntaxToken IdentifierToken { get; protected set; } public TSimpleNameSyntax SimpleNameOpt { get; protected set; } // The entire expression containing the name, not including the invocation. i.e. "X.Goo" // in "X.Goo()". public TExpressionSyntax SimpleNameOrMemberAccessExpression { get; protected set; } public TInvocationExpressionSyntax InvocationExpressionOpt { get; protected set; } public bool IsInConditionalAccessExpression { get; protected set; } public bool IsWrittenTo { get; protected set; } public SignatureInfo SignatureInfo { get; protected set; } public MethodKind MethodKind { get; internal set; } public MethodGenerationKind MethodGenerationKind { get; protected set; } protected Location location = null; public Location Location { get { if (IdentifierToken.SyntaxTree != null) { return IdentifierToken.GetLocation(); } return location; } } protected async Task<bool> TryFinishInitializingStateAsync(TService service, SemanticDocument document, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); TypeToGenerateIn = await SymbolFinder.FindSourceDefinitionAsync(TypeToGenerateIn, document.Project.Solution, cancellationToken).ConfigureAwait(false) as INamedTypeSymbol; if (TypeToGenerateIn.IsErrorType()) { return false; } if (!service.ValidateTypeToGenerateIn(document.Project.Solution, TypeToGenerateIn, IsStatic, ClassInterfaceModuleStructTypes)) { return false; } if (!CodeGenerator.CanAdd(document.Project.Solution, TypeToGenerateIn, cancellationToken)) { return false; } // Ok. It either didn't bind to any symbols, or it bound to a symbol but with // errors. In the former case we definitely want to offer to generate a method. In // the latter case, we want to generate a method *unless* there's an existing method // with the same signature. var existingMethods = TypeToGenerateIn.GetMembers(IdentifierToken.ValueText) .OfType<IMethodSymbol>(); var destinationProvider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var syntaxFacts = destinationProvider.GetService<ISyntaxFactsService>(); var syntaxFactory = destinationProvider.GetService<SyntaxGenerator>(); IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(TypeToGenerateIn); var generatedMethod = SignatureInfo.GenerateMethod(syntaxFactory, false, cancellationToken); return !existingMethods.Any(m => SignatureComparer.Instance.HaveSameSignature(m, generatedMethod, caseSensitive: syntaxFacts.IsCaseSensitive, compareParameterName: true, isParameterCaseSensitive: syntaxFacts.IsCaseSensitive)); } } } }
apache-2.0
chmyga/component-runtime
component-api/src/main/java/org/talend/sdk/component/api/service/http/ConfigurerOption.java
1061
/** * Copyright (C) 2006-2020 Talend Inc. - www.talend.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.talend.sdk.component.api.service.http; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Marks a parameter as a configurer option. */ @Target(PARAMETER) @Retention(RUNTIME) public @interface ConfigurerOption { /** * @return option name. */ String value(); }
apache-2.0
eric-haibin-lin/peloton
tests/executor/projection_test.cpp
7470
//===----------------------------------------------------------------------===// // // PelotonDB // // projection_test.cpp // // Identification: tests/executor/projection_test.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include <set> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "backend/planner/projection_plan.h" #include "backend/expression/expression_util.h" #include "backend/expression/constant_value_expression.h" #include "backend/executor/projection_executor.h" #include "backend/executor/logical_tile_factory.h" #include "backend/storage/data_table.h" #include "executor/executor_tests_util.h" #include "executor/mock_executor.h" #include "harness.h" using ::testing::NotNull; using ::testing::Return; namespace peloton { namespace test { void RunTest(executor::ProjectionExecutor &executor, size_t expected_num_tiles) { EXPECT_TRUE(executor.Init()); std::vector<std::unique_ptr<executor::LogicalTile>> result_tiles; while (executor.Execute()) { result_tiles.emplace_back(executor.GetOutput()); } EXPECT_EQ(expected_num_tiles, result_tiles.size()); } TEST(ProjectionTests, BasicTest) { MockExecutor child_executor; EXPECT_CALL(child_executor, DInit()).WillOnce(Return(true)); EXPECT_CALL(child_executor, DExecute()) .WillOnce(Return(true)) .WillOnce(Return(false)); size_t tile_size = 5; // Create a table and wrap it in logical tile std::unique_ptr<storage::DataTable> data_table( ExecutorTestsUtil::CreateTable(tile_size)); ExecutorTestsUtil::PopulateTable(data_table.get(), tile_size, false, false, false); std::unique_ptr<executor::LogicalTile> source_logical_tile1( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(0))); EXPECT_CALL(child_executor, GetOutput()) .WillOnce(Return(source_logical_tile1.release())); // Create the plan node planner::ProjectInfo::TargetList target_list; planner::ProjectInfo::DirectMapList direct_map_list; ///////////////////////////////////////////////////////// // PROJECTION 0 ///////////////////////////////////////////////////////// // construct schema std::vector<catalog::Column> columns; auto orig_schema = data_table.get()->GetSchema(); columns.push_back(orig_schema->GetColumn(0)); auto schema = new catalog::Schema(columns); // direct map planner::ProjectInfo::DirectMap direct_map = std::make_pair(0, std::make_pair(0, 0)); direct_map_list.push_back(direct_map); auto project_info = new planner::ProjectInfo(std::move(target_list), std::move(direct_map_list)); planner::ProjectionPlan node(project_info, schema); // Create and set up executor executor::ProjectionExecutor executor(&node, nullptr); executor.AddChild(&child_executor); RunTest(executor, 1); } TEST(ProjectionTests, TwoColumnTest) { MockExecutor child_executor; EXPECT_CALL(child_executor, DInit()).WillOnce(Return(true)); EXPECT_CALL(child_executor, DExecute()) .WillOnce(Return(true)) .WillOnce(Return(false)); size_t tile_size = 5; // Create a table and wrap it in logical tile std::unique_ptr<storage::DataTable> data_table( ExecutorTestsUtil::CreateTable(tile_size)); ExecutorTestsUtil::PopulateTable(data_table.get(), tile_size, false, false, false); std::unique_ptr<executor::LogicalTile> source_logical_tile1( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(0))); EXPECT_CALL(child_executor, GetOutput()) .WillOnce(Return(source_logical_tile1.release())); // Create the plan node planner::ProjectInfo::TargetList target_list; planner::ProjectInfo::DirectMapList direct_map_list; ///////////////////////////////////////////////////////// // PROJECTION 3, 1, 3 ///////////////////////////////////////////////////////// // construct schema std::vector<catalog::Column> columns; auto orig_schema = data_table.get()->GetSchema(); columns.push_back(orig_schema->GetColumn(3)); columns.push_back(orig_schema->GetColumn(1)); columns.push_back(orig_schema->GetColumn(3)); auto schema = new catalog::Schema(columns); // direct map planner::ProjectInfo::DirectMap map0 = std::make_pair(0, std::make_pair(0, 3)); planner::ProjectInfo::DirectMap map1 = std::make_pair(1, std::make_pair(0, 1)); planner::ProjectInfo::DirectMap map2 = std::make_pair(2, std::make_pair(0, 3)); direct_map_list.push_back(map0); direct_map_list.push_back(map1); direct_map_list.push_back(map2); auto project_info = new planner::ProjectInfo(std::move(target_list), std::move(direct_map_list)); planner::ProjectionPlan node(project_info, schema); // Create and set up executor executor::ProjectionExecutor executor(&node, nullptr); executor.AddChild(&child_executor); RunTest(executor, 1); } TEST(ProjectionTests, BasicTargetTest) { MockExecutor child_executor; EXPECT_CALL(child_executor, DInit()).WillOnce(Return(true)); EXPECT_CALL(child_executor, DExecute()) .WillOnce(Return(true)) .WillOnce(Return(false)); size_t tile_size = 5; // Create a table and wrap it in logical tile std::unique_ptr<storage::DataTable> data_table( ExecutorTestsUtil::CreateTable(tile_size)); ExecutorTestsUtil::PopulateTable(data_table.get(), tile_size, false, false, false); std::unique_ptr<executor::LogicalTile> source_logical_tile1( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(0))); EXPECT_CALL(child_executor, GetOutput()) .WillOnce(Return(source_logical_tile1.release())); // Create the plan node planner::ProjectInfo::TargetList target_list; planner::ProjectInfo::DirectMapList direct_map_list; ///////////////////////////////////////////////////////// // PROJECTION 0, TARGET 0 + 20 ///////////////////////////////////////////////////////// // construct schema std::vector<catalog::Column> columns; auto orig_schema = data_table.get()->GetSchema(); columns.push_back(orig_schema->GetColumn(0)); columns.push_back(orig_schema->GetColumn(0)); auto schema = new catalog::Schema(columns); // direct map planner::ProjectInfo::DirectMap direct_map = std::make_pair(0, std::make_pair(0, 0)); direct_map_list.push_back(direct_map); // target list auto const_val = new expression::ConstantValueExpression( ValueFactory::GetIntegerValue(20)); auto tuple_value_expr = expression::TupleValueFactory(0, 0); expression::AbstractExpression *expr = expression::OperatorFactory( EXPRESSION_TYPE_OPERATOR_PLUS, tuple_value_expr, const_val); planner::ProjectInfo::Target target = std::make_pair(1, expr); target_list.push_back(target); auto project_info = new planner::ProjectInfo(std::move(target_list), std::move(direct_map_list)); planner::ProjectionPlan node(project_info, schema); // Create and set up executor executor::ProjectionExecutor executor(&node, nullptr); executor.AddChild(&child_executor); RunTest(executor, 1); } } // namespace test } // namespace peloton
apache-2.0
OnPositive/aml
org.aml.typesystem/src/main/java/org/aml/typesystem/beans/PropertyViewImpl.java
5280
package org.aml.typesystem.beans; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.aml.typesystem.AbstractType; import org.aml.typesystem.meta.TypeInformation; import org.aml.typesystem.meta.facets.FacetDeclaration; import org.aml.typesystem.meta.restrictions.AdditionalProperties; import org.aml.typesystem.meta.restrictions.HasPropertyRestriction; import org.aml.typesystem.meta.restrictions.IMatchesProperty; import org.aml.typesystem.meta.restrictions.MapPropertyIs; import org.aml.typesystem.meta.restrictions.PropertyIs; /** * <p>PropertyViewImpl class.</p> * * @author kor * @version $Id: $Id */ public class PropertyViewImpl implements IPropertyView { protected AbstractType original; protected LinkedHashMap<String, PropertyBean> props = new LinkedHashMap<>(); protected HashMap<String, PropertyBean> allprops = new LinkedHashMap<>(); protected HashMap<String, PropertyBean> superProperties = new LinkedHashMap<>(); protected LinkedHashMap<String, PropertyBean> facets = new LinkedHashMap<>(); protected LinkedHashMap<String, PropertyBean> allFacets = new LinkedHashMap<>(); /** {@inheritDoc} */ @Override public List<IProperty> properties() { return new ArrayList<IProperty>(props.values()); } /** {@inheritDoc} */ @Override public List<IProperty> allProperties() { return new ArrayList<IProperty>(allprops.values()); } /** * <p>superProperties.</p> * * @return a {@link java.util.List} object. */ public List<IProperty> superProperties() { return new ArrayList<IProperty>(superProperties.values()); } /** {@inheritDoc} */ @Override public List<IProperty> facets() { return new ArrayList<IProperty>(facets.values()); } /** {@inheritDoc} */ @Override public List<IProperty> allFacets() { return new ArrayList<IProperty>(allFacets.values()); } /** * <p>Constructor for PropertyViewImpl.</p> * * @param t a {@link org.aml.typesystem.AbstractType} object. */ public PropertyViewImpl(AbstractType t) { this.original=t; buildProperties(t.meta(), allprops); for (AbstractType q:t.superTypes()){ buildProperties(q.meta(), superProperties); } buildProperties(t.declaredMeta(), props); buildFacetDeclarations(t.declaredMeta(), facets); buildFacetDeclarations(t.meta(), allFacets); } /** * <p>getDeclaredFacetsMap.</p> * * @return a {@link java.util.Map} object. */ public Map<String,PropertyBean>getDeclaredFacetsMap(){ return facets; } /** * <p>getDeclaredPropertiesMap.</p> * * @return a {@link java.util.Map} object. */ public Map<String,PropertyBean>getDeclaredPropertiesMap(){ return props; } private void buildProperties(Set<TypeInformation> meta, HashMap<String, PropertyBean> props) { for (final TypeInformation t : meta) { if (t instanceof IMatchesProperty) { registerPropertyBean(props, t); } else if (t instanceof HasPropertyRestriction) { updatePropertyBeanToMarkRequired(props, t); } } } private void buildFacetDeclarations(final Set<TypeInformation> declaredMeta, final HashMap<String, PropertyBean> facets) { for (final TypeInformation z : declaredMeta) { if (z instanceof FacetDeclaration) { final FacetDeclaration d = (FacetDeclaration) z; final PropertyBean pbean = new PropertyBean(); pbean.required = true; pbean.id = d.getName(); pbean.type = d.getType(); facets.put(d.getName(), pbean); } } } private void registerPropertyBean(HashMap<String, PropertyBean> props, TypeInformation t) { final IMatchesProperty ps = (IMatchesProperty) t; PropertyBean value2 = props.get(ps.id()); if (value2 == null) { value2 = new PropertyBean(); value2.setDeclaredAt(t.ownerType()); } if (ps instanceof AdditionalProperties) { value2.additional = true; value2.required = true; } if (ps instanceof MapPropertyIs) { value2.isMap = true; value2.required = true; } if (ps instanceof PropertyIs) { PropertyIs m=(PropertyIs) ps; value2.positional=m.isPositional(); } value2.type = ps.range(); value2.id = ps.id(); props.put(ps.id(), value2); } private void updatePropertyBeanToMarkRequired(HashMap<String, PropertyBean> props, TypeInformation t) { final HasPropertyRestriction pr = (HasPropertyRestriction) t; PropertyBean value2 = props.get(pr.id()); if (value2 == null) { value2 = new PropertyBean(); value2.setDeclaredAt(t.ownerType()); } value2.id = pr.id(); value2.required = true; props.put(pr.id(), value2); } /** * <p>getXMLHints.</p> * * @return a {@link org.aml.typesystem.beans.XMLHints} object. */ public XMLHints getXMLHints() { return new XMLHints(null, this.original); } /** * <p>getProperty.</p> * * @param s a {@link java.lang.String} object. * @return a {@link org.aml.typesystem.beans.IProperty} object. */ public IProperty getProperty(String s) { return allprops.get(s); } @Override public IProperty property(String name) { return allprops.get(name); } @Override public List<IProperty> positionalProperties() { return this.properties().stream().filter(x->x.isPositional()).collect(Collectors.toList()); } }
apache-2.0
JeffWangGithub/JeffBaseLibrary
src/com/meilishuo/baselibrary/widget/BaseHolder.java
808
package com.meilishuo.baselibrary.widget; import android.view.View; /** * BaseHolder中封装了ListView需要显示的数据和每一个item条目中的所有view * @author Jeff * * @param <T> */ public abstract class BaseHolder<T> { public T mData; private View view; public BaseHolder(){ view = initView(); //用户自行进行设置View view.setTag(this); //将携带布局文件中控件的holder设置到View对象中 } public void setData(T data) { this.mData = data; refreshView(); } /** * 给条目设置数据 */ public abstract void refreshView(); public T getData(){ return mData; } public View getRootView(){ return view; } /** * 初始化条目的布局 * @return */ public abstract View initView(); }
apache-2.0
jdgwartney/vsphere-ws
java/JAXWS/samples/com/vmware/vim25/DvsTrafficRule.java
5148
package com.vmware.vim25; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for DvsTrafficRule complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="DvsTrafficRule"> * &lt;complexContent> * &lt;extension base="{urn:vim25}DynamicData"> * &lt;sequence> * &lt;element name="key" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="sequence" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="qualifier" type="{urn:vim25}DvsNetworkRuleQualifier" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="action" type="{urn:vim25}DvsNetworkRuleAction" minOccurs="0"/> * &lt;element name="direction" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DvsTrafficRule", propOrder = { "key", "description", "sequence", "qualifier", "action", "direction" }) public class DvsTrafficRule extends DynamicData { protected String key; protected String description; protected Integer sequence; protected List<DvsNetworkRuleQualifier> qualifier; protected DvsNetworkRuleAction action; protected String direction; /** * Gets the value of the key property. * * @return * possible object is * {@link String } * */ public String getKey() { return key; } /** * Sets the value of the key property. * * @param value * allowed object is * {@link String } * */ public void setKey(String value) { this.key = value; } /** * Gets the value of the description property. * * @return * possible object is * {@link String } * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } /** * Gets the value of the sequence property. * * @return * possible object is * {@link Integer } * */ public Integer getSequence() { return sequence; } /** * Sets the value of the sequence property. * * @param value * allowed object is * {@link Integer } * */ public void setSequence(Integer value) { this.sequence = value; } /** * Gets the value of the qualifier property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the qualifier property. * * <p> * For example, to add a new item, do as follows: * <pre> * getQualifier().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DvsNetworkRuleQualifier } * * */ public List<DvsNetworkRuleQualifier> getQualifier() { if (qualifier == null) { qualifier = new ArrayList<DvsNetworkRuleQualifier>(); } return this.qualifier; } /** * Gets the value of the action property. * * @return * possible object is * {@link DvsNetworkRuleAction } * */ public DvsNetworkRuleAction getAction() { return action; } /** * Sets the value of the action property. * * @param value * allowed object is * {@link DvsNetworkRuleAction } * */ public void setAction(DvsNetworkRuleAction value) { this.action = value; } /** * Gets the value of the direction property. * * @return * possible object is * {@link String } * */ public String getDirection() { return direction; } /** * Sets the value of the direction property. * * @param value * allowed object is * {@link String } * */ public void setDirection(String value) { this.direction = value; } }
apache-2.0
jecuendet/maven4openxava
dist/openxava/workspace/OpenXavaTest/gen-src-xava/org/openxava/test/model/IReceptionist.java
967
// File generated by OpenXava: Wed Sep 11 11:56:52 CEST 2013 // Archivo generado por OpenXava: Wed Sep 11 11:56:52 CEST 2013 // WARNING: NO EDIT // OJO: NO EDITAR // Component: Customer Java interface for aggregate/Interfaz java para Agregado: Receptionist package org.openxava.test.model; import java.math.*; import java.rmi.RemoteException; public interface IReceptionist extends org.openxava.model.IModel { // Properties/Propiedades public static final String PROPERTY_oid = "oid"; int getOid() throws RemoteException; public static final String PROPERTY_name = "name"; String getName() throws RemoteException; void setName(String name) throws RemoteException; // References/Referencias // DeliveryPlace : Reference/Referencia org.openxava.test.model.IDeliveryPlace getDeliveryPlace() throws RemoteException; void setDeliveryPlace(org.openxava.test.model.IDeliveryPlace newDeliveryPlace) throws RemoteException; // Methods }
apache-2.0
junkerm/specmate
bundles/specmate-migration-test/src/com/specmate/migration/test/severalattributesadded/testmodel/base/util/BaseAdapterFactory.java
7404
/** */ package com.specmate.migration.test.severalattributesadded.testmodel.base.util; import com.specmate.migration.test.severalattributesadded.testmodel.base.*; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * The <b>Adapter Factory</b> for the model. * It provides an adapter <code>createXXX</code> method for each class of the model. * <!-- end-user-doc --> * @see com.specmate.migration.test.severalattributesadded.testmodel.base.BasePackage * @generated */ public class BaseAdapterFactory extends AdapterFactoryImpl { /** * The cached model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static BasePackage modelPackage; /** * Creates an instance of the adapter factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BaseAdapterFactory() { if (modelPackage == null) { modelPackage = BasePackage.eINSTANCE; } } /** * Returns whether this factory is applicable for the type of the object. * <!-- begin-user-doc --> * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model. * <!-- end-user-doc --> * @return whether this factory is applicable for the type of the object. * @generated */ @Override public boolean isFactoryForType(Object object) { if (object == modelPackage) { return true; } if (object instanceof EObject) { return ((EObject)object).eClass().getEPackage() == modelPackage; } return false; } /** * The switch that delegates to the <code>createXXX</code> methods. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected BaseSwitch<Adapter> modelSwitch = new BaseSwitch<Adapter>() { @Override public Adapter caseIID(IID object) { return createIIDAdapter(); } @Override public Adapter caseINamed(INamed object) { return createINamedAdapter(); } @Override public Adapter caseIContentElement(IContentElement object) { return createIContentElementAdapter(); } @Override public Adapter caseIContainer(IContainer object) { return createIContainerAdapter(); } @Override public Adapter caseFolder(Folder object) { return createFolderAdapter(); } @Override public Adapter caseITestable(ITestable object) { return createITestableAdapter(); } @Override public Adapter caseIModifiable(IModifiable object) { return createIModifiableAdapter(); } @Override public Adapter defaultCase(EObject object) { return createEObjectAdapter(); } }; /** * Creates an adapter for the <code>target</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param target the object to adapt. * @return the adapter for the <code>target</code>. * @generated */ @Override public Adapter createAdapter(Notifier target) { return modelSwitch.doSwitch((EObject)target); } /** * Creates a new adapter for an object of class '{@link com.specmate.migration.test.severalattributesadded.testmodel.base.IID <em>IID</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see com.specmate.migration.test.severalattributesadded.testmodel.base.IID * @generated */ public Adapter createIIDAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link com.specmate.migration.test.severalattributesadded.testmodel.base.INamed <em>INamed</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see com.specmate.migration.test.severalattributesadded.testmodel.base.INamed * @generated */ public Adapter createINamedAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link com.specmate.migration.test.severalattributesadded.testmodel.base.IContentElement <em>IContent Element</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see com.specmate.migration.test.severalattributesadded.testmodel.base.IContentElement * @generated */ public Adapter createIContentElementAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link com.specmate.migration.test.severalattributesadded.testmodel.base.IContainer <em>IContainer</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see com.specmate.migration.test.severalattributesadded.testmodel.base.IContainer * @generated */ public Adapter createIContainerAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link com.specmate.migration.test.severalattributesadded.testmodel.base.Folder <em>Folder</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see com.specmate.migration.test.severalattributesadded.testmodel.base.Folder * @generated */ public Adapter createFolderAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link com.specmate.migration.test.severalattributesadded.testmodel.base.ITestable <em>ITestable</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see com.specmate.migration.test.severalattributesadded.testmodel.base.ITestable * @generated */ public Adapter createITestableAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link com.specmate.migration.test.severalattributesadded.testmodel.base.IModifiable <em>IModifiable</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see com.specmate.migration.test.severalattributesadded.testmodel.base.IModifiable * @generated */ public Adapter createIModifiableAdapter() { return null; } /** * Creates a new adapter for the default case. * <!-- begin-user-doc --> * This default implementation returns null. * <!-- end-user-doc --> * @return the new adapter. * @generated */ public Adapter createEObjectAdapter() { return null; } } //BaseAdapterFactory
apache-2.0
statisticsnorway/java-vtl
java-vtl-script/src/test/java/no/ssb/vtl/script/expressions/logic/OrExpressionTest.java
2593
package no.ssb.vtl.script.expressions.logic; /* * ========================LICENSE_START================================= * Java VTL * %% * Copyright (C) 2016 - 2017 Hadrien Kohl * %% * 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. * =========================LICENSE_END================================== */ import com.google.common.collect.ImmutableTable; import com.google.common.collect.Table; import no.ssb.vtl.model.VTLExpression; import no.ssb.vtl.model.VTLObject; import no.ssb.vtl.script.expressions.LiteralExpression; import org.assertj.core.api.JUnitSoftAssertions; import org.junit.Rule; import org.junit.Test; public class OrExpressionTest { private VTLExpression truthy= new LiteralExpression(VTLObject.of(true)); private VTLExpression falsy = new LiteralExpression(VTLObject.of(false)); private VTLExpression nully = new LiteralExpression(VTLObject.of((Boolean) null)); @Rule public JUnitSoftAssertions softly = new JUnitSoftAssertions(); @Test public void testTruth() throws Exception { ImmutableTable.Builder<VTLExpression, VTLExpression, VTLExpression> builder = ImmutableTable.builder(); builder.put(falsy, falsy, falsy); builder.put(falsy, truthy, truthy); builder.put(falsy, nully, nully); builder.put(truthy, falsy, truthy); builder.put(truthy, truthy,truthy); builder.put(truthy, nully, truthy); builder.put(nully, falsy, nully); builder.put(nully, truthy,truthy); builder.put(nully, nully, nully); for (Table.Cell<VTLExpression, VTLExpression, VTLExpression> test : builder.build().cellSet()) { VTLExpression left = test.getRowKey(); VTLExpression right = test.getColumnKey(); VTLObject expected = test.getValue().resolve(null); VTLExpression result = new OrExpression(left, right); softly.assertThat(expected.get()) .as("result of %s -> %s", result, result.resolve(null).get()) .isEqualTo(result.resolve(null).get()); } } }
apache-2.0
yelllowme/wanglin
app/src/main/java/com/wanglinkeji/wanglin/activity/ChoosedPhoto_SmallActivity.java
26444
package com.wanglinkeji.wanglin.activity; import android.app.Activity; import android.content.ContentResolver; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.download.ImageDownloader; import com.wanglinkeji.wanglin.R; import com.wanglinkeji.wanglin.adapter.GridViewAdapter_ChoosedPhotoSmall; import com.wanglinkeji.wanglin.adapter.ListViewAdapter_ChoosedPhoto_photoFloderList; import com.wanglinkeji.wanglin.model.PhotoModel; import com.wanglinkeji.wanglin.model.PhotofolderModel; import com.wanglinkeji.wanglin.util.OtherUtil; import com.wanglinkeji.wanglin.util.WangLinApplication; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; /** * Created by Administrator on 2016/9/6. * 图片选择器,小图列表Activity */ public class ChoosedPhoto_SmallActivity extends Activity implements View.OnClickListener { //用来控制GridView是否显示拍照栏的全局变量 public static boolean isShowTakePhoto = true; private ImageView imageView_cancle, imageView_popwindowTakePhoto_cancle, imageView_popwindowTakePhoto_photo; private TextView textView_finish, textView_showAlbum, textView_preview, textView_popwindowTakePhoto_finish; private LinearLayout layout_bottom, layout_title, layout_folderList, layout_popwindowTakePhoto_title; private GridView gridView_photos; private ListView listView_photoFolder; private ListViewAdapter_ChoosedPhoto_photoFloderList listViewAdapter_choosedPhoto_photoFloderList; private GridViewAdapter_ChoosedPhotoSmall gridViewAdapter_choosedPhotoSmall; private PopupWindow popupWindow_takePhoto; private View rootView, popwindowTakePhoto_contentView; //相册layout是否显示 private boolean isShowAlbum = false; //拍照后popwindow是否显示title private boolean isShowPopwindowTakePhotoTitle = true; //显示图片的配置 private DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.shape_rectangle_black_lighter_noborder_nocorner) .showImageOnFail(R.drawable.shape_rectangle_gray_noborder_nocorner) .cacheInMemory(true) .cacheOnDisk(true) .bitmapConfig(Bitmap.Config.RGB_565) .build(); private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ //保证相册List消失动画后,相册layout才GONE case -666:{ layout_folderList.setVisibility(View.GONE); break; } //拍照后的popwindow标题栏消失 case -777:{ layout_popwindowTakePhoto_title.setVisibility(View.GONE); } default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.layout_activity_choosed_photo_small); getallPhoto(); //刚开始时,显示的就是所有图片 PhotoModel.list_showPhotos = PhotoModel.list_allPhotos; getPhotoFloder(); viewInit(); setViewAftergetPhoto(); } @Override protected void onResume() { super.onResume(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode){ //从浏览大图返回 case OtherUtil.REQUEST_CODE_CHOOSED_PHOTO_SMALL_TO_BIG:{ if (resultCode == RESULT_OK){ //判断返回时按下的哪一个按钮,cancle还是ensure if (data.getStringExtra("fromWhat").equals("cancle")) { //设置numOfChoosed的显示数量 setViewAftergetPhoto(); //根据allPhoto,刷新showPhoto for (int i = 0; i < PhotoModel.list_allPhotos.size(); i++) { for (int j = 0; j < PhotoModel.list_showPhotos.size(); j++) { if (PhotoModel.list_showPhotos.get(j).getPath().equals(PhotoModel.list_allPhotos.get(i).getPath())) { PhotoModel.list_showPhotos.get(j).setChoosed(PhotoModel.list_allPhotos.get(i).isChoosed()); } } } //手动刷新GridView的选中图标,就不用notify GridView //如果GridView没有显示拍照栏 if (isShowTakePhoto == false){ for (int i = 0; i < PhotoModel.list_showPhotos.size(); i++){ if (i >= gridView_photos.getFirstVisiblePosition() && i < gridView_photos.getFirstVisiblePosition() + gridView_photos.getChildCount()){ if (PhotoModel.list_showPhotos.get(i).isChoosed() == true ){ View view = (View)gridView_photos.getChildAt(i - gridView_photos.getFirstVisiblePosition()); ImageView image = (ImageView)view.findViewById(R.id.imageview_choosedPhotoSmalItem_isChoosed); image.setImageResource(R.mipmap.photo_choosed_icon); }else if(PhotoModel.list_showPhotos.get(i).isChoosed() == false){ View view = (View)gridView_photos.getChildAt(i - gridView_photos.getFirstVisiblePosition()); ImageView image = (ImageView)view.findViewById(R.id.imageview_choosedPhotoSmalItem_isChoosed); image.setImageResource(R.mipmap.photo_notchoosed_icon); } } } //如果GridView显示了拍照栏 }else { for (int gridview_position = 0; gridview_position < PhotoModel.list_showPhotos.size() + 1; gridview_position++){ if (gridview_position > 0 && gridview_position >= gridView_photos.getFirstVisiblePosition() && gridview_position < gridView_photos.getFirstVisiblePosition() + gridView_photos.getChildCount()){ int photo_position = gridview_position - 1; if (PhotoModel.list_showPhotos.get(photo_position).isChoosed() == true ){ View view = (View)gridView_photos.getChildAt(gridview_position - gridView_photos.getFirstVisiblePosition()); ImageView image = (ImageView)view.findViewById(R.id.imageview_choosedPhotoSmalItem_isChoosed); image.setImageResource(R.mipmap.photo_choosed_icon); }else if(PhotoModel.list_showPhotos.get(photo_position).isChoosed() == false){ View view = (View)gridView_photos.getChildAt(gridview_position - gridView_photos.getFirstVisiblePosition()); ImageView image = (ImageView)view.findViewById(R.id.imageview_choosedPhotoSmalItem_isChoosed); image.setImageResource(R.mipmap.photo_notchoosed_icon); } } } } //如果是点击的确定,则直接finish }else if(data.getStringExtra("fromWhat").equals("ensure")){ finishBtnEvent(); } } break; } //从拍照返回 case OtherUtil.REQUEST_CODE_CHOODEDPHOTO_SMALL_TO_TAKE_PHOTO:{ File file = new File(PhotoModel.takePhoto_path); if (file.length() > 0){ OtherUtil.requestScanFile(this, file); //用ImageLoader显示照片 ImageLoader imageLoader = ImageLoader.getInstance(); imageLoader.displayImage(ImageDownloader.Scheme.FILE.wrap(PhotoModel.takePhoto_path), imageView_popwindowTakePhoto_photo,options); popupWindow_takePhoto.showAtLocation(rootView, Gravity.CENTER, 0, 0); } break; } default: break; } } @Override public void onClick(View view) { switch (view.getId()){ //返回按钮 case R.id.imageview_choosedPhotoSmall_cancle:{ ChoosedPhoto_SmallActivity.this.finish(); break; } //完成按钮 case R.id.textview_choosedPhotoSmall_finish:{ finishBtnEvent(); break; } //打开相册按钮 case R.id.textview_choosedPhotoSmall_showAlbum:{ if (isShowAlbum == true){ folderListGoneAnim(); }else { folderListVisiableAnim(); } break; } //预览按钮 case R.id.textview_choosedPhotoSmall_preview:{ if (PhotoModel.getNumChoosedPhoto(PhotoModel.list_allPhotos) > 0) { ArrayList<PhotoModel> photos = new ArrayList<PhotoModel>(); for (int i = 0; i < PhotoModel.list_allPhotos.size(); i++) { if (PhotoModel.list_allPhotos.get(i).isChoosed() == true) { PhotoModel photo = new PhotoModel(); photo.setPath(PhotoModel.list_allPhotos.get(i).getPath()); photo.setChoosed(PhotoModel.list_allPhotos.get(i).isChoosed()); photos.add(photo); } } PhotoModel.list_bigPhotos = photos; Intent intent = new Intent(ChoosedPhoto_SmallActivity.this, ChoosedPhoto_BigActivity.class); startActivityForResult(intent, OtherUtil.REQUEST_CODE_CHOOSED_PHOTO_SMALL_TO_BIG); } break; } //相册layout case R.id.layout_choosedPhoto_Small_folderList:{ folderListGoneAnim(); break; } //拍照后的popwindow返回按钮 case R.id.imageview_choosedPhotoSmall_popwindowTakePhoto_cancle:{ popupWindow_takePhoto.dismiss(); break; } //拍照后的popwindow完成按钮 case R.id.textview_choosedPhotoSmall_popwindowTakePhoto_finish:{ PhotoModel photoModel = new PhotoModel(); photoModel.setChoosed(true); photoModel.setPath(PhotoModel.takePhoto_path); PhotoModel.list_choosedPhotos.add(photoModel); break; } //拍照后的popwindow照片 case R.id.imageview_choosedPhotoSmall_popwindowTakePhoto_photo:{ if (isShowPopwindowTakePhotoTitle == true){ isShowPopwindowTakePhotoTitle = false; layout_popwindowTakePhoto_title.startAnimation(OtherUtil.get_Translate_Anim(400, 0, 0, 0, -WangLinApplication.screen_Height/12.5f)); handler.sendEmptyMessageDelayed(-777, 400); }else { isShowPopwindowTakePhotoTitle = true; layout_popwindowTakePhoto_title.setVisibility(View.VISIBLE); layout_popwindowTakePhoto_title.startAnimation(OtherUtil.get_Translate_Anim(400, 0, 0, -WangLinApplication.screen_Height/12.5f, 0)); } break; } default: break; } } private void viewInit(){ //默认显示全部图片时要显示“拍照”栏 isShowTakePhoto = true; /** * 相片小图界面控件 */ imageView_cancle = (ImageView)findViewById(R.id.imageview_choosedPhotoSmall_cancle); imageView_cancle.setOnClickListener(this); textView_finish = (TextView)findViewById(R.id.textview_choosedPhotoSmall_finish); textView_finish.setOnClickListener(this); textView_finish.setText(PhotoModel.finishText); textView_showAlbum = (TextView)findViewById(R.id.textview_choosedPhotoSmall_showAlbum); textView_showAlbum.setOnClickListener(this); textView_preview = (TextView)findViewById(R.id.textview_choosedPhotoSmall_preview); textView_preview.setOnClickListener(this); layout_bottom = (LinearLayout)findViewById(R.id.layout_choosedPhoto_Small_bottom); layout_bottom.setOnClickListener(this); OtherUtil.setViewLayoutParams(layout_bottom, false, 12.5f, 1); layout_title = (LinearLayout)findViewById(R.id.layout_choosedPhoto_Small_title); OtherUtil.setViewLayoutParams(layout_title, false, 12.5f, 1); gridView_photos = (GridView)findViewById(R.id.gridview_choosedPhoto_small); gridViewAdapter_choosedPhotoSmall = new GridViewAdapter_ChoosedPhotoSmall(PhotoModel.list_showPhotos, ChoosedPhoto_SmallActivity.this, R.layout.layout_gridview_item_choosed_photo_small, textView_finish, textView_preview); gridView_photos.setAdapter(gridViewAdapter_choosedPhotoSmall); /** * 相片相册选择界面 */ layout_folderList = (LinearLayout)findViewById(R.id.layout_choosedPhoto_Small_folderList); layout_folderList.setOnClickListener(this); OtherUtil.setViewLayoutParams(layout_folderList, false, 1.19f, 1); listView_photoFolder = (ListView)findViewById(R.id.listview_choosedPhoto_photoFloderList); OtherUtil.setViewLayoutParams(listView_photoFolder, false, 1.5f, 1); listViewAdapter_choosedPhoto_photoFloderList = new ListViewAdapter_ChoosedPhoto_photoFloderList(PhotofolderModel.list_photoFolder, ChoosedPhoto_SmallActivity.this, R.layout.layout_listview_item_choosed_photo_folder_list); listView_photoFolder.setAdapter(listViewAdapter_choosedPhoto_photoFloderList); listView_photoFolder.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { int clickPosition = (new Long(id)).intValue(); textView_showAlbum.setText(PhotofolderModel.list_photoFolder.get(clickPosition).getName()); for (int i = 0; i < PhotofolderModel.list_photoFolder.size(); i++){ if (i == clickPosition){ PhotofolderModel.list_photoFolder.get(i).setChoosed(true); }else { PhotofolderModel.list_photoFolder.get(i).setChoosed(false); } } listViewAdapter_choosedPhoto_photoFloderList.notifyDataSetChanged(); if (clickPosition == 0){ //只有在显示全部图片的时候才会有拍照栏 isShowTakePhoto = true; PhotoModel.list_showPhotos = PhotoModel.list_allPhotos; gridViewAdapter_choosedPhotoSmall = new GridViewAdapter_ChoosedPhotoSmall(PhotoModel.list_showPhotos, ChoosedPhoto_SmallActivity.this, R.layout.layout_gridview_item_choosed_photo_small, textView_finish, textView_preview); gridView_photos.setAdapter(gridViewAdapter_choosedPhotoSmall); }else { //只有在显示全部图片的时候才会有拍照栏 isShowTakePhoto = false; PhotoModel.list_showPhotos = OtherUtil.getPicturesByFolderPath(PhotofolderModel.list_photoFolder.get(clickPosition).getDir()); gridViewAdapter_choosedPhotoSmall = new GridViewAdapter_ChoosedPhotoSmall(PhotoModel.list_showPhotos, ChoosedPhoto_SmallActivity.this, R.layout.layout_gridview_item_choosed_photo_small, textView_finish, textView_preview); gridView_photos.setAdapter(gridViewAdapter_choosedPhotoSmall); } folderListGoneAnim(); } }); /** * 拍照后的图片显示Popwindow */ rootView = LayoutInflater.from(ChoosedPhoto_SmallActivity.this).inflate(R.layout.layout_activity_choosed_photo_small, null); popwindowTakePhoto_contentView = LayoutInflater.from(ChoosedPhoto_SmallActivity.this).inflate(R.layout.layout_popwindow_takephoto_showphoto, null); popupWindow_takePhoto = new PopupWindow(popwindowTakePhoto_contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true); imageView_popwindowTakePhoto_cancle = (ImageView)popwindowTakePhoto_contentView.findViewById(R.id.imageview_choosedPhotoSmall_popwindowTakePhoto_cancle); imageView_popwindowTakePhoto_cancle.setOnClickListener(this); imageView_popwindowTakePhoto_photo = (ImageView)popwindowTakePhoto_contentView.findViewById(R.id.imageview_choosedPhotoSmall_popwindowTakePhoto_photo); imageView_popwindowTakePhoto_photo.setOnClickListener(this); textView_popwindowTakePhoto_finish = (TextView)popwindowTakePhoto_contentView.findViewById(R.id.textview_choosedPhotoSmall_popwindowTakePhoto_finish); textView_popwindowTakePhoto_finish.setOnClickListener(this); layout_popwindowTakePhoto_title = (LinearLayout)popwindowTakePhoto_contentView.findViewById(R.id.layout_choosedPhotoSmall_popwindowTakePhoto_title); } private void finishBtnEvent(){ List<PhotoModel> list_photos = new ArrayList<>(); for (int i = 0; i < PhotoModel.list_allPhotos.size(); i++){ if (PhotoModel.list_allPhotos.get(i).isChoosed() == true){ PhotoModel photoModel = new PhotoModel(); photoModel.setChoosed(true); photoModel.setPath(PhotoModel.list_allPhotos.get(i).getPath()); list_photos.add(photoModel); } } PhotoModel.list_choosedPhotos = list_photos; setResult(RESULT_OK); ChoosedPhoto_SmallActivity.this.finish(); } //在扫描图片完成后设置控件 private void setViewAftergetPhoto(){ if (PhotoModel.getNumChoosedPhoto(PhotoModel.list_allPhotos) == 0){ //完成按钮 textView_finish.setTextColor(0X99FFFFFF); textView_finish.setBackgroundResource(R.drawable.shape_rectangle_blue_lighter_er_noborder_allcorner); textView_finish.setText(PhotoModel.finishText); textView_finish.setEnabled(false); //预览按钮 textView_preview.setText("预览"); textView_preview.setTextColor(0X99FFFFFF); textView_preview.setEnabled(false); }else { //完成按钮 textView_finish.setTextColor(0XFFFFFFFF); textView_finish.setBackgroundResource(R.drawable.shape_rectangle_blue_lighter_noborder_allcorner); String text = "(" + PhotoModel.getNumChoosedPhoto(PhotoModel.list_allPhotos) + "/" + PhotoModel.photoCount + ")"; textView_finish.setText(PhotoModel.finishText + text); textView_finish.setEnabled(true); //预览按钮 textView_preview.setText("预览" + text); textView_preview.setTextColor(0XFFFFFFFF); textView_preview.setEnabled(true); } } //相册layout消失动画+属性设置 private void folderListGoneAnim(){ isShowAlbum = false; listView_photoFolder.startAnimation(OtherUtil.get_Translate_Anim(300, 0, 0, 0, WangLinApplication.screen_Height/1.2f)); handler.sendEmptyMessageDelayed(-666, 300); } //相册layout消失动画+属性设置 private void folderListVisiableAnim(){ isShowAlbum = true; layout_folderList.setVisibility(View.VISIBLE); listView_photoFolder.startAnimation(OtherUtil.get_Translate_Anim(300, 0, 0, WangLinApplication.screen_Height/1.2f, 0)); } //扫描本地相册,获取所有图片 private void getallPhoto(){ List<PhotoModel> list_photos = new ArrayList<PhotoModel>(); if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show(); return; } Uri imageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; ContentResolver contentResolver = ChoosedPhoto_SmallActivity.this.getContentResolver(); Cursor cursor = contentResolver.query(imageUri, null, MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?", new String[]{"image/jpeg", "image/png"}, MediaStore.Images.Media.DATE_MODIFIED); while (cursor.moveToNext()){ String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); PhotoModel photo = new PhotoModel(); photo.setPath(path); photo.setChoosed(false); list_photos.add(photo); } if (!cursor.isClosed()){ cursor.close(); } Collections.reverse(list_photos); PhotoModel.list_allPhotos = list_photos; for (int i = 0; i < PhotoModel.list_choosedPhotos.size(); i++){ for (int j = 0; j < PhotoModel.list_allPhotos.size(); j++){ if (PhotoModel.list_allPhotos.get(j).getPath().equals(PhotoModel.list_choosedPhotos.get(i).getPath())){ PhotoModel.list_allPhotos.get(j).setChoosed(true); } } } } //扫描SDcard获取所有图片文件夹 private void getPhotoFloder(){ PhotofolderModel.list_photoFolder = new ArrayList<>(); if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show(); return; } String firstImagePath_all = null; HashSet<String> mDirPaths = new HashSet<String>(); int totalCount = 0; Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; ContentResolver mContentResolver = ChoosedPhoto_SmallActivity.this.getContentResolver(); // 只查询jpeg和png的图片 Cursor mCursor = mContentResolver.query(mImageUri, null, MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?", new String[] { "image/jpeg", "image/png" }, MediaStore.Images.Media.DATE_MODIFIED); PhotofolderModel allPhotoFloder = new PhotofolderModel(); while (mCursor.moveToNext()) { // 获取图片的路径 String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA)); // 拿到第一张图片的路径 if (firstImagePath_all == null){ firstImagePath_all = path; } // 获取该图片的父路径名 File parentFile = new File(path).getParentFile(); if (parentFile == null){ continue; } String dirPath = parentFile.getAbsolutePath(); PhotofolderModel photoFloder = null; // 利用一个HashSet防止多次扫描同一个文件夹(不加这个判断,图片多起来还是相当恐怖的~~) if (mDirPaths.contains(dirPath)) { continue; } else { mDirPaths.add(dirPath); // 初始化imageFloder photoFloder = new PhotofolderModel(); photoFloder.setDir(dirPath); photoFloder.setFirstImagePath(path); } int picSize = parentFile.list(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { if (filename.endsWith(".jpg") || filename.endsWith(".png") || filename.endsWith(".jpeg")){ return true; } return false; } }).length; totalCount += picSize; photoFloder.setCount(picSize); photoFloder.setCount_choosed(0); photoFloder.setChoosed(false); PhotofolderModel.list_photoFolder.add(photoFloder); } //将相册倒序 Collections.reverse(PhotofolderModel.list_photoFolder); //加入所有图片选项 allPhotoFloder.setCount(totalCount); allPhotoFloder.setFirstImagePath(firstImagePath_all); allPhotoFloder.setDir("/所有图片"); allPhotoFloder.setCount_choosed(0); allPhotoFloder.setChoosed(true); PhotofolderModel.list_photoFolder.add(0,allPhotoFloder); mCursor.close(); // 扫描完成,辅助的HashSet也就可以释放内存了 mDirPaths = null; } }
apache-2.0
udoprog/heroic
aggregation/simple/src/main/java/com/spotify/heroic/aggregation/simple/CountUniqueInstance.java
1719
/* * Copyright (c) 2015 Spotify AB. * * 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.spotify.heroic.aggregation.simple; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.spotify.heroic.aggregation.BucketAggregationInstance; import com.spotify.heroic.metric.MetricType; import com.spotify.heroic.metric.Point; public class CountUniqueInstance extends BucketAggregationInstance<CountUniqueBucket> { @JsonCreator public CountUniqueInstance(@JsonProperty("size") final long size, @JsonProperty("extent") final long extent) { super(size, extent, ALL_TYPES, MetricType.POINT); } @Override protected CountUniqueBucket buildBucket(long timestamp) { return new CountUniqueBucket(timestamp); } @Override protected Point build(CountUniqueBucket bucket) { return new Point(bucket.timestamp(), bucket.count()); } }
apache-2.0
qjafcunuas/jbromo
jbromo-webapp/jbromo-webapp-jsf/jbromo-webapp-jsf-sample/src/main/java/org/jbromo/webapp/jsf/sample/view/layer/table/rowclick/RowClickDataTableModel.java
2282
/*- * Copyright (C) 2013-2014 The JBromo Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jbromo.webapp.jsf.sample.view.layer.table.rowclick; import javax.inject.Named; import org.apache.myfaces.extensions.cdi.core.api.scope.conversation.ViewAccessScoped; import org.jbromo.common.dto.IOrderBy; import org.jbromo.common.dto.IOrderBy.SORT; import org.jbromo.webapp.jsf.component.datatable.AbstractDataTableModel; import org.jbromo.webapp.jsf.component.datatable.DataTableSortMultiColumn; import org.jbromo.webapp.jsf.sample.view.layer.service.DataRow; import org.jbromo.webapp.jsf.sample.view.layer.service.DataRowOrderBy; /** * Define the simple table model. * @author qjafcunuas */ @Named @ViewAccessScoped public class RowClickDataTableModel extends AbstractDataTableModel<DataRow> { /** * serial version UID. */ private static final long serialVersionUID = -7947750742835660437L; /** * Default constructor. */ public RowClickDataTableModel() { super(); setSortColumns(new DataTableSortMultiColumn()); } @Override protected IOrderBy getOrderBy(final String columnRef, final SORT sort) { return DataRowOrderBy.getOrderBy(columnRef, sort); } }
apache-2.0
BartoszJarocki/boilerpipe-android
src/main/java/mf/org/apache/wml/dom/WMLImgElementImpl.java
3267
/* * 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 mf.org.apache.wml.dom; import mf.org.apache.wml.WMLImgElement; /** * @xerces.internal * @version $Id: WMLImgElementImpl.java 661560 2008-05-30 03:22:25Z mrglavas $ * @author <a href="mailto:david@topware.com.tw">David Li</a> */ public class WMLImgElementImpl extends WMLElementImpl implements WMLImgElement { private static final long serialVersionUID = -500092034867051550L; public WMLImgElementImpl (WMLDocumentImpl owner, String tagName) { super( owner, tagName); } public void setWidth(String newValue) { setAttribute("width", newValue); } public String getWidth() { return getAttribute("width"); } public void setClassName(String newValue) { setAttribute("class", newValue); } public String getClassName() { return getAttribute("class"); } public void setXmlLang(String newValue) { setAttribute("xml:lang", newValue); } public String getXmlLang() { return getAttribute("xml:lang"); } public void setLocalSrc(String newValue) { setAttribute("localsrc", newValue); } public String getLocalSrc() { return getAttribute("localsrc"); } public void setHeight(String newValue) { setAttribute("height", newValue); } public String getHeight() { return getAttribute("height"); } public void setAlign(String newValue) { setAttribute("align", newValue); } public String getAlign() { return getAttribute("align"); } public void setVspace(String newValue) { setAttribute("vspace", newValue); } public String getVspace() { return getAttribute("vspace"); } public void setAlt(String newValue) { setAttribute("alt", newValue); } public String getAlt() { return getAttribute("alt"); } public void setId(String newValue) { setAttribute("id", newValue); } public String getId() { return getAttribute("id"); } public void setHspace(String newValue) { setAttribute("hspace", newValue); } public String getHspace() { return getAttribute("hspace"); } public void setSrc(String newValue) { setAttribute("src", newValue); } public String getSrc() { return getAttribute("src"); } }
apache-2.0
capravictoriae/Space-Mission-Design-and-Operations-EE585x-MOOC-Python-
Unit2/P2.4.4_A.py
203
earth_mu = 3.986e14 earth_r = 6.378e6 # m speed = 7.76 * 1000 # m/s # V = sqrt(mu/r) => V^2 = mu/r => V^2/mu = 1/r # mu / V^2 = r dist = earth_mu / (speed**2) dist = dist - earth_r print(dist/1000)
apache-2.0
lefou/asciidoctorj
asciidoctorj-core/src/main/java/org/asciidoctor/extension/PreprocessorReader.java
410
package org.asciidoctor.extension; import java.util.Map; import org.asciidoctor.ast.Document; public interface PreprocessorReader extends Reader { void push_include(String data, String file, String path, int lineNumber, Map<String, Object> attributes); /** * * @return * @deprecated Please use {@link #getDocument()} */ Document document(); Document getDocument(); }
apache-2.0
googlevr/seurat
seurat/tiler/selection/cost_calculator_test.cc
2532
/* Copyright 2017 Google 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. */ #include "seurat/tiler/selection/cost_calculator.h" #include <array> #include <random> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "seurat/tiler/selection/selection_problem.h" #include "seurat/tiler/selection/selection_util.h" namespace seurat { namespace tiler { namespace selection { namespace { TEST(CostCalculatorTest, TestComputeSolutionCost) { std::mt19937 random; std::uniform_real_distribution<float> cost(0.1f, 10.0f); std::uniform_real_distribution<float> weight0(1.0f, 10.0f); std::uniform_real_distribution<float> weight1(20.0f, 50.0f); ItemSet items(2); const int kNumItems = 10; for (int i = 0; i < kNumItems; ++i) { items.AppendItem(cost(random), {{{0, weight0(random)}, {1, weight1(random)}}}); } std::vector<double> capacity = {{10.0 * 10, 50.0 * 10}}; SelectionProblem problem; problem.items = &items; problem.capacity = capacity; // Test with various thread counts. for (int thread_count : std::array<int, 11>{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20}}) { CostCalculator cost_calculator(thread_count); std::vector<int> selected_items = {0, 1, 3, 6, 9}; double primal_cost; double dual_cost; std::vector<double> multipliers = {30.0f, 42.0f}; std::vector<double> total_weight(2); cost_calculator.ComputeSolutionCost(problem, multipliers, selected_items, &primal_cost, &dual_cost, absl::MakeSpan(total_weight)); EXPECT_EQ(primal_cost, ComputeTotalCost(items, selected_items)); EXPECT_EQ(dual_cost, ComputeDualCost(problem, multipliers, total_weight, primal_cost)); std::vector<double> total_weight_2(2); ComputeTotalWeight(items, selected_items, absl::MakeSpan(total_weight_2)); EXPECT_EQ(total_weight_2, total_weight); } } } // namespace } // namespace selection } // namespace tiler } // namespace seurat
apache-2.0
fuitsec/fuitsec
src/app/app-projectlist.js
1542
fuitsec.app.projectlist = { vue: null, setSort: function (key) { var self = this; console.log('listSetSort', key, '|', self.vue.activeProject.state.listsortkey, self.vue.activeProject.state.listsortdir); if (self.vue.activeProject.state.listsortkey === key) { self.vue.activeProject.state.listsortdir = (self.vue.activeProject.state.listsortdir === 'desc') ? 'asc' : 'desc'; } else { self.vue.activeProject.state.listsortdir = 'desc'; } self.vue.activeProject.state.listsortkey = key; }, itemDelete: function(item){ var self = this; var idx = self.vue.items.indexOf(item); console.log('listItemDelete', item, i); if (window.confirm('Delete item?')) { self.vue.items.splice(idx, 1); self.vue.activeContent = fuitsec.bootstrap.defaults.activeContent; fuitsec.services.repository.deleteItem({ id: item.id, success: function (itemContent) { self.vue.activeProject.itemcount--; self.vue.clearActiveContent(); fuitsec.services.repository.deleteProjectItemHeader({ id: item.id, success: function() { self.vue.persistLibrary(); } }); //self.vue.persistProjectItemHeaders(); } }); } } };
apache-2.0
callistaenterprise/blog-non-blocking-rest-service-with-spring-mvc
spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/routingslip/nonblocking/statemachine/AsynchProcessor.java
1475
package se.callista.springmvc.asynch.pattern.routingslip.nonblocking.statemachine; import com.ning.http.client.AsyncHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import se.callista.springmvc.asynch.common.statemachine.Processor; import se.callista.springmvc.asynch.common.statemachine.State; import se.callista.springmvc.asynch.common.statemachine.StateMachine; import java.io.IOException; /** * Created by magnus on 15/05/14. */ @Component public class AsynchProcessor implements Processor { private static final Logger LOG = LoggerFactory.getLogger(AsynchProcessor.class); @Autowired private StateMachine stateMachine; private static final AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); @Value("${sp.non_blocking.url}") private String SP_NON_BLOCKING_URL; @Override public void process(State state) { try { int sleeptimeMs = 100 * (state.getProcessingStepNo()); String url = SP_NON_BLOCKING_URL + "?minMs=" + sleeptimeMs + "&maxMs=" + sleeptimeMs; LOG.debug("Launch asynch call"); asyncHttpClient.prepareGet(url).execute(new AsynchProcessorCallback(stateMachine, state)); } catch (IOException e) { throw new RuntimeException(e); } } }
apache-2.0
ibm-contribs/kubernetes
pkg/registry/core/podtemplate/strategy.go
3416
/* Copyright 2014 The Kubernetes 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 podtemplate import ( "fmt" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation/field" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/fields" genericapirequest "k8s.io/kubernetes/pkg/genericapiserver/api/request" "k8s.io/kubernetes/pkg/storage" ) // podTemplateStrategy implements behavior for PodTemplates type podTemplateStrategy struct { runtime.ObjectTyper api.NameGenerator } // Strategy is the default logic that applies when creating and updating PodTemplate // objects via the REST API. var Strategy = podTemplateStrategy{api.Scheme, api.SimpleNameGenerator} // NamespaceScoped is true for pod templates. func (podTemplateStrategy) NamespaceScoped() bool { return true } // PrepareForCreate clears fields that are not allowed to be set by end users on creation. func (podTemplateStrategy) PrepareForCreate(ctx genericapirequest.Context, obj runtime.Object) { _ = obj.(*api.PodTemplate) } // Validate validates a new pod template. func (podTemplateStrategy) Validate(ctx genericapirequest.Context, obj runtime.Object) field.ErrorList { pod := obj.(*api.PodTemplate) return validation.ValidatePodTemplate(pod) } // Canonicalize normalizes the object after validation. func (podTemplateStrategy) Canonicalize(obj runtime.Object) { } // AllowCreateOnUpdate is false for pod templates. func (podTemplateStrategy) AllowCreateOnUpdate() bool { return false } // PrepareForUpdate clears fields that are not allowed to be set by end users on update. func (podTemplateStrategy) PrepareForUpdate(ctx genericapirequest.Context, obj, old runtime.Object) { _ = obj.(*api.PodTemplate) } // ValidateUpdate is the default update validation for an end user. func (podTemplateStrategy) ValidateUpdate(ctx genericapirequest.Context, obj, old runtime.Object) field.ErrorList { return validation.ValidatePodTemplateUpdate(obj.(*api.PodTemplate), old.(*api.PodTemplate)) } func (podTemplateStrategy) AllowUnconditionalUpdate() bool { return true } func (podTemplateStrategy) Export(ctx genericapirequest.Context, obj runtime.Object, exact bool) error { // Do nothing return nil } func PodTemplateToSelectableFields(podTemplate *api.PodTemplate) fields.Set { return nil } // GetAttrs returns labels and fields of a given object for filtering purposes. func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) { pt, ok := obj.(*api.PodTemplate) if !ok { return nil, nil, fmt.Errorf("given object is not a pod template.") } return labels.Set(pt.ObjectMeta.Labels), PodTemplateToSelectableFields(pt), nil } func MatchPodTemplate(label labels.Selector, field fields.Selector) storage.SelectionPredicate { return storage.SelectionPredicate{ Label: label, Field: field, GetAttrs: GetAttrs, } }
apache-2.0
material-components/material-components-android
catalog/java/io/material/catalog/topappbar/TopAppBarScrollingDemoFragment.java
2589
/* * Copyright 2017 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 * * 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 io.material.catalog.topappbar; import io.material.catalog.R; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import androidx.annotation.Nullable; import com.google.android.material.appbar.AppBarLayout; import com.google.android.material.shape.MaterialShapeDrawable; import io.material.catalog.feature.DemoFragment; import io.material.catalog.feature.DemoUtils; /** A fragment that displays a scrolling Top App Bar demo for the Catalog app. */ public class TopAppBarScrollingDemoFragment extends DemoFragment { @Override public void onCreate(@Nullable Bundle bundle) { super.onCreate(bundle); setHasOptionsMenu(true); } @Override public View onCreateDemoView( LayoutInflater layoutInflater, @Nullable ViewGroup viewGroup, @Nullable Bundle bundle) { View view = layoutInflater.inflate(R.layout.cat_topappbar_scrolling_fragment, viewGroup, false); Toolbar toolbar = view.findViewById(R.id.toolbar); AppCompatActivity activity = (AppCompatActivity) getActivity(); activity.setSupportActionBar(toolbar); AppBarLayout appBarLayout = view.findViewById(R.id.appbarlayout); appBarLayout.setStatusBarForeground( MaterialShapeDrawable.createWithElevationOverlay(requireContext())); return view; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) { menuInflater.inflate(R.menu.cat_topappbar_menu, menu); super.onCreateOptionsMenu(menu, menuInflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { return DemoUtils.showSnackbar(getActivity(), item) || super.onOptionsItemSelected(item); } @Override public boolean shouldShowDefaultDemoActionBar() { return false; } }
apache-2.0
rostam/gradoop
gradoop-flink/src/main/java/org/gradoop/flink/model/impl/functions/graphcontainment/InAnyGraph.java
1526
/* * Copyright © 2014 - 2019 Leipzig University (Database Research Group) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradoop.flink.model.impl.functions.graphcontainment; import org.apache.flink.api.java.functions.FunctionAnnotation; import org.gradoop.common.model.impl.id.GradoopIdSet; import org.gradoop.common.model.impl.pojo.GraphElement; import org.gradoop.flink.model.impl.functions.filters.CombinableFilter; /** * True, if an element is contained in any of a set of given graphs. * * @param <GE> element type */ @FunctionAnnotation.ReadFields("graphIds") public class InAnyGraph<GE extends GraphElement> implements CombinableFilter<GE> { /** * graph ids */ private final GradoopIdSet graphIds; /** * constructor * @param graphIds graph ids */ public InAnyGraph(GradoopIdSet graphIds) { this.graphIds = graphIds; } @Override public boolean filter(GE element) throws Exception { return element.getGraphIds().containsAny(this.graphIds); } }
apache-2.0
jeltz/rust-debian-package
src/librustdoc/sort_item_type_pass.rs
2229
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Sorts items by type use doc; use pass::Pass; use sort_pass; pub fn mk_pass() -> Pass { fn by_score(item1: &doc::ItemTag, item2: &doc::ItemTag) -> bool { fn score(item: &doc::ItemTag) -> int { match *item { doc::ConstTag(_) => 0, doc::TyTag(_) => 1, doc::EnumTag(_) => 2, doc::StructTag(_) => 3, doc::TraitTag(_) => 4, doc::ImplTag(_) => 5, doc::FnTag(_) => 6, doc::ModTag(_) => 7, doc::NmodTag(_) => 8 } } score(item1) <= score(item2) } sort_pass::mk_pass(~"sort_item_type", by_score) } #[test] fn test() { use astsrv; use extract; let source = ~"mod imod { } \ extern mod inmod { } \ static iconst: int = 0; \ fn ifn() { } \ enum ienum { ivar } \ trait itrait { fn a(); } \ pub impl int { fn a() { } } \ type itype = int; \ struct istruct { f: () }"; do astsrv::from_str(source) |srv| { let doc = extract::from_srv(srv.clone(), ~""); let doc = (mk_pass().f)(srv.clone(), doc); assert!(doc.cratemod().items[0].name() == ~"iconst"); assert!(doc.cratemod().items[1].name() == ~"itype"); assert!(doc.cratemod().items[2].name() == ~"ienum"); assert!(doc.cratemod().items[3].name() == ~"istruct"); assert!(doc.cratemod().items[4].name() == ~"itrait"); assert!(doc.cratemod().items[5].name() == ~"__extensions__"); assert!(doc.cratemod().items[6].name() == ~"ifn"); assert!(doc.cratemod().items[7].name() == ~"imod"); assert!(doc.cratemod().items[8].name() == ~"inmod"); } }
apache-2.0
alex-zuy/boilerplate-generator
processor/src/test/java/com/github/alex/zuy/boilerplate/collector/support/TypeElementsSetMatcher.java
3328
package com.github.alex.zuy.boilerplate.collector.support; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.stream.Collectors; import javax.lang.model.element.TypeElement; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; public class TypeElementsSetMatcher extends TypeSafeMatcher<Collection<TypeElement>> { private final SortedSet<String> expectedTypeElements; private final StringBuilder mismatchDescription = new StringBuilder(); private TypeElementsSetMatcher(String... expectedTypeElements) { this.expectedTypeElements = new TreeSet<>(); this.expectedTypeElements.addAll(Arrays.asList(expectedTypeElements)); } @Override protected boolean matchesSafely(Collection<TypeElement> typeElements) { return isAllTypeElementsUnique(typeElements) && isAllTypeElementsMatch(typeElements); } @Override public void describeTo(Description description) { description.appendText(mismatchDescription.toString()); } private boolean isAllTypeElementsMatch(Collection<TypeElement> typeElements) { SortedSet<String> actualQualifiersSet = toQualifiersSet(typeElements); if (actualQualifiersSet.equals(expectedTypeElements)) { return true; } else { Set<String> intersection = new HashSet<>(actualQualifiersSet); intersection.retainAll(expectedTypeElements); actualQualifiersSet.stream() .filter(qualifier -> !intersection.contains(qualifier)) .forEach(qualifier -> mismatchDescription.append( String.format("TypeElement \"%s\" was not expected; ", qualifier))); expectedTypeElements.stream() .filter(qualifier -> !intersection.contains(qualifier)) .forEach(qualifier -> mismatchDescription.append( String.format("TypeElement \"%s\" was not present; ", qualifier))); return false; } } private boolean isAllTypeElementsUnique(Collection<TypeElement> typeElements) { SortedSet<String> uniqueQualifiers = toQualifiersSet(typeElements); if (uniqueQualifiers.size() == typeElements.size()) { return true; } else { uniqueQualifiers.forEach(qualifier -> { long entriesCount = typeElements.stream() .filter(typeElement -> typeElement.getQualifiedName().contentEquals(qualifier)) .count(); if (entriesCount > 1) { mismatchDescription.append( String.format("TypeElement \"%s\" appears %d times", qualifier, entriesCount)); } }); return false; } } public static TypeElementsSetMatcher isSetOfTypeElements(String... typeElements) { return new TypeElementsSetMatcher(typeElements); } private static SortedSet<String> toQualifiersSet(Collection<TypeElement> typeElements) { return typeElements.stream() .map(typeElement -> typeElement.getQualifiedName().toString()) .collect(Collectors.toCollection(TreeSet::new)); } }
apache-2.0
vobruba-martin/closure-compiler
src/com/google/javascript/jscomp/disambiguate/FlatType.java
5558
/* * Copyright 2008 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp.disambiguate; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableSet; import com.google.errorprone.annotations.DoNotCall; import com.google.javascript.rhino.jstype.JSType; import java.util.LinkedHashMap; import javax.annotation.Nullable; /** * A struct representing a {@link JSType} "flattened" for use in disambiguation. * * <p>"Flat" refers to the coercion of multiple {@link JSType}s, which should behave the same duing * disambiguation, into a single {@link FlatType}. * * <p>Each instance pairs a type with the information required to converge on the set of * disambiguation clusters that type is a member of. Recall that a different set of clusters exists * for each property name, thus each instance holds the information for *all* relevant property * names simultaneously. */ final class FlatType { /** * The structure of the type wrapped by this {@link FlatType}. * * <p>Each {@link FlatType} has exactly one of its {@code type} fields populated, as indicated by * its {@code arity}. * * <p>Types have a recursive structure. Particularly for unions, this can make it hard to * express/confirm that they have been flattened "all the way down". Storing unions and other * types with different datatypes makes this easier. */ enum Arity { SINGLE, UNION; } /** * Reasons a property name became associated with a type. * * <p>This information is only used for debugging. It doesn't affect the behaviour of the pass. */ enum PropAssociation { AST, // a property associated with a FlatType because of an AST access flatType.prop TYPE_SYSTEM, // a property associated with a FlatType because the type system recorded such an // association, despite no association being found in the AST SUPERTYPE // a property inherited from a supertype in the type graph } private final Arity arity; @Nullable private final JSType typeSingle; @Nullable private final ImmutableSet<FlatType> typeUnion; private final int id; private final LinkedHashMap<PropertyClustering, PropAssociation> associatedProps = new LinkedHashMap<>(); private boolean invalidating = false; static FlatType createForSingle(JSType single, int id) { checkNotNull(single); checkArgument(!single.isNullType()); checkArgument(!single.isVoidType()); checkArgument(!single.isNoType()); checkArgument(!single.isUnknownType()); checkArgument(!single.isTemplatizedType()); checkArgument(!single.isUnionType()); checkArgument(id >= 0); return new FlatType(single, id); } static FlatType createForUnion(ImmutableSet<FlatType> union, int id) { checkArgument(union.size() > 1); for (FlatType alt : union) { checkArgument(alt.hasArity(Arity.SINGLE)); } checkArgument(id >= 0); return new FlatType(union, id); } @VisibleForTesting static FlatType createForTesting(int id) { checkArgument(id < 0); // All test types have negative ids to differentiate them. return new FlatType((JSType) null, id); } private FlatType(JSType single, int id) { this.id = id; this.arity = Arity.SINGLE; this.typeUnion = null; this.typeSingle = single; } private FlatType(ImmutableSet<FlatType> union, int id) { this.id = id; this.arity = Arity.UNION; this.typeUnion = union; this.typeSingle = null; } Arity getArity() { return this.arity; } boolean hasArity(Arity x) { return this.arity.equals(x); } JSType getTypeSingle() { return checkNotNull(this.typeSingle); } ImmutableSet<FlatType> getTypeUnion() { return checkNotNull(this.typeUnion); } /** * An ID used to efficiently construct a unique name for any cluster this node becomes the * represenative of. */ int getId() { return this.id; } /** The set of properties that that might be accessed from this type. */ LinkedHashMap<PropertyClustering, PropAssociation> getAssociatedProps() { return this.associatedProps; } /** * Does this type invalidate disambiguation. * * <p>Invalidating types prevent any property that they're associated with from being * disambiguated/renmaed. As a consequence of ths disambiguation algorithm, this includes all * properties of all ancestor types. */ boolean isInvalidating() { return this.invalidating; } void setInvalidating() { this.invalidating = true; } @Override @DoNotCall // For debugging only. public String toString() { return MoreObjects.toStringHelper(this) .add("id", this.id) .add("type_single", this.typeSingle) .add("type_union", this.typeUnion) .toString(); } }
apache-2.0
SemanticCloud/SemanticCloud
SemanticEngineService/src/main/java/org/semanticcloud/semanticEngine/rest/ClassResource.java
2234
package org.semanticcloud.semanticEngine.rest; import java.util.List; import org.semanticcloud.semanticEngine.controll.OntologyService; import org.semanticcloud.semanticEngine.controll.OperatorService; import org.semanticcloud.semanticEngine.model.ontology.OwlClass; import org.semanticcloud.semanticEngine.model.ontology.OntoProperty; import org.semanticcloud.semanticEngine.model.ConfigurationException; import org.semanticcloud.semanticEngine.model.PropertyOperator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("class/{classUri}") public class ClassResource { @Autowired private OntologyService ontologyService; @Autowired private OperatorService operatorService; @RequestMapping(method = RequestMethod.GET) public OwlClass getClassInfo(@PathVariable String classUri) { OwlClass owlClass = ontologyService.getOwlClass(classUri); return owlClass; } @RequestMapping(value = "property",method = RequestMethod.GET) public List<OntoProperty> getClassProperties(@PathVariable String classUri) { OwlClass owlClass = ontologyService.getOwlClass(classUri); return owlClass.getProperties(); } @RequestMapping(value = "subclass", method = RequestMethod.GET) public List<OwlClass> getSubclasses(@PathVariable String classUri) { return ontologyService.getOwlSubclasses(classUri); } @RequestMapping(value = "{classUri}/properties/{propertyUri}/operators", method = RequestMethod.GET) public List<PropertyOperator> getPropertyOperators(@PathVariable String classUri, @PathVariable String propertyUri) { OwlClass owlClass = ontologyService.getOwlClass(classUri); OntoProperty property = null; try { property = ontologyService.getProperty(propertyUri); } catch (ConfigurationException e) { e.printStackTrace(); } return operatorService.getOperators(property); } }
apache-2.0
oldinaction/smjava
project-star/Shop/src/com/lyq/util/hibernate/HibernateUtils.java
2211
package com.lyq.util.hibernate; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * Hibernate工具类,用于获取Session * @author Li Yongqiang */ public class HibernateUtils { // 声明SessionFactory对象 private static SessionFactory factory = null; // 实例化ThreadLocal对象 private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); // 实例化Configuration对象 private static Configuration cfg = new Configuration(); // 静态块 static { try { // 加载Hibernate配置文件 cfg.configure(); // 实例化SessionFactory factory = cfg.buildSessionFactory(); } catch (HibernateException e) { e.printStackTrace(); // 打印异常信息 } } /** * 获取Session对象 * @return Session对象 */ public static Session getSession() { // 从threadLocal中获取Session Session session = (Session) threadLocal.get(); // 判断session是否为空或未处于开启状态 if (session == null || !session.isOpen()) { if (factory == null) { rebuildSessionFactory(); } // 从factory开启一个Session session = (factory != null) ? factory.openSession() : null; threadLocal.set(session); // 将session放入threadLocal中 } return session; } /** * 获取SessionFactory对象 * @return SessionFactory对象 */ public static SessionFactory getSessionFactory() { return factory; } /** * 关闭Session * @param session对象 */ public static void closeSession() { // 从threadLocal中获取Session Session session = (Session) threadLocal.get(); // 移除threadLocal中的对象 threadLocal.remove(); if (session != null) { if (session.isOpen()) { session.close(); // 关闭Session } } } /** * 创建SessionFactory对象 */ public static void rebuildSessionFactory() { try { // 加载Hibernate配置文件 cfg.configure(); // 实例化SessionFactory factory = cfg.buildSessionFactory(); } catch (Exception e) { e.printStackTrace(); // 打印异常信息 } } }
apache-2.0
mashin-io/rich-spark
streaming/src/main/scala/org/apache/spark/streaming/rdd/WriteAheadLogBackedBlockRDD.scala
9265
/* * 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.streaming.rdd import java.io.File import java.nio.ByteBuffer import java.util.UUID import scala.reflect.ClassTag import scala.util.control.NonFatal import org.apache.spark._ import org.apache.spark.rdd.BlockRDD import org.apache.spark.storage.{BlockId, StorageLevel} import org.apache.spark.streaming.util._ import org.apache.spark.util.SerializableConfiguration import org.apache.spark.util.io.ChunkedByteBuffer /** * Partition class for [[org.apache.spark.streaming.rdd.WriteAheadLogBackedBlockRDD]]. * It contains information about the id of the blocks having this partition's data and * the corresponding record handle in the write ahead log that backs the partition. * * @param index index of the partition * @param blockId id of the block having the partition data * @param isBlockIdValid Whether the block Ids are valid (i.e., the blocks are present in the Spark * executors). If not, then block lookups by the block ids will be skipped. * By default, this is an empty array signifying true for all the blocks. * @param walRecordHandle Handle of the record in a write ahead log having the partition data */ private[streaming] class WriteAheadLogBackedBlockRDDPartition( val index: Int, val blockId: BlockId, val isBlockIdValid: Boolean, val walRecordHandle: WriteAheadLogRecordHandle ) extends Partition /** * This class represents a special case of the BlockRDD where the data blocks in * the block manager are also backed by data in write ahead logs. For reading * the data, this RDD first looks up the blocks by their ids in the block manager. * If it does not find them, it looks up the WAL using the corresponding record handle. * The lookup of the blocks from the block manager can be skipped by setting the corresponding * element in isBlockIdValid to false. This is a performance optimization which does not affect * correctness, and it can be used in situations where it is known that the block * does not exist in the Spark executors (e.g. after a failed driver is restarted). * * @param sc SparkContext * @param _blockIds Ids of the blocks that contains this RDD's data * @param walRecordHandles Record handles in write ahead logs that contain this RDD's data * @param isBlockIdValid Whether the block Ids are valid (i.e., the blocks are present in the Spark * executors). If not, then block lookups by the block ids will be skipped. * By default, this is an empty array signifying true for all the blocks. * @param storeInBlockManager Whether to store a block in the block manager * after reading it from the WAL * @param storageLevel storage level to store when storing in block manager * (applicable when storeInBlockManager = true) */ private[streaming] class WriteAheadLogBackedBlockRDD[T: ClassTag]( sc: SparkContext, @transient private val _blockIds: Array[BlockId], @transient val walRecordHandles: Array[WriteAheadLogRecordHandle], @transient private val isBlockIdValid: Array[Boolean] = Array.empty, storeInBlockManager: Boolean = false, storageLevel: StorageLevel = StorageLevel.MEMORY_ONLY_SER) extends BlockRDD[T](sc, _blockIds) { require( _blockIds.length == walRecordHandles.length, s"Number of block Ids (${_blockIds.length}) must be " + s" same as number of WAL record handles (${walRecordHandles.length})") require( isBlockIdValid.isEmpty || isBlockIdValid.length == _blockIds.length, s"Number of elements in isBlockIdValid (${isBlockIdValid.length}) must be " + s" same as number of block Ids (${_blockIds.length})") // Hadoop configuration is not serializable, so broadcast it as a serializable. @transient private val hadoopConfig = sc.hadoopConfiguration private val broadcastedHadoopConf = new SerializableConfiguration(hadoopConfig) override def isValid(): Boolean = true override def getPartitions: Array[Partition] = { assertValid() Array.tabulate(_blockIds.length) { i => val isValid = if (isBlockIdValid.length == 0) true else isBlockIdValid(i) new WriteAheadLogBackedBlockRDDPartition(i, _blockIds(i), isValid, walRecordHandles(i)) } } /** * Gets the partition data by getting the corresponding block from the block manager. * If the block does not exist, then the data is read from the corresponding record * in write ahead log files. */ override def compute(split: Partition, context: TaskContext): Iterator[T] = { assertValid() val hadoopConf = broadcastedHadoopConf.value val blockManager = SparkEnv.get.blockManager val serializerManager = SparkEnv.get.serializerManager val partition = split.asInstanceOf[WriteAheadLogBackedBlockRDDPartition] val blockId = partition.blockId def getBlockFromBlockManager(): Option[Iterator[T]] = { blockManager.get(blockId).map(_.data.asInstanceOf[Iterator[T]]) } def getBlockFromWriteAheadLog(): Iterator[T] = { var dataRead: ByteBuffer = null var writeAheadLog: WriteAheadLog = null try { // The WriteAheadLogUtils.createLog*** method needs a directory to create a // WriteAheadLog object as the default FileBasedWriteAheadLog needs a directory for // writing log data. However, the directory is not needed if data needs to be read, hence // a dummy path is provided to satisfy the method parameter requirements. // FileBasedWriteAheadLog will not create any file or directory at that path. // FileBasedWriteAheadLog will not create any file or directory at that path. Also, // this dummy directory should not already exist otherwise the WAL will try to recover // past events from the directory and throw errors. val nonExistentDirectory = new File( System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString).getAbsolutePath writeAheadLog = WriteAheadLogUtils.createLogForReceiver( SparkEnv.get.conf, nonExistentDirectory, hadoopConf) dataRead = writeAheadLog.read(partition.walRecordHandle) } catch { case NonFatal(e) => throw new SparkException( s"Could not read data from write ahead log record ${partition.walRecordHandle}", e) } finally { if (writeAheadLog != null) { writeAheadLog.close() writeAheadLog = null } } if (dataRead == null) { throw new SparkException( s"Could not read data from write ahead log record ${partition.walRecordHandle}, " + s"read returned null") } logInfo(s"Read partition data of $this from write ahead log, record handle " + partition.walRecordHandle) if (storeInBlockManager) { blockManager.putBytes(blockId, new ChunkedByteBuffer(dataRead.duplicate()), storageLevel) logDebug(s"Stored partition data of $this into block manager with level $storageLevel") dataRead.rewind() } serializerManager .dataDeserializeStream(blockId, new ChunkedByteBuffer(dataRead).toInputStream()) .asInstanceOf[Iterator[T]] } if (partition.isBlockIdValid) { getBlockFromBlockManager().getOrElse { getBlockFromWriteAheadLog() } } else { getBlockFromWriteAheadLog() } } /** * Get the preferred location of the partition. This returns the locations of the block * if it is present in the block manager, else if FileBasedWriteAheadLogSegment is used, * it returns the location of the corresponding file segment in HDFS . */ override def getPreferredLocations(split: Partition): Seq[String] = { val partition = split.asInstanceOf[WriteAheadLogBackedBlockRDDPartition] val blockLocations = if (partition.isBlockIdValid) { getBlockIdLocations().get(partition.blockId) } else { None } blockLocations.getOrElse { partition.walRecordHandle match { case fileSegment: FileBasedWriteAheadLogSegment => try { HdfsUtils.getFileSegmentLocations( fileSegment.path, fileSegment.offset, fileSegment.length, hadoopConfig) } catch { case NonFatal(e) => logError("Error getting WAL file segment locations", e) Seq.empty } case _ => Seq.empty } } } }
apache-2.0
mapzen/android
mapzen-places-api/src/test/java/com/mapzen/places/api/LatLngTest.java
936
package com.mapzen.places.api; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class LatLngTest { LatLng latLng = new LatLng(40, 70); @Test public void shouldSetLat() { assertThat(latLng.getLatitude()).isEqualTo(40); } @Test public void shouldSetLng() { assertThat(latLng.getLongitude()).isEqualTo(70); } @Test public void shouldSetMinLat() { LatLng minLat = new LatLng(-100, 70); assertThat(minLat.getLatitude()).isEqualTo(-90); } @Test public void shouldSetMaxLat() { LatLng maxLat = new LatLng(100, 70); assertThat(maxLat.getLatitude()).isEqualTo(90); } @Test public void shouldSetLng_160() { LatLng minLng = new LatLng(40, -200); assertThat(minLng.getLongitude()).isEqualTo(160); } @Test public void shouldSetLng_neg160() { LatLng maxLng = new LatLng(40, 200); assertThat(maxLng.getLongitude()).isEqualTo(-160); } }
apache-2.0
emmartins/wildfly-server-migration
servers/wildfly11.0/src/main/java/org/jboss/migration/wfly11/task/subsystem/coremanagement/AddCoreManagementSubsystem.java
2142
/* * Copyright 2017 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. */ package org.jboss.migration.wfly11.task.subsystem.coremanagement; import org.jboss.migration.wfly10.config.management.ProfileResource; import org.jboss.migration.wfly10.config.task.management.subsystem.AddSubsystemResourceSubtaskBuilder; import org.jboss.migration.wfly10.config.task.management.subsystem.AddSubsystemResources; import org.jboss.migration.core.jboss.JBossExtensionNames; import org.jboss.migration.core.jboss.JBossSubsystemNames; /** * @author emmartins */ public class AddCoreManagementSubsystem<S> extends AddSubsystemResources<S> { public AddCoreManagementSubsystem() { super(JBossExtensionNames.CORE_MANAGEMENT, new AddCoreManagementSubsystemResourceSubtaskBuilder<>()); // do not add subsystem config to "standalone-load-balancer.xml" config skipPolicyBuilders(getSkipPolicyBuilder(), buildParameters -> context -> buildParameters.getServerConfiguration().getConfigurationPath().getPath().endsWith("standalone-load-balancer.xml")); } static class AddCoreManagementSubsystemResourceSubtaskBuilder<S> extends AddSubsystemResourceSubtaskBuilder<S> { AddCoreManagementSubsystemResourceSubtaskBuilder() { super(JBossSubsystemNames.CORE_MANAGEMENT); // do not add subsystem config to profile "load-balancer" skipPolicyBuilder(buildParameters -> context -> buildParameters.getResource().getResourceType() == ProfileResource.RESOURCE_TYPE && buildParameters.getResource().getResourceName().equals("load-balancer")); } } }
apache-2.0
networknt/light-java-example
eventuate/account-management/common/src/main/java/com/networknt/eventuate/account/common/event/account/AccountCreditedEvent.java
312
package com.networknt.eventuate.account.common.event.account; import java.math.BigDecimal; public class AccountCreditedEvent extends AccountChangedEvent { private AccountCreditedEvent() { } public AccountCreditedEvent(BigDecimal amount, String transactionId) { super(amount, transactionId); } }
apache-2.0
jbeecham/ovirt-engine
backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/SetVmStatusVDSCommand.java
2171
package org.ovirt.engine.core.vdsbroker; import java.util.List; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.common.businessentities.VmDynamic; import org.ovirt.engine.core.common.businessentities.VmNetworkInterface; import org.ovirt.engine.core.common.businessentities.VmNetworkStatistics; import org.ovirt.engine.core.common.businessentities.VmStatistics; import org.ovirt.engine.core.common.vdscommands.SetVmStatusVDSCommandParameters; import org.ovirt.engine.core.dal.dbbroker.DbFacade; public class SetVmStatusVDSCommand<P extends SetVmStatusVDSCommandParameters> extends VDSCommandBase<P> { public SetVmStatusVDSCommand(P parameters) { super(parameters); } @Override protected void ExecuteVDSCommand() { SetVmStatusVDSCommandParameters parameters = getParameters(); VmDynamic vmDynamic = DbFacade.getInstance().getVmDynamicDao().get(parameters.getVmId()); vmDynamic.setstatus(parameters.getStatus()); if (VM.isStatusDown(parameters.getStatus())) { ResourceManager.getInstance().RemoveAsyncRunningVm(parameters.getVmId()); VmStatistics vmStatistics = DbFacade.getInstance().getVmStatisticsDao().get(parameters.getVmId()); VM vm = new VM(null, vmDynamic, vmStatistics); ResourceManager.getInstance().InternalSetVmStatus(vm, parameters.getStatus()); DbFacade.getInstance().getVmStatisticsDao().update(vm.getStatisticsData()); List<VmNetworkInterface> interfaces = vm.getInterfaces(); if (interfaces != null && interfaces.size() > 0) { for (VmNetworkInterface ifc : interfaces) { VmNetworkStatistics stats = ifc.getStatistics(); DbFacade.getInstance().getVmNetworkStatisticsDao().update(stats); } } } else if (parameters.getStatus() == VMStatus.Unknown) { ResourceManager.getInstance().RemoveAsyncRunningVm(parameters.getVmId()); } DbFacade.getInstance().getVmDynamicDao().update(vmDynamic); } }
apache-2.0
williamb80/EMS
EMS.WebAPI/Global.asax.cs
368
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Routing; namespace EMS.WebAPI { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); } } }
apache-2.0
hmrc/iht-frontend
app/iht/utils/RegistrationKickOutHelper.scala
4748
/* * Copyright 2022 HM Revenue & Customs * * 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 iht.utils import iht.config.AppConfig import iht.connector.CachingConnector import iht.models.{DeceasedDateOfDeath, RegistrationDetails} import play.api.Logging import play.api.mvc.Results._ import play.api.mvc.{Call, Result} import uk.gov.hmrc.http.HeaderCarrier import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future trait RegistrationKickOutHelper extends Logging { implicit val appConfig: AppConfig lazy val RegistrationKickoutReasonCachingKey = "RegistrationKickoutReason" lazy val KickoutDeceasedDateOfDeathDateCapitalTax = "KickoutDeceasedDateOfDeathDateCapitalTax" lazy val KickoutDeceasedDateOfDeathDateOther = "KickoutDeceasedDateOfDeathDateOther" lazy val KickoutDeceasedDetailsLocationScotland = "KickoutDeceasedDetailsLocationScotland" lazy val KickoutDeceasedDetailsLocationNI = "KickoutDeceasedDetailsLocationNI" lazy val KickoutDeceasedDetailsLocationOther = "KickoutDeceasedDetailsLocationOther" lazy val KickoutApplicantDetailsProbateScotland = "KickoutApplicantDetailsProbateScotland" lazy val KickoutApplicantDetailsProbateNi = "KickoutApplicantDetailsProbateNi" lazy val KickoutNotApplyingForProbate = "KickoutNotApplyingForProbate" lazy val KickoutNotAnExecutor = "KickoutNotAnExecutor" def kickoutReasonDeceasedDateOfDeathInternal(deceasedDateOfDeath:DeceasedDateOfDeath): Option[String] = deceasedDateOfDeath.dateOfDeath match { case x if appConfig.dateOfDeathMinValidationDate.compareTo(deceasedDateOfDeath.dateOfDeath) > 0 => Some(KickoutDeceasedDateOfDeathDateCapitalTax) case x if appConfig.dateOfDeathMaxValidationDate.compareTo(deceasedDateOfDeath.dateOfDeath) > 0 => Some(KickoutDeceasedDateOfDeathDateOther) case _ => None } def kickoutReasonDeceasedDateOfDeath(rd: RegistrationDetails): Option[String] = kickoutReasonDeceasedDateOfDeathInternal(rd.deceasedDateOfDeath.get) def kickoutReasonDeceasedDetails(rd: RegistrationDetails): Option[String] = rd.deceasedDetails.flatMap(_.domicile).flatMap{ case appConfig.domicileEnglandOrWales => None case appConfig.domicileScotland => Some(KickoutDeceasedDetailsLocationScotland) case appConfig.domicileNorthernIreland => Some(KickoutDeceasedDetailsLocationNI) case _ => Some(KickoutDeceasedDetailsLocationOther) } def kickoutReasonApplicantDetails(rd: RegistrationDetails): Option[String] = { rd.applicantDetails.flatMap(_.country).flatMap{ case appConfig.applicantCountryScotland => Some(KickoutApplicantDetailsProbateScotland) case appConfig.applicantCountryNorthernIreland => Some(KickoutApplicantDetailsProbateNi) case _ => None } } def checkNotApplyingForProbateKickout(rd: RegistrationDetails): Option[String] = { rd.applicantDetails.flatMap(_.isApplyingForProbate).flatMap{ case true => None case _ => Some(KickoutNotApplyingForProbate) } } def checkNotAnExecutorKickout(rd: RegistrationDetails): Option[String] = { rd.applicantDetails.flatMap(_.executorOfEstate).flatMap{ case true => None case _ => Some(KickoutNotAnExecutor) } } def noKickoutCheck(rd: RegistrationDetails): Option[String] = None def storeAndRedirectWithKickoutCheck(cachingConnector: CachingConnector, rd: RegistrationDetails, getKickoutReason: RegistrationDetails => Option[String], nextPage: Call, failMessage: String = "Failed to successfully store registration details") (implicit hc: HeaderCarrier): Future[Result] = cachingConnector.storeRegistrationDetails(rd).flatMap{ case Some(_) => getKickoutReason.apply(rd).fold(Future.successful(Redirect(nextPage))) { kickoutReason => cachingConnector.storeSingleValue(RegistrationKickoutReasonCachingKey, kickoutReason).flatMap(_ => Future.successful(Redirect(iht.controllers.registration.routes.KickoutRegController.onPageLoad())))} case None => logger.warn(failMessage) Future.successful(InternalServerError(failMessage)) } }
apache-2.0
GrowSocial/pilot
growsocial/client/views/people/people.js
5617
// TODO add a button on the map "back to list" Template.people.events({ 'click .showMapButton': function(event, instance) { event.preventDefault(); // scroll window to map var sel = $('#peopleMap')[0]; if (sel) sel.scrollIntoView(true); if (this.person && this.person.latlng) { // jump to person in map instance.jumpto.set('person', this.person); } }, }); Template.personDetail.helpers({ pathForProfile: function(person) { var params = { personId: person.member_key }; var path = FlowRouter.path("profile", params); return path; }, }); Template.people.helpers({ people: function () { return People.find({},{sort: {lastname: 1, firstname: 1}}); }, notAdmin: function(person) { return (person.member_key != 'pseudo_0'); }, jumpto: function() { return Template.instance().jumpto; }, }); Template.people.onCreated(function() { const instance = this; instance.jumpto = new ReactiveDict(); }); Template.peopleMap.onCreated(function() { const instance = this; instance.peopleMarkersList = []; instance.leafletmapp = {}; }); Template.peopleMap.onRendered(function() { const instance = this; //map code L.Icon.Default.imagePath = 'packages/bevanhunt_leaflet/images'; // L.tileLayer.provider('Thunderforest.Outdoors').addTo(instance.leafletmapp); instance.leafletmapp = L.map('peopleMap'); var osmUrl='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; // var osmUrl='http://{s}.tile.osm.org/{z}/{x}/{y}.png'; // no https certificate on osm.org var osmAttrib='&copy; OpenStreetMap contributors'; var osm = new L.TileLayer(osmUrl, {minZoom: 1, maxZoom: 19, attribution: osmAttrib}); instance.leafletmapp.addLayer(osm); // map won't show much until view is set // iterate the people cursor passed into the template var peopleCursor = instance.data.people; instance.autorun(function() { // BUG1 markers only render on first visit when part of group, so have to be re-added on re-render // BUG2 marker group makes markers bounce around on zoom and re-render if (instance.peopleMarkersList) { // clear markers - else each render rewrites new ones and leaves old ones :P for (var i=0, len = instance.peopleMarkersList.length; i < len; i++) { var marker = instance.peopleMarkersList[i]; instance.leafletmapp.removeLayer(marker); } } instance.peopleMarkersList = []; var peopleLatLngList = []; peopleCursor.forEach(function(person) { if (person.latlng) { // Being selective, only drawing the coords that are in Florida! // TODO take this out when enabled the "local area view" if (person.latlng.lat >= 23.845649887659352 && person.latlng.lat <= 31.615965936476076 && person.latlng.lng >= -85.078125 && person.latlng.lng <= -79.36523437500001) { var marker = L.marker(person.latlng); // TODO popup to have: profile picture, link back to item in list var popupText = "<b>" + person.fullname + "</b>"; if (person.city) { popupText = popupText + "<br>" + person.city; } marker.bindPopup(popupText); // BUG markers only render on first visit when part of group // workaround: add them individually instead marker.addTo(instance.leafletmapp); instance.peopleMarkersList.push(marker); // add latlng to a list peopleLatLngList.push(person.latlng); } } }); // /peopleCursor.forEach // set view to include all markers on the map if (peopleLatLngList.length > 1) { // adjust bounds for map var peopleBounds = L.latLngBounds(peopleLatLngList); instance.leafletmapp.fitBounds(peopleBounds, {padding: [20,20]}); // padding so markers arent on edges } else if (peopleLatLngList.length === 1) { instance.leafletmapp.setView(peopleLatLngList[0], 11); } else { // default view with no markers, how sad! var newLatLng = {lat: 26.064975195273117, lng: -80.2321028709411}; // busy traffic! instance.leafletmapp.setView(newLatLng, 11); } }); // /autorun instance.autorun(function() { // pull person chosen through reactiveDict var jumptoPerson = instance.data.jumpto && instance.data.jumpto.get('person'); if (jumptoPerson) { var jumptoLatlng = jumptoPerson.latlng; // find the appropriate marker var jumptoMarker = null; for (var i=0, len = instance.peopleMarkersList.length; i < len; i++) { var marker = instance.peopleMarkersList[i]; // instance.leafletmapp.removeLayer(marker); var mlatlng = marker.getLatLng(); if (mlatlng.lat === jumptoLatlng.lat && mlatlng.lng === jumptoLatlng.lng) { // we have a match! jumptoMarker = marker; break; } } if (!jumptoMarker) { // didn't find a marker, so create one jumptoMarker = L.marker(jumptoLatlng); // TODO popup to have: profile picture, link back to item in list var popupText = "<b>" + jumptoPerson.fullname + "</b>"; if (jumptoPerson.city) { popupText = popupText + "<br>" + jumptoPerson.city; } jumptoMarker.bindPopup(popupText); jumptoMarker.addTo(instance.leafletmapp); } // set map to look at chosen jumpto instance.leafletmapp.setView(jumptoLatlng, 11); jumptoMarker.openPopup(); } }); // /autorun });
apache-2.0
david-romero/Pachanga
src/main/java/com/p/model/AccountAuth.java
571
package com.p.model; import java.io.Serializable; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class AccountAuth implements Serializable { private static final long serialVersionUID = 5733967566904320005L; private List<Account> accounts; public AccountAuth(List<Account> accounts) { super(); this.accounts = accounts; } public AccountAuth() { super(); } public List<Account> getAccounts() { return accounts; } public void setAccounts(List<Account> accounts) { this.accounts = accounts; } }
apache-2.0
samdauwe/BabylonCpp
src/BabylonCpp/src/physics/helper/physics_vortex_event.cpp
5011
#include <babylon/physics/helper/physics_vortex_event.h> #include <babylon/culling/ray.h> #include <babylon/engines/scene.h> #include <babylon/meshes/builders/cylinder_builder.h> #include <babylon/meshes/builders/mesh_builder_options.h> #include <babylon/meshes/mesh.h> #include <babylon/physics/helper/physics_event_data.h> #include <babylon/physics/helper/physics_hit_data.h> #include <babylon/physics/iphysics_enabled_object.h> #include <babylon/physics/physics_engine.h> #include <babylon/physics/physics_impostor.h> namespace BABYLON { PhysicsVortexEvent::PhysicsVortexEvent(Scene* scene, const Vector3& origin, const PhysicsVortexEventOptions& options) : _scene{scene} , _origin{origin} , _options{options} , _physicsEngine{nullptr} , _originTop{Vector3::Zero()} , _tickCallback{nullptr} , _cylinder{nullptr} , _cylinderPosition{Vector3::Zero()} , _dataFetched{false} { _physicsEngine = _scene->getPhysicsEngine(); _origin.addToRef(Vector3(0.f, _options.height / 2.f, 0.f), _cylinderPosition); _origin.addToRef(Vector3(0.f, _options.height, 0.f), _originTop); _tickCallback = [this](Scene* /*scene*/, EventState& /*es*/) -> void { _tick(); }; _prepareCylinder(); } PhysicsVortexEvent::~PhysicsVortexEvent() = default; PhysicsVortexEventData PhysicsVortexEvent::getData() { _dataFetched = true; return { _cylinder // cylinder }; } void PhysicsVortexEvent::enable() { _tick(); _scene->registerBeforeRender(_tickCallback); } void PhysicsVortexEvent::disable() { _scene->unregisterBeforeRender(_tickCallback); } void PhysicsVortexEvent::dispose(bool force) { if (!_cylinder) { return; } if (force) { _cylinder->dispose(); } else { if (!_dataFetched) { _cylinder->dispose(); } } } std::unique_ptr<PhysicsHitData> PhysicsVortexEvent::getImpostorHitData(PhysicsImpostor& impostor) { if (impostor.mass == 0.f) { return nullptr; } if (!_intersectsWithCylinder(impostor)) { return nullptr; } if (impostor.object->getClassName() != "Mesh" && impostor.object->getClassName() != "InstancedMesh") { return nullptr; } auto impostorObjectCenter = impostor.getObjectCenter(); // the distance to the origin as if both objects were on a plane (Y-axis) Vector3 originOnPlane{_origin.x, impostorObjectCenter.y, _origin.z}; auto originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane); Ray ray{originOnPlane, originToImpostorDirection, _options.radius}; const auto hit = ray.intersectsMesh(static_cast<AbstractMesh*>(impostor.object)); auto contactPoint = hit.pickedPoint; if (!contactPoint) { return nullptr; } const auto absoluteDistanceFromOrigin = hit.distance / _options.radius; auto directionToOrigin = contactPoint->normalize(); if (absoluteDistanceFromOrigin > _options.centripetalForceThreshold) { directionToOrigin = directionToOrigin.negate(); } auto forceX = 0.f, forceY = 0.f, forceZ = 0.f; if (absoluteDistanceFromOrigin > _options.centripetalForceThreshold) { forceX = directionToOrigin.x * _options.centripetalForceMultiplier; forceY = directionToOrigin.y * _options.updraftForceMultiplier; forceZ = directionToOrigin.z * _options.centripetalForceMultiplier; } else { const auto perpendicularDirection = Vector3::Cross(originOnPlane, impostorObjectCenter).normalize(); forceX = (perpendicularDirection.x + directionToOrigin.x) * _options.centrifugalForceMultiplier; forceY = _originTop.y * _options.updraftForceMultiplier; forceZ = (perpendicularDirection.z + directionToOrigin.z) * _options.centrifugalForceMultiplier; } auto force = Vector3(forceX, forceY, forceZ); force = force.multiplyByFloats(_options.strength, _options.strength, _options.strength); return std::make_unique<PhysicsHitData>(PhysicsHitData{ force, // force, impostorObjectCenter, // contactPoint absoluteDistanceFromOrigin // distanceFromOrigin }); } void PhysicsVortexEvent::_tick() { const auto& impostors = _physicsEngine->getImpostors(); for (const auto& impostor : impostors) { auto impostorHitData = getImpostorHitData(*impostor); if (!impostorHitData) { return; } impostor->applyForce(impostorHitData->force, impostorHitData->contactPoint); } } void PhysicsVortexEvent::_prepareCylinder() { if (!_cylinder) { CylinderOptions options; options.height = _options.height; options.diameter = _options.radius * 2.f; _cylinder = CylinderBuilder::CreateCylinder("vortexEventCylinder", options, _scene); _cylinder->isVisible = false; } } bool PhysicsVortexEvent::_intersectsWithCylinder(PhysicsImpostor& impostor) { const auto impostorObject = static_cast<AbstractMesh*>(impostor.object); _cylinder->position = _cylinderPosition; return _cylinder->intersectsMesh(*impostorObject, true); } } // end of namespace BABYLON
apache-2.0
DavidNorman/tensorflow
tensorflow/compiler/tf2xla/xla_compiler_test.cc
78724
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/tf2xla/xla_compiler.h" #include "absl/strings/match.h" #include "tensorflow/cc/framework/ops.h" #include "tensorflow/cc/ops/const_op.h" #include "tensorflow/cc/ops/data_flow_ops.h" #include "tensorflow/cc/ops/function_ops.h" #include "tensorflow/cc/ops/functional_ops.h" #include "tensorflow/cc/ops/list_ops.h" #include "tensorflow/cc/ops/math_ops.h" #include "tensorflow/cc/ops/resource_variable_ops.h" #include "tensorflow/cc/ops/standard_ops.h" #include "tensorflow/compiler/tf2xla/shape_util.h" #include "tensorflow/compiler/tf2xla/side_effect_util.h" #include "tensorflow/compiler/tf2xla/type_util.h" #include "tensorflow/compiler/tf2xla/xla_op_kernel.h" #include "tensorflow/compiler/tf2xla/xla_op_registry.h" #include "tensorflow/compiler/xla/client/client_library.h" #include "tensorflow/compiler/xla/client/local_client.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/compiler/xla/literal.h" #include "tensorflow/compiler/xla/service/hlo.pb.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/tests/literal_test_util.h" #include "tensorflow/core/common_runtime/function.h" #include "tensorflow/core/framework/common_shape_fns.h" #include "tensorflow/core/framework/function.h" #include "tensorflow/core/framework/function.pb.h" #include "tensorflow/core/framework/function_testlib.h" #include "tensorflow/core/framework/graph_to_functiondef.h" #include "tensorflow/core/framework/node_def_util.h" #include "tensorflow/core/framework/resource_mgr.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_testutil.h" #include "tensorflow/core/graph/algorithm.h" #include "tensorflow/core/graph/graph.h" #include "tensorflow/core/graph/graph_constructor.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/public/version.h" namespace tensorflow { class XlaCompilerTest : public ::testing::Test { protected: void SetUp() override { client_ = xla::ClientLibrary::LocalClientOrDie(); XlaOpRegistry::RegisterCompilationKernels(); FunctionDefLibrary flib; flib_def_.reset(new FunctionLibraryDefinition(OpRegistry::Global(), flib)); } XlaCompiler::Options DefaultOptions() { XlaCompiler::Options options; options.device_type = DeviceType(DEVICE_CPU_XLA_JIT); options.client = client_; options.flib_def = flib_def_.get(); return options; } FunctionLibraryDefinition* LocalFlibDef(XlaCompiler* compiler) { return compiler->local_flib_def_.get(); } xla::Client* client_; std::unique_ptr<FunctionLibraryDefinition> flib_def_; }; namespace { // Helper class to test the ability to pass resources through to XLA // compiled kernels. class DummyResourceForTest : public ResourceBase { public: string DebugString() const override { return "dummy"; } void Increment() { ++value_; } int Get() { return value_; } private: int value_ = 0; }; class DummyReadResourceOp : public XlaOpKernel { public: explicit DummyReadResourceOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} void Compile(XlaOpKernelContext* ctx) override { ResourceMgr* rm = ctx->op_kernel_context()->resource_manager(); OP_REQUIRES(ctx, rm, errors::Internal("No resource manager.")); DummyResourceForTest* dummy; OP_REQUIRES_OK(ctx, rm->Lookup<DummyResourceForTest>( rm->default_container(), "dummy", &dummy)); dummy->Increment(); dummy->Unref(); ctx->SetOutput(0, ctx->Input(0)); ctx->SetOutput(1, ctx->Input(0)); } }; class DummyReadResourceCC { public: DummyReadResourceCC(const Scope& scope, const Input& value) { if (!scope.ok()) return; auto _value = ops::AsNodeOut(scope, value); if (!scope.ok()) return; Node* ret; const auto unique_name = scope.GetUniqueNameForOp("DummyReadResource"); auto builder = NodeBuilder(unique_name, "DummyReadResource").Input(_value); scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); if (!scope.ok()) return; this->output1_ = Output(ret, 0); this->output2_ = Output(ret, 1); } Output output1_; Output output2_; }; REGISTER_OP("DummyReadResource") .Input("input: int32") .Output("output1: int32") .Output("output2: int32") .SetShapeFn(shape_inference::UnknownShape) .Doc(R"doc( A dummy Op. input: dummy input. output1: dummy output. output2: dummy output. )doc"); REGISTER_XLA_OP(Name("DummyReadResource"), DummyReadResourceOp); // DummyDuplicateOp is present purely to test multiple REGISTER_XLA_OP calls // on the same Op name below. class DummyDuplicateOp : public XlaOpKernel { public: explicit DummyDuplicateOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} void Compile(XlaOpKernelContext* ctx) override { ctx->SetOutput(0, ctx->Input(0)); } }; REGISTER_OP("DummyDuplicateOp") .Input("input: int32") .Output("output: int32") .Doc(R"doc( A dummy Op. input: dummy input. output: dummy output. )doc"); REGISTER_XLA_OP(Name("DummyDuplicateOp").Device(DEVICE_CPU_XLA_JIT), DummyDuplicateOp); REGISTER_XLA_OP(Name("DummyDuplicateOp").Device(DEVICE_GPU_XLA_JIT), DummyDuplicateOp); // Tests compilation and execution of an empty graph. TEST_F(XlaCompilerTest, EmptyReturnValues) { XlaCompiler compiler(DefaultOptions()); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph( XlaCompiler::CompileOptions(), "add", std::move(graph), /*args=*/{}, /*user_aliases=*/{}, &result)); TF_ASSERT_OK(client_->Execute(*result.computation, {}).status()); } // Tests compilation and execution of a graph that adds two tensors. TEST_F(XlaCompilerTest, Simple) { // Builds a graph that adds two Tensors. Scope scope = Scope::NewRootScope().ExitOnError(); auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); auto b = ops::_Arg(scope.WithOpName("B"), DT_INT32, 1); auto c = ops::Add(scope.WithOpName("C"), a, b); auto d = ops::_Retval(scope.WithOpName("D"), c, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(2); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({2}); args[1].kind = XlaCompiler::Argument::kParameter; args[1].type = DT_INT32; args[1].shape = TensorShape({2}); // Compiles the graph. XlaCompiler compiler(DefaultOptions()); XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", std::move(graph), args, /*user_aliases=*/{}, &result)); // Tests that the generated computation works. xla::Literal param0_literal = xla::LiteralUtil::CreateR1<int32>({7, 42}); xla::Literal param1_literal = xla::LiteralUtil::CreateR1<int32>({-3, 101}); std::unique_ptr<xla::GlobalData> param0_data = client_->TransferToServer(param0_literal).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> param1_data = client_->TransferToServer(param1_literal).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> actual = client_ ->Execute(*result.computation, {param0_data.get(), param1_data.get()}) .ConsumeValueOrDie(); xla::Literal actual_literal = client_->Transfer(*actual).ConsumeValueOrDie(); xla::Literal expected0 = xla::LiteralUtil::CreateR1<int32>({4, 143}); xla::Literal expected_literal = xla::LiteralUtil::MakeTuple({&expected0}); EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal)); } // Tests compilation of a graph where the _Retval node is not necessarily last // amongst the graph nodes in construction order, and always_return_tuple is // false. Regression test for bug where the wrong value was returned. TEST_F(XlaCompilerTest, OutOfOrderGraph) { Scope scope = Scope::NewRootScope().ExitOnError(); auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); auto b = ops::_Arg(scope.WithOpName("B"), DT_INT32, 1); // The _Retval node is not last in construction order. auto d = ops::_Retval(scope.WithOpName("D"), a, 0); auto c = ops::Add(scope.WithOpName("C"), a, b); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(2); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({2}); args[1].kind = XlaCompiler::Argument::kParameter; args[1].type = DT_INT32; args[1].shape = TensorShape({2}); // Compiles the graph. XlaCompiler compiler(DefaultOptions()); XlaCompiler::CompileOptions compile_options; compile_options.always_return_tuple = false; XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph), args, /*user_aliases=*/{}, &result)); // Tests that the generated computation works. xla::Literal param0_literal = xla::LiteralUtil::CreateR1<int32>({7, 42}); xla::Literal param1_literal = xla::LiteralUtil::CreateR1<int32>({-3, 101}); std::unique_ptr<xla::GlobalData> param0_data = client_->TransferToServer(param0_literal).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> param1_data = client_->TransferToServer(param1_literal).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> actual = client_ ->Execute(*result.computation, {param0_data.get(), param1_data.get()}) .ConsumeValueOrDie(); xla::Literal actual_literal = client_->Transfer(*actual).ConsumeValueOrDie(); EXPECT_TRUE(xla::LiteralTestUtil::Equal(param0_literal, actual_literal)); } // Tests that the compiler can correctly propagate the layout assigned by // shape_representation_fn_ to resource returns that have not been written to. TEST_F(XlaCompilerTest, HonorShapeRepresentationFnForUnwrittenResource) { Scope scope = Scope::NewRootScope().ExitOnError(); auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 0); auto d = ops::_Retval(scope.WithOpName("D"), var, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(1); args[0].kind = XlaCompiler::Argument::kResource; args[0].resource_kind = XlaResource::kVariable; args[0].initialized = true; args[0].type = DT_INT32; args[0].shape = TensorShape({2, 3}); auto options = DefaultOptions(); options.shape_representation_fn = [](const TensorShape& shape, DataType dt, bool use_fast_memory) -> xla::StatusOr<xla::Shape> { xla::Shape xla_shape; TF_RETURN_IF_ERROR(TensorShapeToXLAShape(dt, shape, &xla_shape)); *xla_shape.mutable_layout() = xla::LayoutUtil::MakeLayout({0, 1}); return xla_shape; }; // Compiles the graph. XlaCompiler compiler(options); XlaCompiler::CompilationResult result; XlaCompiler::CompileOptions compile_options; compile_options.return_updated_values_for_all_resources = true; TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph), args, /*user_aliases=*/{}, &result)); xla::Shape transposed = xla::ShapeUtil::MakeShapeWithLayout(xla::S32, {2, 3}, {0, 1}); // Check that the return shapes are correctly tranposed. EXPECT_EQ(result.xla_output_shape, xla::ShapeUtil::MakeTupleShape({transposed})); } // Tests that the compiler can correctly propagate fast mem attribute for input // resource variable. TEST_F(XlaCompilerTest, HonorShapeRepresentationFnForFastMemVar) { Scope scope = Scope::NewRootScope().ExitOnError(); auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 0); auto d = ops::_Retval(scope.WithOpName("D"), var, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(1); args[0].kind = XlaCompiler::Argument::kResource; args[0].resource_kind = XlaResource::kVariable; args[0].initialized = true; args[0].type = DT_INT32; args[0].shape = TensorShape({2, 3}); args[0].fast_mem = true; auto options = DefaultOptions(); int fast_mem_arg_count = 0; options.shape_representation_fn = [&fast_mem_arg_count](const TensorShape& shape, DataType dt, bool use_fast_memory) -> xla::StatusOr<xla::Shape> { xla::Shape xla_shape; TF_RETURN_IF_ERROR(TensorShapeToXLAShape(dt, shape, &xla_shape)); *xla_shape.mutable_layout() = xla::LayoutUtil::MakeLayout({0, 1}); if (use_fast_memory) { fast_mem_arg_count++; } return xla_shape; }; // Compiles the graph. XlaCompiler compiler(options); XlaCompiler::CompilationResult result; XlaCompiler::CompileOptions compile_options; compile_options.return_updated_values_for_all_resources = true; TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph), args, /*user_aliases=*/{}, &result)); EXPECT_EQ(fast_mem_arg_count, 1); } // Tests that the compiler can correctly propagate the layout assigned by // shape_representation_fn_ to return types. TEST_F(XlaCompilerTest, HonorShapeRepresentationFnForRetVal) { Scope scope = Scope::NewRootScope().ExitOnError(); auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 1); // Adds an identity op around the resource to make sure identity ops propagate // resources correctly. auto identity = ops::Identity(scope.WithOpName("VIdentity"), var); auto write = ops::AssignAddVariableOp(scope, identity, a); auto read = ops::ReadVariableOp( scope.WithControlDependencies(std::vector<Operation>{write}), var, DT_INT32); auto read_plus_one = ops::Add(scope, read, ops::Const<int32>(scope, 1)); auto d = ops::_Retval(scope.WithOpName("D"), read_plus_one, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(2); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({2, 3}); args[1].kind = XlaCompiler::Argument::kResource; args[1].resource_kind = XlaResource::kVariable; args[1].initialized = true; args[1].type = DT_INT32; args[1].shape = TensorShape({2, 3}); auto options = DefaultOptions(); options.shape_representation_fn = [](const TensorShape& shape, DataType dt, bool use_fast_memory) -> xla::StatusOr<xla::Shape> { xla::Shape xla_shape; TF_RETURN_IF_ERROR(TensorShapeToXLAShape(dt, shape, &xla_shape)); *xla_shape.mutable_layout() = xla::LayoutUtil::MakeLayout({0, 1}); return xla_shape; }; // Compiles the graph. XlaCompiler compiler(options); XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", std::move(graph), args, /*user_aliases=*/{}, &result)); xla::Shape transposed = xla::ShapeUtil::MakeShapeWithLayout(xla::S32, {2, 3}, {0, 1}); // Check that the return shapes are correctly tranposed. EXPECT_EQ(result.xla_output_shape, xla::ShapeUtil::MakeTupleShape({transposed, transposed})); } // The layout of resource variable shouldn't change after transpose TEST_F(XlaCompilerTest, TransposeVariables) { Scope scope = Scope::NewRootScope().ExitOnError(); auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 1); // Adds an identity op around the resource to make sure identity ops propagate // resources correctly. auto identity = ops::Identity(scope.WithOpName("VIdentity"), var); auto write = ops::AssignAddVariableOp(scope, identity, a); auto read = ops::ReadVariableOp( scope.WithControlDependencies(std::vector<Operation>{write}), var, DT_INT32); auto transposed_read = ops::Transpose(scope, read, {1, 0}); auto reshape = ops::Reshape(scope, transposed_read, {2, 3}); auto d = ops::_Retval(scope.WithOpName("D"), reshape, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(2); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({2, 3}); args[1].kind = XlaCompiler::Argument::kResource; args[1].resource_kind = XlaResource::kVariable; args[1].initialized = true; args[1].type = DT_INT32; args[1].shape = TensorShape({2, 3}); // Compiles the graph. XlaCompiler compiler(DefaultOptions()); XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "transpose", std::move(graph), args, /*user_aliases=*/{}, &result)); xla::Shape transposed = xla::ShapeUtil::MakeShapeWithLayout(xla::S32, {2, 3}, {1, 0}); // Check that the return shapes are correctly tranposed. EXPECT_EQ(result.xla_output_shape, xla::ShapeUtil::MakeTupleShape({transposed, transposed})); } // Tests that the compiler doesn't reorder the parameters. TEST_F(XlaCompilerTest, MixedOrderArguments) { for (bool swap_order : {false, true}) { Scope scope = Scope::NewRootScope().ExitOnError(); auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, swap_order ? 0 : 1); auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, swap_order ? 1 : 0); // Adds an identity op around the resource to make sure identity ops // propagate resources correctly. auto identity = ops::Identity(scope.WithOpName("VIdentity"), var); auto write = ops::AssignAddVariableOp(scope, identity, a); auto read = ops::ReadVariableOp( scope.WithControlDependencies(std::vector<Operation>{write}), var, DT_INT32); auto read_plus_one = ops::Add(scope, read, ops::Const<int32>(scope, 1)); auto d = ops::_Retval(scope.WithOpName("D"), read_plus_one, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(2); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({2}); args[1].kind = XlaCompiler::Argument::kResource; args[1].resource_kind = XlaResource::kVariable; args[1].initialized = true; args[1].type = DT_INT32; args[1].shape = TensorShape({2}); if (swap_order) { // Even after swapping arguments, the compiler should maintain the new // ordering of parameters. std::swap(args[0], args[1]); } // Compiles the graph. XlaCompiler compiler(DefaultOptions()); XlaCompiler::CompileOptions compile_options; compile_options.always_return_tuple = false; XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph), args, /*user_aliases=*/{}, &result)); EXPECT_THAT(result.input_mapping, ::testing::ElementsAre(0, 1)); } } TEST_F(XlaCompilerTest, HasSaneErrorOnNonCompileTimeConstantInputToReshape) { // Builds a graph that adds reshapes a tensor, but with the shape not // statically known. Scope scope = Scope::NewRootScope().ExitOnError(); auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); auto b = ops::_Arg(scope.WithOpName("B"), DT_INT32, 1); auto c = ops::Reshape(scope.WithOpName("C"), a, b); auto d = ops::_Retval(scope.WithOpName("D"), c, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(2); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({2}); args[1].kind = XlaCompiler::Argument::kParameter; args[1].type = DT_INT32; args[1].shape = TensorShape({2}); // Compiles the graph. XlaCompiler compiler(DefaultOptions()); XlaCompiler::CompilationResult result; Status status = compiler.CompileGraph(XlaCompiler::CompileOptions(), "reshape", std::move(graph), args, /*user_aliases=*/{}, &result); EXPECT_FALSE(status.ok()); EXPECT_TRUE( absl::StrContains(status.error_message(), "depends on a parameter")) << status.error_message(); EXPECT_TRUE(absl::StrContains(status.error_message(), "{{node C}}")) << status.error_message(); EXPECT_TRUE(absl::StrContains(status.error_message(), "must be a compile-time constant")) << status.error_message(); } // Tests handling of compile-time constant outputs. TEST_F(XlaCompilerTest, ConstantOutputs) { // Builds a graph with one compile-time constant output and one data-dependent // output, i.e., // func(a) { b=7; c=-a; return b, c; } Scope scope = Scope::NewRootScope().ExitOnError(); auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); auto b = ops::Const<int32>(scope.WithOpName("B"), 7); auto c = ops::Neg(scope.WithOpName("C"), a); auto d = ops::_Retval(scope.WithOpName("D"), b, 0); auto e = ops::_Retval(scope.WithOpName("E"), c, 1); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(1); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({2}); XlaCompiler::Options options = DefaultOptions(); XlaCompiler compiler(options); { // Compiles the graph, with resolve_compile_time_constants enabled. std::unique_ptr<Graph> graph_copy(new Graph(OpRegistry::Global())); CopyGraph(*graph, graph_copy.get()); XlaCompiler::CompileOptions compile_options; compile_options.resolve_compile_time_constants = true; XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(compile_options, "constants", std::move(graph_copy), args, /*user_aliases=*/{}, &result)); ASSERT_EQ(2, result.outputs.size()); EXPECT_TRUE(result.outputs[0].is_constant); test::ExpectTensorEqual<int32>(result.outputs[0].constant_value, test::AsScalar(7)); EXPECT_FALSE(result.outputs[1].is_constant); // Tests that the generated computation works. xla::Literal param0_literal = xla::LiteralUtil::CreateR1<int32>({7, 42}); std::unique_ptr<xla::GlobalData> param0_data = client_->TransferToServer(param0_literal).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> actual = client_->Execute(*result.computation, {param0_data.get()}) .ConsumeValueOrDie(); xla::Literal actual_literal = client_->Transfer(*actual).ConsumeValueOrDie(); xla::Literal expected0 = xla::LiteralUtil::CreateR1<int32>({-7, -42}); xla::Literal expected_literal = xla::LiteralUtil::MakeTuple({&expected0}); EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal)); } { // Compiles the graph, with resolve_compile_time_constants disabled. std::unique_ptr<Graph> graph_copy(new Graph(OpRegistry::Global())); CopyGraph(*graph, graph_copy.get()); XlaCompiler::CompileOptions compile_options; compile_options.resolve_compile_time_constants = false; XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(compile_options, "constants", std::move(graph_copy), args, /*user_aliases=*/{}, &result)); ASSERT_EQ(2, result.outputs.size()); EXPECT_FALSE(result.outputs[0].is_constant); EXPECT_FALSE(result.outputs[1].is_constant); // Tests that the generated computation works. xla::Literal param0_literal = xla::LiteralUtil::CreateR1<int32>({7, 42}); std::unique_ptr<xla::GlobalData> param0_data = client_->TransferToServer(param0_literal).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> actual = client_->Execute(*result.computation, {param0_data.get()}) .ConsumeValueOrDie(); xla::Literal actual_literal = client_->Transfer(*actual).ConsumeValueOrDie(); xla::Literal expected0 = xla::LiteralUtil::CreateR0<int32>(7); xla::Literal expected1 = xla::LiteralUtil::CreateR1<int32>({-7, -42}); xla::Literal expected = xla::LiteralUtil::MakeTuple({&expected0, &expected1}); EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected, actual_literal)); } } TEST_F(XlaCompilerTest, ConstantOutputsOfFunctionalNode) { // Define a function with one compile-time constant output and one // data-dependent output. // @function.Defun(noinline=True) // foo(a) {b=7; return b, a; } const Tensor seven = test::AsScalar<int>(7); FunctionDef fdef = FunctionDefHelper::Create( "foo", {"a_0:int32"}, {"const:int32", "a:int32"}, {}, { {{"Const"}, "Const", {}, {{"dtype", DT_INT32}, {"value", seven}}}, }, {{"a", "a_0"}, {"const", "Const:output:0"}}); (*fdef.mutable_attr())["_noinline"].set_b(true); FunctionDefLibrary fdef_lib; *(fdef_lib.add_function()) = fdef; std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); { Scope scope = Scope::NewRootScope().ExitOnError(); TF_EXPECT_OK(scope.graph()->AddFunctionLibrary(fdef_lib)); auto arg = ops::_Arg(scope.WithOpName("input_arg"), DT_INT32, 0); NodeDef foo; foo.set_name("foo"); foo.set_op("foo"); *foo.add_input() = "input_arg"; Status status; scope.graph()->AddNode(foo, &status); TF_ASSERT_OK(status); NodeDef retval_1; retval_1.set_name("retval_0"); retval_1.set_op(FunctionLibraryDefinition::kRetOp); *retval_1.add_input() = "foo"; (*retval_1.mutable_attr())["T"].set_type(DT_INT32); (*retval_1.mutable_attr())["index"].set_i(0); scope.graph()->AddNode(retval_1, &status); TF_ASSERT_OK(status); NodeDef retval_2; retval_2.set_name("retval_1"); retval_2.set_op(FunctionLibraryDefinition::kRetOp); *retval_2.add_input() = "foo:1"; (*retval_2.mutable_attr())["T"].set_type(DT_INT32); (*retval_2.mutable_attr())["index"].set_i(1); scope.graph()->AddNode(retval_2, &status); TF_ASSERT_OK(status); TF_ASSERT_OK(scope.ToGraph(graph.get())); } // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(1); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({1}); XlaCompiler::Options options = DefaultOptions(); FunctionLibraryDefinition flib_def(OpRegistry::Global(), fdef_lib); options.flib_def = &flib_def; XlaCompiler compiler(options); XlaCompiler::CompileOptions compile_options; compile_options.resolve_compile_time_constants = true; XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(compile_options, "constants", std::move(graph), args, /*user_aliases=*/{}, &result)); ASSERT_EQ(2, result.outputs.size()); EXPECT_TRUE(result.outputs[0].is_constant); test::ExpectTensorEqual<int32>(result.outputs[0].constant_value, test::AsScalar(7)); EXPECT_FALSE(result.outputs[1].is_constant); } // Tests compilation and execution of a graph that adds two tensors. TEST_F(XlaCompilerTest, ResourceManager) { // Builds a graph that calls the dummy resource Op. Scope scope = Scope::NewRootScope().ExitOnError(); auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); auto b = DummyReadResourceCC(scope.WithOpName("B"), a); auto c = ops::Add(scope.WithOpName("C"), b.output2_, b.output1_); auto d = ops::_Retval(scope.WithOpName("D"), c, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the argument. std::vector<XlaCompiler::Argument> args(1); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({2}); DummyResourceForTest* resource = new DummyResourceForTest(); // Compiles the graph. auto options = DefaultOptions(); std::function<Status(ResourceMgr*)> populate_function = [resource](ResourceMgr* rm) { resource->Ref(); return rm->Create(rm->default_container(), "dummy", resource); }; options.populate_resource_manager = &populate_function; XlaCompiler compiler(options); EXPECT_EQ(0, resource->Get()); XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "dummy", std::move(graph), args, /*user_aliases=*/{}, &result)); EXPECT_EQ(1, resource->Get()); resource->Unref(); } // Tests compilation and execution of a graph that adds two tensors. TEST_F(XlaCompilerTest, DeterministicCompilation) { // Builds a graph that contains a node with two output edges. The compiler // should always traverse them in the same order. const int64 test_count = 2; std::vector<XlaCompiler::CompilationResult> results(test_count); for (int64 i = 0; i < test_count; ++i) { Scope scope = Scope::NewRootScope().ExitOnError(); auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); auto b = ops::Neg(scope.WithOpName("B"), a); auto c = ops::Neg(scope.WithOpName("C"), a); auto d = ops::Add(scope.WithOpName("D"), b, c); auto e = ops::_Retval(scope.WithOpName("E"), d, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the argument. std::vector<XlaCompiler::Argument> args(1); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({2}); // Compiles the graph. auto options = DefaultOptions(); XlaCompiler compiler(options); TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "dummy", std::move(graph), args, /*user_aliases=*/{}, &results[i])); } for (int64 i = 1; i < test_count; ++i) { const auto& m1 = results[i - 1].computation->proto(); const auto& m2 = results[i].computation->proto(); ASSERT_EQ(m1.computations_size(), m2.computations_size()); // Check if every hlo computation is the same. for (int k = 0; k < m1.computations_size(); k++) { const auto& c1 = m1.computations(k); const auto& c2 = m2.computations(k); ASSERT_EQ(c1.instructions_size(), c2.instructions_size()); for (int j = 0; j < c1.instructions_size(); j++) { auto instr1 = c1.instructions(j); auto instr2 = c2.instructions(j); instr1.clear_name(); instr1.clear_id(); instr1.clear_operand_ids(); instr2.clear_name(); instr2.clear_id(); instr2.clear_operand_ids(); // The names of instructions were uniquified by the XlaBuilder and the // unique ids may be different, the rest of the fields should be // identical. string str1, str2; LOG(INFO) << "instr1 = " << instr1.DebugString(); LOG(INFO) << "instr2 = " << instr2.DebugString(); instr1.AppendPartialToString(&str1); instr2.AppendPartialToString(&str2); EXPECT_EQ(str1, str2); } } } } // Tests a computation that receives a TensorArray resource as input and // updates it. TEST_F(XlaCompilerTest, CanPassTensorArraysToAndFromComputation) { Scope scope = Scope::NewRootScope().ExitOnError(); auto arg = ops::_Arg(scope.WithOpName("arg"), DT_RESOURCE, 0); auto flow = ops::Const<float>(scope, {}); auto grad1 = ops::TensorArrayGrad(scope, arg, flow, "grad1"); auto grad2 = ops::TensorArrayGrad(scope, arg, grad1.flow_out, "grad2"); auto index = ops::Const<int32>(scope, 1); auto write = ops::TensorArrayWrite(scope, grad1.grad_handle, index, index, grad2.flow_out); auto read = ops::TensorArrayRead(scope, arg, index, write.flow_out, DT_INT32); auto retval = ops::_Retval(scope.WithOpName("retval"), read, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(1); args[0].kind = XlaCompiler::Argument::kResource; args[0].resource_kind = XlaResource::kTensorArray; args[0].initialized = true; args[0].type = DT_INT32; args[0].shape = TensorShape({}); args[0].max_array_size = 2; args[0].tensor_array_gradients = {"grad2"}; // Compiles the graph. XlaCompiler compiler(DefaultOptions()); XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", std::move(graph), args, /*user_aliases=*/{}, &result)); ASSERT_EQ(1, result.resource_updates.size()); const XlaCompiler::ResourceUpdate& update = result.resource_updates[0]; EXPECT_EQ(0, update.input_index); EXPECT_EQ(DT_INT32, update.type); EXPECT_EQ((std::set<string>{"grad1", "grad2"}), update.tensor_array_gradients_accessed); // Tests that the generated computation works. xla::Literal input_base = xla::LiteralUtil::CreateR1<int32>({7, 42}); xla::Literal input_grad2 = xla::LiteralUtil::CreateR1<int32>({-3, 101}); xla::Literal input = xla::LiteralUtil::MakeTuple({&input_base, &input_grad2}); std::unique_ptr<xla::GlobalData> param0_data = client_->TransferToServer(input).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> actual = client_->Execute(*result.computation, {param0_data.get()}) .ConsumeValueOrDie(); xla::Literal actual_literal = client_->Transfer(*actual).ConsumeValueOrDie(); xla::Literal output_read = xla::LiteralUtil::CreateR0<int32>(42); xla::Literal output_base = xla::LiteralUtil::CreateR1<int32>({7, 42}); xla::Literal output_grad1 = xla::LiteralUtil::CreateR1<int32>({0, 1}); xla::Literal output_grad2 = xla::LiteralUtil::CreateR1<int32>({-3, 101}); xla::Literal output_resource = xla::LiteralUtil::MakeTuple({&output_base, &output_grad1, &output_grad2}); xla::Literal expected_literal = xla::LiteralUtil::MakeTuple({&output_read, &output_resource}); EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal)); } // Tests compilation and execution of a graph that adds two tensors. TEST_F(XlaCompilerTest, UnwrittenTensorArrayGradientsAreNotComputationOutputs) { Scope scope = Scope::NewRootScope().ExitOnError(); auto arg = ops::_Arg(scope.WithOpName("arg"), DT_RESOURCE, 0); auto flow = ops::Const<float>(scope, {}); auto grad1 = ops::TensorArrayGrad(scope, arg, flow, "grad1"); auto index = ops::Const<int32>(scope, 1); auto read = ops::TensorArrayRead(scope, arg, index, grad1.flow_out, DT_INT32); auto retval = ops::_Retval(scope.WithOpName("retval"), read, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(1); args[0].kind = XlaCompiler::Argument::kResource; args[0].resource_kind = XlaResource::kTensorArray; args[0].initialized = true; args[0].type = DT_INT32; args[0].shape = TensorShape({}); args[0].max_array_size = 2; args[0].tensor_array_gradients = {"grad1"}; // Compiles the graph. XlaCompiler compiler(DefaultOptions()); XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", std::move(graph), args, /*user_aliases=*/{}, &result)); EXPECT_EQ(0, result.resource_updates.size()); } // Tests compilation and execution of a graph that adds two tensors. TEST_F(XlaCompilerTest, NewTensorArrayGradientsAreComputationOutputs) { Scope scope = Scope::NewRootScope().ExitOnError(); auto arg = ops::_Arg(scope.WithOpName("arg"), DT_RESOURCE, 0); auto flow = ops::Const<float>(scope, {}); auto grad1 = ops::TensorArrayGrad(scope, arg, flow, "grad2"); auto index = ops::Const<int32>(scope, 1); auto read = ops::TensorArrayRead(scope, arg, index, grad1.flow_out, DT_INT32); auto retval = ops::_Retval(scope.WithOpName("retval"), read, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(1); args[0].kind = XlaCompiler::Argument::kResource; args[0].resource_kind = XlaResource::kTensorArray; args[0].initialized = true; args[0].type = DT_INT32; args[0].shape = TensorShape({}); args[0].max_array_size = 2; args[0].tensor_array_gradients = {"grad1"}; // Compiles the graph. XlaCompiler compiler(DefaultOptions()); XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", std::move(graph), args, /*user_aliases=*/{}, &result)); EXPECT_EQ(1, result.resource_updates.size()); } // Tests CompileFunction with undefined function fails. TEST_F(XlaCompilerTest, UndefinedFunctionFails) { XlaCompiler compiler(DefaultOptions()); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); XlaCompiler::CompilationResult result; NameAttrList name_attr; name_attr.set_name("Function_NotDefined_"); Status status = compiler.CompileFunction(XlaCompiler::CompileOptions(), name_attr, /*args=*/{}, &result); EXPECT_FALSE(status.ok()); EXPECT_TRUE(absl::StrContains(status.error_message(), "is not defined.")) << status.error_message(); } FunctionDef FillFn() { return FunctionDefHelper::Define( // Name "FillFn", // Args {"x: T", "dims: int32"}, // Return values {"y: T"}, // Attr def {"T: {float, double, int32, int64}"}, // Nodes {{{"y"}, "Fill", {"dims", "x"}, {{"T", "$T"}}}}); } TEST_F(XlaCompilerTest, FunctionCallWithConstants) { // Certain operations in a function, "Fill" for example, requires the // operator's argument to be a compile-time constant instead of a parameter. // This testcase tests if XlaCompiler can handle such operators inside // function calls. XlaCompiler compiler(DefaultOptions()); FunctionDefLibrary flib; *flib.add_function() = FillFn(); TF_ASSERT_OK(flib_def_->AddFunctionDef(FillFn())); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); Scope scope = Scope::NewRootScope().ExitOnError(); auto value = ops::Const<int32>(scope.WithOpName("value"), 1, {}); auto shape = ops::Const<int32>(scope.WithOpName("shape"), {5}, {1}); TF_EXPECT_OK(scope.graph()->AddFunctionLibrary(flib)); NodeDef def; TF_ASSERT_OK(NodeDefBuilder("fill", "FillFn", flib_def_.get()) .Input(value.name(), 0, DT_INT32) .Input(shape.name(), 1, DT_INT32) .Finalize(&def)); Status status; Node* fill = scope.graph()->AddNode(def, &status); TF_ASSERT_OK(status); TF_ASSERT_OK(scope.DoShapeInference(fill)); scope.graph()->AddEdge(value.node(), 0, fill, 0); scope.graph()->AddEdge(shape.node(), 0, fill, 1); auto retval = ops::_Retval(scope.WithOpName("retval"), Output(fill), 0); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the argument. std::vector<XlaCompiler::Argument> args; XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "fill", std::move(graph), args, /*user_aliases=*/{}, &result)); } // Tests CompileFunction with a local function lookup failing, fails with // informative error about both lookups. TEST_F(XlaCompilerTest, LocalFunctionWithWrongArgumentsFail) { XlaCompiler compiler(DefaultOptions()); auto local_flib_def = LocalFlibDef(&compiler); TF_ASSERT_OK(local_flib_def->AddFunctionDef(test::function::XTimesTwo())); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); XlaCompiler::CompilationResult result; NameAttrList name_attr; name_attr.set_name("XTimesTwo"); Status status = compiler.CompileFunction(XlaCompiler::CompileOptions(), name_attr, /*args=*/{}, &result); ASSERT_FALSE(status.ok()); // Flib lookup failure. EXPECT_TRUE(absl::StrContains(status.error_message(), "is not defined.")) << status.error_message(); // Local flib lookup failure. EXPECT_TRUE(absl::StrContains(status.error_message(), "Attr T is not found")) << status.error_message(); } void RunAndCheckVariablesComputation( xla::Client* client, const XlaCompiler::CompilationResult& result) { xla::Literal param0_literal = xla::LiteralUtil::CreateR1<int32>({7, 42}); xla::Literal param1_literal = xla::LiteralUtil::CreateR1<int32>({-3, 101}); std::unique_ptr<xla::GlobalData> param0_data = client->TransferToServer(param0_literal).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> param1_data = client->TransferToServer(param1_literal).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> actual = client ->Execute(*result.computation, {param0_data.get(), param1_data.get()}) .ConsumeValueOrDie(); xla::Literal actual_literal = client->Transfer(*actual).ConsumeValueOrDie(); xla::Literal expected0 = xla::LiteralUtil::CreateR1<int32>({5, 144}); xla::Literal expected1 = xla::LiteralUtil::CreateR1<int32>({4, 143}); xla::Literal expected_literal = xla::LiteralUtil::MakeTuple({&expected0, &expected1}); EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal)); } // Tests a simple graph that reads and writes a variable. TEST_F(XlaCompilerTest, Variables) { Scope scope = Scope::NewRootScope().ExitOnError(); auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 1); // Adds an identity op around the resource to make sure identity ops propagate // resources correctly. auto identity = ops::Identity(scope.WithOpName("VIdentity"), var); auto write = ops::AssignAddVariableOp(scope, identity, a); auto read = ops::ReadVariableOp( scope.WithControlDependencies(std::vector<Operation>{write}), var, DT_INT32); auto read_plus_one = ops::Add(scope, read, ops::Const<int32>(scope, 1)); auto d = ops::_Retval(scope.WithOpName("D"), read_plus_one, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(2); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({2}); args[1].kind = XlaCompiler::Argument::kResource; args[1].resource_kind = XlaResource::kVariable; args[1].initialized = true; args[1].type = DT_INT32; args[1].shape = TensorShape({2}); // Compiles the graph. XlaCompiler compiler(DefaultOptions()); XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", std::move(graph), args, /*user_aliases=*/{}, &result)); RunAndCheckVariablesComputation(client_, result); } TEST_F(XlaCompilerTest, ResultLayoutSingle) { Scope scope = Scope::NewRootScope().ExitOnError(); auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); auto b = ops::_Retval(scope.WithOpName("RET"), a, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(1); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({2, 3}); auto options = DefaultOptions(); // Sets the representation function to return a non-default layout. options.shape_representation_fn = [](const TensorShape& shape, DataType type, bool use_fast_memory) -> xla::StatusOr<xla::Shape> { xla::Shape xla_shape; TF_RETURN_IF_ERROR(TensorShapeToXLAShape(type, shape, &xla_shape)); *xla_shape.mutable_layout() = xla::LayoutUtil::MakeLayout({0, 1}); return xla_shape; }; // Compiles the graph. XlaCompiler compiler(options); XlaCompiler::CompilationResult result; auto compile_options = XlaCompiler::CompileOptions(); compile_options.always_return_tuple = false; TF_ASSERT_OK(compiler.CompileGraph(compile_options, "id", std::move(graph), args, /*user_aliases=*/{}, &result)); EXPECT_TRUE(xla::ShapeUtil::Equal( result.xla_output_shape, xla::ShapeUtil::MakeShapeWithLayout(xla::S32, {2, 3}, {0, 1}))); } TEST_F(XlaCompilerTest, ResultLayoutMultiple) { Scope scope = Scope::NewRootScope().ExitOnError(); auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); auto b = ops::_Retval(scope.WithOpName("RET1"), a, 0); auto c = ops::_Retval(scope.WithOpName("RET2"), a, 1); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(1); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({2, 3}); auto options = DefaultOptions(); // Sets the representation function to return a non-default layout. options.shape_representation_fn = [](const TensorShape& shape, DataType type, bool use_fast_memory) -> xla::StatusOr<xla::Shape> { xla::Shape xla_shape; TF_RETURN_IF_ERROR(TensorShapeToXLAShape(type, shape, &xla_shape)); *xla_shape.mutable_layout() = xla::LayoutUtil::MakeLayout({0, 1}); return xla_shape; }; // Compiles the graph. XlaCompiler compiler(options); XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "id", std::move(graph), args, /*user_aliases=*/{}, &result)); xla::Shape result_shape = xla::ShapeUtil::MakeShapeWithLayout(xla::S32, {2, 3}, {0, 1}); EXPECT_TRUE(xla::ShapeUtil::Equal( result.xla_output_shape, xla::ShapeUtil::MakeTupleShape({result_shape, result_shape}))); } // Tests a simple graph that reads and writes a variable. TEST_F(XlaCompilerTest, ReturnResourceHandleOnly) { Scope scope = Scope::NewRootScope().ExitOnError(); auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 0); auto d = ops::_Retval(scope.WithOpName("D"), var, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(1); args[0].kind = XlaCompiler::Argument::kResource; args[0].resource_kind = XlaResource::kVariable; args[0].initialized = true; args[0].type = DT_INT32; args[0].shape = TensorShape({2}); // Compiles the graph. XlaCompiler compiler(DefaultOptions()); XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", std::move(graph), args, /*user_aliases=*/{}, &result)); // Tests that the generated computation works. xla::Literal param1_literal = xla::LiteralUtil::CreateR1<int32>({-3, 101}); std::unique_ptr<xla::GlobalData> param1_data = client_->TransferToServer(param1_literal).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> actual = client_->Execute(*result.computation, {param1_data.get()}) .ConsumeValueOrDie(); xla::Literal actual_literal = client_->Transfer(*actual).ConsumeValueOrDie(); xla::Literal expected_literal = xla::LiteralUtil::MakeTuple({}); EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal)); } TEST_F(XlaCompilerTest, ReturnResourceHandle) { Scope scope = Scope::NewRootScope().ExitOnError(); auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 1); // Adds an identity op around the resource to make sure identity ops propagate // resources correctly. auto identity = ops::Identity(scope.WithOpName("VIdentity"), var); auto write = ops::AssignAddVariableOp(scope, identity, a); auto read = ops::ReadVariableOp( scope.WithControlDependencies(std::vector<Operation>{write}), var, DT_INT32); auto read_plus_one = ops::Add(scope, read, ops::Const<int32>(scope, 1)); auto r = ops::_Retval(scope.WithOpName("R"), var, 0); auto d = ops::_Retval(scope.WithOpName("D"), read_plus_one, 1); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(2); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({2}); args[1].kind = XlaCompiler::Argument::kResource; args[1].resource_kind = XlaResource::kVariable; args[1].initialized = true; args[1].type = DT_INT32; args[1].shape = TensorShape({2}); // Compiles the graph. XlaCompiler compiler(DefaultOptions()); XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", std::move(graph), args, /*user_aliases=*/{}, &result)); RunAndCheckVariablesComputation(client_, result); } xla::StatusOr<std::unique_ptr<Graph>> BuildTestGraph() { Scope scope = Scope::NewRootScope().ExitOnError(); auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 1); auto write = ops::AssignAddVariableOp(scope, var, a); auto read = ops::ReadVariableOp( scope.WithControlDependencies(std::vector<Operation>{write}), var, DT_INT32); auto read_plus_one = ops::Add(scope, read, ops::Const<int32>(scope, 1)); auto d = ops::_Retval(scope.WithOpName("D"), read_plus_one, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_RETURN_IF_ERROR(scope.ToGraph(graph.get())); return std::move(graph); } // Tests a simple graph that reads and writes a variable, with a // shape_representation_fn passed to the compiler that flattens all // variable tensors to vectors. TEST_F(XlaCompilerTest, VariableRepresentationShapeFunction) { TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Graph> graph, BuildTestGraph()); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(2); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({2, 2}); args[1].kind = XlaCompiler::Argument::kResource; args[1].resource_kind = XlaResource::kVariable; args[1].initialized = true; args[1].type = DT_INT32; args[1].shape = TensorShape({2, 2}); // Compiles the graph. XlaCompiler::Options options = DefaultOptions(); options.shape_representation_fn = [](const TensorShape& shape, DataType type, bool use_fast_memory) -> xla::StatusOr<xla::Shape> { xla::PrimitiveType ptype; TF_RETURN_IF_ERROR(DataTypeToPrimitiveType(type, &ptype)); return xla::ShapeUtil::MakeShape(ptype, {shape.num_elements()}); }; XlaCompiler compiler(options); XlaCompiler::CompileOptions compile_options; compile_options.is_entry_computation = false; // Only reshape variables. XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph), args, /*user_aliases=*/{}, &result)); TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<xla::ProgramShape> program_shape, client_->GetComputationShape(*result.computation)); ASSERT_EQ(program_shape->parameters_size(), 2); EXPECT_TRUE( xla::ShapeUtil::Compatible(program_shape->parameters(0), xla::ShapeUtil::MakeShape(xla::S32, {2, 2}))); EXPECT_TRUE(xla::ShapeUtil::Compatible( program_shape->parameters(1), xla::ShapeUtil::MakeShape(xla::S32, {4}))); EXPECT_TRUE(xla::ShapeUtil::Compatible( program_shape->result(), xla::ShapeUtil::MakeTupleShape( {xla::ShapeUtil::MakeShape(xla::S32, {2, 2}), xla::ShapeUtil::MakeShape(xla::S32, {4})}))); // Tests that the generated computation works. xla::Literal param0_literal = xla::LiteralUtil::CreateR2<int32>({{4, 55}, {1, -3}}); xla::Literal param1_literal = xla::LiteralUtil::CreateR1<int32>({22, 11, 33, 404}); std::unique_ptr<xla::GlobalData> param0_data = client_->TransferToServer(param0_literal).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> param1_data = client_->TransferToServer(param1_literal).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> actual = client_ ->Execute(*result.computation, {param0_data.get(), param1_data.get()}) .ConsumeValueOrDie(); xla::Literal actual_literal = client_->Transfer(*actual).ConsumeValueOrDie(); xla::Literal expected0 = xla::LiteralUtil::CreateR2<int32>({{27, 67}, {35, 402}}); xla::Literal expected1 = xla::LiteralUtil::CreateR1<int32>({26, 66, 34, 401}); xla::Literal expected_literal = xla::LiteralUtil::MakeTuple({&expected0, &expected1}); EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal)); } TEST_F(XlaCompilerTest, ArgRetvalShapeRepresentationFunction) { TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Graph> graph, BuildTestGraph()); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(2); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({2, 2}); args[1].kind = XlaCompiler::Argument::kResource; args[1].resource_kind = XlaResource::kVariable; args[1].initialized = true; args[1].type = DT_INT32; args[1].shape = TensorShape({2, 2}); // Compiles the graph. XlaCompiler::Options options = DefaultOptions(); options.shape_representation_fn = [](const TensorShape& shape, DataType type, bool use_fast_memory) -> xla::StatusOr<xla::Shape> { xla::PrimitiveType ptype; TF_RETURN_IF_ERROR(DataTypeToPrimitiveType(type, &ptype)); return xla::ShapeUtil::MakeShape(ptype, {shape.num_elements()}); }; XlaCompiler compiler(options); XlaCompiler::CompileOptions compile_options; compile_options.is_entry_computation = true; // Reshape args and retvals. XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph), args, /*user_aliases=*/{}, &result)); TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<xla::ProgramShape> program_shape, client_->GetComputationShape(*result.computation)); ASSERT_EQ(program_shape->parameters_size(), 2); EXPECT_TRUE(xla::ShapeUtil::Compatible( program_shape->parameters(0), xla::ShapeUtil::MakeShape(xla::S32, {4}))); EXPECT_TRUE(xla::ShapeUtil::Compatible( program_shape->parameters(1), xla::ShapeUtil::MakeShape(xla::S32, {4}))); EXPECT_TRUE(xla::ShapeUtil::Compatible( program_shape->result(), xla::ShapeUtil::MakeTupleShape( {xla::ShapeUtil::MakeShape(xla::S32, {4}), xla::ShapeUtil::MakeShape(xla::S32, {4})}))); // Tests that the generated computation works. xla::Literal param0_literal = xla::LiteralUtil::CreateR1<int32>({4, 55, 1, -3}); xla::Literal param1_literal = xla::LiteralUtil::CreateR1<int32>({22, 11, 33, 404}); std::unique_ptr<xla::GlobalData> param0_data = client_->TransferToServer(param0_literal).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> param1_data = client_->TransferToServer(param1_literal).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> actual = client_ ->Execute(*result.computation, {param0_data.get(), param1_data.get()}) .ConsumeValueOrDie(); xla::Literal actual_literal = client_->Transfer(*actual).ConsumeValueOrDie(); xla::Literal expected0 = xla::LiteralUtil::CreateR1<int32>({27, 67, 35, 402}); xla::Literal expected1 = xla::LiteralUtil::CreateR1<int32>({26, 66, 34, 401}); xla::Literal expected_literal = xla::LiteralUtil::MakeTuple({&expected0, &expected1}); EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal)); } // Tests a graph which has a function with an invalid op. TEST_F(XlaCompilerTest, FunctionWithInvalidOp) { XlaCompiler compiler(DefaultOptions()); FunctionDefLibrary flib; FunctionDef fn = FillFn(); NodeDef* node = fn.add_node_def(); node->set_name("Invalid"); node->set_op("InvalidOp"); /* unsupported op */ node = fn.add_node_def(); node->set_name("Switch"); node->set_op("Switch"); /* control flow node */ *flib.add_function() = fn; TF_ASSERT_OK(flib_def_->AddFunctionDef(fn)); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); Scope scope = Scope::NewRootScope().ExitOnError(); auto value = ops::Const<int32>(scope.WithOpName("value"), 1, {}); auto shape = ops::Const<int32>(scope.WithOpName("shape"), {5}, {1}); TF_ASSERT_OK(scope.graph()->AddFunctionLibrary(flib)); NodeDef def; TF_ASSERT_OK(NodeDefBuilder("fill_fn", "FillFn", flib_def_.get()) .Input(value.name(), 0, DT_INT32) .Input(shape.name(), 1, DT_INT32) .Finalize(&def)); Status status; Node* fill = scope.graph()->AddNode(def, &status); TF_ASSERT_OK(status); TF_ASSERT_OK(scope.DoShapeInference(fill)); scope.graph()->AddEdge(value.node(), 0, fill, 0); scope.graph()->AddEdge(shape.node(), 0, fill, 1); auto retval = ops::_Retval(scope.WithOpName("retval"), Output(fill), 0); TF_ASSERT_OK(scope.ToGraph(graph.get())); std::vector<XlaCompiler::Argument> args; XlaCompiler::CompilationResult result; status = compiler.CompileGraph(XlaCompiler::CompileOptions(), "fill", std::move(graph), args, /*user_aliases=*/{}, &result); ASSERT_FALSE(status.ok()); EXPECT_TRUE(absl::StrContains(status.error_message(), "InvalidOp")) << status.error_message(); EXPECT_TRUE(absl::StrContains(status.error_message(), "{{node fill_fn}}")) << status.error_message(); } // Tests a graph which has a node with invalid data type. TEST_F(XlaCompilerTest, NodeWithInvalidDataType) { std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); NodeDef shape; shape.set_name("Shape"); shape.set_op("Shape"); (*shape.mutable_attr())["T"].set_type(DT_INT32); (*shape.mutable_attr())["out_type"].set_type(DT_BOOL); /* invalid type */ Status status; Node* shape_node = graph->AddNode(shape, &status); TF_ASSERT_OK(status); graph->AddControlEdge(graph->source_node(), shape_node); std::vector<XlaCompiler::Argument> args; XlaCompiler::CompilationResult result; XlaCompiler compiler(DefaultOptions()); status = compiler.CompileGraph(XlaCompiler::CompileOptions(), "invalid_type", std::move(graph), args, /*user_aliases=*/{}, &result); ASSERT_FALSE(status.ok()); EXPECT_TRUE(absl::StrContains(status.error_message(), "is not in the list of allowed values")) << status.error_message(); EXPECT_TRUE(absl::StrContains(status.error_message(), "{{node Shape}}")) << status.error_message(); } TEST_F(XlaCompilerTest, SingleOpWithoutInputs) { std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); NodeDef no_op; no_op.set_name("NoOp"); no_op.set_op("NoOp"); Status status; graph->AddNode(no_op, &status); TF_ASSERT_OK(status); std::vector<XlaCompiler::Argument> args; XlaCompiler compiler(DefaultOptions()); // No control edge linking NoOp with source/sink. { std::unique_ptr<Graph> graph_copy(new Graph(OpRegistry::Global())); CopyGraph(*graph, graph_copy.get()); XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "NoOp", std::move(graph_copy), args, /*user_aliases=*/{}, &result)); } } class DummySideEffectingOp : public XlaOpKernel { public: explicit DummySideEffectingOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} void Compile(XlaOpKernelContext* ctx) override { OP_REQUIRES_OK(ctx, ctx->compiler()->SetNodeToken( name(), xla::CreateToken(ctx->builder()))); } }; REGISTER_OP("DummySideEffectingOp"); REGISTER_XLA_OP(Name("DummySideEffectingOp"), DummySideEffectingOp); TEST_F(XlaCompilerTest, TokenInputAndOutput) { std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); NodeDef side_effecting_op; side_effecting_op.set_name("DummySideEffectingOp"); side_effecting_op.set_op("DummySideEffectingOp"); AddNodeAttr(kXlaTokenInputNodesAttrName, std::vector<string>{kXlaTokenArgNodeName}, &side_effecting_op); Status status; graph->AddNode(side_effecting_op, &status); TF_ASSERT_OK(status); EXPECT_TRUE(FixupSourceAndSinkEdges(graph.get())); std::vector<XlaCompiler::Argument> args(1); args[0].kind = XlaCompiler::Argument::kResource; args[0].resource_kind = XlaResource::kVariable; args[0].initialized = true; args[0].type = DT_INT32; args[0].shape = TensorShape({2, 2}); { // The case for entry computation: we don't add token input/output. Instead, // we use CreateToken HLO to create the entry token. XlaCompiler::CompileOptions options; options.is_entry_computation = true; options.add_token_input_output = false; options.return_updated_values_for_all_resources = true; XlaCompiler compiler(DefaultOptions()); std::unique_ptr<Graph> graph_copy(new Graph(OpRegistry::Global())); CopyGraph(*graph, graph_copy.get()); XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(options, "NoOp", std::move(graph_copy), args, /*user_aliases=*/{}, &result)); EXPECT_EQ(result.xla_input_shapes.size(), 1); EXPECT_TRUE(result.xla_output_shape.IsTuple()); EXPECT_EQ(xla::ShapeUtil::TupleElementCount(result.xla_output_shape), 1); } { // The case for non-entry computation (e.g. while loop body). We add token // input/output. XlaCompiler::CompileOptions options; options.is_entry_computation = false; options.add_token_input_output = true; options.return_updated_values_for_all_resources = true; XlaCompiler compiler(DefaultOptions()); std::unique_ptr<Graph> graph_copy(new Graph(OpRegistry::Global())); CopyGraph(*graph, graph_copy.get()); XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(options, "NoOp", std::move(graph_copy), args, /*user_aliases=*/{}, &result)); EXPECT_EQ(result.xla_input_shapes.size(), 2); EXPECT_TRUE(result.xla_input_shapes[1].IsToken()); EXPECT_TRUE(result.xla_output_shape.IsTuple()); EXPECT_EQ(xla::ShapeUtil::TupleElementCount(result.xla_output_shape), 2); EXPECT_TRUE(xla::ShapeUtil::GetTupleElementShape(result.xla_output_shape, 1) .IsToken()); } } TEST_F(XlaCompilerTest, OpsWithTensorListInput) { FunctionDefLibrary fdef_lib; FunctionLibraryDefinition flib_def(OpRegistry::Global(), fdef_lib); // Build cond fn for While. { Scope scope = Scope::NewRootScope().ExitOnError(); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); ops::_Arg(scope.WithOpName("arg"), DT_VARIANT, 0); auto result = ops::Const<bool>(scope, {true}, {}); ops::_Retval(scope.WithOpName("ret"), result, 0); TF_ASSERT_OK(scope.ToGraph(graph.get())); FunctionDef fdef; TF_ASSERT_OK(GraphToFunctionDef(*graph, "cond", &fdef)); TF_ASSERT_OK(flib_def.AddFunctionDef(fdef)); } // Build body fn for While. { Scope scope = Scope::NewRootScope().ExitOnError(); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); auto arg = ops::_Arg(scope.WithOpName("arg"), DT_VARIANT, 0); ops::_Retval(scope.WithOpName("ret"), arg, 0); TF_ASSERT_OK(scope.ToGraph(graph.get())); FunctionDef fdef; TF_ASSERT_OK(GraphToFunctionDef(*graph, "body", &fdef)); TF_ASSERT_OK(flib_def.AddFunctionDef(fdef)); } Scope scope = Scope::NewRootScope().ExitOnError(); auto element_shape = ops::Const<int32>(scope, {1}, {1}); auto max_elements = ops::Const<int32>(scope, {10}, {}); auto arg = ops::_Arg(scope.WithOpName("arg"), DT_VARIANT, 0); std::initializer_list<Output> out = {arg, arg}; auto add_n = ops::AddN(scope, out); NameAttrList cond_fn, body_fn; cond_fn.set_name("cond"); body_fn.set_name("body"); auto while_op = ops::While(scope, std::initializer_list<Input>{arg}, cond_fn, body_fn); auto ret0 = ops::_Retval(scope.WithOpName("ret0"), add_n, 0); auto ret1 = ops::_Retval(scope.WithOpName("ret1"), while_op.output[0], 1); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(1); args[0].kind = XlaCompiler::Argument::kTensorList; xla::Shape tensor_list_element_shape; TF_ASSERT_OK(TensorShapeToXLAShape(DT_INT32, TensorShape{1}, &tensor_list_element_shape)); xla::Shape index_shape; TF_ASSERT_OK(TensorShapeToXLAShape(DT_INT32, TensorShape{}, &index_shape)); std::vector<xla::Shape> shapes{tensor_list_element_shape, index_shape}; xla::Shape arg_shape = xla::ShapeUtil::MakeTupleShape(shapes); args[0].shape = arg_shape; // Compiles the graph. XlaCompiler::Options options = DefaultOptions(); options.flib_def = &flib_def; XlaCompiler compiler(options); XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", std::move(graph), args, /*user_aliases=*/{}, &result)); ASSERT_EQ(result.outputs.size(), 2); const XlaCompiler::OutputDescription& output0 = result.outputs[0]; ASSERT_TRUE(output0.is_tensor_list); const XlaCompiler::OutputDescription& output1 = result.outputs[1]; ASSERT_TRUE(output1.is_tensor_list); } // Test the compiler supports WhileOp with a loop body where DT_RESOURCE // variables are both inputs and outputs. TEST_F(XlaCompilerTest, WhileWithResources) { FunctionDefLibrary fdef_lib; FunctionLibraryDefinition flib_def(OpRegistry::Global(), fdef_lib); // Build cond fn for While. { Scope scope = Scope::NewRootScope().ExitOnError(); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0); auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_RESOURCE, 1); auto arg2 = ops::_Arg(scope.WithOpName("arg2"), DT_RESOURCE, 2); auto less = ops::Less(scope, arg0, ops::Const<int32>(scope, 10)); (void)ops::_Retval(scope.WithOpName("ret"), less, 0); TF_ASSERT_OK(scope.ToGraph(graph.get())); FunctionDef fdef; TF_ASSERT_OK(GraphToFunctionDef(*graph, "cond", &fdef)); TF_ASSERT_OK(flib_def.AddFunctionDef(fdef)); } // Build body fn for While. { Scope scope = Scope::NewRootScope().ExitOnError(); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0); auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_RESOURCE, 1); auto arg2 = ops::_Arg(scope.WithOpName("arg2"), DT_RESOURCE, 2); auto read1 = ops::ReadVariableOp(scope.WithOpName("read1"), arg1, DT_INT32); auto plus_read1 = ops::Add(scope, arg0, read1); auto read2 = ops::ReadVariableOp(scope.WithOpName("read2"), arg2, DT_INT32); auto minus_read2 = ops::Sub(scope, plus_read1, read2); (void)ops::_Retval(scope.WithOpName("ret0"), minus_read2, 0); (void)ops::_Retval(scope.WithOpName("ret1"), arg1, 1); (void)ops::_Retval(scope.WithOpName("ret2"), arg2, 2); TF_ASSERT_OK(scope.ToGraph(graph.get())); FunctionDef fdef; TF_ASSERT_OK(GraphToFunctionDef(*graph, "body", &fdef)); TF_ASSERT_OK(flib_def.AddFunctionDef(fdef)); } Scope scope = Scope::NewRootScope().ExitOnError(); auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0); auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_RESOURCE, 1); auto arg2 = ops::_Arg(scope.WithOpName("arg2"), DT_RESOURCE, 2); NameAttrList cond_fn, body_fn; cond_fn.set_name("cond"); body_fn.set_name("body"); auto while_op = ops::While( scope, std::initializer_list<Input>{arg0, arg1, arg2}, cond_fn, body_fn); (void)ops::_Retval(scope.WithOpName("ret0"), while_op.output[0], 0); (void)ops::_Retval(scope.WithOpName("ret1"), while_op.output[1], 1); (void)ops::_Retval(scope.WithOpName("ret2"), while_op.output[2], 2); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(3); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({}); args[1].kind = XlaCompiler::Argument::kResource; args[1].resource_kind = XlaResource::kVariable; args[1].initialized = true; args[1].type = DT_INT32; args[1].shape = TensorShape({}); args[2].kind = XlaCompiler::Argument::kResource; args[2].resource_kind = XlaResource::kVariable; args[2].initialized = true; args[2].type = DT_INT32; args[2].shape = TensorShape({}); // Compiles the graph. XlaCompiler::Options options = DefaultOptions(); options.flib_def = &flib_def; XlaCompiler compiler(options); XlaCompiler::CompileOptions compile_options = XlaCompiler::CompileOptions(); compile_options.return_updated_values_for_all_resources = true; XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(compile_options, "tested_while_with_vars", std::move(graph), args, /*user_aliases=*/{}, &result)); ASSERT_EQ(result.outputs.size(), 3); const XlaCompiler::OutputDescription& output1 = result.outputs[1]; ASSERT_EQ(output1.input_index, 1); const XlaCompiler::OutputDescription& output2 = result.outputs[2]; ASSERT_EQ(output2.input_index, 2); // Tests that the generated computation works. xla::Literal literal0 = xla::LiteralUtil::CreateR0<int32>(0); xla::Literal literal1 = xla::LiteralUtil::CreateR0<int32>(2); xla::Literal literal2 = xla::LiteralUtil::CreateR0<int32>(1); std::unique_ptr<xla::GlobalData> data0 = client_->TransferToServer(literal0).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> data1 = client_->TransferToServer(literal1).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> data2 = client_->TransferToServer(literal2).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> actual = client_ ->Execute(*result.computation, {data0.get(), data1.get(), data2.get()}) .ConsumeValueOrDie(); xla::Literal actual_literal = client_->Transfer(*actual).ConsumeValueOrDie(); xla::Literal expected0 = xla::LiteralUtil::CreateR0<int32>(10); xla::Literal expected1 = xla::LiteralUtil::CreateR0<int32>(2); xla::Literal expected2 = xla::LiteralUtil::CreateR0<int32>(1); xla::Literal expected_literal = xla::LiteralUtil::MakeTuple({&expected0, &expected1, &expected2}); EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal)); } TEST_F(XlaCompilerTest, SetShardingForReturnedTuple) { // Builds a graph that returns its only argument. Scope scope = Scope::NewRootScope().ExitOnError(); auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); auto b = ops::_Retval(scope.WithOpName("B"), a, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Sets _XlaSharding attribute for the _Retval node. auto node_name_index = graph->BuildNodeNameIndex(); Node* ret_node = node_name_index["B"]; ASSERT_NE(ret_node, nullptr); xla::Array<int64> tile_assignment({2}); tile_assignment.FillIota(0); xla::HloSharding sharding = xla::HloSharding::Tile(tile_assignment); ret_node->AddAttr("_XlaSharding", sharding.ToProto().SerializeAsString()); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(1); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({2}); // Compiles the graph. XlaCompiler compiler(DefaultOptions()); XlaCompiler::CompilationResult result; TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "test", std::move(graph), args, /*user_aliases=*/{}, &result)); // Tests that we set sharding on the root TUPLE instruction. const auto& hlo_module_proto = result.computation->proto(); ASSERT_EQ(hlo_module_proto.computations_size(), 1); const auto& hlo_computation_proto = hlo_module_proto.computations(0); absl::optional<xla::HloInstructionProto> root_instruction_proto; for (const auto& inst : hlo_computation_proto.instructions()) { if (inst.id() == hlo_computation_proto.root_id()) { root_instruction_proto = inst; break; } } ASSERT_TRUE(root_instruction_proto); xla::Shape tuple_shape = xla::ShapeUtil::MakeTupleShape( {xla::ShapeUtil::MakeShape(xla::S32, {2})}); xla::HloSharding tuple_sharding = xla::HloSharding::Tuple( tuple_shape, std::vector<xla::HloSharding>{sharding}); EXPECT_EQ(root_instruction_proto->sharding().SerializeAsString(), tuple_sharding.ToProto().SerializeAsString()); } TEST_F(XlaCompilerTest, DoNotConstantFoldShapeOp) { // When we have a dynamic shape input followed by a Shape op, the Shape op // should return dynamic size: // // [2, b] // b's static size is 3 and dynamic size is 2 // | // Size // should return 2, 2 Scope scope = Scope::NewRootScope().ExitOnError(); auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); auto b = ops::_Arg(scope.WithOpName("B"), DT_INT32, 1); auto shape = ops::Shape(scope.WithOpName("shape"), a); (void)ops::_Retval(scope.WithOpName("retval"), shape, 0); std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global())); TF_ASSERT_OK(scope.ToGraph(graph.get())); // Builds a description of the arguments. std::vector<XlaCompiler::Argument> args(2); args[0].kind = XlaCompiler::Argument::kParameter; args[0].type = DT_INT32; args[0].shape = TensorShape({2, 3}); // Indicates that first dimension is dynamic, and arg 1 holds the runtime // value of it. args[0].dynamic_dim_to_arg_num_map.insert({1, 1}); // Arg 1 holds the dynamic size. args[1].kind = XlaCompiler::Argument::kParameter; args[1].type = DT_INT32; args[1].shape = TensorShape({}); // Compiles the graph. XlaCompiler compiler(DefaultOptions()); XlaCompiler::CompilationResult result; auto options = XlaCompiler::CompileOptions(); options.resolve_compile_time_constants = false; TF_ASSERT_OK(compiler.CompileGraph(options, "test", std::move(graph), args, /*user_aliases=*/{}, &result)); xla::Literal literal0 = xla::LiteralUtil::CreateR2<int32>({{0, 1, 2}, {3, 4, 5}}); xla::Literal literal1 = xla::LiteralUtil::CreateR0<int32>(2); std::unique_ptr<xla::GlobalData> data0 = client_->TransferToServer(literal0).ConsumeValueOrDie(); std::unique_ptr<xla::GlobalData> data1 = client_->TransferToServer(literal1).ConsumeValueOrDie(); // Prepare arguments. std::unique_ptr<xla::GlobalData> actual = client_->Execute(*result.computation, {data0.get(), data1.get()}) .ConsumeValueOrDie(); xla::Literal actual_literal = client_->Transfer(*actual).ConsumeValueOrDie(); // The dynamic size of the op is <2, 2> instead of static size <2, 3> xla::Literal expected = xla::LiteralUtil::CreateR1<int32>({2, 2}); xla::Literal expected_literal = xla::LiteralUtil::MakeTuple({&expected}); EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal)); } } // namespace } // namespace tensorflow
apache-2.0
Guidewire/teamcity_exporter
collector.go
653
package main import ( "time" "github.com/prometheus/client_golang/prometheus" ) func NewCollector() *Collector { col := &Collector{ startupTime: prometheus.NewDesc(namespace+"_collector_startup_time", "Collector startup time", nil, nil), } metricsStorage.Set(getHash(col.startupTime.String()), prometheus.MustNewConstMetric(col.startupTime, prometheus.GaugeValue, float64(time.Now().Unix()))) return col } func (col *Collector) Describe(ch chan<- *prometheus.Desc) { ch <- col.startupTime } func (col *Collector) Collect(ch chan<- prometheus.Metric) { for i := range metricsStorage.IterBuffered() { ch <- i.Val.(prometheus.Metric) } }
apache-2.0
mcn42/WeatherServer
src/main/java/org/mnilsen/weather/aws/AwsIotClient.java
8848
/* * 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 org.mnilsen.weather.aws; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.iot.client.AWSIotException; import com.amazonaws.services.iot.client.AWSIotMessage; import com.amazonaws.services.iot.client.AWSIotMqttClient; import com.amazonaws.services.iot.client.AWSIotQos; import com.amazonaws.services.iot.client.AWSIotTopic; import com.amazonaws.services.iot.client.sample.sampleUtil.SampleUtil; import com.amazonaws.services.iot.client.sample.sampleUtil.SampleUtil.KeyStorePasswordPair; import com.amazonaws.services.sns.AmazonSNS; import com.amazonaws.services.sns.AmazonSNSClientBuilder; import com.amazonaws.services.sns.model.MessageAttributeValue; import com.amazonaws.services.sns.model.PublishRequest; import com.amazonaws.services.sns.model.PublishResult; import java.util.HashMap; import java.util.Map; import java.util.TimerTask; import java.util.logging.Level; import org.mnilsen.weather.server.AppProperty; import org.mnilsen.weather.server.Coordinator; import org.mnilsen.weather.server.Log; import org.mnilsen.weather.server.Utils; import org.mnilsen.weather.server.model.Reading; import org.mnilsen.weather.server.model.ReadingHistory; /** * * @author michaeln */ public class AwsIotClient { private final String clientEndpoint = Utils.getAppProperties().get(AppProperty.AWS_CLIENT_ENDPOINT); private final String clientId = Utils.getAppProperties().get(AppProperty.AWS_CLIENT_ID); private final String certificateFile = Utils.getAppProperties().get(AppProperty.AWS_CERT_FILE); private final String privateKeyFile = Utils.getAppProperties().get(AppProperty.AWS_PK_FILE); private final String updateTopic = Utils.getAppProperties().get(AppProperty.AWS_UPDATE_TOPIC); private final String updateAccTopic = Utils.getAppProperties().get(AppProperty.AWS_UPDATE_ACCEPTED_TOPIC); private final String updateRejTopic = Utils.getAppProperties().get(AppProperty.AWS_UPDATE_REJECTED_TOPIC); private AWSIotMqttClient client = null; private UpdateTask updateTask = null; private Map<String, MessageAttributeValue> smsAttributes = null; private AmazonSNS snsClient = null; public AwsIotClient() { } public void start() { this.startSNS(); KeyStorePasswordPair pair = SampleUtil.getKeyStorePasswordPair(certificateFile, privateKeyFile); client = new AWSIotMqttClient(clientEndpoint, clientId, pair.keyStore, pair.keyPassword); Long period = Utils.getAppProperties().getLong(AppProperty.AWS_UPDATE_PERIOD); try { Log.getLog().info(String.format("Connecting to AWS endpoint %s", this.clientEndpoint)); client.connect(); Log.getLog().info(String.format("Connected to AWS endpoint: %s", this.client.getConnectionStatus())); MyTopic mt = new MyTopic(this.updateAccTopic, AWSIotQos.QOS0); client.subscribe(mt); Log.getLog().info(String.format("Subscribed to AWS topic: %s", this.updateAccTopic)); mt = new MyTopic(this.updateRejTopic, AWSIotQos.QOS0); client.subscribe(mt); Log.getLog().info(String.format("Subscribed to AWS topic: %s", this.updateRejTopic)); this.updateTask = new UpdateTask(); Utils.getAppTimer().schedule(updateTask, 31000L, period); Log.getLog().info(String.format("Started Update Task with period %s", period)); } catch (AWSIotException ex) { Log.getLog().log(Level.SEVERE, "AWS Client connect error", ex); } } public void startSNS() { this.prepSMSAlerts(); } public void stop() { Log.getLog().info("Stopping AWS connection"); if (client != null) { try { client.disconnect(); } catch (AWSIotException ex) { Log.getLog().log(Level.SEVERE, "AWS Client disconnect error", ex); } } } private void sendUpdate() { Log.getLog().info(String.format("Sending update to AWS topic '%s'", this.updateTopic)); Reading current = Coordinator.getInstance().getCurrentReading(); ReadingHistory history = Coordinator.getInstance().getCurrentHistory(); String currStr = current == null ? "{}" : Utils.getReadingJson(current); String histStr = history == null ? "{}" : Utils.getHistoryJson(history); StringBuilder sb = new StringBuilder(); sb.append(String.format("{\"state\": {\"reported\": {\"current\": %s, \"history\": %s}}}", currStr, histStr)); //Log.getLog().log(Level.INFO, "Sending JSON: {0}", sb.toString()); WeatherMessage wm = new WeatherMessage(this.updateTopic, AWSIotQos.QOS0, sb.toString()); try { this.client.publish(wm); Log.getLog().info("Update sent to AWS"); } catch (AWSIotException ex) { Log.getLog().log(Level.SEVERE, "AWS Client publish update error", ex); } } public class WeatherMessage extends AWSIotMessage { public WeatherMessage(String topic, AWSIotQos qos, String payload) { super(topic, qos, payload); } @Override public void onSuccess() { Log.getLog().log(Level.INFO, "Publish to AWS succeeded"); } @Override public void onFailure() { Log.getLog().log(Level.SEVERE, "Publish to AWS failed"); } @Override public void onTimeout() { Log.getLog().log(Level.SEVERE, "Publish to AWS timed out"); } } private void prepSMSAlerts() { smsAttributes = new HashMap<>(); smsAttributes.put("AWS.SNS.SMS.SenderID", new MessageAttributeValue() .withStringValue("Weather") //The sender ID shown on the device. .withDataType("String")); smsAttributes.put("AWS.SNS.SMS.MaxPrice", new MessageAttributeValue() .withStringValue("0.10") //Sets the max price to 0.10 USD. .withDataType("Number")); smsAttributes.put("AWS.SNS.SMS.SMSType", new MessageAttributeValue() .withStringValue("Promotional") .withDataType("String")); BasicAWSCredentials cred = new BasicAWSCredentials(Utils .getAppProperties().get(AppProperty.AWS_ACCESS_KEY) ,Utils.getAppProperties().get(AppProperty.AWS_SECRET_KEY)); snsClient = AmazonSNSClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(cred)).build(); // SetSMSAttributesRequest setRequest = new SetSMSAttributesRequest() // .addAttributesEntry("DefaultSenderID", "WeatherSensor") // .addAttributesEntry("MonthlySpendLimit", "1") // .addAttributesEntry("DeliveryStatusIAMRole", // "arn:aws:iam::234513162694:role/SNSSuccessFeedback") // .addAttributesEntry("DeliveryStatusSuccessSamplingRate", "10") // .addAttributesEntry("DefaultSMSType", "Promotional"); // snsClient.setSMSAttributes(setRequest); // Map<String, String> myAttributes = snsClient.getSMSAttributes(new GetSMSAttributesRequest()) // .getAttributes(); // Log.getLog().info("My SMS attributes:"); // for (String key : myAttributes.keySet()) { // System.out.println(key + " = " + myAttributes.get(key)); // } } public void sendSMSMessage(String message,String phoneNumber) { PublishResult result = snsClient.publish(new PublishRequest() .withMessage(message) .withPhoneNumber(phoneNumber) .withMessageAttributes(smsAttributes)); Log.getLog().info(result.toString()); } class UpdateTask extends TimerTask { @Override public void run() { try { sendUpdate(); } catch(Exception e) { Log.getLog().log(Level.SEVERE, String.format("AWS update error: %s",e.getMessage())); } } } public class MyTopic extends AWSIotTopic { public MyTopic(String topic, AWSIotQos qos) { super(topic, qos); } @Override public void onMessage(AWSIotMessage message) { Log.getLog().log(Level.INFO, String.format("AWS Message received- topic: %s, payload: %s", message.getTopic(), message.getStringPayload())); } } public static void main(String[] args) { Utils.config("test.properties"); AwsIotClient client = new AwsIotClient(); client.startSNS(); client.sendSMSMessage("This is a test...", "+9086564206"); } }
apache-2.0
firzhan/custom_message_processor
custom_code/src/main/java/org/apache/synapse/message/custom/processor/impl/CustomForwardingService.java
15470
package org.apache.synapse.message.custom.processor.impl; import org.apache.axiom.om.OMElement; import org.apache.axiom.soap.SOAPEnvelope; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.MessageContext; import org.apache.synapse.SynapseConstants; import org.apache.synapse.SynapseException; import org.apache.synapse.commons.json.JsonUtil; import org.apache.synapse.core.axis2.Axis2MessageContext; import org.apache.synapse.endpoints.Endpoint; import org.apache.synapse.message.MessageConsumer; import org.apache.synapse.message.processor.MessageProcessor; import org.apache.synapse.message.processor.MessageProcessorConstants; import org.apache.synapse.message.processor.impl.forwarder.ForwardingProcessorConstants; import org.apache.synapse.message.processor.impl.forwarder.ForwardingService; import org.apache.synapse.message.processor.impl.forwarder.ScheduledMessageForwardingProcessor; import org.apache.synapse.message.senders.blocking.BlockingMsgSender; import org.apache.synapse.util.MessageHelper; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import java.util.HashSet; import java.util.Map; import java.util.Set; public class CustomForwardingService extends ForwardingService { private static final Log log = LogFactory.getLog(CustomForwardingService.class); private String targetEndpoint = null; /** * These two maintain the state of service. For each iteration these should be reset */ private boolean isSuccessful = false; private volatile boolean isTerminated = false; /** Owner of the this job */ private MessageProcessor messageProcessor; /** The consumer that is associated with the particular message store */ private MessageConsumer messageConsumer; /** * This is specially used for REST scenarios where http status codes can take semantics in a RESTful architecture. */ private String[] nonRetryStatusCodes = null; /** This is the client which sends messages to the end point */ private BlockingMsgSender sender; /** Number of retries before shutting-down the processor. -1 default value indicates that * retry should happen forever */ private int maxDeliverAttempts = -1; private int attemptCount = 0; /** Configuration to continue the message processor even without stopping * the message processor after maximum number of delivery */ private boolean isMaxDeliveryAttemptDropEnabled = false; /** Interval between two retries to the client. This only come to affect only if the client is un-reachable */ private int retryInterval = 1000; /** * Though it says init() it does not instantiate objects every time the service is running. This simply * initialize the local variables with pre-instantiated objects. * @param jobExecutionContext is the Quartz context * @return true if it is successfully executed. */ public boolean init(JobExecutionContext jobExecutionContext) { JobDataMap jdm = jobExecutionContext.getMergedJobDataMap(); Map<String, Object> parameters = (Map<String, Object>) jdm.get(MessageProcessorConstants.PARAMETERS); super.init(jobExecutionContext); if (jdm.get(ForwardingProcessorConstants.TARGET_ENDPOINT) != null) { targetEndpoint = (String) jdm.get(ForwardingProcessorConstants.TARGET_ENDPOINT); } messageProcessor = (MessageProcessor)jdm.get(MessageProcessorConstants.PROCESSOR_INSTANCE); messageConsumer = messageProcessor.getMessageConsumer(); if (jdm.get(ForwardingProcessorConstants.NON_RETRY_STATUS_CODES) != null) { nonRetryStatusCodes = (String []) jdm.get(ForwardingProcessorConstants.NON_RETRY_STATUS_CODES); } sender = (BlockingMsgSender) jdm.get(ScheduledMessageForwardingProcessor.BLOCKING_SENDER); String mdaParam = (String) parameters.get(MessageProcessorConstants.MAX_DELIVER_ATTEMPTS); if (mdaParam != null) { try { maxDeliverAttempts = Integer.parseInt(mdaParam); } catch (NumberFormatException nfe) { parameters.remove(MessageProcessorConstants.MAX_DELIVER_ATTEMPTS); log.error("Invalid value for max delivery attempts switching back to default value", nfe); } } if (parameters.get(ForwardingProcessorConstants.MAX_DELIVERY_DROP)!=null) { if ((parameters.get(ForwardingProcessorConstants.MAX_DELIVERY_DROP)).toString().equals("Enabled")) { if (this.maxDeliverAttempts>0) { isMaxDeliveryAttemptDropEnabled = true; } } } String ri = (String) parameters.get(MessageProcessorConstants.RETRY_INTERVAL); if (ri != null) { try { retryInterval = Integer.parseInt(ri); } catch (NumberFormatException nfe) { parameters.remove(MessageProcessorConstants.RETRY_INTERVAL); log.error("Invalid value for retry interval switching back to default value", nfe); } } return true; } public boolean dispatch(MessageContext messageContext) { if (log.isDebugEnabled()) { log.debug("Sending the message to client with message processor [" + messageProcessor.getName() + "]"); } // The below code is just for keeping the backward compatibility with the old code. if (targetEndpoint == null) { targetEndpoint = (String) messageContext.getProperty(ForwardingProcessorConstants.TARGET_ENDPOINT); } MessageContext outCtx = null; SOAPEnvelope originalEnvelop = messageContext.getEnvelope(); if (targetEndpoint != null) { Endpoint ep = messageContext.getEndpoint(targetEndpoint); try { // Send message to the client while (!isSuccessful && !isTerminated) { try { // For each retry we need to have a fresh copy of the actual message. otherwise retry may not // work as expected. messageContext.setEnvelope(MessageHelper.cloneSOAPEnvelope(originalEnvelop)); OMElement firstChild = null; // org.apache.axis2.context.MessageContext origAxis2Ctx = ((Axis2MessageContext) messageContext).getAxis2MessageContext(); if (JsonUtil.hasAJsonPayload(origAxis2Ctx)) { firstChild = origAxis2Ctx.getEnvelope().getBody().getFirstElement(); } // Had to do this because MessageHelper#cloneSOAPEnvelope does not clone OMSourcedElemImpl correctly. if (JsonUtil.hasAJsonPayload(firstChild)) { // OMElement clonedFirstElement = messageContext.getEnvelope().getBody().getFirstElement(); if (clonedFirstElement != null) { clonedFirstElement.detach(); messageContext.getEnvelope().getBody().addChild(firstChild); } }// Had to do this because MessageHelper#cloneSOAPEnvelope does not clone OMSourcedElemImpl correctly. // Fixing ESBJAVA-3178 origAxis2Ctx.setProperty("non.error.http.status.codes", getNonRetryStatusCodes()); outCtx = sender.send(ep, messageContext); isSuccessful = true; // isSuccessfull is true even session is not available because of avoiding the unwanted retries } catch (Exception e) { // this means send has failed due to some reason so we have to retry it if (e instanceof SynapseException) { isSuccessful = isNonRetryErrorCode(e.getCause().getMessage()); } if (!isSuccessful) { log.error("BlockingMessageSender of message processor ["+ this.messageProcessor.getName() + "] failed to send message to the endpoint"); } } if (isSuccessful) { if (outCtx != null) { if ("true".equals(outCtx. getProperty(ForwardingProcessorConstants.BLOCKING_SENDER_ERROR))) { // this means send has failed due to some reason so we have to retry it isSuccessful = isNonRetryErrorCode( (String) outCtx.getProperty(SynapseConstants.ERROR_MESSAGE)); if (isSuccessful) { sendThroughReplySeq(outCtx); } else { // This means some error has occurred so must try to send down the fault sequence. log.error("BlockingMessageSender of message processor ["+ this.messageProcessor.getName() + "] failed to send message to the endpoint"); sendThroughFaultSeq(outCtx); } } else { // Send the message down the reply sequence if there is one sendThroughReplySeq(outCtx); messageConsumer.ack(); attemptCount = 0; isSuccessful = true; if (log.isDebugEnabled()) { log.debug("Successfully sent the message to endpoint [" + ep.getName() +"]" + " with message processor [" + messageProcessor.getName() + "]"); } } } else { // This Means we have invoked an out only operation // remove the message and reset the count messageConsumer.ack(); attemptCount = 0; isSuccessful = true; if (log.isDebugEnabled()) { log.debug("Successfully sent the message to endpoint [" + ep.getName() +"]" + " with message processor [" + messageProcessor.getName() + "]"); } } } if (!isSuccessful) { prepareToRetry(messageContext); } else { if (messageProcessor.isPaused()) { this.messageProcessor.resumeService(); log.info("Resuming the service of message processor [" + messageProcessor.getName() + "]"); } } } } catch (Exception e) { log.error("Message processor [" + messageProcessor.getName() + "] failed to send the message to" + " client", e); } } else { //No Target Endpoint defined for the Message //So we do not have a place to deliver. //Here we log a warning and remove the message //todo: we can improve this by implementing a target inferring mechanism log.warn("Property " + ForwardingProcessorConstants.TARGET_ENDPOINT + " not found in the message context , Hence removing the message "); messageConsumer.ack(); } return true; } private Set<Integer> getNonRetryStatusCodes() { Set<Integer>nonRetryCodes = new HashSet<Integer>(); if(nonRetryStatusCodes != null){ for (String code : nonRetryStatusCodes) { try { int codeI = Integer.parseInt(code); nonRetryCodes.add(codeI); } catch (NumberFormatException e) {} // ignore the invalid status code } } return nonRetryCodes; } private boolean isNonRetryErrorCode(String errorMsg) { boolean isSuccess = false; if (nonRetryStatusCodes != null) { for (String code : nonRetryStatusCodes) { if (errorMsg != null && errorMsg.contains(code)) { isSuccess = true; break; } } } return isSuccess; } private void prepareToRetry(MessageContext messageContext) { if (!isTerminated) { // First stop the processor since no point in re-triggering jobs if the we can't send // it to the client if (!messageProcessor.isPaused()) { this.messageProcessor.pauseService(); log.info("Pausing the service of message processor [" + messageProcessor.getName() + "]"); } checkAndDeactivateProcessor(attemptCount, maxDeliverAttempts, messageContext); if (log.isDebugEnabled()) { log.debug("Failed to send to client retrying after " + retryInterval + "s with attempt count - " + attemptCount); } try { // wait for some time before retrying Thread.sleep(retryInterval); } catch (InterruptedException ignore) { // No harm even it gets interrupted. So nothing to handle. } } } private void checkAndDeactivateProcessor(int attemptCount, int maxAttempts, MessageContext messageContext) { if (maxAttempts > 0) { this.attemptCount++; if (attemptCount >= maxAttempts) { if (this.isMaxDeliveryAttemptDropEnabled) { continueMessageProcessor(); if (log.isDebugEnabled()) { log.debug("Message processor [" + messageProcessor.getName() + "] Dropped the failed message and continue due to reach of max attempts"); } } else { sendThroughReplySeq(messageContext); continueMessageProcessor(); if (log.isDebugEnabled()) { log.debug("Message processor [" + messageProcessor.getName() + "] stopped due to reach of max attempts"); } } } } } private void continueMessageProcessor(){ messageConsumer.ack(); attemptCount = 0; isSuccessful = true; if (this.messageProcessor.isPaused()) { this.messageProcessor.resumeService(); } log.info("Removed failed message and continue the message processor [" +this.messageProcessor.getName()+"]"); } }
apache-2.0
ogrebgr/forge-server-skeleton-php
hidden/inc/modules/tangra_cms/forms/_ci/ci_attr_type/ci_attr_type_form_ajax_ctrl.class.php
1051
<?php // $Id$ require_once(TANGRA_MAIN_DIR.'web_site/web_page/just_headers_view.class.php'); require_once(DIR_INC.'modules/admin_panel/site_admin_ajax_form_ctrl_with_object_ua.class.php'); require_once(DIR_INC.'modules/tangra_cms/forms/_ci/ci_attr_type/ci_attr_type_form_ctrl.class.php'); class CI_Attr_Type_Form_Ajax_Ctrl extends Site_Admin_Ajax_Form_Ctrl_With_Object_UA { protected function on_good_submit() { $redir = $this->create_redirect_composer('admin/modules/tangra_cms/ci/ci_attr_types.php'); $object = $this->form_ctrl->get_object(); $location = $redir->get_target_address($this->get__context()); $ret = array('command' => Ajax_Ctrl::COMMAND_REDIRECT, 'command_value' => $location); return $ret; } protected function on_bad_submit() { return true; } protected function create_form_ctrl() { $tvm = $this->get_tvm(); $dbc = $this->get_dbc(); $config = $this->get__config(); $ret = new CI_Attr_Type_Form_Ctrl('ci_attr_type', $tvm, $dbc, 'obj_id', $config->get_hidden_dir().'inc/'); return $ret; } }
apache-2.0
jexp/idea2
plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/ClassToBindProperty.java
7075
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.uiDesigner.propertyInspector.properties; import com.intellij.ide.util.TreeClassChooser; import com.intellij.ide.util.TreeClassChooserFactory; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonShortcuts; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.ui.ComponentWithBrowseButton; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.ui.EditorTextField; import com.intellij.uiDesigner.FormEditingUtil; import com.intellij.uiDesigner.UIDesignerBundle; import com.intellij.uiDesigner.propertyInspector.InplaceContext; import com.intellij.uiDesigner.propertyInspector.Property; import com.intellij.uiDesigner.propertyInspector.PropertyEditor; import com.intellij.uiDesigner.propertyInspector.PropertyRenderer; import com.intellij.uiDesigner.propertyInspector.renderers.ClassToBindRenderer; import com.intellij.uiDesigner.radComponents.RadComponent; import com.intellij.uiDesigner.radComponents.RadRootContainer; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * @author Anton Katilin * @author Vladimir Kondratyev */ public final class ClassToBindProperty extends Property<RadRootContainer, String> { private final ClassToBindRenderer myRenderer; private final MyEditor myEditor; public ClassToBindProperty(final Project project) { super(null, "bind to class"); myRenderer = new ClassToBindRenderer(); myEditor = new MyEditor(project); } public PropertyEditor<String> getEditor(){ return myEditor; } @NotNull public PropertyRenderer<String> getRenderer(){ return myRenderer; } public String getValue(final RadRootContainer component) { return component.getClassToBind(); } protected void setValueImpl(final RadRootContainer component, final String value) throws Exception { String className = value; if (className != null && className.length() == 0) { className = null; } component.setClassToBind(className); } private final class MyEditor extends PropertyEditor<String> { private final EditorTextField myEditorTextField; private Document myDocument; private final ComponentWithBrowseButton<EditorTextField> myTfWithButton; private String myInitialValue; private final Project myProject; private final ClassToBindProperty.MyEditor.MyActionListener myActionListener; public MyEditor(final Project project) { myProject = project; myEditorTextField = new EditorTextField("", project, StdFileTypes.JAVA) { protected boolean shouldHaveBorder() { return false; } }; myActionListener = new MyActionListener(); myTfWithButton = new ComponentWithBrowseButton<EditorTextField>(myEditorTextField, myActionListener); myEditorTextField.setBorder(null); new MyCancelEditingAction().registerCustomShortcutSet(CommonShortcuts.ESCAPE, myTfWithButton); /* myEditorTextField.addActionListener( new ActionListener() { public void actionPerformed(final ActionEvent e) { fireValueCommitted(); } } ); */ } public String getValue() throws Exception { final String value = myDocument.getText(); if (value.length() == 0 && myInitialValue == null) { return null; } return value.replace('$', '.'); // PSI works only with dots } public JComponent getComponent(final RadComponent component, final String value, final InplaceContext inplaceContext) { myInitialValue = value; setEditorText(value != null ? value : ""); myActionListener.setModule(component.getModule()); return myTfWithButton; } private void setEditorText(final String s) { final PsiManager manager = PsiManager.getInstance(myProject); final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); PsiPackage defaultPackage = JavaPsiFacade.getInstance(manager.getProject()).findPackage(""); final PsiCodeFragment fragment = factory.createReferenceCodeFragment(s, defaultPackage, true, true); myDocument = PsiDocumentManager.getInstance(manager.getProject()).getDocument(fragment); myEditorTextField.setDocument(myDocument); } public void updateUI() { SwingUtilities.updateComponentTreeUI(myTfWithButton); } private final class MyActionListener implements ActionListener{ private Module myModule; public void setModule(final Module module) { myModule = module; } public void actionPerformed(final ActionEvent e){ final String className = myEditorTextField.getText(); final PsiClass aClass = FormEditingUtil.findClassToBind(myModule, className); final Project project = myModule.getProject(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); final TreeClassChooser chooser = TreeClassChooserFactory.getInstance(project).createWithInnerClassesScopeChooser( UIDesignerBundle.message("title.choose.class.to.bind"), GlobalSearchScope.projectScope(project), new TreeClassChooser.ClassFilter() { // we need show classes from the sources roots only public boolean isAccepted(final PsiClass aClass) { final VirtualFile vFile = aClass.getContainingFile().getVirtualFile(); return vFile != null && fileIndex.isInSource(vFile); } }, aClass ); chooser.showDialog(); final PsiClass result = chooser.getSelectedClass(); if (result != null) { setEditorText(result.getQualifiedName()); } myEditorTextField.requestFocus(); // todo[anton] make it via providing proper parent } } private final class MyCancelEditingAction extends AnAction{ public void actionPerformed(final AnActionEvent e) { fireEditingCancelled(); } } } }
apache-2.0
stdlib-js/stdlib
lib/node_modules/@stdlib/process/read-stdin/docs/types/index.d.ts
2408
/* * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib 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. */ // TypeScript Version: 2.0 /// <reference types="node"/> import { Buffer } from 'buffer'; /** * Callback invoked upon reading all data from `stdin`. * * @param err - error object * @param data - data contents */ type Callback = ( err: Error | null, data: Buffer | string ) => void; /** * Interface for reading from `stdin`. */ interface StdIn { /** * Reads data from `stdin`. * * @param encoding - string encoding. If set, data will be returned as an encoded `string` * @param clbk - callback to be invoked upon reading all data from `stdin` * * @example * function onRead( error, data ) { * if ( error ) { * throw error; * } * console.log( data ); * // => '...' * } * * stdin( 'utf8', onRead ); */ ( encoding: string | null, clbk: Callback ): void; // tslint-disable-line max-line-length /** * Reads data from `stdin`. * * @param clbk - callback to be invoked upon reading all data from `stdin` * * @example * function onRead( error, data ) { * if ( error ) { * throw error; * } * console.log( data.toString() ); * // => '...' * } * * stdin( onRead ); */ ( clbk: Callback ): void; } /** * Reads data from `stdin`. * * @param encoding - string encoding. If set, data will be returned as an encoded `string` * @param clbk - callback to be invoked upon reading all data from `stdin` * * @example * function onRead( error, data ) { * if ( error ) { * throw error; * } * console.log( data.toString() ); * // => '...' * } * * stdin( onRead ); * * @example * function onRead( error, data ) { * if ( error ) { * throw error; * } * console.log( data ); * // => '...' * } * * stdin( 'utf8', onRead ); */ declare var stdin: StdIn; // EXPORTS // export = stdin;
apache-2.0
bernhardhuber/kisoonlineapp
kisoonlineapp-csv/src/main/java/org/kisoonlineapp/kisoonlineapp/csv/ArchivKisoVeranstaltungOutputTemplate.java
3328
/* * 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 org.kisoonlineapp.kisoonlineapp.csv; import java.io.PrintWriter; import org.apache.commons.csv.CSVRecord; /** * * @author berni */ class ArchivKisoVeranstaltungOutputTemplate extends AbstractOutputTemplate { private final PrintWriter pw; String tableName = "CSV_ARCHIV_VERANSTALTUNGEN"; private final FieldInfo[] fieldInfos = new FieldInfo[]{ new FieldInfo.Builder().name("Id").quoting(false).build(), new FieldInfo.Builder().name("Status").defaultValue("Buchbar").build(), new FieldInfo.Builder().name("Code").build(), new FieldInfo.Builder().name("Name").build(), new FieldInfo.Builder().name("Beginndatum").build(), new FieldInfo.Builder().name("Endedatum").build(), new FieldInfo.Builder().name("Beginnuhrzeit").fixTime(true).build(), new FieldInfo.Builder().name("Endeuhrzeit").fixTime(true).build(), new FieldInfo.Builder().name("Beschreibung").build(), new FieldInfo.Builder().name("Treffpunkt").build(), new FieldInfo.Builder().name("GemeindeName").build(), new FieldInfo.Builder().name("GemeindePostleitzahl").build(), new FieldInfo.Builder().name("GemeindeKoordinaten").build(), new FieldInfo.Builder().name("Leitung").build(), new FieldInfo.Builder().name("TeilnehmerAlterAb").quoting(false).build(), new FieldInfo.Builder().name("TeilnehmerAlterBis").quoting(false).build(), new FieldInfo.Builder().name("TeilnehmeranzahlMax").quoting(false).build(), new FieldInfo.Builder().name("TeilnehmerAnzahlMin").quoting(false).build(), new FieldInfo.Builder().name("TeilnehmerHinweis").build(), new FieldInfo.Builder().name("Kosten").quoting(false).build(), new FieldInfo.Builder().name("KostenHinweis").build() }; ArchivKisoVeranstaltungOutputTemplate(PrintWriter pw) { this.pw = pw; } @Override public void outputCsvRecord(CSVRecord csvRecord) { outputPrefix(); outputData(csvRecord); outputSuffix(); } @Override protected void outputPrefix() { pw.print("INSERT INTO " + tableName + " ("); final int len = fieldInfos.length; for (int i = 0; i < len; i++) { final FieldInfo fi = fieldInfos[i]; final String fieldName = fi.name; pw.print(fieldName); outputOptionalComma(i, len); } pw.print(") VALUES ("); } @Override protected void outputData(CSVRecord csvRecord) { final int len = fieldInfos.length; for (int i = 0; i < len; i++) { final FieldInfo fi = fieldInfos[i]; final String fieldName = fi.name; final String value = csvRecord.get(fieldName); final String formattedValue = fi.formatValue(value); pw.print(formattedValue); outputOptionalComma(i, len); } } @Override protected void outputSuffix() { pw.println(");"); } protected void outputOptionalComma(int i, int len) { if (i < len - 1) { pw.print(", "); } } }
apache-2.0
StefH/WireMock.Net
src/WireMock.Net/RegularExpressions/RegexExtended.cs
3297
using System; using System.Collections.Generic; using System.Text.RegularExpressions; using Stef.Validation; namespace WireMock.RegularExpressions { /// <summary> /// Extension to the <see cref="Regex"/> object, adding support for GUID tokens for matching on. /// </summary> #if !NETSTANDARD1_3 [Serializable] #endif internal class RegexExtended : Regex { /// <inheritdoc cref="Regex"/> public RegexExtended(string pattern) : this(pattern, RegexOptions.None) { } /// <inheritdoc cref="Regex"/> public RegexExtended(string pattern, RegexOptions options) : this(pattern, options, Regex.InfiniteMatchTimeout) { } /// <inheritdoc cref="Regex"/> public RegexExtended(string pattern, RegexOptions options, TimeSpan matchTimeout) : base(ReplaceGuidPattern(pattern), options, matchTimeout) { } #if !NETSTANDARD1_3 /// <inheritdoc cref="Regex"/> protected RegexExtended(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif // Dictionary of various Guid tokens with a corresponding regular expression pattern to use instead. private static readonly Dictionary<string, string> GuidTokenPatterns = new Dictionary<string, string> { // Lower case format `B` Guid pattern { @"\guidb", @"(\{[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}\})" }, // Upper case format `B` Guid pattern { @"\GUIDB", @"(\{[A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}\})" }, // Lower case format `D` Guid pattern { @"\guidd", "([a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12})" }, // Upper case format `D` Guid pattern { @"\GUIDD", "([A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12})" }, // Lower case format `N` Guid pattern { @"\guidn", "([a-z0-9]{32})" }, // Upper case format `N` Guid pattern { @"\GUIDN", "([A-Z0-9]{32})" }, // Lower case format `P` Guid pattern { @"\guidp", @"(\([a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}\))" }, // Upper case format `P` Guid pattern { @"\GUIDP", @"(\([A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}\))" }, // Lower case format `X` Guid pattern { @"\guidx", @"(\{0x[a-f0-9]{8},0x[a-f0-9]{4},0x[a-f0-9]{4},\{(0x[a-f0-9]{2},){7}(0x[a-f0-9]{2})\}\})" }, // Upper case format `X` Guid pattern { @"\GUIDX", @"(\{0x[A-F0-9]{8},0x[A-F0-9]{4},0x[A-F0-9]{4},\{(0x[A-F0-9]{2},){7}(0x[A-F0-9]{2})\}\})" }, }; /// <summary> /// Replaces all instances of valid GUID tokens with the correct regular expression to match. /// </summary> /// <param name="pattern">Pattern to replace token for.</param> private static string ReplaceGuidPattern(string pattern) { Guard.NotNull(pattern, nameof(pattern)); foreach (var tokenPattern in GuidTokenPatterns) { pattern = pattern.Replace(tokenPattern.Key, tokenPattern.Value); } return pattern; } } }
apache-2.0
vivantech/kc_fixes
src/main/java/org/kuali/kra/award/home/AwardService.java
3209
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * 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.kuali.kra.award.home; import org.kuali.kra.award.document.AwardDocument; import org.kuali.kra.bo.versioning.VersionStatus; import org.kuali.kra.service.VersionException; import org.kuali.rice.kew.api.exception.WorkflowException; import java.util.List; /** * * This class intends to provide basic business service behavior * and accessors for Awards. */ public interface AwardService { /** * Get the Award based upon its unique id number. * * @param awardId the Award's unique id number * @return the Award or null if not found. * * @deprecated The identifier for Award is a Long, but this method expects a String */ public Award getAward(String awardId); /** * Get the Award based upon its unique id number. * * @param awardId * @return */ public Award getAward(Long awardId); /** * This method finds all Awards for the specified awardNumber * @param awardId * @return The list of Awards */ public List<Award> findAwardsForAwardNumber(String awardNumber); /** * Create new version of the award document * @param awardDocument * @return * @throws VersionException */ public AwardDocument createNewAwardVersion(AwardDocument awardDocument) throws VersionException, WorkflowException; /** * Update the award to use the new VersionStatus. If the version status is ACTIVE, any other active version of this * award will be set to ARCHIVED. * @param award * @param status */ void updateAwardSequenceStatus(Award award, VersionStatus status); // ### Vivantech Fix : #31 / [#84250170] rename method to better reflect functionality /** * Returns the newest non-cancelled award. * @param awardNumber * @return */ public Award getNewestAward(String awardNumber); /** * Returns the active award or if none exist, the newest non-cancelled award. * @param awardNumber * @return */ public Award getActiveOrNewestAward(String awardNumber); /** * This method is to synch custom attributes. During copy process only existing custom attributes * available in the old document is copied. We need to make sure we have all the latest custom attributes * tied to the new document. * @param newAward * @param oldAward */ public void synchNewCustomAttributes(Award newAward, Award oldAward); public Award getAwardAssociatedWithDocument(String docNumber); }
apache-2.0
epam/DLab
services/self-service/src/main/resources/webapp/src/app/core/services/managementEnvironments.service.ts
2080
/*************************************************************************** Copyright (c) 2016, EPAM SYSTEMS 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. ****************************************************************************/ import { Injectable } from '@angular/core'; import { Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { ApplicationServiceFacade } from './'; @Injectable() export class ManageEnvironmentsService { constructor(private applicationServiceFacade: ApplicationServiceFacade) {} getAllEnvironmentData(): Observable<Response> { return this.applicationServiceFacade .buildGetAllEnvironmentData() .map(response => response.json()) .catch((error: any) => { return Observable.throw( new Error( `{"status": "${error.status}", "statusText": "${error.statusText}", "message": "${ error._body }"}` ) ); }); } environmentManagement(data, action: string, resource: string, computational?: string): Observable<{} | Response> { const params = computational ? `/${action}/${resource}/${computational}` : `/${action}/${resource}`; return this.applicationServiceFacade .buildEnvironmentManagement(params, data) .map((response: Response) => response) .catch((error: any) => { return Observable.throw( new Error( `{"status": "${error.status}", "statusText": "${error.statusText}", "message": "${ error._body }"}` ) ); }); } }
apache-2.0
cmu-db/dbms-library
dbdb/core/forms.py
9094
# stdlib imports # django imports from django import forms from django.conf import settings from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from django.forms import widgets from django.forms.fields import MultipleChoiceField from django.forms.widgets import Textarea # third-party imports from nocaptcha_recaptcha.fields import NoReCaptchaField from nocaptcha_recaptcha.widgets import NoReCaptchaWidget # project imports from dbdb.core.models import CitationUrl from dbdb.core.models import Feature from dbdb.core.models import FeatureOption from dbdb.core.models import System from dbdb.core.models import SystemVersion from dbdb.core.models import SystemVersionMetadata # widgets class InvisibleReCaptchaWidget(NoReCaptchaWidget): template = getattr(settings, 'INVISIBLE_RECAPTCHA_WIDGET_TEMPLATE', 'nocaptcha_recaptcha/widget.html') # fields class TagFieldM2M(MultipleChoiceField): widget = forms.TextInput(attrs={'data-role': 'tagsinput', 'placeholder': ''}) def prepare_value(self, value): try: return ','.join([x.url for x in value]) except (AttributeError, TypeError): if value is not None: return value.split(',') return '' def clean(self, value): if value: urls = value.split(',') else: urls = [] url_objs = [] for url in urls: cit_url, _ = CitationUrl.objects.get_or_create(url=url) url_objs.append(cit_url) return url_objs pass # forms class SystemFeaturesForm(forms.Form): def __init__(self, *args, **kwargs): try: features = kwargs.pop('features') except KeyError: features = [] super(SystemFeaturesForm, self).__init__(*args, **kwargs) initial = {} for feature in features: o = feature.options.values_list('value', flat=True) if len(o) > 1: o = list(o) elif len(o) == 1: o = o[0] else: o = None initial[feature.feature.label] = { 'options': o, 'description': feature.description, 'citations': ','.join(feature.citations.values_list('url', flat=True)) } pass features = Feature.objects.all() self.features = [] for feature in features: initial_value = None if feature.multivalued: if feature.label in initial: initial_value = initial[feature.label]['options'] self.fields[feature.label+'_choices'] = forms.MultipleChoiceField( choices=( (x, x) for x in FeatureOption.objects.filter(feature=feature).order_by('value') ), initial=initial_value, required=False ) pass else: if feature.label in initial: initial_value = initial[feature.label]['options'] self.fields[feature.label+'_choices'] = forms.ChoiceField( choices=( (x, x) for x in FeatureOption.objects.filter(feature=feature).order_by('value') ), initial=initial_value, required=False ) pass initial_desc = None initial_cit = None if feature.label in initial: initial_desc = initial[feature.label]['description'] initial_cit = initial[feature.label]['citations'] pass self.fields[feature.label+'_description'] = forms.CharField( label='Description', help_text="This field supports Markdown Syntax", widget=widgets.Textarea(), initial=initial_desc, required=False ) self.fields[feature.label+'_citation'] = forms.CharField( label='Citations', help_text="Separate the urls with commas", widget=widgets.TextInput(attrs={'data-role': 'tagsinput', 'placeholder': ''}), initial=initial_cit, required=False ) self.fields[feature.label+'_choices'].feature_id = feature.id self.fields[feature.label+'_description'].feature_id = feature.id self.fields[feature.label+'_citation'].feature_id = feature.id pass return pass # model forms class CreateUserForm(forms.ModelForm): email = forms.EmailField(max_length=254, required=True) password = forms.CharField(max_length=128, label='Password', widget=widgets.PasswordInput) password2 = forms.CharField(max_length=128, label='Password Confirmation', widget=widgets.PasswordInput) captcha = NoReCaptchaField( gtag_attrs={ 'callback': 'onCaptchaSubmit', # name of JavaScript callback function 'bind': 'btn_submit' # submit button's ID in the form template }, widget=InvisibleReCaptchaWidget ) def __init__(self, *args, **kwargs): super(CreateUserForm, self).__init__(*args, **kwargs) self.initial_email = None initial = getattr(self, 'initial', None) if initial and 'email' in initial and initial['email']: self.initial_email = initial['email'] self.fields['email'].widget.attrs['readonly'] = True pass return def clean_email(self): if self.initial_email: return self.initial_email return self.cleaned_data['email'] def clean_password2(self): if self.cleaned_data['password2'] == self.cleaned_data['password']: return self.cleaned_data['password2'] raise ValidationError("The passwords do not match") class Meta: model = get_user_model() fields = ['username', 'email', 'password', 'password2', 'captcha'] pass class SystemForm(forms.ModelForm): # This is only shown to non-superusers orig_name = forms.CharField(max_length=128, label="Name", disabled=True, required=False) class Meta: model = System fields = ['name','orig_name'] pass class SystemVersionEditForm(forms.ModelForm): description_citations = TagFieldM2M( help_text="Separate the urls with commas", required=False ) history_citations = TagFieldM2M( help_text="Separate the urls with commas", required=False ) start_year_citations = TagFieldM2M( help_text="Separate the urls with commas", required=False ) end_year_citations = TagFieldM2M( help_text="Separate the urls with commas", required=False ) acquired_by_citations = TagFieldM2M( help_text="Separate the urls with commas", required=False ) class Meta: model = SystemVersion fields = [ 'logo', 'description', 'description_citations', 'history', 'history_citations', 'url', 'source_url', 'tech_docs', 'wikipedia_url', 'developer', 'start_year', 'start_year_citations', 'end_year', 'end_year_citations', 'acquired_by', 'acquired_by_citations', 'project_types', 'countries', 'former_names', 'comment' ] pass class SystemVersionForm(forms.ModelForm): description_citations = TagFieldM2M( help_text="Separate the urls with commas", required=False ) history_citations = TagFieldM2M( help_text="Separate the urls with commas", required=False ) start_year_citations = TagFieldM2M( help_text="Separate the urls with commas", required=False ) end_year_citations = TagFieldM2M( help_text="Separate the urls with commas", required=False ) acquired_by_citations = TagFieldM2M( help_text="Separate the urls with commas", required=False ) class Meta: model = SystemVersion fields = [ 'logo', 'description', 'description_citations', 'history', 'history_citations', 'url', 'source_url', 'tech_docs', 'wikipedia_url', 'developer', 'start_year', 'start_year_citations', 'end_year', 'end_year_citations', 'acquired_by', 'acquired_by_citations', 'project_types', 'countries', 'former_names', ] pass class SystemVersionMetadataForm(forms.ModelForm): class Meta: model = SystemVersionMetadata exclude = ['system'] pass
apache-2.0
shs96c/buck
src/com/facebook/buck/apple/toolchain/impl/AppleCxxPlatforms.java
24975
/* * Copyright 2014-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.apple.toolchain.impl; import com.dd.plist.NSDictionary; import com.dd.plist.NSObject; import com.dd.plist.NSString; import com.dd.plist.PropertyListFormatException; import com.dd.plist.PropertyListParser; import com.facebook.buck.apple.AppleConfig; import com.facebook.buck.apple.toolchain.AppleCxxPlatform; import com.facebook.buck.apple.toolchain.ApplePlatform; import com.facebook.buck.apple.toolchain.AppleSdk; import com.facebook.buck.apple.toolchain.AppleSdkPaths; import com.facebook.buck.apple.toolchain.AppleToolchain; import com.facebook.buck.core.config.BuckConfig; import com.facebook.buck.core.exceptions.HumanReadableException; import com.facebook.buck.core.model.Flavor; import com.facebook.buck.core.model.UserFlavor; import com.facebook.buck.core.sourcepath.PathSourcePath; import com.facebook.buck.core.toolchain.tool.Tool; import com.facebook.buck.core.toolchain.tool.impl.VersionedTool; import com.facebook.buck.core.toolchain.toolprovider.impl.ConstantToolProvider; import com.facebook.buck.core.util.log.Logger; import com.facebook.buck.cxx.toolchain.ArchiverProvider; import com.facebook.buck.cxx.toolchain.BsdArchiver; import com.facebook.buck.cxx.toolchain.CompilerProvider; import com.facebook.buck.cxx.toolchain.CxxBuckConfig; import com.facebook.buck.cxx.toolchain.CxxPlatform; import com.facebook.buck.cxx.toolchain.CxxPlatforms; import com.facebook.buck.cxx.toolchain.CxxToolProvider; import com.facebook.buck.cxx.toolchain.DebugPathSanitizer; import com.facebook.buck.cxx.toolchain.HeaderVerification; import com.facebook.buck.cxx.toolchain.MungingDebugPathSanitizer; import com.facebook.buck.cxx.toolchain.PicType; import com.facebook.buck.cxx.toolchain.PosixNmSymbolNameTool; import com.facebook.buck.cxx.toolchain.PrefixMapDebugPathSanitizer; import com.facebook.buck.cxx.toolchain.PreprocessorProvider; import com.facebook.buck.cxx.toolchain.linker.DefaultLinkerProvider; import com.facebook.buck.cxx.toolchain.linker.LinkerProvider; import com.facebook.buck.cxx.toolchain.linker.Linkers; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.swift.toolchain.SwiftPlatform; import com.facebook.buck.swift.toolchain.impl.SwiftPlatformFactory; import com.facebook.buck.util.Optionals; import com.facebook.buck.util.environment.Platform; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.regex.Pattern; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /** * Utility class to create Objective-C/C/C++/Objective-C++ platforms to support building iOS and Mac * OS X products with Xcode. */ public class AppleCxxPlatforms { private static final Logger LOG = Logger.get(AppleCxxPlatforms.class); // Utility class, do not instantiate. private AppleCxxPlatforms() {} private static final String USR_BIN = "usr/bin"; public static ImmutableList<AppleCxxPlatform> buildAppleCxxPlatforms( Optional<ImmutableMap<AppleSdk, AppleSdkPaths>> sdkPaths, Optional<ImmutableMap<String, AppleToolchain>> toolchains, ProjectFilesystem filesystem, BuckConfig buckConfig) { if (!sdkPaths.isPresent() || !toolchains.isPresent()) { return ImmutableList.of(); } AppleConfig appleConfig = buckConfig.getView(AppleConfig.class); ImmutableList.Builder<AppleCxxPlatform> appleCxxPlatformsBuilder = ImmutableList.builder(); XcodeToolFinder xcodeToolFinder = new XcodeToolFinder(appleConfig); XcodeBuildVersionCache xcodeBuildVersionCache = new XcodeBuildVersionCache(); sdkPaths .get() .forEach( (sdk, appleSdkPaths) -> { String targetSdkVersion = appleConfig.getTargetSdkVersion(sdk.getApplePlatform()).orElse(sdk.getVersion()); LOG.debug("SDK %s using default version %s", sdk, targetSdkVersion); for (String architecture : sdk.getArchitectures()) { appleCxxPlatformsBuilder.add( buildWithXcodeToolFinder( filesystem, sdk, targetSdkVersion, architecture, appleSdkPaths, buckConfig, xcodeToolFinder, xcodeBuildVersionCache)); } }); return appleCxxPlatformsBuilder.build(); } private static Tool getXcodeTool( ProjectFilesystem filesystem, ImmutableList<Path> toolSearchPaths, XcodeToolFinder xcodeToolFinder, AppleConfig appleConfig, String toolName, String toolVersion) { return VersionedTool.builder() .setPath( PathSourcePath.of(filesystem, getToolPath(toolName, toolSearchPaths, xcodeToolFinder))) .setName(Joiner.on('-').join(ImmutableList.of("apple", toolName))) .setVersion(appleConfig.getXcodeToolVersion(toolName, toolVersion)) .build(); } @VisibleForTesting public static AppleCxxPlatform buildWithXcodeToolFinder( ProjectFilesystem filesystem, AppleSdk targetSdk, String minVersion, String targetArchitecture, AppleSdkPaths sdkPaths, BuckConfig buckConfig, XcodeToolFinder xcodeToolFinder, XcodeBuildVersionCache xcodeBuildVersionCache) { AppleCxxPlatform.Builder platformBuilder = AppleCxxPlatform.builder(); ImmutableList.Builder<Path> toolSearchPathsBuilder = ImmutableList.builder(); // Search for tools from most specific to least specific. toolSearchPathsBuilder .add(sdkPaths.getSdkPath().resolve(USR_BIN)) .add(sdkPaths.getSdkPath().resolve("Developer").resolve(USR_BIN)) .add(sdkPaths.getPlatformPath().resolve("Developer").resolve(USR_BIN)); for (Path toolchainPath : sdkPaths.getToolchainPaths()) { toolSearchPathsBuilder.add(toolchainPath.resolve(USR_BIN)); } if (sdkPaths.getDeveloperPath().isPresent()) { toolSearchPathsBuilder.add(sdkPaths.getDeveloperPath().get().resolve(USR_BIN)); toolSearchPathsBuilder.add(sdkPaths.getDeveloperPath().get().resolve("Tools")); } // TODO(beng): Add more and better cflags. ImmutableList.Builder<String> cflagsBuilder = ImmutableList.builder(); cflagsBuilder.add("-isysroot", sdkPaths.getSdkPath().toString()); cflagsBuilder.add("-arch", targetArchitecture); cflagsBuilder.add(targetSdk.getApplePlatform().getMinVersionFlagPrefix() + minVersion); if (targetSdk.getApplePlatform().equals(ApplePlatform.WATCHOS)) { cflagsBuilder.add("-fembed-bitcode"); } AppleConfig appleConfig = buckConfig.getView(AppleConfig.class); ImmutableList.Builder<String> ldflagsBuilder = ImmutableList.builder(); ldflagsBuilder.addAll(Linkers.iXlinker("-sdk_version", targetSdk.getVersion())); if (appleConfig.linkAllObjC()) { ldflagsBuilder.addAll(Linkers.iXlinker("-ObjC")); } if (targetSdk.getApplePlatform().equals(ApplePlatform.WATCHOS)) { ldflagsBuilder.addAll(Linkers.iXlinker("-bitcode_verify")); } // Populate Xcode version keys from Xcode's own Info.plist if available. Optional<String> xcodeBuildVersion = Optional.empty(); Optional<Path> developerPath = sdkPaths.getDeveloperPath(); if (developerPath.isPresent()) { Path xcodeBundlePath = developerPath.get().getParent(); if (xcodeBundlePath != null) { Path xcodeInfoPlistPath = xcodeBundlePath.resolve("Info.plist"); try (InputStream stream = Files.newInputStream(xcodeInfoPlistPath)) { NSDictionary parsedXcodeInfoPlist = (NSDictionary) PropertyListParser.parse(stream); NSObject xcodeVersionObject = parsedXcodeInfoPlist.objectForKey("DTXcode"); if (xcodeVersionObject != null) { Optional<String> xcodeVersion = Optional.of(xcodeVersionObject.toString()); platformBuilder.setXcodeVersion(xcodeVersion); } } catch (IOException e) { LOG.warn( "Error reading Xcode's info plist %s; ignoring Xcode versions", xcodeInfoPlistPath); } catch (PropertyListFormatException | ParseException | ParserConfigurationException | SAXException e) { LOG.warn("Error in parsing %s; ignoring Xcode versions", xcodeInfoPlistPath); } } xcodeBuildVersion = xcodeBuildVersionCache.lookup(developerPath.get()); platformBuilder.setXcodeBuildVersion(xcodeBuildVersion); LOG.debug("Xcode build version is: " + xcodeBuildVersion.orElse("<absent>")); } ImmutableList.Builder<String> versions = ImmutableList.builder(); versions.add(targetSdk.getVersion()); ImmutableList<String> toolchainVersions = targetSdk .getToolchains() .stream() .map(AppleToolchain::getVersion) .flatMap(Optionals::toStream) .collect(ImmutableList.toImmutableList()); if (toolchainVersions.isEmpty()) { if (!xcodeBuildVersion.isPresent()) { throw new HumanReadableException("Failed to read toolchain versions and Xcode version."); } versions.add(xcodeBuildVersion.get()); } else { versions.addAll(toolchainVersions); } String version = Joiner.on(':').join(versions.build()); ImmutableList<Path> toolSearchPaths = toolSearchPathsBuilder.build(); Tool clangPath = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "clang", version); Tool clangXxPath = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "clang++", version); Tool ar = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "ar", version); Tool ranlib = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "ranlib", version); Tool strip = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "strip", version); Tool nm = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "nm", version); Tool actool = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "actool", version); Tool ibtool = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "ibtool", version); Tool momc = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "momc", version); Tool xctest = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "xctest", version); Tool dsymutil = getXcodeTool( filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "dsymutil", version); Tool lipo = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "lipo", version); Tool lldb = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "lldb", version); Optional<Path> stubBinaryPath = targetSdk .getApplePlatform() .getStubBinaryPath() .map(input -> sdkPaths.getSdkPath().resolve(input)); CxxBuckConfig config = new CxxBuckConfig(buckConfig); UserFlavor targetFlavor = UserFlavor.of( Flavor.replaceInvalidCharacters(targetSdk.getName() + "-" + targetArchitecture), String.format("SDK: %s, architecture: %s", targetSdk.getName(), targetArchitecture)); ImmutableBiMap.Builder<Path, String> sanitizerPaths = ImmutableBiMap.builder(); sanitizerPaths.put(sdkPaths.getSdkPath(), "APPLE_SDKROOT"); sanitizerPaths.put(sdkPaths.getPlatformPath(), "APPLE_PLATFORM_DIR"); if (sdkPaths.getDeveloperPath().isPresent()) { sanitizerPaths.put(sdkPaths.getDeveloperPath().get(), "APPLE_DEVELOPER_DIR"); } // https://github.com/facebook/buck/pull/1168: add the root cell's absolute path to the quote // include path, and also force it to be sanitized by all user rule keys. sanitizerPaths.put(filesystem.getRootPath(), "."); cflagsBuilder.add("-iquote", filesystem.getRootPath().toString()); DebugPathSanitizer compilerDebugPathSanitizer = new PrefixMapDebugPathSanitizer( DebugPathSanitizer.getPaddedDir( ".", config.getDebugPathSanitizerLimit(), File.separatorChar), sanitizerPaths.build()); DebugPathSanitizer assemblerDebugPathSanitizer = new MungingDebugPathSanitizer( config.getDebugPathSanitizerLimit(), File.separatorChar, Paths.get("."), sanitizerPaths.build()); ImmutableList<String> cflags = cflagsBuilder.build(); ImmutableMap.Builder<String, String> macrosBuilder = ImmutableMap.builder(); macrosBuilder.put("SDKROOT", sdkPaths.getSdkPath().toString()); macrosBuilder.put("PLATFORM_DIR", sdkPaths.getPlatformPath().toString()); macrosBuilder.put("CURRENT_ARCH", targetArchitecture); if (sdkPaths.getDeveloperPath().isPresent()) { macrosBuilder.put("DEVELOPER_DIR", sdkPaths.getDeveloperPath().get().toString()); } ImmutableMap<String, String> macros = macrosBuilder.build(); Optional<String> buildVersion = Optional.empty(); Path platformVersionPlistPath = sdkPaths.getPlatformPath().resolve("version.plist"); try (InputStream versionPlist = Files.newInputStream(platformVersionPlistPath)) { NSDictionary versionInfo = (NSDictionary) PropertyListParser.parse(versionPlist); if (versionInfo != null) { NSObject productBuildVersion = versionInfo.objectForKey("ProductBuildVersion"); if (productBuildVersion != null) { buildVersion = Optional.of(productBuildVersion.toString()); } else { LOG.warn( "In %s, missing ProductBuildVersion. Build version will be unset for this platform.", platformVersionPlistPath); } } else { LOG.warn( "Empty version plist in %s. Build version will be unset for this platform.", platformVersionPlistPath); } } catch (NoSuchFileException e) { LOG.warn( "%s does not exist. Build version will be unset for this platform.", platformVersionPlistPath); } catch (PropertyListFormatException | SAXException | ParserConfigurationException | ParseException | IOException e) { // Some other error occurred, print the exception since it may contain error details. LOG.warn( e, "Failed to parse %s. Build version will be unset for this platform.", platformVersionPlistPath); } PreprocessorProvider aspp = new PreprocessorProvider(new ConstantToolProvider(clangPath), CxxToolProvider.Type.CLANG); CompilerProvider as = new CompilerProvider(new ConstantToolProvider(clangPath), CxxToolProvider.Type.CLANG); PreprocessorProvider cpp = new PreprocessorProvider(new ConstantToolProvider(clangPath), CxxToolProvider.Type.CLANG); CompilerProvider cc = new CompilerProvider(new ConstantToolProvider(clangPath), CxxToolProvider.Type.CLANG); PreprocessorProvider cxxpp = new PreprocessorProvider(new ConstantToolProvider(clangXxPath), CxxToolProvider.Type.CLANG); CompilerProvider cxx = new CompilerProvider(new ConstantToolProvider(clangXxPath), CxxToolProvider.Type.CLANG); ImmutableList.Builder<String> whitelistBuilder = ImmutableList.builder(); whitelistBuilder.add("^" + Pattern.quote(sdkPaths.getSdkPath().toString()) + "\\/.*"); whitelistBuilder.add( "^" + Pattern.quote(sdkPaths.getPlatformPath() + "/Developer/Library/Frameworks") + "\\/.*"); for (Path toolchainPath : sdkPaths.getToolchainPaths()) { LOG.debug("Apple toolchain path: %s", toolchainPath); try { whitelistBuilder.add("^" + Pattern.quote(toolchainPath.toRealPath().toString()) + "\\/.*"); } catch (IOException e) { LOG.warn(e, "Apple toolchain path could not be resolved: %s", toolchainPath); } } HeaderVerification headerVerification = config.getHeaderVerificationOrIgnore().withPlatformWhitelist(whitelistBuilder.build()); LOG.debug( "Headers verification platform whitelist: %s", headerVerification.getPlatformWhitelist()); CxxPlatform cxxPlatform = CxxPlatforms.build( targetFlavor, Platform.MACOS, config, as, aspp, cc, cxx, cpp, cxxpp, new DefaultLinkerProvider( LinkerProvider.Type.DARWIN, new ConstantToolProvider(clangXxPath)), ImmutableList.<String>builder().addAll(cflags).addAll(ldflagsBuilder.build()).build(), strip, ArchiverProvider.from(new BsdArchiver(ar)), Optional.of(new ConstantToolProvider(ranlib)), new PosixNmSymbolNameTool(nm), cflagsBuilder.build(), ImmutableList.of(), cflags, ImmutableList.of(), "dylib", "%s.dylib", "a", "o", compilerDebugPathSanitizer, assemblerDebugPathSanitizer, macros, Optional.empty(), headerVerification, PicType.PIC); ApplePlatform applePlatform = targetSdk.getApplePlatform(); ImmutableList.Builder<Path> swiftOverrideSearchPathBuilder = ImmutableList.builder(); AppleSdkPaths.Builder swiftSdkPathsBuilder = AppleSdkPaths.builder().from(sdkPaths); Optional<SwiftPlatform> swiftPlatform = getSwiftPlatform( applePlatform.getName(), targetArchitecture + "-apple-" + applePlatform.getSwiftName().orElse(applePlatform.getName()) + minVersion, version, swiftSdkPathsBuilder.build(), swiftOverrideSearchPathBuilder.addAll(toolSearchPaths).build(), xcodeToolFinder, filesystem); platformBuilder .setCxxPlatform(cxxPlatform) .setSwiftPlatform(swiftPlatform) .setAppleSdk(targetSdk) .setAppleSdkPaths(sdkPaths) .setMinVersion(minVersion) .setBuildVersion(buildVersion) .setActool(actool) .setIbtool(ibtool) .setMomc(momc) .setCopySceneKitAssets( getOptionalTool( "copySceneKitAssets", toolSearchPaths, xcodeToolFinder, version, filesystem)) .setXctest(xctest) .setDsymutil(dsymutil) .setLipo(lipo) .setStubBinary(stubBinaryPath) .setLldb(lldb) .setCodesignAllocate( getOptionalTool( "codesign_allocate", toolSearchPaths, xcodeToolFinder, version, filesystem)) .setCodesignProvider(appleConfig.getCodesignProvider()); return platformBuilder.build(); } private static Optional<SwiftPlatform> getSwiftPlatform( String platformName, String targetArchitectureName, String version, AppleSdkPaths sdkPaths, ImmutableList<Path> toolSearchPaths, XcodeToolFinder xcodeToolFinder, ProjectFilesystem filesystem) { ImmutableList<String> swiftParams = ImmutableList.of( "-frontend", "-sdk", sdkPaths.getSdkPath().toString(), "-target", targetArchitectureName); ImmutableList.Builder<String> swiftStdlibToolParamsBuilder = ImmutableList.builder(); swiftStdlibToolParamsBuilder .add("--copy") .add("--verbose") .add("--strip-bitcode") .add("--platform") .add(platformName); for (Path toolchainPath : sdkPaths.getToolchainPaths()) { swiftStdlibToolParamsBuilder.add("--toolchain").add(toolchainPath.toString()); } Optional<Tool> swiftc = getOptionalToolWithParams( "swiftc", toolSearchPaths, xcodeToolFinder, version, swiftParams, filesystem); Optional<Tool> swiftStdLibTool = getOptionalToolWithParams( "swift-stdlib-tool", toolSearchPaths, xcodeToolFinder, version, swiftStdlibToolParamsBuilder.build(), filesystem); if (swiftc.isPresent()) { return Optional.of( SwiftPlatformFactory.build( platformName, sdkPaths.getToolchainPaths(), swiftc.get(), swiftStdLibTool)); } else { return Optional.empty(); } } private static Optional<Tool> getOptionalTool( String tool, ImmutableList<Path> toolSearchPaths, XcodeToolFinder xcodeToolFinder, String version, ProjectFilesystem filesystem) { return getOptionalToolWithParams( tool, toolSearchPaths, xcodeToolFinder, version, ImmutableList.of(), filesystem); } private static Optional<Tool> getOptionalToolWithParams( String tool, ImmutableList<Path> toolSearchPaths, XcodeToolFinder xcodeToolFinder, String version, ImmutableList<String> params, ProjectFilesystem filesystem) { return xcodeToolFinder .getToolPath(toolSearchPaths, tool) .map( input -> VersionedTool.builder() .setPath(PathSourcePath.of(filesystem, input)) .setName(tool) .setVersion(version) .setExtraArgs(params) .build()); } private static Path getToolPath( String tool, ImmutableList<Path> toolSearchPaths, XcodeToolFinder xcodeToolFinder) { Optional<Path> result = xcodeToolFinder.getToolPath(toolSearchPaths, tool); if (!result.isPresent()) { throw new HumanReadableException("Cannot find tool %s in paths %s", tool, toolSearchPaths); } return result.get(); } @VisibleForTesting public static class XcodeBuildVersionCache { private final Map<Path, Optional<String>> cache = new HashMap<>(); /** * Returns the Xcode build version. This is an alphanumeric string as output by {@code * xcodebuild -version} and shown in the About Xcode window. This value is embedded into the * plist of app bundles built by Xcode, under the field named {@code DTXcodeBuild} * * @param developerDir Path to developer dir, i.e. /Applications/Xcode.app/Contents/Developer * @return the xcode build version if found, nothing if it fails to be found, or the version * plist file cannot be read. */ protected Optional<String> lookup(Path developerDir) { return cache.computeIfAbsent( developerDir, ignored -> { Path versionPlist = developerDir.getParent().resolve("version.plist"); NSString result; try { NSDictionary dict = (NSDictionary) PropertyListParser.parse(Files.readAllBytes(versionPlist)); result = (NSString) dict.get("ProductBuildVersion"); } catch (IOException | ClassCastException | SAXException | PropertyListFormatException | ParseException e) { LOG.warn( e, "%s: Cannot find xcode build version, file is in an invalid format.", versionPlist); return Optional.empty(); } catch (ParserConfigurationException e) { throw new IllegalStateException("plist parser threw unexpected exception", e); } if (result != null) { return Optional.of(result.toString()); } else { LOG.warn( "%s: Cannot find xcode build version, file is in an invalid format.", versionPlist); return Optional.empty(); } }); } } }
apache-2.0
cheerx/qingstor-sdk-scala
src/test/scala/com/qingstor/sdk/util/QSRequestUtilTest.scala
2170
package com.qingstor.sdk.util import java.io.File import akka.http.scaladsl.model.ContentTypes import com.qingstor.sdk.annotation.ParamAnnotation import com.qingstor.sdk.util.QSRequestUtilTest.{TestGetRequestParam, TestGetResponseParams} import org.scalatest.FunSuite class QSRequestUtilTest extends FunSuite{ test("Test getRequestParams") { val maps = QSRequestUtil.getRequestParams(TestGetRequestParam("abc", true), "headers") val shouldResult = Map[String, AnyRef]("Foo" -> "abc", "Bar" -> "true") assert(maps == shouldResult) assertThrows[NoSuchElementException](maps("Baz")) } test("Test getResponseParams") { val headers = QSRequestUtil.getResponseParams(new TestGetResponseParams(), "headers") val elements = QSRequestUtil.getResponseParams(new TestGetResponseParams(), "elements") assert(headers == Map("Foo" -> "getFoo")) assert(elements == Map("Bar" -> "getBar")) } test("Test invokeMethod") { val t = new TestGetResponseParams() QSRequestUtil.invokeMethod(t, "setBar", Array("abc")) assert(t.getBar == "abc") } test("Test parseContentType") { val jpgFile = new File("/tmp/test.jpg") assert(QSRequestUtil.parseContentType(jpgFile).toString() == "image/jpeg") val octFile = new File("/tmp/test") assert(QSRequestUtil.parseContentType(octFile) == ContentTypes.`application/octet-stream`) } } object QSRequestUtilTest { case class TestGetRequestParam(foo: String, bar: Boolean = false, baz: Option[Int] = None) { @ParamAnnotation(location = "headers", name = "Foo") def getFoo: String = this.foo @ParamAnnotation(location = "headers", name = "Bar") def getBar: Boolean = this.bar @ParamAnnotation(location = "headers", name = "Baz") def getBaz: Option[Int] = this.baz } class TestGetResponseParams { private var foo: Int = _ private var bar: String = _ def setFoo(n: Int): Unit = this.foo = n def setBar(str: String): Unit = this.bar = str @ParamAnnotation(location = "headers", name = "Foo") def getFoo: Int = this.foo @ParamAnnotation(location = "elements", name = "Bar") def getBar: String = this.bar } }
apache-2.0
sacloud/libsacloud
v2/helper/service/enhanceddb/delete_request.go
930
// Copyright 2016-2022 The Libsacloud 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 enhanceddb import ( "github.com/sacloud/libsacloud/v2/helper/validate" "github.com/sacloud/libsacloud/v2/sacloud/types" ) type DeleteRequest struct { ID types.ID `request:"-" validate:"required"` FailIfNotFound bool `request:"-"` } func (req *DeleteRequest) Validate() error { return validate.Struct(req) }
apache-2.0
ChristopherMacGown/pynpoint
pynpoint/providers/darwin/uptime.py
1457
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2011 Christopher MacGown. 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. import datetime import re import time from pynpoint import providers __module__ = str.join('.', (__package__, "uptime")) # todo(chris): Make this work when pynpoint is daemonized. UPTIME_RE = re.compile("kern.boottime:.*\s+(?P<uptime_secs>\d+),") m = UPTIME_RE.search(providers.command("sysctl", "kern.boottime")) UPTIME = int(m.group("uptime_secs")) CURR_TIME = time.time() @providers.provides(provider=__module__) def uptime_secs(): """Exposes the number of seconds the box has been up.""" return int(CURR_TIME - UPTIME) @providers.provides(provider=__module__) def uptime(): """Exposes the current uptime of the box in human readable format.""" cur_dt = datetime.datetime.fromtimestamp(CURR_TIME) upt_dt = datetime.datetime.fromtimestamp(UPTIME) return str(cur_dt - upt_dt)
apache-2.0
111pontes/ydk-py
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_isis_act.py
23584
""" Cisco_IOS_XR_isis_act This module contains a collection of YANG definitions for Cisco IOS\-XR ISIS action package configuration. Copyright (c) 2016 by Cisco Systems, Inc. All rights reserved. """ import re import collections from enum import Enum from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict from ydk.errors import YPYError, YPYModelError class ClearIsisProcessRpc(object): """ Clear all IS\-IS data structures .. attribute:: input **type**\: :py:class:`Input <ydk.models.cisco_ios_xr.Cisco_IOS_XR_isis_act.ClearIsisProcessRpc.Input>` """ _prefix = 'isis-act' _revision = '2016-06-30' def __init__(self): self.input = ClearIsisProcessRpc.Input() self.input.parent = self self.is_rpc = True class Input(object): """ .. attribute:: instance Clear data from single IS\-IS instance **type**\: :py:class:`Instance <ydk.models.cisco_ios_xr.Cisco_IOS_XR_isis_act.ClearIsisProcessRpc.Input.Instance>` .. attribute:: process Clear all IS\-IS data structures **type**\: :py:class:`Empty<ydk.types.Empty>` """ _prefix = 'isis-act' _revision = '2016-06-30' def __init__(self): self.parent = None self.instance = ClearIsisProcessRpc.Input.Instance() self.instance.parent = self self.process = None class Instance(object): """ Clear data from single IS\-IS instance .. attribute:: instance_identifier IS\-IS process instance identifier **type**\: str """ _prefix = 'isis-act' _revision = '2016-06-30' def __init__(self): self.parent = None self.instance_identifier = None @property def _common_path(self): return '/Cisco-IOS-XR-isis-act:clear-isis-process/Cisco-IOS-XR-isis-act:input/Cisco-IOS-XR-isis-act:instance' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' if self.parent is None: raise YPYError('Parent reference is needed to determine if entity has configuration data') return self.parent.is_config() def _has_data(self): if self.instance_identifier is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_isis_act as meta return meta._meta_table['ClearIsisProcessRpc.Input.Instance']['meta_info'] @property def _common_path(self): return '/Cisco-IOS-XR-isis-act:clear-isis-process/Cisco-IOS-XR-isis-act:input' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' if self.parent is None: raise YPYError('Parent reference is needed to determine if entity has configuration data') return self.parent.is_config() def _has_data(self): if self.instance is not None and self.instance._has_data(): return True if self.process is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_isis_act as meta return meta._meta_table['ClearIsisProcessRpc.Input']['meta_info'] @property def _common_path(self): return '/Cisco-IOS-XR-isis-act:clear-isis-process' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if self.input is not None and self.input._has_data(): return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_isis_act as meta return meta._meta_table['ClearIsisProcessRpc']['meta_info'] class ClearIsisRouteRpc(object): """ Clear IS\-IS routes .. attribute:: input **type**\: :py:class:`Input <ydk.models.cisco_ios_xr.Cisco_IOS_XR_isis_act.ClearIsisRouteRpc.Input>` """ _prefix = 'isis-act' _revision = '2016-06-30' def __init__(self): self.input = ClearIsisRouteRpc.Input() self.input.parent = self self.is_rpc = True class Input(object): """ .. attribute:: instance Clear data from single IS\-IS instance **type**\: :py:class:`Instance <ydk.models.cisco_ios_xr.Cisco_IOS_XR_isis_act.ClearIsisRouteRpc.Input.Instance>` .. attribute:: route Clear IS\-IS routes **type**\: :py:class:`Empty<ydk.types.Empty>` """ _prefix = 'isis-act' _revision = '2016-06-30' def __init__(self): self.parent = None self.instance = ClearIsisRouteRpc.Input.Instance() self.instance.parent = self self.route = None class Instance(object): """ Clear data from single IS\-IS instance .. attribute:: instance_identifier IS\-IS process instance identifier **type**\: str """ _prefix = 'isis-act' _revision = '2016-06-30' def __init__(self): self.parent = None self.instance_identifier = None @property def _common_path(self): return '/Cisco-IOS-XR-isis-act:clear-isis-route/Cisco-IOS-XR-isis-act:input/Cisco-IOS-XR-isis-act:instance' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' if self.parent is None: raise YPYError('Parent reference is needed to determine if entity has configuration data') return self.parent.is_config() def _has_data(self): if self.instance_identifier is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_isis_act as meta return meta._meta_table['ClearIsisRouteRpc.Input.Instance']['meta_info'] @property def _common_path(self): return '/Cisco-IOS-XR-isis-act:clear-isis-route/Cisco-IOS-XR-isis-act:input' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' if self.parent is None: raise YPYError('Parent reference is needed to determine if entity has configuration data') return self.parent.is_config() def _has_data(self): if self.instance is not None and self.instance._has_data(): return True if self.route is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_isis_act as meta return meta._meta_table['ClearIsisRouteRpc.Input']['meta_info'] @property def _common_path(self): return '/Cisco-IOS-XR-isis-act:clear-isis-route' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if self.input is not None and self.input._has_data(): return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_isis_act as meta return meta._meta_table['ClearIsisRouteRpc']['meta_info'] class ClearIsisStatRpc(object): """ Clear IS\-IS protocol statistics .. attribute:: input **type**\: :py:class:`Input <ydk.models.cisco_ios_xr.Cisco_IOS_XR_isis_act.ClearIsisStatRpc.Input>` """ _prefix = 'isis-act' _revision = '2016-06-30' def __init__(self): self.input = ClearIsisStatRpc.Input() self.input.parent = self self.is_rpc = True class Input(object): """ .. attribute:: instance Clear data from single IS\-IS instance **type**\: :py:class:`Instance <ydk.models.cisco_ios_xr.Cisco_IOS_XR_isis_act.ClearIsisStatRpc.Input.Instance>` .. attribute:: statistics Clear IS\-IS protocol statistics **type**\: :py:class:`Statistics <ydk.models.cisco_ios_xr.Cisco_IOS_XR_isis_act.ClearIsisStatRpc.Input.Statistics>` """ _prefix = 'isis-act' _revision = '2016-06-30' def __init__(self): self.parent = None self.instance = ClearIsisStatRpc.Input.Instance() self.instance.parent = self self.statistics = ClearIsisStatRpc.Input.Statistics() self.statistics.parent = self class Instance(object): """ Clear data from single IS\-IS instance .. attribute:: instance_identifier IS\-IS process instance identifier **type**\: str """ _prefix = 'isis-act' _revision = '2016-06-30' def __init__(self): self.parent = None self.instance_identifier = None @property def _common_path(self): return '/Cisco-IOS-XR-isis-act:clear-isis-stat/Cisco-IOS-XR-isis-act:input/Cisco-IOS-XR-isis-act:instance' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' if self.parent is None: raise YPYError('Parent reference is needed to determine if entity has configuration data') return self.parent.is_config() def _has_data(self): if self.instance_identifier is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_isis_act as meta return meta._meta_table['ClearIsisStatRpc.Input.Instance']['meta_info'] class Statistics(object): """ Clear IS\-IS protocol statistics .. attribute:: interface_name Interface name **type**\: str **pattern:** (([a\-zA\-Z0\-9\_]\*\\d+/){3,4}\\d+)\|(([a\-zA\-Z0\-9\_]\*\\d+/){3,4}\\d+\\.\\d+)\|(([a\-zA\-Z0\-9\_]\*\\d+/){2}([a\-zA\-Z0\-9\_]\*\\d+))\|(([a\-zA\-Z0\-9\_]\*\\d+/){2}([a\-zA\-Z0\-9\_]+))\|([a\-zA\-Z0\-9\_\-]\*\\d+)\|([a\-zA\-Z0\-9\_\-]\*\\d+\\.\\d+)\|(mpls)\|(dwdm) **mandatory**\: True """ _prefix = 'isis-act' _revision = '2016-06-30' def __init__(self): self.parent = None self.interface_name = None @property def _common_path(self): return '/Cisco-IOS-XR-isis-act:clear-isis-stat/Cisco-IOS-XR-isis-act:input/Cisco-IOS-XR-isis-act:statistics' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' if self.parent is None: raise YPYError('Parent reference is needed to determine if entity has configuration data') return self.parent.is_config() def _has_data(self): if self.interface_name is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_isis_act as meta return meta._meta_table['ClearIsisStatRpc.Input.Statistics']['meta_info'] @property def _common_path(self): return '/Cisco-IOS-XR-isis-act:clear-isis-stat/Cisco-IOS-XR-isis-act:input' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' if self.parent is None: raise YPYError('Parent reference is needed to determine if entity has configuration data') return self.parent.is_config() def _has_data(self): if self.instance is not None and self.instance._has_data(): return True if self.statistics is not None and self.statistics._has_data(): return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_isis_act as meta return meta._meta_table['ClearIsisStatRpc.Input']['meta_info'] @property def _common_path(self): return '/Cisco-IOS-XR-isis-act:clear-isis-stat' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if self.input is not None and self.input._has_data(): return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_isis_act as meta return meta._meta_table['ClearIsisStatRpc']['meta_info'] class ClearIsisDistRpc(object): """ Reset BGP\-LS topology distribution .. attribute:: input **type**\: :py:class:`Input <ydk.models.cisco_ios_xr.Cisco_IOS_XR_isis_act.ClearIsisDistRpc.Input>` """ _prefix = 'isis-act' _revision = '2016-06-30' def __init__(self): self.input = ClearIsisDistRpc.Input() self.input.parent = self self.is_rpc = True class Input(object): """ .. attribute:: distribution Reset BGP\-LS topology distribution **type**\: :py:class:`Empty<ydk.types.Empty>` .. attribute:: instance Reset BGP\-LS topology from single IS\-IS instance **type**\: :py:class:`Instance <ydk.models.cisco_ios_xr.Cisco_IOS_XR_isis_act.ClearIsisDistRpc.Input.Instance>` """ _prefix = 'isis-act' _revision = '2016-06-30' def __init__(self): self.parent = None self.distribution = None self.instance = ClearIsisDistRpc.Input.Instance() self.instance.parent = self class Instance(object): """ Reset BGP\-LS topology from single IS\-IS instance .. attribute:: instance_identifier IS\-IS process instance identifier **type**\: str """ _prefix = 'isis-act' _revision = '2016-06-30' def __init__(self): self.parent = None self.instance_identifier = None @property def _common_path(self): return '/Cisco-IOS-XR-isis-act:clear-isis-dist/Cisco-IOS-XR-isis-act:input/Cisco-IOS-XR-isis-act:instance' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' if self.parent is None: raise YPYError('Parent reference is needed to determine if entity has configuration data') return self.parent.is_config() def _has_data(self): if self.instance_identifier is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_isis_act as meta return meta._meta_table['ClearIsisDistRpc.Input.Instance']['meta_info'] @property def _common_path(self): return '/Cisco-IOS-XR-isis-act:clear-isis-dist/Cisco-IOS-XR-isis-act:input' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' if self.parent is None: raise YPYError('Parent reference is needed to determine if entity has configuration data') return self.parent.is_config() def _has_data(self): if self.distribution is not None: return True if self.instance is not None and self.instance._has_data(): return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_isis_act as meta return meta._meta_table['ClearIsisDistRpc.Input']['meta_info'] @property def _common_path(self): return '/Cisco-IOS-XR-isis-act:clear-isis-dist' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if self.input is not None and self.input._has_data(): return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_isis_act as meta return meta._meta_table['ClearIsisDistRpc']['meta_info'] class ClearIsisRpc(object): """ Clear IS\-IS data structures .. attribute:: input **type**\: :py:class:`Input <ydk.models.cisco_ios_xr.Cisco_IOS_XR_isis_act.ClearIsisRpc.Input>` """ _prefix = 'isis-act' _revision = '2016-06-30' def __init__(self): self.input = ClearIsisRpc.Input() self.input.parent = self self.is_rpc = True class Input(object): """ .. attribute:: instance Clear data from single IS\-IS instance **type**\: :py:class:`Instance <ydk.models.cisco_ios_xr.Cisco_IOS_XR_isis_act.ClearIsisRpc.Input.Instance>` .. attribute:: route Clear IS\-IS routes **type**\: :py:class:`Empty<ydk.types.Empty>` .. attribute:: rt_type Clear data for these route types **type**\: :py:class:`RtTypeEnum <ydk.models.cisco_ios_xr.Cisco_IOS_XR_isis_act.ClearIsisRpc.Input.RtTypeEnum>` .. attribute:: topology Topology table information **type**\: str """ _prefix = 'isis-act' _revision = '2016-06-30' def __init__(self): self.parent = None self.instance = ClearIsisRpc.Input.Instance() self.instance.parent = self self.route = None self.rt_type = None self.topology = None class RtTypeEnum(Enum): """ RtTypeEnum Clear data for these route types .. data:: AFI_ALL_MULTICAST = 0 .. data:: AFI_ALL_SAFI_ALL = 1 .. data:: AFI_ALL_UNICAST = 2 .. data:: IPv4_MULTICAST = 3 .. data:: IPv4_SAFI_ALL = 4 .. data:: IPv4_UNICAST = 5 .. data:: IPv6_MULTICAST = 6 .. data:: IPv6_SAFI_ALL = 7 .. data:: IPv6_UNICAST = 8 """ AFI_ALL_MULTICAST = 0 AFI_ALL_SAFI_ALL = 1 AFI_ALL_UNICAST = 2 IPv4_MULTICAST = 3 IPv4_SAFI_ALL = 4 IPv4_UNICAST = 5 IPv6_MULTICAST = 6 IPv6_SAFI_ALL = 7 IPv6_UNICAST = 8 @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_isis_act as meta return meta._meta_table['ClearIsisRpc.Input.RtTypeEnum'] class Instance(object): """ Clear data from single IS\-IS instance .. attribute:: instance_identifier IS\-IS process instance identifier **type**\: str """ _prefix = 'isis-act' _revision = '2016-06-30' def __init__(self): self.parent = None self.instance_identifier = None @property def _common_path(self): return '/Cisco-IOS-XR-isis-act:clear-isis/Cisco-IOS-XR-isis-act:input/Cisco-IOS-XR-isis-act:instance' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' if self.parent is None: raise YPYError('Parent reference is needed to determine if entity has configuration data') return self.parent.is_config() def _has_data(self): if self.instance_identifier is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_isis_act as meta return meta._meta_table['ClearIsisRpc.Input.Instance']['meta_info'] @property def _common_path(self): return '/Cisco-IOS-XR-isis-act:clear-isis/Cisco-IOS-XR-isis-act:input' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' if self.parent is None: raise YPYError('Parent reference is needed to determine if entity has configuration data') return self.parent.is_config() def _has_data(self): if self.instance is not None and self.instance._has_data(): return True if self.route is not None: return True if self.rt_type is not None: return True if self.topology is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_isis_act as meta return meta._meta_table['ClearIsisRpc.Input']['meta_info'] @property def _common_path(self): return '/Cisco-IOS-XR-isis-act:clear-isis' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if self.input is not None and self.input._has_data(): return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_isis_act as meta return meta._meta_table['ClearIsisRpc']['meta_info']
apache-2.0
towavephone/MemoryCleaner
app/src/main/java/edu/wkd/towave/memorycleaner/mvp/presenters/impl/fragment/SettingPresenter.java
4362
package edu.wkd.towave.memorycleaner.mvp.presenters.impl.fragment; import android.content.Context; import android.os.Bundle; import android.preference.Preference; import android.support.annotation.StringRes; import android.text.TextUtils; import edu.wkd.towave.memorycleaner.R; import edu.wkd.towave.memorycleaner.injector.ContextLifeCycle; import edu.wkd.towave.memorycleaner.mvp.presenters.Presenter; import edu.wkd.towave.memorycleaner.mvp.presenters.impl.activity.MainPresenter; import edu.wkd.towave.memorycleaner.mvp.views.View; import edu.wkd.towave.memorycleaner.mvp.views.impl.fragment.SettingView; import edu.wkd.towave.memorycleaner.tools.PreferenceUtils; import edu.wkd.towave.memorycleaner.tools.ThemeUtils; import javax.inject.Inject; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; /** * Created by Administrator on 2016/5/5. */ public class SettingPresenter implements Presenter { private SettingView mSettingView; private final Context mContext; private boolean isShowStartActivity = false; private PreferenceUtils mPreferenceUtils; private MainPresenter.NotifyEvent<Void> event; @Inject public SettingPresenter(@ContextLifeCycle("Activity") Context context, PreferenceUtils mPreferenceUtils) { this.mContext = context; this.mPreferenceUtils = mPreferenceUtils; } @Override public void onCreate(Bundle savedInstanceState) { mSettingView.findPreference(); initPreference(); EventBus.getDefault().register(this); } void initPreference() { isShowStartActivity = mPreferenceUtils.getBooleanParam( getString(mContext, R.string.show_start_activity_key)); mSettingView.setShowStartActivityChecked(isShowStartActivity); } @Override public void onResume() { } public boolean onPreferenceTreeClick(Preference preference) { if (mSettingView.isResume() && preference == null) { return false; } String key = preference.getKey(); if (TextUtils.equals(key, getString(mContext, R.string.show_start_activity_key))) { isShowStartActivity = !isShowStartActivity; mPreferenceUtils.saveParam( getString(mContext, R.string.show_start_activity_key), isShowStartActivity); } if (TextUtils.equals(key, getString(mContext, R.string.change_theme_key))) { mSettingView.showThemeChooseDialog(); } return false; } public void onViewCreated(android.view.View v) { mSettingView.initPreferenceListView(v); } private String getString(Context context, @StringRes int string) { if (context != null) return context.getString(string); return ""; } @Override public void onStart() { //EventBus.getDefault().register(this); } @Override public void onPause() { } @Override public void onStop() { //EventBus.getDefault().unregister(this); } @Subscribe public void onEventMainThread(Boolean result) { //handleLoginResult(result); } @Override public void onDestroy() { if (event != null && event.getType() != MainPresenter.NotifyEvent.CHANGE_THEME) { EventBus.getDefault().post(event); } EventBus.getDefault().unregister(this); } public void onThemeChoose(int position) { int value = ThemeUtils.getCurrentTheme(mContext).getIntValue(); if (value != position) { mPreferenceUtils.saveParam( getString(mContext, R.string.change_theme_key), position); notifyChangeTheme(); } } private void notifyChangeTheme() { if (event == null) { event = new MainPresenter.NotifyEvent<>(); } event.setType(MainPresenter.NotifyEvent.CHANGE_THEME); //post change theme event immediately EventBus.getDefault().post(event); mSettingView.reload(); } @Override public void attachView(View v) { mSettingView = (SettingView) v; } }
apache-2.0
yu757371316/MySQL
user_manager/backend/neo-usermgr-mybatis-dao/src/test/java/com/neo/usermgr/mybatis/service/UnionQuerySqlServiceTest.java
29848
/** * File Name : UnionQuerySqlServiceTest * Creator : 20160701688 * Created Date : 2017/04/11 * Comment : */ package com.neo.usermgr.mybatis.service; import com.neo.usermgr.common.def.AuthorityDef; import com.neo.usermgr.common.def.UmUserDef; import com.neo.usermgr.common.model.*; import com.neo.usermgr.mybatis.common.SpringTestCaseBase; import com.neo.usermgr.mybatis.model.AuthorityColumn; import com.neo.usermgr.mybatis.model.UmUserColumn; import com.neo.usermgr.mybatis.service.itf.UnionQuerySqlServiceI; import com.neo.usermgr.mybatis.service.itf.UnitTestSqlServiceI; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; import java.util.Date; import java.util.List; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class UnionQuerySqlServiceTest extends SpringTestCaseBase { @Autowired private UnitTestSqlServiceI unitTestSqlServiceImpl; @Autowired private UnionQuerySqlServiceI unionQuerySqlServiceImpl; private Authority newAuthority() { Authority authority = new Authority(); authority.setId(1); authority.setName("用户管理"); authority.setSiteId(1); authority.setPath("/accountRecharge"); authority.setContent("用户管理权限"); authority.setTitle("用户管理权限"); authority.setType(1); return authority; } private void insertAuthority(){ Authority authority = newAuthority(); unitTestSqlServiceImpl.insertAuthorityForUnitTest(authority); authority = newAuthority(); authority.setId(2); authority.setName("authorityTest2"); authority.setSiteId(3); unitTestSqlServiceImpl.insertAuthorityForUnitTest(authority); authority = newAuthority(); authority.setId(3); authority.setName("authorityTest3"); unitTestSqlServiceImpl.insertAuthorityForUnitTest(authority); } private UmUser newUmUser(){ UmUser umUser = new UmUser(); umUser.setId("1"); umUser.setUserName("umUserTest1"); umUser.setNickName("NK"); umUser.setPassword("c33367701511b4f6020ec61ded352059"); umUser.setEmail("duan.zhizi@neoway.com"); umUser.setPhone("13728934123"); umUser.setCompanyId(1); umUser.setParentId("40288256537d270b01538281f8b40000"); umUser.setStatus(UmUserDef.UmUserStatus.EmailUnVerify.getIndex()); umUser.setRole(UmUserDef.UmUserRole.User.getIndex()); umUser.setDateCreate(new Date()); return umUser; } private void insertUmUser(){ UmUser umUser = newUmUser(); unitTestSqlServiceImpl.insertUmUserForUnitTest(umUser); umUser = newUmUser(); umUser.setId("2"); umUser.setUserName("umUserTest2"); unitTestSqlServiceImpl.insertUmUserForUnitTest(umUser); umUser = newUmUser(); umUser.setId("3"); umUser.setUserName("umUserTest3"); unitTestSqlServiceImpl.insertUmUserForUnitTest(umUser); } private AuthGroup newAuthGroup(){ AuthGroup authGroup = new AuthGroup(); authGroup.setId(1); authGroup.setName("authGroupTest1"); authGroup.setCreator("1"); return authGroup; } private void insertAuthGroup(){ AuthGroup authGroup = newAuthGroup(); unitTestSqlServiceImpl.insertAuthGroupForUnitTest(authGroup); authGroup = newAuthGroup(); authGroup.setId(2); authGroup.setName("authGroupTest2"); unitTestSqlServiceImpl.insertAuthGroupForUnitTest(authGroup); authGroup = newAuthGroup(); authGroup.setId(3); authGroup.setName("authGroupTest3"); unitTestSqlServiceImpl.insertAuthGroupForUnitTest(authGroup); } private AuthGroupAuthority newAuthGroupAuthority(){ AuthGroupAuthority authGroupAuthority = new AuthGroupAuthority(); authGroupAuthority.setId(1); authGroupAuthority.setAuthorityId(1); authGroupAuthority.setGroupId(1); return authGroupAuthority; } private void insertAuthGroupAuthority(){ AuthGroupAuthority authGroupAuthority = newAuthGroupAuthority(); unitTestSqlServiceImpl.insertAuthGroupAuthorityForUnitTest(authGroupAuthority); authGroupAuthority = newAuthGroupAuthority(); authGroupAuthority.setId(2); authGroupAuthority.setGroupId(2); authGroupAuthority.setAuthorityId(1); unitTestSqlServiceImpl.insertAuthGroupAuthorityForUnitTest(authGroupAuthority); authGroupAuthority = newAuthGroupAuthority(); authGroupAuthority.setId(3); authGroupAuthority.setGroupId(3); authGroupAuthority.setAuthorityId(2); unitTestSqlServiceImpl.insertAuthGroupAuthorityForUnitTest(authGroupAuthority); } private AuthGroupUser newAuthGroupUser(){ AuthGroupUser authGroupUser = new AuthGroupUser(); authGroupUser.setId(1); authGroupUser.setGroupId(1); authGroupUser.setUserId("1"); return authGroupUser; } private void insertAuthGroupUser(){ AuthGroupUser authGroupUser = newAuthGroupUser(); unitTestSqlServiceImpl.insertAuthGroupUserForUnitTest(authGroupUser); authGroupUser = newAuthGroupUser(); authGroupUser.setId(2); authGroupUser.setGroupId(2); authGroupUser.setUserId("2"); unitTestSqlServiceImpl.insertAuthGroupUserForUnitTest(authGroupUser); authGroupUser = newAuthGroupUser(); authGroupUser.setId(3); authGroupUser.setGroupId(3); authGroupUser.setUserId("2"); unitTestSqlServiceImpl.insertAuthGroupUserForUnitTest(authGroupUser); } private Organize newOrganize(){ Organize organize = new Organize(); organize.setId(1); organize.setCreator("1"); organize.setOrganizeParent(0); organize.setName("organizeTest1"); return organize; } private void insertOrganize(){ Organize organize = newOrganize(); unitTestSqlServiceImpl.insertOrganizeForUnitTest(organize); organize = newOrganize(); organize.setId(2); organize.setName("organizeTest2"); unitTestSqlServiceImpl.insertOrganizeForUnitTest(organize); organize = newOrganize(); organize.setId(3); organize.setName("organizeTest3"); unitTestSqlServiceImpl.insertOrganizeForUnitTest(organize); } private OrganizeUser newOrganizeUser(){ OrganizeUser organizeUser = new OrganizeUser(); organizeUser.setId(1); organizeUser.setUserId("1"); organizeUser.setOrganizeId(1); return organizeUser; } private void insertOrganizeUser(){ OrganizeUser organizeUser = newOrganizeUser(); unitTestSqlServiceImpl.insertOrganizeUserForUnitTest(organizeUser); organizeUser = newOrganizeUser(); organizeUser.setId(2); organizeUser.setUserId("2"); organizeUser.setOrganizeId(2); unitTestSqlServiceImpl.insertOrganizeUserForUnitTest(organizeUser); organizeUser = newOrganizeUser(); organizeUser.setId(3); organizeUser.setUserId("3"); organizeUser.setOrganizeId(2); unitTestSqlServiceImpl.insertOrganizeUserForUnitTest(organizeUser); organizeUser = newOrganizeUser(); organizeUser.setId(4); organizeUser.setUserId("3"); organizeUser.setOrganizeId(3); unitTestSqlServiceImpl.insertOrganizeUserForUnitTest(organizeUser); } @Override public void setUp() { } @Override public void tearDown() { logger.debug("delete authGroupUser"); unitTestSqlServiceImpl.deleteAuthGroupUserForUnitTest(); logger.debug("delete authGroupAuthority"); unitTestSqlServiceImpl.deleteAuthGroupAuthorityForUnitTest(); logger.debug("delete organizeUser"); unitTestSqlServiceImpl.deleteOrganizeUserForUnitTest(); logger.debug("delete organize"); unitTestSqlServiceImpl.deleteOrganizeForUnitTest(); logger.debug("delete authGroup"); unitTestSqlServiceImpl.deleteAuthGroupForUnitTest(); logger.debug("delete umUser"); unitTestSqlServiceImpl.deleteUmUserForUnitTest(); logger.debug("delete authority"); unitTestSqlServiceImpl.deleteAuthorityForUnitTest(); } @Test public void test_queryAuthGroupListWithCondition_ReturnAuthGroupList_WhenAllIsNull(){ insertAuthGroup(); logger.debug(" test queryAuthGroupListWithCondition"); String creator = "1"; String authName = null; String groupName = null; String userName = null; int offset = 0; int count = 100; List<AuthGroup> authGroupList = unionQuerySqlServiceImpl. queryAuthGroupListWithCondition(creator, authName,groupName,userName,offset,count); logger.debug("authGroupList:{}",authGroupList); assertTrue(authGroupList.size() == 3); } @Test public void test_queryAuthGroupListWithCondition_ReturnAuthGroupList_ByGroupName(){ insertAuthGroup(); logger.debug(" test queryAuthGroupListWithCondition"); String creator = "1"; String authName = null; String groupName = "authGroupTest1"; String userName = null; int offset = 0; int count = 100; List<AuthGroup> authGroupList = unionQuerySqlServiceImpl. queryAuthGroupListWithCondition(creator,authName,groupName,userName,offset,count); logger.debug("authGroupList:{}",authGroupList); assertTrue(authGroupList.size() == 1); } @Test public void test_queryAuthGroupListWithCondition_ReturnAuthGroupList_ByAuthName(){ insertAuthority(); insertAuthGroup(); insertAuthGroupAuthority(); logger.debug(" test queryAuthGroupListWithCondition"); String creator = "1"; String authName = "authorityTest1"; String groupName = null; String userName = null; int offset = 1; int count = 2; List<AuthGroup> authGroupList = unionQuerySqlServiceImpl. queryAuthGroupListWithCondition(creator, authName,groupName,userName,offset,count); logger.debug("authGroupList:{}",authGroupList); assertTrue(authGroupList.size() == 1); } @Test public void test_queryAuthGroupListWithCondition_ReturnAuthGroupList_ByUserName(){ insertUmUser(); insertAuthGroup(); insertAuthGroupUser(); logger.debug(" test queryAuthGroupListWithCondition"); String creator = "1"; String authName = null; String groupName = null; String userName = "umUserTest2"; int offset = 0; int count = 10; List<AuthGroup> authGroupList = unionQuerySqlServiceImpl. queryAuthGroupListWithCondition(creator, authName,groupName,userName,offset,count); logger.debug("authGroupList:{}",authGroupList); assertTrue(authGroupList.size() == 2); } @Test public void test_queryAuthGroupListTotalCountWithCondition_ReturnTotalCount_WhenAllIsNull(){ insertAuthGroup(); logger.debug(" test queryAuthGroupListTotalCountWithCondition"); String creator = "1"; String authName = null; String groupName = null; String userName = null; int authGroupListCount = unionQuerySqlServiceImpl. queryAuthGroupListTotalCountWithCondition(creator, authName,groupName,userName); logger.debug("authGroupListCount:{}",authGroupListCount); assertTrue(authGroupListCount == 3); } @Test public void test_queryAuthorityIdsExceptByGroupIds_ReturnAuthorityIds(){ /** * AuthorityId: 1,2,3 *AuthorityName:authorityTest1,authorityTest2,authorityTest3 *host:adm.neoway.com, sim.neoway.com */ insertAuthority(); /** * AuthGroupId: 1, 2, 3 * AuthGroupName: authGroupTest1, authGroupTest2, authGroupTest3 * Creator: "1","1","1" */ insertAuthGroup(); /**(AuthGroupAuthorityId, GroupId, AuthorityId) * (1,1,1)(2,2,1)(3,3,2) */ insertAuthGroupAuthority(); //"UserId: 1","2","3" insertUmUser(); //AuthGroupUser:(2,2,"2")(3,3,"2"),(1,1,"1") insertAuthGroupUser(); logger.debug("test query AuthorityIds Intersection By GroupIds"); List<Integer> authGroupIds = new ArrayList<>(); authGroupIds.add(1); String creator = "2"; List<Integer> authorityIds = unionQuerySqlServiceImpl. queryAuthorityIdsExceptByGroupIds(authGroupIds,creator); logger.debug("length:{}, authorityIds:{}",authorityIds.size(), authorityIds); assertTrue(authorityIds.size() == 1); } @Test public void test_queryAuthorityIdsByUserId_ReturnAuthorityIds(){ /** * AuthorityId: 1,2,3 *AuthorityName:authorityTest1,authorityTest2,authorityTest3 *host:adm.neoway.com, sim.neoway.com */ insertAuthority(); /** * AuthGroupId: 1, 2, 3 * AuthGroupName: authGroupTest1, authGroupTest2, authGroupTest3 * Creator: "1","1","1" */ insertAuthGroup(); /**(AuthGroupAuthorityId, GroupId, AuthorityId) * (1,1,1)(2,2,1)(3,3,2) */ insertAuthGroupAuthority(); //"UserId: 1","2","3" insertUmUser(); //AuthGroupUser:(2,2,"2")(3,3,"2"),(1,1,"1") insertAuthGroupUser(); String creator = "2"; List<Integer> authorityIds = unionQuerySqlServiceImpl. queryAuthorityIdsByUserId(creator); logger.debug("length:{}, authorityIds:{}",authorityIds.size(), authorityIds); assertTrue(authorityIds.size() == 2); } @Test public void test_deleteAuthGroupAuthorityByCreatorAndAuthIds_ReturnDeleteNum(){ /** * AuthorityId: 1,2,3 *AuthorityName:authorityTest1,authorityTest2,authorityTest3 *host:adm.neoway.com, sim.neoway.com */ insertAuthority(); /** * AuthGroupId: 1, 2, 3 * AuthGroupName: authGroupTest1, authGroupTest2, authGroupTest3 * Creator: "1","1","1" */ insertAuthGroup(); /**(AuthGroupAuthorityId, GroupId, AuthorityId) * (1,1,1)(2,2,1)(3,3,2) */ insertAuthGroupAuthority(); String creator = "1"; List<Integer> authIds = new ArrayList<>(); authIds.add(1); authIds.add(2); int deleteResult = unionQuerySqlServiceImpl. deleteAuthGroupAuthorityByCreatorAndAuthIds(creator, authIds); logger.debug("deleteResult",deleteResult); assertTrue(deleteResult == 3); } @Test public void test_deleteAuthGroupAuthorityByCreatorAndAuthIdNotInAuthIds_ReturnDeleteNum(){ /** * AuthorityId: 1,2,3 *AuthorityName:authorityTest1,authorityTest2,authorityTest3 *host:adm.neoway.com, sim.neoway.com */ insertAuthority(); /** * AuthGroupId: 1, 2, 3 * AuthGroupName: authGroupTest1, authGroupTest2, authGroupTest3 * Creator: "1","1","1" */ insertAuthGroup(); /**(AuthGroupAuthorityId, GroupId, AuthorityId) * (1,1,1)(2,2,1)(3,3,2) */ insertAuthGroupAuthority(); String creator = "1"; List<Integer> authIds = new ArrayList<>(); authIds.add(2); int deleteResult = unionQuerySqlServiceImpl. deleteAuthGroupAuthorityByCreatorAndAuthIdNotInAuthIds(creator, authIds); logger.debug("deleteResult",deleteResult); assertTrue(deleteResult == 2); } @Test public void test_getAuthorityListWithCondition_ReturnAuthorityList(){ /** * AuthorityId: 1,2,3 *AuthorityName:authorityTest1,authorityTest2,authorityTest3 *host:adm.neoway.com, sim.neoway.com, adm.neoway.com */ insertAuthority(); /** * AuthGroupId: 1, 2, 3 * AuthGroupName: authGroupTest1, authGroupTest2, authGroupTest3 * Creator: "1","1","1" */ insertAuthGroup(); /** * (1,1,1)(2,2,1)(3,3,2) */ insertAuthGroupAuthority(); //"UserId: 1","2","3" insertUmUser(); //AuthGroupUser:(2,2,"2")(3,3,"2"),(1,1,"1") insertAuthGroupUser(); logger.debug("test getAuthorityListWithCondition"); String authOwner = "2"; String name = null; String host = "adm.neoway.com"; int offset = 0; int count = 10; List<Authority> authorityList = unionQuerySqlServiceImpl.getAuthorityListWithCondition( new AuthorityColumn(), authOwner, name, host, offset, count); logger.debug("length:{}, authorityList:{}",authorityList.size(), authorityList); assertTrue(authorityList.size() == 1); } @Test public void test_getAuthorityListCountWithCondition_ReturnAuthorityList(){ /** * AuthorityId: 1,2,3 *AuthorityName:authorityTest1,authorityTest2,authorityTest3 *host:adm.neoway.com, sim.neoway.com,adm.neoway.com */ insertAuthority(); /** * AuthGroupId: 1, 2, 3 * AuthGroupName: authGroupTest1, authGroupTest2, authGroupTest3 * Creator: "1","1","1" */ insertAuthGroup(); /** * (1,1,1)(2,2,1)(3,3,2) */ insertAuthGroupAuthority(); //"UserId: 1","2","3" insertUmUser(); //AuthGroupUser:(2,2,"2")(3,3,"2"),(1,1,"1") insertAuthGroupUser(); logger.debug("test getAuthorityListCountWithCondition"); String authOwner = "2"; String name = "authorityTest3"; String host = null; int listCount = unionQuerySqlServiceImpl.getAuthorityListCountWithCondition( authOwner, name, host); logger.debug("listCount:{}",listCount); assertTrue(listCount == 0); } @Test public void test_getAuthorityListWithAuthGroupName_ReturnAuthorityList(){ /** * AuthorityId: 1,2,3 *AuthorityName:authorityTest1,authorityTest2,authorityTest3 *host:adm.neoway.com, sim.neoway.com, adm.neoway.com */ insertAuthority(); /** * AuthGroupId: 1, 2, 3 * AuthGroupName: authGroupTest1, authGroupTest2, authGroupTest3 * Creator: "1","1","1" */ insertAuthGroup(); /** * (AuthGroupAuthorityId, AuthGroupId, AuthorityId) * (1,1,1)(2,2,1)(3,3,2) */ insertAuthGroupAuthority(); logger.debug("test getAuthorityListWithAuthGroupName"); String authGroupName = "authGroupTest1"; String authGroupCreator = "1"; int offset = 0; int count = 100; List<Authority> authorityList = unionQuerySqlServiceImpl.getAuthorityListWithAuthGroupName( new AuthorityColumn(), authGroupName, authGroupCreator, offset, count); logger.debug("length:{}, authorityList:{}",authorityList.size(), authorityList); assertTrue(authorityList.size() == 1); } @Test public void test_getAuthorityListCountWithAuthGroupName_ReturnAuthorityListCount(){ /** * AuthorityId: 1,2,3 *AuthorityName:authorityTest1,authorityTest2,authorityTest3 *host:adm.neoway.com, sim.neoway.com */ insertAuthority(); /** * AuthGroupId: 1, 2, 3 * AuthGroupName: authGroupTest1, authGroupTest2, authGroupTest3 * Creator: "1","1","1" */ insertAuthGroup(); /** * (1,1,1)(2,2,1)(3,3,2) */ insertAuthGroupAuthority(); logger.debug("test getAuthorityListCountWithAuthGroupName"); String authGroupName = null; String authGroupCreator = null; int listCount = unionQuerySqlServiceImpl.getAuthorityListCountWithAuthGroupName( authGroupName, authGroupCreator); logger.debug("listCount:{}",listCount); assertTrue(listCount == 2); } @Test public void test_getUmUserListWithCondition_ReturnUmUserList(){ /** * AuthorityId: 1,2,3 *AuthorityName:authorityTest1,authorityTest2,authorityTest3 *host:adm.neoway.com, sim.neoway.com */ insertAuthority(); /** * AuthGroupId: 1, 2, 3 * AuthGroupName: authGroupTest1, authGroupTest2, authGroupTest3 * Creator: "1","1","1" */ insertAuthGroup(); /**id,groupId, authorityId * (1,1,1)(2,2,1)(3,3,2) */ insertAuthGroupAuthority(); //UserId: "1","2","3" //parentId:"40288256537d270b01538281f8b40000" //role: User insertUmUser(); //AuthGroupUserId,groupId, userId // (2,2,"2")(3,3,"2"),(1,1,"1") insertAuthGroupUser(); logger.debug("test getUmUserListWithCondition"); String userId = null; String parentId = "40288256537d270b01538281f8b40000"; int userListRole = 3; String authName = "authorityTest1"; String authGroupName = null; int offset = 0; int count = 100; List<UmUser> umUserList = unionQuerySqlServiceImpl.getUmUserListWithCondition( new UmUserColumn(), userId, parentId, userListRole, authName, authGroupName, offset, count); logger.debug("length:{}, umUserList:{}",umUserList.size(), umUserList); assertTrue(umUserList.size() == 2); } @Test public void test_getUmUserListCountWithCondition_ReturnUmUserListCount(){ /** * AuthorityId: 1,2,3 *AuthorityName:authorityTest1,authorityTest2,authorityTest3 *host:adm.neoway.com, sim.neoway.com */ insertAuthority(); /** * AuthGroupId: 1, 2, 3 * AuthGroupName: authGroupTest1, authGroupTest2, authGroupTest3 * Creator: "1","1","1" */ insertAuthGroup(); /**id,groupId, authorityId * (1,1,1)(2,2,1)(3,3,2) */ insertAuthGroupAuthority(); //UserId: "1","2","3" //parentId:"40288256537d270b01538281f8b40000" //role: User insertUmUser(); //AuthGroupUserId,groupId, userId // (2,2,"2")(3,3,"2"),(1,1,"1") insertAuthGroupUser(); logger.debug("test getUmUserListWithCondition"); String userId = null; String parentId = "40288256537d270b01538281f8b40000"; int userListRole = 3; String authName = null; String authGroupName = "authGroupTest2"; int umUserListCount = unionQuerySqlServiceImpl.getUmUserListCountWithCondition(userId, parentId, userListRole, authName, authGroupName); logger.debug("umUserListCount:{}",umUserListCount); assertTrue(umUserListCount == 1); } @Test public void test_getUmUserListByUserGroupName_ReturnUmUserList(){ //UserId: "1","2","3" //parentId:"40288256537d270b01538281f8b40000" //role: User insertUmUser(); /** * OrganizeId: 1, 2, 3 * OrganizeName: organizeTest1, organizeTest2, organizeTest3 * Creator: "1","1","1" */ insertOrganize(); //OrganizeUser:(1,"1",1)(2,"2",2),(3,"3",2),(4,"3",3) insertOrganizeUser(); logger.debug("test getUmUserListWithCondition"); String userId = null; String parentId = "40288256537d270b01538281f8b40000"; int userListRole = 3; String userGroupName = "organizeTest2"; String creator = "1"; int offset = 0; int count = 100; UmUserColumn uc = new UmUserColumn(); uc.password = false; List<UmUser> umUserList = unionQuerySqlServiceImpl.getUmUserListByUserGroupName( uc, userId, parentId, userListRole, userGroupName, creator, offset, count); //userIdResult: "2", "3" logger.debug("length:{}, umUserList:{}",umUserList.size(), umUserList); assertTrue(umUserList.size() == 2); } @Test public void test_getUmUserListCountByUserGroupName_ReturnUmUserListCount(){ //UserId: "1","2","3" //parentId:"40288256537d270b01538281f8b40000" //role: User insertUmUser(); /** * OrganizeId: 1, 2, 3 * OrganizeName: organizeTest1, organizeTest2, organizeTest3 * Creator: "1","1","1" */ insertOrganize(); //OrganizeUser:(1,"1",1)(2,"2",2),(3,"3",2),(4,"3",3) insertOrganizeUser(); logger.debug("test getUmUserListWithCondition"); String userId = null; String parentId = "40288256537d270b01538281f8b40000"; int userListRole = 3; String userGroupName = null; String creator = "1"; int result = unionQuerySqlServiceImpl.getUmUserListCountByUserGroupName( userId, parentId, userListRole, userGroupName, creator); //userIdResult: "2", "3" logger.debug("result",result); assertTrue(result == 3); } @Test public void test_queryAuthGroupIdsUnionByUserIds_ReturnGroupIds(){ logger.debug("query AuthGroupIds Union By UserIds"); initAuthGroupUser(); List<String> userIds = new ArrayList<>(); userIds.add("1"); userIds.add("2"); userIds.add("3"); String creator = "1"; List<Integer> authGroupIds = unionQuerySqlServiceImpl. queryAuthGroupIdsUnionByUserIds(creator,userIds); logger.debug("authGroupIds:{}",authGroupIds); assertTrue(authGroupIds.size() == 3); } @Test public void test_queryAuthGroupIdsIntersectionByUserIds_ReturnGroupIds(){ logger.debug("query AuthGroupIds Intersection By UserIds"); initAuthGroupUser(); List<String> userIds = new ArrayList<>(); userIds.add("2"); userIds.add("3"); String creator = "1"; List<Integer> authGroupIds = unionQuerySqlServiceImpl. queryAuthGroupIdsIntersectionByUserIds(creator, userIds); logger.debug("authGroupIds:{}",authGroupIds); assertTrue(authGroupIds.size() == 0); } @Test public void test_queryAuthGroupIdsExceptByUserIds_ReturnAuthGroupIds(){ logger.debug("queryAuthGroupIdsExceptByUserIds"); initAuthGroupUser(); List<String> userIds = new ArrayList<>(); userIds.add("1"); userIds.add("2"); String creator = "1"; List<Integer> authGroupIds = unionQuerySqlServiceImpl. queryAuthGroupIdsExceptByUserIds(userIds, creator); logger.debug("authGroupIds:{}",authGroupIds); assertTrue(authGroupIds.size() == 0); } @Test public void test_queryUserIdsExceptByOrganizes_ReturnUserIds(){ logger.debug("queryUserIdsExceptByOrganizes"); //"UserId: 1","2","3" insertUmUser(); /** * OrganizeId: 1, 2, 3 * OrganizeName: organizeTest1, organizeTest2, organizeTest3 * Creator: "1","1","1" */ insertOrganize(); //OrganizeUser:(1,"1",1)(2,"2",2),(3,"3",2),(4,"3",3) insertOrganizeUser(); List<Integer> organizeIds = new ArrayList<>(); organizeIds.add(1); organizeIds.add(3); String parentId = "40288256537d270b01538281f8b40000"; int role = 3; List<String> userIds = unionQuerySqlServiceImpl. queryUserIdsExceptByOrganizes(organizeIds, parentId, role); //2 logger.debug("userIds:{}",userIds); assertTrue(userIds.size() ==1); } @Test public void test_queryAuthGroupByUserId_ReturnAuthGroups(){ logger.debug("queryAuthGroupByUserId"); initAuthGroupUser(); String userId = "2"; List<AuthGroup> authGroups = unionQuerySqlServiceImpl. queryAuthGroupByUserId(userId); //result AuthGroupId : 2, 3 logger.debug("authGroups:{}",authGroups); assertTrue(authGroups.size() ==2); } @Test public void test_queryUserGroupByUserId_ReturnOrganizes(){ logger.debug("queryUserGroupByUserId"); //"UserId: 1","2","3" insertUmUser(); /** * OrganizeId: 1, 2, 3 * OrganizeName: organizeTest1, organizeTest2, organizeTest3 * Creator: "1","1","1" */ insertOrganize(); //OrganizeUser:(1,"1",1)(2,"2",2),(3,"3",2),(4,"3",3) insertOrganizeUser(); String userId = "3"; List<Organize> organizes = unionQuerySqlServiceImpl. queryUserGroupByUserId(userId); //result organizeId: 2, 3 logger.debug("organizes:{}",organizes); assertTrue(organizes.size() ==2); } private void initAuthGroupUser(){ /** * AuthGroupId: 1, 2, 3 * AuthGroupName: authGroupTest1, authGroupTest2, authGroupTest3 * Creator: "1","1","1" */ insertAuthGroup(); //UserId: "1","2","3" //parentId:"40288256537d270b01538281f8b40000" //role: User insertUmUser(); //AuthGroupUserId,groupId, userId // (2,2,"2")(3,3,"2"),(1,1,"1") insertAuthGroupUser(); } }
apache-2.0
rafael/kubernetes
pkg/kubelet/config/config.go
9215
/* Copyright 2014 Google 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 config import ( "fmt" "reflect" "sync" "github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet" "github.com/GoogleCloudPlatform/kubernetes/pkg/util" "github.com/GoogleCloudPlatform/kubernetes/pkg/util/config" "github.com/golang/glog" ) // PodConfigListener receives notifications for changes to a configuration. type PodConfigListener interface { // OnUpdate is invoked when the kubelet.Pod configuration has been changed by one of // the sources. The update is properly normalized to remove duplicates. OnUpdate(pod kubelet.PodUpdate) } // ListenerFunc implements the PodConfigListener interface type ListenerFunc func(update kubelet.PodUpdate) func (h ListenerFunc) OnUpdate(update kubelet.PodUpdate) { h(update) } // PodConfigNotificationMode describes how changes are sent to the update channel type PodConfigNotificationMode int const ( // PodConfigNotificationSnapshot delivers the full configuration as a SET whenever // any change occurs PodConfigNotificationSnapshot = iota // PodConfigNotificationSetsAndUpdates delivers an UPDATE message whenever pods are // changed, and a SET message if there are any additions or removals. PodConfigNotificationSnapshotAndUpdates // PodConfigNotificationIncremental delivers ADD, UPDATE, and REMOVE to the update channel PodConfigNotificationIncremental ) // PodConfig is a configuration mux that merges many sources of pod configuration into a single // consistent structure, and then delivers incremental change notifications to listeners // in order. type PodConfig struct { pods *podStorage mux *config.Mux // the channel of denormalized changes passed to listeners updates chan kubelet.PodUpdate } // NewPodConfig creates an object that can merge many configuration sources into a stream // of normalized updates to a pod configuration. func NewPodConfig(mode PodConfigNotificationMode) *PodConfig { updates := make(chan kubelet.PodUpdate, 1) storage := newPodStorage(updates, mode) podConfig := &PodConfig{ pods: storage, mux: config.NewMux(storage), updates: updates, } return podConfig } // Channel creates or returns a config source channel. The channel // only accepts PodUpdates func (c *PodConfig) Channel(source string) chan<- interface{} { return c.mux.Channel(source) } // Updates returns a channel of updates to the configuration, properly denormalized. func (c *PodConfig) Updates() <-chan kubelet.PodUpdate { return c.updates } // Sync requests the full configuration be delivered to the update channel. func (c *PodConfig) Sync() { c.pods.Sync() } // podStorage manages the current pod state at any point in time and ensures updates // to the channel are delivered in order. Note that this object is an in-memory source of // "truth" and on creation contains zero entries. Once all previously read sources are // available, then this object should be considered authoritative. type podStorage struct { podLock sync.RWMutex // map of source name to pod name to pod reference pods map[string]map[string]*kubelet.Pod mode PodConfigNotificationMode // ensures that updates are delivered in strict order // on the updates channel updateLock sync.Mutex updates chan<- kubelet.PodUpdate } // TODO: PodConfigNotificationMode could be handled by a listener to the updates channel // in the future, especially with multiple listeners. // TODO: allow initialization of the current state of the store with snapshotted version. func newPodStorage(updates chan<- kubelet.PodUpdate, mode PodConfigNotificationMode) *podStorage { return &podStorage{ pods: make(map[string]map[string]*kubelet.Pod), mode: mode, updates: updates, } } // Merge normalizes a set of incoming changes from different sources into a map of all Pods // and ensures that redundant changes are filtered out, and then pushes zero or more minimal // updates onto the update channel. Ensures that updates are delivered in order. func (s *podStorage) Merge(source string, change interface{}) error { s.updateLock.Lock() defer s.updateLock.Unlock() adds, updates, deletes := s.merge(source, change) // deliver update notifications switch s.mode { case PodConfigNotificationIncremental: if len(deletes.Pods) > 0 { s.updates <- *deletes } if len(adds.Pods) > 0 { s.updates <- *adds } if len(updates.Pods) > 0 { s.updates <- *updates } case PodConfigNotificationSnapshotAndUpdates: if len(updates.Pods) > 0 { s.updates <- *updates } if len(deletes.Pods) > 0 || len(adds.Pods) > 0 { s.updates <- kubelet.PodUpdate{s.MergedState().([]kubelet.Pod), kubelet.SET} } case PodConfigNotificationSnapshot: if len(updates.Pods) > 0 || len(deletes.Pods) > 0 || len(adds.Pods) > 0 { s.updates <- kubelet.PodUpdate{s.MergedState().([]kubelet.Pod), kubelet.SET} } default: panic(fmt.Sprintf("unsupported PodConfigNotificationMode: %#v", s.mode)) } return nil } func (s *podStorage) merge(source string, change interface{}) (adds, updates, deletes *kubelet.PodUpdate) { s.podLock.Lock() defer s.podLock.Unlock() adds = &kubelet.PodUpdate{Op: kubelet.ADD} updates = &kubelet.PodUpdate{Op: kubelet.UPDATE} deletes = &kubelet.PodUpdate{Op: kubelet.REMOVE} pods := s.pods[source] if pods == nil { pods = make(map[string]*kubelet.Pod) } update := change.(kubelet.PodUpdate) switch update.Op { case kubelet.ADD, kubelet.UPDATE: if update.Op == kubelet.ADD { glog.Infof("Adding new pods from source %s : %v", source, update.Pods) } else { glog.Infof("Updating pods from source %s : %v", source, update.Pods) } filtered := filterInvalidPods(update.Pods, source) for _, ref := range filtered { name := ref.Name if existing, found := pods[name]; found { if !reflect.DeepEqual(existing.Manifest, ref.Manifest) { // this is an update existing.Manifest = ref.Manifest updates.Pods = append(updates.Pods, *existing) continue } // this is a no-op continue } // this is an add ref.Namespace = source pods[name] = ref adds.Pods = append(adds.Pods, *ref) } case kubelet.REMOVE: glog.Infof("Removing a pod %v", update) for _, value := range update.Pods { name := value.Name if existing, found := pods[name]; found { // this is a delete delete(pods, name) deletes.Pods = append(deletes.Pods, *existing) continue } // this is a no-op } case kubelet.SET: glog.Infof("Setting pods for source %s : %v", source, update) // Clear the old map entries by just creating a new map oldPods := pods pods = make(map[string]*kubelet.Pod) filtered := filterInvalidPods(update.Pods, source) for _, ref := range filtered { name := ref.Name if existing, found := oldPods[name]; found { pods[name] = existing if !reflect.DeepEqual(existing.Manifest, ref.Manifest) { // this is an update existing.Manifest = ref.Manifest updates.Pods = append(updates.Pods, *existing) continue } // this is a no-op continue } ref.Namespace = source pods[name] = ref adds.Pods = append(adds.Pods, *ref) } for name, existing := range oldPods { if _, found := pods[name]; !found { // this is a delete deletes.Pods = append(deletes.Pods, *existing) } } default: glog.Infof("Received invalid update type: %v", update) } s.pods[source] = pods return adds, updates, deletes } func filterInvalidPods(pods []kubelet.Pod, source string) (filtered []*kubelet.Pod) { names := util.StringSet{} for i := range pods { var errors []error if names.Has(pods[i].Name) { errors = append(errors, api.ValidationError{api.ErrTypeDuplicate, "Pod.Name", pods[i].Name}) } else { names.Insert(pods[i].Name) } if errs := kubelet.ValidatePod(&pods[i]); len(errs) != 0 { errors = append(errors, errs...) } if len(errors) > 0 { glog.Warningf("Pod %d from %s failed validation, ignoring: %v", i+1, source, errors) continue } filtered = append(filtered, &pods[i]) } return } // Sync sends a copy of the current state through the update channel func (s *podStorage) Sync() { s.updateLock.Lock() defer s.updateLock.Unlock() s.updates <- kubelet.PodUpdate{s.MergedState().([]kubelet.Pod), kubelet.SET} } // Object implements config.Accessor func (s *podStorage) MergedState() interface{} { s.podLock.RLock() defer s.podLock.RUnlock() pods := make([]kubelet.Pod, 0) for source, sourcePods := range s.pods { for _, podRef := range sourcePods { pod := *podRef pod.Namespace = source pods = append(pods, pod) } } return pods }
apache-2.0
lsimone/ariatemplates
test/aria/widgets/WidgetsTestSuite.js
2946
/* * Copyright 2012 Amadeus s.a.s. * 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. */ Aria.classDefinition({ $classpath : "test.aria.widgets.WidgetsTestSuite", $extends : "aria.jsunit.TestSuite", $constructor : function () { this.$TestSuite.constructor.call(this); this.addTests("test.aria.widgets.form.FormTestSuite"); this.addTests("test.aria.widgets.container.ContainerTestSuite"); this.addTests("test.aria.widgets.autoselect.AutoSelect"); this.addTests("test.aria.widgets.autoselect.programmatic.AutoSelect"); this.addTests("test.aria.widgets.errorTip.ButtonErrorTipsTest"); this.addTests("test.aria.widgets.errorTip.IconButtonErrorTipsTest"); this.addTests("test.aria.widgets.errorTip.LinkErrorTipsTest"); this.addTests("test.aria.widgets.AriaSkinInterfaceTest"); this.addTests("test.aria.widgets.AriaSkinNormalizationTest"); this.addTests("test.aria.widgets.WidgetTest"); this.addTests("test.aria.widgets.action.ActionTestSuite"); this.addTests("test.aria.widgets.form.text.Text"); this.addTests("test.aria.widgets.form.text.EllipsisTest"); this.addTests("test.aria.widgets.calendar.CalendarControllerTest"); this.addTests("test.aria.widgets.calendar.lineHeight.CalendarLineHeightTest"); this.addTests("test.aria.widgets.calendar.rangeCalendar.RangeCalendarTestSuite"); this.addTests("test.aria.widgets.controllers.SelectBoxControllerTest"); this.addTests("test.aria.widgets.controllers.SelectControllerTest"); this.addTests("test.aria.widgets.dropdown.DropDownTestSuite"); this.addTests("test.aria.widgets.environment.WidgetSettings"); this.addTests("test.aria.widgets.errorlist.ErrorListControllerTest"); this.addTests("test.aria.widgets.errorlist.ListErrorTestCase"); this.addTests("test.aria.widgets.action.iconbutton.issue276.IconButtonTestCase"); this.addTests("test.aria.widgets.verticalAlign.VerticalAlignTestCase"); this.addTests("test.aria.widgets.icon.IconTest"); this.addTests("test.aria.widgets.icon.notooltip.NoTooltipIconTest"); this.addTests("test.aria.widgets.splitter.scrollbars.ScrollbarTestCase"); this.addTests("test.aria.widgets.issue746.SkinClassFallbackTestCase"); this.addTests("test.aria.widgets.form.text.textcontentissue.TextContentTest"); } });
apache-2.0
ray-project/ray
python/ray/util/client/server/server_pickler.py
4862
"""Implements the client side of the client/server pickling protocol. These picklers are aware of the server internals and can find the references held for the client within the server. More discussion about the client/server pickling protocol can be found in: ray/util/client/client_pickler.py ServerPickler dumps ray objects from the server into the appropriate stubs. ClientUnpickler loads stubs from the client and finds their associated handle in the server instance. """ import io import sys import ray from typing import Any from typing import TYPE_CHECKING from ray._private.client_mode_hook import disable_client_hook import ray.cloudpickle as cloudpickle from ray.util.client.client_pickler import PickleStub from ray.util.client.server.server_stubs import ClientReferenceActor from ray.util.client.server.server_stubs import ClientReferenceFunction if TYPE_CHECKING: from ray.util.client.server.server import RayletServicer import ray.core.generated.ray_client_pb2 as ray_client_pb2 if sys.version_info < (3, 8): try: import pickle5 as pickle # noqa: F401 except ImportError: import pickle # noqa: F401 else: import pickle # noqa: F401 class ServerPickler(cloudpickle.CloudPickler): def __init__(self, client_id: str, server: "RayletServicer", *args, **kwargs): super().__init__(*args, **kwargs) self.client_id = client_id self.server = server def persistent_id(self, obj): if isinstance(obj, ray.ObjectRef): obj_id = obj.binary() if obj_id not in self.server.object_refs[self.client_id]: # We're passing back a reference, probably inside a reference. # Let's hold onto it. self.server.object_refs[self.client_id][obj_id] = obj return PickleStub( type="Object", client_id=self.client_id, ref_id=obj_id, name=None, baseline_options=None, ) elif isinstance(obj, ray.actor.ActorHandle): actor_id = obj._actor_id.binary() if actor_id not in self.server.actor_refs: # We're passing back a handle, probably inside a reference. self.server.actor_refs[actor_id] = obj if actor_id not in self.server.actor_owners[self.client_id]: self.server.actor_owners[self.client_id].add(actor_id) return PickleStub( type="Actor", client_id=self.client_id, ref_id=obj._actor_id.binary(), name=None, baseline_options=None, ) return None class ClientUnpickler(pickle.Unpickler): def __init__(self, server, *args, **kwargs): super().__init__(*args, **kwargs) self.server = server def persistent_load(self, pid): assert isinstance(pid, PickleStub) if pid.type == "Ray": return ray elif pid.type == "Object": return self.server.object_refs[pid.client_id][pid.ref_id] elif pid.type == "Actor": return self.server.actor_refs[pid.ref_id] elif pid.type == "RemoteFuncSelfReference": return ClientReferenceFunction(pid.client_id, pid.ref_id) elif pid.type == "RemoteFunc": return self.server.lookup_or_register_func( pid.ref_id, pid.client_id, pid.baseline_options ) elif pid.type == "RemoteActorSelfReference": return ClientReferenceActor(pid.client_id, pid.ref_id) elif pid.type == "RemoteActor": return self.server.lookup_or_register_actor( pid.ref_id, pid.client_id, pid.baseline_options ) elif pid.type == "RemoteMethod": actor = self.server.actor_refs[pid.ref_id] return getattr(actor, pid.name) else: raise NotImplementedError("Uncovered client data type") def dumps_from_server( obj: Any, client_id: str, server_instance: "RayletServicer", protocol=None ) -> bytes: with io.BytesIO() as file: sp = ServerPickler(client_id, server_instance, file, protocol=protocol) sp.dump(obj) return file.getvalue() def loads_from_client( data: bytes, server_instance: "RayletServicer", *, fix_imports=True, encoding="ASCII", errors="strict" ) -> Any: with disable_client_hook(): if isinstance(data, str): raise TypeError("Can't load pickle from unicode string") file = io.BytesIO(data) return ClientUnpickler( server_instance, file, fix_imports=fix_imports, encoding=encoding ).load() def convert_from_arg(pb: "ray_client_pb2.Arg", server: "RayletServicer") -> Any: return loads_from_client(pb.data, server)
apache-2.0
olikbox/java_training_course
addressbook-web-tests/src/test/java/ru/stqa/ptf/addressbook/appmanger/GroupHelper.java
2557
package ru.stqa.ptf.addressbook.appmanger; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import ru.stqa.ptf.addressbook.model.GroupData; import java.util.ArrayList; import java.util.List; import static ru.stqa.ptf.addressbook.tests.TestBase.app; /** * Created by Olga_Verkhovtseva on 5/23/2017. */ public class GroupHelper extends BaseHelper { public GroupHelper(WebDriver wd) { super(wd); } public void initGroupCreation() { click(By.name("new")); } public void fillGroupForm(GroupData groupData) { type(By.name("group_name"), groupData.getName()); type(By.name("group_header"), groupData.getHeader()); type(By.name("group_footer"), groupData.getFooter()); } public void submitGroupCreation() { click(By.name("submit")); } public void selectGroupModification(int index) { wd.findElements(By.name("selected[]")).get(index).click(); } public void intitGroupModification() { click(By.name("edit")); } public void submitGroupModification() { click(By.name("update")); } public void submitGroupDelete() { click(By.name("delete")); } public void returntoGroupPage() { click(By.linkText("group page")); } public void createGroup(GroupData group) { initGroupCreation(); fillGroupForm(group); submitGroupCreation(); returntoGroupPage(); } public boolean IsThereAGroup() { return isElementPresent(By.name("selected[]")); } public void modifyGroup(GroupData group) { List <GroupData> before = getGroupList(); selectGroupModification(before.size() - 1); intitGroupModification(); fillGroupForm(group); submitGroupModification(); returntoGroupPage(); } public List <GroupData> getGroupList() { List<GroupData> groups = new ArrayList<>(); List<WebElement> elements = wd.findElements(By.cssSelector("span.group")); for (WebElement element:elements) { String name = element.getText(); int id = Integer.parseInt(element.findElement(By.tagName("input")).getAttribute("value")); groups.add ( new GroupData ( ).withId ( id ).withName ( name ) ); } return groups; } public void modifyGroup(int index) { selectGroupModification(index); submitGroupDelete(); app.getNavigationHelper().returntoGroupPage(); } }
apache-2.0
otherio/threadable.com
spec/controllers/admin/organizations_controller_spec.rb
5450
require 'spec_helper' describe Admin::OrganizationsController, :type => :controller do when_not_signed_in do describe 'GET :index' do it 'should render a 404' do get :index expect(response).to redirect_to sign_in_url(r: admin_organizations_url) end end describe 'GET :new' do it 'should render a 404' do get :new expect(response).to redirect_to sign_in_url(r: admin_new_organization_url) end end describe 'POST :create' do it 'should render a 404' do post :create expect(response).to redirect_to sign_in_url end end describe 'GET :edit' do it 'should render a 404' do get :edit, id: 'foo' expect(response).to redirect_to sign_in_url(r: admin_edit_organization_url) end end describe 'PUT :update' do it 'should render a 404' do put :update, id: 'foo' expect(response).to redirect_to sign_in_url end end describe 'DELETE :destroy' do it 'should render a 404' do delete :destroy, id: 'foo' expect(response).to redirect_to sign_in_url end end end when_signed_in_as 'ian@other.io' do describe 'GET :index' do it 'should render the index page' do organizations = double(:organizations) expect(threadable.organizations).to receive(:all_by_created_at).and_return(organizations) get :index expect(response).to render_template :index expect(assigns[:organizations]).to eq organizations end end describe 'GET :new' do it 'should render the new organization page' do new_organization = double(:new_organization) expect(threadable.organizations).to receive(:new).and_return(new_organization) get :new expect(response).to render_template :new expect(assigns[:organization]).to eq new_organization end end describe 'POST :create' do let(:organization_params){ { name: 'Robot Cow', add_current_user_as_a_member: "1", trusted: "1" } } let(:organization){ double(:organization, to_param: 'robot-cow', persisted?: persisted) } before do expect(threadable.organizations).to receive(:create).with(name: 'Robot Cow', add_current_user_as_a_member: true, trusted: true).and_return(organization) post :create, organization: organization_params end context 'when the organization is successfully created' do let(:persisted){ true } it 'should redirect to the organization edit page' do expect(response).to redirect_to admin_edit_organization_path('robot-cow') expect(flash[:notice]).to eq "Organization was successfully created." end end context 'when the organization is not successfully created' do let(:persisted){ false } it 'should render to the organization edit page' do expect(response).to render_template :new expect(assigns[:organization]).to eq organization end end end describe 'GET :edit' do let(:organization){ double :organization, members: double(:members) } let(:members){ double :members } before do expect(threadable.organizations).to receive(:find_by_slug!).with('low-rider').and_return(organization) expect(organization.members).to receive(:all).and_return(members) end it 'should render the organization edit page' do get :edit, id: 'low-rider' expect(response).to render_template :edit expect(assigns[:organization]).to eq organization expect(assigns[:members]).to eq members end end describe 'PUT :update' do let(:organization){ double :organization, members: double(:members), to_param: 'lowrider' } let(:organization_params){ {slug: 'lowrider'} } before do expect(threadable.organizations).to receive(:find_by_slug!).with('low-rider').and_return(organization) expect(organization).to receive(:admin_update).with(organization_params).and_return(update_successful) put :update, id: 'low-rider', organization: organization_params end context 'when the organization is successfully updated' do let(:update_successful){ true } it 'should redirect to the organization edit page' do expect(response).to redirect_to admin_edit_organization_path('lowrider') expect(flash[:notice]).to eq "Organization was successfully updated." end end context 'when the organization is not successfully updated' do let(:update_successful){ false } it 'should render to the organization edit page' do expect(response).to render_template :edit expect(assigns[:organization]).to eq organization end end end describe 'DELETE :destroy' do let(:organization){ double :organization, members: double(:members), slug: 'lowrider' } before do expect(threadable.organizations).to receive(:find_by_slug!).with('low-rider').and_return(organization) expect(organization).to receive(:destroy!) delete :destroy, id: 'low-rider' end it 'should redirect to the admin organizations page' do expect(response).to redirect_to admin_organizations_url expect(flash[:notice]).to eq "Organization was successfully destroyed." end end end end
apache-2.0
ftomassetti/turin-programming-language
documentation/conf.py
9385
# -*- coding: utf-8 -*- # # Turin Programming Language documentation build configuration file, created by # sphinx-quickstart on Sat Oct 3 12:03:31 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.todo', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Turin Programming Language' copyright = u'2015, Federico Tomassetti' author = u'Federico Tomassetti' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'TurinProgrammingLanguagedoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'TurinProgrammingLanguage.tex', u'Turin Programming Language Documentation', u'Federico Tomassetti', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'turinprogramminglanguage', u'Turin Programming Language Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'TurinProgrammingLanguage', u'Turin Programming Language Documentation', author, 'TurinProgrammingLanguage', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
apache-2.0
dhakehurst/net.akehurst.application.framework.examples
net.akehurst.app.flightSystem/application/desktop.jfx/src/main/java/net/akehurst/example/flightSimulator/application/FlightSystemMain.java
1394
/* * Copyright (c) 2015 D. David H. Akehurst * * 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.akehurst.example.flightSimulator.application; import java.net.URL; import net.akehurst.application.framework.realisation.ApplicationFramework; import net.akehurst.example.flightSimulator.gui.controls.GuiControlsPanel; public class FlightSystemMain { public static void main(String[] args) { //URL url = GuiControlsPanel.class.getResource("GuiControlsPanel.fxml"); ApplicationFramework.start(FlightSystemApplication.class, args); // try { // EnvironmentSimulation envSim = new EnvironmentSimulation(5); // EnvironmentReference.actual = envSim; // // FlightSystemApplication main = new FlightSystemApplication(args); // envSim.start(); // main.start(); // main.join(); // } catch (Throwable t) { // t.printStackTrace(); // } } }
apache-2.0
nimble-platform/frontend-service
src/app/catalogue/ubl-model-view/catalogue/catalogue-view.component.ts
30068
/* * Copyright 2020 * SRDC - Software Research & Development Consultancy; Ankara; Turkey In collaboration with * SRFG - Salzburg Research Forschungsgesellschaft mbH; Salzburg; Austria 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 {Component, Input, OnInit, ViewChild} from '@angular/core'; import { Location } from '@angular/common'; import { CookieService } from 'ng2-cookies'; import { CatalogueService } from "../../catalogue.service"; import { CallStatus } from "../../../common/call-status"; import { ActivatedRoute, Params, Router } from "@angular/router"; import { PublishService } from "../../publish-and-aip.service"; import { CategoryService } from "../../category/category.service"; import {copy, isLogisticsService, selectPreferredNameForSolrCategory, sortSolrCategories} from '../../../common/utils'; import { UserService } from "../../../user-mgmt/user.service"; import { CompanySettings } from "../../../user-mgmt/model/company-settings"; import { CataloguePaginationResponse } from '../../model/publish/catalogue-pagination-response'; import { Item } from '../../model/publish/item'; import { selectDescription, selectName } from '../../../common/utils'; import { ItemProperty } from '../../model/publish/item-property'; import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'; import { Observable } from 'rxjs/Observable'; import {CATALOGUE_LINE_SORT_OPTIONS, CATALOGUE_LINE_STATUS, NON_PUBLIC_FIELD_ID} from '../../model/constants'; import { Catalogue } from '../../model/publish/catalogue'; import { CatalogueLine } from "../../model/publish/catalogue-line"; import { TranslateService } from '@ngx-translate/core'; import { DeleteExportCatalogueModalComponent } from "./delete-export-catalogue-modal.component"; import {WhiteBlackListService} from '../../white-black-list.service'; import {NetworkCompanyListService} from '../../../user-mgmt/network-company-list.service'; import {AppComponent} from '../../../app.component'; import * as myGlobals from '../../../globals'; import {SimpleSearchService} from '../../../simple-search/simple-search.service'; import {ProductOfferingDetails} from '../../model/publish/product-offering-details'; @Component({ selector: 'catalogue-view', templateUrl: './catalogue-view.component.html', styleUrls: ["./catalogue-view.component.css"], providers: [CookieService] }) export class CatalogueViewComponent implements OnInit { @Input() viewMode:"OwnerView"|"ContractView"|"OfferView" = "OwnerView"; product_vendor_name = myGlobals.product_vendor_name; catalogueResponse: CataloguePaginationResponse; settings: CompanySettings; // available catalogue lines with respect to the selected category catalogueLinesWRTTypes: any = []; // catalogue lines which are available to the user after search operation catalogueLinesArray: CatalogueLine[] = []; // categories of the catalogue lines retrieved from indexing-service categoriesInSolrFormat: any = []; selectedCategory = "All"; // necessary info for pagination collectionSize = 0; page = 1; // default pageSize = 10; addCatalogue = false; // variables for white/black list functionality // whether the white/black list panel is visible whiteBlackListPanelVisible:boolean = false; // selected companies for white list whiteListCompanies:any[] = []; // selected companies for black list blackListCompanies:any[] = []; // party name map for the ones included in white/black list partyNameMap:Map<string,string> = null; // call status for white/black list operations whiteBlackListCallStatus:CallStatus = new CallStatus(); // the end of variables for white/black list functionality // Flag indicating that the source page is the search page. searchRef:boolean = false; // check whether catalogue-line-panel should be displayed for a specific catalogue line catalogueLineView = {}; selectedCatalogue: string = "all"; catalogueUuid: string = 'all'; cataloguesIds: string[] = []; catalogueUuids: string[] = []; productStatus = "All"; sortOption = null; catalogueText: string = ""; getCatalogueStatus = new CallStatus(); productCatalogueRetrievalStatus: CallStatus = new CallStatus(); callStatus = new CallStatus(); deleteStatuses: CallStatus[] = []; // variables for product offering functionality // whether the product selection is enabled for offering productSelectionForOffering:boolean = false; // call status for party names getPartyNameCallStatus:CallStatus = new CallStatus(); // details of the product offer productOfferingDetails:ProductOfferingDetails = null; // whether the companies are selected from the network groups or not companyListInput:boolean = true; // the end of variables for product offering functionality public config = myGlobals.config; catalogueIdForContractCreation:string = null; catalogueUuidForContractCreation:string = null; @ViewChild(DeleteExportCatalogueModalComponent) private deleteCatalogueModal: DeleteExportCatalogueModalComponent; CATALOGUE_LINE_SORT_OPTIONS = CATALOGUE_LINE_SORT_OPTIONS; CATALOGUE_LINE_STATUS = CATALOGUE_LINE_STATUS; public searchText: string = ""; encodeURIComponent = encodeURIComponent; selectPreferredNameForSolrCategory = selectPreferredNameForSolrCategory; constructor(private cookieService: CookieService, private publishService: PublishService, public appComponent: AppComponent, private catalogueService: CatalogueService, private categoryService: CategoryService, public networkCompanyListService: NetworkCompanyListService, private translate: TranslateService, private simpleSearchService: SimpleSearchService, private route: ActivatedRoute, private whiteBlackListService: WhiteBlackListService, private userService: UserService, private router: Router, private location: Location) { } ngOnInit() { this.route.queryParams.subscribe((params: Params) => { // searchRef is true if the source page is search page this.searchRef = !!params['searchRef']; this.searchText = ""; this.deleteStatuses = []; this.catalogueText = ""; this.sortOption = null; this.cataloguesIds = []; this.catalogueUuid = this.searchRef && this.whiteBlackListService.catalogueId ? this.whiteBlackListService.catalogueId :"all"; // if the user is coming from the search page and a catalogue id is set, set the catalogue id again if (this.searchRef && this.whiteBlackListService.catalogueId) { this.catalogueUuid = this.whiteBlackListService.catalogueId; // if a specific catalogue id is available in the query parameters, set it to the active catalogue name } else if (params['cUuid']) { this.catalogueUuid = params['cUuid']; } else { this.catalogueUuid = 'all'; } this.selectedCatalogue = this.catalogueUuid; this.catalogueLinesWRTTypes = []; this.catalogueLinesArray = []; this.categoriesInSolrFormat = []; this.selectedCategory = "All"; this.productStatus = "All"; this.collectionSize = 0; this.page = 1; this.pageSize = 10; this.addCatalogue = false; this.whiteBlackListPanelVisible = this.searchRef && this.whiteBlackListService.catalogueId != null; this.catalogueLineView = {}; this.sortOption = this.sortOption == null ? CATALOGUE_LINE_SORT_OPTIONS[0].name : this.sortOption; this.initDataRetrieval(); for (let i = 0; i < this.pageSize; i++) { this.deleteStatuses.push(new CallStatus()); } }); } setSelectedPartiesAndPopulatePartyNameMap(){ // retrieve selected company vat numbers let selectedPartyVatNumbers: string[] = []; if(this.settings.negotiationSettings.company.network && this.settings.negotiationSettings.company.network.length > 0){ for (let network of this.settings.negotiationSettings.company.network) { for (let vatNumber of network.vatNumber) { if(selectedPartyVatNumbers.indexOf(vatNumber) == -1){ selectedPartyVatNumbers.push(vatNumber); } } } } if(this.productOfferingDetails.vatNumber.length > 0){ for (let vatNumber of this.productOfferingDetails.vatNumber) { if(selectedPartyVatNumbers.indexOf(vatNumber) == -1){ selectedPartyVatNumbers.push(vatNumber); } } } if(selectedPartyVatNumbers.length > 0){ this.getPartyNameCallStatus.submit(); this.simpleSearchService.getEFactoryCompanies(selectedPartyVatNumbers).then(parties => { this.partyNameMap = new Map<string,string>(); for (let party of parties.result) { this.partyNameMap.set(party.vatNumber,party.legalName); } this.getPartyNameCallStatus.callback("Retrieved party names",true); }).catch(error => { this.getPartyNameCallStatus.error(this.translate.instant("Failed to get party names"),error); }) } } setWhiteBlackListAndPopulatePartyNameMap(whiteListParties:any[],blackListParties:any[]){ let selectedParties = [].concat(whiteListParties).concat(blackListParties); let vatNumbers = selectedParties.map(value => value.vatNumber); if(vatNumbers.length > 0){ this.whiteBlackListCallStatus.submit(); this.simpleSearchService.getEFactoryCompanies(vatNumbers).then(response => { let parties = response.result; this.partyNameMap = new Map<string, string>(); for (let party of parties) { this.partyNameMap.set(party.vatNumber,party.legalName); } this.whiteListCompanies = []; for (let whiteListParty of whiteListParties) { this.whiteListCompanies.push({"vatNumber":whiteListParty.vatNumber,"legalName":this.partyNameMap.get(whiteListParty.vatNumber)}); } this.blackListCompanies = []; for (let blackListParty of blackListParties) { this.blackListCompanies.push({"vatNumber":blackListParty.vatNumber,"legalName":this.partyNameMap.get(blackListParty.vatNumber)}); } this.whiteBlackListCallStatus.callback("Retrieved party names",true); }).catch(error => { this.whiteBlackListCallStatus.error("Failed to get party names",error); }) } else{ this.whiteListCompanies = []; this.blackListCompanies = []; } } isWhiteBlackListCallStatusLoading(): boolean { return this.whiteBlackListCallStatus.fb_submitted; } selectName(ip: ItemProperty | Item) { return selectName(ip); } selectDescription(item: Item) { return selectDescription(item); } changeCat() { this.catalogueUuid = this.selectedCatalogue; this.whiteBlackListPanelVisible = false; this.requestCatalogue(); } requestCatalogue(): void { const userId = this.cookieService.get("user_id"); // check whether the user chose a category to filter the catalogue lines let categoryName = this.selectedCategory == "All" ? null : this.selectedCategory; // do not need to pass a request param for 'All' option of status let productStatus = this.productStatus == "All" ? null : this.productStatus; // get selected catalogue id let catalogueId = this.catalogueUuid; if (catalogueId !== 'all') { let index = this.catalogueUuids.indexOf(catalogueId); if (index !== -1) { catalogueId = this.cataloguesIds[index]; this.location.replaceState( this.router.createUrlTree(['/dashboard'], {queryParams: {tab: 'CATALOGUE', 'cUuid': this.catalogueUuid}}).toString() ); } else { this.location.replaceState( this.router.createUrlTree(['/dashboard'], {queryParams: {tab: 'CATALOGUE'}}).toString() ); return; } } this.getCatalogueStatus.submit(); Promise.all([ this.catalogueService.getCatalogueResponse(userId, categoryName, this.searchText, this.pageSize, (this.page - 1) * this.pageSize, this.sortOption, catalogueId, productStatus), this.getCompanySettings(userId) ]) .then(([catalogueResponse, settings]) => { this.categoryService.getCategories(catalogueResponse.categoryUris).then(categories => { this.catalogueResponse = catalogueResponse; this.settings = settings; this.updateView(categories.result); this.getCatalogueStatus.callback(null, true); }).catch(error => { this.getCatalogueStatus.error("Failed to get catalogue", error); }) }, error => { this.getCatalogueStatus.error("Failed to get catalogue", error); } ) } private getCompanySettings(userId: string): Promise<CompanySettings> { if (this.settings) { return Promise.resolve(this.settings); } return this.userService.getSettingsForUser(userId); } // called when the catalogue pagination response is retrieved to update the view private updateView(categoriesInSolrFormat = null): void { let len = this.catalogueResponse.catalogueLines.length; this.categoriesInSolrFormat = sortSolrCategories(categoriesInSolrFormat); this.collectionSize = this.catalogueResponse.size; this.catalogueLinesArray = [...this.catalogueResponse.catalogueLines]; this.catalogueLinesWRTTypes = this.catalogueLinesArray; // if the white/black list functionality is available, // we need to set white/black lists using: // - either the ones in the catalogue pagination response if the source page is not the company search page or new catalogue is selected // - or the ones in the whiteBlackListService if the source page is the company search page if(this.config.whiteBlackListForCatalogue){ // the source page is the company search page if(this.searchRef && this.whiteBlackListService.catalogueId){ this.setWhiteBlackListAndPopulatePartyNameMap(this.whiteBlackListService.getSelectedCompanies('White'),this.whiteBlackListService.getSelectedCompanies('Black')); // reset whiteBlackListService service this.whiteBlackListService.reset() } else{ this.setWhiteBlackListAndPopulatePartyNameMap(this.catalogueResponse.permittedParties ? this.catalogueResponse.permittedParties.map(value => this.getVatNumberObject(value)):[], this.catalogueResponse.restrictedParties ? this.catalogueResponse.restrictedParties.map(value => this.getVatNumberObject(value)) : []) } } let i = 0; // Initialize catalogueLineView for (; i < len; i++) { this.catalogueLineView[this.catalogueResponse.catalogueLines[i].id] = false; } if(this.viewMode == 'OfferView'){ this.productOfferingDetails = copy(this.networkCompanyListService.productOfferingDetails); this.setSelectedPartiesAndPopulatePartyNameMap(); } } getVatNumberObject(vatNumber:string){ return {"vatNumber":vatNumber} } onDeleteCatalogue(): void { this.deleteCatalogueModal.open('delete'); } onHidePriceForCatalogue(){ let hidden = !this.catalogueResponse.priceHidden; this.productCatalogueRetrievalStatus.submit(); this.catalogueService.hidePriceForCatalogue(this.catalogueResponse.catalogueUuid, hidden).then( () => { this.catalogueResponse.priceHidden = hidden; this.productCatalogueRetrievalStatus.callback(this.translate.instant(this.catalogueResponse.priceHidden ? "Hid prices for the catalogue successfully" :"Exposed prices for the catalogue successfully") ,false); }).catch(error => { this.productCatalogueRetrievalStatus.error(this.translate.instant(hidden ? "Failed to hide prices for the catalogue" : "Failed to expose prices for the catalogue"),error); }) } // methods for white/black list functionality onAddWhiteBlackListToCatalogue(){ this.whiteBlackListPanelVisible = true; this.productSelectionForOffering = false; } onRemoveCompanyFromWhiteBlackList(listMode:'White'|'Black', index:number) { if(listMode=='White'){ this.whiteListCompanies.splice(index,1); } else { this.blackListCompanies.splice(index,1); } } onAddCompanyToWhiteBlackList(listMode:'White'|'Black'): void { this.whiteBlackListService.listMode = listMode; this.whiteBlackListService.catalogueId = this.selectedCatalogue; this.whiteBlackListService.setSelectedPartiesInSearchForWhiteList(this.whiteListCompanies); this.whiteBlackListService.setSelectedPartiesInSearchForBlackList(this.blackListCompanies); this.router.navigate(['/simple-search'], { queryParams: { sTop: 'comp', pageRef: 'catalogue' } }); } onSaveBlackWhiteLists(){ let blackList = this.blackListCompanies.map(value => value.vatNumber); let whiteList = this.whiteListCompanies.map(value => value.vatNumber); this.whiteBlackListCallStatus.submit(); this.catalogueService.addBlackWhiteListToCatalog(this.selectedCatalogue,blackList,whiteList).then(() => { this.whiteBlackListCallStatus.callback(this.translate.instant("Added black/white list to catalogue successfully")) }).catch(error => { this.whiteBlackListCallStatus.error("Failed to add black/white list to catalogue",error) }) } // the end of methods for white/black list functionality // methods for product offering functionality onOfferCatalogueButtonClicked(): void { this.productSelectionForOffering = true; this.whiteBlackListPanelVisible = false; } offerProduct(line){ this.viewMode = 'OfferView'; this.productOfferingDetails = new ProductOfferingDetails(); this.productOfferingDetails.selectedProduct = line; // to retrieve party names for the ones in the network this.setSelectedPartiesAndPopulatePartyNameMap(); } offerCatalog(selectedCatalogueUuid:string){ this.productOfferingDetails = new ProductOfferingDetails(); if(selectedCatalogueUuid == 'all'){ this.productOfferingDetails.selectedCatalogueUuids = copy(this.catalogueUuids); this.productOfferingDetails.selectedCatalogIds = this.cataloguesIds.map(catalogueId => catalogueId == "default" ? this.translate.instant("Main Catalogue"):catalogueId).join(); } else{ let index = this.catalogueUuids.findIndex(uuid => uuid == selectedCatalogueUuid); this.productOfferingDetails.selectedCatalogueUuids = [selectedCatalogueUuid]; this.productOfferingDetails.selectedCatalogIds = this.cataloguesIds[index] == "default" ? this.translate.instant("Main Catalogue"): this.cataloguesIds[index]; } this.viewMode = 'OfferView'; // to retrieve party names for the ones in the network this.setSelectedPartiesAndPopulatePartyNameMap(); } onRemoveCompanyFromList(companyIndex:number) { this.productOfferingDetails.vatNumber.splice(companyIndex,1); } onAddCompanyToList(): void { this.networkCompanyListService.reset(); this.networkCompanyListService.productOfferingDetails = this.productOfferingDetails; this.router.navigate(['/simple-search'], { queryParams: { sTop: 'comp', pageRef: 'offering' } }); } isPartyNamesLoading(): boolean { return this.getPartyNameCallStatus.fb_submitted; } onSendOffer(){ this.callStatus.submit(); if(this.productOfferingDetails.vatNumber.length == 0){ this.callStatus.error(this.translate.instant("Select at least one company to send your offer!")); return; } let catalogIds = this.productOfferingDetails.selectedCatalogueUuids; let lineIds = null; if(this.productOfferingDetails.selectedProduct){ catalogIds = [this.productOfferingDetails.selectedProduct.goodsItem.item.catalogueDocumentReference.id]; lineIds = [this.productOfferingDetails.selectedProduct.goodsItem.item.manufacturersItemIdentification.id] } this.catalogueService.offerCatalogsOrLines(catalogIds,lineIds,this.productOfferingDetails.vatNumber,this.productOfferingDetails.description).then(() => { this.callStatus.callback(this.translate.instant("Offered the product details to specified companies successfully")); }).catch(error => { this.callStatus.error(this.translate.instant("Failed to offer your products"),error); }); } cancelProductOffering(){ this.viewMode = "OwnerView"; this.productSelectionForOffering = false; // reset call status this.callStatus.reset(); } onListInputUpdated(){ this.companyListInput = !this.companyListInput; this.productOfferingDetails.vatNumber = []; } onSelectedNetwork(networkId:string){ let network = this.settings.negotiationSettings.company.network.find(network => network.id == networkId); if(network){ this.productOfferingDetails.vatNumber = copy(network.vatNumber); } else{ this.productOfferingDetails.vatNumber = []; } } // the end of methods for product offering functionality onDeleteCatalogueImages(): void { this.deleteCatalogueModal.open('delete-images'); } onGenerateContractForCatalogue(): void { const index = this.catalogueUuids.findIndex(uuid => uuid == this.selectedCatalogue); // save the selected catalogue id this.catalogueIdForContractCreation = this.cataloguesIds[index]; // save the selected catalogue uuid this.catalogueUuidForContractCreation = this.selectedCatalogue; // change the view this.viewMode = "ContractView"; this.whiteBlackListPanelVisible = false; } onContractCreationCompleted(){ // change the view this.viewMode = "OwnerView"; // reset the selected catalogue id and uuid this.catalogueIdForContractCreation = null; this.catalogueUuidForContractCreation = null; } onAddCatalogue() { const userId = this.cookieService.get("user_id"); this.userService.getUserParty(userId).then(userParty => { let catalogue: Catalogue = new Catalogue(this.catalogueText, null, userParty, "", "", []); // add catalogue line to the end of catalogue this.catalogueService.postCatalogue(catalogue) .then(() => { this.catalogueText = ""; this.cancelAddingCatalogue(); this.ngOnInit(); }) .catch(() => { }) }).catch(() => { }); } cancelAddingCatalogue() { this.addCatalogue = false; } onAddingCatalogue() { this.addCatalogue = true; } onOpenCatalogueLine(e: Event) { e.stopImmediatePropagation(); } redirectToEdit(catalogueLine) { this.catalogueService.editCatalogueLine(catalogueLine); this.publishService.resetData("edit"); this.categoryService.resetSelectedCategories(); this.catalogueService.getCatalogueFromUuid(catalogueLine.goodsItem.item.catalogueDocumentReference.id) .then(res => { if (isLogisticsService(catalogueLine)) this.router.navigate(['catalogue/publish-logistic'], { queryParams: { cat: res.id} }); else this.router.navigate(['catalogue/publish-single'], { queryParams: { cat: res.id } }); }) .catch(() => { if (isLogisticsService(catalogueLine)) this.router.navigate(['catalogue/publish-logistic'], { queryParams: { cat: 'default' } }); else this.router.navigate(['catalogue/publish-single'], { queryParams: { cat: 'default' } }); }); } redirectToCopy(catalogueLine) { this.catalogueService.editCatalogueLine(catalogueLine); this.publishService.resetData("copy"); this.categoryService.resetSelectedCategories(); if (this.catalogueUuid == "all") { this.catalogueService.getCatalogueFromUuid(catalogueLine.goodsItem.item.catalogueDocumentReference.id) .then(res => { if (isLogisticsService(catalogueLine)) this.router.navigate(['catalogue/publish-logistic'], { queryParams: { cat: res.id} }); else this.router.navigate(['catalogue/publish-single'], { queryParams: { cat: res.id } }); }) .catch(() => { if (isLogisticsService(catalogueLine)) this.router.navigate(['catalogue/publish-logistic'], { queryParams: { cat: 'default' } }); else this.router.navigate(['catalogue/publish-single'], { queryParams: { cat: 'default' } }); }); } else { if (isLogisticsService(catalogueLine)) this.router.navigate(['catalogue/publish-logistic'], { queryParams: { cat: this.catalogueUuid } }); else this.router.navigate(['catalogue/publish-single'], { queryParams: { cat: this.catalogueUuid} }); } } deleteCatalogueLine(catalogueLine: CatalogueLine, i: number): void { this.appComponent.confirmModalComponent.open("Are you sure that you want to delete this catalogue item?").then(result => { if(result){ const status = this.getDeleteStatus(i); status.submit(); let catalogue_uuid = ""; if (this.catalogueService.catalogueResponse.catalogueUuid === "" || this.catalogueService.catalogueResponse.catalogueUuid == null) { catalogue_uuid = catalogueLine.goodsItem.item.catalogueDocumentReference.id; } else { catalogue_uuid = this.catalogueService.catalogueResponse.catalogueUuid; } this.catalogueService.deleteCatalogueLine(catalogue_uuid, catalogueLine.id) .then(() => { this.requestCatalogue(); status.callback("Catalogue line deleted", true); }) .catch(() => { status.error("Error while deleting catalogue line"); }); } }); } getDeleteStatus(index: number): CallStatus { return this.deleteStatuses[index % this.pageSize]; } onExportCatalogue(): void { this.deleteCatalogueModal.open('export'); } onChangeProductStatus(): void { this.deleteCatalogueModal.open('product-status'); } onUploadImage(): void { this.deleteCatalogueModal.open('upload-image'); } navigateToThePublishPage() { this.router.navigate(['/catalogue/publish-single']); } navigateToBulkUploadPage() { this.router.navigate(["/catalogue/publish-bulk"]); } initDataRetrieval() { this.productCatalogueRetrievalStatus.submit(); // first retrieve the identifiers this.catalogueService.getCatalogueIdsUUidsForParty().then((catalogueIds) => { var idList = []; var uuidList = []; for (var obj in catalogueIds) { idList.push(catalogueIds[obj][0]); uuidList.push(catalogueIds[obj][1]); } this.cataloguesIds = idList; this.catalogueUuids = uuidList; // once the ids are available, get the actual data this.requestCatalogue(); this.productCatalogueRetrievalStatus.callback("Successfully loaded catalogueId list", true); }).catch(() => { this.productCatalogueRetrievalStatus.error('Failed to get product catalogues'); }); } isPricePublicInformation(catLine:CatalogueLine){ return !(catLine.nonPublicInformation && catLine.nonPublicInformation.findIndex(value => value.id === NON_PUBLIC_FIELD_ID.DEFAULT_PRICE) !== -1); } }
apache-2.0
maheshraju-Huawei/actn
apps/pcc/app/src/main/java/org/onosproject/pcc/pccmgr/ctl/PcepPeerConfig.java
2114
package org.onosproject.pcc.pccmgr.ctl; import org.onlab.packet.Ip4Address; import org.onosproject.pcc.pccmgr.api.PcepConnectPeer; import org.onosproject.pcc.pccmgr.api.PcepPeerCfg; /** * Created by root1 on 3/6/16. */ public class PcepPeerConfig implements PcepPeerCfg { private int asNumber; private short holdTime; private Ip4Address pceIp = null; private State state; private boolean selfInitiated; private PcepConnectPeer connectPeer; private byte sessionId; /** * Constructor to initialize the values. */ PcepPeerConfig() { state = State.IDLE; selfInitiated = false; } @Override public int getAsNumber() { return this.asNumber; } @Override public void setAsNumber(int asNumber) { this.asNumber = asNumber; } @Override public short getHoldtime() { return this.holdTime; } @Override public void setHoldtime(short holdTime) { this.holdTime = holdTime; } @Override public void setPeerPceIp(String pceIp, int asNumber) { this.pceIp = Ip4Address.valueOf(pceIp); this.asNumber = asNumber; } @Override public String getPeerPceIp() { if (this.pceIp != null) { return this.pceIp.toString(); } else { return null; } } @Override public State getState() { return this.state; } @Override public void setState(State state) { this.state = state; } @Override public boolean getSelfInnitConnection() { return this.selfInitiated; } @Override public void setSelfInnitConnection(boolean selfInit) { this.selfInitiated = selfInit; } @Override public PcepConnectPeer connectPeer() { return this.connectPeer; } @Override public void setConnectPeer(PcepConnectPeer connectPeer) { this.connectPeer = connectPeer; } public void setSessionId(byte id) { this.sessionId = id; } public byte getSessionId() { return this.sessionId; } }
apache-2.0
virtualdataset/metagen-java
virtdata-lib-basics/src/main/java/io/virtdata/libbasics/shared/nondeterministic/ThreadNumToInteger.java
2127
/* * * Copyright 2015 Jonathan Shook * * 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 io.virtdata.libbasics.shared.nondeterministic; import io.virtdata.annotations.DeprecatedFunction; import io.virtdata.annotations.ThreadSafeMapper; import java.util.function.LongFunction; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Matches a digit sequence in the current thread name and caches it in a thread local. * This allows you to use any intentionally indexed thread factories to provide an analogue for * concurrency. Note that once the thread number is cached, it will not be refreshed. This means * you can't change the thread name and get an updated value. */ @ThreadSafeMapper @DeprecatedFunction("This is being replaced by ThreadNum() for naming consistency.") public class ThreadNumToInteger implements LongFunction<Integer> { private static final Pattern pattern = Pattern.compile("^.*?(\\d+).*$"); private ThreadLocal<Integer> threadLocalInt = new ThreadLocal<Integer>() { @Override protected Integer initialValue() { Matcher matcher = pattern.matcher(Thread.currentThread().getName()); if (matcher.matches()) { return Integer.valueOf(matcher.group(1)); } else { throw new RuntimeException( "Unable to match a digit sequence in thread name:" + Thread.currentThread().getName() ); } } }; @Override public Integer apply(long value) { return threadLocalInt.get(); } }
apache-2.0
skoba/openehr-ruby
spec/lib/openehr/rm/common/generic/revision_history_item_spec.rb
1336
require File.dirname(__FILE__) + '/../../../../../spec_helper' include OpenEHR::RM::Common::Generic include OpenEHR::RM::Support::Identification describe RevisionHistoryItem do before(:each)do version_id = double(ObjectVersionID, :objectid => 'RIO') audits = double(Array, :size => 30, :empty? => false) @revision_history_item = RevisionHistoryItem.new(:version_id => version_id, :audits => audits) end it 'should be an instance of RevisionHistoryItem' do expect(@revision_history_item).to be_an_instance_of RevisionHistoryItem end it 's version_id.objectid should be RIO' do expect(@revision_history_item.version_id.objectid).to eq('RIO') end it 's audits.size should be 30' do expect(@revision_history_item.audits.size).to be_equal 30 end it 'should raise ArgumentError when nil is assigned to version id' do expect { @revision_history_item.version_id = nil }.to raise_error ArgumentError end it 'should raise ArgumentError when nil is assinged to audits' do expect { @revision_history_item.audits = nil }.to raise_error ArgumentError end it 'should raise ArgumentError when empty is assinged to audits' do expect { @revision_history_item.audits = Array.new }.to raise_error ArgumentError end end
apache-2.0
nsicontest/nsi-ri
src/net/geant/nsicontest/reservation/psm/Provisioned.java
901
/** * */ package net.geant.nsicontest.reservation.psm; import javax.xml.ws.Holder; import org.ogf.schemas.nsi._2013._12.connection.types.ProvisionStateEnumType; import org.ogf.schemas.nsi._2013._12.framework.headers.CommonHeaderType; /** * A steady state for the provision state machine in which data plane resources for this reservation are in a provisioned state. * This state does not imply that data plane resources are active, but it does indicate that a uPA can active the data plane resources * if current_time is between startTime and endTime. */ final class Provisioned extends ProvisionState { Provisioned(ProvisionStateMachine psm) { super(psm); } @Override public ProvisionStateEnumType asNsiState() { return ProvisionStateEnumType.PROVISIONED; } @Override public void release(final Holder<CommonHeaderType> header) { psm.switchState(psm.RELEASING, header); } }
apache-2.0