code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package psidev.psi.mi.jami.utils.comparator.experiment; import psidev.psi.mi.jami.model.VariableParameterValueSet; import psidev.psi.mi.jami.utils.comparator.CollectionComparator; /** * Comparator for a collection of variableParameterValueSet * * @author Marine Dumousseau (marine@ebi.ac.uk) * @version $Id$ * @since <pre>22/05/13</pre> */ public class VariableParameterValueSetCollectionComparator extends CollectionComparator<VariableParameterValueSet> { /** * Creates a new CollectionComparator. */ public VariableParameterValueSetCollectionComparator() { super(new VariableParameterValueSetComparator()); } /** {@inheritDoc} */ @Override public VariableParameterValueSetComparator getObjectComparator() { return (VariableParameterValueSetComparator) super.getObjectComparator(); } }
MICommunity/psi-jami
jami-core/src/main/java/psidev/psi/mi/jami/utils/comparator/experiment/VariableParameterValueSetCollectionComparator.java
Java
apache-2.0
852
/* * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana */ package org.eclipse.jnosql.artemis.column; import jakarta.nosql.column.ColumnFamilyManager; import jakarta.nosql.mapping.column.ColumnTemplate; import jakarta.nosql.mapping.column.ColumnTemplateProducer; import jakarta.nosql.tck.test.CDIExtension; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import javax.inject.Inject; import static org.junit.jupiter.api.Assertions.assertNotNull; @CDIExtension public class DefaultColumnTemplateProducerTest { @Inject private ColumnTemplateProducer producer; @Test public void shouldReturnErrorWhenColumnFamilyManagerNull() { Assertions.assertThrows(NullPointerException.class, () -> producer.get(null)); } @Test public void shouldReturn() { ColumnFamilyManager manager = Mockito.mock(ColumnFamilyManager.class); ColumnTemplate columnTemplate = producer.get(manager); assertNotNull(columnTemplate); } }
JNOSQL/diana
artemis/artemis-column/src/test/java/org/eclipse/jnosql/artemis/column/DefaultColumnTemplateProducerTest.java
Java
apache-2.0
1,551
/* * 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.carbondata.core.datastore.compression.nondecimal; import java.math.BigDecimal; import java.nio.ByteBuffer; import org.apache.carbondata.common.logging.LogService; import org.apache.carbondata.common.logging.LogServiceFactory; import org.apache.carbondata.core.datastore.chunk.store.MeasureChunkStoreFactory; import org.apache.carbondata.core.datastore.chunk.store.MeasureDataChunkStore; import org.apache.carbondata.core.datastore.compression.Compressor; import org.apache.carbondata.core.datastore.compression.CompressorFactory; import org.apache.carbondata.core.datastore.compression.ValueCompressionHolder; import org.apache.carbondata.core.metadata.datatype.DataType; import org.apache.carbondata.core.util.ValueCompressionUtil; public class CompressionNonDecimalDefault extends ValueCompressionHolder<double[]> { /** * Attribute for Carbon LOGGER */ private static final LogService LOGGER = LogServiceFactory.getLogService(CompressionNonDecimalDefault.class.getName()); /** * doubleCompressor. */ private static Compressor compressor = CompressorFactory.getInstance().getCompressor(); /** * value. */ private double[] value; private MeasureDataChunkStore<double[]> measureChunkStore; private double divisionFactory; @Override public void uncompress(DataType dataType, byte[] compressedData, int offset, int length, int decimalPlaces, Object maxValueObject, int numberOfRows) { super.unCompress(compressor, dataType, compressedData, offset, length, numberOfRows, maxValueObject, decimalPlaces); } @Override public void compress() { compressedValue = super.compress(compressor, DataType.DOUBLE, value); } @Override public void setValue(double[] value) { this.value = value; } @Override public double[] getValue() { return this.value; } @Override public void setValueInBytes(byte[] value) { ByteBuffer buffer = ByteBuffer.wrap(value); this.value = ValueCompressionUtil.convertToDoubleArray(buffer, value.length); } @Override public long getLongValue(int index) { throw new UnsupportedOperationException( "Long value is not defined for CompressionNonDecimalDefault"); } @Override public double getDoubleValue(int index) { return (measureChunkStore.getDouble(index) / divisionFactory); } @Override public BigDecimal getBigDecimalValue(int index) { throw new UnsupportedOperationException( "Big decimal value is not defined for CompressionNonDecimalDefault"); } @Override public void freeMemory() { this.measureChunkStore.freeMemory(); } @Override public void setValue(double[] data, int numberOfRows, Object maxValueObject, int decimalPlaces) { this.measureChunkStore = MeasureChunkStoreFactory.INSTANCE .getMeasureDataChunkStore(DataType.DOUBLE, numberOfRows); this.measureChunkStore.putData(data); this.divisionFactory = Math.pow(10, decimalPlaces); } }
ksimar/incubator-carbondata
core/src/main/java/org/apache/carbondata/core/datastore/compression/nondecimal/CompressionNonDecimalDefault.java
Java
apache-2.0
3,766
<?php //neue Datenbankverbindung $mysqli = new mysqli("localhost", "root", "", "zpfisdsql1"); ?>
zpfisd-bbc/BBC-Chat
ressources/config.php
PHP
apache-2.0
96
// HTMLParser Library - A java-based parser for HTML // http://htmlparser.org // Copyright (C) 2006 Derrick Oswald // // Revision Control Information // // $URL: https://svn.sourceforge.net/svnroot/htmlparser/trunk/filterbuilder/src/main/java/org/htmlparser/parserapplications/filterbuilder/HtmlTreeModel.java $ // $Author: derrickoswald $ // $Date: 2006-09-16 10:44:17 -0400 (Sat, 16 Sep 2006) $ // $Revision: 4 $ // // This library is free software; you can redistribute it and/or // modify it under the terms of the Common Public License; either // version 1.0 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // Common Public License for more details. // // You should have received a copy of the Common Public License // along with this library; if not, the license is available from // the Open Source Initiative (OSI) website: // http://opensource.org/licenses/cpl1.0.php package org.htmlparser.parserapplications.filterbuilder; import java.util.Vector; import javax.swing.tree.*; import javax.swing.event.*; import org.htmlparser.Node; import org.htmlparser.tags.Html; import org.htmlparser.util.NodeList; /** * Quick and dirty tree model for HTML nodes. */ public class HtmlTreeModel implements TreeModel { /** * The list of tree listeners. */ protected Vector mTreeListeners; /** * The root {@link Node}. */ protected Node mRoot; /** * Create an HTML tree view. * @param root The nodes at the root of the tree * (the nodes are wrapped in an Html node that is never seen * because it's the root, but this makes all downstream processing * super-simple because every tree node is then a {@link Node}, * not sometimes a {@link NodeList} at the root). */ public HtmlTreeModel (NodeList root) { mTreeListeners = new Vector (); // for simplicity we encapsulate the nodelist in a Html tag mRoot = new Html (); mRoot.setChildren (root); } // // TreeModel interface // /** * Adds a listener for the TreeModelEvent posted after the tree changes. * @param l {@inheritDoc} */ public void addTreeModelListener (TreeModelListener l) { synchronized (mTreeListeners) { if (!mTreeListeners.contains(l)) mTreeListeners.addElement(l); } } /** * Removes a listener previously added with addTreeModelListener(). * @param l {@inheritDoc} */ public void removeTreeModelListener(TreeModelListener l) { synchronized (mTreeListeners) { mTreeListeners.removeElement (l); } } /** * Returns the child of parent at index index in the parent's child array. * @param parent {@inheritDoc} * @param index {@inheritDoc} * @return {@inheritDoc} */ public Object getChild (Object parent, int index) { Node node; NodeList list; Object ret; node = (Node)parent; list = node.getChildren (); if (null == list) throw new IllegalArgumentException ("invalid parent for getChild()"); else ret = list.elementAt (index); return (ret); } /** * Returns the number of children of parent. * @param parent {@inheritDoc} * @return {@inheritDoc} */ public int getChildCount (Object parent) { Node node; NodeList list; int ret; ret = 0; node = (Node)parent; list = node.getChildren (); if (null != list) ret = list.size (); return (ret); } /** * Returns the index of child in parent. * @param parent {@inheritDoc} * @param child {@inheritDoc} * @return {@inheritDoc} */ public int getIndexOfChild (Object parent, Object child) { Node node; NodeList list; int count; int ret; ret = -1; node = (Node)parent; list = node.getChildren (); if (null != list) { count = list.size (); for (int i = 0; i < count; i++) if (child == list.elementAt (i)) { ret = i; break; } } else throw new IllegalArgumentException ("invalid parent for getIndexOfChild()"); if (0 > ret) throw new IllegalArgumentException ("child not found in getIndexOfChild()"); return (ret); } /** * Returns the root of the tree. * @return {@inheritDoc} */ public Object getRoot () { return (mRoot); } /** * Returns true if node is a leaf. * @param node {@inheritDoc} * @return {@inheritDoc} */ public boolean isLeaf (Object node) { NodeList list; boolean ret; list = ((Node)node).getChildren (); if (null == list) ret = true; else ret = 0 == list.size (); return (ret); } /** * Messaged when the user has altered the value for the item identified by path to newValue. * @param path {@inheritDoc} * @param newValue {@inheritDoc} */ public void valueForPathChanged (TreePath path, Object newValue) { TreeModelEvent event; Vector v; event = new TreeModelEvent (this, path); synchronized (mTreeListeners) { v = (Vector)mTreeListeners.clone (); } for (int i = 0; i < v.size (); i++) { TreeModelListener listener = (TreeModelListener)v.elementAt (i); listener.treeStructureChanged (event); } } }
patrickfav/tuwien
master/swt workspace/HTMLParser/src/org/htmlparser/parserapplications/filterbuilder/HtmlTreeModel.java
Java
apache-2.0
5,998
<?php return [ 'Holsem-s12' => 'S12库存', 'Holsem-x12b' => 'X12B库存', 'Holsem-x5' => 'X5库存', 'Holsem-x5b' => 'X5B库存', 'Holsem-x8' => 'X8库存', 'Holsem-x8b' => 'X8B库存', 'Holsem-a1' => 'A1库存', 'Createtime' => '时间', 'Updatetime' => '更新时间' ];
yangqihua/holsem
application/admin/lang/zh-cn/inventory.php
PHP
apache-2.0
329
module Fog module OpenStackCore class IdentityV2 class Real def list_roles admin_request( :method => 'GET', :expects => 200, :path => '/v2.0/OS-KSADM/roles', ) end end # Real class Mock end end # OpenStackCore end # IdentityV2 end # Fog
fog/fog-openstack-core
lib/fog/openstackcore/requests/identity/v2/list_roles.rb
Ruby
apache-2.0
352
/* * 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.phoenix.pherf; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.ExpectedSystemExit; import java.util.Properties; import static org.junit.Assert.assertEquals; public class PherfTest { @Rule public final ExpectedSystemExit exit = ExpectedSystemExit.none(); @Test public void testListArgument() { String[] args = {"-listFiles"}; Pherf.main(args); } @Test public void testUnknownOption() { String[] args = {"-drop", "all", "-q", "-m","-bsOption"}; // Makes sure that System.exit(1) is called. exit.expectSystemExitWithStatus(1); Pherf.main(args); } @Test public void testDefaultLogPerNRowsArgument() throws Exception { String[] args = {"-listFiles"}; assertEquals(Long.valueOf(PherfConstants.LOG_PER_NROWS), getLogPerNRowsValue(new Pherf(args).getProperties())); } @Test public void testCustomizedLogPerNRowsArgument() throws Exception { Long customizedPerNRows = 15l; String[] args = {"-listFiles", "-log_per_nrows", customizedPerNRows.toString()}; assertEquals(customizedPerNRows, getLogPerNRowsValue(new Pherf(args).getProperties())); } @Test public void testInvalidLogPerNRowsArgument() throws Exception { Long zero = 0l; Long negativeOne = -1l; String invaildNum = "abc"; String[] args = {"-listFiles", "-log_per_nrows", zero.toString()}; assertEquals(Long.valueOf(PherfConstants.LOG_PER_NROWS), getLogPerNRowsValue(new Pherf(args).getProperties())); String[] args2 = {"-listFiles", "-log_per_nrows", negativeOne.toString()}; assertEquals(Long.valueOf(PherfConstants.LOG_PER_NROWS), getLogPerNRowsValue(new Pherf(args2).getProperties())); String[] args3 = {"-listFiles", "-log_per_nrows", invaildNum}; assertEquals(Long.valueOf(PherfConstants.LOG_PER_NROWS), getLogPerNRowsValue(new Pherf(args3).getProperties())); } private Long getLogPerNRowsValue(Properties prop) { return Long.valueOf(prop.getProperty(PherfConstants.LOG_PER_NROWS_NAME)); } }
apurtell/phoenix
phoenix-pherf/src/test/java/org/apache/phoenix/pherf/PherfTest.java
Java
apache-2.0
3,071
package com.example.designsupportlibrary.weather.model; public class Main { public Double temp; public Double humidity; public Double pressure; public Double temp_min; public Double temp_max; }
chikkutechie/androidexamples
DesignSupportLibrary/src/main/java/com/example/designsupportlibrary/weather/model/Main.java
Java
apache-2.0
224
package com.coolbiweather.android.gson; /** * Created by KaifengB1 on 2017/6/20. */ public class AQI { public AQICity city; public class AQICity { public String aqi; public String pm25; } }
qiantu98/coolweather
app/src/main/java/com/coolbiweather/android/gson/AQI.java
Java
apache-2.0
223
package java_mypft.mantis.appmanager; import java_mypft.mantis.model.UserData; import org.openqa.selenium.By; public class ReplacePasswordHelper extends HelperBase { public ReplacePasswordHelper(ApplicationManager app) { super(app); } public void loginAsAdmin() { wd.get(app.getProperty("web.baseUrl") + "/login_page.php"); type(By.name("username"), "administrator"); type(By.name("password"), "root"); click(By.xpath("//form[@id='login-form']/fieldset/input[2]")); } public void resetUserPassword(int userId) { wd.manage().window().maximize(); click(By.xpath("//div[@id='sidebar']//span[.=' управление ']")); click(By.xpath("//div[@class='row']//a[.='Управление пользователями']")); click(By.xpath(String.format("//a[@href='manage_user_edit_page.php?user_id=%s']", userId))); click(By.xpath("//span//input[@value='Сбросить пароль']")); click(By.xpath("//div[@class='btn-group']//a[.='Продолжить']")); } public void renewalPassword(String confirmationLink, String password, UserData userData) { wd.get(confirmationLink); type(By.id("realname"), userData.getRealname()); type(By.id("password"),password); type(By.id("password-confirm"),password); click(By.xpath("//span[@class='submit-button']/button")); } }
MBarkovskaya/java_mypft
mantis-tests/src/test/java/java_mypft/mantis/appmanager/ReplacePasswordHelper.java
Java
apache-2.0
1,388
/* * Copyright 2014-2019 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.sagemaker.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.sagemaker.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * GetSearchSuggestionsRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class GetSearchSuggestionsRequestMarshaller { private static final MarshallingInfo<String> RESOURCE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Resource").build(); private static final MarshallingInfo<StructuredPojo> SUGGESTIONQUERY_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("SuggestionQuery").build(); private static final GetSearchSuggestionsRequestMarshaller instance = new GetSearchSuggestionsRequestMarshaller(); public static GetSearchSuggestionsRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(GetSearchSuggestionsRequest getSearchSuggestionsRequest, ProtocolMarshaller protocolMarshaller) { if (getSearchSuggestionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getSearchSuggestionsRequest.getResource(), RESOURCE_BINDING); protocolMarshaller.marshall(getSearchSuggestionsRequest.getSuggestionQuery(), SUGGESTIONQUERY_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
jentfoo/aws-sdk-java
aws-java-sdk-sagemaker/src/main/java/com/amazonaws/services/sagemaker/model/transform/GetSearchSuggestionsRequestMarshaller.java
Java
apache-2.0
2,420
/* * 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 student_grade_calculator; import java.util.TreeMap; /** * * @author Seth */ public class Categories{ public double percentage; public TreeMap<String, Student_Grade_Calculator.Assignment> entries; public String name; public Categories(String name){ this.name = name; } public void add(String name, Student_Grade_Calculator.Assignment assignment){ entries.put(name, assignment); } }
nakasoori/Student-Grade-Tracker
Student_Grade_Calculator/src/student_grade_calculator/Categories.java
Java
apache-2.0
705
package jflowmap.util.piccolo; import edu.umd.cs.piccolo.PNode; import edu.umd.cs.piccolo.activities.PActivity; import edu.umd.cs.piccolo.event.PBasicInputEventHandler; import edu.umd.cs.piccolo.event.PInputEvent; import edu.umd.cs.piccolo.util.PAffineTransform; import edu.umd.cs.piccolo.util.PBounds; import edu.umd.cs.piccolox.nodes.PClip; /** * @author Ilya Boyandin */ public class PCollapsableItemsContainer extends PNode { private static final double itemLabelSpacing = 5; private static final double itemItemSpacing = 5; private static final double itemBodySpacing = 5; private static final int collapseAnimationDuration = 200; private final boolean collapsedByDefault; private final CollapseHandler collapseHandler; private double labelsWidth; public PCollapsableItemsContainer() { this(true); } public PCollapsableItemsContainer(boolean collapsedByDefault) { this.collapsedByDefault = collapsedByDefault; this.collapseHandler = new CollapseHandler(); } public void layoutItems() { double labelMaxX = 0; for (Item item : PNodes.childrenOfType(this, Item.class)) { PBounds lb = item.getLabel().getFullBoundsReference(); double mx = lb.getMaxX(); if (mx > labelMaxX) labelMaxX = mx; } this.labelsWidth = labelMaxX; double accHeight = 0; for (Item item : PNodes.childrenOfType(this, Item.class)) { PNode head = item.getHead(); PNode label = item.getLabel(); PClip bodyClip = item.getBodyClip(); // PNodes.moveTo(label, getX(), getY() + accHeight + itemItemSpacing); PNodes.moveTo(label, labelMaxX - label.getFullBoundsReference().getWidth(), getY() + accHeight + itemItemSpacing); PNodes.moveTo(head, getX() + labelMaxX + itemLabelSpacing, getY() + accHeight); PNodes.moveTo(bodyClip, getX() + labelMaxX + itemLabelSpacing, getY() + accHeight + head.getHeight() + itemBodySpacing); accHeight += Math.max(head.getHeight(), label.getHeight()) + itemItemSpacing; } repaint(); } public double getItemsOffsetX() { return labelsWidth + itemLabelSpacing; } public Item addNewItem(String labelText, PNode head, PNode body) { return addNewItem(createLabel(labelText), head, body); } public Item addNewItem(PNode label, PNode head, PNode body) { Item item = new Item(label, head, body, collapsedByDefault); addChild(item); return item; } public void toggleCollapsed(Item item) { int index = PNodes.indexOfChild(this, item); if (index >= 0) { // shift subsequent items for (int i = index + 1, numChildren = getChildrenCount(); i < numChildren; i++) { PNode child = getChild(i); if (child instanceof Item) { final Item it = (Item)child; it.terminateAnimationIfStepping(); it.animateToTransform(item.shift(it.getTransform()), collapseAnimationDuration); } } item.setCollapsed(!item.isCollapsed()); } } public Item findItemByLabel(PNode label) { for (Item item : PNodes.childrenOfType(this, Item.class)) { if (item.getLabel() == label) return item; } return null; } public class Item extends PNode { private final PNode label; private final PNode head; private final PClip bodyClip; // private final Rectangle2D clipRect; private final PNode body; private boolean collapsed; private PActivity lastActivity; private Item(PNode label, PNode head, PNode body, boolean collapsed) { this.label = label; this.head = head; this.body = body; if (label != null) { addChild(label); } if (head != null) { addChild(head); } this.bodyClip = new PClip(); this.bodyClip.setStroke(null); PBounds bb = getBodyBounds(); bodyClip.setPathToRectangle((float)bb.x, (float)bb.y, (float)bb.width, (float)bb.height); this.collapsed = collapsed; updateClip(false); if (body != null) { addChild(bodyClip); bodyClip.addChild(body); } } public PCollapsableItemsContainer getContainer() { return PCollapsableItemsContainer.this; } public PNode getLabel() { return label; } public PNode getHead() { return head; } public PNode getBody() { return body; } public PClip getBodyClip() { return bodyClip; } public boolean isCollapsed() { return collapsed; } public void setCollapsed(boolean collapsed) { boolean oldCollapsed = this.collapsed; this.collapsed = collapsed; if (oldCollapsed != collapsed) { updateClip(true); } } public void toggleCollapsed() { PCollapsableItemsContainer.this.toggleCollapsed(this); } private void updateClip(boolean animate) { PBounds bb = getBodyBounds(); if (collapsed) { bb.height = 0; } if (animate) { bodyClip.animateToBounds(bb.x, bb.y, bb.width, bb.height, collapseAnimationDuration); } else { bodyClip.setBounds(bb.x, bb.y, bb.width, bb.height); } } private void terminateAnimationIfStepping() { if (lastActivity != null && lastActivity.isStepping()) { lastActivity.terminate(PActivity.TERMINATE_AND_FINISH_IF_STEPPING); lastActivity = null; } } @Override public boolean addActivity(PActivity activity) { if (super.addActivity(activity)) { lastActivity = activity; return true; } else { return false; } } private PAffineTransform shift(PAffineTransform t) { PAffineTransform st = new PAffineTransform(); st.setOffset(0, (collapsed ? +1 : -1) * (getBodyBounds().getHeight() + itemBodySpacing * 2)); st.concatenate(t); return st; } private PBounds getBodyBounds() { PBounds fb = body.getFullBounds(); for (PNode child : PNodes.childrenOf(body)) { fb.add(child.getBoundsReference()); } return fb; } } public PLabel createLabel(String text) { PLabel label = new PLabel(text); label.addInputEventListener(collapseHandler); return label; } public class CollapseHandler extends PBasicInputEventHandler { @Override public void mouseClicked(PInputEvent event) { PLabel label = PNodes.getAncestorOfType(event.getPickedNode(), PLabel.class); if (label != null) { findItemByLabel(label).toggleCollapsed(); } } } }
e3bo/jflowmap
src/jflowmap/util/piccolo/PCollapsableItemsContainer.java
Java
apache-2.0
6,746
var deepExtend = require('deep-extend'); var flat = require('flat'); var fs = require('fs'); var path = require('path'); var propsParser = require('properties-parser'); var defaultConfig = require(path.join(__dirname,'config.json')); var homePath = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME']; var currentConfigPath = path.join(process.cwd(),'stormpath.json'); var userConfigPath = path.join(homePath,'stormpath.json'); var currentConfig = fs.existsSync(currentConfigPath) ? fs.readSync(currentConfigPath) : {}; var userConfig = fs.existsSync(userConfigPath) ? fs.readSync(userConfigPath) : {}; /** * @class Config * @param {Object} config Config overrides * * Constructs a Stormpath Config object, by looking in the following locations: * * 0. use default internal config * 1. stormpath.json in ~/.stormpath/stormpath.json * 2. stormpath.json in current directory * 3. read from environment variables * 4. passed in to constructor * */ function Config(options){ deepExtend(this, defaultConfig); deepExtend(this, userConfig||{}); deepExtend(this, currentConfig||{}); deepExtend(this, this.getEnvVars()); deepExtend(this, options||{}); var apiKeyFileName = this.client.apiKey.file; if ( apiKeyFileName && !this.client.apiKey.id && !this.client.apiKey.secret ){ if (!fs.existsSync(apiKeyFileName)) { throw new Error('Client API key file not found: '+ apiKeyFileName); } var props = propsParser.read(apiKeyFileName); if (!props || !props.id || !props.secret) { throw new Error('Unable to read properties file: ' + apiKeyFileName); } this.client.apiKey.id = props.id; this.client.apiKey.secret = props.secret; } } Config.prototype.getEnvVars = function(){ var flattendDefaultConfig = flat.flatten(this,{ delimiter: '_' }); var flatEnvValues = Object.keys(flattendDefaultConfig) .reduce(function(envVarMap,key){ var envKey = 'STORMPATH_' + key.toUpperCase(); var value = process.env[envKey]; if(value!==undefined){ envVarMap[key] = typeof flattendDefaultConfig[key] === 'number' ? parseInt(value,10) : value; } return envVarMap; },{}); return flat.unflatten(flatEnvValues,{delimiter:'_'}); }; module.exports = Config;
wakashige/stormpath-sdk-node
lib/Config.js
JavaScript
apache-2.0
2,308
/* * Copyright 2010 JBoss 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.drools.planner.examples.curriculumcourse.domain; import com.thoughtworks.xstream.annotations.XStreamAlias; import org.apache.commons.lang.builder.CompareToBuilder; import org.drools.planner.examples.common.domain.AbstractPersistable; @XStreamAlias("Day") public class Day extends AbstractPersistable { private int dayIndex; public int getDayIndex() { return dayIndex; } public void setDayIndex(int dayIndex) { this.dayIndex = dayIndex; } @Override public String toString() { return Integer.toString(dayIndex); } }
cyberdrcarr/optaplanner
drools-planner-examples/src/main/java/org/drools/planner/examples/curriculumcourse/domain/Day.java
Java
apache-2.0
1,184
/* * Copyright (C) 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package models.petstore; import fathom.rest.swagger.ApiProperty; import fathom.rest.swagger.ApiModel; import java.util.Date; /** * @author James Moger */ @ApiModel(description = "an order for one or more pets") public class Order { @ApiProperty long id; @ApiProperty long petId; @ApiProperty int quantity; @ApiProperty(description = "Order Status") OrderStatus status; @ApiProperty Date shipDate; @ApiProperty boolean complete; }
gitblit/fathom
fathom-integration-test/src/main/java/models/petstore/Order.java
Java
apache-2.0
1,109
/* * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dataMapper.diagram.custom.action; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.ecore.EObject; import org.eclipse.gef.EditPart; import org.eclipse.gmf.runtime.common.ui.action.AbstractActionHandler; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PlatformUI; import dataMapper.diagram.custom.util.DialogDisplayUtils; import dataMapper.diagram.custom.util.SchemaKeyEditorDialog; import dataMapper.impl.InputImpl; /** * This class handles context menu action 'load input schema' */ public class LoadInputSchemaAction extends AbstractActionHandler { private static final int DIALOG_HEIGHT = 250; private static final int DIALOG_WIDTH = 520; private static final String CONFIGURE_INPUT_SCHEMA_ACTION_ID = "configure-input-schema-action-id"; //$NON-NLS-1$ private static final String INVALID_SELECTION = "Invalid selection."; //$NON-NLS-1$ private static final String INPUT_SCHEMA_DIALOG = Messages.LoadInputSchemaAction_InputSchemaDialog; private static final String SCHEMA_TYPE_INPUT = Messages.LoadInputSchemaAction_SchemaTypeInput; private static final String LOAD_INPUT_SCHEMA_FROM_FILE = Messages.LoadInputSchemaAction_LoadFromFile; public LoadInputSchemaAction(IWorkbenchPart workbenchPart) { super(workbenchPart); setId(CONFIGURE_INPUT_SCHEMA_ACTION_ID); setText(LOAD_INPUT_SCHEMA_FROM_FILE); setToolTipText(LOAD_INPUT_SCHEMA_FROM_FILE); ISharedImages workbenchImages = PlatformUI.getWorkbench().getSharedImages(); setImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_NEW_WIZARD)); } protected void doRun(IProgressMonitor progressMonitor) { EditPart selectedEP = getSelectedEditPart(); if (selectedEP != null) { if (selectedEP.getModel() instanceof View) { EObject selectedObj = ((View) selectedEP.getModel()).getElement(); Assert.isTrue(selectedObj instanceof InputImpl, INVALID_SELECTION); } Shell shell = new Shell(Display.getDefault()); // Schema key editor dialog : create/import schema SchemaKeyEditorDialog dialog = new SchemaKeyEditorDialog(shell, selectedEP, getWorkbenchPart(), SCHEMA_TYPE_INPUT); dialog.create(); dialog.getShell().setSize(DIALOG_WIDTH, DIALOG_HEIGHT); dialog.getShell().setText(INPUT_SCHEMA_DIALOG); DialogDisplayUtils.setPositionInCenter(dialog.getShell()); dialog.getShell().forceActive(); dialog.open(); // This handles loading of input schema } } protected EditPart getSelectedEditPart() { IStructuredSelection selection = getStructuredSelection(); if (selection.size() == 1) { Object selectedEP = selection.getFirstElement(); if (selectedEP instanceof EditPart) { return (EditPart) selectedEP; } } return null; /* In case of selecting the wrong editpart */ } @Override public void refresh() { /* refresh action. Does not do anything */ } }
splinter/developer-studio
data-mapper/org.wso2.developerstudio.visualdatamapper.diagram/src/dataMapper/diagram/custom/action/LoadInputSchemaAction.java
Java
apache-2.0
3,764
from adobject import * class ADComputer(ADObject): """Python class representing a computer object in Active Directory.""" @classmethod def create(cls, name, container_object, enable=True, optional_attributes={}): """Creates and returns a new computer object.""" assert type(name) == str assert container_object.__class__.__name__ == 'ADContainer' return container_object.create_computer(name=name,enable=enable,optional_attributes=optional_attributes) def get_creator(self): """returns ADUser object of the user who added the computer to the domain. Returns None if user no longer exists.""" try: sid = str(pyadutils.convert_sid(self.get_attribute('mS-DS-CreatorSID', False))).split(':')[1] dn = adsearch.by_sid(sid) return ADUser(dn) except: return None ADObject._py_ad_object_mappings['computer'] = ADComputer
ECS-Security/Hive
pyad/adcomputer.py
Python
apache-2.0
934
/* * Copyright 2016 Lime - HighTech Solutions 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 io.getlime.push.model.entity; import java.util.Date; import java.util.Map; /** * Class representing a message body - the information that do not serve as a "message descriptor" * but rather as payload. This data package is a subject of end-to-end encryption. */ public class PushMessageBody { private String title; private String body; private String icon; private Integer badge; private String sound; private String category; private String collapseKey; private Date validUntil; private Map<String, Object> extras; /** * Push message title. Short and digestible message stating the message purpose, for example "Balance update". * @return Push message title. */ public String getTitle() { return title; } /** * Set push message title. Short and digestible message stating the message purpose, for * example "Balance update". * @param title Push message title. */ public void setTitle(String title) { this.title = title; } /** * Get long message text, used as a notification body. Place your message to this property, * for example "Your today's balance is $782.40". * @return Notification body text. */ public String getBody() { return body; } /** * Set long message text, used as a notification body. Place your message to this property, * for example "Your today's balance is $782.40". * @param body Notification body text. */ public void setBody(String body) { this.body = body; } /** * App icon badge value (iOS only). * @return App icon badge. */ public Integer getBadge() { return badge; } /** * Set app icon badge value (iOS only). * @param badge App icon badge. */ public void setBadge(Integer badge) { this.badge = badge; } /** * Get the sound name to be played with the notification. * @return Sound name. */ public String getSound() { return sound; } /** * Set the sound name to be played with the notification. * @param sound Sound name. */ public void setSound(String sound) { this.sound = sound; } /** * Get the notification category, used to distinguish actions assinged with the notification. * @return Notification category. */ public String getCategory() { return category; } /** * Set the notification category, used to distinguish actions assinged with the notification. * @param category Notification category. */ public void setCategory(String category) { this.category = category; } /** * Get the collapse key, used to collapse messages on the server in case messages cannot be delivered and * as a tag / thread ID to group messages with the same content type. * @return Notification collapse key. */ public String getCollapseKey() { return collapseKey; } /** * Set the collapse key, used to collapse messages on the server in case messages cannot be delivered and * as a tag / thread ID to group messages with the same content type. * @param collapseKey Notification collapse key. */ public void setCollapseKey(String collapseKey) { this.collapseKey = collapseKey; } /** * Get notification delivery validity (timestamp message should live to in case it's not delivered immediately). * @return Validity timestamp. */ public Date getValidUntil() { return validUntil; } /** * Set notification delivery validity (timestamp message should live to in case it's not delivered immediately). * @param validUntil Validity timestamp. */ public void setValidUntil(Date validUntil) { this.validUntil = validUntil; } /** * Get the map (Map&lt;String, Object&gt;) with optional message parameters. This is translated to custom parameters * on iOS and to data notification payload object on Android. * @return Extra attributes. */ public Map<String, Object> getExtras() { return extras; } /** * Set the map (Map&lt;String, Object&gt;) with optional message parameters. This is translated to custom parameters * on iOS and to data notification payload object on Android. * @param extras Extra attributes. */ public void setExtras(Map<String, Object> extras) { this.extras = extras; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PushMessageBody that = (PushMessageBody) o; if (title != null ? !title.equals(that.title) : that.title != null) return false; return body != null ? body.equals(that.body) : that.body == null; } @Override public int hashCode() { int result = title != null ? title.hashCode() : 0; result = 31 * result + (body != null ? body.hashCode() : 0); return result; } }
martintupy/powerauth-push-server
powerauth-push-model/src/main/java/io/getlime/push/model/entity/PushMessageBody.java
Java
apache-2.0
5,878
package org.docksidestage.sqlserver.dbflute.cbean.bs; import org.dbflute.cbean.AbstractConditionBean; import org.dbflute.cbean.ConditionBean; import org.dbflute.cbean.ConditionQuery; import org.dbflute.cbean.chelper.*; import org.dbflute.cbean.coption.*; import org.dbflute.cbean.dream.*; import org.dbflute.cbean.sqlclause.SqlClause; import org.dbflute.cbean.sqlclause.SqlClauseCreator; import org.dbflute.cbean.scoping.*; import org.dbflute.dbmeta.DBMetaProvider; import org.dbflute.twowaysql.factory.SqlAnalyzerFactory; import org.dbflute.twowaysql.style.BoundDateDisplayTimeZoneProvider; import org.docksidestage.sqlserver.dbflute.allcommon.DBFluteConfig; import org.docksidestage.sqlserver.dbflute.allcommon.DBMetaInstanceHandler; import org.docksidestage.sqlserver.dbflute.allcommon.ImplementedInvokerAssistant; import org.docksidestage.sqlserver.dbflute.allcommon.ImplementedSqlClauseCreator; import org.docksidestage.sqlserver.dbflute.cbean.*; import org.docksidestage.sqlserver.dbflute.cbean.cq.*; /** * The base condition-bean of VENDOR_CHECK. * @author DBFlute(AutoGenerator) */ public class BsVendorCheckCB extends AbstractConditionBean { // =================================================================================== // Attribute // ========= protected VendorCheckCQ _conditionQuery; // =================================================================================== // Constructor // =========== public BsVendorCheckCB() { if (DBFluteConfig.getInstance().isPagingCountLater()) { enablePagingCountLater(); } if (DBFluteConfig.getInstance().isPagingCountLeastJoin()) { enablePagingCountLeastJoin(); } if (DBFluteConfig.getInstance().isNonSpecifiedColumnAccessAllowed()) { enableNonSpecifiedColumnAccess(); } if (DBFluteConfig.getInstance().isSpecifyColumnRequired()) { enableSpecifyColumnRequired(); } xsetSpecifyColumnRequiredExceptDeterminer(DBFluteConfig.getInstance().getSpecifyColumnRequiredExceptDeterminer()); if (DBFluteConfig.getInstance().isSpecifyColumnRequiredWarningOnly()) { xenableSpecifyColumnRequiredWarningOnly(); } if (DBFluteConfig.getInstance().isQueryUpdateCountPreCheck()) { enableQueryUpdateCountPreCheck(); } } // =================================================================================== // SqlClause // ========= @Override protected SqlClause createSqlClause() { SqlClauseCreator creator = DBFluteConfig.getInstance().getSqlClauseCreator(); if (creator != null) { return creator.createSqlClause(this); } return new ImplementedSqlClauseCreator().createSqlClause(this); // as default } // =================================================================================== // DB Meta // ======= @Override protected DBMetaProvider getDBMetaProvider() { return DBMetaInstanceHandler.getProvider(); // as default } public String asTableDbName() { return "VENDOR_CHECK"; } // =================================================================================== // PrimaryKey Handling // =================== /** * Accept the query condition of primary key as equal. * @param vendorCheckId : PK, NotNull, numeric(16). (NotNull) * @return this. (NotNull) */ public VendorCheckCB acceptPK(Long vendorCheckId) { assertObjectNotNull("vendorCheckId", vendorCheckId); BsVendorCheckCB cb = this; cb.query().setVendorCheckId_Equal(vendorCheckId); return (VendorCheckCB)this; } /** * Accept the query condition of primary key as equal. (old style) * @param vendorCheckId : PK, NotNull, numeric(16). (NotNull) */ public void acceptPrimaryKey(Long vendorCheckId) { assertObjectNotNull("vendorCheckId", vendorCheckId); BsVendorCheckCB cb = this; cb.query().setVendorCheckId_Equal(vendorCheckId); } public ConditionBean addOrderBy_PK_Asc() { query().addOrderBy_VendorCheckId_Asc(); return this; } public ConditionBean addOrderBy_PK_Desc() { query().addOrderBy_VendorCheckId_Desc(); return this; } // =================================================================================== // Query // ===== /** * Prepare for various queries. <br> * Examples of main functions are following: * <pre> * <span style="color: #3F7E5E">// Basic Queries</span> * cb.query().setMemberId_Equal(value); <span style="color: #3F7E5E">// =</span> * cb.query().setMemberId_NotEqual(value); <span style="color: #3F7E5E">// !=</span> * cb.query().setMemberId_GreaterThan(value); <span style="color: #3F7E5E">// &gt;</span> * cb.query().setMemberId_LessThan(value); <span style="color: #3F7E5E">// &lt;</span> * cb.query().setMemberId_GreaterEqual(value); <span style="color: #3F7E5E">// &gt;=</span> * cb.query().setMemberId_LessEqual(value); <span style="color: #3F7E5E">// &lt;=</span> * cb.query().setMemberName_InScope(valueList); <span style="color: #3F7E5E">// in ('a', 'b')</span> * cb.query().setMemberName_NotInScope(valueList); <span style="color: #3F7E5E">// not in ('a', 'b')</span> * <span style="color: #3F7E5E">// LikeSearch with various options: (versatile)</span> * <span style="color: #3F7E5E">// {like ... [options]}</span> * cb.query().setMemberName_LikeSearch(value, option); * cb.query().setMemberName_NotLikeSearch(value, option); <span style="color: #3F7E5E">// not like ...</span> * <span style="color: #3F7E5E">// FromTo with various options: (versatile)</span> * <span style="color: #3F7E5E">// {(default) fromDatetime &lt;= BIRTHDATE &lt;= toDatetime}</span> * cb.query().setBirthdate_FromTo(fromDatetime, toDatetime, option); * <span style="color: #3F7E5E">// DateFromTo: (Date means yyyy/MM/dd)</span> * <span style="color: #3F7E5E">// {fromDate &lt;= BIRTHDATE &lt; toDate + 1 day}</span> * cb.query().setBirthdate_IsNull(); <span style="color: #3F7E5E">// is null</span> * cb.query().setBirthdate_IsNotNull(); <span style="color: #3F7E5E">// is not null</span> * * <span style="color: #3F7E5E">// ExistsReferrer: (correlated sub-query)</span> * <span style="color: #3F7E5E">// {where exists (select PURCHASE_ID from PURCHASE where ...)}</span> * cb.query().existsPurchase(purchaseCB <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * purchaseCB.query().set... <span style="color: #3F7E5E">// referrer sub-query condition</span> * }); * cb.query().notExistsPurchase... * * <span style="color: #3F7E5E">// (Query)DerivedReferrer: (correlated sub-query)</span> * cb.query().derivedPurchaseList().max(purchaseCB <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * purchaseCB.specify().columnPurchasePrice(); <span style="color: #3F7E5E">// derived column for function</span> * purchaseCB.query().set... <span style="color: #3F7E5E">// referrer sub-query condition</span> * }).greaterEqual(value); * * <span style="color: #3F7E5E">// ScalarCondition: (self-table sub-query)</span> * cb.query().scalar_Equal().max(scalarCB <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * scalarCB.specify().columnBirthdate(); <span style="color: #3F7E5E">// derived column for function</span> * scalarCB.query().set... <span style="color: #3F7E5E">// scalar sub-query condition</span> * }); * * <span style="color: #3F7E5E">// OrderBy</span> * cb.query().addOrderBy_MemberName_Asc(); * cb.query().addOrderBy_MemberName_Desc().withManualOrder(option); * cb.query().addOrderBy_MemberName_Desc().withNullsFirst(); * cb.query().addOrderBy_MemberName_Desc().withNullsLast(); * cb.query().addSpecifiedDerivedOrderBy_Desc(aliasName); * * <span style="color: #3F7E5E">// Query(Relation)</span> * cb.query().queryMemberStatus()...; * cb.query().queryMemberAddressAsValid(targetDate)...; * </pre> * @return The instance of condition-query for base-point table to set up query. (NotNull) */ public VendorCheckCQ query() { assertQueryPurpose(); // assert only when user-public query return doGetConditionQuery(); } public VendorCheckCQ xdfgetConditionQuery() { // public for parameter comment and internal return doGetConditionQuery(); } protected VendorCheckCQ doGetConditionQuery() { if (_conditionQuery == null) { _conditionQuery = createLocalCQ(); } return _conditionQuery; } protected VendorCheckCQ createLocalCQ() { return xcreateCQ(null, getSqlClause(), getSqlClause().getBasePointAliasName(), 0); } protected VendorCheckCQ xcreateCQ(ConditionQuery childQuery, SqlClause sqlClause, String aliasName, int nestLevel) { VendorCheckCQ cq = xnewCQ(childQuery, sqlClause, aliasName, nestLevel); cq.xsetBaseCB(this); return cq; } protected VendorCheckCQ xnewCQ(ConditionQuery childQuery, SqlClause sqlClause, String aliasName, int nestLevel) { return new VendorCheckCQ(childQuery, sqlClause, aliasName, nestLevel); } /** * {@inheritDoc} */ public ConditionQuery localCQ() { return doGetConditionQuery(); } // =================================================================================== // Union // ===== /** * Set up 'union' for base-point table. <br> * You don't need to call SetupSelect in union-query, * because it inherits calls before. (Don't call SetupSelect after here) * <pre> * cb.query().<span style="color: #CC4747">union</span>(<span style="color: #553000">unionCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">unionCB</span>.query().set... * }); * </pre> * @param unionCBLambda The callback for query of 'union'. (NotNull) */ public void union(UnionQuery<VendorCheckCB> unionCBLambda) { final VendorCheckCB cb = new VendorCheckCB(); cb.xsetupForUnion(this); xsyncUQ(cb); try { lock(); unionCBLambda.query(cb); } finally { unlock(); } xsaveUCB(cb); final VendorCheckCQ cq = cb.query(); query().xsetUnionQuery(cq); } /** * Set up 'union all' for base-point table. <br> * You don't need to call SetupSelect in union-query, * because it inherits calls before. (Don't call SetupSelect after here) * <pre> * cb.query().<span style="color: #CC4747">unionAll</span>(<span style="color: #553000">unionCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">unionCB</span>.query().set... * }); * </pre> * @param unionCBLambda The callback for query of 'union all'. (NotNull) */ public void unionAll(UnionQuery<VendorCheckCB> unionCBLambda) { final VendorCheckCB cb = new VendorCheckCB(); cb.xsetupForUnion(this); xsyncUQ(cb); try { lock(); unionCBLambda.query(cb); } finally { unlock(); } xsaveUCB(cb); final VendorCheckCQ cq = cb.query(); query().xsetUnionAllQuery(cq); } // =================================================================================== // SetupSelect // =========== // [DBFlute-0.7.4] // =================================================================================== // Specify // ======= protected HpSpecification _specification; /** * Prepare for SpecifyColumn, (Specify)DerivedReferrer. <br> * This method should be called after SetupSelect. * <pre> * <span style="color: #0000C0">memberBhv</span>.selectEntity(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.setupSelect_MemberStatus(); <span style="color: #3F7E5E">// should be called before specify()</span> * <span style="color: #553000">cb</span>.specify().columnMemberName(); * <span style="color: #553000">cb</span>.specify().specifyMemberStatus().columnMemberStatusName(); * <span style="color: #553000">cb</span>.specify().derivedPurchaseList().max(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.specify().columnPurchaseDatetime(); * <span style="color: #553000">purchaseCB</span>.query().set... * }, aliasName); * }).alwaysPresent(<span style="color: #553000">member</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * ... * }); * </pre> * @return The instance of specification. (NotNull) */ public HpSpecification specify() { assertSpecifyPurpose(); if (_specification == null) { _specification = new HpSpecification(this , xcreateSpQyCall(() -> true, () -> xdfgetConditionQuery()) , _purpose, getDBMetaProvider(), xcSDRFnFc()); } return _specification; } public HpColumnSpHandler localSp() { return specify(); } public boolean hasSpecifiedLocalColumn() { return _specification != null && _specification.hasSpecifiedColumn(); } public static class HpSpecification extends HpAbstractSpecification<VendorCheckCQ> { public HpSpecification(ConditionBean baseCB, HpSpQyCall<VendorCheckCQ> qyCall , HpCBPurpose purpose, DBMetaProvider dbmetaProvider , HpSDRFunctionFactory sdrFuncFactory) { super(baseCB, qyCall, purpose, dbmetaProvider, sdrFuncFactory); } /** * VENDOR_CHECK_ID: {PK, NotNull, numeric(16)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnVendorCheckId() { return doColumn("VENDOR_CHECK_ID"); } /** * TYPE_OF_VARCHAR: {varchar(32)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfVarchar() { return doColumn("TYPE_OF_VARCHAR"); } /** * TYPE_OF_NVARCHAR: {nvarchar(32)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfNvarchar() { return doColumn("TYPE_OF_NVARCHAR"); } /** * TYPE_OF_TEXT: {text(2147483647)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfText() { return doColumn("TYPE_OF_TEXT"); } /** * TYPE_OF_NUMERIC_DECIMAL: {numeric(5, 3)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfNumericDecimal() { return doColumn("TYPE_OF_NUMERIC_DECIMAL"); } /** * TYPE_OF_NUMERIC_INTEGER: {numeric(5)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfNumericInteger() { return doColumn("TYPE_OF_NUMERIC_INTEGER"); } /** * TYPE_OF_NUMERIC_BIGINT: {numeric(12)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfNumericBigint() { return doColumn("TYPE_OF_NUMERIC_BIGINT"); } /** * TYPE_OF_SMALLINTEGER: {smallint(5)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfSmallinteger() { return doColumn("TYPE_OF_SMALLINTEGER"); } /** * TYPE_OF_INTEGER: {int(10)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfInteger() { return doColumn("TYPE_OF_INTEGER"); } /** * TYPE_OF_BIGINT: {bigint(19)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfBigint() { return doColumn("TYPE_OF_BIGINT"); } /** * TYPE_OF_MONEY: {money(19, 4)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfMoney() { return doColumn("TYPE_OF_MONEY"); } /** * TYPE_OF_SMALLMONEY: {smallmoney(10, 4)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfSmallmoney() { return doColumn("TYPE_OF_SMALLMONEY"); } /** * TYPE_OF_DATETIME: {datetime(23, 3)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfDatetime() { return doColumn("TYPE_OF_DATETIME"); } /** * TYPE_OF_SMALLDATETIME: {smalldatetime(16)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfSmalldatetime() { return doColumn("TYPE_OF_SMALLDATETIME"); } /** * TYPE_OF_BIT: {bit(1)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfBit() { return doColumn("TYPE_OF_BIT"); } /** * TYPE_OF_BINARY: {binary(3000)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfBinary() { return doColumn("TYPE_OF_BINARY"); } /** * TYPE_OF_VARBINARY: {varbinary(3000)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfVarbinary() { return doColumn("TYPE_OF_VARBINARY"); } /** * TYPE_OF_UNIQUEIDENTIFIER: {uniqueidentifier(36)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfUniqueidentifier() { return doColumn("TYPE_OF_UNIQUEIDENTIFIER"); } /** * TYPE_OF_XML: {xml(2147483647)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnTypeOfXml() { return doColumn("TYPE_OF_XML"); } public void everyColumn() { doEveryColumn(); } public void exceptRecordMetaColumn() { doExceptRecordMetaColumn(); } @Override protected void doSpecifyRequiredColumn() { columnVendorCheckId(); // PK } @Override protected String getTableDbName() { return "VENDOR_CHECK"; } /** * Prepare for (Specify)MyselfDerived (SubQuery). * @return The object to set up a function for myself table. (NotNull) */ public HpSDRFunction<VendorCheckCB, VendorCheckCQ> myselfDerived() { assertDerived("myselfDerived"); if (xhasSyncQyCall()) { xsyncQyCall().qy(); } // for sync (for example, this in ColumnQuery) return cHSDRF(_baseCB, _qyCall.qy(), (String fn, SubQuery<VendorCheckCB> sq, VendorCheckCQ cq, String al, DerivedReferrerOption op) -> cq.xsmyselfDerive(fn, sq, al, op), _dbmetaProvider); } } // =================================================================================== // Dream Cruise // ============ /** * Welcome to the Dream Cruise for condition-bean deep world. <br> * This is very specialty so you can get the frontier spirit. Bon voyage! * @return The condition-bean for dream cruise, which is linked to main condition-bean. */ public VendorCheckCB dreamCruiseCB() { VendorCheckCB cb = new VendorCheckCB(); cb.xsetupForDreamCruise((VendorCheckCB) this); return cb; } protected ConditionBean xdoCreateDreamCruiseCB() { return dreamCruiseCB(); } // [DBFlute-0.9.5.3] // =================================================================================== // Column Query // ============ /** * Set up column-query. {column1 = column2} * <pre> * <span style="color: #3F7E5E">// where FOO &lt; BAR</span> * cb.<span style="color: #CC4747">columnQuery</span>(<span style="color: #553000">colCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">colCB</span>.specify().<span style="color: #CC4747">columnFoo()</span>; <span style="color: #3F7E5E">// left column</span> * }).lessThan(<span style="color: #553000">colCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">colCB</span>.specify().<span style="color: #CC4747">columnBar()</span>; <span style="color: #3F7E5E">// right column</span> * }); <span style="color: #3F7E5E">// you can calculate for right column like '}).plus(3);'</span> * </pre> * @param colCBLambda The callback for specify-query of left column. (NotNull) * @return The object for setting up operand and right column. (NotNull) */ public HpColQyOperand<VendorCheckCB> columnQuery(final SpecifyQuery<VendorCheckCB> colCBLambda) { return xcreateColQyOperand((rightSp, operand) -> { return xcolqy(xcreateColumnQueryCB(), xcreateColumnQueryCB(), colCBLambda, rightSp, operand); }); } protected VendorCheckCB xcreateColumnQueryCB() { VendorCheckCB cb = new VendorCheckCB(); cb.xsetupForColumnQuery((VendorCheckCB)this); return cb; } // [DBFlute-0.9.6.3] // =================================================================================== // OrScope Query // ============= /** * Set up the query for or-scope. <br> * (Same-column-and-same-condition-key conditions are allowed in or-scope) * <pre> * <span style="color: #3F7E5E">// where (FOO = '...' or BAR = '...')</span> * cb.<span style="color: #CC4747">orScopeQuery</span>(<span style="color: #553000">orCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">orCB</span>.query().setFoo... * <span style="color: #553000">orCB</span>.query().setBar... * }); * </pre> * @param orCBLambda The callback for query of or-condition. (NotNull) */ public void orScopeQuery(OrQuery<VendorCheckCB> orCBLambda) { xorSQ((VendorCheckCB)this, orCBLambda); } @Override protected HpCBPurpose xhandleOrSQPurposeChange() { return null; // means no check } /** * Set up the and-part of or-scope. <br> * (However nested or-scope query and as-or-split of like-search in and-part are unsupported) * <pre> * <span style="color: #3F7E5E">// where (FOO = '...' or (BAR = '...' and QUX = '...'))</span> * cb.<span style="color: #994747">orScopeQuery</span>(<span style="color: #553000">orCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">orCB</span>.query().setFoo... * <span style="color: #553000">orCB</span>.<span style="color: #CC4747">orScopeQueryAndPart</span>(<span style="color: #553000">andCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">andCB</span>.query().setBar... * <span style="color: #553000">andCB</span>.query().setQux... * }); * }); * </pre> * @param andCBLambda The callback for query of and-condition. (NotNull) */ public void orScopeQueryAndPart(AndQuery<VendorCheckCB> andCBLambda) { xorSQAP((VendorCheckCB)this, andCBLambda); } /** * Check invalid query when query is set. <br> * (it throws an exception if set query is invalid) <br> * You should call this before registrations of where clause and other queries. <br> * Union and SubQuery and other sub condition-bean inherit this. <br> * * <p>renamed to checkNullOrEmptyQuery() since 1.1, * but not deprecated because it might have many use.</p> * * #java8 compatible option */ public void checkInvalidQuery() { checkNullOrEmptyQuery(); } /** * Accept (no check) an invalid query when a query is set. <br> * (no condition if a set query is invalid) <br> * You should call this before registrations of where clause and other queries. <br> * Union and SubQuery and other sub condition-bean inherit this. * @deprecated use ignoreNullOrEmptyQuery() */ public void acceptInvalidQuery() { getSqlClause().ignoreNullOrEmptyQuery(); } /** * Allow to auto-detect joins that can be inner-join. <br> * <pre> * o You should call this before registrations of where clause. * o Union and SubQuery and other sub condition-bean inherit this. * o You should confirm your SQL on the log to be tuned by inner-join correctly. * </pre> * @deprecated use enableInnerJoinAutoDetect() */ public void allowInnerJoinAutoDetect() { enableInnerJoinAutoDetect(); } /** * Suppress auto-detecting inner-join. <br> * You should call this before registrations of where clause. * @deprecated use disableInnerJoinAutoDetect() */ public void suppressInnerJoinAutoDetect() { disableInnerJoinAutoDetect(); } /** * Allow an empty string for query. <br> * (you can use an empty string as condition) <br> * You should call this before registrations of where clause and other queries. <br> * Union and SubQuery and other sub condition-bean inherit this. * @deprecated use enableEmptyStringQuery() */ public void allowEmptyStringQuery() { doEnableEmptyStringQuery(); } /** * Enable checking record count before QueryUpdate (contains QueryDelete). (default is disabled) <br> * No query update if zero count. (basically for MySQL's deadlock by next-key lock) * @deprecated use enableQueryUpdateCountPreCheck() */ public void enableCheckCountBeforeQueryUpdate() { enableQueryUpdateCountPreCheck(); } /** * Disable checking record count before QueryUpdate (contains QueryDelete). (back to default) <br> * Executes query update even if zero count. (normal specification) * @deprecated use disableQueryUpdateCountPreCheck() */ public void disableCheckCountBeforeQueryUpdate() { disableQueryUpdateCountPreCheck(); } /** * Allow "that's bad timing" check. * @deprecated use enableThatsBadTiming() */ public void allowThatsBadTiming() { enableThatsBadTiming(); } /** * Suppress "that's bad timing" check. * @deprecated use disableThatsBadTiming() */ public void suppressThatsBadTiming() { disableThatsBadTiming(); } // =================================================================================== // DisplaySQL // ========== @Override protected SqlAnalyzerFactory getSqlAnalyzerFactory() { return new ImplementedInvokerAssistant().assistSqlAnalyzerFactory(); } @Override protected String getConfiguredLogDatePattern() { return DBFluteConfig.getInstance().getLogDatePattern(); } @Override protected String getConfiguredLogTimestampPattern() { return DBFluteConfig.getInstance().getLogTimestampPattern(); } @Override protected String getConfiguredLogTimePattern() { return DBFluteConfig.getInstance().getLogTimePattern(); } @Override protected BoundDateDisplayTimeZoneProvider getConfiguredLogTimeZoneProvider() { return DBFluteConfig.getInstance().getLogTimeZoneProvider(); } // =================================================================================== // Meta Handling // ============= public boolean hasUnionQueryOrUnionAllQuery() { return query().hasUnionQueryOrUnionAllQuery(); } // =================================================================================== // Purpose Type // ============ @Override protected void xprepareSyncQyCall(ConditionBean mainCB) { final VendorCheckCB cb; if (mainCB != null) { cb = (VendorCheckCB)mainCB; } else { cb = new VendorCheckCB(); } specify().xsetSyncQyCall(xcreateSpQyCall(() -> true, () -> cb.query())); } // =================================================================================== // Internal // ======== // very internal (for suppressing warn about 'Not Use Import') protected String xgetConditionBeanClassNameInternally() { return VendorCheckCB.class.getName(); } protected String xgetConditionQueryClassNameInternally() { return VendorCheckCQ.class.getName(); } protected String xgetSubQueryClassNameInternally() { return SubQuery.class.getName(); } protected String xgetConditionOptionClassNameInternally() { return ConditionOption.class.getName(); } }
dbflute-test/dbflute-test-dbms-sqlserver
src/main/java/org/docksidestage/sqlserver/dbflute/cbean/bs/BsVendorCheckCB.java
Java
apache-2.0
32,125
package org.jboss.hal.processor.mbui.table; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Generated; import javax.inject.Inject; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import elemental2.dom.HTMLElement; import org.jboss.gwt.elemento.core.builder.ElementsBuilder; import org.jboss.gwt.elemento.core.Elements; import org.jboss.hal.ballroom.form.Form; import org.jboss.hal.ballroom.table.Scope; import org.jboss.hal.ballroom.ExpressionUtil; import org.jboss.hal.ballroom.LayoutBuilder; import org.jboss.hal.ballroom.autocomplete.ReadChildrenAutoComplete; import org.jboss.hal.core.mbui.dialog.AddResourceDialog; import org.jboss.hal.core.mbui.form.GroupedForm; import org.jboss.hal.core.mbui.form.ModelNodeForm; import org.jboss.hal.core.mbui.table.ModelNodeTable; import org.jboss.hal.core.mbui.MbuiContext; import org.jboss.hal.dmr.Operation; import org.jboss.hal.dmr.ResourceAddress; import org.jboss.hal.meta.AddressTemplate; import org.jboss.hal.meta.Metadata; import org.jboss.hal.meta.security.Constraint; import org.jboss.hal.resources.Ids; import org.jboss.hal.spi.Message; import org.jboss.hal.spi.MessageEvent; import static java.util.Arrays.asList; import static org.jboss.gwt.elemento.core.Elements.*; import static org.jboss.hal.ballroom.LayoutBuilder.column; import static org.jboss.hal.ballroom.LayoutBuilder.row; import static org.jboss.hal.dmr.ModelDescriptionConstants.ADD; import static org.jboss.hal.dmr.ModelDescriptionConstants.READ_RESOURCE_OPERATION; /* * WARNING! This class is generated. Do not modify. */ @Generated("org.jboss.hal.processor.mbui.MbuiViewProcessor") public final class Mbui_RemoveConstraintActionView extends RemoveConstraintActionView { private final Metadata metadata0; private final Map<String, HTMLElement> expressionElements; @Inject @SuppressWarnings("unchecked") public Mbui_RemoveConstraintActionView(MbuiContext mbuiContext) { super(mbuiContext); AddressTemplate metadata0Template = AddressTemplate.of("/subsystem=foo"); this.metadata0 = mbuiContext.metadataRegistry().lookup(metadata0Template); this.expressionElements = new HashMap<>(); table = new ModelNodeTable.Builder<org.jboss.hal.dmr.NamedNode>("table", metadata0) .button("Foo", table -> presenter.reload(), Constraint.parse("executable(subsystem=foo:remove)")) .columns("name") .build(); HTMLElement html0; HTMLElement root = row() .add(column() .add(html0 = div() .innerHtml(SafeHtmlUtils.fromSafeConstant("<h1>Table</h1>")) .element()) .add(table) ) .element(); expressionElements.put("html0", html0); registerAttachable(table); initElement(root); } @Override public void attach() { super.attach(); } }
hpehl/hal.next
app/src/test/resources/org/jboss/hal/processor/mbui/table/Mbui_RemoveConstraintActionView.java
Java
apache-2.0
3,024
package metrics import "github.com/prometheus/client_golang/prometheus" var ( // PodFailure returns counter for pod_errors_total metric PodFailure = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "pod_errors_total", Help: "Number of failure operation on PODs", }, []string{"operation"}, ) // PodSuccess returns counter for pod_successes_total metric PodSuccess = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "pod_successes_total", Help: "Number of succeed operation on PODs", }, []string{"operation"}, ) // FuncDuration returns summary for controller_function_duration_seconds metric FuncDuration = prometheus.NewSummaryVec( prometheus.SummaryOpts{ Name: "controller_function_duration_seconds", Help: "The runtime of an function.", Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, }, []string{"function"}, ) )
tczekajlo/kube-consul-register
metrics/controller.go
GO
apache-2.0
913
using Antlr4.Runtime; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Tree; using System.Diagnostics; using MetaDslx.Languages.Antlr4Roslyn.Generator; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using MetaDslx.Languages.Meta; using System.Reflection; using MetaDslx.CodeAnalysis.Syntax; using MetaDslx.Languages.Antlr4Roslyn.Syntax.InternalSyntax; using Roslyn.Utilities; namespace MetaDslx.Languages.Antlr4Roslyn.Compilation { public class Antlr4RoslynCompiler : Antlr4Compiler<Antlr4RoslynLexer, Antlr4RoslynParser> { private Antlr4Tool _antlr4Tool; private string _antlr4TempPath; internal Location _noLocation; private Antlr4AnnotationRemover remover; public string GeneratedAntlr4GrammarFile { get; private set; } public string Antlr4GrammarSource { get; private set; } public Antlr4Grammar Grammar { get; private set; } public string LanguageName { get; private set; } public string BaseDirectory { get; private set; } public string SyntaxDirectory { get; private set; } public string InternalSyntaxDirectory { get; private set; } public bool IsLexer { get; private set; } public bool IsParser { get; private set; } public string LexerHeader { get; private set; } public string ParserHeader { get; private set; } public bool GenerateCompiler { get; private set; } public bool GenerateLanguageService { get; private set; } public bool IgnoreRoslynRules { get; private set; } public bool GenerateAntlr4 { get; private set; } public bool HasAntlr4Errors { get; private set; } public string GeneratedSyntaxKind { get; private set; } public string GeneratedInternalSyntax { get; private set; } public string GeneratedTokenSyntaxFacts { get; private set; } public string GeneratedNodeSyntaxFacts { get; private set; } public string GeneratedSyntax { get; private set; } public string GeneratedSyntaxTree { get; private set; } public string GeneratedLanguage { get; private set; } public string GeneratedLanguageServicesBase { get; private set; } public string GeneratedLanguageServices { get; private set; } public string GeneratedErrorCode { get; private set; } public string GeneratedSyntaxLexer { get; private set; } public string GeneratedSyntaxParser { get; private set; } public string GeneratedLanguageVersion { get; private set; } public string GeneratedParseOptions { get; private set; } public string GeneratedFeature { get; private set; } public string GeneratedCompilation { get; private set; } public string GeneratedCompilationFactory { get; private set; } public string GeneratedCompilationOptions { get; private set; } public string GeneratedScriptCompilationInfo { get; private set; } public string GeneratedDeclarationTreeBuilder { get; private set; } public string GeneratedBinderFactoryVisitor { get; private set; } public string GeneratedBoundKind { get; private set; } public string GeneratedBoundNodeFactoryVisitor { get; private set; } public string GeneratedIsBindableNodeVisitor { get; private set; } public string GeneratedSymbolFacts { get; private set; } //public string GeneratedLanguageService { get; private set; } public Antlr4RoslynCompiler(string manualOutputDirectory, string automaticOutputDirectory, string inputFilePath, string defaultNamespace, Antlr4Tool antlr4Tool) : base(manualOutputDirectory, automaticOutputDirectory, inputFilePath, defaultNamespace) { _antlr4Tool = antlr4Tool; this.GenerateAntlr4 = true; string languageName = Path.GetFileNameWithoutExtension(this.FileName); if (languageName.EndsWith("Parser")) languageName = languageName.Substring(0, languageName.Length - 6); else if (languageName.EndsWith("Lexer")) languageName = languageName.Substring(0, languageName.Length - 5); this.LanguageName = languageName; if (defaultNamespace == null) defaultNamespace = string.Empty; if (defaultNamespace.EndsWith(".InternalSyntax")) { defaultNamespace = defaultNamespace.Substring(0, defaultNamespace.Length - 15); } if (defaultNamespace.EndsWith(".Syntax")) { defaultNamespace = defaultNamespace.Substring(0, defaultNamespace.Length - 7); } this.DefaultNamespace = defaultNamespace; this.BaseDirectory = Path.GetDirectoryName(inputFilePath); if (!string.IsNullOrWhiteSpace(this.BaseDirectory)) { string directory = this.BaseDirectory; if (directory.EndsWith("InternalSyntax")) directory = directory.Substring(0, directory.Length - 14); directory = directory.TrimEnd('\\', '/'); if (directory.EndsWith("Syntax")) directory = directory.Substring(0, directory.Length - 6); directory = directory.TrimEnd('\\', '/'); this.BaseDirectory = directory; } this.SyntaxDirectory = Path.Combine(this.BaseDirectory, "Syntax"); this.InternalSyntaxDirectory = Path.Combine(this.SyntaxDirectory, "InternalSyntax"); _noLocation = new ExternalFileLocation(this.InputFilePath, TextSpan.FromBounds(0, 1), new LinePositionSpan(LinePosition.Zero, LinePosition.Zero)); } protected override Antlr4RoslynLexer CreateLexer(AntlrInputStream stream) { return new Antlr4RoslynLexer(stream); } protected override Antlr4RoslynParser CreateParser(CommonTokenStream stream) { return new Antlr4RoslynParser(stream); } protected override ParserRuleContext DoCreateTree() { return this.Parser.grammarSpec(); } protected virtual bool PreCompile() { if (this.Antlr4GrammarSource != null) return true; this.InitSyntaxTree(); if (this.HasErrors) return false; if (_antlr4Tool != null) { var Antlr4Directory = Path.Combine(this.AutomaticOutputDirectory, this.InternalSyntaxDirectory); this.remover = new Antlr4AnnotationRemover(this.CommonTokenStream); this.remover.Visit(this.ParseTree); this.Antlr4GrammarSource = remover.GetText(); this.GeneratedAntlr4GrammarFile = Path.Combine(this.InternalSyntaxDirectory, Path.ChangeExtension(this.FileName, ".g4")); this.WriteOutputFile(this.GeneratedAntlr4GrammarFile, this.Antlr4GrammarSource, omitCodeGenerationWarning: true); _antlr4Tool.GenerateVisitor = true; if (!this.GenerateAntlr4) { _antlr4TempPath = Path.GetTempPath(); _antlr4Tool.OutputPath = _antlr4TempPath; } else { _antlr4Tool.OutputPath = null; //if (_antlr4Tool.OutputPath == null) _antlr4Tool.OutputPath = Antlr4Directory; } _antlr4Tool.SourceCodeFiles.Add(Path.Combine(Antlr4Directory, Path.ChangeExtension(this.FileName, ".g4"))); _antlr4Tool.TargetNamespace = this.DefaultNamespace + ".Syntax.InternalSyntax"; bool success = _antlr4Tool.Execute(); foreach (var diag in _antlr4Tool.Diagnostics) { this.AddDiagnostic(diag, this.InputFilePath); if (diag.Severity == DiagnosticSeverity.Error) success = false; } if (!success) { this.AddDiagnostic(Antlr4RoslynErrorCode.ERR_Antlr4ToolError, "could not generate C# files"); return false; } else { foreach (var filePath in _antlr4Tool.GeneratedCodeFiles) { this.RegisterGeneratedFile(filePath); } } } return true; } private void IncrementalParserFix(string parserFilePath) { StringBuilder sb = new StringBuilder(); using(StreamReader reader = new StreamReader(parserFilePath)) { string prevLine1 = null; string prevLine2 = null; string prevLine3 = null; while(!reader.EndOfStream) { var line = reader.ReadLine(); if (line.Contains("global::MetaDslx.Languages.Antlr4Roslyn.Syntax.InternalSyntax.IncrementalParser")) return; if (line.Contains(": Parser {")) { line = line.Replace(": Parser {", $": global::MetaDslx.Languages.Antlr4Roslyn.Syntax.InternalSyntax.IncrementalParser {{\r\n private {LanguageName}SyntaxParser SyntaxParser => ({LanguageName}SyntaxParser)this.IncrementalAntlr4Parser;"); } if (line.Contains("Context _localctx = new ")) { var contextTypeName = line.Substring(0, line.IndexOf("_localctx")).Trim(); var indent = line.Substring(0, line.IndexOf(contextTypeName)); var smallIndent = indent.Length >= 1 ? indent.Substring(1) : indent; var ruleName = contextTypeName.Substring(0, contextTypeName.Length - 7); bool recursive = false; if (prevLine1 != null && prevLine1.Contains(") {")) { if (prevLine3 != null) { sb.AppendLine(prevLine3); prevLine3 = null; } if (prevLine2 != null) { sb.AppendLine(prevLine2); prevLine2 = null; } sb.AppendLine(prevLine1); prevLine1 = null; } else if (prevLine3 != null && prevLine3.Contains(") {")) { sb.AppendLine(prevLine3); prevLine3 = null; recursive = true; var findRuleName = ruleName.ToCamelCase(); foreach (var rule in this.Grammar.ParserRules) { if (rule.Name == findRuleName) { rule.IsRecursive = true; break; } } } //sb.AppendLine($"{indent}BeginRuleContext();"); //sb.AppendLine($"{indent}if (this.TryGetIncrementalContext(_ctx, State, RULE_{ruleName.ToCamelCase()}, out {contextTypeName} existingContext)) return existingContext;"); if (recursive) sb.AppendLine($"{indent}return this.SyntaxParser != null && this.SyntaxParser.IsIncremental ? this.SyntaxParser._Antlr4Parse{ruleName}(_p) : _DoParse{ruleName}(_p);"); else sb.AppendLine($"{indent}return this.SyntaxParser != null && this.SyntaxParser.IsIncremental ? this.SyntaxParser._Antlr4Parse{ruleName}() : _DoParse{ruleName}();"); //sb.AppendLine($"{indent}EndRuleContext();"); sb.AppendLine($"{smallIndent}}}"); sb.AppendLine(); if (recursive) sb.AppendLine($"{smallIndent}internal {contextTypeName} _DoParse{ruleName}(int _p) {{"); else sb.AppendLine($"{smallIndent}internal {contextTypeName} _DoParse{ruleName}() {{"); } if (prevLine3 != null) sb.AppendLine(prevLine3); prevLine3 = prevLine2; prevLine2 = prevLine1; prevLine1 = line; } if (prevLine3 != null) sb.AppendLine(prevLine3); if (prevLine2 != null) sb.AppendLine(prevLine2); if (prevLine1 != null) sb.AppendLine(prevLine1); } File.WriteAllText(parserFilePath, sb.ToString()); } protected override void DoCompile() { if (!this.PreCompile()) return; RoslynRuleCollector ruleCollector = new RoslynRuleCollector(this); ruleCollector.Visit(this.ParseTree); this.IsLexer = ruleCollector.IsLexer; this.LexerHeader = ruleCollector.LexerHeader; this.IsParser = ruleCollector.IsParser; this.ParserHeader = ruleCollector.ParserHeader; this.GenerateCompiler = ruleCollector.GenerateCompiler; this.GenerateLanguageService = ruleCollector.GenerateLanguageService; this.IgnoreRoslynRules = ruleCollector.IgnoreRoslynRules; this.Grammar = ruleCollector.Grammar; this.PostCompile(); } protected virtual bool PostCompile() { this.Grammar.ErrorCodeCategory = this.LanguageName; this.Grammar.MessagePrefix = new string(this.LanguageName.Where(c => char.IsUpper(c) || char.IsNumber(c)).ToArray()); string antlr4TokensFile = Path.Combine(this.AutomaticOutputDirectory, Path.ChangeExtension(this.GeneratedAntlr4GrammarFile, ".tokens")); if (!File.Exists(antlr4TokensFile)) { this.AddDiagnostic(Antlr4RoslynErrorCode.ERR_Antlr4ToolError, string.Format("Tokens file '{0}' is missing.", antlr4TokensFile)); return false; } string antlr4TokensSource = File.ReadAllText(antlr4TokensFile); this.ReadTokens(antlr4TokensSource); this.Grammar.FirstParserRuleSyntaxKind = this.Grammar.ParserRules.FirstOrDefault(); this.Grammar.LastParserRuleSyntaxKind = this.Grammar.ParserRules.LastOrDefault(); this.Grammar.LexerRules.Sort((r1, r2) => r1.Kind.CompareTo(r2.Kind)); this.Grammar.FirstTokenSyntaxKind = this.Grammar.LexerRules.FirstOrDefault(r => r.Kind > 0); this.Grammar.LastTokenSyntaxKind = this.Grammar.LexerRules.LastOrDefault(r => r.Kind > 0); this.Grammar.FirstFixedTokenSyntaxKind = this.Grammar.LexerRules.FirstOrDefault(r => r.Kind > 0 && this.Grammar.FixedTokens.Contains(r)); this.Grammar.LastFixedTokenSyntaxKind = this.Grammar.LexerRules.LastOrDefault(r => r.Kind > 0 && this.Grammar.FixedTokens.Contains(r)); if (this.IsLexer) { this.CollectLexerTokenKinds(); } if (this.IsParser) { this.FindFirstNonAbstractAlternatives(); this.CollectCustomAnnotations(); this.CollectHasAnnotationFlags(); } if (_antlr4TempPath != null) { Directory.Delete(_antlr4TempPath, true); } return true; } protected override void DoGenerate() { this.GenerateLexer(); this.GenerateParser(); } private void ReadTokens(string tokensSource) { if (tokensSource == null) return; Dictionary<string, int> fixedTokens = new Dictionary<string, int>(); using (StringReader reader = new StringReader(tokensSource)) { while (true) { string line = reader.ReadLine(); if (line == null) break; string tokenName; int tokenKind; bool fixedToken; if (!string.IsNullOrEmpty(line) && this.TryGetToken(line, out tokenName, out tokenKind, out fixedToken)) { if (fixedToken) { fixedTokens.Add(tokenName, tokenKind); } else { Antlr4LexerRule rule = this.Grammar.LexerRules.FirstOrDefault(r => r.Name == tokenName); if (rule == null) { rule = new Antlr4LexerRule(this.Grammar.LexerModes.FirstOrDefault(), _noLocation); rule.Name = tokenName; rule.Artificial = true; this.Grammar.LexerRules.Add(rule); } rule.Kind = tokenKind; } if (!this.IgnoreRoslynRules) { var collidingRule = this.Grammar.ParserRules.FirstOrDefault(pr => pr.Name?.ToPascalCase() == tokenName); if (collidingRule != null) { this.DiagnosticBag.Add(Antlr4RoslynErrorCode.ERR_RuleNameTokenNameCollision, collidingRule.Location, tokenName, collidingRule.Name); } } } } } foreach (var fixedToken in fixedTokens) { Antlr4LexerRule rule = this.Grammar.LexerRules.FirstOrDefault(r => r.Kind == fixedToken.Value); if (rule != null) { rule.FixedToken = fixedToken.Key; this.Grammar.FixedTokens.Add(rule); } } } private bool TryGetToken(string tokenLine, out string tokenName, out int tokenKind, out bool fixedToken) { tokenName = null; tokenKind = 0; fixedToken = false; int index = 0; tokenLine = tokenLine.Trim(); if (tokenLine.StartsWith("'")) { ++index; while (index < tokenLine.Length) { if (tokenLine[index] == '\'') { ++index; tokenName = tokenLine.Substring(0, index); fixedToken = true; break; } if (tokenLine[index] == '\\') ++index; ++index; } index = tokenLine.LastIndexOf('='); } else { index = tokenLine.IndexOf('='); if (index < 0) return false; tokenName = tokenLine.Substring(0, index).Trim(); } return tokenName != null && int.TryParse(tokenLine.Substring(index + 1).Trim(), out tokenKind) && tokenKind > 0; } private void GenerateLexer() { if (!this.IsLexer) return; if (this.DiagnosticBag.HasAnyErrors()) return; CompilerGenerator generator = new CompilerGenerator(this.Grammar); generator.Properties.DefaultNamespace = this.DefaultNamespace; generator.Properties.LanguageName = this.LanguageName; this.GeneratedTokenSyntaxFacts = generator.GenerateTokenSyntaxFacts(); this.GeneratedSyntaxKind = generator.GenerateSyntaxKind(false, this.LanguageName + "TokensSyntaxKind", "SyntaxKind"); //this.GeneratedLanguageService = this.GetLanguageService(); if (this.AutomaticOutputDirectory == null || this.ManualOutputDirectory == null) return; if (this.GenerateCompiler) { this.WriteOutputFile(Path.Combine(this.SyntaxDirectory, this.LanguageName + "SyntaxFacts.Tokens.cs"), this.GeneratedTokenSyntaxFacts); this.WriteOutputFile(Path.Combine(this.SyntaxDirectory, this.LanguageName + "SyntaxKind.Tokens.cs"), this.GeneratedSyntaxKind); } } private void GenerateParser() { if (!this.IsParser) return; if (!this.GenerateCompiler) return; if (this.DiagnosticBag.HasAnyErrors()) return; CompilerGenerator generator = new CompilerGenerator(this.Grammar); generator.Properties.DefaultNamespace = this.DefaultNamespace; generator.Properties.LanguageName = this.LanguageName; string antlr4ParserFile = Path.Combine(this.AutomaticOutputDirectory, Path.ChangeExtension(this.GeneratedAntlr4GrammarFile, ".cs")); IncrementalParserFix(antlr4ParserFile); this.GeneratedSyntaxKind = generator.GenerateSyntaxKind(true, this.LanguageName + "SyntaxKind", this.LanguageName + "TokensSyntaxKind"); this.GeneratedNodeSyntaxFacts = generator.GenerateNodeSyntaxFacts(); this.GeneratedInternalSyntax = generator.GenerateInternalSyntax(); this.GeneratedSyntax = generator.GenerateSyntax(); this.GeneratedSyntaxTree = generator.GenerateSyntaxTree(); this.GeneratedErrorCode = generator.GenerateErrorCode(); this.GeneratedSymbolFacts = generator.GenerateSymbolFacts(); this.GeneratedSyntaxLexer = generator.GenerateSyntaxLexer(); this.GeneratedSyntaxParser = generator.GenerateSyntaxParser(); this.GeneratedLanguage = generator.GenerateLanguage(); this.GeneratedLanguageVersion = generator.GenerateLanguageVersion(); this.GeneratedParseOptions = generator.GenerateParseOptions(); this.GeneratedFeature = generator.GenerateFeature(); this.GeneratedLanguageServicesBase = generator.GenerateLanguageServicesBase(); this.GeneratedLanguageServices = generator.GenerateLanguageServices(); this.GeneratedCompilation = generator.GenerateCompilation(); this.GeneratedCompilationFactory = generator.GenerateCompilationFactory(); this.GeneratedCompilationOptions = generator.GenerateCompilationOptions(); this.GeneratedScriptCompilationInfo = generator.GenerateScriptCompilationInfo(); this.GeneratedDeclarationTreeBuilder = generator.GenerateDeclarationTreeBuilder(); this.GeneratedBinderFactoryVisitor = generator.GenerateBinderFactoryVisitor(); this.GeneratedBoundKind = generator.GenerateBoundKind(); this.GeneratedBoundNodeFactoryVisitor = generator.GenerateBoundNodeFactoryVisitor(); this.GeneratedIsBindableNodeVisitor = generator.GenerateIsBindableNodeVisitor(); if (this.AutomaticOutputDirectory == null || this.ManualOutputDirectory == null) return; if (this.GenerateCompiler) { var CompilationDirectory = Path.Combine(this.BaseDirectory, "Compilation"); var ErrorsDirectory = Path.Combine(this.BaseDirectory, "Errors"); var SymbolsDirectory = Path.Combine(this.BaseDirectory, "Symbols"); var BindingDirectory = Path.Combine(this.BaseDirectory, "Binding"); this.WriteOutputFile(Path.Combine(this.InternalSyntaxDirectory, this.LanguageName + "InternalSyntax.cs"), this.GeneratedInternalSyntax); this.WriteOutputFile(Path.Combine(this.InternalSyntaxDirectory, this.LanguageName + @"SyntaxLexer.cs"), this.GeneratedSyntaxLexer); this.WriteOutputFile(Path.Combine(this.InternalSyntaxDirectory, this.LanguageName + @"SyntaxParser.cs"), this.GeneratedSyntaxParser); this.WriteOutputFile(Path.Combine(this.SyntaxDirectory, this.LanguageName + "SyntaxKind.Nodes.cs"), this.GeneratedSyntaxKind); this.WriteOutputFile(Path.Combine(this.SyntaxDirectory, this.LanguageName + "SyntaxFacts.Nodes.cs"), this.GeneratedNodeSyntaxFacts); this.WriteOutputFile(Path.Combine(this.SyntaxDirectory, this.LanguageName + "Syntax.cs"), this.GeneratedSyntax); this.WriteOutputFile(Path.Combine(this.SyntaxDirectory, this.LanguageName + "SyntaxTree.cs"), this.GeneratedSyntaxTree); this.WriteOutputFile(Path.Combine(this.SyntaxDirectory, this.LanguageName + @"ParseOptions.cs"), this.GeneratedParseOptions); this.WriteOutputFile(Path.Combine(ErrorsDirectory, this.LanguageName + @"ErrorCode.cs"), this.GeneratedErrorCode); this.WriteOutputFile(Path.Combine(SymbolsDirectory, this.LanguageName + @"SymbolFacts.cs"), this.GeneratedSymbolFacts); this.WriteOutputFile(Path.Combine(CompilationDirectory, this.LanguageName + @"CompilationOptions.cs"), this.GeneratedCompilationOptions); this.WriteOutputFile(Path.Combine(CompilationDirectory, this.LanguageName + @"Compilation.cs"), this.GeneratedCompilation); this.WriteOutputFile(Path.Combine(CompilationDirectory, this.LanguageName + @"CompilationFactory.cs"), this.GeneratedCompilationFactory); this.WriteOutputFile(Path.Combine(CompilationDirectory, this.LanguageName + @"Language.cs"), this.GeneratedLanguage); this.WriteOutputFile(Path.Combine(CompilationDirectory, this.LanguageName + @"LanguageVersion.cs"), this.GeneratedLanguageVersion); this.WriteOutputFile(Path.Combine(CompilationDirectory, this.LanguageName + @"LanguageServicesBase.cs"), this.GeneratedLanguageServicesBase); this.WriteOutputFile(Path.Combine(CompilationDirectory, this.LanguageName + @"LanguageServices.cs"), this.GeneratedLanguageServices, automatic: false); this.WriteOutputFile(Path.Combine(BindingDirectory, this.LanguageName + @"DeclarationTreeBuilderVisitor.cs"), this.GeneratedDeclarationTreeBuilder); this.WriteOutputFile(Path.Combine(BindingDirectory, this.LanguageName + @"BinderFactoryVisitor.cs"), this.GeneratedBinderFactoryVisitor); this.WriteOutputFile(Path.Combine(BindingDirectory, this.LanguageName + @"BoundKind.cs"), this.GeneratedBoundKind); this.WriteOutputFile(Path.Combine(BindingDirectory, this.LanguageName + @"BoundNodeFactoryVisitor.cs"), this.GeneratedBoundNodeFactoryVisitor); this.WriteOutputFile(Path.Combine(BindingDirectory, this.LanguageName + @"IsBindableNodeVisitor.cs"), this.GeneratedIsBindableNodeVisitor); /*this.WriteOutputFile(Path.Combine(this.AutomaticManualOutputDirectory, @"Compilation\" + this.LanguageName + @"ScriptCompilationInfo.cs"), this.GeneratedScriptCompilationInfo); this.WriteOutputFile(Path.Combine(this.AutomaticManualOutputDirectory, @"Compilation\" + this.LanguageName + @"Feature.cs"), this.GeneratedFeature);*/ } } private void CollectCustomAnnotations() { this.DefineCustomAnnotations(); //this.ReferenceCustomAnnotations(); } private void FindFirstNonAbstractAlternatives() { foreach (var rule in this.Grammar.ParserRules) { if (rule.Alternatives.Count > 0 && rule.FirstNonAbstractAlternative == null) { FindFirstNonAbstractAlternative(rule); } } } private void FindFirstNonAbstractAlternative(Antlr4ParserRule rule) { rule.FirstNonAbstractAlternative = rule.Alternatives.Where(alt => alt.Alternatives.Count == 0).FirstOrDefault(); if (rule.FirstNonAbstractAlternative == null) { foreach (var alt in rule.Alternatives) { if (alt.Alternatives.Count > 0 && alt.FirstNonAbstractAlternative == null) { FindFirstNonAbstractAlternative(alt); } } rule.FirstNonAbstractAlternative = rule.Alternatives.Where(alt => alt.FirstNonAbstractAlternative != null).FirstOrDefault()?.FirstNonAbstractAlternative; } } private void DefineCustomAnnotations() { foreach (var rule in this.Grammar.ParserRules) { this.DefineCustomAnnotations(rule.Annotations.GetCustomAnnotations()); foreach (var elem in rule.AllElements) { this.DefineCustomAnnotations(elem.Annotations.GetCustomAnnotations()); } foreach (var alt in rule.Alternatives) { this.DefineCustomAnnotations(alt.Annotations.GetCustomAnnotations()); foreach (var elem in alt.AllElements) { this.DefineCustomAnnotations(elem.Annotations.GetCustomAnnotations()); } } } } private void DefineCustomAnnotations(ImmutableArray<MetaCompilerAnnotation> annots) { foreach (var annot in annots) { MetaCompilerAnnotation existing = this.Grammar.CustomAnnotations.FirstOrDefault(a => a.Name == annot.Name); if (existing == null) { existing = new MetaCompilerAnnotation(annot.Name, new MetaAnnotationProperty[0]); this.Grammar.CustomAnnotations.Add(existing); } } } private void CollectLexerTokenKinds() { if (this.DiagnosticBag.HasAnyErrors()) return; this.CollectVirtualTokenKinds(); List<Antlr4LexerRule> defaultWhitespace = new List<Antlr4LexerRule>(); List<Antlr4LexerRule> defaultEndOfLine = new List<Antlr4LexerRule>(); List<Antlr4LexerRule> defaultSeparator = new List<Antlr4LexerRule>(); List<Antlr4LexerRule> defaultIdentifier = new List<Antlr4LexerRule>(); foreach (var rule in this.Grammar.LexerRules) { var tokenAnnot = rule.Annotations.GetAnnotation("Token"); if (tokenAnnot != null) { string kind = tokenAnnot.GetValue("kind"); if (kind != null) { List<Antlr4LexerRule> rules = null; if (!this.Grammar.LexerTokenKinds.TryGetValue(kind, out rules)) { rules = new List<Antlr4LexerRule>(); this.Grammar.LexerTokenKinds.Add(kind, rules); } rules.Add(rule); } if (tokenAnnot.GetValue("defaultWhitespace") == "true") { this.Grammar.DefaultWhitespaceKind = rule; defaultWhitespace.Add(rule); } if (tokenAnnot.GetValue("defaultEndOfLine") == "true") { this.Grammar.DefaultEndOfLineKind = rule; defaultEndOfLine.Add(rule); } if (tokenAnnot.GetValue("defaultIdentifier") == "true") { this.Grammar.DefaultIdentifierKind = rule; defaultIdentifier.Add(rule); } if (tokenAnnot.GetValue("defaultSeparator") == "true") { this.Grammar.DefaultSeparatorKind = rule; defaultSeparator.Add(rule); } } } foreach (var mode in this.Grammar.LexerModes) { var tokenAnnot = mode.Annotations.GetAnnotation("Token"); if (tokenAnnot != null) { string kind = tokenAnnot.GetValue("kind"); if (kind != null) { List<Antlr4LexerRule> rules = null; if (!this.Grammar.LexerTokenKinds.TryGetValue(kind, out rules)) { rules = new List<Antlr4LexerRule>(); this.Grammar.LexerTokenKinds.Add(kind, rules); } } } } this.CheckDefaultAnnotations(defaultWhitespace, "Whitespace"); this.CheckDefaultAnnotations(defaultEndOfLine, "EndOfLine"); this.CheckDefaultAnnotations(defaultSeparator, "Separator"); this.CheckDefaultAnnotations(defaultIdentifier, "Identifier"); } private void CheckDefaultAnnotations(List<Antlr4LexerRule> rules, string annot) { if (this.IgnoreRoslynRules) return; if (rules.Count == 0) { this.AddDiagnostic(Antlr4RoslynErrorCode.ERR_MissingDefaultAnnotation, _noLocation, string.Format("$Token(default{0}=true)", annot)); } else if (rules.Count >= 2) { foreach (var rule in rules) { this.AddDiagnostic(Antlr4RoslynErrorCode.ERR_MultipleDefaultAnnotation, rule.Location, string.Format("$Token(default{0}=true)", annot)); } } } private void CollectVirtualTokenKinds() { var syntaxFactsType = typeof(CodeAnalysis.Syntax.SyntaxFacts); foreach (var method in syntaxFactsType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { if ((method.IsAbstract || method.IsVirtual) && method.Name.StartsWith("Is") && method.ReturnType == typeof(bool)) { var parameters = method.GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType == typeof(CodeAnalysis.Syntax.SyntaxKind)) { string tokenKindName = method.Name.Substring(2); this.Grammar.VirtualTokenKinds.Add(tokenKindName); this.Grammar.LexerTokenKinds.Add(tokenKindName, new List<Antlr4LexerRule>()); } } } this.Grammar.LexerTokenKinds.Remove("TriviaWithEndOfLine"); } private void CollectHasAnnotationFlags() { if (this.DiagnosticBag.HasAnyErrors()) return; foreach (var rule in this.Grammar.ParserRules) { foreach (var alt in rule.Alternatives) { alt.Annotations = rule.Annotations.AddRange(alt.Annotations.Annotations); } } foreach (var rule in this.Grammar.ParserRules) { this.SetAnnotationFlags(rule); foreach (var alt in rule.Alternatives) { this.SetAnnotationFlags(alt); } } bool foundNewFlag = true; while (foundNewFlag) { foundNewFlag = false; foreach (var rule in this.Grammar.ParserRules) { bool oldContainsAnnotations = rule.ContainsAnnotations; bool oldContainsBinderAnnotations = rule.ContainsBinderAnnotations; bool oldContainsBoundNodeAnnotations = rule.ContainsBoundNodeAnnotations; foundNewFlag = this.CollectHasAnnotationFlags(rule) | foundNewFlag; foreach (var alt in rule.Alternatives) { foundNewFlag = this.CollectHasAnnotationFlags(alt) | foundNewFlag; MergeContainsAnnotationsFrom(rule, alt); } foundNewFlag = (rule.ContainsAnnotations && !oldContainsAnnotations) | (rule.ContainsBinderAnnotations && !oldContainsBinderAnnotations) | (rule.ContainsBoundNodeAnnotations && !oldContainsBoundNodeAnnotations) | foundNewFlag; } } } private bool CollectHasAnnotationFlags(Antlr4ParserRule rule) { bool foundElemFlag = false; foreach (var elem in rule.Elements) { bool oldContainsAnnotations = elem.ContainsAnnotations; bool oldContainsBinderAnnotations = elem.ContainsBinderAnnotations; bool oldContainsBoundNodeAnnotations = elem.ContainsBoundNodeAnnotations; this.SetAnnotationFlags(elem); if (elem.ContainsAnnotations) { this.Grammar.ParserRuleElemUses.Add(elem.RedName()); } if (elem.BlockItems.Count > 0) { foreach (var item in elem.BlockItems) { bool oldItemContainsAnnotations = item.ContainsAnnotations; bool oldItemContainsBinderAnnotations = item.ContainsBinderAnnotations; bool oldItemContainsBoundNodeAnnotations = item.ContainsBoundNodeAnnotations; this.SetAnnotationFlags(item); if (item.ContainsAnnotations) { this.Grammar.ParserRuleElemUses.Add(item.RedName()); } Antlr4ParserRule itemTypeRule = this.Grammar.FindParserRule(item.Type); if (itemTypeRule != null) { MergeContainsAnnotationsFrom(item, itemTypeRule); } MergeContainsAnnotationsFrom(elem, item); foundElemFlag = (item.ContainsAnnotations && !oldItemContainsAnnotations) | (item.ContainsBinderAnnotations && !oldItemContainsBinderAnnotations) | (item.ContainsBoundNodeAnnotations && !oldItemContainsBoundNodeAnnotations) | foundElemFlag; } } Antlr4ParserRule elemTypeRule = this.Grammar.FindParserRule(elem.Type); if (elemTypeRule != null) { MergeContainsAnnotationsFrom(elem, elemTypeRule); } MergeContainsAnnotationsFrom(rule, elem); foundElemFlag = (elem.ContainsAnnotations && !oldContainsAnnotations) | (elem.ContainsBinderAnnotations && !oldContainsBinderAnnotations) | (elem.ContainsBoundNodeAnnotations && !oldContainsBoundNodeAnnotations) | foundElemFlag; } return foundElemFlag; } private void SetAnnotationFlags(Antlr4AnnotatedObject obj) { int binderAnnotationCount = obj.Annotations.Annotations.Count(a => MetaCompilerAnnotationInfo.BinderAnnotations.Contains(a.Name)); int boundNodeAnnotationCount = obj.Annotations.Annotations.Count(a => MetaCompilerAnnotationInfo.BoundNodeAnnotations.Contains(a.Name)); int customAnnotationCount = obj.Annotations.Annotations.Count(a => !MetaCompilerAnnotationInfo.WellKnownAnnotations.Contains(a.Name)); obj.HasAnnotations = obj.Annotations.Annotations.Count > 0; obj.HasBinderAnnotations = binderAnnotationCount + customAnnotationCount > 0; obj.HasBoundNodeAnnotations = boundNodeAnnotationCount + customAnnotationCount > 0; obj.ContainsAnnotations |= obj.HasAnnotations; obj.ContainsBinderAnnotations |= obj.HasBinderAnnotations; obj.ContainsBoundNodeAnnotations |= obj.HasBoundNodeAnnotations; } private void MergeContainsAnnotationsFrom(Antlr4AnnotatedObject target, Antlr4AnnotatedObject source) { target.ContainsAnnotations |= source.ContainsAnnotations; target.ContainsBinderAnnotations |= source.ContainsBinderAnnotations; target.ContainsBoundNodeAnnotations |= source.ContainsBoundNodeAnnotations; } public static string FixedTokenToCSharpString(string value) { if (string.IsNullOrWhiteSpace(value)) return null; if (value.Length >= 2 && value.StartsWith("'") && value.EndsWith("'")) { StringBuilder sb = new StringBuilder(); sb.Append('"'); value = value.Substring(1, value.Length - 2); for (int i = 0; i < value.Length; ++i) { if (i + 1 < value.Length && value[i] == '\\') { sb.Append(value[i]); sb.Append(value[i + 1]); ++i; } else if (value[i] == '"') { sb.Append("\\\""); } else { sb.Append(value[i]); } } sb.Append('"'); value = sb.ToString(); return value; } return value; } public static string FixedTokenToText(string value) { if (string.IsNullOrWhiteSpace(value)) return null; if (value.Length >= 2 && value.StartsWith("'") && value.EndsWith("'")) { StringBuilder sb = new StringBuilder(); value = value.Substring(1, value.Length - 2); for (int i = 0; i < value.Length; ++i) { if (i + 1 < value.Length && value[i] == '\\') { switch (value[i + 1]) { case 'b': sb.Append("\b"); break; case 't': sb.Append("\t"); break; case 'n': sb.Append("\n"); break; case 'f': sb.Append("\f"); break; case 'r': sb.Append("\r"); break; case '"': sb.Append("\""); break; case '\'': sb.Append("\'"); break; case '\\': sb.Append("\\"); break; default: sb.Append(value[i + 1]); break; } ++i; } else { sb.Append(value[i]); } } value = sb.ToString(); return value; } return value; } internal static readonly string[] reservedNames = { "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while", }; } internal class RoslynRuleCollector : Antlr4RoslynParserBaseVisitor<object> { private Antlr4RoslynCompiler compiler; private string parserName; private string lexerName; private string parserHeader; private string lexerHeader; private Antlr4Grammar currentGrammar; private Antlr4LexerMode currentMode; private Antlr4LexerRule currentLexerRule; private bool firstRule; private int modeCounter; public Antlr4Grammar Grammar { get { return this.currentGrammar; } } public bool IsParser { get; private set; } public bool IsLexer { get; private set; } public bool GenerateCompiler { get; private set; } public bool GenerateLanguageService { get; private set; } public bool IgnoreRoslynRules { get; private set; } public string LexerHeader => this.lexerHeader; public string ParserHeader => this.parserHeader; public RoslynRuleCollector(Antlr4RoslynCompiler compiler) { this.firstRule = true; this.compiler = compiler; } private void CollectAnnotations(Antlr4AnnotatedObject obj, Antlr4RoslynParser.AnnotationContext[] annotations) { foreach (var annot in annotations) { string annotationName = annot.qualifiedName().GetText(); if (annot.annotationBody() != null) { var propertyBuilder = ImmutableArray.CreateBuilder<MetaAnnotationProperty>(); if (annot.annotationBody().annotationAttributeList() != null) { foreach (var attr in annot.annotationBody().annotationAttributeList().annotationAttribute()) { string propertyName = attr.annotationIdentifier().GetText(); CheckAnnotationParameters(attr.annotationIdentifier(), annotationName, propertyName); MetaAnnotationProperty property = null; if (attr.expression() != null) { string value = attr.expression().GetText(); property = new MetaAnnotationProperty(propertyName, value); } else if (attr.expressionList() != null) { var valueBuilder = ImmutableArray.CreateBuilder<string>(); foreach (var expr in attr.expressionList().expression()) { string value = expr.GetText(); valueBuilder.Add(value); } property = new MetaAnnotationProperty(propertyName, valueBuilder.ToImmutable()); } if (property != null) { propertyBuilder.Add(property); } } } else if (annot.annotationBody().expression() != null) { string value = annot.annotationBody().expression().GetText(); propertyBuilder.Add(MetaCompilerAnnotationInfo.CreateDefaultProperty(annotationName, value)); } else if (annot.annotationBody().expressionList() != null) { var valueBuilder = ImmutableArray.CreateBuilder<string>(); foreach (var expr in annot.annotationBody().expressionList().expression()) { string value = expr.GetText(); valueBuilder.Add(value); } propertyBuilder.Add(MetaCompilerAnnotationInfo.CreateDefaultProperty(annotationName, valueBuilder.ToImmutable())); } MetaCompilerAnnotation annotation = new MetaCompilerAnnotation(annotationName, propertyBuilder.ToImmutable()); obj.Annotations = obj.Annotations.Add(annotation); } else { MetaCompilerAnnotation annotation = new MetaCompilerAnnotation(annotationName, ImmutableArray<MetaAnnotationProperty>.Empty); obj.Annotations = obj.Annotations.Add(annotation); } } } private void CheckAnnotationParameters(ParserRuleContext context, string annotationName, string parameterName) { int index = MetaCompilerAnnotationInfo.WellKnownAnnotations.IndexOf(annotationName); if (index >= 0) { if (!MetaCompilerAnnotationInfo.WellKnownAnnotationProperties[index].Contains(parameterName)) { this.compiler.AddDiagnostic(context, Antlr4RoslynErrorCode.WRN_InvalidWellKnownAnnotationParameter, annotationName, parameterName); } } } private Location GetLocation(ParserRuleContext context) { return new ExternalFileLocation(this.compiler.InputFilePath, context.GetTextSpan(), context.GetLinePositionSpan()); } private Location GetLocation(ITerminalNode terminalNode) { return new ExternalFileLocation(this.compiler.InputFilePath, terminalNode.Symbol.GetTextSpan(), terminalNode.Symbol.GetLinePositionSpan()); } public override object VisitGrammarSpec(Antlr4RoslynParser.GrammarSpecContext context) { if (context.grammarType().PARSER() != null) { this.parserName = context.identifier().GetText(); this.lexerName = this.parserName; this.IsLexer = false; this.IsParser = true; } else if (context.grammarType().LEXER() != null) { this.lexerName = context.identifier().GetText(); this.IsLexer = true; this.IsParser = false; } else { this.parserName = context.identifier().GetText(); this.lexerName = this.parserName; this.IsLexer = true; this.IsParser = true; } currentGrammar = new Antlr4Grammar(this.compiler._noLocation); currentGrammar.Name = context.identifier().GetText(); currentMode = new Antlr4LexerMode(this.currentGrammar, this.GetLocation(context.identifier())); currentMode.Name = "DEFAULT_MODE"; this.modeCounter = 0; currentMode.Kind = this.modeCounter; currentGrammar.LexerModes.Add(currentMode); this.CollectAnnotations(currentGrammar, context.annotation()); return base.VisitGrammarSpec(context); } public override object VisitTokensSpec([NotNull] Antlr4RoslynParser.TokensSpecContext context) { if (context.idList() != null) { foreach (var id in context.idList().annotatedIdentifier()) { this.currentLexerRule = new Antlr4LexerRule(this.currentMode, this.GetLocation(id.identifier())); this.currentLexerRule.Name = id.identifier().GetText(); //this.currentLexerRule.FixedToken = id.identifier().GetText(); if (this.currentLexerRule != null) { //this.currentGrammar.FixedTokens.Add(this.currentLexerRule); this.currentGrammar.LexerRules.Add(this.currentLexerRule); this.currentMode.LexerRules.Add(this.currentLexerRule); this.CollectAnnotations(this.currentLexerRule, id.annotation()); this.currentLexerRule = null; } } } return null; } public override object VisitOption(Antlr4RoslynParser.OptionContext context) { string optionName = context.identifier().GetText(); string optionValue = context.optionValue().GetText(); if (optionName == "generateCompiler") { this.GenerateCompiler = optionValue == "true"; } if (optionName == "generateLanguageService") { this.GenerateLanguageService = optionValue == "true"; } if (optionName == "ignoreRoslynRules") { this.IgnoreRoslynRules = optionValue == "true"; } if (optionName == "tokenVocab") { this.lexerName = optionValue; string import = optionValue; this.Grammar.Imports.Add(import + ".tokens"); } return base.VisitOption(context); } public override object VisitDelegateGrammar([NotNull] Antlr4RoslynParser.DelegateGrammarContext context) { var identifiers = context.identifier(); if (identifiers.Length >= 2) { string import = identifiers[1].GetText(); this.Grammar.Imports.Add(import + ".g4"); } else if (identifiers.Length >= 1) { string import = identifiers[0].GetText(); this.Grammar.Imports.Add(import + ".g4"); } return base.VisitDelegateGrammar(context); } public override object VisitAction(Antlr4RoslynParser.ActionContext context) { string id = context.identifier().GetText(); if (id == "header") { string scopeName = null; if (context.actionScopeName() != null) { scopeName = context.actionScopeName().GetText(); } string action = context.actionBlock().GetText(); int first = action.IndexOf('{'); int last = action.LastIndexOf('}'); if (first >= 0 && last >= 0) { action = action.Substring(first + 1, last - first - 1); } if (scopeName == null || scopeName == "parser") { this.parserHeader = action; this.Grammar.ParserHeader = action; } if (scopeName == null || scopeName == "lexer") { this.lexerHeader = action; this.Grammar.LexerHeader = action; } } return base.VisitAction(context); } public override object VisitModeSpec(Antlr4RoslynParser.ModeSpecContext context) { currentMode = new Antlr4LexerMode(this.currentGrammar, this.GetLocation(context.identifier())); if (context.identifier() != null) { currentMode.Name = context.identifier().GetText(); } ++this.modeCounter; currentMode.Kind = this.modeCounter; currentGrammar.LexerModes.Add(currentMode); this.CollectAnnotations(currentMode, context.annotation()); return base.VisitModeSpec(context); } public override object VisitLexerRuleSpec(Antlr4RoslynParser.LexerRuleSpecContext context) { if (context.FRAGMENT() == null) { this.currentLexerRule = new Antlr4LexerRule(this.currentMode, this.GetLocation(context.TOKEN_REF())); this.currentLexerRule.Name = context.TOKEN_REF().GetText(); base.VisitLexerRuleSpec(context); if (this.currentLexerRule != null) { if (context.lexerRuleBlock().lexerAltList().lexerAlt().Length == 1) { Antlr4RoslynParser.LexerAltContext lexerAlt = context.lexerRuleBlock().lexerAltList().lexerAlt(0); if (lexerAlt.lexerElements().lexerElement().Length == 1) { Antlr4RoslynParser.LexerElementContext lexerElement = lexerAlt.lexerElements().lexerElement(0); if (lexerElement.ebnfSuffix() == null) { Antlr4RoslynParser.LexerAtomContext lexerAtom = null; if (lexerElement.labeledLexerElement() != null) { Antlr4RoslynParser.LabeledLexerElementContext labeledLexerElement = lexerElement.labeledLexerElement(); if (labeledLexerElement.lexerAtom() != null) { lexerAtom = labeledLexerElement.lexerAtom(); } } else if (lexerElement.lexerAtom() != null) { lexerAtom = lexerElement.lexerAtom(); } /*if (lexerAtom != null && lexerAtom.terminal() != null && !this.HasModeCommand(lexerAlt)) { if (lexerAtom.terminal().TOKEN_REF() != null) { this.currentLexerRule.FixedToken = lexerAtom.terminal().TOKEN_REF().GetText(); this.currentGrammar.FixedTokenCandidates.Add(this.currentLexerRule); } else if (lexerAtom.terminal().STRING_LITERAL() != null) { string literal = lexerAtom.terminal().STRING_LITERAL().GetText(); this.currentLexerRule.FixedToken = literal; this.currentGrammar.FixedTokens.Add(this.currentLexerRule); } }*/ } } } this.currentGrammar.LexerRules.Add(this.currentLexerRule); this.currentMode.LexerRules.Add(this.currentLexerRule); this.CollectAnnotations(this.currentLexerRule, context.annotation()); this.currentLexerRule = null; } } return null; } private bool HasModeCommand(Antlr4RoslynParser.LexerAltContext lexerAlt) { if (lexerAlt.lexerCommands() != null) { foreach (var lexCmd in lexerAlt.lexerCommands().lexerCommand()) { if (lexCmd.lexerCommandName().GetText() == "mode") { return true; } } } return false; } public override object VisitLexerCommand(Antlr4RoslynParser.LexerCommandContext context) { string commandName = context.lexerCommandName().GetText(); if (string.IsNullOrEmpty(commandName)) return null; if (commandName == "more") { this.currentLexerRule = null; } return null; } public override object VisitRuleBlock([NotNull] Antlr4RoslynParser.RuleBlockContext context) { Antlr4RoslynParser.ParserRuleSpecContext ruleSpec = context.Parent as Antlr4RoslynParser.ParserRuleSpecContext; if (ruleSpec != null) { bool handled = false; bool reportedError = false; string ruleName = ruleSpec.RULE_REF().GetText(); Antlr4ParserRule rule = null; if (!handled && context.ruleAltList().labeledAlt().Length == 1) { if (!handled && this.IsRoslynRule(context.ruleAltList().labeledAlt()[0], ref reportedError, out rule)) { rule.Location = GetLocation(ruleSpec.RULE_REF()); handled = true; } } if (!reportedError && !handled && this.IsRoslynAltList(context, TokenOrRule.Rule, false, ref reportedError, out rule)) { handled = true; } if (!reportedError && !handled && this.IsRoslynAltList(context, TokenOrRule.Token, false, ref reportedError, out rule)) { handled = true; } bool possiblyGood = false; if (!reportedError && !handled) { if (this.IsInheritanceRule(context, ref reportedError, out possiblyGood, out rule)) { handled = true; } else if (possiblyGood) { handled = true; reportedError = true; if (!this.IgnoreRoslynRules) this.compiler.AddDiagnostic(ruleSpec.RULE_REF(), Antlr4RoslynErrorCode.ERR_RuleMapUnnamedAlt, ruleName); } } if (!reportedError && !handled) { if (!this.IgnoreRoslynRules) this.compiler.AddDiagnostic(ruleSpec.RULE_REF(), Antlr4RoslynErrorCode.ERR_RuleMapTooComplex, ruleName); } if (!reportedError && handled && rule != null) { this.CollectAnnotations(rule, ruleSpec.annotation()); this.Grammar.ParserRules.Add(rule); rule.Name = ruleName; } if (this.firstRule) { this.firstRule = false; Antlr4RoslynParser.LabeledAltContext[] labeledAlts = context.ruleAltList().labeledAlt(); bool endsWithEof = false; if (labeledAlts != null && labeledAlts.Length > 0) { endsWithEof = true; for (int i = 0; i < labeledAlts.Length; i++) { if (!EndsWithEof(labeledAlts[i])) { endsWithEof = false; break; } } } if (!endsWithEof) { if (!this.IgnoreRoslynRules) this.compiler.AddDiagnostic(context, Antlr4RoslynErrorCode.ERR_MainRuleMustEndWithEof); } } } else { if (!this.IgnoreRoslynRules) this.compiler.AddDiagnostic(context, Antlr4RoslynErrorCode.ERR_BlockUnhandled); } return base.VisitRuleBlock(context); } public override object VisitElement([NotNull] Antlr4RoslynParser.ElementContext elem) { if (elem.labeledElement() != null && elem.labeledElement().PLUS_ASSIGN() == null && elem.labeledElement().ASSIGN() != null && IsEbnfList(elem.ebnfSuffix())) { if (!this.IgnoreRoslynRules) this.compiler.AddDiagnostic(elem.labeledElement().ASSIGN(), Antlr4RoslynErrorCode.ERR_LabeledListMustUsePlusAssign); } return base.VisitElement(elem); } private bool CheckUniqueElements(Antlr4ParserRule rule, ref bool reportedErrors) { bool result = true; var elements = rule.AllElements; for (int i = 0; i < elements.Count; i++) { if (elements[i].IsBlock) continue; bool renameNeeded = false; for (int j = 0; j < elements.Count; j++) { if (j == i || elements[j].IsBlock) continue; if (elements[j].Name == elements[i].Name || elements[j].Type == elements[i].Name) { renameNeeded = true; break; } } if (renameNeeded) { result = false; reportedErrors = true; if (!this.IgnoreRoslynRules) this.compiler.AddDiagnostic(elements[i].Node, Antlr4RoslynErrorCode.ERR_UnnamedElement, elements[i].Type); } } return result; } private bool IsInheritanceRule(Antlr4RoslynParser.RuleBlockContext context, ref bool reportedErrors, out bool possiblyGood, out Antlr4ParserRule rule) { bool allNamed = true; foreach (var alt in context.ruleAltList().labeledAlt()) { if (alt.identifier() == null) { allNamed = false; break; } } rule = new Antlr4ParserRule(this.currentGrammar, this.GetLocation(context)); possiblyGood = true; foreach (var alt in context.ruleAltList().labeledAlt()) { string ruleName = alt.identifier() != null ? alt.identifier().GetText() : null; bool handled = false; Antlr4ParserRule ruleAlt; if (!handled && this.IsRoslynRule(alt, ref reportedErrors, out ruleAlt)) { handled = true; ruleAlt.Name = ruleName; ruleAlt.ParentRule = rule; rule.Alternatives.Add(ruleAlt); this.CollectAnnotations(ruleAlt, alt.annotation()); } if (!handled) { possiblyGood = false; } } return allNamed && possiblyGood; } private bool IsRoslynRule(Antlr4RoslynParser.LabeledAltContext context, ref bool reportedErrors, out Antlr4ParserRule rule) { Antlr4RoslynParser.ElementContext[] elems = context.alternative().element().Where(e => !this.IsActionBlock(e)).ToArray(); rule = new Antlr4ParserRule(this.Grammar, this.GetLocation(context.identifier())); for (int i = 0; i < elems.Length; ++i) { Antlr4ParserRuleElement element; int skip = this.IsRoslynRuleElement(elems[i], i + 1 < elems.Length ? elems[i + 1] : null, i + 2 < elems.Length ? elems[i + 2] : null, true, ref reportedErrors, out element); if (skip > 0) { element.Rule = rule; rule.Elements.Add(element); i += skip - 1; } else { return false; } } return this.CheckUniqueElements(rule, ref reportedErrors); } private bool IsActionBlock(Antlr4RoslynParser.ElementContext elem) { return elem.actionBlock() != null; } private bool EndsWithEof(Antlr4RoslynParser.LabeledAltContext context) { Antlr4RoslynParser.ElementContext[] elems = context.alternative().element().Where(e => !this.IsActionBlock(e)).ToArray(); if (elems.Length > 0) { Antlr4RoslynParser.ElementContext elem = elems[elems.Length - 1]; if (elem.atom() != null) { if (elem.atom().terminal() != null && elem.atom().terminal().TOKEN_REF() != null) { string name = elem.atom().terminal().TOKEN_REF().GetText(); return name == "EOF"; } } else if (elem.labeledElement() != null && elem.labeledElement().atom() != null) { if (elem.labeledElement().atom().terminal() != null && elem.labeledElement().atom().terminal().TOKEN_REF() != null) { string name = elem.labeledElement().atom().terminal().TOKEN_REF().GetText(); return name == "EOF"; } } } return false; } private int IsRoslynRuleElement(Antlr4RoslynParser.ElementContext first, Antlr4RoslynParser.ElementContext second, Antlr4RoslynParser.ElementContext third, bool allowBlocks, ref bool reportedErrors, out Antlr4ParserRuleElement element) { int skip = this.IsSeparatedList(first, second, third, out element); if (skip > 0) { return skip; } Antlr4RoslynParser.ElementContext elem = first; if (this.IsSingleTokenOrRuleElement(elem, TokenOrRule.Any, true, out element)) { return 1; } else if (elem.labeledElement() != null && elem.labeledElement().block() != null) { if (this.IsRoslynBlockTokenAlts(elem.labeledElement().block(), ref reportedErrors, out element)) { element.Name = elem.labeledElement().identifier().GetText(); if (this.IsEbnfOptional(elem.ebnfSuffix())) { element.IsOptional = true; } if (this.IsEbnfList(elem.ebnfSuffix())) { element.IsList = true; } return 1; } if (!this.IgnoreRoslynRules) this.compiler.AddDiagnostic(elem.labeledElement().identifier(), Antlr4RoslynErrorCode.ERR_BlockMap); return 0; } else if (elem.ebnf() != null) { if (this.IsRoslynBlockSingleAlt(elem.ebnf().block(), ref reportedErrors, out element)) { Antlr4RoslynParser.BlockSuffixContext blockSuffix = elem.ebnf().blockSuffix(); if (blockSuffix != null) { if (this.IsEbnfOptional(blockSuffix.ebnfSuffix())) { element.IsOptional = true; return 1; } if (!this.IgnoreRoslynRules) this.compiler.AddDiagnostic(blockSuffix, Antlr4RoslynErrorCode.ERR_BlockMapSuffix); return 0; } else { return 1; } } else if (this.IsRoslynBlockTokenAlts(elem.ebnf().block(), ref reportedErrors, out element)) { reportedErrors = true; if (!this.IgnoreRoslynRules) this.compiler.AddDiagnostic(elem.ebnf().block(), Antlr4RoslynErrorCode.ERR_UnnamedBlock); return 0; } if (!this.IgnoreRoslynRules) this.compiler.AddDiagnostic(elem.ebnf().block(), Antlr4RoslynErrorCode.ERR_BlockMap); return 0; } return 0; } private bool IsEbnfOptional(Antlr4RoslynParser.EbnfSuffixContext context) { if (context == null) return false; return context.PLUS() == null && (context.STAR() != null || context.QUESTION().Length == 1); } private bool IsEbnfList(Antlr4RoslynParser.EbnfSuffixContext context) { if (context == null) return false; return (context.PLUS() != null || context.STAR() != null) && context.QUESTION().Length == 0; } private bool IsRoslynBlock(Antlr4RoslynParser.BlockContext context, ref bool reportedErrors, out Antlr4ParserRuleElement block) { if (this.IsRoslynBlockTokenAlts(context, ref reportedErrors, out block)) { return true; } if (this.IsRoslynBlockSingleAlt(context, ref reportedErrors, out block)) { return true; } return false; } private bool IsRoslynAltList(Antlr4RoslynParser.RuleBlockContext context, TokenOrRule kind, bool allowEbnf, ref bool reportedErrors, out Antlr4ParserRule rule) { rule = new Antlr4ParserRule(this.Grammar, this.GetLocation(context)); Antlr4ParserRuleElement blockElem = null; if (kind == TokenOrRule.Token) { var ruleRef = ((Antlr4RoslynParser.ParserRuleSpecContext)(context.Parent)).RULE_REF(); blockElem = new Antlr4ParserRuleElement(context, this.GetLocation(ruleRef)); blockElem.Rule = rule; blockElem.Name = ruleRef.GetText(); blockElem.IsFixedTokenAltBlock = true; blockElem.IsBlock = true; rule.Elements.Add(blockElem); } var alts = context.ruleAltList().labeledAlt().Select(la => la.alternative()).ToList(); foreach (var alt in alts) { Antlr4ParserRuleElement element; if (this.IsRoslynSingleTokenOrRuleElementAlt(alt, kind, false, out element)) { if (blockElem != null) { element.ParentBlock = blockElem; blockElem.BlockItems.Add(element); } else { element.Rule = rule; rule.Elements.Add(element); } } else { rule = null; return false; } } rule.IsSimpleAlt = kind == TokenOrRule.Rule; return this.CheckUniqueElements(rule, ref reportedErrors); } private bool IsRoslynBlockTokenAlts(Antlr4RoslynParser.BlockContext context, ref bool reportedErrors, out Antlr4ParserRuleElement block) { block = new Antlr4ParserRuleElement(context, this.GetLocation(context)); block.IsBlock = true; block.IsFixedTokenAltBlock = true; var alts = context.altList().alternative(); foreach (var alt in alts) { Antlr4ParserRuleElement token; if (this.IsRoslynSingleTokenOrRuleElementAlt(alt, TokenOrRule.Token, false, out token)) { token.ParentBlock = block; block.BlockItems.Add(token); } else { block = null; return false; } } return true; } private bool IsRoslynBlockSingleAlt(Antlr4RoslynParser.BlockContext context, ref bool reportedErrors, out Antlr4ParserRuleElement block) { if (context.altList().alternative().Length == 1) { block = new Antlr4ParserRuleElement(context, this.GetLocation(context)); block.IsBlock = true; var alt = context.altList().alternative()[0]; Antlr4RoslynParser.ElementContext[] elems = alt.element().Where(e => !this.IsActionBlock(e)).ToArray(); for (int i = 0; i < elems.Length; ++i) { Antlr4ParserRuleElement element; int skip = this.IsRoslynRuleElement(elems[i], i + 1 < elems.Length ? elems[i + 1] : null, i + 2 < elems.Length ? elems[i + 2] : null, false, ref reportedErrors, out element); if (skip > 0) { element.ParentBlock = block; block.BlockItems.Add(element); i += skip - 1; } else { if (!this.IgnoreRoslynRules) this.compiler.AddDiagnostic(elems[i], Antlr4RoslynErrorCode.ERR_ElementMap); reportedErrors = true; block = null; return false; } } return true; } block = null; return false; } private bool IsRoslynSingleElementAlt(Antlr4RoslynParser.AlternativeContext context, TokenOrRule kind, bool allowEbnf, ref bool reportedErrors, out Antlr4ParserRuleElement element) { Antlr4RoslynParser.ElementContext[] elems = context.element().Where(e => !this.IsActionBlock(e)).ToArray(); int skip = this.IsRoslynRuleElement(elems[0], elems.Length >= 2 ? elems[1] : null, elems.Length >= 3 ? elems[2] : null, false, ref reportedErrors, out element); if (skip > 0 && skip == elems.Length) { return true; } element = null; return false; } private bool IsRoslynSingleTokenOrRuleElementAlt(Antlr4RoslynParser.AlternativeContext context, TokenOrRule kind, bool allowEbnf, out Antlr4ParserRuleElement element) { Antlr4RoslynParser.ElementContext[] elems = context.element().Where(e => !this.IsActionBlock(e)).ToArray(); if (elems.Length == 1) { Antlr4RoslynParser.ElementContext elem = elems[0]; if (this.IsSingleTokenOrRuleElement(elem, kind, allowEbnf, out element)) { return true; } } element = null; return false; } private bool IsSingleTokenOrRuleElement(Antlr4RoslynParser.ElementContext elem, TokenOrRule kind, bool allowEbnf, out Antlr4ParserRuleElement element) { element = null; if (elem.ebnf() == null && elem.actionBlock() == null) { string name = null; Antlr4RoslynParser.AtomContext atom = null; if (elem.labeledElement() != null) { if (elem.labeledElement().atom() != null) { name = elem.labeledElement().identifier().GetText(); atom = elem.labeledElement().atom(); } else { return false; } } else if (elem.atom() != null) { atom = elem.atom(); } if (atom != null) { if (atom.terminal() != null) { if (kind == TokenOrRule.Rule) return false; element = new Antlr4ParserRuleElement(elem, this.GetLocation(atom.terminal())); element.Type = atom.terminal().GetText(); this.CollectAnnotations(element, elem.annotation()); } else if (atom.ruleref() != null) { if (kind == TokenOrRule.Token) return false; element = new Antlr4ParserRuleElement(elem, this.GetLocation(atom.ruleref())); element.Type = atom.ruleref().GetText(); this.CollectAnnotations(element, elem.annotation()); } if (element != null) { if (name == null) element.Name = element.Type; else element.Name = name; if (elem.ebnfSuffix() != null) { if (!allowEbnf) { element = null; return false; } if (elem.ebnfSuffix().PLUS() != null) { element.IsList = true; } else if (elem.ebnfSuffix().STAR() != null) { element.IsList = true; element.IsOptional = true; } else if (elem.ebnfSuffix().QUESTION().Length > 0) { element.IsOptional = true; } } if (!element.IsOptional) { var alternativeContext = elem.Parent as Antlr4RoslynParser.AlternativeContext; if (alternativeContext != null) { var altListContext = alternativeContext.Parent as Antlr4RoslynParser.AltListContext; if (altListContext != null) { var blockContext = altListContext.Parent as Antlr4RoslynParser.BlockContext; if (blockContext != null) { var ebnfContext= blockContext.Parent as Antlr4RoslynParser.EbnfContext; if (ebnfContext != null) { if (IsEbnfOptional(ebnfContext?.blockSuffix()?.ebnfSuffix())) { element.IsOptional = true; } } } } } } return true; } } } return false; } private int IsSeparatedList(Antlr4RoslynParser.ElementContext first, Antlr4RoslynParser.ElementContext second, Antlr4RoslynParser.ElementContext third, out Antlr4ParserRuleElement element) { int skip = 0; if (first != null && second != null) { if (second.ebnf() != null && second.ebnf().blockSuffix() != null && second.ebnf().blockSuffix().ebnfSuffix() != null && (second.ebnf().blockSuffix().ebnfSuffix().PLUS() != null || second.ebnf().blockSuffix().ebnfSuffix().STAR() != null) && second.ebnf().blockSuffix().ebnfSuffix().QUESTION().Length == 0 && second.ebnf().block().altList().alternative().Length == 1) { Antlr4RoslynParser.ElementContext[] secondBlockElements = second.ebnf().block().altList().alternative()[0].element().Where(e => !this.IsActionBlock(e)).ToArray(); if (secondBlockElements.Length == 2) { Antlr4RoslynParser.ElementContext token = secondBlockElements[0]; Antlr4RoslynParser.ElementContext ruleRep = secondBlockElements[1]; Antlr4ParserRuleElement ruleElement; Antlr4ParserRuleElement tokenElement; Antlr4ParserRuleElement ruleRepElement; if (this.IsSingleTokenOrRuleElement(first, TokenOrRule.Rule, false, out ruleElement) && this.IsSingleTokenOrRuleElement(token, TokenOrRule.Token, false, out tokenElement) && this.IsSingleTokenOrRuleElement(ruleRep, TokenOrRule.Rule, false, out ruleRepElement) && ruleElement.Type == ruleRepElement.Type && ruleElement.Name == ruleRepElement.Name) { skip = 2; ruleElement.IsList = true; ruleElement.IsSeparated = true; ruleElement.Separator = tokenElement; tokenElement.ParentBlock = ruleElement; ruleElement.EndToken = Antlr4SeparatedListEndToken.Forbidden; Antlr4ParserRuleElement lastElement; if (third != null && this.IsSingleTokenOrRuleElement(third, TokenOrRule.Token, true, out lastElement) && lastElement.Type == tokenElement.Type && lastElement.Name == tokenElement.Name) { ++skip; if (!lastElement.IsList) { if (lastElement.IsOptional) ruleElement.EndToken = Antlr4SeparatedListEndToken.Allowed; else ruleElement.EndToken = Antlr4SeparatedListEndToken.Mandatory; } } element = ruleElement; return skip; } } } } if (first != null) { if (first.ebnf() != null && first.ebnf().blockSuffix() != null && first.ebnf().blockSuffix().ebnfSuffix() != null && (first.ebnf().blockSuffix().ebnfSuffix().PLUS() != null || first.ebnf().blockSuffix().ebnfSuffix().STAR() != null) && first.ebnf().blockSuffix().ebnfSuffix().QUESTION().Length == 0 && first.ebnf().block().altList().alternative().Length == 1) { Antlr4RoslynParser.ElementContext[] firstBlockElements = first.ebnf().block().altList().alternative()[0].element().Where(e => !this.IsActionBlock(e)).ToArray(); if (firstBlockElements.Length == 2) { Antlr4RoslynParser.ElementContext ruleRep = firstBlockElements[0]; Antlr4RoslynParser.ElementContext token = firstBlockElements[1]; Antlr4ParserRuleElement ruleRepElement; Antlr4ParserRuleElement tokenElement; if (this.IsSingleTokenOrRuleElement(ruleRep, TokenOrRule.Rule, false, out ruleRepElement) && this.IsSingleTokenOrRuleElement(token, TokenOrRule.Token, false, out tokenElement)) { skip = 1; ruleRepElement.IsList = true; ruleRepElement.IsSeparated = true; ruleRepElement.Separator = tokenElement; tokenElement.ParentBlock = ruleRepElement; ruleRepElement.EndToken = Antlr4SeparatedListEndToken.Mandatory; Antlr4ParserRuleElement lastElement; if (second != null && this.IsSingleTokenOrRuleElement(second, TokenOrRule.Rule, false, out lastElement) && lastElement.Type == ruleRepElement.Type && lastElement.Name == ruleRepElement.Name) { ruleRepElement.EndToken = Antlr4SeparatedListEndToken.Forbidden; ++skip; } element = ruleRepElement; return skip; } } } } element = null; return 0; } private enum TokenOrRule { Any, Token, Rule } } // TODO: make these classes internal public enum Antlr4SeparatedListEndToken { Forbidden, Mandatory, Allowed } public class Antlr4AnnotatedObject { public Antlr4AnnotatedObject(Location location) { this.Annotations = MetaCompilerAnnotations.Empty; this.Location = location; } public MetaCompilerAnnotations Annotations { get; internal set; } public bool ContainsDeclarationTreeAnnotations { get; internal set; } public bool ContainsAnnotations { get; internal set; } public bool HasAnnotations { get; internal set; } public bool ContainsBinderAnnotations { get; internal set; } public bool HasBinderAnnotations { get; internal set; } public bool ContainsBoundNodeAnnotations { get; internal set; } public bool HasBoundNodeAnnotations { get; internal set; } public Location Location { get; internal set; } } public class Antlr4Grammar : Antlr4AnnotatedObject { public Antlr4Grammar(Location location) : base(location) { this.CustomAnnotations = new List<MetaCompilerAnnotation>(); this.Imports = new HashSet<string>(); this.ParserRuleElemUses = new HashSet<string>(); this.ParserRules = new List<Antlr4ParserRule>(); this.LexerRules = new List<Antlr4LexerRule>(); this.VirtualTokenKinds = new List<string>(); this.LexerTokenKinds = new Dictionary<string, List<Antlr4LexerRule>>(); this.LexerModes = new List<Antlr4LexerMode>(); this.FixedTokenCandidates = new List<Antlr4LexerRule>(); this.FixedTokens = new List<Antlr4LexerRule>(); } public string Name { get; set; } public string ErrorCodeCategory { get; set; } public string MessagePrefix { get; set; } public string LexerHeader { get; set; } public string ParserHeader { get; set; } public List<MetaCompilerAnnotation> CustomAnnotations { get; private set; } public HashSet<string> Imports { get; private set; } public HashSet<string> ParserRuleElemUses { get; private set; } public List<string> VirtualTokenKinds { get; private set; } public Dictionary<string, List<Antlr4LexerRule>> LexerTokenKinds { get; private set; } public Antlr4LexerRule FirstTokenSyntaxKind { get; set; } public Antlr4LexerRule LastTokenSyntaxKind { get; set; } public Antlr4LexerRule FirstFixedTokenSyntaxKind { get; set; } public Antlr4LexerRule LastFixedTokenSyntaxKind { get; set; } public Antlr4ParserRule FirstParserRuleSyntaxKind { get; set; } public Antlr4ParserRule LastParserRuleSyntaxKind { get; set; } public List<Antlr4ParserRule> ParserRules { get; private set; } public List<Antlr4LexerRule> LexerRules { get; private set; } public Antlr4LexerRule DefaultWhitespaceKind { get; set; } public Antlr4LexerRule DefaultEndOfLineKind { get; set; } public Antlr4LexerRule DefaultIdentifierKind { get; set; } public Antlr4LexerRule DefaultSeparatorKind { get; set; } public List<Antlr4LexerMode> LexerModes { get; private set; } internal List<Antlr4LexerRule> FixedTokenCandidates { get; private set; } public List<Antlr4LexerRule> FixedTokens { get; private set; } public Antlr4ParserRule FindParserRule(string type) { return this.ParserRules.FirstOrDefault(rule => rule.Name == type); } } public class Antlr4ParserRule : Antlr4AnnotatedObject { public Antlr4ParserRule(Antlr4Grammar grammar, Location location) : base(location) { this.Grammar = grammar; this.Elements = new List<Antlr4ParserRuleElement>(); this.Alternatives = new List<Antlr4ParserRule>(); } public Antlr4Grammar Grammar { get; private set; } public Antlr4ParserRule ParentRule { get; internal set; } public string Name { get; set; } public List<Antlr4ParserRuleElement> Elements { get; private set; } public List<Antlr4ParserRule> Alternatives { get; private set; } public Antlr4ParserRule FirstNonAbstractAlternative { get; internal set; } public bool IsSimpleAlt { get; internal set; } public bool IsRecursive { get; internal set; } public List<Antlr4ParserRuleElement> AllElements { get { List<Antlr4ParserRuleElement> result = new List<Antlr4ParserRuleElement>(); foreach (var elem in this.Elements) { if (elem.IsBlock && !elem.IsFixedTokenAltBlock) { foreach (var blockElem in elem.BlockItems) { result.Add(blockElem); } } else { result.Add(elem); } } return result; } } } public class Antlr4ParserRuleElement : Antlr4AnnotatedObject { public Antlr4ParserRuleElement(object node, Location location) : base(location) { this.Node = node; this.BlockItems = new List<Antlr4ParserRuleElement>(); } public Antlr4Grammar Grammar { get { if (this.Rule != null) return this.Rule.Grammar; if (this.ParentBlock != null) return this.ParentBlock.Grammar; return null; } } public Antlr4ParserRule Rule { get; internal set; } public Antlr4ParserRuleElement ParentBlock { get; internal set; } public object Node { get; private set; } public string Name { get; set; } public string Type { get; set; } public string OriginalType { get; set; } public bool IsOptional { get; set; } public bool IsFixedToken { get { return this.IsToken && this.Grammar.FixedTokens.Any(ft => ft.Name == this.Name); } } public bool IsList { get; set; } public bool IsSeparated { get; set; } public bool IsSimplified { get; set; } public Antlr4SeparatedListEndToken EndToken { get; set; } public Antlr4ParserRuleElement Separator { get; set; } public bool IsToken { get { return !string.IsNullOrEmpty(this.Type) && char.IsUpper(this.Type[0]); } } public bool IsParserRule { get { return !string.IsNullOrEmpty(this.Type) && char.IsLower(this.Type[0]); } } public bool IsBlock { get; set; } public bool IsFixedTokenAltBlock { get; set; } public List<Antlr4ParserRuleElement> BlockItems { get; private set; } public string GetAccessorName() { bool method = false; string result; if ((!this.IsSimplified && this.Name != this.Type) || (this.IsSimplified && this.Name != this.OriginalType)) { if (this.IsList) result = "_" + this.Name; else result = this.Name; } else { if (this.Type == "EOF") result = "Eof"; else if (this.IsSimplified) result = this.OriginalType; else result = this.Type; method = true; } if (Antlr4RoslynCompiler.reservedNames.Contains(result)) result = "@"+result; if (method) result += "()"; return result; } public bool IsMappedToIList() { if (this.IsList) { if ((!this.IsSimplified && this.Name != this.Type) || (this.IsSimplified && this.Name != this.OriginalType)) { return true; } } return false; } } public class Antlr4LexerMode : Antlr4AnnotatedObject { public Antlr4LexerMode(Antlr4Grammar grammar, Location location) : base(location) { this.Grammar = grammar; this.LexerRules = new List<Antlr4LexerRule>(); } public Antlr4Grammar Grammar { get; private set; } public string Name { get; set; } public int Kind { get; set; } public List<Antlr4LexerRule> LexerRules { get; private set; } } public class Antlr4LexerRule : Antlr4AnnotatedObject { public Antlr4LexerRule(Antlr4LexerMode mode, Location location) : base(location) { this.Mode = mode; } public Antlr4Grammar Grammar { get { return this.Mode.Grammar; } } public Antlr4LexerMode Mode { get; private set; } public string Name { get; set; } public string FixedToken { get; set; } public int Kind { get; set; } public bool Artificial { get; set; } } internal class Antlr4AnnotationRemover : Antlr4RoslynParserBaseVisitor<object> { private TokenStreamRewriter rewriter; private BufferedTokenStream tokens; public Antlr4AnnotationRemover(BufferedTokenStream tokens) { this.tokens = tokens; rewriter = new TokenStreamRewriter(tokens); } public string GetText() { return rewriter.GetText(); } public LinePositionSpan GetTokenSpanAt(int line, int column) { foreach (var token in tokens.GetTokens()) { if (token.Line == line && token.Column == column) return new LinePositionSpan(new LinePosition(token.Line - 1, token.Column), new LinePosition(token.Line - 1, token.Column + token.StopIndex - token.StartIndex + 1)); } return default; } private void RemoveText(ParserRuleContext context) { string text = this.tokens.GetText(context); StringBuilder sb = new StringBuilder(); foreach (char ch in text) { if (ch == '\r' || ch == '\n') { sb.Append(ch); } else { sb.Append(' '); } } //rewriter.Delete(context.Start, context.Stop); string newText = sb.ToString(); rewriter.Replace(context.Start, context.Stop, newText); } public override object VisitOption(Antlr4RoslynParser.OptionContext context) { if (context.identifier().GetText() == "generateCompiler") { this.RemoveText(context); } else if (context.identifier().GetText() == "generateCompilerBase") { this.RemoveText(context); } else if (context.identifier().GetText() == "ignoreRoslynRules") { this.RemoveText(context); } else if (context.identifier().GetText() == "generateLanguageService") { this.RemoveText(context); } return null; } public override object VisitAnnotation(Antlr4RoslynParser.AnnotationContext context) { this.RemoveText(context); return null; } } }
balazssimon/meta-cs
src/Main/MetaDslx.CodeAnalysis.Antlr4/Languages/Antlr4Roslyn/Compilation/Antlr4RoslynCompiler.cs
C#
apache-2.0
101,781
var request = require('supertest'); var assert = require('chai').assert; describe('testing user authentication', function() { var server; beforeEach(function(done) { delete require.cache[require.resolve('../src/server')]; server = require('../src/server'); done(); }); afterEach(function(done) { server.close(done); }); it('returns authentication token', function test(done) { var auth = { "email": "kraken@yahoo.com", "password": "password", }; request(server).post('/api/authenticate').send(auth) .expect('Content-Type', 'application/json') .end(function(err, result) { assert.equal(result.body.success, true); assert.equal(result.body.message, "Your token is valid for 8 hours"); done(); }); }); });
jcaple/giphy_search
test/test-authenticate.js
JavaScript
apache-2.0
762
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Code generated by cloud.google.com/go/internal/gapicgen/gensnippets. DO NOT EDIT. // [START compute_v1_generated_Instances_BulkInsert_sync] package main import ( "context" compute "cloud.google.com/go/compute/apiv1" computepb "google.golang.org/genproto/googleapis/cloud/compute/v1" ) func main() { ctx := context.Background() c, err := compute.NewInstancesRESTClient(ctx) if err != nil { // TODO: Handle error. } defer c.Close() req := &computepb.BulkInsertInstanceRequest{ // TODO: Fill request struct fields. // See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/compute/v1#BulkInsertInstanceRequest. } op, err := c.BulkInsert(ctx, req) if err != nil { // TODO: Handle error. } err = op.Wait(ctx) if err != nil { // TODO: Handle error. } } // [END compute_v1_generated_Instances_BulkInsert_sync]
googleapis/google-cloud-go
internal/generated/snippets/compute/apiv1/InstancesClient/BulkInsert/main.go
GO
apache-2.0
1,441
namespace PrintHost.view { partial class SDCard { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SDCard)); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolAddFile = new System.Windows.Forms.ToolStripButton(); this.toolDelFile = new System.Windows.Forms.ToolStripButton(); this.toolStartPrint = new System.Windows.Forms.ToolStripButton(); this.toolStopPrint = new System.Windows.Forms.ToolStripButton(); this.toolMount = new System.Windows.Forms.ToolStripButton(); this.toolUnmount = new System.Windows.Forms.ToolStripButton(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.toolStatus = new System.Windows.Forms.ToolStripStatusLabel(); this.progress = new System.Windows.Forms.ToolStripProgressBar(); this.files = new System.Windows.Forms.ListView(); this.columnHeaderName = new System.Windows.Forms.ColumnHeader(); this.columnHeaderSize = new System.Windows.Forms.ColumnHeader(); this.buttonClose = new System.Windows.Forms.Button(); this.timer = new System.Windows.Forms.Timer(this.components); this.imageList = new System.Windows.Forms.ImageList(this.components); this.toolNewFolder = new System.Windows.Forms.ToolStripButton(); this.toolStrip1.SuspendLayout(); this.statusStrip1.SuspendLayout(); this.SuspendLayout(); // // toolStrip1 // this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip1.ImageScalingSize = new System.Drawing.Size(32, 32); this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolAddFile, this.toolDelFile, this.toolNewFolder, this.toolStartPrint, this.toolStopPrint, this.toolMount, this.toolUnmount}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(383, 39); this.toolStrip1.TabIndex = 0; this.toolStrip1.Text = "toolStrip1"; // // toolAddFile // this.toolAddFile.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolAddFile.Image = ((System.Drawing.Image)(resources.GetObject("toolAddFile.Image"))); this.toolAddFile.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolAddFile.Name = "toolAddFile"; this.toolAddFile.Size = new System.Drawing.Size(36, 36); this.toolAddFile.Text = "toolStripButton1"; this.toolAddFile.ToolTipText = "Upload current file"; this.toolAddFile.Click += new System.EventHandler(this.toolAddFile_Click); // // toolDelFile // this.toolDelFile.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolDelFile.Image = ((System.Drawing.Image)(resources.GetObject("toolDelFile.Image"))); this.toolDelFile.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolDelFile.Name = "toolDelFile"; this.toolDelFile.Size = new System.Drawing.Size(36, 36); this.toolDelFile.Text = "toolDelFile"; this.toolDelFile.ToolTipText = "Delete file"; this.toolDelFile.Click += new System.EventHandler(this.toolStripButton1_Click); // // toolStartPrint // this.toolStartPrint.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStartPrint.Enabled = false; this.toolStartPrint.Image = ((System.Drawing.Image)(resources.GetObject("toolStartPrint.Image"))); this.toolStartPrint.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStartPrint.Name = "toolStartPrint"; this.toolStartPrint.Size = new System.Drawing.Size(36, 36); this.toolStartPrint.Text = "toolStripButton2"; this.toolStartPrint.ToolTipText = "Run selected file / Continue paused print"; this.toolStartPrint.Click += new System.EventHandler(this.toolStartPrint_Click); // // toolStopPrint // this.toolStopPrint.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStopPrint.Image = ((System.Drawing.Image)(resources.GetObject("toolStopPrint.Image"))); this.toolStopPrint.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStopPrint.Name = "toolStopPrint"; this.toolStopPrint.Size = new System.Drawing.Size(36, 36); this.toolStopPrint.Text = "toolStripButton3"; this.toolStopPrint.ToolTipText = "Pause/Stop running sd print"; this.toolStopPrint.Click += new System.EventHandler(this.toolStopPrint_Click); // // toolMount // this.toolMount.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolMount.Image = ((System.Drawing.Image)(resources.GetObject("toolMount.Image"))); this.toolMount.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolMount.Name = "toolMount"; this.toolMount.Size = new System.Drawing.Size(36, 36); this.toolMount.Text = "toolStripButton2"; this.toolMount.ToolTipText = "Mount sd card"; this.toolMount.Click += new System.EventHandler(this.toolMount_Click); // // toolUnmount // this.toolUnmount.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolUnmount.Image = ((System.Drawing.Image)(resources.GetObject("toolUnmount.Image"))); this.toolUnmount.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolUnmount.Name = "toolUnmount"; this.toolUnmount.Size = new System.Drawing.Size(36, 36); this.toolUnmount.Text = "toolStripButton3"; this.toolUnmount.ToolTipText = "Unmount sd card"; this.toolUnmount.Click += new System.EventHandler(this.toolUnmount_Click); // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStatus, this.progress}); this.statusStrip1.Location = new System.Drawing.Point(0, 386); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Padding = new System.Windows.Forms.Padding(1, 0, 15, 0); this.statusStrip1.Size = new System.Drawing.Size(383, 22); this.statusStrip1.SizingGrip = false; this.statusStrip1.TabIndex = 1; this.statusStrip1.Text = "statusStrip1"; // // toolStatus // this.toolStatus.Name = "toolStatus"; this.toolStatus.Size = new System.Drawing.Size(151, 17); this.toolStatus.Spring = true; this.toolStatus.Text = "-"; // // progress // this.progress.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.progress.Maximum = 200; this.progress.Name = "progress"; this.progress.Size = new System.Drawing.Size(214, 16); // // files // this.files.Activation = System.Windows.Forms.ItemActivation.OneClick; this.files.AllowColumnReorder = true; this.files.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.files.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeaderName, this.columnHeaderSize}); this.files.FullRowSelect = true; this.files.Location = new System.Drawing.Point(13, 42); this.files.MultiSelect = false; this.files.Name = "files"; this.files.Size = new System.Drawing.Size(360, 294); this.files.SmallImageList = this.imageList; this.files.Sorting = System.Windows.Forms.SortOrder.Ascending; this.files.TabIndex = 2; this.files.UseCompatibleStateImageBehavior = false; this.files.View = System.Windows.Forms.View.Details; this.files.SelectedIndexChanged += new System.EventHandler(this.files_SelectedIndexChanged); this.files.DoubleClick += new System.EventHandler(this.files_DoubleClick); // // columnHeaderName // this.columnHeaderName.Text = "Name"; this.columnHeaderName.Width = 250; // // columnHeaderSize // this.columnHeaderSize.Text = "Size"; this.columnHeaderSize.Width = 83; // // buttonClose // this.buttonClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonClose.Location = new System.Drawing.Point(291, 342); this.buttonClose.Name = "buttonClose"; this.buttonClose.Size = new System.Drawing.Size(80, 22); this.buttonClose.TabIndex = 3; this.buttonClose.Text = "Close"; this.buttonClose.UseVisualStyleBackColor = true; this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click); // // timer // this.timer.Enabled = true; this.timer.Interval = 1000; this.timer.Tick += new System.EventHandler(this.timer_Tick); // // imageList // this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream"))); this.imageList.TransparentColor = System.Drawing.Color.Transparent; this.imageList.Images.SetKeyName(0, "load16.png"); this.imageList.Images.SetKeyName(1, "folder.png"); // // toolNewFolder // this.toolNewFolder.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolNewFolder.Image = ((System.Drawing.Image)(resources.GetObject("toolNewFolder.Image"))); this.toolNewFolder.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolNewFolder.Name = "toolNewFolder"; this.toolNewFolder.Size = new System.Drawing.Size(36, 36); this.toolNewFolder.Text = "New folder"; this.toolNewFolder.ToolTipText = "Create new folder"; this.toolNewFolder.Click += new System.EventHandler(this.toolNewFolder_Click); // // SDCard // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.ClientSize = new System.Drawing.Size(383, 408); this.ControlBox = false; this.Controls.Add(this.buttonClose); this.Controls.Add(this.files); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.toolStrip1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SDCard"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.Text = "SD card manager"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.SDCard_FormClosing); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton toolAddFile; private System.Windows.Forms.ToolStripButton toolStartPrint; private System.Windows.Forms.ToolStripButton toolStopPrint; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.ToolStripStatusLabel toolStatus; private System.Windows.Forms.ToolStripProgressBar progress; private System.Windows.Forms.ListView files; private System.Windows.Forms.ColumnHeader columnHeaderName; private System.Windows.Forms.ColumnHeader columnHeaderSize; private System.Windows.Forms.Button buttonClose; private System.Windows.Forms.Timer timer; private System.Windows.Forms.ToolStripButton toolDelFile; private System.Windows.Forms.ToolStripButton toolMount; private System.Windows.Forms.ToolStripButton toolUnmount; private System.Windows.Forms.ImageList imageList; private System.Windows.Forms.ToolStripButton toolNewFolder; } }
brandon75f/PrintHost
Printhost/FossHost-master/src/PrintHost/view/SDCard.Designer.cs
C#
apache-2.0
14,691
// Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "ngraph/opsets/opset.hpp" #include "ngraph/opsets/opset2.hpp" #include "plaidml/op/op.h" #include "plaidml_ops.hpp" #include "plaidml_util.hpp" using namespace plaidml; // NOLINT[build/namespaces] using namespace InferenceEngine; // NOLINT[build/namespaces] namespace PlaidMLPlugin { void registerSpaceToBatch() { registerOp("SpaceToBatch", [](const Context& ctx) { IE_ASSERT(ctx.operands.size() == 4); auto I = ctx.operands.at(0); auto block_shape = get_shape_from_constant_operand(1, ctx.layer); if (block_shape.size() != I.rank()) { THROW_IE_EXCEPTION << "block_shape and tensor dims have to equal!"; } if (block_shape[0] != 1) { THROW_IE_EXCEPTION << "block_shape[0] is expected to be one."; } auto crops_begin = get_coords_from_constant_operand(2, ctx.layer); auto crops_end = get_coords_from_constant_operand(3, ctx.layer); // According to openvino op spec: // Zero-pad the start and end of dimensions [D_0, ..., D_{N - 1}] of the input according to `pads_begin` and // `pads_end`: // x = [batch + P_0, D_1 + P_1, D_2 + P_2, ..., D_{N - 1} + P_{N - 1}], where P_i = pads_begin[i] + pads_end[i] std::vector<int> lo_pads; for (auto pad : crops_begin) { lo_pads.push_back(pad); } std::vector<int> hi_pads; for (auto pad : crops_end) { hi_pads.push_back(pad); } if (lo_pads[0] || hi_pads[0]) { THROW_IE_EXCEPTION << "batch dim pad have to be zero!"; } edsl::Tensor padding_I = op::explicit_padding(I, lo_pads, hi_pads).padval(edsl::Constant(0)); // reshape padding tensor // x' = reshape(x, [batch, (D_1 + P_1) / B_1, B_1, (D_2 + P_2) / B_2, B_2, ..., // (D_{N - 1} + P_{N - 1}) / B_{N - 1}, B_{N - 1}]), where B_i = block_shape[i] std::vector<edsl::TensorDim> I_dims(padding_I.rank()); padding_I.bind_dims(I_dims); std::vector<edsl::TensorDim> temp_dims; temp_dims.push_back(I_dims[0]); for (size_t i = 1; i < block_shape.size(); i++) { temp_dims.emplace_back(I_dims[i] / block_shape[i]); temp_dims.emplace_back(block_shape[i]); } auto reshape_I = edsl::reshape(padding_I, temp_dims); // transpose reshape tensor. // x'' = transpose(x', [2, 4, ..., (N - 1) + (N - 1), 0, 1, 3, ..., N + (N - 1)]) // // setup the sort dims std::vector<size_t> reshape_dims(reshape_I.rank()); auto dims_size = reshape_dims.size(); auto mid_dim = dims_size / 2; reshape_dims[mid_dim] = 0; for (size_t i = 0; i < mid_dim; i++) { reshape_dims[i] = 2 * (i + 1); reshape_dims[i + mid_dim + 1] = 2 * i + 1; } std::vector<edsl::Value> dims_wrapper; for (auto dim : reshape_dims) { dims_wrapper.emplace_back(dim); } auto transpose_I = op::transpose(reshape_I, edsl::Value(dims_wrapper)); // reshape to the final tensor. // y = reshape(x'', [batch * B_1 * ... * B_{N - 1}, (D_1 + P_1) / B_1, (D_2 + P_2) / B_2, ... , // (D_{N - 1} + P_{N - 1}) / B_{N - 1}]) size_t total_block_size = 1; for (size_t i = 0; i < block_shape.size(); i++) { total_block_size *= block_shape[i]; } for (size_t i = 0; i < I_dims.size(); i++) { if (i == 0) { I_dims[i] = I_dims[i] * total_block_size; } I_dims[i] = I_dims[i] / block_shape[i]; } edsl::Tensor O = edsl::reshape(transpose_I, I_dims); return edsl::make_tuple(O); }); } } // namespace PlaidMLPlugin
plaidml/plaidml
plaidml/bridge/openvino/ops/space_to_batch.cpp
C++
apache-2.0
3,562
<?php /** * @author Manuel Thalmann <m@nuth.ch> * @license Apache-2.0 */ use System\Web\{ ScriptDefinition }; { $jQuery = ScriptDefinition::FromFile('https://code.jquery.com/jquery-3.2.1.js'); $bootstrapScript = ScriptDefinition::FromFile('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'); $testScript = ScriptDefinition::FromCode(' $(document).ready(function() { let testNode = document.getElementById("jQuery-test"); if ($ != undefined) { testNode.innerHTML = "<b>Test passed!</b>"; } else { testNode.innerHTML = "<b>Test not passed</b>"; } $("#javaScript-test").html("<b>Test passed!</b>"); });'); echo $jQuery->Draw(); echo $bootstrapScript->Draw(); echo $testScript->Draw(); echo ' <h2>Including scripts (jQuery, Bootstrap) using <code>ScriptFile</code></h2> <p id="jQuery-test"><b>Test not passed</b></p> <h2>Running JavaScript using <code>InlineScript</code></h2> <p id="javaScript-test"><b>Test not passed</b></p>'; } ?>
manuth/TemPHPlate
UnitTests/JavaScript.php
PHP
apache-2.0
1,300
/******************************************************************************* * * Struts2-JSR303-beanValidation-Plugin - An Open Source Struts2 Plugin to hook Bean Validator. * ================================================================================================================= * * Copyright (C) 2013 by Umesh Awasthi * https://github.com/umeshawasthi/jsr303-validator-plugin * * ********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * **********************************************************************************************************************/ package com.github.umeshawasthi.struts2.jsr303.validation.interceptor; import javax.validation.Validator; /** *Validation manager which is responsible for providing instance of {@link Validator} based on the underlying validation provider. *For any JSR303 complaint implementation,{@link Validator} should be implemented in thread safe way. * * @author Umesh Awasthi */ public interface JSR303ValidationManager { public Validator getValidator(); }
apexcapital/jsr303-validator-plugin
src/main/java/com/github/umeshawasthi/struts2/jsr303/validation/interceptor/JSR303ValidationManager.java
Java
apache-2.0
1,672
package chanedi.util; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * 该Properties能记录条目的先后顺序,见{@link PropertiesWithOrder#keysInOrder()} * @author Chanedi */ public class PropertiesWithOrder extends Properties { private List<Object> keyList = new ArrayList<Object>(); @Override public synchronized Object put(Object key, Object value) { if (!keyList.contains(key)) { keyList.add(key); } return super.put(key, value); } /** * 返回key值,该key值顺序与文件中的顺序相同。 * @return */ public List<Object> keysInOrder() { return keyList; } }
chanedi/QuickProject
QuickProject-Util/src/main/java/chanedi/util/PropertiesWithOrder.java
Java
apache-2.0
713
/** * Copyright © 2013 Erwin Müller (erwin.mueller@anrisoftware.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.anrisoftware.globalpom.data.csvimport; /*- * #%L * Global POM Utilities :: Data * %% * Copyright (C) 2013 - 2018 Advanced Natural Research 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. * #L% */ import java.io.IOException; @SuppressWarnings("serial") public class ReadValuesException extends CsvImportException { public ReadValuesException(CsvImporterImpl importer, IOException e) { super("Error reading value", e); addContextValue("importer", importer); } }
devent/globalpom-utils
globalpomutils-data/src/main/java/com/anrisoftware/globalpom/data/csvimport/ReadValuesException.java
Java
apache-2.0
1,667
/* * 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.camel.runtimecatalog.impl; import java.util.HashMap; import java.util.Map; import org.apache.camel.impl.DefaultCamelContext; import org.apache.camel.runtimecatalog.EndpointValidationResult; import org.apache.camel.runtimecatalog.LanguageValidationResult; import org.apache.camel.runtimecatalog.RuntimeCamelCatalog; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class RuntimeCamelCatalogTest { static RuntimeCamelCatalog catalog; private static final Logger LOG = LoggerFactory.getLogger(RuntimeCamelCatalogTest.class); @BeforeClass public static void createCamelCatalog() { catalog = new DefaultRuntimeCamelCatalog(new DefaultCamelContext()); } @Test public void testFromCamelContext() throws Exception { String schema = new DefaultCamelContext().getExtension(RuntimeCamelCatalog.class).modelJSonSchema("choice"); assertNotNull(schema); } @Test public void testJsonSchema() throws Exception { String schema = catalog.modelJSonSchema("aggregate"); assertNotNull(schema); // lets make it possible to find bean/method using both names schema = catalog.modelJSonSchema("method"); assertNotNull(schema); schema = catalog.modelJSonSchema("bean"); assertNotNull(schema); } @Test public void testAsEndpointUriMapFile() throws Exception { Map<String, String> map = new HashMap<>(); map.put("directoryName", "src/data/inbox"); map.put("noop", "true"); map.put("delay", "5000"); String uri = catalog.asEndpointUri("file", map, true); assertEquals("file:src/data/inbox?delay=5000&noop=true", uri); String uri2 = catalog.asEndpointUriXml("file", map, true); assertEquals("file:src/data/inbox?delay=5000&amp;noop=true", uri2); } @Test public void testAsEndpointUriTimer() throws Exception { Map<String, String> map = new HashMap<>(); map.put("timerName", "foo"); map.put("period", "5000"); String uri = catalog.asEndpointUri("timer", map, true); assertEquals("timer:foo?period=5000", uri); } @Test public void testAsEndpointUriPropertiesPlaceholders() throws Exception { Map<String, String> map = new HashMap<>(); map.put("timerName", "foo"); map.put("period", "{{howoften}}"); map.put("repeatCount", "5"); String uri = catalog.asEndpointUri("timer", map, true); assertEquals("timer:foo?period=%7B%7Bhowoften%7D%7D&repeatCount=5", uri); uri = catalog.asEndpointUri("timer", map, false); assertEquals("timer:foo?period={{howoften}}&repeatCount=5", uri); } @Test public void testAsEndpointUriBeanLookup() throws Exception { Map<String, String> map = new HashMap<>(); map.put("resourceUri", "foo.xslt"); map.put("converter", "#myConverter"); String uri = catalog.asEndpointUri("xslt", map, true); assertEquals("xslt:foo.xslt?converter=%23myConverter", uri); uri = catalog.asEndpointUri("xslt", map, false); assertEquals("xslt:foo.xslt?converter=#myConverter", uri); } @Test public void testEndpointPropertiesPlaceholders() throws Exception { Map<String, String> map = catalog.endpointProperties("timer:foo?period={{howoften}}&repeatCount=5"); assertNotNull(map); assertEquals(3, map.size()); assertEquals("foo", map.get("timerName")); assertEquals("{{howoften}}", map.get("period")); assertEquals("5", map.get("repeatCount")); } @Test public void testAsEndpointUriLog() throws Exception { Map<String, String> map = new HashMap<>(); map.put("loggerName", "foo"); map.put("loggerLevel", "WARN"); map.put("multiline", "true"); map.put("showAll", "true"); map.put("showBody", "false"); map.put("showBodyType", "false"); map.put("showExchangePattern", "false"); map.put("style", "Tab"); assertEquals("log:foo?loggerLevel=WARN&multiline=true&showAll=true&style=Tab", catalog.asEndpointUri("log", map, false)); } @Test public void testAsEndpointUriLogShort() throws Exception { Map<String, String> map = new HashMap<>(); map.put("loggerName", "foo"); map.put("loggerLevel", "DEBUG"); assertEquals("log:foo?loggerLevel=DEBUG", catalog.asEndpointUri("log", map, false)); } @Test public void testAsEndpointUriWithplaceholder() throws Exception { Map<String, String> map = new HashMap<>(); map.put("name", "foo"); map.put("blockWhenFull", "{{block}}"); assertEquals("seda:foo?blockWhenFull={{block}}", catalog.asEndpointUri("seda", map, false)); } @Test public void testEndpointPropertiesSedaRequired() throws Exception { Map<String, String> map = catalog.endpointProperties("seda:foo"); assertNotNull(map); assertEquals(1, map.size()); assertEquals("foo", map.get("name")); map = catalog.endpointProperties("seda:foo?blockWhenFull=true"); assertNotNull(map); assertEquals(2, map.size()); assertEquals("foo", map.get("name")); assertEquals("true", map.get("blockWhenFull")); } @Test public void validateProperties() throws Exception { // valid EndpointValidationResult result = catalog.validateEndpointProperties("log:mylog"); assertTrue(result.isSuccess()); // unknown result = catalog.validateEndpointProperties("log:mylog?level=WARN&foo=bar"); assertFalse(result.isSuccess()); assertTrue(result.getUnknown().contains("foo")); assertEquals(1, result.getNumberOfErrors()); // enum result = catalog.validateEndpointProperties("seda:foo?waitForTaskToComplete=blah"); assertFalse(result.isSuccess()); assertEquals("blah", result.getInvalidEnum().get("waitForTaskToComplete")); assertEquals(1, result.getNumberOfErrors()); // reference okay result = catalog.validateEndpointProperties("seda:foo?queue=#queue"); assertTrue(result.isSuccess()); assertEquals(0, result.getNumberOfErrors()); // unknown component result = catalog.validateEndpointProperties("foo:bar?me=you"); assertTrue(result.isSuccess()); assertTrue(result.hasWarnings()); assertTrue(result.getUnknownComponent().equals("foo")); assertEquals(0, result.getNumberOfErrors()); assertEquals(1, result.getNumberOfWarnings()); // invalid boolean but default value result = catalog.validateEndpointProperties("log:output?showAll=ggg"); assertFalse(result.isSuccess()); assertEquals("ggg", result.getInvalidBoolean().get("showAll")); assertEquals(1, result.getNumberOfErrors()); // time pattern result = catalog.validateEndpointProperties("timer://foo?fixedRate=true&delay=0&period=2s"); assertTrue(result.isSuccess()); // reference lookup result = catalog.validateEndpointProperties("timer://foo?fixedRate=#fixed&delay=#myDelay"); assertTrue(result.isSuccess()); // optional without consumer. prefix result = catalog.validateEndpointProperties("file:inbox?delay=5000&greedy=true"); assertTrue(result.isSuccess()); // prefix result = catalog.validateEndpointProperties("file:inbox?delay=5000&scheduler.foo=123&scheduler.bar=456"); assertTrue(result.isSuccess()); // stub result = catalog.validateEndpointProperties("stub:foo?me=123&you=456"); assertTrue(result.isSuccess()); // incapable to parse result = catalog.validateEndpointProperties("{{getFtpUrl}}?recursive=true"); assertTrue(result.isSuccess()); assertTrue(result.hasWarnings()); assertTrue(result.getIncapable() != null); } @Test public void validatePropertiesSummaryUnknown() throws Exception { // unknown component yammer EndpointValidationResult result = catalog .validateEndpointProperties("yammer:MESSAGES?blah=yada&accessToken=aaa&consumerKey=&useJson=no&initialDelay=five&pollStrategy=myStrategy"); assertTrue(result.isSuccess()); assertTrue(result.hasWarnings()); String reason = result.summaryErrorMessage(true, true, true); LOG.info(reason); // unknown component jms result = catalog.validateEndpointProperties("jms:unknown:myqueue"); assertTrue(result.isSuccess()); assertTrue(result.hasWarnings()); reason = result.summaryErrorMessage(false, false, true); LOG.info(reason); } @Test public void validateTimePattern() throws Exception { assertTrue(catalog.validateTimePattern("0")); assertTrue(catalog.validateTimePattern("500")); assertTrue(catalog.validateTimePattern("10000")); assertTrue(catalog.validateTimePattern("5s")); assertTrue(catalog.validateTimePattern("5sec")); assertTrue(catalog.validateTimePattern("5secs")); assertTrue(catalog.validateTimePattern("3m")); assertTrue(catalog.validateTimePattern("3min")); assertTrue(catalog.validateTimePattern("3minutes")); assertTrue(catalog.validateTimePattern("5m15s")); assertTrue(catalog.validateTimePattern("1h")); assertTrue(catalog.validateTimePattern("1hour")); assertTrue(catalog.validateTimePattern("2hours")); assertFalse(catalog.validateTimePattern("bla")); assertFalse(catalog.validateTimePattern("2year")); assertFalse(catalog.validateTimePattern("60darn")); } @Test public void testEndpointComponentName() throws Exception { String name = catalog.endpointComponentName("jms:queue:foo"); assertEquals("jms", name); } @Test public void testSimpleExpression() throws Exception { LanguageValidationResult result = catalog.validateLanguageExpression(null, "simple", "${body}"); assertTrue(result.isSuccess()); assertEquals("${body}", result.getText()); result = catalog.validateLanguageExpression(null, "simple", "${body"); assertFalse(result.isSuccess()); assertEquals("${body", result.getText()); LOG.info(result.getError()); assertTrue(result.getError().startsWith("expected symbol functionEnd but was eol at location 5")); assertEquals("expected symbol functionEnd but was eol", result.getShortError()); assertEquals(5, result.getIndex()); } @Test public void testSimplePredicate() throws Exception { LanguageValidationResult result = catalog.validateLanguagePredicate(null, "simple", "${body} == 'abc'"); assertTrue(result.isSuccess()); assertEquals("${body} == 'abc'", result.getText()); result = catalog.validateLanguagePredicate(null, "simple", "${body} > ${header.size"); assertFalse(result.isSuccess()); assertEquals("${body} > ${header.size", result.getText()); LOG.info(result.getError()); assertTrue(result.getError().startsWith("expected symbol functionEnd but was eol at location 22")); assertEquals("expected symbol functionEnd but was eol", result.getShortError()); assertEquals(22, result.getIndex()); } @Test public void testSimplePredicatePlaceholder() throws Exception { LanguageValidationResult result = catalog.validateLanguagePredicate(null, "simple", "${body} contains '{{danger}}'"); assertTrue(result.isSuccess()); assertEquals("${body} contains '{{danger}}'", result.getText()); result = catalog.validateLanguagePredicate(null, "simple", "${bdy} contains '{{danger}}'"); assertFalse(result.isSuccess()); assertEquals("${bdy} contains '{{danger}}'", result.getText()); LOG.info(result.getError()); assertTrue(result.getError().startsWith("Unknown function: bdy at location 0")); assertTrue(result.getError().contains("'{{danger}}'")); assertEquals("Unknown function: bdy", result.getShortError()); assertEquals(0, result.getIndex()); } @Test public void testValidateLanguage() throws Exception { LanguageValidationResult result = catalog.validateLanguageExpression(null, "simple", "${body}"); assertTrue(result.isSuccess()); assertEquals("${body}", result.getText()); result = catalog.validateLanguageExpression(null, "header", "foo"); assertTrue(result.isSuccess()); assertEquals("foo", result.getText()); result = catalog.validateLanguagePredicate(null, "simple", "${body} > 10"); assertTrue(result.isSuccess()); assertEquals("${body} > 10", result.getText()); result = catalog.validateLanguagePredicate(null, "header", "bar"); assertTrue(result.isSuccess()); assertEquals("bar", result.getText()); result = catalog.validateLanguagePredicate(null, "foobar", "bar"); assertFalse(result.isSuccess()); assertEquals("Unknown language foobar", result.getError()); } @Test public void testValidateEndpointConsumerOnly() throws Exception { String uri = "file:inbox?bufferSize=4096&readLock=changed&delete=true"; EndpointValidationResult result = catalog.validateEndpointProperties(uri, false, true, false); assertTrue(result.isSuccess()); uri = "file:inbox?bufferSize=4096&readLock=changed&delete=true&fileExist=Append"; result = catalog.validateEndpointProperties(uri, false, true, false); assertFalse(result.isSuccess()); assertEquals("fileExist", result.getNotConsumerOnly().iterator().next()); } @Test public void testValidateEndpointProducerOnly() throws Exception { String uri = "file:outbox?bufferSize=4096&fileExist=Append"; EndpointValidationResult result = catalog.validateEndpointProperties(uri, false, false, true); assertTrue(result.isSuccess()); uri = "file:outbox?bufferSize=4096&fileExist=Append&delete=true"; result = catalog.validateEndpointProperties(uri, false, false, true); assertFalse(result.isSuccess()); assertEquals("delete", result.getNotProducerOnly().iterator().next()); } }
objectiser/camel
core/camel-core/src/test/java/org/apache/camel/runtimecatalog/impl/RuntimeCamelCatalogTest.java
Java
apache-2.0
15,488
/* * 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 com.mycompany.rbossf.dao; /** * * @author ib */ import com.mycompany.rbossf.entity.OrderLineItem; import org.springframework.data.jpa.repository.JpaRepository; public interface OrderLineItemRepository extends JpaRepository<OrderLineItem, Long>{ }
bidurbs/pm-rboss
src/main/java/com/mycompany/rbossf/dao/OrderLineItemRepository.java
Java
apache-2.0
450
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v10/enums/user_identifier_source.proto package com.google.ads.googleads.v10.enums; public final class UserIdentifierSourceProto { private UserIdentifierSourceProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_enums_UserIdentifierSourceEnum_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_enums_UserIdentifierSourceEnum_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n;google/ads/googleads/v10/enums/user_id" + "entifier_source.proto\022\036google.ads.google" + "ads.v10.enums\032\034google/api/annotations.pr" + "oto\"r\n\030UserIdentifierSourceEnum\"V\n\024UserI" + "dentifierSource\022\017\n\013UNSPECIFIED\020\000\022\013\n\007UNKN" + "OWN\020\001\022\017\n\013FIRST_PARTY\020\002\022\017\n\013THIRD_PARTY\020\003B" + "\363\001\n\"com.google.ads.googleads.v10.enumsB\031" + "UserIdentifierSourceProtoP\001ZCgoogle.gola" + "ng.org/genproto/googleapis/ads/googleads" + "/v10/enums;enums\242\002\003GAA\252\002\036Google.Ads.Goog" + "leAds.V10.Enums\312\002\036Google\\Ads\\GoogleAds\\V" + "10\\Enums\352\002\"Google::Ads::GoogleAds::V10::" + "Enumsb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.api.AnnotationsProto.getDescriptor(), }); internal_static_google_ads_googleads_v10_enums_UserIdentifierSourceEnum_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_ads_googleads_v10_enums_UserIdentifierSourceEnum_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_enums_UserIdentifierSourceEnum_descriptor, new java.lang.String[] { }); com.google.api.AnnotationsProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
googleads/google-ads-java
google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/enums/UserIdentifierSourceProto.java
Java
apache-2.0
2,717
package com.qihua.console.security; /** * 服务器等待请求超时。 * * @author zhen.ni@ebaotech.com * @since 2013-10-11 * @version 1.0 * @see */ public class HttpRequest408Exception extends Exception { private static final long serialVersionUID = 1L; }
nickevin/Qihua
src/main/java/com/qihua/console/security/HttpRequest408Exception.java
Java
apache-2.0
279
// Copyright 2019, University of Freiburg, // Chair of Algorithms and Data Structures. // Author: Johannes Kalmbach(joka921) <johannes.kalmbach@gmail.com> // // Only performs the "mergeVocabulary" step of the IndexBuilder pipeline // Can be used e.g. for benchmarking this step to develop faster IndexBuilders. #include "index/Vocabulary.h" #include "index/VocabularyGenerator.h" // ____________________________________________________________________________________________________ int main(int argc, char** argv) { if (argc != 3) { std::cerr << "Usage: " << argv[0] << "<basename of index> <number of partial vocabulary files to merge>"; } std::string basename = argv[1]; size_t numFiles = atoi(argv[2]); VocabularyMerger m; m.mergeVocabulary(basename, numFiles, StringSortComparator()); }
Buchhold/QLever
src/VocabularyMergerMain.cpp
C++
apache-2.0
828
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ import { combineReducers } from 'redux'; import { INIT_PAYMENT_METHODS, ADD_PAYMENT_METHOD, EDIT_SUPPORTED_METHODS, EDIT_PAYMENT_METHOD_DATA, REMOVE_PAYMENT_METHOD, INIT_TOTAL, EDIT_TOTAL_LABEL, EDIT_TOTAL_VALUE, EDIT_TOTAL_CURRENCY, INIT_DISPLAY_ITEMS, ADD_DISPLAY_ITEM, EDIT_DISPLAY_ITEM_LABEL, EDIT_DISPLAY_ITEM_VALUE, EDIT_DISPLAY_ITEM_CURRENCY, REMOVE_DISPLAY_ITEM, INIT_OPTIONS, EDIT_OPTIONS_NAME, EDIT_OPTIONS_PHONE, EDIT_OPTIONS_EMAIL, EDIT_OPTIONS_BILLING, EDIT_OPTIONS_SHIPPING, EDIT_OPTIONS_SHIPPING_TYPE, REMOVE_OPTIONS_SHIPPING_TYPE, INIT_SHIPPING_OPTIONS, ADD_SHIPPING_OPTION, EDIT_SHIPPING_OPTION_ID, EDIT_SHIPPING_OPTION_LABEL, EDIT_SHIPPING_OPTION_VALUE, EDIT_SHIPPING_OPTION_CURRENCY, EDIT_SHIPPING_OPTION_SELECTED, REMOVE_SHIPPING_OPTION, SHOW_RESULT } from './actions.js'; /* Example data structure: { paymentMethods: [...], details: { displayItems: [...], total: {...}, shippingOptions: [...] }, options: {...}, } */ const request = (state = [], action) => { let { paymentMethods = [], details = {}, options = {} } = state; let { displayItems = [], total = {}, shippingOptions = [] } = details; switch (action.type) { case INIT_PAYMENT_METHODS: paymentMethods = [{ supportedMethods: "https://google.com/pay", data: `{ "environment": "TEST", "apiVersion": 2, "apiVersionMinor": 0, "merchantInfo": { "merchantName": "Merchant Demo" }, "allowedPaymentMethods": [{ "type": "CARD", "parameters": { "allowedAuthMethods": ["PAN_ONLY", "CRYPTOGRAM_3DS"], "allowedCardNetworks": ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"] }, "tokenizationSpecification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway":"stripe", "stripe:publishableKey":"pk_test_fkdoiK6FR5BLZMFNbSGoDjpn", "stripe:version":"2018-10-31" } } }] }` }, { supportedMethods: 'https://bobbucks.dev/pay', data: '{}' }]; return { ...state, paymentMethods } case ADD_PAYMENT_METHOD: paymentMethods = [...paymentMethods, { supportedMethods: '', data: '' }]; return { ...state, paymentMethods }; case EDIT_SUPPORTED_METHODS: paymentMethods = paymentMethods.map((paymentMethod, index) => { if (index === action.index) { return {...paymentMethod, supportedMethods: action.supportedMethods } } return paymentMethod; }); return { ...state, paymentMethods }; case EDIT_PAYMENT_METHOD_DATA: paymentMethods = paymentMethods.map((paymentMethod, index) => { if (index === action.index) { return {...paymentMethod, data: action.data } } return paymentMethod; }); return { ...state, paymentMethods }; case REMOVE_PAYMENT_METHOD: paymentMethods = paymentMethods.filter((_, index) => index !== action.index); return { ...state, paymentMethods }; case INIT_DISPLAY_ITEMS: displayItems = [{ label: 'Original Donation Amount', amount: { value: '10.00', currency: 'USD' } }]; return { ...state, details: { displayItems, total, shippingOptions }}; case ADD_DISPLAY_ITEM: displayItems = [ ...displayItems, { label: '', amount: { value: '', currency: '' } } ]; return { ...state, details: { displayItems, total, shippingOptions }}; case EDIT_DISPLAY_ITEM_LABEL: displayItems = displayItems.map((displayItem, index) => { if (index === action.index) { return { label: action.label, amount: { value: displayItem.amount.value, currency: displayItem.amount.currency } } } return displayItem; }); return { ...state, details: { displayItems, total, shippingOptions }}; case EDIT_DISPLAY_ITEM_VALUE: displayItems = displayItems.map((displayItem, index) => { if (index === action.index) { return { label: displayItem.label, amount: { value: action.value, currency: displayItem.amount.currency } } } return displayItem; }); return { ...state, details: { displayItems, total, shippingOptions }}; case EDIT_DISPLAY_ITEM_CURRENCY: displayItems = displayItems.map((displayItem, index) => { if (index === action.index) { return { label: displayItem.label, amount: { value: displayItem.amount.value, currency: action.currency } } } return displayItem; }); return { ...state, details: { displayItems, total, shippingOptions }}; case REMOVE_DISPLAY_ITEM: displayItems = displayItems.filter((_, index) => index !== action.index); return { ...state, details: { displayItems, total, shippingOptions }}; case INIT_TOTAL: total = { label: 'Total', amount: { value: '10.00', currency: 'USD' } } return { ...state, details: { displayItems, total, shippingOptions }}; case EDIT_TOTAL_LABEL: total = { label: action.total, amount: { value: total.amount.value, currency: total.amount.currency } }; return { ...state, details: { displayItems, total, shippingOptions }}; case EDIT_TOTAL_VALUE: total = { label: total.label, amount: { value: action.value, currency: total.amount.currency } }; return { ...state, details: { displayItems, total, shippingOptions }}; case EDIT_TOTAL_CURRENCY: total = { label: total.label, amount: { value: total.amount.value, currency: action.currency } }; return { ...state, details: { displayItems, total, shippingOptions }}; case INIT_SHIPPING_OPTIONS: shippingOptions = [{ id: 'standard', label: 'Standard', amount: { value: '0.00', currency: 'USD' }, selected: true }, { id: 'express', label: 'Express', amount: { value: '5.00', currency: 'USD' } }, { id: 'international', label: 'International', amount: { value: '10.00', currency: 'USD' } }] return { ...state, details: { displayItems, total, shippingOptions }}; case ADD_SHIPPING_OPTION: shippingOptions = [ ...shippingOptions, { id: '', label: '', amount: { value: '', currency: '' }, selected: false } ]; return { ...state, details: { displayItems, total, shippingOptions }}; case EDIT_SHIPPING_OPTION_ID: shippingOptions = shippingOptions.map((shippingOption, index) => { if (index === action.index) { return { ...shippingOption, id: action.id } } return shippingOption; }); return { ...state, details: { displayItems, total, shippingOptions }}; case EDIT_SHIPPING_OPTION_LABEL: shippingOptions = shippingOptions.map((shippingOption, index) => { if (index === action.index) { return { ...shippingOption, label: action.label } } return shippingOption; }); return { ...state, details: { displayItems, total, shippingOptions }}; case EDIT_SHIPPING_OPTION_VALUE: shippingOptions = shippingOptions.map((shippingOption, index) => { if (index === action.index) { return { ...shippingOption, amount: { value: action.value, currency: shippingOption.amount.currency } } } return shippingOption; }); return { ...state, details: { displayItems, total, shippingOptions }}; case EDIT_SHIPPING_OPTION_CURRENCY: shippingOptions = shippingOptions.map((shippingOption, index) => { if (index === action.index) { return { ...shippingOption, amount: { value: shippingOption.amount.value, currency: action.currency } } } return shippingOption; }); return { ...state, details: { displayItems, total, shippingOptions }}; case EDIT_SHIPPING_OPTION_SELECTED: shippingOptions = shippingOptions.map((shippingOption, index) => { if (index === action.index) { return { ...shippingOption, selected: action.selected } } return shippingOption; }); return { ...state, details: { displayItems, total, shippingOptions }}; case REMOVE_SHIPPING_OPTION: shippingOptions = shippingOptions.filter((_, index) => index !== action.index); return { ...state, details: { displayItems, total, shippingOptions }}; case INIT_OPTIONS: options = { requestPayerName: false, requestPayerPhone: false, requestPayerEmail: false, requestPayerBillingAddress: false, requestShipping: false } return { ...state, options }; case EDIT_OPTIONS_NAME: options = { ...options, requestPayerName: action.checked } return { ...state, options }; case EDIT_OPTIONS_PHONE: options = { ...options, requestPayerPhone: action.checked } return { ...state, options }; case EDIT_OPTIONS_EMAIL: options = { ...options, requestPayerEmail: action.checked } return { ...state, options }; case EDIT_OPTIONS_BILLING: options = { ...options, requestPayerBillingAddress: action.checked } return { ...state, options }; case EDIT_OPTIONS_SHIPPING: options = { ...options, requestShipping: action.checked } return { ...state, options }; case EDIT_OPTIONS_SHIPPING_TYPE: options = { ...options, shippingType: action.shippingType } return { ...state, options }; case REMOVE_OPTIONS_SHIPPING_TYPE: delete options.shippingType; return { ...state, options }; default: return state; } } const result = (state = [], action) => { switch (action.type) { case SHOW_RESULT: return action.result; default: return state; } } export const PaymentRequestApp = combineReducers({ request, result });
GoogleChromeLabs/paymentrequest-show
src/store/reducers.js
JavaScript
apache-2.0
11,202
package com.mkyong.customer.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import com.db.MySQLAccess; import com.model.MonthlyReport; import com.model.User; import com.utils.KeyMaker; public class MyNewMonthlyReportController extends SimpleFormController { public MyNewMonthlyReportController() { setCommandClass(MonthlyReport.class); setCommandName("monthlyReport"); } @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { MonthlyReport monthlyReport = (MonthlyReport) command; monthlyReport.uid = KeyMaker.newKey(); monthlyReport.yearMonth=monthlyReport.year+"/"+monthlyReport.month; // System.out.println("MyNewMonthlyReportController nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn"); MySQLAccess o = new MySQLAccess(); try { o.insertMonthlyReport(monthlyReport); //!!!!!-------------------------------------- } catch (Exception e) { e.printStackTrace(); } // return new ModelAndView(new RedirectView("compList.htm")); return new ModelAndView(getSuccessView(), "monthlyReport", monthlyReport); } @Override protected Object formBackingObject(HttpServletRequest request) throws Exception { HttpSession session = request.getSession(false); User user = (User) session.getAttribute("user"); MonthlyReport monthlyReport = new MonthlyReport(); // monthlyReport.compName=user.userComp; // monthlyReport.compId=user.compid; return monthlyReport; } @Override protected Map referenceData(HttpServletRequest request) throws Exception { Map referenceData = new HashMap(); referenceData.put("years", SelectYearMonth.getYears()); referenceData.put("months", SelectYearMonth.getMonths()); return referenceData; } }
mingxin6/incu
inc2_tw2/src/com/mkyong/customer/controller/MyNewMonthlyReportController.java
Java
apache-2.0
2,166
package com.google.sps.taskqueue.push; import com.google.appengine.api.blobstore.BlobKey; import com.google.appengine.api.blobstore.BlobstoreService; import com.google.appengine.api.blobstore.BlobstoreServiceFactory; import com.google.sps.tool.ResponseSerializer; import com.google.appengine.api.blobstore.BlobstoreFailureException; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/blobstoreKeyDeletionWorker") public class BlobstoreKeyDeletionWorker extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String key = request.getParameter("key"); String accessCode = request.getParameter("accessCode"); // Ensure that arbitrary user does not have access to this servlet if (accessCode == "s197") { ResponseSerializer.sendErrorJson( response, "You do not have access to deleting the blobs directly"); return; } BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); BlobKey blobKey = new BlobKey(key); try { /* Blobstore does not have a transaction as a part of its API. * We will just catch an error and signal the Queue Service to retry the task. * Response code 200 signals the queue service that our worker succeeded. */ blobstoreService.delete(blobKey); response.sendError(200); } catch (BlobstoreFailureException e) { /* When the response returns an HTTP status code outside the range 200–299 * the Queue Service retries the task until it succeeds. */ response.sendError(500); } } }
googleinterns/step197-2020
src/main/java/com/google/sps/taskqueue/push/BlobstoreKeyDeletionWorker.java
Java
apache-2.0
1,842
<?php /** * [yushunbox System] Copyright (c) 2014 yushunbox.com * yushunbox is NOT a free software, it under the license terms, visited http://www.yushunbox.com/ for more details. */ !defined('IN_UC') && exit('Access Denied'); define('UC_USER_CHECK_USERNAME_FAILED', -1); define('UC_USER_USERNAME_BADWORD', -2); define('UC_USER_USERNAME_EXISTS', -3); define('UC_USER_EMAIL_FORMAT_ILLEGAL', -4); define('UC_USER_EMAIL_ACCESS_ILLEGAL', -5); define('UC_USER_EMAIL_EXISTS', -6); class usercontrol extends base { function __construct() { $this->usercontrol(); } function usercontrol() { parent::__construct(); $this->load('user'); $this->app = $this->cache['apps'][UC_APPID]; } // -1 未开启 function onsynlogin() { $this->init_input(); $uid = $this->input('uid'); if($this->app['synlogin']) { if($this->user = $_ENV['user']->get_user_by_uid($uid)) { $synstr = ''; foreach($this->cache['apps'] as $appid => $app) { if($app['synlogin'] && $app['appid'] != $this->app['appid']) { $synstr .= '<script type="text/javascript" src="'.$app['url'].'/api/uc.php?time='.$this->time.'&code='.urlencode($this->authcode('action=synlogin&username='.$this->user['username'].'&uid='.$this->user['uid'].'&password='.$this->user['password']."&time=".$this->time, 'ENCODE', $app['authkey'])).'"></script>'; } } return $synstr; } } return ''; } function onsynlogout() { $this->init_input(); if($this->app['synlogin']) { $synstr = ''; foreach($this->cache['apps'] as $appid => $app) { if($app['synlogin'] && $app['appid'] != $this->app['appid']) { $synstr .= '<script type="text/javascript" src="'.$app['url'].'/api/uc.php?time='.$this->time.'&code='.urlencode($this->authcode('action=synlogout&time='.$this->time, 'ENCODE', $app['authkey'])).'"></script>'; } } return $synstr; } return ''; } function onregister() { $this->init_input(); $username = $this->input('username'); $password = $this->input('password'); $email = $this->input('email'); $questionid = $this->input('questionid'); $answer = $this->input('answer'); $regip = $this->input('regip'); if(($status = $this->_check_username($username)) < 0) { return $status; } if(($status = $this->_check_email($email)) < 0) { return $status; } $uid = $_ENV['user']->add_user($username, $password, $email, 0, $questionid, $answer, $regip); return $uid; } function onedit() { $this->init_input(); $username = $this->input('username'); $oldpw = $this->input('oldpw'); $newpw = $this->input('newpw'); $email = $this->input('email'); $ignoreoldpw = $this->input('ignoreoldpw'); $questionid = $this->input('questionid'); $answer = $this->input('answer'); if(!$ignoreoldpw && $email && ($status = $this->_check_email($email, $username)) < 0) { return $status; } $status = $_ENV['user']->edit_user($username, $oldpw, $newpw, $email, $ignoreoldpw, $questionid, $answer); if($newpw && $status > 0) { $this->load('note'); $_ENV['note']->add('updatepw', 'username='.urlencode($username).'&password='); $_ENV['note']->send(); } return $status; } function onlogin() { $this->init_input(); $isuid = $this->input('isuid'); $username = $this->input('username'); $password = $this->input('password'); $checkques = $this->input('checkques'); $questionid = $this->input('questionid'); $answer = $this->input('answer'); if($isuid == 1) { $user = $_ENV['user']->get_user_by_uid($username); } elseif($isuid == 2) { $user = $_ENV['user']->get_user_by_email($username); } else { $user = $_ENV['user']->get_user_by_username($username); } $passwordmd5 = preg_match('/^\w{32}$/', $password) ? $password : md5($password); if(empty($user)) { $status = -1; } elseif($user['password'] != md5($passwordmd5.$user['salt'])) { $status = -2; } elseif($checkques && $user['secques'] != '' && $user['secques'] != $_ENV['user']->quescrypt($questionid, $answer)) { $status = -3; } else { $status = $user['uid']; } $merge = $status != -1 && !$isuid && $_ENV['user']->check_mergeuser($username) ? 1 : 0; return array($status, $user['username'], $password, $user['email'], $merge); } function oncheck_email() { $this->init_input(); $email = $this->input('email'); return $this->_check_email($email); } function oncheck_username() { $this->init_input(); $username = $this->input('username'); if(($status = $this->_check_username($username)) < 0) { return $status; } else { return 1; } } function onget_user() { $this->init_input(); $username = $this->input('username'); if(!$this->input('isuid')) { $status = $_ENV['user']->get_user_by_username($username); } else { $status = $_ENV['user']->get_user_by_uid($username); } if($status) { return array($status['uid'],$status['username'],$status['email']); } else { return 0; } } function ongetprotected() { $protectedmembers = $this->db->fetch_all("SELECT uid,username FROM ".UC_DBTABLEPRE."protectedmembers GROUP BY username"); return $protectedmembers; } function ondelete() { $this->init_input(); $uid = $this->input('uid'); return $_ENV['user']->delete_user($uid); } function onaddprotected() { $this->init_input(); $username = $this->input('username'); $admin = $this->input('admin'); $appid = $this->app['appid']; $usernames = (array)$username; foreach($usernames as $username) { $user = $_ENV['user']->get_user_by_username($username); $uid = $user['uid']; $this->db->query("REPLACE INTO ".UC_DBTABLEPRE."protectedmembers SET uid='$uid', username='$username', appid='$appid', dateline='{$this->time}', admin='$admin'", 'SILENT'); } return $this->db->errno() ? -1 : 1; } function ondeleteprotected() { $this->init_input(); $username = $this->input('username'); $appid = $this->app['appid']; $usernames = (array)$username; foreach($usernames as $username) { $this->db->query("DELETE FROM ".UC_DBTABLEPRE."protectedmembers WHERE username='$username' AND appid='$appid'"); } return $this->db->errno() ? -1 : 1; } function onmerge() { $this->init_input(); $oldusername = $this->input('oldusername'); $newusername = $this->input('newusername'); $uid = $this->input('uid'); $password = $this->input('password'); $email = $this->input('email'); if(($status = $this->_check_username($newusername)) < 0) { return $status; } $uid = $_ENV['user']->add_user($newusername, $password, $email, $uid); $this->db->query("DELETE FROM ".UC_DBTABLEPRE."mergemembers WHERE appid='".$this->app['appid']."' AND username='$oldusername'"); return $uid; } function onmerge_remove() { $this->init_input(); $username = $this->input('username'); $this->db->query("DELETE FROM ".UC_DBTABLEPRE."mergemembers WHERE appid='".$this->app['appid']."' AND username='$username'"); return NULL; } function _check_username($username) { $username = addslashes(trim(stripslashes($username))); if(!$_ENV['user']->check_username($username)) { return UC_USER_CHECK_USERNAME_FAILED; } elseif(!$_ENV['user']->check_usernamecensor($username)) { return UC_USER_USERNAME_BADWORD; } elseif($_ENV['user']->check_usernameexists($username)) { return UC_USER_USERNAME_EXISTS; } return 1; } function _check_email($email, $username = '') { if(empty($this->settings)) { $this->settings = $this->cache('settings'); } if(!$_ENV['user']->check_emailformat($email)) { return UC_USER_EMAIL_FORMAT_ILLEGAL; } elseif(!$_ENV['user']->check_emailaccess($email)) { return UC_USER_EMAIL_ACCESS_ILLEGAL; } elseif(!$this->settings['doublee'] && $_ENV['user']->check_emailexists($email, $username)) { return UC_USER_EMAIL_EXISTS; } else { return 1; } } function onuploadavatar() { } function onrectavatar() { } function flashdata_decode($s) { } } ?>
shengkai86/yushungroup
framework/library/uc/control/user.php
PHP
apache-2.0
8,671
const pkg = require("/package.json").peabodyos; const util = require("util"); if(pkg.installer) { console.log("[PeabodyOS] Please Wait while the installer starts..."); require("./installer"); } else { console.log("[PeabodyOS] Please Wait while the server is booting..."); //process.termout.write(util.format(runtime.pci.deviceList)+"\n"); }
SpaceboyRoss01/PeabodyOS
src/system/sys/distro/server/index.js
JavaScript
apache-2.0
357
RailsProject::Application.configure do # Settings specified here will take precedence over those in config/application.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Configure static asset server for tests with Cache-Control for performance config.serve_static_assets = true config.static_cache_control = "public, max-age=3600" # Log error messages when you accidentally call methods on nil config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Raise exception on mass assignment protection for Active Record models config.active_record.mass_assignment_sanitizer = :strict # Print deprecation notices to the stderr config.active_support.deprecation = :stderr end
amith-mysore/rails
config/environments/test.rb
Ruby
apache-2.0
1,532
package io.debezium.examples.aggregation.model; import com.fasterxml.jackson.annotation.*; public class Customer { private final EventType _eventType; private final Integer id; private final String first_name; private final String last_name; private final String email; @JsonCreator public Customer( @JsonProperty("_eventType") EventType _eventType, @JsonProperty("id") Integer id, @JsonProperty("first_name") String first_name, @JsonProperty("last_name") String last_name, @JsonProperty("email") String email) { this._eventType = _eventType == null ? EventType.UPSERT : _eventType; this.id = id; this.first_name = first_name; this.last_name = last_name; this.email = email; } public EventType get_eventType() { return _eventType; } public Integer getId() { return id; } public String getFirst_name() { return first_name; } public String getLast_name() { return last_name; } public String getEmail() { return email; } @Override public String toString() { return "Customer{" + "_eventType='" + _eventType + '\'' + ", id=" + id + ", first_name='" + first_name + '\'' + ", last_name='" + last_name + '\'' + ", email='" + email + '\'' + '}'; } }
debezium/debezium-examples
kstreams/poc-ddd-aggregates/src/main/java/io/debezium/examples/aggregation/model/Customer.java
Java
apache-2.0
1,482
// fstconfidence.cc // 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 2013-2014 Yandex LLC // \file // Use modified to Kaldi MBR decoder to compute lattice confidence scores // #include <iostream> #include <fst/fstlib.h> #include <dcd/lattice-arc.h> #include <dcd/mbr-decode.h> using namespace std; using namespace fst; template<class Arc> void Nbest(const Fst<Arc>& fst, int n, MutableFst<Arc>* ofst) { VectorFst<Arc> ifst(fst); Project(&ifst, PROJECT_OUTPUT); RmEpsilon(&ifst); vector<typename Arc::Weight> d; typedef AutoQueue<typename Arc::StateId> Q; AnyArcFilter<Arc> filter; Q q(ifst, &d, filter); ShortestPathOptions<Arc, Q, AnyArcFilter<Arc> > opts(&q, filter); opts.nshortest = n; opts.unique = true; ShortestPath(ifst, ofst, &d, opts); } template<class Arc> void RmWeights(MutableFst<Arc>* fst) { ArcMap(fst, RmWeightMapper<Arc>()); } template<class Arc> void ToTropical(const Fst<Arc>& ifst, MutableFst<StdArc>* ofst) { ArcMap(ifst, ofst, WeightConvertMapper<Arc, StdArc>()); } template<class Arc> void ToLog(const Fst<Arc>& ifst, MutableFst<LogArc>* ofst) { ArcMap(ifst, ofst, WeightConvertMapper<Arc, LogArc>()); } REGISTER_FST(VectorFst, KaldiLatticeArc); DECLARE_int32(v); int main(int argc, char *argv[]) { string usage = "MBR Decode FST files.\n\n Usage: "; usage += argv[0]; usage += " in.fst [out.fst]\n"; std::set_new_handler(FailedNewHandler); SetFlags(usage.c_str(), &argc, &argv, true); Fst<KaldiLatticeArc> *fst = Fst<KaldiLatticeArc>::Read(""); VectorFst<KaldiLatticeArc> ifst(*fst); Project(&ifst, PROJECT_OUTPUT); RmEpsilon(&ifst); StdVectorFst ofst; MbrDecode(ifst, &ofst); ofst.Write(""); return 0; }
opendcd/opendcd
src/bin/fstconfidence.cc
C++
apache-2.0
2,218
import App from "../app"; export function launchProbe({id}) { const system = App.systems.find(s => s.id === id); if (!system) return {}; return {simulatorId: system.simulatorId}; } export function probeProcessedData({id, simulatorId}) { if (simulatorId) return {simulatorId}; const system = App.systems.find(s => s.id === id); if (!system) return {}; return {simulatorId: system.simulatorId}; }
Thorium-Sim/thorium
server/triggers/probes.js
JavaScript
apache-2.0
410
''' 9. Find all of the crypto map entries that are using PFS group2 ''' from ciscoconfparse import CiscoConfParse config = CiscoConfParse('cisco_ipsec.txt') pfs_group2 = config.find_objects_w_child(parentspec=r"^crypto map CRYPTO", childspec=r"pfs group2") for entry in pfs_group2: print entry.text
eclecticitguy/pynet_paid
class1/ex9_confparse.py
Python
apache-2.0
346
""" Copyright 2016 adpoliak 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. """ from distutils.version import LooseVersion from sortedcontainers.sortedset import SortedSet # import curses # import os # import sys import typing class VersionItem(object): def __init__(self, name: str): self._name = name @property def name(self): return self._name class VersionChoiceDialog(object): @property def chosen_version(self): return self._chosen_version @property def do_not_ask_again(self): return self._do_not_ask_again @do_not_ask_again.setter def do_not_ask_again(self, value: bool): self._do_not_ask_again = value @property def keep_while_available(self): return self._keep_while_available @keep_while_available.setter def keep_while_available(self, value: bool): self._keep_while_available = value @property def persist(self): return self._persist @persist.setter def persist(self, value: bool): self._persist = value @property def return_code(self): return self._return_code @return_code.setter def return_code(self, value: str): self._return_code = value def persist_action(self): if self.persist is not None: self.persist ^= True if self.persist: self.keep_while_available = False self.do_not_ask_again = False else: self.keep_while_available = None self.do_not_ask_again = None def update_persist_state(self): if self.keep_while_available or self.do_not_ask_again: self.persist = None else: self.persist = False def keep_action(self): if self.keep_while_available is not None: self.keep_while_available ^= True self.update_persist_state() def noprompt_action(self): if self.do_not_ask_again is not None: self.do_not_ask_again ^= True def select_action(self): self._chosen_version = list(self._child_names)[self._index] if self.chosen_version.endswith(':KEEP'): self._can_continue = False self.persist = None self.keep_while_available = None self.do_not_ask_again = None else: self._can_continue = True self.persist = False self.persist = False self.do_not_ask_again = False def cancel_action(self): self.return_code = 'cancel' def accept_action(self): if self._can_continue: self.return_code = 'accept' def __init__(self, master: typing.Optional[object], versions: SortedSet, persist: typing.Optional[bool] = False, keep: typing.Optional[bool] = False, last_used: typing.Optional[str] = None, *args, **kwargs): # assign tkinter-compatible interface items to placeholder to placate PyCharm _ = master _ = args _ = kwargs self._can_continue = None self._child_names = SortedSet(versions) self._child_objects = None self._chosen_version = None self._do_not_ask_again = False self._keep_while_available = keep self._last_used = last_used self._return_code = None self._persist = persist self._index = 0 if persist: self.persist_action() if keep: self.keep_action() if last_used is not None: last_used_version_object = LooseVersion(last_used) self._index = self._child_names.index(last_used_version_object) \ if last_used_version_object in self._child_names else 0 self.select_action()
adpoliak/NSAptr
ui/curses/versionchooser.py
Python
apache-2.0
4,308
package com.june.util; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.june.controller.base.BaseController; import cn.jpush.api.ErrorCodeEnum; import cn.jpush.api.IOSExtra; import cn.jpush.api.JPushClient; import cn.jpush.api.MessageResult; @Controller @RequestMapping(value="/jpush") public class JPushClientUtil extends BaseController{ private static final String appKey = "737cea7b852bf8c60cecbf51"; // 必填,例如466f7032ac604e02fb7bda89 private static final String masterSecret = "c0e2c47796f2095cbc56a516";// "13ac09b17715bd117163d8a1";//必填,每个应用都对应一个masterSecret private static JPushClient jpush = null; public static final int MAX = Integer.MAX_VALUE; public static final int MIN = (int) MAX / 2; /** * 保存离线的时长。秒为单位。最多支持10天(864000秒)。 * 0 表示该消息不保存离线。即:用户在线马上发出,当前不在线用户将不会收到此消息。 * 此参数不设置则表示默认,默认为保存1天的离线消息(86400秒)。 */ private static long timeToLive = 60 * 60 * 24; public static void main(String[] args) { String msgTitle = "推送测试"; String msgContent = "看到信息了么,看到就推送成功了!"; String userid="7753b9c538de44c791bb44eed1980d39"; pushMessage(msgTitle,msgContent,userid); } private static void init(){ jpush = new JPushClient(masterSecret, appKey, timeToLive); } /** * 给单个人推送消息 * @param msgTitle * @param msgContent * @param userid 用户id(uuid) */ public static void pushMessage(String msgTitle, String msgContent,String userid) { String result = ""; init(); // 在实际业务中,建议 sendNo 是一个你自己的业务可以处理的一个自增数字。 // 除非需要覆盖,请确保不要重复使用。详情请参考 API 文档相关说明。 int sendNo = getRandomSendNo(); // IOS设备扩展参数, 设置badge,设置声音 Map<String, Object> extra = new HashMap<String, Object>(); IOSExtra iosExtra = new IOSExtra(10, "WindowsLogonSound.wav"); extra.put("ios", iosExtra); // 对所有用户发送通知 //手机端方法:sendNotificationWithAppKey //sendCustomMessageWithAppKey //MessageResult msgResult = jpush.sendNotificationWithAppKey(sendNo,msgTitle, msgContent); //MessageResult msgResult = jpush.sendNotificationWithAlias(sendNo,userid, msgTitle, msgContent); //MessageResult msgResult = jpush.sendCustomMessageWithAppKey(sendNo,msgTitle, msgContent); MessageResult msgResult = jpush.sendNotificationWithAppKey(sendNo,msgTitle, msgContent); //cn.jpush.api.push.MessageResult msgResult = jpush.sendCustomMessage(msgTitle, msgContent, params, extras); if (null != msgResult) { result = "服务器返回数据: " + msgResult.toString(); System.out.println(result); if (msgResult.getErrcode() == ErrorCodeEnum.NOERROR.value()) { result = String.format( "发送成功, sendNo= %s,messageId= %s", msgResult.getSendno(), msgResult.getMsg_id() ); System.out.println(result); } else { result = "发送失败, 错误代码=" + msgResult.getErrcode() + ", 错误消息=" + msgResult.getErrmsg() ; System.out.println(result); } } else { System.out.println("无法获取数据"); } } /** * 给多个人推送消息 * @param list */ /*public static void pushManyMessage(List<PageData> list){ for(int i=0;i<list.size();i++){ pushMessage( list.get(i).get("msgTitle").toString(), list.get(i).get("msgContent").toString(), list.get(i).get("user_id").toString() ); } }*/ /** * 保持 sendNo 的唯一性是有必要的 */ public static int getRandomSendNo() { return (int) (MIN + Math.random() * (MAX - MIN)); } }
junehappylove/framework
src/main/java/com/june/util/JPushClientUtil.java
Java
apache-2.0
4,096
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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 mock from heat.engine import clients from heat.tests.common import HeatTestCase from heatclient import client as heatclient class ClientsTest(HeatTestCase): def test_clients_chosen_at_module_initilization(self): self.assertFalse(hasattr(clients.Clients, 'nova')) self.assertTrue(hasattr(clients.Clients('fakecontext'), 'nova')) def test_clients_get_heat_url(self): con = mock.Mock() con.tenant_id = "b363706f891f48019483f8bd6503c54b" obj = clients.Clients(con) obj._get_client_option = mock.Mock() obj._get_client_option.return_value = None self.assertEqual(None, obj._get_heat_url()) heat_url = "http://0.0.0.0:8004/v1/%(tenant_id)s" obj._get_client_option.return_value = heat_url tenant_id = "b363706f891f48019483f8bd6503c54b" result = heat_url % {"tenant_id": tenant_id} self.assertEqual(result, obj._get_heat_url()) obj._get_client_option.return_value = result self.assertEqual(result, obj._get_heat_url()) @mock.patch.object(heatclient, 'Client') def test_clients_heat(self, mock_call): con = mock.Mock() con.auth_url = "http://auth.example.com:5000/v2.0" con.tenant_id = "b363706f891f48019483f8bd6503c54b" con.auth_token = "3bcc3d3a03f44e3d8377f9247b0ad155" obj = clients.Clients(con) obj._get_heat_url = mock.Mock(name="_get_heat_url") obj._get_heat_url.return_value = None obj.url_for = mock.Mock(name="url_for") obj.url_for.return_value = "url_from_keystone" obj.heat() self.assertEqual('url_from_keystone', mock_call.call_args[0][1]) obj._get_heat_url.return_value = "url_from_config" obj._heat = None obj.heat() self.assertEqual('url_from_config', mock_call.call_args[0][1])
ntt-sic/heat
heat/tests/test_clients.py
Python
apache-2.0
2,473
package org.ovirt.engine.core.bll.storage.pool; import org.ovirt.engine.core.utils.ISingleAsyncOperation; public class RefreshStoragePoolAndDisconnectAsyncOperationFactory extends ActivateDeactivateSingleAsyncOperationFactory { @Override public ISingleAsyncOperation createSingleAsyncOperation() { return new RefreshStoragePoolAndDisconnectAsyncOperation(getVdss(), getStorageDomain(), getStoragePool()); } }
OpenUniversity/ovirt-engine
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/storage/pool/RefreshStoragePoolAndDisconnectAsyncOperationFactory.java
Java
apache-2.0
432
package com.cloud.api.command.admin.network; import com.cloud.api.APICommand; import com.cloud.api.ApiErrorCode; import com.cloud.api.ResponseObject.ResponseView; import com.cloud.api.ServerApiException; import com.cloud.api.command.user.network.UpdateNetworkCmd; import com.cloud.api.response.NetworkResponse; import com.cloud.context.CallContext; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.network.Network; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.utils.exception.InvalidParameterValueException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @APICommand(name = "updateNetwork", description = "Updates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Full, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkCmdByAdmin extends UpdateNetworkCmd { public static final Logger s_logger = LoggerFactory.getLogger(UpdateNetworkCmdByAdmin.class.getName()); @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException { final User callerUser = _accountService.getActiveUser(CallContext.current().getCallingUserId()); final Account callerAccount = _accountService.getActiveAccountById(callerUser.getAccountId()); final Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Couldn't find network by id"); } final Network result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr(), getDisplayNetwork(), getCustomId(), getDns1(), getDns2()); if (result != null) { final NetworkResponse response = _responseGenerator.createNetworkResponse(ResponseView.Full, result); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network"); } } }
remibergsma/cosmic
cosmic-core/api/src/main/java/com/cloud/api/command/admin/network/UpdateNetworkCmdByAdmin.java
Java
apache-2.0
2,305
from django.db.transaction import atomic from api.api_views import APIView from api.exceptions import VmIsNotOperational, VmHasPendingTasks, VmIsLocked, PreconditionRequired from api.task.response import FailureTaskResponse, SuccessTaskResponse from api.task.utils import task_log_success from api.vm.utils import get_vm from api.vm.messages import LOG_MIGRATE_DC from api.vm.migrate.serializers import VmDcSerializer from que.utils import task_id_from_task_id from vms.models import TaskLogEntry, Backup, Snapshot class VmDc(APIView): """ api.vm.migrate.views.vm_dc """ def __init__(self, request, hostname_or_uuid, data): super(VmDc, self).__init__(request) self.hostname_or_uuid = hostname_or_uuid self.data = data self.vm = get_vm(request, hostname_or_uuid, exists_ok=True, noexists_fail=True) @atomic def put(self): request, vm = self.request, self.vm if vm.locked: raise VmIsLocked if vm.status not in (vm.STOPPED, vm.RUNNING, vm.NOTCREATED): raise VmIsNotOperational('VM is not stopped, running or notcreated') if vm.json_changed(): raise PreconditionRequired('VM definition has changed; Update first') ser = VmDcSerializer(request, vm, data=self.data) if not ser.is_valid(): return FailureTaskResponse(request, ser.errors, vm=vm) if vm.tasks: raise VmHasPendingTasks old_dc = vm.dc dc = ser.dc # Change DC for one VM, repeat this for other VM + Recalculate node & storage resources in target and source vm.dc = dc vm.save(update_node_resources=True, update_storage_resources=True) # Change task log entries DC for target VM TaskLogEntry.objects.filter(object_pk=vm.uuid).update(dc=dc) # Change related VM backup's DC Backup.objects.filter(vm=vm).update(dc=dc) for ns in ser.nss: # Issue #chili-885 for i in (dc, old_dc): Backup.update_resources(ns, vm, i) Snapshot.update_resources(ns, vm, i) detail = 'Successfully migrated VM %s from datacenter %s to datacenter %s' % (vm.hostname, old_dc.name, dc.name) # Will create task log entry in old DC res = SuccessTaskResponse(request, detail, vm=vm, msg=LOG_MIGRATE_DC, detail=detail) # Create task log entry in new DC too task_log_success(task_id_from_task_id(res.data.get('task_id'), dc_id=dc.id), LOG_MIGRATE_DC, obj=vm, detail=detail, update_user_tasks=False) return res
erigones/esdc-ce
api/vm/migrate/vm_dc.py
Python
apache-2.0
2,612
package com.charles.robin.mvc.annotation; import java.lang.annotation.*; @Component @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Repository { String value() default ""; }
Lotusun/Robin
src/main/java/com/charles/robin/mvc/annotation/Repository.java
Java
apache-2.0
224
//#include "pl_inner_tinyxml.h" #include "global_consts.h" #include "config_loader.h" #include "c2cplatform/library/xml/xmlparser.h" #include <algorithm> #include <sstream> #include <sys/types.h> #include <dirent.h> #include <unistd.h> #include <assert.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <fcntl.h> ////////////////////////// // Utils Definition uint32_t HexStr2Int(const std::string& sHexStr); // "0x00a10000" --> 10551296L void LRTrim(std::string& sValue); bool IsDigit(const std::string& sDigit); void SpliteStrings(std::string& sStr, std::vector<std::string>& VecStrs); //char * _ConvertEnc(char* encFrom, char* encTo, const char* in); //using namespace pl_inner_xml; ////////////////////////// // class CConfigLoader CConfigLoader::CConfigLoader() : m_bInit(false) { } CConfigLoader::~CConfigLoader() { } int CConfigLoader::Initialize(const char* pszLocalCfgFile) { assert(pszLocalCfgFile); m_bInit = true; m_sLocalCfgFile = pszLocalCfgFile; return 0; } /* int CConfigLoader::ReLoadAll() { return LoadAll(); } */ int CConfigLoader::LoadAll() { assert(m_bInit); // Load Config from ServiceConfig.xml & Set value to m_mapSvcCateCfg int iRetCode = 0; m_stLocalCfgItem.dwLocalIP = GetLocalIP(m_stLocalCfgItem.sLocalIP);//»ñÈ¡±¾»úip£¬±£´æÖÁdwLocalIPºÍsLocalIP iRetCode = doLoadPrivateConfig(); if(iRetCode != 0) { return -1; } iRetCode=doLoadGlobalServiceConfig(); // ¼æÈÝĿǰÇé¿ö if(iRetCode != 0) { return -1; } /* iRetCode = doLoadGlobalServiceConfig2("./"); if(iRetCode != 0) { return -1; } */ int iCmdCnt = GetCmdCnt(GLOBAL_TIMEOUT_CONFIG.c_str()); if(iCmdCnt > 0) { iRetCode = doLoadGlobalTimeoutConfig(GLOBAL_TIMEOUT_CONFIG.c_str(), iCmdCnt); if(iRetCode != 0) { return -1; } } return 0; } int CConfigLoader::doLoadGlobalTimeoutConfig(const char* pszGlobalTimeoutConfig, int iCmdCnt) { assert(pszGlobalTimeoutConfig); c2cplatform::library::xml::CXMLParser oXMLParser; if(oXMLParser.OpenXML(pszGlobalTimeoutConfig) != 0) { fprintf(stderr, "OpenXML %s Failed! %s\n", pszGlobalTimeoutConfig, oXMLParser.GetLastErrMsg()); return -1; } printf("\n"); int iDurTimeoutAttrId = DEFAULT_DUR_TIMEOUT_ITILID; oXMLParser.GetXPathAttrVal("/TimeoutConfigRoot/DurTimeoutAttrId[1]", "AttrId", iDurTimeoutAttrId); m_stLocalCfgItem.mapTimeout.clear(); for(int i = 1; i <= iCmdCnt; i++)//¿ÉÄÜÓжà¸ö£¬°´Öµ°´¶ÎµÄÅäÖò»Í¬ { uint32_t dwCmd = 0; std::string sCmd; char sExp[256] = {0}; snprintf(sExp, sizeof(sExp), "/TimeoutConfigRoot/Item[%u]", i); //¶ÁÃüÁîºÅ========================== if(oXMLParser.GetXPathAttrVal(sExp, "Cmd", sCmd) != 0) { fprintf(stderr, "global_timeout GetXPathAttrVal[Cmd] Failed!\n"); return -1; } if(sCmd.length() == 6) //0xf100 -> 0xf1000000 sCmd += "0000"; sscanf(sCmd.c_str(), "%x", &dwCmd); // ÊDz»ÊDZ¾Ä£¿éµÄÃüÁîºÅ if(m_stLocalCfgItem.dwGroupId != (dwCmd & 0xFFFF0000)) continue; //²åÈë±¾soµÄcmdid¶ÔÓ¦µÄ·ÀÑ©±ÀÉèÖà TimeoutVal_T oTimeoutVal; oTimeoutVal.dwSessTimeout = 0; oTimeoutVal.iDurTimeoutCanDrop = 1; //ȱʡ¶ªÆú oXMLParser.GetXPathAttrVal(sExp, "SessTimeout", oTimeoutVal.dwSessTimeout); oXMLParser.GetXPathAttrVal(sExp, "DurTimeout", oTimeoutVal.dwDurTimeout); if (oTimeoutVal.dwDurTimeout == 0) { oTimeoutVal.dwDurTimeout = DEFAULT_DUR_TIMEOUT_MS; } oXMLParser.GetXPathAttrVal(sExp, "SessRoomFullAttrId", oTimeoutVal.iSessRoomFullAttrId); oXMLParser.GetXPathAttrVal(sExp, "DurTimeoutAttrId", oTimeoutVal.iDurTimeoutAttrId); if (oTimeoutVal.iDurTimeoutAttrId == 0) { oTimeoutVal.iDurTimeoutAttrId = iDurTimeoutAttrId;//ȱʡ¸æ¾¯ } oXMLParser.GetXPathAttrVal(sExp, "DurTimeoutCanDrop", oTimeoutVal.iDurTimeoutCanDrop); if (0 != oXMLParser.GetXPathAttrVal(sExp, "DurTimeoutAction", oTimeoutVal.iDurTimeoutAction)) { oTimeoutVal.iDurTimeoutAction = 1; // ĬÈÏÊDz»·µ»ØÓ¦´ð¸øÇ°¶Ë£¬ÒòΪÒѾ­Ñ©±ÀÁË } oXMLParser.GetXPathAttrVal(sExp, "Desc", oTimeoutVal.sDesc); LRTrim(oTimeoutVal.sDesc); // ÅÅÖØ if(!(m_stLocalCfgItem.mapTimeout.insert(std::make_pair(dwCmd, oTimeoutVal)).second)) { printf("global_timeout (Duplicate) Error find on Cmd[0x%x]\n", dwCmd); return -1; } /* printf("Get Timeout Config for this module, Cmd[0x%x] SessTimeout[%u]s DurTimeout[%u]ms\n", dwCmd, oTimeoutVal.dwSessTimeout, oTimeoutVal.dwDurTimeout); */ } bool bUseDefault = false; if(m_stLocalCfgItem.mapTimeout.empty()) //ÒµÎñδÖ÷¶¯ÅäÖ÷ÀÑ©±À²ÎÊý,ȱʡʹ֧֮³Ö { TimeoutVal_T oTimeoutVal; oTimeoutVal.dwSessTimeout = 0; oTimeoutVal.dwDurTimeout = DEFAULT_DUR_TIMEOUT_MS; //ȱʡѩ±Àʱ¼ä(µ¥Î»ms) oTimeoutVal.iDurTimeoutAttrId = iDurTimeoutAttrId;//ȱʡ¸æ¾¯ oTimeoutVal.iDurTimeoutCanDrop = 1; // ·ÏÆúÕâ¸ö²ÎÊý oTimeoutVal.iDurTimeoutAction = 2; //Ñ©±À£¬È±Ê¡·µ»Ø Ó¦´ð m_stLocalCfgItem.mapTimeout.insert(std::make_pair(m_stLocalCfgItem.dwGroupId, oTimeoutVal)); bUseDefault = true; } // Dump mapTimeout for(std::map<uint32_t, TimeoutVal_T>::iterator it = m_stLocalCfgItem.mapTimeout.begin(); it != m_stLocalCfgItem.mapTimeout.end(); ++it) { fprintf(stderr,"Dump for this module, UseDefault[%s] Cmd[0x%x] SessTimeout[%u]s DurTimeout[%u]ms SessRoomFullAttrId[%d] DurTimeoutAttrId[%d] DurTimeoutCanDrop[%d] Desc[%s] DurTimeoutAction[%d]!\n", (bUseDefault ? "true" : "false"), (*it).first, (*it).second.dwSessTimeout, (*it).second.dwDurTimeout, (*it).second.iSessRoomFullAttrId, (*it).second.iDurTimeoutAttrId, (*it).second.iDurTimeoutCanDrop, (*it).second.sDesc.c_str(), (*it).second.iDurTimeoutAction); } return 0; } int CConfigLoader::doLoadPrivateConfig() { assert(m_bInit); m_stLocalCfgItem.wPort = 0; m_stLocalCfgItem.dwGroupId = 0; m_stLocalCfgItem.dwGroupIndex = 0; m_stLocalCfgItem.wMaxCocurrNum = MAX_STATEFUL_SVC_ALLOC_NUM; m_stLocalCfgItem.dwSessTimeoutSec = SESSION_TIMEOUT_SEC; m_stLocalCfgItem.sDllDir = DEFAULT_SHARE_OBJ_DIR; m_stLocalCfgItem.sGlobalServiceConf = DEFAULT_GLOBAL_SVC_CONF; m_stLocalCfgItem.sSvrLog = DEFAULT_CONT_SVR_LOG; m_stLocalCfgItem.sNotifyLog = DEFAULT_CONT_NOTIFY_LOG; //m_stLocalCfgItem.sSvrStatLog = DEFAULT_CONT_SVR_STAT_LOG; //m_stLocalCfgItem.sBusinessLog = DEFAULT_BUSINESS_LOG; //m_stLocalCfgItem.bAuxSvr = false; //m_stLocalCfgItem.sAuxUSockPath = DEFAULT_AUX_USOCK_PATH; //m_stLocalCfgItem.nAuxCliNum = DEFAULT_AUX_CLI_NUM; m_stLocalCfgItem.bDBSupport = false; m_stLocalCfgItem.sDBName = DEFAULT_DB_NAME; m_stLocalCfgItem.sDBHost = DEFAULT_DB_HOST; m_stLocalCfgItem.sDBUser = DEFAULT_DB_USER; m_stLocalCfgItem.sDBPass = DEFAULT_DB_PASS; //m_stLocalCfgItem.sLogSvcConf = DEFAULT_LOG_SVC_CONF; //m_stLocalCfgItem.sLogModule = DEFAULT_LOG_MODULE; m_stLocalCfgItem.iMsgqFrontKey = 0; m_stLocalCfgItem.iMsgqBackKey = 0; m_stLocalCfgItem.nGroupSize = 1; m_stLocalCfgItem.iPkgReqAttrId = 0; m_stLocalCfgItem.iPkgRespAttrId = 0; m_stLocalCfgItem.iErrPkgRespAttrId = 0; m_stLocalCfgItem.iMaxSessRoomAttrId = 0; m_stLocalCfgItem.iSessRoomFullAttrId = 0; m_stLocalCfgItem.iFrontMQMaxUsageAttrId = 0; m_stLocalCfgItem.iBackMQMaxUsageAttrId = 0; m_stLocalCfgItem.bPthSupport = false; m_stLocalCfgItem.nPthUCtxSize = DEFAULT_PTH_UCTX_SIZE; m_stLocalCfgItem.bDebugSupport = false; m_stLocalCfgItem.bRemotePerform = false; m_stLocalCfgItem.dwMaxPkgLen = DEFAULT_MAX_PKG_LEN; c2cplatform::library::xml::CXMLParser oXMLParser; if(0!=oXMLParser.OpenXML(m_sLocalCfgFile.c_str())) { m_sLastErrMsg = "Cannot open XML file : "; m_sLastErrMsg += m_sLocalCfgFile; return -1; } //ÅжÏÐÂÀÏÅäÖà { //»ñÈ¡ÅäÖõÄitem std::string sPathItemNameOld = "/"+LOCAL_ROOT+"/item"; std::string sPathItemNameNew = "/"+CONFIG_ROOT+"/"+LOCAL_ROOT+"/item"; std::string sPathItemValueOld = "/"+LOCAL_ROOT+"/item"; std::string sPathItemValueNew = "/"+CONFIG_ROOT+"/"+LOCAL_ROOT+"/item"; std::string sValueOld; if (oXMLParser.GetXPathVal(sPathItemNameOld, sValueOld) == 0) { fprintf(stderr, "cont_config.xml old config[%s][%s]\n", sPathItemNameOld.c_str(), sValueOld.c_str()); m_sPathItem = sPathItemNameOld; } std::string sValueNew; if (oXMLParser.GetXPathVal(sPathItemNameNew, sValueNew) == 0) { fprintf(stderr, "cont_config.xml new config[%s][%s]\n", sPathItemNameNew.c_str(), sValueNew.c_str()); m_sPathItem = sPathItemNameNew; } } std::vector<std::string> vecName; if(oXMLParser.GetXPathAttrVal(m_sPathItem, ITEM_NAME, vecName) != 0) { fprintf(stderr,"GetXPathAttrVal[vecName] Failed!\n"); return -1; } std::vector<std::string> vecValue; if(oXMLParser.GetXPathAttrVal(m_sPathItem, ITEM_VALUE, vecValue) != 0) { fprintf(stderr,"GetXPathAttrVal[vecValue] Failed!\n"); return -1; } if(vecName.size()!=vecValue.size()) { fprintf(stderr,"Attribue [Name] size no match [value]\n"); return -1; } for(unsigned int i=0;i<vecName.size();i++) { if(SHARE_OBJ_DIR == vecName[i]) { m_stLocalCfgItem.sDllDir = vecValue[i].c_str(); } else if(LISTEN_PORT == vecName[i]) { if(!IsDigit(vecValue[i])) { m_sLastErrMsg = "Invalid Listen Port : "; m_sLastErrMsg += vecValue[i]; return -1; } m_stLocalCfgItem.wPort = atoi(vecValue[i].c_str()); } else if(MAX_COCURR_NUM == vecName[i]) { if(!IsDigit(vecValue[i])) { m_sLastErrMsg = "Invalid Max CocurrNum : "; m_sLastErrMsg += vecValue[i]; return -1; } m_stLocalCfgItem.wMaxCocurrNum = atoi(vecValue[i].c_str()); if(0 == m_stLocalCfgItem.wMaxCocurrNum) { m_sLastErrMsg = "Invalid Max CocurrNum : "; m_sLastErrMsg += vecValue[i]; return -1; } } else if(SESS_TIMEOUT_SEC == vecName[i]) { if(!IsDigit(vecValue[i])) { m_sLastErrMsg = "Invalid SessTimeout Second : "; m_sLastErrMsg += vecValue[i]; return -1; } m_stLocalCfgItem.dwSessTimeoutSec = atoi(vecValue[i].c_str()); } else if(THIS_GROUP_ID == vecName[i]) { vecValue[i] += "0000"; m_stLocalCfgItem.dwGroupId = HexStr2Int(vecValue[i]); if(0 == m_stLocalCfgItem.dwGroupId) { m_sLastErrMsg = "Invalid GroupId : "; m_sLastErrMsg += vecValue[i]; return -1; } } else if(THIS_GROUP_INDEX == vecName[i]) { if(!IsDigit(vecValue[i])) { m_sLastErrMsg = "Invalid group index : "; m_sLastErrMsg += vecValue[i]; return -1; } m_stLocalCfgItem.dwGroupIndex = atoi(vecValue[i].c_str()); } else if(GLOBAL_SVC_CONF == vecName[i]) { m_stLocalCfgItem.sGlobalServiceConf = vecValue[i]; } else if(DB_SUPPORT == vecName[i]) { m_stLocalCfgItem.bDBSupport = (vecValue[i] != "0"); } else if(CONT_SVR_LOG == vecName[i]) { m_stLocalCfgItem.sSvrLog = vecValue[i]; } else if(CONT_NOTIFY_LOG == vecName[i]) { m_stLocalCfgItem.sNotifyLog = vecValue[i]; } else if(DB_SUPPORT == vecName[i]) { m_stLocalCfgItem.bDBSupport = (vecValue[i] != "0"); } else if(DB_NAME == vecName[i]) { m_stLocalCfgItem.sDBName = vecValue[i]; } else if(DB_HOST == vecName[i]) { m_stLocalCfgItem.sDBHost = vecValue[i]; } else if(DB_USER == vecName[i]) { m_stLocalCfgItem.sDBUser = vecValue[i]; } else if(DB_PASS == vecName[i]) { m_stLocalCfgItem.sDBPass = vecValue[i]; } else if(PKG_REQ_ATTR_ID == vecName[i]) { if(!IsDigit(vecValue[i])) { m_sLastErrMsg = "Invalid PkgReqAttrId : "; m_sLastErrMsg += vecValue[i]; return -1; } m_stLocalCfgItem.iPkgReqAttrId = atoi(vecValue[i].c_str()); } else if(PKG_RESP_ATTR_ID == vecName[i]) { if(!IsDigit(vecValue[i])) { m_sLastErrMsg = "Invalid PkgRespAttrId : "; m_sLastErrMsg += vecValue[i]; return -1; } m_stLocalCfgItem.iPkgRespAttrId = atoi(vecValue[i].c_str()); } else if(ERR_PKG_RESP_ATTR_ID == vecName[i]) { if(!IsDigit(vecValue[i])) { m_sLastErrMsg = "Invalid ErrPkgRespAttrId : "; m_sLastErrMsg += vecValue[i]; return -1; } m_stLocalCfgItem.iErrPkgRespAttrId = atoi(vecValue[i].c_str()); } else if(MAX_SESS_ROOM_ATTR_ID == vecName[i]) { if(!IsDigit(vecValue[i])) { m_sLastErrMsg = "Invalid MaxSessRoomAttrId : "; m_sLastErrMsg += vecValue[i]; return -1; } m_stLocalCfgItem.iMaxSessRoomAttrId = atoi(vecValue[i].c_str()); } else if(SESS_ROOM_FULL_ATTR_ID == vecName[i]) { if(!IsDigit(vecValue[i])) { m_sLastErrMsg = "Invalid SessRoomFullAttrId : "; m_sLastErrMsg += vecValue[i]; return -1; } m_stLocalCfgItem.iSessRoomFullAttrId = atoi(vecValue[i].c_str()); } else if(FRONT_MQ_MAX_USAGE_ATTR_ID == vecName[i]) { if(!IsDigit(vecValue[i])) { m_sLastErrMsg = "Invalid FrontMQMaxUsageAttrId: "; m_sLastErrMsg += vecValue[i]; return -1; } m_stLocalCfgItem.iFrontMQMaxUsageAttrId = atoi(vecValue[i].c_str()); } else if(BACK_MQ_MAX_USAGE_ATTR_ID == vecName[i]) { if(!IsDigit(vecValue[i])) { m_sLastErrMsg = "Invalid BackMQMaxUsageAttrId: "; m_sLastErrMsg += vecValue[i]; return -1; } m_stLocalCfgItem.iBackMQMaxUsageAttrId = atoi(vecValue[i].c_str()); } else if(PTH_SUPPORT == vecName[i]) { m_stLocalCfgItem.bPthSupport = (vecValue[i] != "0"); } else if(DEBUG_SUPPORT == vecName[i]) { m_stLocalCfgItem.bDebugSupport = (vecValue[i] != "0"); } else if(REMOTE_PERFORM == vecName[i]) { m_stLocalCfgItem.bRemotePerform = (vecValue[i] != "0"); } else if(PTH_UCTX_SIZE == vecName[i]) { if(!IsDigit(vecValue[i])) { m_sLastErrMsg = "Invalid Pth UCTX Size : "; m_sLastErrMsg += vecValue[i]; return -1; } m_stLocalCfgItem.nPthUCtxSize = atoi(vecValue[i].c_str()); if(16 > m_stLocalCfgItem.nPthUCtxSize) { m_stLocalCfgItem.nPthUCtxSize = 16; } } else if(MAX_PKG_LEN == vecName[i]) { if(!IsDigit(vecValue[i])) { m_sLastErrMsg = "Invalid MaxPkgLen : "; m_sLastErrMsg += vecValue[i]; return -1; } m_stLocalCfgItem.dwMaxPkgLen = atoi(vecValue[i].c_str()); } else if(MQ_WAITTIME_UMP_KEY == vecName[i]) { m_stLocalCfgItem.sMQWaitTimeUmpKey = vecValue[i];; } } if(0 == m_stLocalCfgItem.dwGroupId) { m_sLastErrMsg = "Local Config Missing GroupId"; return -1; } fprintf(stderr,"doLoadPrivateConfig OK!\n"); return 0; } int CConfigLoader::doLoadGlobalServiceConfig() { assert(m_bInit); c2cplatform::library::xml::CXMLParser oXMLParser; if(0!=oXMLParser.OpenXML(m_stLocalCfgItem.sGlobalServiceConf.c_str())) { m_sLastErrMsg = "Cannot open XML file : "; m_sLastErrMsg += m_stLocalCfgItem.sGlobalServiceConf; return -1; } std::vector<std::string> vecName; if(oXMLParser.GetXPathAttrVal("/"+SVC_GROUP_ROOT+"/Group",GROUP_NAME, vecName) != 0) { fprintf(stderr,"GetXPathAttrVal[vecName] Failed!\n"); return -1; } std::vector<std::string> vecId; if(oXMLParser.GetXPathAttrVal("/"+SVC_GROUP_ROOT+"/Group",GROUP_ID, vecId) != 0) { fprintf(stderr,"GetXPathAttrVal[vecId] Failed!\n"); return -1; } std::vector<std::string> vecFrontKey; if(oXMLParser.GetXPathAttrVal("/"+SVC_GROUP_ROOT+"/Group",FRONT_MSGQ_KEY, vecFrontKey) != 0) { fprintf(stderr,"GetXPathAttrVal[vecFrontKey] Failed!\n"); return -1; } std::vector<std::string> vecBackKey; if(oXMLParser.GetXPathAttrVal("/"+SVC_GROUP_ROOT+"/Group",BACK_MSGQ_KEY, vecBackKey) != 0) { fprintf(stderr,"GetXPathAttrVal[vecBackKey] Failed!\n"); return -1; } std::vector<std::string> vecSize; if(oXMLParser.GetXPathAttrVal("/"+SVC_GROUP_ROOT+"/Group",GROUP_SIZE, vecSize) != 0) { fprintf(stderr,"GetXPathAttrVal[vecSize] Failed!\n"); return -1; } if(vecName.size()!=vecId.size() || vecName.size()!=vecFrontKey.size() || vecName.size()!=vecBackKey.size() || vecName.size()!=vecSize.size()) { fprintf(stderr,"Attribue [Name] size no match [ID]/[FrontMsgQKey]/[BackMsgQKey/[Size]\n"); } /*std::map<std::string, std::string> mapRoute; if(oXMLParser.GetXPathAttrVal2("/"+SVC_GROUP_ROOT+"/Group", GROUP_ID, GROUP_ROUTE, mapRoute) != 0) { fprintf(stderr,"GetXPathAttrVal[vecRoute] Failed:%s!\n", oXMLParser.GetLastErrMsg()); } for (std::map<std::string, std::string>::iterator it = mapRoute.begin(); it != mapRoute.end(); ++it) { std::string sCmd = it->first; sCmd += "0000"; uint32_t dwGroupId = HexStr2Int(sCmd); if(0 == dwGroupId) { fprintf(stderr, "Invalid GroupId : %d\n", dwGroupId); continue; } std::string sRoute = it->second; m_mapTcpCmdRoute.insert(std::make_pair(dwGroupId, getRouteType(sRoute))); }*/ for(unsigned int i=0;i<vecName.size();i++) { LRTrim(vecName[i]); LRTrim(vecId[i]); LRTrim(vecFrontKey[i]); LRTrim(vecBackKey[i]); LRTrim(vecSize[i]); if(IsDigit(vecBackKey[i])) { m_mapMsgqKeyBack[atoi(vecBackKey[i].c_str())] = vecName[i]; } uint32_t dwGroupId = HexStr2Int(vecId[i] + "0000"); if(0 == dwGroupId) { fprintf(stderr, "Invalid Group Id : %s\n", vecId[i].c_str()); return -1; } // Check BACK_NET_IO_TSE, BACK_NET_IO_BOSS, ... if(vecName[i].find(BACK_CNTL_GROUP_NAME) != std::string::npos) { // 12 = length("BACK_NET_IO_"); if(vecName[i].length() >= 12) { m_stLocalCfgItem.mapBackNetioItems[dwGroupId] = std::string(vecName[i].begin() + 12, vecName[i].end()); m_stLocalCfgItem.mapBackNetioItems2[std::string(vecName[i].begin() + 12, vecName[i].end())] = dwGroupId; } else if(11 == vecName[i].length())//"BACK_NET_IO" { m_stLocalCfgItem.mapBackNetioItems[dwGroupId] = "TCP"; m_stLocalCfgItem.mapBackNetioItems2["TCP"] = dwGroupId; } else assert(0); FrontKeys_T stFrontKeys; memset(&stFrontKeys, 0, sizeof(stFrontKeys)); stFrontKeys.nKeyNum = 1; stFrontKeys.arrKeys[0] = atoi(vecFrontKey[i].c_str()); m_mapMsgqKeyFront[dwGroupId] = stFrontKeys;//back_netioµÄfront key£¬ÒòΪ²¿·ÖsoÐèʹÓÃbacknetio£¬Í¨¹ýmapBackNetioGroupsÕÒµ½cmd£¬ÔÙÕÒµ½key } if((vecName[i].find(BACK_CNTL_GROUP_NAME) == std::string::npos) && (vecName[i].find(CNTL_GROUP_NAME) != std::string::npos)) { dwNetIoCmd = dwGroupId; } } std::set<std::string> setDuplicateCheckGroupId; std::set<std::string> setDuplicateCheckFrontQ; std::set<std::string> setDuplicateCheckBackQ; for(unsigned int i=0;i<vecName.size();i++)//ͨ¹ý2´ÎforÑ­»·£¬±£Ö¤back_netioÄÜÏȱ»´¦Àí£¬·ÀÖ¹ÓÐÈËÔÚxmlÖн«back_netioÐзÅÔÚÓÐtcpµÄÐÐÖ®ºó { LRTrim(vecName[i]); LRTrim(vecId[i]); LRTrim(vecFrontKey[i]); LRTrim(vecBackKey[i]); LRTrim(vecSize[i]); uint32_t dwGroupId = HexStr2Int(vecId[i] + "0000"); if(0 == dwGroupId) { fprintf(stderr, "Invalid Group Id : %s\n", vecId[i].c_str()); return -1; } if(IsDigit(vecBackKey[i])) { m_mapMsgqKeyBack[atoi(vecBackKey[i].c_str())] = vecName[i]; m_mapBackKeyCmd[atoi(vecBackKey[i].c_str())] = dwGroupId; } if(std::string::npos == vecName[i].find(CNTL_GROUP_NAME)) // Pass NET_IO...(Ö»Õë¶ÔsoµÄÅäÖÃÏî) { //·ÇnetioÐÐ /********************* Duplicate Check ****************************************/ if(isdigit(vecFrontKey[i][0])) { if(setDuplicateCheckGroupId.find(vecId[i]) == setDuplicateCheckGroupId.end()) setDuplicateCheckGroupId.insert(vecId[i]); else fprintf(stderr, "Duplicated !!! GroupId[%s] Pls Check global_conf/ServiceConfig.xml!\n", vecId[i].c_str()); if(setDuplicateCheckFrontQ.find(vecFrontKey[i]) == setDuplicateCheckFrontQ.end()) setDuplicateCheckFrontQ.insert(vecFrontKey[i]); else fprintf(stderr, "Duplicated !!! FrontMsgQKey[%s] Pls Check global_conf/ServiceConfig.xml!\n", vecFrontKey[i].c_str()); if(setDuplicateCheckBackQ.find(vecBackKey[i]) == setDuplicateCheckBackQ.end()) setDuplicateCheckBackQ.insert(vecBackKey[i]); else fprintf(stderr, "Duplicated !!! BackMsgQKey[%s] Pls Check global_conf/ServiceConfig.xml!\n", vecBackKey[i].c_str()); } /********************* Duplicate Check ****************************************/ fprintf(stderr,"%s %s %s %s %s\n",vecName[i].c_str(),vecId[i].c_str(),vecFrontKey[i].c_str() ,vecBackKey[i].c_str(),vecSize[i].c_str()); if(MakeRouteInfo(vecId[i], vecFrontKey[i], vecBackKey[i], vecSize[i], vecName[i]) != 0) { fprintf(stderr, "MakeRouteInfo failed : %s\n", m_sLastErrMsg.c_str()); return -1; } } } if(0 == m_stLocalCfgItem.iMsgqFrontKey || 0 == m_stLocalCfgItem.iMsgqBackKey) { std::stringstream ss; ss << "Local Config Wrong MsqQkey,FrontKey:["; ss << m_stLocalCfgItem.iMsgqFrontKey << "] BackKey["; ss << m_stLocalCfgItem.iMsgqBackKey << "]"; m_sLastErrMsg = ss.str(); return -1; } return 0; } void CConfigLoader::Dump(std::ostream& os) { os << "------------------ Private Config -------------------" << std::endl; os << "Group ID = 0x" << std::hex << m_stLocalCfgItem.dwGroupId << std::dec << std::endl; os << "Group Name = " << m_stLocalCfgItem.sGroupName << std::endl; os << "Group Size = " << m_stLocalCfgItem.nGroupSize << std::endl; os << "Group MsgQ Front Key = " << m_stLocalCfgItem.iMsgqFrontKey << "(0x" << std::hex << m_stLocalCfgItem.iMsgqFrontKey << std::dec << ")" << std::endl; os << "Group MsgQ Back Key = " << m_stLocalCfgItem.iMsgqBackKey << "(0x" << std::hex << m_stLocalCfgItem.iMsgqBackKey << std::dec << ")" << std::endl; os << "Share Object Dir = " << m_stLocalCfgItem.sDllDir << std::endl; os << "Global Service Conf = " << m_stLocalCfgItem.sGlobalServiceConf << std::endl; os << "Max CocurrNum = " << m_stLocalCfgItem.wMaxCocurrNum << std::endl; os << "Max PkgLen = " << m_stLocalCfgItem.dwMaxPkgLen << std::endl; os << "Pth Support = " << (m_stLocalCfgItem.bPthSupport ? "YES" : "NO") << std::endl; if(m_stLocalCfgItem.bPthSupport) os << "Pth UCTX Size = " << (m_stLocalCfgItem.nPthUCtxSize) << "K"<< std::endl; if(m_stLocalCfgItem.bRemotePerform) os << "RemotePerformLog ON." << std::endl; else os << "RemotePerformLog OFF." << std::endl; os << "PkgReqAttrId = " << m_stLocalCfgItem.iPkgReqAttrId << std::endl; os << "PkgRespAttrId = " << m_stLocalCfgItem.iPkgRespAttrId << std::endl; os << "ErrPkgRespAttrId = " << m_stLocalCfgItem.iErrPkgRespAttrId << std::endl; os << "MaxSessRoomAttrId = " << m_stLocalCfgItem.iMaxSessRoomAttrId << std::endl; os << "SessRoomFullAttrId = " << m_stLocalCfgItem.iSessRoomFullAttrId << std::endl; os << "MQWaitTimeUmpKey = " << m_stLocalCfgItem.sMQWaitTimeUmpKey << std::endl; os << "----------------------BackNetio------------------------" << std::endl; for(std::map<uint32_t, std::string>::const_iterator it = m_stLocalCfgItem.mapBackNetioItems.begin(); it != m_stLocalCfgItem.mapBackNetioItems.end(); ++it) { os << (*it).second << "-->0x" << std::hex << (*it).first << std::dec << std::endl; } os << "-------------------------------------------------------" << std::endl; /* os << "----------------------BackMsgQ-Cmd------------------------------" << std::endl; for (GroupBackKeyCmdMap_T::const_iterator it = m_mapBackKeyCmd.begin(); it != m_mapBackKeyCmd.end(); ++it) { os << (*it).first << "-->0x" <<std::hex << (*it).second << "NetIo:0x" << dwNetIoCmd << std::dec << std::endl; } os << "----------------------------------------------------------------" << std::endl; */ /* Debug os << "----------------------BackMsgQ-GroupName------------------------" << std::endl; for(GroupMsgqKeyBackMap_T::const_iterator it = m_mapMsgqKeyBack.begin(); it != m_mapMsgqKeyBack.end(); ++it) { os << (*it).first << "--" << std::hex << (*it).second << std::dec << std::endl; } os << "-------------------------------------------------------" << std::endl; */ } int CConfigLoader::getConfig(const std::string& sName,std::string& sValue) { c2cplatform::library::xml::CXMLParser oXMLParser; if(0!=oXMLParser.OpenXML(m_sLocalCfgFile.c_str())) { m_sLastErrMsg = "Cannot open XML file : "; m_sLastErrMsg += m_sLocalCfgFile; return -1; } std::vector<std::string> vecName; if(oXMLParser.GetXPathAttrVal(m_sPathItem, ITEM_NAME, vecName) != 0) { fprintf(stderr,"GetXPathAttrVal[vecName] Failed!\n"); return -1; } std::vector<std::string> vecValue; if(oXMLParser.GetXPathAttrVal(m_sPathItem, ITEM_VALUE, vecValue) != 0) { fprintf(stderr,"GetXPathAttrVal[vecValue] Failed!\n"); return -1; } if(vecName.size()!=vecValue.size()) { fprintf(stderr,"Attribue [Name] size no match [value]\n"); return -1; } for(unsigned int i=0;i<vecName.size();i++) { if(sName == vecName[i]) { sValue = vecValue[i]; return 0; } } fprintf(stderr,"getConfig not find[%s]\n", sName.c_str()); return -1; } int CConfigLoader::getConfig(const std::string& sName,uint32_t& dwValue) { c2cplatform::library::xml::CXMLParser oXMLParser; if(0!=oXMLParser.OpenXML(m_sLocalCfgFile.c_str())) { m_sLastErrMsg = "Cannot open XML file : "; m_sLastErrMsg += m_sLocalCfgFile; return -1; } std::vector<std::string> vecName; if(oXMLParser.GetXPathAttrVal(m_sPathItem, ITEM_NAME, vecName) != 0) { fprintf(stderr,"GetXPathAttrVal[vecName] Failed!\n"); return -1; } std::vector<std::string> vecValue; if(oXMLParser.GetXPathAttrVal(m_sPathItem, ITEM_VALUE, vecValue) != 0) { fprintf(stderr,"GetXPathAttrVal[vecValue] Failed!\n"); return -1; } if(vecName.size()!=vecValue.size()) { fprintf(stderr,"Attribue [Name] size no match [value]\n"); return -1; } for(unsigned int i=0;i<vecName.size();i++) { if(sName == vecName[i]) { if(!IsDigit(vecValue[i])) { m_sLastErrMsg = "Value is not digit"; return -1; } dwValue = atoi(vecValue[i].c_str()); return 0; } } fprintf(stderr,"getConfig not find[%s]\n", sName.c_str()); return -1; } int CConfigLoader::MakeRouteInfo(std::string& sGroupId,std::string& sFrontMsgQKey,std::string& sBackMsgQKey, std::string& sGroupSize,std::string& sGroupName) { if(sGroupId.empty()) { m_sLastErrMsg = "sGroupId.empty()"; return -1; } uint32_t dwGroupId = HexStr2Int(sGroupId + "0000"); if(0 == dwGroupId) { m_sLastErrMsg = "Invalid Group Id : "; m_sLastErrMsg += sGroupId; return -1; } //GroupMsgqKeyFrontMap_T::iterator it = m_mapMsgqKeyFront.find(dwGroupId); //if(it != m_mapMsgqKeyFront.end()) // Use global_conf/ServiceConf.xml //{ // m_sLastErrMsg = "it != m_mapMsgqKeyFront.end(), Groupid="+sGroupId; // return -1; //} if(sFrontMsgQKey.empty()) { sFrontMsgQKey = sGroupId; } else//·Ç¿Õ ¿ÉÄÜÊÇTCP£¬¿ÉÄÜÊÇkey { for(std::map<uint32_t, std::string>::const_iterator it = m_stLocalCfgItem.mapBackNetioItems.begin(); it != m_stLocalCfgItem.mapBackNetioItems.end(); ++it) { if(sFrontMsgQKey == (*it).second)//sFrontMsgQKey=="TCP"µÈÇé¿ö { m_stLocalCfgItem.mapBackNetioGroups[dwGroupId] = (*it).first;//¸ÃÃüÁîºÅÐèҪʹÓÃbacknetio£¬key=soÃüÁîºÅ£¬value=backnetioµÄÃüÁîºÅ fprintf(stderr,"GroupId:[0x%x] use BackNetio GroupId:[%x]\n",dwGroupId,(*it).first); return 0; } } } ////////////////////// Try to Split FrontKeys /////////////////////////////// std::vector<std::string> vecFrontKeys; SpliteStrings(sFrontMsgQKey, vecFrontKeys); /////////////////////////////////////////////////////////////////////////////// FrontKeys_T stFrontKeys; stFrontKeys.nKeyNum = vecFrontKeys.size(); assert(stFrontKeys.nKeyNum <= MAX_FRONT_KEYS); for(uint32_t i = 0; i < stFrontKeys.nKeyNum; ++i) { stFrontKeys.arrKeys[i] = atoi(vecFrontKeys[i].c_str()); //printf("GroupId[0x%x] Keys[%d] KeyNum[%d]\n", dwGroupId, stFrontKeys.arrKeys[i], stFrontKeys.nKeyNum); } // Match this GroupId ±¾Éíso£¬Í¨¹ýdwGroupIndexÈ·¶¨Ö»Ê¹ÓÃ1¸öfrontkeyºÍ1¸öbackkey if(m_stLocalCfgItem.dwGroupId == dwGroupId) { if(sBackMsgQKey.empty()) { std::stringstream oss; oss << (dwGroupId / 0x10000 + 1);//back_keyĬÈÏÊÇfrontkey+1 sBackMsgQKey = oss.str(); } if(m_stLocalCfgItem.dwGroupIndex >= stFrontKeys.nKeyNum) { m_sLastErrMsg = "\nGroupIndex Out of bound!"; return -1; } sFrontMsgQKey = vecFrontKeys[m_stLocalCfgItem.dwGroupIndex]; m_stLocalCfgItem.iMsgqFrontKey = atoi(sFrontMsgQKey.c_str()); m_stLocalCfgItem.iMsgqBackKey = atoi(sBackMsgQKey.c_str()); std::transform(sGroupName.begin(), sGroupName.end(), sGroupName.begin(), toupper); m_stLocalCfgItem.sGroupName = sGroupName; if(!sGroupSize.empty()) m_stLocalCfgItem.nGroupSize = atoi(sGroupSize.c_str()); } else { m_mapMsgqKeyFront[dwGroupId] = stFrontKeys;//¼Ç¼ÆäËûsoµÄcmdidºÍfrontkey(¿ÉÄܶà¸ökey£¬¶ººÅ·Ö¸î) } return 0; } int CConfigLoader::GetCmdCnt(const char* pszGlobalTimeoutConfig) { assert(pszGlobalTimeoutConfig); c2cplatform::library::xml::CXMLParser oXMLParser; oXMLParser.OpenXML(pszGlobalTimeoutConfig); std::vector<std::string> vecCmd; //ÃüÁîºÅÁÐ±í£¬¿É°´Öµ¡¢°´¶Î if(oXMLParser.GetXPathAttrVal("/TimeoutConfigRoot/Item", "Cmd", vecCmd) != 0) { printf("GetXPathAttrVal[Cmd] Failed!\n"); return -1; } return vecCmd.size(); } uint32_t CConfigLoader::GetLocalIP(std::string& sLocalIP) { int iClientSockfd = socket(AF_INET, SOCK_DGRAM, 0); if(iClientSockfd < 0 ) { printf("Client, Create socket failed\n"); return 0; } struct sockaddr_in stINETAddr; stINETAddr.sin_addr.s_addr = inet_addr("172.16.130.1"); stINETAddr.sin_family = AF_INET; stINETAddr.sin_port = htons(8888); int iCurrentFlag = fcntl(iClientSockfd, F_GETFL, 0); fcntl(iClientSockfd, F_SETFL, iCurrentFlag | FNDELAY); connect(iClientSockfd, (struct sockaddr *)&stINETAddr, sizeof(sockaddr)); struct sockaddr_in stINETAddrLocal; socklen_t iAddrLenLocal = sizeof(stINETAddrLocal); getsockname(iClientSockfd, (struct sockaddr *)&stINETAddrLocal, &iAddrLenLocal); sLocalIP = inet_ntoa(stINETAddrLocal.sin_addr); uint32_t dwLocalIP = static_cast<uint32_t>(stINETAddrLocal.sin_addr.s_addr); //uint32_t dwLocalIP = static_cast<uint32_t>(inet_netof(stINETAddrLocal.sin_addr)); close(iClientSockfd); return dwLocalIP; } /* int CConfigLoader::doLoadGlobalServiceConfig2(const char* pszBaseDir) { assert(m_bInit); // Get all priv config file path DIR* dp = NULL; if((dp = opendir(pszBaseDir)) == NULL) { printf("Cannot open %s\n", pszBaseDir); return -1; } std::vector<std::string> vec_priv_conf; std::string sTmp; struct dirent *dirp; while((dirp = readdir(dp)) != NULL) if(dirp->d_type == DT_DIR && strcmp(dirp->d_name, ".") != 0 && strcmp(dirp->d_name, "..") != 0) { //printf("type[%d]name[%s] ", dirp->d_type, dirp->d_name); sTmp = pszBaseDir; sTmp += "/"; sTmp += dirp->d_name; sTmp += "/etc/cont_config.xml"; vec_priv_conf.push_back(sTmp); } closedir(dp); // Get Route info from all these priv config files TiXmlNode* node = NULL; TiXmlElement* RootElement = NULL; TiXmlElement* ItemElement = NULL; std::string sPrivConfFile; std::string sName; std::string sValue; std::string sGroupId; std::string sGroupName; std::string sFrontQKey; std::string sBackQKey; std::string sGroupSize; for(std::vector<std::string>::iterator it = vec_priv_conf.begin(); it != vec_priv_conf.end(); ++it) { sPrivConfFile = (*it); //printf("parsing file [%s]\n", sPrivConfFile.c_str()); TiXmlDocument doc(sPrivConfFile.c_str()); if (!doc.LoadFile()) { m_sLastErrMsg = "Cannot open XML file : "; m_sLastErrMsg += sPrivConfFile; return -1; } // Get Root Element node = doc.FirstChild(LOCAL_ROOT.c_str()); RootElement = node->ToElement(); // Search for 'Item' node = RootElement->FirstChildElement(); ItemElement = node->ToElement(); sGroupId = ""; sGroupName = ""; sFrontQKey = ""; sBackQKey = ""; sGroupSize = ""; while(ItemElement) { sName = ItemElement->Attribute(ITEM_NAME.c_str()); LRTrim(sName); sValue = ItemElement->Attribute(ITEM_VALUE.c_str()); LRTrim(sValue); if(THIS_GROUP_ID == sName) sGroupId = sValue; else if(FRONT_MSGQ_KEY == sName) sFrontQKey = sValue; else if(BACK_MSGQ_KEY == sName) sBackQKey = sValue; else if(GROUP_SIZE == sName) sGroupSize = sValue; ItemElement = ItemElement->NextSiblingElement(); } MakeRouteInfo(sGroupId, sFrontQKey, sBackQKey, sGroupSize, sGroupName); } if(0 == m_stLocalCfgItem.iMsgqFrontKey) { m_sLastErrMsg = "Service Config Missing MsgqFrontKey"; return -1; } else if(0 == m_stLocalCfgItem.iMsgqBackKey) { m_sLastErrMsg = "Service Config Missing MsgqBackKey"; return -1; } return 0; } */ int CConfigLoader::ReloadContainer(bool IsBackKey) { assert(m_bInit); c2cplatform::library::xml::CXMLParser oXMLParser; if(0!=oXMLParser.OpenXML(m_stLocalCfgItem.sGlobalServiceConf.c_str())) { m_sLastErrMsg = "Cannot open XML file : "; m_sLastErrMsg += m_stLocalCfgItem.sGlobalServiceConf; return -1; } std::vector<std::string> vecName; if(oXMLParser.GetXPathAttrVal("/"+SVC_GROUP_ROOT+"/Group",GROUP_NAME, vecName) != 0) { fprintf(stderr,"GetXPathAttrVal[vecName] Failed!\n"); return -1; } std::vector<std::string> vecId; if(oXMLParser.GetXPathAttrVal("/"+SVC_GROUP_ROOT+"/Group",GROUP_ID, vecId) != 0) { fprintf(stderr,"GetXPathAttrVal[vecId] Failed!\n"); return -1; } std::vector<std::string> vecFrontKey; if(oXMLParser.GetXPathAttrVal("/"+SVC_GROUP_ROOT+"/Group",FRONT_MSGQ_KEY, vecFrontKey) != 0) { fprintf(stderr,"GetXPathAttrVal[vecFrontKey] Failed!\n"); return -1; } std::vector<std::string> vecBackKey; if(oXMLParser.GetXPathAttrVal("/"+SVC_GROUP_ROOT+"/Group",BACK_MSGQ_KEY, vecBackKey) != 0) { fprintf(stderr,"GetXPathAttrVal[vecBackKey] Failed!\n"); return -1; } std::vector<std::string> vecSize; if(oXMLParser.GetXPathAttrVal("/"+SVC_GROUP_ROOT+"/Group",GROUP_SIZE, vecSize) != 0) { fprintf(stderr,"GetXPathAttrVal[vecSize] Failed!\n"); return -1; } if(vecName.size()!=vecId.size() || vecName.size()!=vecFrontKey.size() || vecName.size()!=vecBackKey.size() || vecName.size()!=vecSize.size()) { fprintf(stderr,"Attribue [Name] size no match [ID]/[FrontMsgQKey]/[BackMsgQKey/[Size]\n"); return -1; } for(size_t i=0;i<vecId.size();i++) { LRTrim(vecName[i]); LRTrim(vecId[i]); LRTrim(vecFrontKey[i]); LRTrim(vecBackKey[i]); LRTrim(vecSize[i]); // Match this GroupId uint32_t dwGroupId = 0; vecId[i] += "0000"; dwGroupId = HexStr2Int(vecId[i]); if(0 == dwGroupId) { m_sLastErrMsg = "Invalid Group Id : "; m_sLastErrMsg += vecId[i]; return -1; } if(m_stLocalCfgItem.dwGroupId == dwGroupId) { if(IsBackKey) m_stLocalCfgItem.iMsgqBackKey = atoi(vecBackKey[i].c_str()); else { std::vector<std::string> vecFrontKeys; SpliteStrings(vecFrontKey[i], vecFrontKeys); if(m_stLocalCfgItem.dwGroupIndex >= vecFrontKeys.size()) { m_sLastErrMsg = "\nGroupIndex Out of bound!"; return -1; } std::string sFrontMsgQKey = vecFrontKeys[m_stLocalCfgItem.dwGroupIndex]; m_stLocalCfgItem.iMsgqFrontKey = atoi(sFrontMsgQKey.c_str()); } } } return 0; } const uint32_t CConfigLoader::GetBackNetioGroupId(const std::string& strRemote) { uint32_t dwBackNetioGroupId = 0; std::map<std::string, uint32_t>::iterator it = m_stLocalCfgItem.mapBackNetioItems2.find(strRemote); if (it != m_stLocalCfgItem.mapBackNetioItems2.end()) { dwBackNetioGroupId = it->second; } return dwBackNetioGroupId; } const uint32_t CConfigLoader::getCmdByBackKey(int iMsgQBackKey) { GroupBackKeyCmdMap_T::iterator it = m_mapBackKeyCmd.find(iMsgQBackKey); if (it != m_mapBackKeyCmd.end()) { return it->second; } return 0; } void CConfigLoader::delGroupMsgqKeyFront(uint32_t dwGroupid) { m_mapMsgqKeyFront.erase(dwGroupid); } void CConfigLoader::delBackNetioKeyFront(uint32_t dwGroupid) { m_stLocalCfgItem.mapBackNetioGroups.erase(dwGroupid); } int CConfigLoader::Reload(uint32_t dwGroupid) { assert(m_bInit); c2cplatform::library::xml::CXMLParser oXMLParser;//¹¹Îöº¯ÊýÍê³Éclose if(0!=oXMLParser.OpenXML(m_stLocalCfgItem.sGlobalServiceConf.c_str())) { m_sLastErrMsg = "Cannot open XML file : "; m_sLastErrMsg += m_stLocalCfgItem.sGlobalServiceConf; return -1; } std::vector<std::string> vecName; if(oXMLParser.GetXPathAttrVal("/"+SVC_GROUP_ROOT+"/Group",GROUP_NAME, vecName) != 0) { fprintf(stderr,"GetXPathAttrVal[vecName] Failed!\n"); return -1; } std::vector<std::string> vecId; if(oXMLParser.GetXPathAttrVal("/"+SVC_GROUP_ROOT+"/Group",GROUP_ID, vecId) != 0) { fprintf(stderr,"GetXPathAttrVal[vecId] Failed!\n"); return -1; } std::vector<std::string> vecFrontKey; if(oXMLParser.GetXPathAttrVal("/"+SVC_GROUP_ROOT+"/Group",FRONT_MSGQ_KEY, vecFrontKey) != 0) { fprintf(stderr,"GetXPathAttrVal[vecFrontKey] Failed!\n"); return -1; } std::vector<std::string> vecBackKey; if(oXMLParser.GetXPathAttrVal("/"+SVC_GROUP_ROOT+"/Group",BACK_MSGQ_KEY, vecBackKey) != 0) { fprintf(stderr,"GetXPathAttrVal[vecBackKey] Failed!\n"); return -1; } std::vector<std::string> vecSize; if(oXMLParser.GetXPathAttrVal("/"+SVC_GROUP_ROOT+"/Group",GROUP_SIZE, vecSize) != 0) { fprintf(stderr,"GetXPathAttrVal[vecSize] Failed!\n"); return -1; } if(vecName.size()!=vecId.size() || vecName.size()!=vecFrontKey.size() || vecName.size()!=vecBackKey.size() || vecName.size()!=vecSize.size()) { fprintf(stderr,"Attribue [Name] size no match [ID]/[FrontMsgQKey]/[BackMsgQKey/[Size]\n"); return -1; } for(int i=vecId.size()-1;i>=0;i--) { LRTrim(vecName[i]); LRTrim(vecId[i]); LRTrim(vecFrontKey[i]); LRTrim(vecBackKey[i]); LRTrim(vecSize[i]); std::string sGroupId = vecId[i]+"0000"; if(dwGroupid==HexStr2Int(sGroupId)) return MakeRouteInfo(vecId[i], vecFrontKey[i], vecBackKey[i], vecSize[i], vecName[i]); } return 0; } /*//ºÍback_netioÖеÄgetRouteTypeÒ»Ö£¬½öÓÃÓÚÄ£µ÷Éϱ¨ uint32_t CConfigLoader::getRouteType(std::string& sRoute) { std::transform(sRoute.begin(), sRoute.end(), sRoute.begin(), ::tolower); uint32_t dwRouteType = 0; if (sRoute == "mod") { dwRouteType = ROUTE_TYPE_MOD; } else if (sRoute == "l5") { dwRouteType = ROUTE_TYPE_L5; } else if (sRoute == "ca" || sRoute == "byca") { dwRouteType = ROUTE_TYPE_BYCA; } else { dwRouteType = ROUTE_TYPE_MOD_AND_L5; } return dwRouteType; } //ºÍback_netioÖÐCAPP->getRouteByCmdÒ»Ñù£¬½öÓÃÓÚÄ£µ÷Éϱ¨ uint32_t CConfigLoader::getRouteByCmd(uint32_t dwCommand) { dwCommand = dwCommand & 0xFFFF0000; GroupTcpCmdRouteMap_T::iterator it = m_mapTcpCmdRoute.find(dwCommand); if (it != m_mapTcpCmdRoute.end()) { return it->second; } else { return ROUTE_TYPE_MOD_AND_L5; } }*/ ///////////////////////////////////////////// // Uitls uint32_t HexStr2Int(const std::string& sHexStr) // "0x00a10000" --> 10551296L { std::string::const_iterator it = sHexStr.begin() + 2; uint32_t dwResult = 0; uint32_t dwVal = 0; uint8_t cVal = 0; for(; it != sHexStr.end(); ++it) { cVal = *it; if(cVal >= '0' && cVal <= '9') { dwVal = cVal - '0'; } else if(cVal >= 'a' && cVal <= 'f') { dwVal = cVal - 'a' + 10; } else if(cVal >= 'A' && cVal <= 'F') { dwVal = cVal - 'A' + 10; } else return 0; // Invalid HexStr dwResult = dwResult * 16 + dwVal; } return dwResult; } void LRTrim(std::string& sValue) { char chSpace = ' '; char chTab = '\t'; std::string::const_iterator it1, it2; for(it1 = sValue.begin(); it1 != sValue.end(); it1++) { if(*it1 != chSpace && *it1 != chTab) break; } it2 = sValue.end() - 1; if(it2 == it1) { it2 = sValue.end(); } else { for(; it2 >= it1; it2--) { if(*it2 != chSpace && *it2 != chTab) { it2++; break; } } } sValue = std::string(it1, it2); } bool IsDigit(const std::string& sDigit) { if(sDigit.length() == 0) return false; for(std::string::const_iterator it = sDigit.begin() ; it != sDigit.end(); ++it) { char cVal = *it; if(!isdigit(cVal)) return false; } return true; } void SpliteStrings(std::string& sStr, std::vector<std::string>& VecStrs) { std::string::const_iterator itItemStart; std::string::size_type itStartPos, itEndPos; char cDelima = ';'; std::string sDelima = ";"; // Append Delima if need if(*(sStr.rbegin()) != cDelima) sStr += sDelima; itStartPos = 0; itItemStart = sStr.begin(); std::string sTmp; while(1) { itEndPos = sStr.find_first_of(cDelima, itStartPos); if(itEndPos == std::string::npos) { break; } sTmp = std::string( itItemStart + itStartPos, itItemStart + itEndPos); itStartPos = itEndPos + 1; if(sTmp.length() == 0) // No strValue between two Delimas { continue; } LRTrim(sTmp); VecStrs.push_back(sTmp); } } /* char * _ConvertEnc(char* encFrom, char* encTo, const char* in) { if(in == NULL) return NULL; static char bufout[1024], *sin, *sout; int lenin, lenout, ret = 0; iconv_t c_pt; if((c_pt = iconv_open(encTo, encFrom)) == (iconv_t)-1) { printf("iconv_open false: %s ==¡µ %s\n", encFrom, encTo); return NULL; } iconv(c_pt, NULL, NULL, NULL, NULL); lenin = strlen(in); sin = (char *)in; char* clean_in = sin; lenin = strlen(clean_in) + 1; lenout = 1024; sout = bufout; ret = iconv(c_pt, &clean_in, (size_t *)&lenin, &sout, (size_t *)&lenout); iconv_close(c_pt); if(ret == -1) { return "***"; } return bufout; } */
kuroroyoung/c2c_proj
netframework/netplatform/container3/src/config_loader.cpp
C++
apache-2.0
43,819
$(function() { $("#remarkButton").click(function() { var remark = $("#remark").val().trim(); if (remark == "") { return false; } var tokenId = $("#tokenId").val(); var patientId = $("#patientId").val(); var request = { text: remark }; $.ajax("/api/secure/remarks/new", { method: "POST", headers: { 'X-IPED-TOKEN-ID': tokenId, 'X-IPED-PATIENT-ID': patientId, }, data: {parameter: JSON.stringify(request)}, dataType: "json", success: function(response) { location.reload(); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert('送信に失敗しました'); }, }); return false; }); });
nakaken0629/iped
server/src/main/webapp/web/js/meeting.js
JavaScript
apache-2.0
748
package com.selenium.sample.main; import org.testng.annotations.Test; import com.jt.selenium.testng.SeleniumTestNG; import com.selenium.sample.page.GoogleSearch; /** * This is a very simple sample test to verify the project is run correctly. * * This class illustrates how to use PageObjects within a Java Test class. It is * run via XML, simply running this test standalone will not work as the * framework requires extra data that only the XML can provide. * * @author Dave.Hampton * */ public class SampleTest extends SeleniumTestNG { @Test public void test() throws Exception { /** * This is calling a PageObject and delegates the testing to it. */ GoogleSearch googleSearch = new GoogleSearch(test); googleSearch.openGoogle(); googleSearch.typeValue("RDF Group"); googleSearch.checkResult("Offering a complete portfolio of IT services"); } }
SeleniumJT/seleniumjt
src/test/java/com/selenium/sample/main/SampleTest.java
Java
apache-2.0
883
/* * Copyright 2014-2019 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 * * 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 org.springframework.session.data.redis; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.springframework.data.redis.core.ReactiveHashOperations; import org.springframework.data.redis.core.ReactiveRedisOperations; import org.springframework.session.MapSession; import org.springframework.session.SaveMode; import org.springframework.session.data.redis.ReactiveRedisSessionRepository.RedisSession; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Tests for {@link ReactiveRedisSessionRepository}. * * @author Vedran Pavic */ class ReactiveRedisSessionRepositoryTests { @SuppressWarnings("unchecked") private ReactiveRedisOperations<String, Object> redisOperations = mock(ReactiveRedisOperations.class); @SuppressWarnings("unchecked") private ReactiveHashOperations<String, Object, Object> hashOperations = mock(ReactiveHashOperations.class); @SuppressWarnings("unchecked") private ArgumentCaptor<Map<String, Object>> delta = ArgumentCaptor.forClass(Map.class); private ReactiveRedisSessionRepository repository; private MapSession cached; @BeforeEach void setUp() { this.repository = new ReactiveRedisSessionRepository(this.redisOperations); this.cached = new MapSession(); this.cached.setId("session-id"); this.cached.setCreationTime(Instant.ofEpochMilli(1404360000000L)); this.cached.setLastAccessedTime(Instant.ofEpochMilli(1404360000000L)); } @Test void constructorWithNullReactiveRedisOperations() { assertThatIllegalArgumentException().isThrownBy(() -> new ReactiveRedisSessionRepository(null)) .withMessageContaining("sessionRedisOperations cannot be null"); } @Test void customRedisKeyNamespace() { this.repository.setRedisKeyNamespace("test"); assertThat(ReflectionTestUtils.getField(this.repository, "namespace")).isEqualTo("test:"); } @Test void nullRedisKeyNamespace() { assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setRedisKeyNamespace(null)) .withMessage("namespace cannot be null or empty"); } @Test void emptyRedisKeyNamespace() { assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setRedisKeyNamespace("")) .withMessage("namespace cannot be null or empty"); } @Test void customMaxInactiveInterval() { this.repository.setDefaultMaxInactiveInterval(600); assertThat(ReflectionTestUtils.getField(this.repository, "defaultMaxInactiveInterval")).isEqualTo(600); } @Test void createSessionDefaultMaxInactiveInterval() { StepVerifier.create(this.repository.createSession()) .consumeNextWith((session) -> assertThat(session.getMaxInactiveInterval()) .isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS))) .verifyComplete(); } @Test void createSessionCustomMaxInactiveInterval() { this.repository.setDefaultMaxInactiveInterval(600); StepVerifier.create(this.repository.createSession()) .consumeNextWith( (session) -> assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(600))) .verifyComplete(); } @Test void saveNewSession() { given(this.redisOperations.opsForHash()).willReturn(this.hashOperations); given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true)); given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true)); RedisSession newSession = this.repository.new RedisSession(new MapSession(), true); StepVerifier.create(this.repository.save(newSession)).verifyComplete(); verify(this.redisOperations).opsForHash(); verify(this.hashOperations).putAll(anyString(), this.delta.capture()); verify(this.redisOperations).expire(anyString(), any()); verifyNoMoreInteractions(this.redisOperations); verifyNoMoreInteractions(this.hashOperations); Map<String, Object> delta = this.delta.getAllValues().get(0); assertThat(delta.size()).isEqualTo(3); assertThat(delta.get(RedisSessionMapper.CREATION_TIME_KEY)) .isEqualTo(newSession.getCreationTime().toEpochMilli()); assertThat(delta.get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY)) .isEqualTo((int) newSession.getMaxInactiveInterval().getSeconds()); assertThat(delta.get(RedisSessionMapper.LAST_ACCESSED_TIME_KEY)) .isEqualTo(newSession.getLastAccessedTime().toEpochMilli()); } @Test void saveSessionNothingChanged() { given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true)); given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true)); RedisSession session = this.repository.new RedisSession(this.cached, false); StepVerifier.create(this.repository.save(session)).verifyComplete(); verify(this.redisOperations).hasKey(anyString()); verifyNoMoreInteractions(this.redisOperations); verifyNoMoreInteractions(this.hashOperations); } @Test void saveLastAccessChanged() { given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true)); given(this.redisOperations.opsForHash()).willReturn(this.hashOperations); given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true)); given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true)); RedisSession session = this.repository.new RedisSession(this.cached, false); session.setLastAccessedTime(Instant.ofEpochMilli(12345678L)); StepVerifier.create(this.repository.save(session)).verifyComplete(); verify(this.redisOperations).hasKey(anyString()); verify(this.redisOperations).opsForHash(); verify(this.hashOperations).putAll(anyString(), this.delta.capture()); verify(this.redisOperations).expire(anyString(), any()); verifyNoMoreInteractions(this.redisOperations); verifyNoMoreInteractions(this.hashOperations); assertThat(this.delta.getAllValues().get(0)).isEqualTo( map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, session.getLastAccessedTime().toEpochMilli())); } @Test void saveSetAttribute() { given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true)); given(this.redisOperations.opsForHash()).willReturn(this.hashOperations); given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true)); given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true)); String attrName = "attrName"; RedisSession session = this.repository.new RedisSession(this.cached, false); session.setAttribute(attrName, "attrValue"); StepVerifier.create(this.repository.save(session)).verifyComplete(); verify(this.redisOperations).hasKey(anyString()); verify(this.redisOperations).opsForHash(); verify(this.hashOperations).putAll(anyString(), this.delta.capture()); verify(this.redisOperations).expire(anyString(), any()); verifyNoMoreInteractions(this.redisOperations); verifyNoMoreInteractions(this.hashOperations); assertThat(this.delta.getAllValues().get(0)).isEqualTo( map(RedisIndexedSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName))); } @Test void saveRemoveAttribute() { given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true)); given(this.redisOperations.opsForHash()).willReturn(this.hashOperations); given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true)); given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true)); String attrName = "attrName"; RedisSession session = this.repository.new RedisSession(new MapSession(), false); session.removeAttribute(attrName); StepVerifier.create(this.repository.save(session)).verifyComplete(); verify(this.redisOperations).hasKey(anyString()); verify(this.redisOperations).opsForHash(); verify(this.hashOperations).putAll(anyString(), this.delta.capture()); verify(this.redisOperations).expire(anyString(), any()); verifyNoMoreInteractions(this.redisOperations); verifyNoMoreInteractions(this.hashOperations); assertThat(this.delta.getAllValues().get(0)) .isEqualTo(map(RedisIndexedSessionRepository.getSessionAttrNameKey(attrName), null)); } @Test void redisSessionGetAttributes() { String attrName = "attrName"; RedisSession session = this.repository.new RedisSession(this.cached, false); assertThat(session.getAttributeNames()).isEmpty(); session.setAttribute(attrName, "attrValue"); assertThat(session.getAttributeNames()).containsOnly(attrName); session.removeAttribute(attrName); assertThat(session.getAttributeNames()).isEmpty(); } @Test void delete() { given(this.redisOperations.delete(anyString())).willReturn(Mono.just(1L)); StepVerifier.create(this.repository.deleteById("test")).verifyComplete(); verify(this.redisOperations).delete(anyString()); verifyNoMoreInteractions(this.redisOperations); verifyNoMoreInteractions(this.hashOperations); } @Test void getSessionNotFound() { given(this.redisOperations.opsForHash()).willReturn(this.hashOperations); given(this.hashOperations.entries(anyString())).willReturn(Flux.empty()); given(this.redisOperations.delete(anyString())).willReturn(Mono.just(0L)); StepVerifier.create(this.repository.findById("test")).verifyComplete(); verify(this.redisOperations).opsForHash(); verify(this.hashOperations).entries(anyString()); verify(this.redisOperations).delete(anyString()); verifyNoMoreInteractions(this.redisOperations); verifyNoMoreInteractions(this.hashOperations); } @Test @SuppressWarnings("unchecked") void getSessionFound() { given(this.redisOperations.opsForHash()).willReturn(this.hashOperations); String attribute1 = "attribute1"; String attribute2 = "attribute2"; MapSession expected = new MapSession("test"); expected.setLastAccessedTime(Instant.now().minusSeconds(60)); expected.setAttribute(attribute1, "test"); expected.setAttribute(attribute2, null); Map map = map(RedisSessionMapper.ATTRIBUTE_PREFIX + attribute1, expected.getAttribute(attribute1), RedisSessionMapper.ATTRIBUTE_PREFIX + attribute2, expected.getAttribute(attribute2), RedisSessionMapper.CREATION_TIME_KEY, expected.getCreationTime().toEpochMilli(), RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) expected.getMaxInactiveInterval().getSeconds(), RedisSessionMapper.LAST_ACCESSED_TIME_KEY, expected.getLastAccessedTime().toEpochMilli()); given(this.hashOperations.entries(anyString())).willReturn(Flux.fromIterable(map.entrySet())); StepVerifier.create(this.repository.findById("test")).consumeNextWith((session) -> { verify(this.redisOperations).opsForHash(); verify(this.hashOperations).entries(anyString()); verifyNoMoreInteractions(this.redisOperations); verifyNoMoreInteractions(this.hashOperations); assertThat(session.getId()).isEqualTo(expected.getId()); assertThat(session.getAttributeNames()).isEqualTo(expected.getAttributeNames()); assertThat(session.<String>getAttribute(attribute1)).isEqualTo(expected.getAttribute(attribute1)); assertThat(session.<String>getAttribute(attribute2)).isEqualTo(expected.getAttribute(attribute2)); assertThat(session.getCreationTime().truncatedTo(ChronoUnit.MILLIS)) .isEqualTo(expected.getCreationTime().truncatedTo(ChronoUnit.MILLIS)); assertThat(session.getMaxInactiveInterval()).isEqualTo(expected.getMaxInactiveInterval()); assertThat(session.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS)) .isEqualTo(expected.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS)); }).verifyComplete(); } @Test @SuppressWarnings("unchecked") void getSessionExpired() { given(this.redisOperations.opsForHash()).willReturn(this.hashOperations); Map map = map(RedisSessionMapper.CREATION_TIME_KEY, 0L, RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1, RedisSessionMapper.LAST_ACCESSED_TIME_KEY, Instant.now().minus(5, ChronoUnit.MINUTES).toEpochMilli()); given(this.hashOperations.entries(anyString())).willReturn(Flux.fromIterable(map.entrySet())); given(this.redisOperations.delete(anyString())).willReturn(Mono.just(0L)); StepVerifier.create(this.repository.findById("test")).verifyComplete(); verify(this.redisOperations).opsForHash(); verify(this.hashOperations).entries(anyString()); verify(this.redisOperations).delete(anyString()); verifyNoMoreInteractions(this.redisOperations); verifyNoMoreInteractions(this.hashOperations); } @Test // gh-1120 void getAttributeNamesAndRemove() { RedisSession session = this.repository.new RedisSession(this.cached, false); session.setAttribute("attribute1", "value1"); session.setAttribute("attribute2", "value2"); for (String attributeName : session.getAttributeNames()) { session.removeAttribute(attributeName); } assertThat(session.getAttributeNames()).isEmpty(); } @Test void saveWithSaveModeOnSetAttribute() { given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true)); given(this.redisOperations.opsForHash()).willReturn(this.hashOperations); given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true)); given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true)); this.repository.setSaveMode(SaveMode.ON_SET_ATTRIBUTE); MapSession delegate = new MapSession(); delegate.setAttribute("attribute1", "value1"); delegate.setAttribute("attribute2", "value2"); delegate.setAttribute("attribute3", "value3"); RedisSession session = this.repository.new RedisSession(delegate, false); session.getAttribute("attribute2"); session.setAttribute("attribute3", "value4"); StepVerifier.create(this.repository.save(session)).verifyComplete(); verify(this.redisOperations).hasKey(anyString()); verify(this.redisOperations).opsForHash(); verify(this.hashOperations).putAll(anyString(), this.delta.capture()); assertThat(this.delta.getValue()).hasSize(1); verify(this.redisOperations).expire(anyString(), any()); verifyNoMoreInteractions(this.redisOperations); verifyNoMoreInteractions(this.hashOperations); } @Test void saveWithSaveModeOnGetAttribute() { given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true)); given(this.redisOperations.opsForHash()).willReturn(this.hashOperations); given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true)); given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true)); this.repository.setSaveMode(SaveMode.ON_GET_ATTRIBUTE); MapSession delegate = new MapSession(); delegate.setAttribute("attribute1", "value1"); delegate.setAttribute("attribute2", "value2"); delegate.setAttribute("attribute3", "value3"); RedisSession session = this.repository.new RedisSession(delegate, false); session.getAttribute("attribute2"); session.setAttribute("attribute3", "value4"); StepVerifier.create(this.repository.save(session)).verifyComplete(); verify(this.redisOperations).hasKey(anyString()); verify(this.redisOperations).opsForHash(); verify(this.hashOperations).putAll(anyString(), this.delta.capture()); assertThat(this.delta.getValue()).hasSize(2); verify(this.redisOperations).expire(anyString(), any()); verifyNoMoreInteractions(this.redisOperations); verifyNoMoreInteractions(this.hashOperations); } @Test void saveWithSaveModeAlways() { given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true)); given(this.redisOperations.opsForHash()).willReturn(this.hashOperations); given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true)); given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true)); this.repository.setSaveMode(SaveMode.ALWAYS); MapSession delegate = new MapSession(); delegate.setAttribute("attribute1", "value1"); delegate.setAttribute("attribute2", "value2"); delegate.setAttribute("attribute3", "value3"); RedisSession session = this.repository.new RedisSession(delegate, false); session.getAttribute("attribute2"); session.setAttribute("attribute3", "value4"); StepVerifier.create(this.repository.save(session)).verifyComplete(); verify(this.redisOperations).hasKey(anyString()); verify(this.redisOperations).opsForHash(); verify(this.hashOperations).putAll(anyString(), this.delta.capture()); assertThat(this.delta.getValue()).hasSize(3); verify(this.redisOperations).expire(anyString(), any()); verifyNoMoreInteractions(this.redisOperations); verifyNoMoreInteractions(this.hashOperations); } private Map<String, Object> map(Object... objects) { Map<String, Object> result = new HashMap<>(); if (objects == null) { return result; } for (int i = 0; i < objects.length; i += 2) { result.put((String) objects[i], objects[i + 1]); } return result; } }
vpavic/spring-session
spring-session-data-redis/src/test/java/org/springframework/session/data/redis/ReactiveRedisSessionRepositoryTests.java
Java
apache-2.0
17,979
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.jms.server; import java.util.List; import java.util.Set; import org.apache.activemq.artemis.api.jms.JMSFactoryType; import org.apache.activemq.artemis.core.security.Role; import org.apache.activemq.artemis.core.server.ActiveMQComponent; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.apache.activemq.artemis.jms.server.config.ConnectionFactoryConfiguration; import org.apache.activemq.artemis.spi.core.naming.BindingRegistry; /** * The JMS Management interface. */ public interface JMSServerManager extends ActiveMQComponent { String getVersion(); /** * Has the Server been started. * * @return true if the server us running */ @Override boolean isStarted(); /** * Creates a JMS Queue. * * @param queueName The name of the queue to create * @param selectorString * @param durable * @return true if the queue is created or if it existed and was added to * the Binding Registry * @throws Exception if problems were encountered creating the queue. */ boolean createQueue(boolean storeConfig, String queueName, String selectorString, boolean durable, String... bindings) throws Exception; boolean addTopicToBindingRegistry(final String topicName, final String binding) throws Exception; boolean addQueueToBindingRegistry(final String queueName, final String binding) throws Exception; boolean addConnectionFactoryToBindingRegistry(final String name, final String binding) throws Exception; /** * Creates a JMS Topic * * @param topicName the name of the topic * @param bindings the names of the binding for the Binding Registry or BindingRegistry * @return true if the topic was created or if it existed and was added to * the Binding Registry * @throws Exception if a problem occurred creating the topic */ boolean createTopic(boolean storeConfig, String topicName, String... bindings) throws Exception; /** * Remove the topic from the Binding Registry or BindingRegistry. * Calling this method does <em>not</em> destroy the destination. * * @param name the name of the destination to remove from the BindingRegistry * @return true if removed * @throws Exception if a problem occurred removing the destination */ boolean removeTopicFromBindingRegistry(String name, String binding) throws Exception; /** * Remove the topic from the BindingRegistry. * Calling this method does <em>not</em> destroy the destination. * * @param name the name of the destination to remove from the BindingRegistry * @return true if removed * @throws Exception if a problem occurred removing the destination */ boolean removeTopicFromBindingRegistry(String name) throws Exception; /** * Remove the queue from the BindingRegistry. * Calling this method does <em>not</em> destroy the destination. * * @param name the name of the destination to remove from the BindingRegistry * @return true if removed * @throws Exception if a problem occurred removing the destination */ boolean removeQueueFromBindingRegistry(String name, String binding) throws Exception; /** * Remove the queue from the BindingRegistry. * Calling this method does <em>not</em> destroy the destination. * * @param name the name of the destination to remove from the BindingRegistry * @return true if removed * @throws Exception if a problem occurred removing the destination */ boolean removeQueueFromBindingRegistry(String name) throws Exception; boolean removeConnectionFactoryFromBindingRegistry(String name, String binding) throws Exception; boolean removeConnectionFactoryFromBindingRegistry(String name) throws Exception; /** * destroys a queue and removes it from the BindingRegistry * * @param name the name of the queue to destroy * @return true if destroyed * @throws Exception if a problem occurred destroying the queue */ boolean destroyQueue(String name) throws Exception; /** * destroys a queue and removes it from the BindingRegistry. * disconnects any consumers connected to the queue. * * @param name the name of the queue to destroy * @return true if destroyed * @throws Exception if a problem occurred destroying the queue */ boolean destroyQueue(String name, boolean removeConsumers) throws Exception; String[] getBindingsOnQueue(String queue); String[] getBindingsOnTopic(String topic); String[] getBindingsOnConnectionFactory(String factoryName); /** * destroys a topic and removes it from the BindingRegistry * * @param name the name of the topic to destroy * @return true if the topic was destroyed * @throws Exception if a problem occurred destroying the topic */ boolean destroyTopic(String name, boolean removeConsumers) throws Exception; /** * destroys a topic and removes it from theBindingRegistry * * @param name the name of the topic to destroy * @return true if the topic was destroyed * @throws Exception if a problem occurred destroying the topic */ boolean destroyTopic(String name) throws Exception; /** * Call this method to have a CF rebound to the Binding Registry and stored on the Journal * * @throws Exception */ ActiveMQConnectionFactory recreateCF(String name, ConnectionFactoryConfiguration cf) throws Exception; void createConnectionFactory(String name, boolean ha, JMSFactoryType cfType, String discoveryGroupName, String... bindings) throws Exception; void createConnectionFactory(String name, boolean ha, JMSFactoryType cfType, List<String> connectorNames, String... bindings) throws Exception; void createConnectionFactory(String name, boolean ha, JMSFactoryType cfType, List<String> connectorNames, String clientID, long clientFailureCheckPeriod, long connectionTTL, long callTimeout, long callFailoverTimeout, boolean cacheLargeMessagesClient, int minLargeMessageSize, boolean compressLargeMessage, int consumerWindowSize, int consumerMaxRate, int confirmationWindowSize, int producerWindowSize, int producerMaxRate, boolean blockOnAcknowledge, boolean blockOnDurableSend, boolean blockOnNonDurableSend, boolean autoGroup, boolean preAcknowledge, String loadBalancingPolicyClassName, int transactionBatchSize, int dupsOKBatchSize, boolean useGlobalPools, int scheduledThreadPoolMaxSize, int threadPoolMaxSize, long retryInterval, double retryIntervalMultiplier, long maxRetryInterval, int reconnectAttempts, boolean failoverOnInitialConnection, String groupId, String... bindings) throws Exception; void createConnectionFactory(String name, boolean ha, JMSFactoryType cfType, String discoveryGroupName, String clientID, long clientFailureCheckPeriod, long connectionTTL, long callTimeout, long callFailoverTimeout, boolean cacheLargeMessagesClient, int minLargeMessageSize, boolean compressLargeMessages, int consumerWindowSize, int consumerMaxRate, int confirmationWindowSize, int producerWindowSize, int producerMaxRate, boolean blockOnAcknowledge, boolean blockOnDurableSend, boolean blockOnNonDurableSend, boolean autoGroup, boolean preAcknowledge, String loadBalancingPolicyClassName, int transactionBatchSize, int dupsOKBatchSize, boolean useGlobalPools, int scheduledThreadPoolMaxSize, int threadPoolMaxSize, long retryInterval, double retryIntervalMultiplier, long maxRetryInterval, int reconnectAttempts, boolean failoverOnInitialConnection, String groupId, String... bindings) throws Exception; void createConnectionFactory(boolean storeConfig, ConnectionFactoryConfiguration cfConfig, String... bindings) throws Exception; /** * destroys a connection factory. * * @param name the name of the connection factory to destroy * @return true if the connection factory was destroyed * @throws Exception if a problem occurred destroying the connection factory */ boolean destroyConnectionFactory(String name) throws Exception; String[] listRemoteAddresses() throws Exception; String[] listRemoteAddresses(String ipAddress) throws Exception; boolean closeConnectionsForAddress(String ipAddress) throws Exception; boolean closeConsumerConnectionsForAddress(String address) throws Exception; boolean closeConnectionsForUser(String address) throws Exception; String[] listConnectionIDs() throws Exception; String[] listSessions(String connectionID) throws Exception; String listPreparedTransactionDetailsAsJSON() throws Exception; String listPreparedTransactionDetailsAsHTML() throws Exception; ActiveMQServer getActiveMQServer(); void addAddressSettings(String address, AddressSettings addressSettings); AddressSettings getAddressSettings(String address); void addSecurity(String addressMatch, Set<Role> roles); Set<Role> getSecurity(final String addressMatch); BindingRegistry getRegistry(); /** * Set this property if you want JMS resources bound to a registry * * @param registry */ void setRegistry(BindingRegistry registry); }
l-dobrev/activemq-artemis
artemis-jms-server/src/main/java/org/apache/activemq/artemis/jms/server/JMSServerManager.java
Java
apache-2.0
12,701
package io.kuzzle.test.security.KuzzleSecurity; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import io.kuzzle.sdk.core.Kuzzle; import io.kuzzle.sdk.core.Options; import io.kuzzle.sdk.listeners.ResponseListener; import io.kuzzle.sdk.listeners.OnQueryDoneListener; import io.kuzzle.sdk.security.Role; import io.kuzzle.sdk.security.Security; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class getRoleTest { private Kuzzle kuzzle; private Security kuzzleSecurity; private ResponseListener listener; @Before public void setUp() { kuzzle = mock(Kuzzle.class); kuzzleSecurity = new Security(kuzzle); listener = mock(ResponseListener.class); } @Test(expected = IllegalArgumentException.class) public void testGetRoleNoID() { kuzzleSecurity.fetchRole(null, listener); } @Test(expected = IllegalArgumentException.class) public void testGetRoleNoListener() { kuzzleSecurity.fetchRole("foobar", null); } @Test public void testGetRoleValid() throws JSONException { doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { JSONObject response = new JSONObject( "{" + "\"result\": {" + "\"_id\": \"foobar\"," + "\"_source\": {" + "\"indexes\": {}" + "}," + "\"_meta\": {}" + "}" + "}"); ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); ((OnQueryDoneListener) invocation.getArguments()[3]).onError(new JSONObject().put("error", "stub")); return null; } }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); kuzzleSecurity.fetchRole("foobar", null, new ResponseListener<Role>() { @Override public void onSuccess(Role response) { assertEquals(response.id, "foobar"); } @Override public void onError(JSONObject error) { try { assertEquals(error.getString("error"), "stub"); } catch (JSONException e) { throw new RuntimeException(e); } } }); ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); verify(kuzzle, times(1)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "security"); assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "getRole"); } @Test(expected = RuntimeException.class) public void testGetRoleInvalid() throws JSONException { doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); kuzzleSecurity.fetchRole("foobar", null, listener); } @Test(expected = RuntimeException.class) public void testGetRoleInvalidResponse() throws JSONException { doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { JSONObject response = new JSONObject(); ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); return null; } }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); kuzzleSecurity.fetchRole("foobar", null, listener); } }
kuzzleio/sdk-android
src/test/java/io/kuzzle/test/security/KuzzleSecurity/getRoleTest.java
Java
apache-2.0
4,070
package org.loon.framework.android.game.core.graphics.filter; import android.graphics.Bitmap; /** * Copyright 2008 - 2010 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * * @project loonframework * @author chenpeng * @email:ceponline@yahoo.com.cn * @version 0.1 */ public class ImageFilterExecute { int pixel; int index; int transparency; private Bitmap bitmap; private ImageFilter filter; public ImageFilterExecute(Bitmap bit, ImageFilter filter) { this.bitmap = bit; this.filter = filter; } /** * 过滤图片为指定效果 * * @return */ public Bitmap doFilter() { int width = bitmap.getWidth(), height = bitmap.getHeight(); int length = width * height; int pixels[] = new int[length]; bitmap.getPixels(pixels, 0, width, 0, 0, width, height); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { index = x + width * y; pixel = pixels[index]; transparency = (pixel >> 24) & 0xFF; if (transparency > 1) { pixel = filter.filterRGB(x, y, pixel); pixels[index] = pixel; } } } Bitmap dst = Bitmap.createBitmap(pixels, width, height, bitmap .getConfig()); pixels = null; return dst; } }
cping/LGame
Java/old/Canvas_ver/src/org/loon/framework/android/game/core/graphics/filter/ImageFilterExecute.java
Java
apache-2.0
1,707
// =========================================================================== // // // // Copyright 2011 Anton Dubrau and McGill University. // // // // 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 natlab.toolkits.path; import java.util.Collection; import java.util.List; import java.util.Map; import natlab.NatlabPreferences; import natlab.toolkits.filehandling.GenericFile; import com.google.common.base.Function; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; /** * This class represents an ordered set of directories that act as a Path in matlab * where files (*.m, *.mex, *.p) exist. * Does not model main, or builtins, or context. * Uses the Directory Cache to get quick access to directories. * * * TODO - move towards the folderhandler/context objects, * so all the logic of finding functions should be deprecated/removed. * This should only store the list of directories. * * @author ant6n * */ public class MatlabPath extends AbstractPathEnvironment { List<CachedDirectory> directories = Lists.newArrayList(); private boolean persistent; /** * the file extensions for matlab code files * - they are in the order of preference */ private String[] codeFileExtensions = new String[]{"m"}; /** * creates a path environment from the ';'-separated String of directories * if the persistent flag is set, the directories will be cached persistently * (i.e. they will be more quickly available during the next VM session) */ public MatlabPath(String path,boolean persistent){ super(null); this.persistent = persistent; if (path == null || path.length() == 0){ return; } //put all directories in for (String s : Splitter.on(System.getProperty("path.separator")).split(path)) { GenericFile file = GenericFile.create(s); DirectoryCache.put(file,persistent); directories.add(DirectoryCache.get(file)); } } /** * creates a path environment from the ';'-separated String of directories * this will not be cached persistently * @return */ public MatlabPath(String path){ this(path,false); } /** * creates a path from a single directory - can be used to do lookups * in current or private directories * this will not be cached persistently * @return */ public MatlabPath(GenericFile aPath){ super(null); GenericFile file = aPath; DirectoryCache.put(file,persistent); directories.add(DirectoryCache.get(file)); } /** * factory method that returns a path object represented the matlab path stored in * the natlab preferences */ public static MatlabPath getMatlabPath(){ return new MatlabPath(NatlabPreferences.getMatlabPath(),true); } /** * factory method that returns a path object represented the natlab path stored in * the natlab preferences */ public static MatlabPath getNatlabPath(){ return new MatlabPath(NatlabPreferences.getNatlabPath(),true); } /** * returns the set of directories that are overloaded for the given class name * i.e. the the directories whose parents are in the path, and whose name * is @ + className * The directories are returned as non-persistent cached directories */ public Collection<CachedDirectory> getAllOverloadedDirs(String className){ List<CachedDirectory> odirs = Lists.newArrayList(); for (CachedDirectory dir : directories){ for (String s : dir.getChildDirNames()){ if (s.equals("@"+className)){ GenericFile childDir = dir.getChild(s); DirectoryCache.put(childDir,false); odirs.add(DirectoryCache.get(childDir)); } } } return odirs; } @Override public FunctionReference getMain() { return null; } @Override public FunctionReference resolve(String name, GenericFile context) { return resolveInDirs(name,directories); } @Override public FunctionReference resolve(String name, String className, GenericFile context) { return resolveInDirs(name,getAllOverloadedDirs(className)); } public FunctionReference resolveInDirs(String name, Collection<CachedDirectory> dirs){ if (dirs == null) { return null; } for (String ext: codeFileExtensions){ for (CachedDirectory dir : dirs){ if (dir.exists()){ if (dir.getChildFileNames().contains(name+"."+ext)){ return new FunctionReference(dir.getChild(name+"."+ext)); } } } } return null; } @Override public Map<String, FunctionReference> resolveAll(String name, GenericFile context) { // TODO Auto-generated method stub return null; } @Override public Map<String, FunctionReference> getAllOverloaded(String className, GenericFile context) { Collection<CachedDirectory> oDirs = getAllOverloadedDirs(className); Map<String, FunctionReference> map = Maps.newHashMap(); for (String ext : codeFileExtensions){ for (CachedDirectory dir : oDirs){ for (String filename : dir.getChildFileNames()){ if (filename.endsWith(ext)){ String name = filename.substring(0,filename.length()-ext.length()-1); if (!map.containsKey(name)){ map.put(name, new FunctionReference(dir.getChild(filename))); } } } } } return map; } public List<FolderHandler> getAsFolderHandlerList(){ return ImmutableList.copyOf(Lists.transform(directories, new Function<CachedDirectory, FolderHandler>() { @Override public FolderHandler apply(CachedDirectory dir) { return FolderHandler.getFolderHandler(dir); } })); } }
bpilania/Comp621Project
languages/Natlab/src/natlab/toolkits/path/MatlabPath.java
Java
apache-2.0
7,765
//////////// load required libraries var url = require('url'), http = require('http'), path = require('path'), fs = require('fs'), WAMS = require(path.resolve('../../server')); // When using this example as base, make sure that this points to the correct WAMS server library path. /////////////////////////////// //////////// web server section // Set up required variables var port = process.env.PORT || 3000; var homeDir = path.resolve(process.cwd(), '.'); var stat404 = fs.readFileSync(path.join(homeDir, '/status_404.html')); // HTTP-server main function (handle incoming requests and serves files) var serverFunc = function (req, res) { var uri = url.parse(req.url).pathname; if (uri == "/") uri = "/index.html"; file = fs.readFile(path.join(homeDir, uri), function (err, data) { if (err) { // If file doesn't exist, serve 404 error. res.writeHead(404, {'Content-Type': 'text/html', 'Content-Length': stat404.length}); res.end(stat404); } else { switch (/.*\.([^\?.]*).*/.exec(uri)[1]) { // extract file type case "htm": case "html": // handler for HTML-files res.writeHead(200, {'Content-Type': 'text/html', 'Content-Length': data.length}); break; case "js": // handler for JavsScript-files res.writeHead(200, {'Content-Type': 'application/javascript', 'Content-Length': data.length}); break; default: // handler for all other file types res.writeHead(200, {'Content-Type': 'text/plain', 'Content-Length': data.length}); break; } res.end(data); } }); }; ///////////////////////// //////////// WAMS section // Set up HTTP-server: listen on port 8080 and use serverFunc (see above) to serve files to clients. var httpServer = http.createServer(serverFunc).listen(port); // Start WAMS using the HTTP-server WAMS.listen(httpServer); // Disable log-output WAMS.set('log level', 1); // Register callback onGreeting when WAMP receives "greeting"-message WAMS.on("greeting", onGreeting); function onGreeting(data) { // Upon receiving a "greeting"-message, send out a "response"-message to all clients WAMS.emit("response", "Welcome, " + data.data.from + "!"); }
scottbateman/wams.js
examples/HelloWorld/server.js
JavaScript
apache-2.0
2,213
package com.sequenceiq.environment.api.v1.platformresource.model; import java.io.Serializable; import java.util.Collection; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.sequenceiq.environment.api.v1.platformresource.PlatformResourceModelDescription; import io.swagger.annotations.ApiModelProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class PlatformDisksResponse implements Serializable { @ApiModelProperty(PlatformResourceModelDescription.DISK_TYPES) private Map<String, Collection<String>> diskTypes; @ApiModelProperty(PlatformResourceModelDescription.DEFAULT_DISKS) private Map<String, String> defaultDisks; @ApiModelProperty(PlatformResourceModelDescription.DISK_MAPPINGS) private Map<String, Map<String, String>> diskMappings; @ApiModelProperty(PlatformResourceModelDescription.DISK_DISPLAYNAMES) private Map<String, Map<String, String>> displayNames; public PlatformDisksResponse() { diskTypes = new HashMap<>(); defaultDisks = new HashMap<>(); diskMappings = new HashMap<>(); displayNames = new HashMap<>(); } public Map<String, Collection<String>> getDiskTypes() { return diskTypes; } public void setDiskTypes(Map<String, Collection<String>> diskTypes) { this.diskTypes = diskTypes; } public Map<String, String> getDefaultDisks() { return defaultDisks; } public void setDefaultDisks(Map<String, String> defaultDisks) { this.defaultDisks = defaultDisks; } public Map<String, Map<String, String>> getDiskMappings() { return diskMappings; } public void setDiskMappings(Map<String, Map<String, String>> diskMappings) { this.diskMappings = diskMappings; } public Map<String, Map<String, String>> getDisplayNames() { return displayNames; } public void setDisplayNames(Map<String, Map<String, String>> displayNames) { this.displayNames = displayNames; } @Override public String toString() { return "PlatformDisksResponse{" + "diskTypes=" + diskTypes + ", defaultDisks=" + defaultDisks + ", diskMappings=" + diskMappings + ", displayNames=" + displayNames + '}'; } }
hortonworks/cloudbreak
environment-api/src/main/java/com/sequenceiq/environment/api/v1/platformresource/model/PlatformDisksResponse.java
Java
apache-2.0
2,375
// Copyright 2016 The Periph Authors. All rights reserved. // Use of this source code is governed under the Apache License, Version 2.0 // that can be found in the LICENSE file. // led reads the state of a LED or change it. package main import ( "flag" "fmt" "os" "periph.io/x/periph/host" "periph.io/x/periph/host/sysfs" ) func mainImpl() error { flag.Parse() if _, err := host.Init(); err != nil { return err } for _, led := range sysfs.LEDs { fmt.Printf("%s: %s\n", led, led.Function()) } return nil } func main() { if err := mainImpl(); err != nil { fmt.Fprintf(os.Stderr, "led: %s.\n", err) os.Exit(1) } }
maruel/dotstar
vendor/periph.io/x/periph/cmd/led/main.go
GO
apache-2.0
637
/** * 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.pulsar.broker.auth; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.io.IOException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.function.Supplier; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.client.PulsarMockBookKeeper; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.test.PortManager; import org.apache.bookkeeper.util.ZkUtils; import org.apache.pulsar.broker.BookKeeperClientFactory; import org.apache.pulsar.broker.PulsarService; import org.apache.pulsar.broker.ServiceConfiguration; import org.apache.pulsar.broker.namespace.NamespaceService; import org.apache.pulsar.broker.service.schema.BookkeeperSchemaStorage; import org.apache.pulsar.client.admin.PulsarAdmin; import org.apache.pulsar.client.api.Authentication; import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.PulsarClient; import org.apache.pulsar.compaction.Compactor; import org.apache.pulsar.zookeeper.ZooKeeperClientFactory; import org.apache.pulsar.zookeeper.ZookeeperClientFactoryImpl; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.MockZooKeeper; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.ACL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.MoreExecutors; /** * Base class for all tests that need a Pulsar instance without a ZK and BK cluster */ public abstract class MockedPulsarServiceBaseTest { protected ServiceConfiguration conf; protected PulsarService pulsar; protected PulsarAdmin admin; protected PulsarClient pulsarClient; protected URL brokerUrl; protected URL brokerUrlTls; protected URI lookupUrl; protected final int BROKER_WEBSERVICE_PORT = PortManager.nextFreePort(); protected final int BROKER_WEBSERVICE_PORT_TLS = PortManager.nextFreePort(); protected final int BROKER_PORT = PortManager.nextFreePort(); protected final int BROKER_PORT_TLS = PortManager.nextFreePort(); protected MockZooKeeper mockZookKeeper; protected NonClosableMockBookKeeper mockBookKeeper; protected boolean isTcpLookup = false; protected final String configClusterName = "test"; private SameThreadOrderedSafeExecutor sameThreadOrderedSafeExecutor; private ExecutorService bkExecutor; public MockedPulsarServiceBaseTest() { resetConfig(); } protected void resetConfig() { this.conf = new ServiceConfiguration(); this.conf.setBrokerServicePort(BROKER_PORT); this.conf.setBrokerServicePortTls(BROKER_PORT_TLS); this.conf.setAdvertisedAddress("localhost"); this.conf.setWebServicePort(BROKER_WEBSERVICE_PORT); this.conf.setWebServicePortTls(BROKER_WEBSERVICE_PORT_TLS); this.conf.setClusterName(configClusterName); this.conf.setAdvertisedAddress("localhost"); // there are TLS tests in here, they need to use localhost because of the certificate this.conf.setManagedLedgerCacheSizeMB(8); this.conf.setActiveConsumerFailoverDelayTimeMillis(0); this.conf.setDefaultNumberOfNamespaceBundles(1); this.conf.setZookeeperServers("localhost:2181"); this.conf.setConfigurationStoreServers("localhost:3181"); } protected final void internalSetup() throws Exception { init(); lookupUrl = new URI(brokerUrl.toString()); if (isTcpLookup) { lookupUrl = new URI("pulsar://localhost:" + BROKER_PORT); } pulsarClient = PulsarClient.builder().serviceUrl(lookupUrl.toString()).statsInterval(0, TimeUnit.SECONDS).build(); } protected final void internalSetupForStatsTest() throws Exception { init(); String lookupUrl = brokerUrl.toString(); if (isTcpLookup) { lookupUrl = new URI("pulsar://localhost:" + BROKER_PORT).toString(); } pulsarClient = PulsarClient.builder().serviceUrl(lookupUrl.toString()).statsInterval(1, TimeUnit.SECONDS).build(); } protected final void init() throws Exception { sameThreadOrderedSafeExecutor = new SameThreadOrderedSafeExecutor(); bkExecutor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder().setNameFormat("mock-pulsar-bk") .setUncaughtExceptionHandler((thread, ex) -> log.info("Uncaught exception", ex)) .build()); mockZookKeeper = createMockZooKeeper(); mockBookKeeper = createMockBookKeeper(mockZookKeeper, bkExecutor); startBroker(); brokerUrl = new URL("http://" + pulsar.getAdvertisedAddress() + ":" + BROKER_WEBSERVICE_PORT); brokerUrlTls = new URL("https://" + pulsar.getAdvertisedAddress() + ":" + BROKER_WEBSERVICE_PORT_TLS); admin = spy(PulsarAdmin.builder().serviceHttpUrl(brokerUrl.toString()).build()); } protected final void internalCleanup() throws Exception { try { // if init fails, some of these could be null, and if so would throw // an NPE in shutdown, obscuring the real error if (admin != null) { admin.close(); } if (pulsarClient != null) { pulsarClient.close(); } if (pulsar != null) { pulsar.close(); } if (mockBookKeeper != null) { mockBookKeeper.reallyShutdow(); } if (mockZookKeeper != null) { mockZookKeeper.shutdown(); } if (sameThreadOrderedSafeExecutor != null) { sameThreadOrderedSafeExecutor.shutdown(); } if (bkExecutor != null) { bkExecutor.shutdown(); } } catch (Exception e) { log.warn("Failed to clean up mocked pulsar service:", e); throw e; } } protected abstract void setup() throws Exception; protected abstract void cleanup() throws Exception; protected void restartBroker() throws Exception { stopBroker(); startBroker(); } protected void stopBroker() throws Exception { pulsar.close(); // Simulate cleanup of ephemeral nodes //mockZookKeeper.delete("/loadbalance/brokers/localhost:" + pulsar.getConfiguration().getWebServicePort(), -1); } protected void startBroker() throws Exception { this.pulsar = startBroker(conf); } protected PulsarService startBroker(ServiceConfiguration conf) throws Exception { PulsarService pulsar = spy(new PulsarService(conf)); setupBrokerMocks(pulsar); boolean isAuthorizationEnabled = conf.isAuthorizationEnabled(); // enable authrorization to initialize authorization service which is used by grant-permission conf.setAuthorizationEnabled(true); pulsar.start(); conf.setAuthorizationEnabled(isAuthorizationEnabled); Compactor spiedCompactor = spy(pulsar.getCompactor()); doReturn(spiedCompactor).when(pulsar).getCompactor(); return pulsar; } protected void setupBrokerMocks(PulsarService pulsar) throws Exception { // Override default providers with mocked ones doReturn(mockZooKeeperClientFactory).when(pulsar).getZooKeeperClientFactory(); doReturn(mockBookKeeperClientFactory).when(pulsar).newBookKeeperClientFactory(); Supplier<NamespaceService> namespaceServiceSupplier = () -> spy(new NamespaceService(pulsar)); doReturn(namespaceServiceSupplier).when(pulsar).getNamespaceServiceProvider(); doReturn(sameThreadOrderedSafeExecutor).when(pulsar).getOrderedExecutor(); } public static MockZooKeeper createMockZooKeeper() throws Exception { MockZooKeeper zk = MockZooKeeper.newInstance(MoreExecutors.newDirectExecutorService()); List<ACL> dummyAclList = new ArrayList<ACL>(0); ZkUtils.createFullPathOptimistic(zk, "/ledgers/available/192.168.1.1:" + 5000, "".getBytes(ZookeeperClientFactoryImpl.ENCODING_SCHEME), dummyAclList, CreateMode.PERSISTENT); zk.create("/ledgers/LAYOUT", "1\nflat:1".getBytes(ZookeeperClientFactoryImpl.ENCODING_SCHEME), dummyAclList, CreateMode.PERSISTENT); return zk; } public static NonClosableMockBookKeeper createMockBookKeeper(ZooKeeper zookeeper, ExecutorService executor) throws Exception { return spy(new NonClosableMockBookKeeper(zookeeper, executor)); } // Prevent the MockBookKeeper instance from being closed when the broker is restarted within a test public static class NonClosableMockBookKeeper extends PulsarMockBookKeeper { public NonClosableMockBookKeeper(ZooKeeper zk, ExecutorService executor) throws Exception { super(zk, executor); } @Override public void close() throws InterruptedException, BKException { // no-op } @Override public void shutdown() { // no-op } public void reallyShutdow() { super.shutdown(); } } protected ZooKeeperClientFactory mockZooKeeperClientFactory = new ZooKeeperClientFactory() { @Override public CompletableFuture<ZooKeeper> create(String serverList, SessionType sessionType, int zkSessionTimeoutMillis) { // Always return the same instance (so that we don't loose the mock ZK content on broker restart return CompletableFuture.completedFuture(mockZookKeeper); } }; private BookKeeperClientFactory mockBookKeeperClientFactory = new BookKeeperClientFactory() { @Override public BookKeeper create(ServiceConfiguration conf, ZooKeeper zkClient) throws IOException { // Always return the same instance (so that we don't loose the mock BK content on broker restart return mockBookKeeper; } @Override public void close() { // no-op } }; public static void retryStrategically(Predicate<Void> predicate, int retryCount, long intSleepTimeInMillis) throws Exception { for (int i = 0; i < retryCount; i++) { if (predicate.test(null) || i == (retryCount - 1)) { break; } Thread.sleep(intSleepTimeInMillis + (intSleepTimeInMillis * i)); } } private static final Logger log = LoggerFactory.getLogger(MockedPulsarServiceBaseTest.class); }
jai1/pulsar
pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/MockedPulsarServiceBaseTest.java
Java
apache-2.0
11,857
package com.sekift.util; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * Xml Util */ @SuppressWarnings({"unchecked"}) public class XmlUtil { public static Map toMap(String xml) { ByteArrayInputStream sin = new ByteArrayInputStream(xml.getBytes()); return toMap(sin); } public static Map toMap(InputStream in) { try { SAXReader reader = new SAXReader(); Document doc = reader.read(in); return toMap(doc.getRootElement()); } catch (Exception ex) { throw new RuntimeException("From xml to map object case exception", ex); } } public static Map toMap(Element elem) { if (null == elem) { throw new IllegalArgumentException("Unavailable XML Element Object, can not null"); } List<Element> elems = elem.elements(); Map tar = new LinkedHashMap(); for (Element item : elems) { generateMap(tar, item); } return tar; } private static Map generateMap(Map container, Element elem) { String name = elem.getName(); Object obj = container.get(name); if (null != obj) { if (!List.class.isInstance(obj)) { List<Object> newBean = new LinkedList<Object>(); newBean.add(obj); container.put(name, newBean); generateMap(container, elem); } else { List<Object> bean = (List<Object>)obj; if (elem.isTextOnly()) { bean.add(elem.getStringValue()); } else { List<Element> subs = elem.elements(); Map nodes = new LinkedHashMap(); bean.add(nodes); for (Element item : subs) { generateMap(nodes, item); } } } return container; } if (elem.isTextOnly()) { container.put(name, elem.getStringValue()); } else { List<Element> subs = elem.elements(); Map nodes = new LinkedHashMap(); container.put(name, nodes); for (Element item : subs) { generateMap(nodes, item); } } return container; } @Deprecated public static String getXml(List rowList){ if(rowList == null || rowList.isEmpty()){ return getEmptyXml(); } StringBuilder result = new StringBuilder(); result.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?><dataset>"); Iterator it = rowList.iterator(); while(it.hasNext()){ result.append("<row>"); Map map = (Map)it.next(); Set<Map.Entry> entrys = map.entrySet(); for(Map.Entry entry:entrys){ result.append("<"+entry.getKey()+"><![CDATA["+entry.getValue() +"]]></"+entry.getKey()+">"); } result.append("</row>"); } result.append("</dataset>"); return result.toString(); } @Deprecated public static String getEmptyXml(){ return "<?xml version=\"1.0\" encoding=\"utf-8\" ?><dataset></dataset>"; } @Deprecated public static String getErrorXml(String errorMsg){ StringBuilder result = new StringBuilder(); result.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?><error_msg><![CDATA["); result.append(errorMsg); result.append("]]></error_msg>"); return result.toString(); } @Deprecated public static String getErrorXml(String errorMsg,Exception ex){ StringBuilder result = new StringBuilder(); result.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?><error_msg><![CDATA["); try { StringWriter sw = new StringWriter(); ex.printStackTrace(new PrintWriter(sw)); result.append(errorMsg); result.append(sw.toString()); sw.close(); } catch (IOException e) { e.printStackTrace(); } result.append("]]></error_msg>"); return result.toString(); } @Deprecated public static void orderBy(List rowList, String fieldSortBy, Class fieldClassType, boolean inc){ if(rowList == null || rowList.isEmpty()){ return; } Comparator comp; if(fieldClassType == int.class || fieldClassType == Integer.class){ comp = new ElementIntComparator(fieldSortBy, inc); } else { comp = new ElementStringComparator(fieldSortBy, inc); } Collections.sort(rowList, comp); } @Deprecated private static class ElementIntComparator implements Comparator { private String fieldName; private boolean inc; public ElementIntComparator(String fieldName, boolean inc){ this.fieldName = fieldName; this.inc = inc; } public int compare(Object o1, Object o2) { String f1 = (String)((Map)o1).get(fieldName); String f2 = (String)((Map)o2).get(fieldName); int if1 = 0; int if2 = 0; try{ if1 = Integer.parseInt(f1); }catch(NumberFormatException e){ return -1; } try{ if2 = Integer.parseInt(f2); }catch(NumberFormatException e){ return 1; } int result = if1 - if2; if(!inc){ result = -result; } return result; } } @Deprecated private static class ElementStringComparator implements Comparator { private String fieldName; private boolean inc; public ElementStringComparator(String fieldName, boolean inc){ this.fieldName = fieldName; this.inc = inc; } public int compare(Object o1, Object o2) { String f1 = (String)((Map)o1).get(fieldName); String f2 = (String)((Map)o2).get(fieldName); int result = f1.compareToIgnoreCase(f2); if(!inc){ result = -result; } return result; } } }
sekift/ReloadProperties
ReloadProperties/src/com/sekift/uitl/XmlUtil.java
Java
apache-2.0
5,924
// generics/LostInformation.java // (c)2017 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; class Frob {} class Fnorkle {} class Quark<Q> {} class Particle<POSITION, MOMENTUM> {} public class LostInformation { public static void main(String[] args) { List<Frob> list = new ArrayList<>(); Map<Frob, Fnorkle> map = new HashMap<>(); Quark<Fnorkle> quark = new Quark<>(); Particle<Long, Double> p = new Particle<>(); System.out.println(Arrays.toString( list.getClass().getTypeParameters())); System.out.println(Arrays.toString( map.getClass().getTypeParameters())); System.out.println(Arrays.toString( quark.getClass().getTypeParameters())); System.out.println(Arrays.toString( p.getClass().getTypeParameters())); } } /* Output: [E] [K, V] [Q] [POSITION, MOMENTUM] */
mayonghui2112/helloWorld
sourceCode/OnJava8-Examples-master/generics/LostInformation.java
Java
apache-2.0
949
/* * Copyright 2014-2019 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.guardduty.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum FindingPublishingFrequency { FIFTEEN_MINUTES("FIFTEEN_MINUTES"), ONE_HOUR("ONE_HOUR"), SIX_HOURS("SIX_HOURS"); private String value; private FindingPublishingFrequency(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return FindingPublishingFrequency corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static FindingPublishingFrequency fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (FindingPublishingFrequency enumEntry : FindingPublishingFrequency.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
jentfoo/aws-sdk-java
aws-java-sdk-guardduty/src/main/java/com/amazonaws/services/guardduty/model/FindingPublishingFrequency.java
Java
apache-2.0
1,897
/** * @license Apache-2.0 * * Copyright (c) 2018 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'; // MODULES // var bench = require( '@stdlib/bench' ); var round = require( '@stdlib/math/base/special/round' ); var randu = require( '@stdlib/random/base/randu' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var pkg = require( './../package.json' ).name; var pmf = require( './../lib' ); // MAIN // bench( pkg, function benchmark( b ) { var N; var K; var n; var x; var y; var i; b.tic(); for ( i = 0; i < b.iterations; i++ ) { x = round( randu()*10.0 ); N = round( randu()*100.0 ); K = round( randu()*N ); n = round( randu()*N ); y = pmf( x, N, K, n ); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } } b.toc(); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); }); bench( pkg+':factory', function benchmark( b ) { var mypmf; var N; var K; var n; var x; var y; var i; N = round( randu()*100.0 ); K = round( randu()*N ); n = round( randu()*N ); mypmf = pmf.factory( N, K, n ); b.tic(); for ( i = 0; i < b.iterations; i++ ) { x = round( randu()*40.0 ); y = mypmf( x ); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } } b.toc(); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); });
stdlib-js/stdlib
lib/node_modules/@stdlib/stats/base/dists/hypergeometric/pmf/benchmark/benchmark.js
JavaScript
apache-2.0
1,914
package cn.yanxi.algorithm.common; /** * Created by lcyanxi on 2019/1/13 * 给出一个排序好的数组和一个数,求数组中连续元素的和等于所给数的子数组 */ public class FindSumDemo { public static void main(String args[]){ int[] num = {1,2,2,3,4,5,6,7,8,9}; int sum = 7; findSum(num,sum); } public static void findSum(int arr[],int sum){ for (int i=0;i<arr.length;i++){ int tmp=arr[i]; String str=tmp+""; if (tmp>7){ break; } if (tmp==7){ System.out.print(tmp); } for (int j=i+1;j<arr.length;j++){ tmp=tmp+arr[j]; if (tmp<7){ tmp=tmp+arr[j]; str=str+arr[j]+""; } if (tmp==7){ System.out.println(str+arr[j]); } else { break; } } } } }
lcyanxi/dataStructure
dataStructure/src/main/java/cn/yanxi/algorithm/common/FindSumDemo.java
Java
apache-2.0
1,042
/* * Copyright 2012-2017 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.elastictranscoder.model; import javax.annotation.Generated; /** * <p> * The requested resource does not exist or is not available. For example, the pipeline to which you're trying to add a * job doesn't exist or is still being created. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ResourceNotFoundException extends com.amazonaws.services.elastictranscoder.model.AmazonElasticTranscoderException { private static final long serialVersionUID = 1L; /** * Constructs a new ResourceNotFoundException with the specified error message. * * @param message * Describes the error encountered. */ public ResourceNotFoundException(String message) { super(message); } }
dagnir/aws-sdk-java
aws-java-sdk-elastictranscoder/src/main/java/com/amazonaws/services/elastictranscoder/model/ResourceNotFoundException.java
Java
apache-2.0
1,368
/* * Copyright 2012-2017 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.waf.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * <p> * A request to create an <a>XssMatchSet</a>. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/CreateXssMatchSet" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateXssMatchSetRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * A friendly name or description for the <a>XssMatchSet</a> that you're creating. You can't change * <code>Name</code> after you create the <code>XssMatchSet</code>. * </p> */ private String name; /** * <p> * The value returned by the most recent call to <a>GetChangeToken</a>. * </p> */ private String changeToken; /** * <p> * A friendly name or description for the <a>XssMatchSet</a> that you're creating. You can't change * <code>Name</code> after you create the <code>XssMatchSet</code>. * </p> * * @param name * A friendly name or description for the <a>XssMatchSet</a> that you're creating. You can't change * <code>Name</code> after you create the <code>XssMatchSet</code>. */ public void setName(String name) { this.name = name; } /** * <p> * A friendly name or description for the <a>XssMatchSet</a> that you're creating. You can't change * <code>Name</code> after you create the <code>XssMatchSet</code>. * </p> * * @return A friendly name or description for the <a>XssMatchSet</a> that you're creating. You can't change * <code>Name</code> after you create the <code>XssMatchSet</code>. */ public String getName() { return this.name; } /** * <p> * A friendly name or description for the <a>XssMatchSet</a> that you're creating. You can't change * <code>Name</code> after you create the <code>XssMatchSet</code>. * </p> * * @param name * A friendly name or description for the <a>XssMatchSet</a> that you're creating. You can't change * <code>Name</code> after you create the <code>XssMatchSet</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateXssMatchSetRequest withName(String name) { setName(name); return this; } /** * <p> * The value returned by the most recent call to <a>GetChangeToken</a>. * </p> * * @param changeToken * The value returned by the most recent call to <a>GetChangeToken</a>. */ public void setChangeToken(String changeToken) { this.changeToken = changeToken; } /** * <p> * The value returned by the most recent call to <a>GetChangeToken</a>. * </p> * * @return The value returned by the most recent call to <a>GetChangeToken</a>. */ public String getChangeToken() { return this.changeToken; } /** * <p> * The value returned by the most recent call to <a>GetChangeToken</a>. * </p> * * @param changeToken * The value returned by the most recent call to <a>GetChangeToken</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateXssMatchSetRequest withChangeToken(String changeToken) { setChangeToken(changeToken); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getChangeToken() != null) sb.append("ChangeToken: ").append(getChangeToken()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreateXssMatchSetRequest == false) return false; CreateXssMatchSetRequest other = (CreateXssMatchSetRequest) obj; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getChangeToken() == null ^ this.getChangeToken() == null) return false; if (other.getChangeToken() != null && other.getChangeToken().equals(this.getChangeToken()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getChangeToken() == null) ? 0 : getChangeToken().hashCode()); return hashCode; } @Override public CreateXssMatchSetRequest clone() { return (CreateXssMatchSetRequest) super.clone(); } }
dagnir/aws-sdk-java
aws-java-sdk-waf/src/main/java/com/amazonaws/services/waf/model/CreateXssMatchSetRequest.java
Java
apache-2.0
6,052
/* Copyright 2016 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/core/kernels/cast_op_impl.h" namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; std::function<void(OpKernelContext*, const Tensor&, Tensor*)> GetCpuCastFromUint64(DataType dst_dtype) { CURRY_TYPES3(CAST_CASE, CPUDevice, uint64); return nullptr; } #if GOOGLE_CUDA std::function<void(OpKernelContext*, const Tensor&, Tensor*)> GetGpuCastFromUint64(DataType dst_dtype) { CURRY_TYPES3_NO_BF16(CAST_CASE, GPUDevice, uint64); return nullptr; } #endif // GOOGLE_CUDA #ifdef TENSORFLOW_USE_SYCL typedef Eigen::SyclDevice SYCLDevice; std::function<void(OpKernelContext*, const Tensor&, Tensor*)> GetSyclCastFromUint64(DataType dst_dtype) { CURRY_TYPES3_NO_HALF(CAST_CASE, SYCLDevice, uint64); return nullptr; } #endif // TENSORFLOW_USE_SYCL } // namespace tensorflow
jart/tensorflow
tensorflow/core/kernels/cast_op_impl_uint64.cc
C++
apache-2.0
1,521
#!/usr/bin/env python from __future__ import print_function try: # PY2 ip_addr = raw_input("Please enter IP address: ") except NameError: # PY3 ip_addr = input("Please enter IP address: ") ip_addr = ip_addr.split(".") print() print("{:<12} {:<12} {:<12} {:<12}".format(*ip_addr)) print()
damintote/pynet_test
string2.py
Python
apache-2.0
311
/** * 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.camel.processor.aggregate; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.camel.CamelContext; import org.apache.camel.CamelExchangeException; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.ExchangePattern; import org.apache.camel.Expression; import org.apache.camel.Navigate; import org.apache.camel.NoSuchEndpointException; import org.apache.camel.Predicate; import org.apache.camel.Processor; import org.apache.camel.impl.LoggingExceptionHandler; import org.apache.camel.impl.ServiceSupport; import org.apache.camel.processor.SendProcessor; import org.apache.camel.processor.Traceable; import org.apache.camel.spi.AggregationRepository; import org.apache.camel.spi.ExceptionHandler; import org.apache.camel.spi.RecoverableAggregationRepository; import org.apache.camel.spi.Synchronization; import org.apache.camel.util.DefaultTimeoutMap; import org.apache.camel.util.ExchangeHelper; import org.apache.camel.util.LRUCache; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.ServiceHelper; import org.apache.camel.util.StopWatch; import org.apache.camel.util.TimeUtils; import org.apache.camel.util.TimeoutMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An implementation of the <a * href="http://camel.apache.org/aggregator2.html">Aggregator</a> * pattern where a batch of messages are processed (up to a maximum amount or * until some timeout is reached) and messages for the same correlation key are * combined together using some kind of {@link AggregationStrategy} * (by default the latest message is used) to compress many message exchanges * into a smaller number of exchanges. * <p/> * A good example of this is stock market data; you may be receiving 30,000 * messages/second and you may want to throttle it right down so that multiple * messages for the same stock are combined (or just the latest message is used * and older prices are discarded). Another idea is to combine line item messages * together into a single invoice message. */ public class AggregateProcessor extends ServiceSupport implements Processor, Navigate<Processor>, Traceable { private static final Logger LOG = LoggerFactory.getLogger(AggregateProcessor.class); private final Lock lock = new ReentrantLock(); private final CamelContext camelContext; private final Processor processor; private final AggregationStrategy aggregationStrategy; private final Expression correlationExpression; private final ExecutorService executorService; private ScheduledExecutorService recoverService; // store correlation key -> exchange id in timeout map private TimeoutMap<String, String> timeoutMap; private ExceptionHandler exceptionHandler = new LoggingExceptionHandler(getClass()); private AggregationRepository aggregationRepository = new MemoryAggregationRepository(); private Map<Object, Object> closedCorrelationKeys; private Set<String> batchConsumerCorrelationKeys = new LinkedHashSet<String>(); private final Set<String> inProgressCompleteExchanges = new HashSet<String>(); private final Map<String, RedeliveryData> redeliveryState = new ConcurrentHashMap<String, RedeliveryData>(); // optional dead letter channel for exhausted recovered exchanges private Processor deadLetterProcessor; // keep booking about redelivery private class RedeliveryData { int redeliveryCounter; } // options private boolean ignoreInvalidCorrelationKeys; private Integer closeCorrelationKeyOnCompletion; private boolean parallelProcessing; // different ways to have completion triggered private boolean eagerCheckCompletion; private Predicate completionPredicate; private long completionTimeout; private Expression completionTimeoutExpression; private long completionInterval; private int completionSize; private Expression completionSizeExpression; private boolean completionFromBatchConsumer; private AtomicInteger batchConsumerCounter = new AtomicInteger(); private boolean discardOnCompletionTimeout; public AggregateProcessor(CamelContext camelContext, Processor processor, Expression correlationExpression, AggregationStrategy aggregationStrategy, ExecutorService executorService) { ObjectHelper.notNull(camelContext, "camelContext"); ObjectHelper.notNull(processor, "processor"); ObjectHelper.notNull(correlationExpression, "correlationExpression"); ObjectHelper.notNull(aggregationStrategy, "aggregationStrategy"); ObjectHelper.notNull(executorService, "executorService"); this.camelContext = camelContext; this.processor = processor; this.correlationExpression = correlationExpression; this.aggregationStrategy = aggregationStrategy; this.executorService = executorService; } @Override public String toString() { return "AggregateProcessor[to: " + processor + "]"; } public String getTraceLabel() { return "aggregate[" + correlationExpression + "]"; } public List<Processor> next() { if (!hasNext()) { return null; } List<Processor> answer = new ArrayList<Processor>(1); answer.add(processor); return answer; } public boolean hasNext() { return processor != null; } public void process(Exchange exchange) throws Exception { // compute correlation expression String key = correlationExpression.evaluate(exchange, String.class); if (ObjectHelper.isEmpty(key)) { // we have a bad correlation key if (isIgnoreInvalidCorrelationKeys()) { LOG.debug("Invalid correlation key. This Exchange will be ignored: {}", exchange); return; } else { throw new CamelExchangeException("Invalid correlation key", exchange); } } // is the correlation key closed? if (closedCorrelationKeys != null && closedCorrelationKeys.containsKey(key)) { throw new ClosedCorrelationKeyException(key, exchange); } // copy exchange, and do not share the unit of work // the aggregated output runs in another unit of work Exchange copy = ExchangeHelper.createCorrelatedCopy(exchange, false); // when memory based then its fast using synchronized, but if the aggregation repository is IO // bound such as JPA etc then concurrent aggregation per correlation key could // improve performance as we can run aggregation repository get/add in parallel lock.lock(); try { doAggregation(key, copy); } finally { lock.unlock(); } } /** * Aggregates the exchange with the given correlation key * <p/> * This method <b>must</b> be run synchronized as we cannot aggregate the same correlation key * in parallel. * * @param key the correlation key * @param exchange the exchange * @return the aggregated exchange * @throws org.apache.camel.CamelExchangeException is thrown if error aggregating */ private Exchange doAggregation(String key, Exchange exchange) throws CamelExchangeException { LOG.trace("onAggregation +++ start +++ with correlation key: {}", key); Exchange answer; Exchange oldExchange = aggregationRepository.get(exchange.getContext(), key); Exchange newExchange = exchange; Integer size = 1; if (oldExchange != null) { size = oldExchange.getProperty(Exchange.AGGREGATED_SIZE, 0, Integer.class); size++; } // check if we are complete String complete = null; if (isEagerCheckCompletion()) { // put the current aggregated size on the exchange so its avail during completion check newExchange.setProperty(Exchange.AGGREGATED_SIZE, size); complete = isCompleted(key, newExchange); // remove it afterwards newExchange.removeProperty(Exchange.AGGREGATED_SIZE); } // prepare the exchanges for aggregation and aggregate it ExchangeHelper.prepareAggregation(oldExchange, newExchange); answer = onAggregation(oldExchange, exchange); if (answer == null) { throw new CamelExchangeException("AggregationStrategy " + aggregationStrategy + " returned null which is not allowed", exchange); } // update the aggregated size answer.setProperty(Exchange.AGGREGATED_SIZE, size); // maybe we should check completion after the aggregation if (!isEagerCheckCompletion()) { complete = isCompleted(key, answer); } // only need to update aggregation repository if we are not complete if (complete == null) { LOG.trace("In progress aggregated exchange: {} with correlation key: {}", answer, key); aggregationRepository.add(exchange.getContext(), key, answer); } else { // if batch consumer completion is enabled then we need to complete the group if ("consumer".equals(complete)) { for (String batchKey : batchConsumerCorrelationKeys) { Exchange batchAnswer; if (batchKey.equals(key)) { // skip the current aggregated key as we have already aggregated it and have the answer batchAnswer = answer; } else { batchAnswer = aggregationRepository.get(camelContext, batchKey); } if (batchAnswer != null) { batchAnswer.setProperty(Exchange.AGGREGATED_COMPLETED_BY, complete); onCompletion(batchKey, batchAnswer, false); } } batchConsumerCorrelationKeys.clear(); } else { // we are complete for this exchange answer.setProperty(Exchange.AGGREGATED_COMPLETED_BY, complete); onCompletion(key, answer, false); } } LOG.trace("onAggregation +++ end +++ with correlation key: {}", key); return answer; } /** * Tests whether the given exchange is complete or not * * @param key the correlation key * @param exchange the incoming exchange * @return <tt>null</tt> if not completed, otherwise a String with the type that triggered the completion */ protected String isCompleted(String key, Exchange exchange) { if (getCompletionPredicate() != null) { boolean answer = getCompletionPredicate().matches(exchange); if (answer) { return "predicate"; } } if (getCompletionSizeExpression() != null) { Integer value = getCompletionSizeExpression().evaluate(exchange, Integer.class); if (value != null && value > 0) { int size = exchange.getProperty(Exchange.AGGREGATED_SIZE, 1, Integer.class); if (size >= value) { return "size"; } } } if (getCompletionSize() > 0) { int size = exchange.getProperty(Exchange.AGGREGATED_SIZE, 1, Integer.class); if (size >= getCompletionSize()) { return "size"; } } // timeout can be either evaluated based on an expression or from a fixed value // expression takes precedence boolean timeoutSet = false; if (getCompletionTimeoutExpression() != null) { Long value = getCompletionTimeoutExpression().evaluate(exchange, Long.class); if (value != null && value > 0) { if (LOG.isTraceEnabled()) { LOG.trace("Updating correlation key {} to timeout after {} ms. as exchange received: {}", new Object[]{key, value, exchange}); } addExchangeToTimeoutMap(key, exchange, value); timeoutSet = true; } } if (!timeoutSet && getCompletionTimeout() > 0) { // timeout is used so use the timeout map to keep an eye on this if (LOG.isTraceEnabled()) { LOG.trace("Updating correlation key {} to timeout after {} ms. as exchange received: {}", new Object[]{key, getCompletionTimeout(), exchange}); } addExchangeToTimeoutMap(key, exchange, getCompletionTimeout()); } if (isCompletionFromBatchConsumer()) { batchConsumerCorrelationKeys.add(key); batchConsumerCounter.incrementAndGet(); int size = exchange.getProperty(Exchange.BATCH_SIZE, 0, Integer.class); if (size > 0 && batchConsumerCounter.intValue() >= size) { // batch consumer is complete then reset the counter batchConsumerCounter.set(0); return "consumer"; } } // not complete return null; } protected Exchange onAggregation(Exchange oldExchange, Exchange newExchange) { return aggregationStrategy.aggregate(oldExchange, newExchange); } protected void onCompletion(final String key, final Exchange exchange, boolean fromTimeout) { // store the correlation key as property exchange.setProperty(Exchange.AGGREGATED_CORRELATION_KEY, key); // remove from repository as its completed aggregationRepository.remove(exchange.getContext(), key, exchange); if (!fromTimeout && timeoutMap != null) { // cleanup timeout map if it was a incoming exchange which triggered the timeout (and not the timeout checker) timeoutMap.remove(key); } // this key has been closed so add it to the closed map if (closedCorrelationKeys != null) { closedCorrelationKeys.put(key, key); } if (fromTimeout && isDiscardOnCompletionTimeout()) { // discard due timeout LOG.debug("Aggregation for correlation key {} discarding aggregated exchange: ()", key, exchange); // must confirm the discarded exchange aggregationRepository.confirm(exchange.getContext(), exchange.getExchangeId()); // and remove redelivery state as well redeliveryState.remove(exchange.getExchangeId()); } else { // the aggregated exchange should be published (sent out) onSubmitCompletion(key, exchange); } } private void onSubmitCompletion(final Object key, final Exchange exchange) { LOG.debug("Aggregation complete for correlation key {} sending aggregated exchange: {}", key, exchange); // add this as in progress before we submit the task inProgressCompleteExchanges.add(exchange.getExchangeId()); // send this exchange executorService.submit(new Runnable() { public void run() { LOG.debug("Processing aggregated exchange: {}", exchange); // add on completion task so we remember to update the inProgressCompleteExchanges exchange.addOnCompletion(new AggregateOnCompletion(exchange.getExchangeId())); try { processor.process(exchange); } catch (Throwable e) { exchange.setException(e); } // log exception if there was a problem if (exchange.getException() != null) { // if there was an exception then let the exception handler handle it getExceptionHandler().handleException("Error processing aggregated exchange", exchange, exchange.getException()); } else { LOG.trace("Processing aggregated exchange: {} complete.", exchange); } } }); } /** * Restores the timeout map with timeout values from the aggregation repository. * <p/> * This is needed in case the aggregator has been stopped and started again (for example a server restart). * Then the existing exchanges from the {@link AggregationRepository} must have its timeout conditions restored. */ protected void restoreTimeoutMapFromAggregationRepository() throws Exception { // grab the timeout value for each partly aggregated exchange Set<String> keys = aggregationRepository.getKeys(); if (keys == null || keys.isEmpty()) { return; } StopWatch watch = new StopWatch(); LOG.trace("Starting restoring CompletionTimeout for {} existing exchanges from the aggregation repository...", keys.size()); for (String key : keys) { Exchange exchange = aggregationRepository.get(camelContext, key); // grab the timeout value long timeout = exchange.hasProperties() ? exchange.getProperty(Exchange.AGGREGATED_TIMEOUT, 0, long.class) : 0; if (timeout > 0) { LOG.trace("Restoring CompletionTimeout for exchangeId: {} with timeout: {} millis.", exchange.getExchangeId(), timeout); addExchangeToTimeoutMap(key, exchange, timeout); } } // log duration of this task so end user can see how long it takes to pre-check this upon starting LOG.info("Restored {} CompletionTimeout conditions in the AggregationTimeoutChecker in {}", timeoutMap.size(), TimeUtils.printDuration(watch.stop())); } /** * Adds the given exchange to the timeout map, which is used by the timeout checker task to trigger timeouts. * * @param key the correlation key * @param exchange the exchange * @param timeout the timeout value in millis */ private void addExchangeToTimeoutMap(String key, Exchange exchange, long timeout) { // store the timeout value on the exchange as well, in case we need it later exchange.setProperty(Exchange.AGGREGATED_TIMEOUT, timeout); timeoutMap.put(key, exchange.getExchangeId(), timeout); } public Predicate getCompletionPredicate() { return completionPredicate; } public void setCompletionPredicate(Predicate completionPredicate) { this.completionPredicate = completionPredicate; } public boolean isEagerCheckCompletion() { return eagerCheckCompletion; } public void setEagerCheckCompletion(boolean eagerCheckCompletion) { this.eagerCheckCompletion = eagerCheckCompletion; } public long getCompletionTimeout() { return completionTimeout; } public void setCompletionTimeout(long completionTimeout) { this.completionTimeout = completionTimeout; } public Expression getCompletionTimeoutExpression() { return completionTimeoutExpression; } public void setCompletionTimeoutExpression(Expression completionTimeoutExpression) { this.completionTimeoutExpression = completionTimeoutExpression; } public long getCompletionInterval() { return completionInterval; } public void setCompletionInterval(long completionInterval) { this.completionInterval = completionInterval; } public int getCompletionSize() { return completionSize; } public void setCompletionSize(int completionSize) { this.completionSize = completionSize; } public Expression getCompletionSizeExpression() { return completionSizeExpression; } public void setCompletionSizeExpression(Expression completionSizeExpression) { this.completionSizeExpression = completionSizeExpression; } public boolean isIgnoreInvalidCorrelationKeys() { return ignoreInvalidCorrelationKeys; } public void setIgnoreInvalidCorrelationKeys(boolean ignoreInvalidCorrelationKeys) { this.ignoreInvalidCorrelationKeys = ignoreInvalidCorrelationKeys; } public Integer getCloseCorrelationKeyOnCompletion() { return closeCorrelationKeyOnCompletion; } public void setCloseCorrelationKeyOnCompletion(Integer closeCorrelationKeyOnCompletion) { this.closeCorrelationKeyOnCompletion = closeCorrelationKeyOnCompletion; } public boolean isCompletionFromBatchConsumer() { return completionFromBatchConsumer; } public void setCompletionFromBatchConsumer(boolean completionFromBatchConsumer) { this.completionFromBatchConsumer = completionFromBatchConsumer; } public ExceptionHandler getExceptionHandler() { return exceptionHandler; } public void setExceptionHandler(ExceptionHandler exceptionHandler) { this.exceptionHandler = exceptionHandler; } public boolean isParallelProcessing() { return parallelProcessing; } public void setParallelProcessing(boolean parallelProcessing) { this.parallelProcessing = parallelProcessing; } public AggregationRepository getAggregationRepository() { return aggregationRepository; } public void setAggregationRepository(AggregationRepository aggregationRepository) { this.aggregationRepository = aggregationRepository; } public boolean isDiscardOnCompletionTimeout() { return discardOnCompletionTimeout; } public void setDiscardOnCompletionTimeout(boolean discardOnCompletionTimeout) { this.discardOnCompletionTimeout = discardOnCompletionTimeout; } /** * On completion task which keeps the booking of the in progress up to date */ private final class AggregateOnCompletion implements Synchronization { private final String exchangeId; private AggregateOnCompletion(String exchangeId) { // must use the original exchange id as it could potentially change if send over SEDA etc. this.exchangeId = exchangeId; } public void onFailure(Exchange exchange) { LOG.trace("Aggregated exchange onFailure: {}", exchange); // must remember to remove in progress when we failed inProgressCompleteExchanges.remove(exchangeId); // do not remove redelivery state as we need it when we redeliver again later } public void onComplete(Exchange exchange) { LOG.trace("Aggregated exchange onComplete: {}", exchange); // only confirm if we processed without a problem try { aggregationRepository.confirm(exchange.getContext(), exchangeId); // and remove redelivery state as well redeliveryState.remove(exchangeId); } finally { // must remember to remove in progress when we are complete inProgressCompleteExchanges.remove(exchangeId); } } @Override public String toString() { return "AggregateOnCompletion"; } } /** * Background task that looks for aggregated exchanges which is triggered by completion timeouts. */ private final class AggregationTimeoutMap extends DefaultTimeoutMap<String, String> { private AggregationTimeoutMap(ScheduledExecutorService executor, long requestMapPollTimeMillis) { // do NOT use locking on the timeout map as this aggregator has its own shared lock we will use instead super(executor, requestMapPollTimeMillis, false); } @Override public void purge() { // must acquire the shared aggregation lock to be able to purge lock.lock(); try { super.purge(); } finally { lock.unlock(); } } @Override public boolean onEviction(String key, String exchangeId) { log.debug("Completion timeout triggered for correlation key: {}", key); boolean inProgress = inProgressCompleteExchanges.contains(exchangeId); if (inProgress) { LOG.trace("Aggregated exchange with id: {} is already in progress.", exchangeId); return true; } // get the aggregated exchange Exchange answer = aggregationRepository.get(camelContext, key); if (answer != null) { // indicate it was completed by timeout answer.setProperty(Exchange.AGGREGATED_COMPLETED_BY, "timeout"); onCompletion(key, answer, true); } return true; } } /** * Background task that triggers completion based on interval. */ private final class AggregationIntervalTask implements Runnable { public void run() { // only run if CamelContext has been fully started if (!camelContext.getStatus().isStarted()) { LOG.trace("Completion interval task cannot start due CamelContext({}) has not been started yet", camelContext.getName()); return; } LOG.trace("Starting completion interval task"); // trigger completion for all in the repository Set<String> keys = aggregationRepository.getKeys(); if (keys != null && !keys.isEmpty()) { // must acquire the shared aggregation lock to be able to trigger interval completion lock.lock(); try { for (String key : keys) { Exchange exchange = aggregationRepository.get(camelContext, key); if (exchange != null) { LOG.trace("Completion interval triggered for correlation key: {}", key); // indicate it was completed by interval exchange.setProperty(Exchange.AGGREGATED_COMPLETED_BY, "interval"); onCompletion(key, exchange, false); } } } finally { lock.unlock(); } } LOG.trace("Completion interval task complete"); } } /** * Background task that looks for aggregated exchanges to recover. */ private final class RecoverTask implements Runnable { private final RecoverableAggregationRepository recoverable; private RecoverTask(RecoverableAggregationRepository recoverable) { this.recoverable = recoverable; } public void run() { // only run if CamelContext has been fully started if (!camelContext.getStatus().isStarted()) { LOG.trace("Recover check cannot start due CamelContext({}) has not been started yet", camelContext.getName()); return; } LOG.trace("Starting recover check"); Set<String> exchangeIds = recoverable.scan(camelContext); for (String exchangeId : exchangeIds) { // we may shutdown while doing recovery if (!isRunAllowed()) { LOG.info("We are shutting down so stop recovering"); return; } boolean inProgress = inProgressCompleteExchanges.contains(exchangeId); if (inProgress) { LOG.trace("Aggregated exchange with id: {} is already in progress.", exchangeId); } else { LOG.debug("Loading aggregated exchange with id: {} to be recovered.", exchangeId); Exchange exchange = recoverable.recover(camelContext, exchangeId); if (exchange != null) { // get the correlation key String key = exchange.getProperty(Exchange.AGGREGATED_CORRELATION_KEY, String.class); // and mark it as redelivered exchange.getIn().setHeader(Exchange.REDELIVERED, Boolean.TRUE); // get the current redelivery data RedeliveryData data = redeliveryState.get(exchange.getExchangeId()); // if we are exhausted, then move to dead letter channel if (data != null && recoverable.getMaximumRedeliveries() > 0 && data.redeliveryCounter >= recoverable.getMaximumRedeliveries()) { LOG.warn("The recovered exchange is exhausted after " + recoverable.getMaximumRedeliveries() + " attempts, will now be moved to dead letter channel: " + recoverable.getDeadLetterUri()); // send to DLC try { // set redelivery counter exchange.getIn().setHeader(Exchange.REDELIVERY_COUNTER, data.redeliveryCounter); exchange.getIn().setHeader(Exchange.REDELIVERY_EXHAUSTED, Boolean.TRUE); deadLetterProcessor.process(exchange); } catch (Throwable e) { exchange.setException(e); } // handle if failed if (exchange.getException() != null) { getExceptionHandler().handleException("Failed to move recovered Exchange to dead letter channel: " + recoverable.getDeadLetterUri(), exchange.getException()); } else { // it was ok, so confirm after it has been moved to dead letter channel, so we wont recover it again recoverable.confirm(camelContext, exchangeId); } } else { // update current redelivery state if (data == null) { // create new data data = new RedeliveryData(); redeliveryState.put(exchange.getExchangeId(), data); } data.redeliveryCounter++; // set redelivery counter exchange.getIn().setHeader(Exchange.REDELIVERY_COUNTER, data.redeliveryCounter); if (recoverable.getMaximumRedeliveries() > 0) { exchange.getIn().setHeader(Exchange.REDELIVERY_MAX_COUNTER, recoverable.getMaximumRedeliveries()); } LOG.debug("Delivery attempt: {} to recover aggregated exchange with id: {}", data.redeliveryCounter, exchangeId); // not exhaust so resubmit the recovered exchange onSubmitCompletion(key, exchange); } } } } LOG.trace("Recover check complete"); } } @Override protected void doStart() throws Exception { if (getCompletionTimeout() <= 0 && getCompletionInterval() <= 0 && getCompletionSize() <= 0 && getCompletionPredicate() == null && !isCompletionFromBatchConsumer() && getCompletionTimeoutExpression() == null && getCompletionSizeExpression() == null) { throw new IllegalStateException("At least one of the completions options" + " [completionTimeout, completionInterval, completionSize, completionPredicate, completionFromBatchConsumer] must be set"); } if (getCloseCorrelationKeyOnCompletion() != null) { if (getCloseCorrelationKeyOnCompletion() > 0) { LOG.info("Using ClosedCorrelationKeys with a LRUCache with a capacity of " + getCloseCorrelationKeyOnCompletion()); closedCorrelationKeys = new LRUCache<Object, Object>(getCloseCorrelationKeyOnCompletion()); } else { LOG.info("Using ClosedCorrelationKeys with unbounded capacity"); closedCorrelationKeys = new HashMap<Object, Object>(); } } ServiceHelper.startServices(processor, aggregationRepository); // should we use recover checker if (aggregationRepository instanceof RecoverableAggregationRepository) { RecoverableAggregationRepository recoverable = (RecoverableAggregationRepository) aggregationRepository; if (recoverable.isUseRecovery()) { long interval = recoverable.getRecoveryIntervalInMillis(); if (interval <= 0) { throw new IllegalArgumentException("AggregationRepository has recovery enabled and the RecoveryInterval option must be a positive number, was: " + interval); } // create a background recover thread to check every interval recoverService = camelContext.getExecutorServiceStrategy().newScheduledThreadPool(this, "AggregateRecoverChecker", 1); Runnable recoverTask = new RecoverTask(recoverable); LOG.info("Using RecoverableAggregationRepository by scheduling recover checker to run every " + interval + " millis."); // use fixed delay so there is X interval between each run recoverService.scheduleWithFixedDelay(recoverTask, 1000L, interval, TimeUnit.MILLISECONDS); if (recoverable.getDeadLetterUri() != null) { int max = recoverable.getMaximumRedeliveries(); if (max <= 0) { throw new IllegalArgumentException("Option maximumRedeliveries must be a positive number, was: " + max); } LOG.info("After " + max + " failed redelivery attempts Exchanges will be moved to deadLetterUri: " + recoverable.getDeadLetterUri()); // dead letter uri must be a valid endpoint Endpoint endpoint = camelContext.getEndpoint(recoverable.getDeadLetterUri()); if (endpoint == null) { throw new NoSuchEndpointException(recoverable.getDeadLetterUri()); } // force MEP to be InOnly so when sending to DLQ we would not expect a reply if the MEP was InOut deadLetterProcessor = new SendProcessor(endpoint, ExchangePattern.InOnly); ServiceHelper.startService(deadLetterProcessor); } } } if (getCompletionInterval() > 0 && getCompletionTimeout() > 0) { throw new IllegalArgumentException("Only one of completionInterval or completionTimeout can be used, not both."); } if (getCompletionInterval() > 0) { LOG.info("Using CompletionInterval to run every " + getCompletionInterval() + " millis."); ScheduledExecutorService scheduler = camelContext.getExecutorServiceStrategy().newScheduledThreadPool(this, "AggregateTimeoutChecker", 1); // trigger completion based on interval scheduler.scheduleAtFixedRate(new AggregationIntervalTask(), 1000L, getCompletionInterval(), TimeUnit.MILLISECONDS); } // start timeout service if its in use if (getCompletionTimeout() > 0 || getCompletionTimeoutExpression() != null) { LOG.info("Using CompletionTimeout to trigger after " + getCompletionTimeout() + " millis of inactivity."); ScheduledExecutorService scheduler = camelContext.getExecutorServiceStrategy().newScheduledThreadPool(this, "AggregateTimeoutChecker", 1); // check for timed out aggregated messages once every second timeoutMap = new AggregationTimeoutMap(scheduler, 1000L); // fill in existing timeout values from the aggregation repository, for example if a restart occurred, then we // need to re-establish the timeout map so timeout can trigger restoreTimeoutMapFromAggregationRepository(); ServiceHelper.startService(timeoutMap); } } @Override protected void doStop() throws Exception { if (recoverService != null) { camelContext.getExecutorServiceStrategy().shutdownNow(recoverService); } ServiceHelper.stopServices(timeoutMap, processor, deadLetterProcessor); if (closedCorrelationKeys != null) { // it may be a service so stop it as well ServiceHelper.stopService(closedCorrelationKeys); closedCorrelationKeys.clear(); } batchConsumerCorrelationKeys.clear(); redeliveryState.clear(); } @Override protected void doShutdown() throws Exception { // shutdown aggregation repository ServiceHelper.stopService(aggregationRepository); // cleanup when shutting down inProgressCompleteExchanges.clear(); super.doShutdown(); } }
chicagozer/rheosoft
camel-core/src/main/java/org/apache/camel/processor/aggregate/AggregateProcessor.java
Java
apache-2.0
38,611
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.console.parsing; import com.intellij.lang.PsiBuilder; import com.jetbrains.python.PyElementTypes; import com.jetbrains.python.PyTokenTypes; import com.jetbrains.python.parsing.ExpressionParsing; import com.jetbrains.python.parsing.ParsingContext; import com.jetbrains.python.parsing.StatementParsing; import com.jetbrains.python.psi.LanguageLevel; import org.jetbrains.annotations.Nullable; /** * @author traff */ public class PyConsoleParsingContext extends ParsingContext { private final StatementParsing stmtParser; private final ExpressionParsing expressionParser; public PyConsoleParsingContext(final PsiBuilder builder, LanguageLevel languageLevel, StatementParsing.FUTURE futureFlag, PythonConsoleData pythonConsoleData, boolean startsWithIPythonSymbol) { super(builder, languageLevel, futureFlag); stmtParser = new ConsoleStatementParsing(this, futureFlag, startsWithIPythonSymbol, pythonConsoleData); if (pythonConsoleData.isIPythonEnabled()) { expressionParser = new ConsoleExpressionParsing(this); } else { expressionParser = new ExpressionParsing(this); } } @Override public StatementParsing getStatementParser() { return stmtParser; } @Override public ExpressionParsing getExpressionParser() { return expressionParser; } public static class ConsoleStatementParsing extends StatementParsing { private final boolean myStartsWithIPythonSymbol; private final PythonConsoleData myPythonConsoleData; protected ConsoleStatementParsing(ParsingContext context, @Nullable FUTURE futureFlag, boolean startsWithIPythonSymbol, PythonConsoleData pythonConsoleData) { super(context, futureFlag); myStartsWithIPythonSymbol = startsWithIPythonSymbol; myPythonConsoleData = pythonConsoleData; } @Override public void parseStatement() { if (parseIPythonHelp()) { return; } if (myStartsWithIPythonSymbol) { parseIPythonCommand(); } else { if (myPythonConsoleData.isIPythonEnabled()) { if (myPythonConsoleData.isIPythonAutomagic()) { if (myPythonConsoleData.isMagicCommand(myBuilder.getTokenText())) { parseIPythonCommand(); } } } if (myPythonConsoleData.getIndentSize() > 0) { if (myBuilder.getTokenType() == PyTokenTypes.INDENT) { myBuilder.advanceLexer(); } } super.parseStatement(); } } private boolean parseIPythonHelp() { return parseIPythonGlobalHelp() || parseIPythonSuffixHelp(); } /** * Parse statements consisting of the single question mark. */ private boolean parseIPythonGlobalHelp() { PsiBuilder.Marker ipythonHelp = myBuilder.mark(); if (myBuilder.getTokenType() == PyConsoleTokenTypes.QUESTION_MARK) { myBuilder.advanceLexer(); if (myBuilder.getTokenType() == PyTokenTypes.STATEMENT_BREAK || myBuilder.eof()) { ipythonHelp.done(PyElementTypes.EMPTY_EXPRESSION); myBuilder.advanceLexer(); return true; } } ipythonHelp.rollbackTo(); return false; } /** * Parse statements ending with a question mark. */ private boolean parseIPythonSuffixHelp() { PsiBuilder.Marker ipythonHelp = myBuilder.mark(); while (myBuilder.getTokenType() != PyTokenTypes.STATEMENT_BREAK && myBuilder.getTokenType() != PyTokenTypes.LINE_BREAK && !myBuilder.eof() ) { myBuilder.advanceLexer(); } if (myBuilder.rawLookup(-1) != PyConsoleTokenTypes.QUESTION_MARK) { ipythonHelp.rollbackTo(); return false; } int lookupIndex = -2; if (myBuilder.rawLookup(lookupIndex) == PyConsoleTokenTypes.QUESTION_MARK) { --lookupIndex; } if (myBuilder.rawLookup(lookupIndex) == PyTokenTypes.MULT) { ipythonHelp.rollbackTo(); parseIPythonCommand(); return true; } if (myBuilder.rawLookup(lookupIndex) != PyTokenTypes.IDENTIFIER) { myBuilder.error("Help request must follow the name"); } ipythonHelp.done(PyElementTypes.EMPTY_EXPRESSION); myBuilder.advanceLexer(); return true; } private void parseIPythonCommand() { PsiBuilder.Marker ipythonCommand = myBuilder.mark(); while (!myBuilder.eof()) { myBuilder.advanceLexer(); } ipythonCommand.done(PyElementTypes.EMPTY_EXPRESSION); } } public static class ConsoleExpressionParsing extends ExpressionParsing { public ConsoleExpressionParsing(ParsingContext context) { super(context); } @Override public boolean parseExpressionOptional() { if (myBuilder.getTokenType() == PyTokenTypes.PERC || myBuilder.getTokenType() == PyConsoleTokenTypes.PLING || myBuilder.getTokenType() == PyConsoleTokenTypes.QUESTION_MARK) { PsiBuilder.Marker expr = myBuilder.mark(); PsiBuilder.Marker command = myBuilder.mark(); myBuilder.advanceLexer(); if (myBuilder.getTokenType() == PyConsoleTokenTypes.PLING) { myBuilder.advanceLexer(); } if (myBuilder.getTokenType() == PyTokenTypes.IDENTIFIER) { myBuilder.advanceLexer(); command.done(getReferenceType()); } else { expr.drop(); command.drop(); myBuilder.error("Identifier expected."); return false; } while (myBuilder.getTokenType() != null) { myBuilder.advanceLexer(); } expr.done(PyElementTypes.EMPTY_EXPRESSION); return true; } else { return super.parseExpressionOptional(); } } @Override public boolean parseYieldOrTupleExpression(boolean isTargetExpression) { if (parseIPythonCaptureExpression()) { return true; } else { return super.parseYieldOrTupleExpression(isTargetExpression); } } private boolean parseIPythonCaptureExpression() { if (myBuilder.getTokenType() == PyConsoleTokenTypes.PLING) { captureIPythonExpression(); return true; } if (myBuilder.getTokenType() == PyTokenTypes.PERC) { if (myBuilder.lookAhead(1) == PyTokenTypes.PERC) { myBuilder.error("Multiline magic can't be used as an expression"); } captureIPythonExpression(); return true; } return false; } private void captureIPythonExpression() { PsiBuilder.Marker mark = myBuilder.mark(); while (myBuilder.getTokenType() != PyTokenTypes.STATEMENT_BREAK) { myBuilder.advanceLexer(); } mark.done(PyElementTypes.EMPTY_EXPRESSION); } } }
msebire/intellij-community
python/src/com/jetbrains/python/console/parsing/PyConsoleParsingContext.java
Java
apache-2.0
7,218
/** * Copyright 2011-2017 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.windgate.hadoopfs.temporary; import java.io.EOFException; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.asakusafw.runtime.io.ModelInput; import com.asakusafw.windgate.core.resource.SourceDriver; /** * An implementation of {@link SourceDriver} using {@link ModelInputProvider}. * @param <T> the value type * @since 0.2.5 */ public class ModelInputSourceDriver<T> implements SourceDriver<T> { static final Logger LOG = LoggerFactory.getLogger(ModelInputSourceDriver.class); private final ModelInputProvider<T> provider; private final T value; private ModelInput<T> currentInput; private boolean sawNext; /** * Creates a new instance. * @param provider the source model inputs * @param value the value object used for buffer * @throws IllegalArgumentException if any parameter is {@code null} */ public ModelInputSourceDriver(ModelInputProvider<T> provider, T value) { if (provider == null) { throw new IllegalArgumentException("provider must not be null"); //$NON-NLS-1$ } if (value == null) { throw new IllegalArgumentException("value must not be null"); //$NON-NLS-1$ } this.provider = provider; this.value = value; } @Override public void prepare() { sawNext = false; currentInput = null; } @Override public boolean next() throws IOException { while (true) { if (currentInput == null) { if (provider.next()) { currentInput = provider.open(); } else { sawNext = false; return false; } } if (currentInput.readTo(value)) { sawNext = true; return true; } else { currentInput.close(); currentInput = null; // continue } } } @Override public T get() throws IOException { if (sawNext) { return value; } throw new EOFException(); } @Override public void close() throws IOException { LOG.debug("Closing temporary file source"); sawNext = false; try { if (currentInput != null) { currentInput.close(); currentInput = null; } } finally { provider.close(); } } }
cocoatomo/asakusafw
windgate-project/asakusa-windgate-hadoopfs/src/main/java/com/asakusafw/windgate/hadoopfs/temporary/ModelInputSourceDriver.java
Java
apache-2.0
3,156
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- namespace MobileClient.Tests.Helpers { public class ComplexType { public long Id { get; set; } public string Name { get; set; } public MissingIdType Child { get; set; } } }
Azure/azure-mobile-apps-net-client
unittests/MobileClient.Tests/Helpers/Models/ComplexType.cs
C#
apache-2.0
436
// Copyright 2019 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. /** @fileoverview Sentinel main class. */ 'use strict'; const {DateTime} = require('luxon'); const { firestore: {DataSource, FirestoreAccessBase,}, cloudfunctions: { ValidatedStorageFile, CloudFunction, adaptNode6, validatedStorageTrigger, }, pubsub: {EnhancedPubSub, getMessage,}, utils: {getLogger, replaceParameters,}, } = require('@google-cloud/nodejs-common'); const { TaskConfigDao, TaskType, ErrorOptions, } = require('./task_config/task_config_dao.js'); const { TaskLog, TaskLogDao, FIELD_NAMES, TaskLogStatus, } = require('./task_log/task_log_dao.js'); const { buildTask, BaseTask, RetryableError, } = require('./tasks/index.js'); const {buildReport} = require('./tasks/report/index.js'); const { resumeStatusCheck, pauseStatusCheck, } = require('./utils/cronjob_helper.js'); const {StatusCheckTask} = require('./tasks/internal/status_check_task.js'); const { TaskManagerOptions, TaskManager, } = require('./task_manager.js'); /** * String value of BigQuery job status 'done' in BigQuery logging messages. * @const {string} */ const JOB_STATUS_DONE = 'DONE'; /** * String value of BigQuery Data Transfer job status 'SUCCEEDED' * in BigQuery Data Transfer pubsub messages. * @const {string} */ const DATATRANSFER_JOB_STATUS_DONE = 'SUCCEEDED'; /** * Types of internal (intrinsic) tasks. * @enum {string} */ const INTERNAL_TASK_TYPE = Object.freeze({ STATUS_CHECK: 'status_check', }); /** * Sentinel is a Cloud Functions based solution to coordinate BigQuery related * jobs(tasks), e.g. loading file from Cloud Storage, querying or exporting data * to Cloud Storage. Besides these jobs, it also support AutoML Tables batch * prediction job. */ class Sentinel { /** * Initializes the Sentinel instance. * @param {!TaskManagerOptions} options * @param {function(Object<string,*>,Object<string,*>):!BaseTask} buildTaskFn * Function to build a task instance based on given configuration and * parameters. */ constructor(options, buildTaskFn = buildTask) { /** @const {!TaskManager} */ this.taskManager = new TaskManager(options); /** @const {!TaskManagerOptions} */ this.options = options; /** @const {!TaskConfigDao} */ this.taskConfigDao = options.taskConfigDao; /** @const {!TaskLogDao} */ this.taskLogDao = options.taskLogDao; /** @const {function(Object<string,*>,Object<string,*>):!BaseTask} */ this.buildTask = buildTaskFn; /** @const {!Logger} */ this.logger = getLogger('S.MAIN'); } /** * Gets the Cloud Functions 'Storage Monitor' which will send out starting * related task(s) messages based on the the name of the file added to the * monitored directory. * It match Tasks in following order. It will skip second step if Task Id is * found in the first step: * 1. If there is `task[TASK_CONFIG_ID]` in the file name, just starts the * task with TaskConfig Id as `TASK_CONFIG_ID`; * 2. Tries to match the file name with all LOAD tasks' configuration * `fileNamePattern` and starts all matching Tasks. * @param {string} inbound The folder that this function monitors. * @return {!CloudFunction} */ getStorageMonitor(inbound) { /** * Monitors the Cloud Storage for new files. Sends 'start load task' message * if it identifies any new files related to Load tasks. * @param {!ValidatedStorageFile} file Validated Storage file information * from the function 'validatedStorageTrigger'. * @return {!Promise<(!Array<string>|undefined)>} IDs of the 'start load * task' messages. */ const monitorStorage = (file) => { return this.getTaskIdByFile_(file.name).then((taskIds) => { if (taskIds.length === 0) { throw new Error(`Can't find Load Task for file: '${file.name}'`); } this.logger.debug(`Find ${taskIds.length} Task for [${file.name}]`); return Promise.all(taskIds.map((taskId) => { const parameters = JSON.stringify({ file, partitionDay: getDatePartition(file.name), }); this.logger.debug(`Trigger Load task: ${taskId}.`); return this.taskManager.sendTaskMessage(parameters, {taskId}); })); }).catch((error) => { console.error(`Error in handling file: ${file.name}`, error); throw error; }); }; return this.options.validatedStorageTrigger(monitorStorage, inbound); } /** * Returns collection of task IDs which are triggered by the given file name. * @param {string} fileName Name of ingested file. * @return {!Promise<!Array<string>>} * @private */ getTaskIdByFile_(fileName) { const regex = /task\[([\w-]*)]/i; const task = fileName.match(regex); if (task) return Promise.resolve([task[1]]); const hasFileNamePattern = (config) => { const sourceConfig = config.source; return sourceConfig && sourceConfig.fileNamePattern; }; const matchesFileNamePattern = (config) => new RegExp(config.source.fileNamePattern).test(fileName); return this.taskConfigDao.list( [{property: 'type', value: TaskType.LOAD}]).then((configs) => { return configs .filter(({entity: config}) => hasFileNamePattern(config)) .filter(({entity: config}) => matchesFileNamePattern(config)) .map((config) => config.id); }); } /** * Gets the Cloud Functions 'Task Coordinator' which is triggered by a Pub/Sub * message. There are four different kinds of messages: * 1. Starting a task. Message attributes (only string typed value) have * following keys: * a. taskId (TaskConfig Id) determines the TaskConfig of the task; * b. parentId (TaskLog Id) Id of the TaskLog that triggered this one; * Message data is a JSON string for the dynamic parameter values, e.g. * 'today'. It supports type other than string values. * 2. Finishing a task. Message attributes (only string typed value) have * following keys: * a. taskLogId (TaskLog Id) determines the TaskConfig of the task; * 3. Logs from Cloud Logging system of subscribed events, e.g. BigQuery job * complete event. This function will complete the matched Task. * 4. Pubsub message from BigQuery Data Transfer after a Transfer Run job is * finished. The message attributes only have two keys: * a. eventType: The type of event that has just occurred. * TRANSFER_RUN_FINISHED is the only possible value. * b. payloadFormat: The format of the object payload. * JSON_API_V1 is the only possible value * Go https://cloud.google.com/bigquery-transfer/docs/transfer-run-notifications#format * to have more information of the format. */ getTaskCoordinator() { /** * @see method 'finishTask_()' * @see method 'startTask_()' * @see method 'handleResourceEvent_()' * @type {!CloudFunctionNode8} */ const coordinateTask = (message, context) => { if (this.isStartTaskMessage_(message)) { return this.startTaskByMessage_(message, context); } if (this.isFinishTaskMessage_(message)) { return this.finishTaskByMessage_(message); } if (this.isBigQueryLoggingMessage_(message)) { return this.finishBigQueryTask_(message); } if (this.isBigQueryDataTransferMessage_(message)) { return this.finishBigQueryDataTransferTask_(message); } throw new Error(`Unknown message: ${getMessage(message)}`); }; return adaptNode6(coordinateTask); } /** Returns whether this is a message to start a new task. */ isStartTaskMessage_(message) { const attributes = message.attributes || {}; return !!attributes.taskId; } /** Starts the task based on a Pub/sub message. */ startTaskByMessage_(message, context) { const attributes = message.attributes || {}; const data = getMessage(message); this.logger.debug('message.data decoded:', data); const messageId = context.eventId; // New TaskLog Id. this.logger.debug('message id:', messageId); let parametersStr; if (!data) { parametersStr = '{}'; } else if (data.indexOf('${') === -1) { // No placeholder in parameters. parametersStr = data; } else { // There are placeholders in parameters. Need default values. const regex = /\${([^}]*)}/g; const parameters = data.match(regex).map((match) => { return match.substring(2, match.length - 1); }); const {timezone} = JSON.parse(data); parametersStr = replaceParameters(data, getDefaultParameters(parameters, timezone)); } const taskLog = { parameters: parametersStr, ...attributes, }; return this.startTask_(messageId, taskLog); } /** Returns whether this is a message to finish a task. */ isFinishTaskMessage_(message) { const attributes = message.attributes || {}; return !!attributes.taskLogId; } /** Finishes the task based on a Pub/sub message. */ finishTaskByMessage_(message) { const attributes = message.attributes || {}; this.logger.debug(`Complete task ${attributes.taskLogId}`); return this.finishTask_(attributes.taskLogId); } /** * Returns whether this is a message from BigQuery Logging of a completed job. */ isBigQueryLoggingMessage_(message) { const data = getMessage(message); try { const payload = JSON.parse(data); return payload.resource && payload.resource.type === 'bigquery_resource' && payload.protoPayload && payload.protoPayload.methodName === 'jobservice.jobcompleted'; } catch (error) { console.warn('Error when checking when the message is from BigQuery', error); return false; } } /** Finishes the task (if any) related to the completed job in the message. */ finishBigQueryTask_(message) { const data = getMessage(message); const payload = JSON.parse(data); const event = payload.protoPayload.serviceData.jobCompletedEvent; return this.handleBigQueryJobCompletedEvent_(event); } /** * Returns whether this is a message from BigQuery Data Transfer of a completed run job. */ isBigQueryDataTransferMessage_(message) { try { const attributes = message.attributes || {}; return attributes.eventType === 'TRANSFER_RUN_FINISHED' && attributes.payloadFormat === 'JSON_API_V1'; } catch (error) { this.logger.error( 'Error when checking when the message is from BigQuery Data Transfer', error ); return false; } } /** Finishes the task (if any) related to the completed job in the message. */ finishBigQueryDataTransferTask_(message) { const data = getMessage(message); const payload = JSON.parse(data); return this.handleBigQueryDataTransferTask_(payload); } /** * Starts a task in a 'duplicated message proof' way by using * 'TaskLogDao.startTask' to check the status. * @param {(string|number)} taskLogId * @param {!TaskLog} taskLog * @return {!Promise<(string | number)>} taskLogId * @private */ startTask_(taskLogId, taskLog) { // Get the 'lock' to start this task to prevent duplicate messages. return this.taskLogDao.startTask(taskLogId, taskLog).then((started) => { if (started) return this.startTaskJob_(taskLogId, taskLog); console.warn(`TaskLog ${taskLogId} exists. Duplicated? Quit.`); }); } /** * Starts a task job: * 1. Using TaskConfigId and parameters to create the instance of Task, then * run 'Task.start()' to start the real job in the task; * 2. Using 'TaskLogDao.afterStart' to merge the output of 'Task.start()' to * TaskLog, e.g. jobId or other job identity from external systems. * 3. Checking whether this task is already done (returns true when this is * a synchronous task). If yes, continue to finish the task. * @param {(string|number)} taskLogId * @param {!TaskLog} taskLog * @return {!Promise<(string | number)>} taskLogId * @private */ startTaskJob_(taskLogId, taskLog) { const parameters = JSON.parse(taskLog.parameters); return this.prepareTask(taskLog.taskId, parameters).then((task) => { return task.start() .then((updatesToTaskLog) => { console.log('Task started with:', JSON.stringify(updatesToTaskLog)); return this.taskLogDao.afterStart(taskLogId, updatesToTaskLog); }) // Waits for async `afterStart` to complete. .then(() => task.isDone()) .then((done) => { if (done) return this.finishTask_(taskLogId); }) // Waits for async `finishTask_` to complete. .then(() => taskLogId); }).catch((error) => { console.error(error); return this.taskLogDao.saveErrorMessage(taskLogId, error); }); } /** * Returns the task object based on TaskConfigId and parameters, with * TaskManagerOptions injected. * @param {string} taskConfigId * @param {object} parameters Parameters for this Task. There is a special * property named 'intrinsic' in parameters to indicate this task is * offered by Sentinel and doesn't exists in TaskConfig. * The purpose is to let those intrinsic(internal) tasks to reuse * Sentinel's framework of managing the lifecycle of a task. * Using the 'intrinsic' to avoid the possible clash of parameter names. * @return {!Promise<!BaseTask>} Task instance. */ async prepareTask(taskConfigId, parameters = {}) { /** @const {!BaseTask} */ const task = parameters.intrinsic ? this.prepareInternalTask_(parameters.intrinsic, parameters) : await this.prepareExternalTask_(taskConfigId, parameters); return task; } /** * Returns an 'internal' task instance based on the task type and parameters. * * @param {!INTERNAL_TASK_TYPE} type Internal task type. * @param {Object} parameters * @return {!BaseTask} * @private */ prepareInternalTask_(type, parameters) { if (type === INTERNAL_TASK_TYPE.STATUS_CHECK) { const task = new StatusCheckTask({}, parameters); task.setPrepareExternalTaskFn(this.prepareExternalTask_.bind(this)); task.injectContext(this.options); return task; } throw new Error(`Unsupported internal task: ${type}`); } /** * Returns an external task instance based on the TaskConfig Id and parameters * with context (TaskManagerOptions) injected. * When Sentinel starts or finishes an external task, the task information is * passed as a TaskConfig Id and an object of parameters. This function will * use TaskConfigDao to get the TaskConfig(config), then use the config and * parameters to get the Task object. * This function will also be passed into Status Check Task to initialize * other external tasks. * @param {string} taskConfigId * @param {Object} parameters * @return {!Promise<!BaseTask>} * @private */ async prepareExternalTask_(taskConfigId, parameters) { const taskConfig = await this.taskConfigDao.load(taskConfigId); if (!taskConfig) throw new Error(`Fail to load Task ${taskConfigId}`); const task = this.buildTask(taskConfig, parameters); task.injectContext(this.options); return task; }; /** * Finishes a task in a 'duplicated message proof' way by using * 'TaskLogDao.finishTask' to check the status. * @param {(string|number)} taskLogId * @return {!Promise<(!Array<string>|undefined)>} Ids of messages to trigger * next task(s). * @private */ finishTask_(taskLogId) { this.logger.debug(`Start to finish task ${taskLogId}`); return this.taskLogDao.load(taskLogId).then((taskLog) => { return this.taskLogDao.finishTask(taskLogId).then((finished) => { if (finished) return this.finishTaskJob_(taskLogId, taskLog); console.warn(`Fail to finish the taskLog [${taskLogId}]. Quit.`); }) }); } /** * Finishes a task job: * 1. Using TaskConfigId and parameters to create the instance of Task, then * run 'Task.finish()' to finish the job in the task, e.g. download files * from external system; * 2. Using 'TaskLogDao.afterFinish' to merge the output of 'Task.finish()' * to TaskLog; * 3. Triggering next Tasks if there are. * @param {(string|number)} taskLogId * @param {!TaskLog} taskLog * @return {!Promise<(!Array<string>|undefined)>} Ids of messages to trigger * next task(s). * @private */ async finishTaskJob_(taskLogId, taskLog) { const parameters = JSON.parse(taskLog.parameters); let updatedParameterStr = taskLog.parameters; const task = await this.prepareTask(taskLog.taskId, parameters); try { const updatesToTaskLog = await task.finish(); this.logger.debug('Task finished with', JSON.stringify(updatesToTaskLog)); if (updatesToTaskLog.parameters) { updatedParameterStr = updatesToTaskLog.parameters; } // 'afterFinish' won't throw 'RetryableError' which can trigger retry. await this.taskLogDao.afterFinish(taskLogId, updatesToTaskLog); } catch (error) { console.error(error); const taskConfig = await this.taskConfigDao.load(taskLog.taskId); /**@type {!ErrorOptions} */ const errorOptions = Object.assign({ // Default retry 3 times before recognize it's a real failure. retryTimes: 3, ignoreError: false, // Default error is not ignored. }, taskConfig.errorOptions); if (error instanceof RetryableError) { const retriedTimes = taskLog[FIELD_NAMES.RETRIED_TIMES] || 0; if (retriedTimes < errorOptions.retryTimes) { // Roll back task status from 'FINISHING' to 'STARTED' and set task // needs regular status check (to trigger next retry). // TODO(lushu) If there are tasks other than report task needs retry, // consider move this part into the detailed tasks. return this.taskLogDao.merge({ status: TaskLogStatus.STARTED, [FIELD_NAMES.REGULAR_CHECK]: true, [FIELD_NAMES.RETRIED_TIMES]: retriedTimes + 1, }, taskLogId); } console.log( 'Reach the maximum retry times, continue to mark this task failed.'); } if (errorOptions.ignoreError !== true) { return this.taskLogDao.saveErrorMessage(taskLogId, error); } // Save the error information for 'ignore error' task then continue to // trigger its next task(s). await this.taskLogDao.saveErrorMessage(taskLogId, error, true); } return this.taskManager.startTasks(taskLog.next, {[FIELD_NAMES.PARENT_ID]: taskLogId}, updatedParameterStr); } /** * Based on the incoming message, updates the TaskLog and triggers next tasks * if there is any in TaskConfig of the current finished task. * For Load/Query/Export tasks, the taskLog saves 'job Id' generated when the * job starts at the beginning. When these kinds of job is done, the log event * will be sent here with 'job Id'. So we can match to TaskLogs in database * waiting for the job is done. * @param event * @return {!Promise<(!Array<string>|number|undefined)>} The message Id array * of the next tasks and an empty Array if there is no followed task. * Returns taskLogId (number) when an error occurs. * Returns undefined if there is no related taskLog. * @private */ handleBigQueryJobCompletedEvent_(event) { const job = event.job; const eventName = event.eventName; const jobId = job.jobName.jobId; const jobStatus = job.jobStatus.state; this.logger.debug(`Task JobId[${jobId}] [${eventName}] [${jobStatus}]`); const filter = {property: 'jobId', value: jobId}; return this.taskLogDao.list([filter]).then((taskLogs) => { if (taskLogs.length > 1) { throw new Error(`Find more than one task with Job Id: ${jobId}`); } if (taskLogs.length === 1) { const {id: taskLogId} = taskLogs[0]; if (jobStatus === JOB_STATUS_DONE) return this.finishTask_(taskLogId); console.log(`Job Status is not DONE: `, event); return this.taskLogDao.saveErrorMessage(taskLogId, job.jobStatus.error); } this.logger.debug(`BigQuery JobId[${jobId}] is not a Sentinel Job.`); }).catch((error) => { console.error(error); throw error; }); } /** * Based on the incoming message, updates the TaskLog and triggers next tasks * if there is any in TaskConfig of the current finished task. * For Data Transfer tasks, the taskLog saves the 'name' of run job * as 'job id' which is generated when the job starts at the beginning. * When the job is done, the datatransfer job will be sent here with the run * job 'name'. So we can match to TaskLogs in database * waiting for the job is done. * @param payload * @return {!Promise<(!Array<string>|number|undefined)>} The message Id array * of the next tasks and an empty Array if there is no followed task. * Returns taskLogId (number) when an error occurs. * Returns undefined if there is no related taskLog. * @private */ handleBigQueryDataTransferTask_(payload) { const jobId = payload.name; const jobStatus = payload.state; this.logger.debug( `The JobId of Data Transfer Run: ${jobId} and the status is: ${jobStatus}` ); const filter = {property: 'jobId', value: jobId}; return this.taskLogDao .list([filter]) .then((taskLogs) => { if (taskLogs.length > 1) { throw new Error(`Find more than one task with Job Id: ${jobId}`); } if (taskLogs.length === 1) { const {id: taskLogId} = taskLogs[0]; if (jobStatus === DATATRANSFER_JOB_STATUS_DONE) { return this.finishTask_(taskLogId); } this.logger.info(`Job Status is not DONE: `, payload); return this.taskLogDao.saveErrorMessage( taskLogId, payload.errorStatus ); } this.logger.debug( `BigQuery Data Transfer JobId[${jobId}] is not a Sentinel Job.` ); }) .catch((error) => { this.logger.error(error); throw error; }); } } /** * Extracts the date information from the file name. If there is no date * recognized, will return today's date. * @param {string} filename. It is supposed to contain date information in * format 'YYYY-MM-DD' or 'YYYYMMDD'. Though it will also take 'YYYY-MMDD' * or 'YYYYMM-DD'. * @return {string} Date string in format "YYYYMMDD". */ const getDatePartition = (filename) => { const reg = /\d{4}-?\d{2}-?\d{2}/; const date = reg.exec(filename); let partition; if (date) { partition = date[0]; } else { partition = (new Date()).toISOString().split('T')[0]; console.log( `No date find in file: ${filename}. Using current date: ${partition}.`); } return partition.replace(/-/g, ''); }; /** * Returns the default parameter object. Currently, it support following rules: * now - Date ISO String * today - format 'YYYYMMDD' * today_set_X - set the day as X based on today's date, format 'YYYYMMDD' * today_sub_X - sub the X days based on today's date, format 'YYYYMMDD' * today_add_X - add the X days based on today's date, format 'YYYYMMDD' * Y_hyphenated - 'Y' could be any of previous date, format 'YYYY-MM-DD' * Y_timestamp_ms - 'Unix milliseconds timestamp of the start of date 'Y' * yesterday - quick access as 'today_sub_1'. It can has follow ups as well, * e.g. yesterday_sub_X, yesterday_hyphenated, etc. * Parameters get values ignoring their cases status (lower or upper). * @param {Array<string>} parameters Names of default parameter. * @param {string=} timezone Default value is UTC. * @param {number=} unixMillis Unix timestamps in milliseconds. Default value is * now. Used for test. * @return {{string: string}} */ const getDefaultParameters = (parameters, timezone = 'UTC', unixMillis = Date.now()) => { /** * Returns the value based on the given parameter name. * @param {string=} parameter * @return {string|number} */ const getDefaultValue = (parameter) => { let realParameter = parameter.toLocaleLowerCase(); const now = DateTime.fromMillis(unixMillis, {zone: timezone}); if (realParameter === 'now') return now.toISO(); // 'now' is a Date ISO String. if (realParameter === 'today') return now.toFormat('yyyyMMdd'); realParameter = realParameter.replace(/^yesterday/, 'today_sub_1'); if (!realParameter.startsWith('today')) { throw new Error(`Unknown default parameter: ${parameter}`); } const suffixes = realParameter.split('_'); let date = now; for (let index = 1; index < suffixes.length; index++) { if (suffixes[index] === 'hyphenated') return date.toISODate(); if (suffixes[index] === 'timestamp' && suffixes[index + 1] === 'ms') { return date.startOf('days').toMillis(); } const operator = suffixes[index]; let operationOfLib; switch (operator) { case 'add': operationOfLib = 'plus'; break; case 'set': operationOfLib = 'set'; break; case 'sub': operationOfLib = 'minus'; break; default: throw new Error( `Unknown operator in default parameter: ${parameter}`); } const day = suffixes[++index]; if (typeof day === "undefined") { throw new Error(`Malformed of default parameter: ${parameter}`); } date = date[operationOfLib]({days: day}); } return date.toFormat('yyyyMMdd'); } const result = {}; parameters.forEach((parameter) => { result[parameter] = getDefaultValue(parameter); }) return result; }; /** * Returns a Sentinel instance based on the parameters. * Sentinel works on several components which depend on the configuration. This * factory function will seal the details in product environment and let the * Sentinel class be more friendly to test. * * @param {string} namespace The `namespace` of this instance, e.g. prefix of * the topics, Firestore root collection name, Datastore namespace, etc. * @param {!DataSource} datasource The underlying datasource type. * @return {!Sentinel} The Sentinel instance. */ const getSentinel = (namespace, datasource) => { /** @type {TaskManagerOptions} */ const options = { namespace, taskConfigDao: new TaskConfigDao(datasource, namespace), taskLogDao: new TaskLogDao(datasource, namespace), pubsub: EnhancedPubSub.getInstance(), buildReport, statusCheckCronJob: { pause: pauseStatusCheck, resume: resumeStatusCheck, }, validatedStorageTrigger, }; console.log( `Init Sentinel for namespace[${namespace}], Datasource[${datasource}]`); return new Sentinel(options); }; /** * Probes the Google Cloud Project's Firestore mode (Native or Datastore), then * uses it to create an instance of Sentinel. * @param {(string|undefined)=} namespace * @return {!Promise<!Sentinel>} */ const guessSentinel = (namespace = process.env['PROJECT_NAMESPACE']) => { if (!namespace) { console.warn( 'Fail to find ENV variables PROJECT_NAMESPACE, will set as `sentinel`'); namespace = 'sentinel'; } return FirestoreAccessBase.isNativeMode().then((isNative) => { const dataSource = isNative ? DataSource.FIRESTORE : DataSource.DATASTORE; return getSentinel(namespace, dataSource); }); }; module.exports = { Sentinel, getSentinel, guessSentinel, getDatePartition, getDefaultParameters, };
GoogleCloudPlatform/cloud-for-marketing
marketing-analytics/activation/data-tasks-coordinator/src/sentinel.js
JavaScript
apache-2.0
28,561
#region License // Copyright (c) Amos Voron. All rights reserved. // Licensed under the Apache 2.0 License. See LICENSE in the project root for license information. #endregion namespace QueryTalk.Wall { /// <summary> /// This interface is not intended for public use. /// </summary> public interface IOrderBy { } }
querytalk/library
Wall/interfaces/IOrderBy.cs
C#
apache-2.0
339
package WADL; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import java.util.List; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; public class POSTWADLParseHandler { private AccountModel oAccount; private RESTServiceModel oRESTService; private SQLITEController oSQLITEController; private UriInfo oApplicationUri; private String wadlName; private InputStream uploadedInputStream; POSTWADLParseHandler(int accountId,UriInfo applicationUri, InputStream uploadedInputStream, String wadlName) { oAccount = new AccountModel(); oAccount.setAccountId(accountId); this.oRESTService = new RESTServiceModel(); oRESTService.setAccount( this.oAccount); oSQLITEController = new SQLITEController(); oApplicationUri = applicationUri; this.wadlName = wadlName; this.uploadedInputStream = uploadedInputStream; } public void setAccount(AccountModel oAccount) { this.oAccount = oAccount; } public AccountModel getAccount() { return this.oAccount; } public RESTServiceModel postWADLParse() { //TODO add authentication if needed saveUploadedFile(); parseWADLApplication(); return createHypermediaURIs(); } public void saveUploadedFile() { try { File outputFile = new File(String.format("webapps/wsAnnotationTool/WEB-INF/WADLFiles/%d/%s",oAccount.getAccountId(),wadlName)); outputFile.getParentFile().mkdirs(); OutputStream uploadedOutputStream = new FileOutputStream(outputFile); int bytesRead = 0; byte[] inputBytes = new byte[1024]; while ((bytesRead = uploadedInputStream.read(inputBytes)) != -1) { uploadedOutputStream.write(inputBytes, 0, bytesRead); } uploadedInputStream.close(); uploadedOutputStream.close(); } catch (IOException ioEx) { System.out.println(ioEx.getMessage()); System.out.println(ioEx.getCause()); ioEx.printStackTrace(); throw new WebApplicationException(Response.Status.BAD_REQUEST); } } public RESTServiceModel createHypermediaURIs() { //add the sibling hypermedia links POST and GET list oRESTService.getLinkList().clear(); oRESTService.getLinkList().add(new Link(String.format("%s%s",oApplicationUri.getBaseUri(),oApplicationUri.getPath()),"Create new RESTService by parsing a WADL file","POST","Sibling")); String oRelativePath; oRelativePath = oApplicationUri.getPath(); oRelativePath = oRelativePath.replaceAll(String.format("/algoRESTService/WADLParse"),String.format("/RESTService/%d",oRESTService.getRESTServiceId())); oRESTService.getLinkList().add(new Link(String.format("%s%s",oApplicationUri.getBaseUri(),oRelativePath),"Get the created RESTService","GET","Child")); //add the parent hypermedia links POST, GETL oRelativePath = oApplicationUri.getPath(); //add the parent's hypermedia links PUT, GET DELETE //find last index of "/" in order to cut off to get the parent URI appropriately int iLastSlashIndex = String.format("%s%s",oApplicationUri.getBaseUri(),oRelativePath).lastIndexOf("/"); iLastSlashIndex = String.format("%s%s",oApplicationUri.getBaseUri(),oRelativePath).substring(0, iLastSlashIndex).lastIndexOf("/"); oRESTService.getLinkList().add(new Link(String.format("%s%s",oApplicationUri.getBaseUri(),oRelativePath).substring(0, iLastSlashIndex),"Update Account","PUT","Parent")); oRESTService.getLinkList().add(new Link(String.format("%s%s",oApplicationUri.getBaseUri(),oRelativePath).substring(0, iLastSlashIndex),"Read Account","GET","Parent")); oRESTService.getLinkList().add(new Link(String.format("%s%s",oApplicationUri.getBaseUri(),oRelativePath).substring(0, iLastSlashIndex),"Delete Account","DELETE","Parent")); return oRESTService; } public void parseWADLApplication() { try { //build the JDOM object Document wadlDocument = (Document) (new SAXBuilder()).build(new File(String.format("webapps/wsAnnotationTool/WEB-INF/WADLFiles/%d/%s",oAccount.getAccountId(),wadlName))); //get root element (application node in a WADL file) Element WADLApplicationNode = wadlDocument.getRootElement(); //parse application documentation List<Element> listOfApplicationDocs = WADLApplicationNode.getChildren(); Iterator<Element> iteratorOfApplicationDocs = listOfApplicationDocs.iterator(); //for every documentation element of this rest method while(iteratorOfApplicationDocs.hasNext()) { Element oNextApplicationDocElement = iteratorOfApplicationDocs.next(); if(oNextApplicationDocElement.getName().equalsIgnoreCase("doc") && oNextApplicationDocElement.getAttribute("title") != null && !oNextApplicationDocElement.getAttributeValue("title").isEmpty()) { oRESTService.getWsKeywords().add(oNextApplicationDocElement.getAttributeValue("title")); } } //parse all resources nodes parseEntryPoints(WADLApplicationNode); } catch (IOException io) { System.out.println(io.getMessage()); throw new WebApplicationException(Response.Status.NOT_FOUND); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); throw new WebApplicationException(Response.Status.BAD_REQUEST); } } public void parseEntryPoints(Element WADLApplicationNode) { //get "resources" node List<Element> listOfEntryPoints = WADLApplicationNode.getChildren(); //for every set of resources create a RESTService Iterator<Element> iteratorOfEntryPoints = listOfEntryPoints.iterator(); while( iteratorOfEntryPoints.hasNext() ) { // get next entry point Element oNextEntryPoint = iteratorOfEntryPoints.next(); if(oNextEntryPoint.getName().equalsIgnoreCase("resources")) { //parse the base URI of this service oRESTService.setBaseUri(oNextEntryPoint.getAttributeValue("base")); //create new RESTService with this base URI POSTRESTServiceHandler oPOSTRESTServiceHandler = new POSTRESTServiceHandler(oAccount.getAccountId(), oRESTService, oApplicationUri); oRESTService = oPOSTRESTServiceHandler.postRESTService(); //parse all "resource" nodes parseResourcesOfEntryPoints(oNextEntryPoint); } } } public void parseResourcesOfEntryPoints(Element oEntryPoint) { List<Element> listResourcesOfEntryPoint = oEntryPoint.getChildren(); Iterator<Element> iteratorOfResources = listResourcesOfEntryPoint.iterator(); //and iteratively parse them while( iteratorOfResources.hasNext()) { Element oNextResourceElement = iteratorOfResources.next(); if(oNextResourceElement.getName().equalsIgnoreCase("resource")) { ResourceModel oResource = new ResourceModel(); oResource.setRelativeUri(oNextResourceElement.getAttributeValue("path")); //create new resource POSTResourceHandler oPOSTResourceHandler = new POSTResourceHandler(oRESTService.getRESTServiceId(), oResource, oApplicationUri); oResource = oPOSTResourceHandler.postResource(); //parse resource's parameters parseResourceParameters(oResource,oNextResourceElement); //parse resource's methods parseResourceMethods(oResource,oNextResourceElement); } } } public void parseResourceParameters(ResourceModel oResource, Element oResourceElement) { List<Element> listOfResourceParameters = oResourceElement.getChildren(); Iterator<Element> iteratorOfResourceParameters = listOfResourceParameters.iterator(); //for each resource parameter while(iteratorOfResourceParameters.hasNext()) { //parse the resource parameter Element oNextParameterElement = iteratorOfResourceParameters.next(); if(oNextParameterElement.getName().equalsIgnoreCase("param")) { RESTParameterModel oRESTParameter = new RESTParameterModel(); oRESTParameter.setParameterName(oNextParameterElement.getAttributeValue("name")); oRESTParameter.setParameterStyle(oNextParameterElement.getAttributeValue("style")); oRESTParameter.setParameterType(oNextParameterElement.getAttributeValue("type")); oRESTParameter.setParameterRequired(oNextParameterElement.getAttributeValue("required")); oRESTParameter.setDescription(oNextParameterElement.getChildText("doc")); oRESTParameter.setParameterDefault(oNextParameterElement.getAttributeValue("default")); //parse parameter value options parseParameterValueOptions(oRESTParameter, oNextParameterElement); //create the new parameter POSTResourceRESTParameterHandler oPOSTResourceRESTParameterHandler = new POSTResourceRESTParameterHandler(oResource.getResourceId(),oRESTParameter, oApplicationUri); oPOSTResourceRESTParameterHandler.postRESTParameter(); } } } public void parseResourceMethods(ResourceModel oResource, Element oResourceElement) { List<Element> listOfResourceMethods = oResourceElement.getChildren(); Iterator<Element> iteratorOfResourceMethods = listOfResourceMethods.iterator(); //for each resource method while(iteratorOfResourceMethods.hasNext()) { Element oNextMethodElement = iteratorOfResourceMethods.next(); if(oNextMethodElement.getName().equalsIgnoreCase("method")) { RESTMethodModel oRESTMethod = new RESTMethodModel(); oRESTMethod.setMethodIdentifier(oNextMethodElement.getAttributeValue("id")); oRESTMethod.setHTTPVerb(oNextMethodElement.getAttributeValue("name")); //parse any doc elements that describe this method parseMethodDocumentation(oRESTMethod,oNextMethodElement); //create RESTMethod POSTRESTMethodHandler oPOSTRESTMethodHandler = new POSTRESTMethodHandler(oResource.getResourceId(), oRESTMethod, oApplicationUri); oRESTMethod = oPOSTRESTMethodHandler.postRESTMethod(); //parse any method parameters parseMethodParameters(oRESTMethod, oNextMethodElement); } } } public void parseMethodDocumentation(RESTMethodModel oRESTMethod, Element oMethodElement) { List<Element> listOfMethodDocs = oMethodElement.getChildren(); Iterator<Element> iteratorOfMethodDocs = listOfMethodDocs.iterator(); //for every documentation element of this rest method while(iteratorOfMethodDocs.hasNext()) { Element oNextMethodDocElement = iteratorOfMethodDocs.next(); if(oNextMethodDocElement.getName().equalsIgnoreCase("doc") && oNextMethodDocElement.getAttribute("title") != null && !oNextMethodDocElement.getAttributeValue("title").isEmpty()) { oRESTMethod.getMethodKeywords().add(oNextMethodDocElement.getAttributeValue("title")); } } } public void parseMethodParameters(RESTMethodModel oRESTMethod, Element oMethodElement) { List<Element> listOfResourceMethodNodes = oMethodElement.getChildren(); Iterator<Element> iteratorOfResourceMethodNodes = listOfResourceMethodNodes.iterator(); while( iteratorOfResourceMethodNodes.hasNext() ) { Element oNextResourceMethodNode = iteratorOfResourceMethodNodes.next(); if(oNextResourceMethodNode.getName().equalsIgnoreCase("request")) { parseMethodRequestParameters(oRESTMethod, oNextResourceMethodNode); } else if(oNextResourceMethodNode.getName().equalsIgnoreCase("response")) { parseMethodResponseParameters(oRESTMethod, oNextResourceMethodNode); } } } public void parseMethodRequestParameters(RESTMethodModel oRESTMethod, Element oNextRequestMethodNode) { List<Element> listOfMethodRequestParameters = oNextRequestMethodNode.getChildren(); Iterator<Element> iteratorOfMethodRequestParameters = listOfMethodRequestParameters.iterator(); //for each method parameter while( iteratorOfMethodRequestParameters.hasNext()) { Element oNextMethodRequestParameter = iteratorOfMethodRequestParameters.next(); if(oNextMethodRequestParameter.getName().equalsIgnoreCase("param")) { RESTParameterModel oRESTParameter = new RESTParameterModel(); oRESTParameter.setParameterName(oNextMethodRequestParameter.getAttributeValue("name")); oRESTParameter.setParameterStyle(oNextMethodRequestParameter.getAttributeValue("style")); oRESTParameter.setParameterType(oNextMethodRequestParameter.getAttributeValue("type")); oRESTParameter.setParameterRequired(oNextMethodRequestParameter.getAttributeValue("required")); oRESTParameter.setDescription(oNextMethodRequestParameter.getChildText("doc")); oRESTParameter.setParameterDefault(oNextMethodRequestParameter.getAttributeValue("default")); oRESTParameter.setParameterDirection("request"); //parse parameter value options parseParameterValueOptions(oRESTParameter, oNextMethodRequestParameter); //create the new parameter POSTRESTMethodRESTParameterHandler oPOSTRESTMethodRESTParameterHandler = new POSTRESTMethodRESTParameterHandler(oRESTMethod.getRESTMethodId(), oRESTParameter, oApplicationUri); oPOSTRESTMethodRESTParameterHandler.postRESTParameter(); } } } public void parseMethodResponseParameters(RESTMethodModel oRESTMethod, Element oNextResponseMethodNode) { List<Element> listOfMethodResponseParameters = oNextResponseMethodNode.getChildren(); Iterator<Element> iteratorOfMethodResponseParameters = listOfMethodResponseParameters.iterator(); //for each method parameter while( iteratorOfMethodResponseParameters.hasNext()) { Element oNextMethodResponseParameter = iteratorOfMethodResponseParameters.next(); if(oNextMethodResponseParameter.getName().equalsIgnoreCase("param")) { RESTParameterModel oRESTParameter = new RESTParameterModel(); oRESTParameter.setParameterName(oNextMethodResponseParameter.getAttributeValue("name")); oRESTParameter.setParameterStyle(oNextMethodResponseParameter.getAttributeValue("style")); oRESTParameter.setParameterType(oNextMethodResponseParameter.getAttributeValue("type")); oRESTParameter.setParameterRequired(oNextMethodResponseParameter.getAttributeValue("required")); oRESTParameter.setDescription(oNextMethodResponseParameter.getChildText("doc")); oRESTParameter.setParameterDefault(oNextMethodResponseParameter.getAttributeValue("default")); oRESTParameter.setParameterDirection("response"); //parse parameter value options parseParameterValueOptions(oRESTParameter, oNextMethodResponseParameter); //create the new parameter POSTRESTMethodRESTParameterHandler oPOSTRESTMethodRESTParameterHandler = new POSTRESTMethodRESTParameterHandler(oRESTMethod.getRESTMethodId(), oRESTParameter, oApplicationUri); oPOSTRESTMethodRESTParameterHandler.postRESTParameter(); } } } public void parseParameterValueOptions(RESTParameterModel oRESTParameter, Element oMethodParameter) { List<Element> listOfParameterValueOptions = oMethodParameter.getChildren(); Iterator<Element> iteratorOfParameterValueOptions = listOfParameterValueOptions.iterator(); //for each parameter value options while(iteratorOfParameterValueOptions.hasNext()) { Element oNextParameterValueOption = iteratorOfParameterValueOptions.next(); oRESTParameter.getParameterValueOption().add(oNextParameterValueOption.getAttributeValue("value")); } } }
AuthEceSoftEng/web-service-annotation-tool
src/WADL/POSTWADLParseHandler.java
Java
apache-2.0
16,149
/* * 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.pdfbox.pdfparser; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSDocument; import org.apache.pdfbox.cos.COSObject; import org.apache.pdfbox.cos.COSStream; /** * This will parse a PDF 1.5 object stream and extract all of the objects from the stream. * * @author Ben Litchfield */ public class PDFObjectStreamParser extends BaseParser { /** * Log instance. */ private static final Log LOG = LogFactory.getLog(PDFObjectStreamParser.class); private List<COSObject> streamObjects = null; private final COSStream stream; /** * Constructor. * * @param stream The stream to parse. * @param document The document for the current parsing. * @throws IOException If there is an error initializing the stream. */ public PDFObjectStreamParser(COSStream stream, COSDocument document) throws IOException { super(new InputStreamSource(stream.createInputStream())); this.stream = stream; this.document = document; } /** * This will parse the tokens in the stream. This will close the * stream when it is finished parsing. * * @throws IOException If there is an error while parsing the stream. */ public void parse() throws IOException { try { //need to first parse the header. int numberOfObjects = stream.getInt("N"); List<Long> objectNumbers = new ArrayList<Long>(numberOfObjects); streamObjects = new ArrayList<COSObject>(numberOfObjects); for (int i = 0; i < numberOfObjects; i++) { long objectNumber = readObjectNumber(); // skip offset readLong(); objectNumbers.add(objectNumber); } COSObject object; COSBase cosObject; int objectCounter = 0; while ((cosObject = parseDirObject()) != null) { object = new COSObject(cosObject); object.setGenerationNumber(0); if (objectCounter >= objectNumbers.size()) { LOG.error("/ObjStm (object stream) has more objects than /N " + numberOfObjects); break; } object.setObjectNumber(objectNumbers.get(objectCounter)); streamObjects.add(object); if (LOG.isDebugEnabled()) { LOG.debug("parsed=" + object); } // According to the spec objects within an object stream shall not be enclosed // by obj/endobj tags, but there are some pdfs in the wild using those tags // skip endobject marker if present if (!seqSource.isEOF() && seqSource.peek() == 'e') { readLine(); } objectCounter++; } } finally { seqSource.close(); } } /** * This will get the objects that were parsed from the stream. * * @return All of the objects in the stream. */ public List<COSObject> getObjects() { return streamObjects; } }
gavanx/pdflearn
pdfbox/src/main/java/org/apache/pdfbox/pdfparser/PDFObjectStreamParser.java
Java
apache-2.0
3,803
/* * Copyright 2017 Trevor Jones, Jemshit Iskanderov * * 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.trevjonez.inject.view; import android.view.View; import com.trevjonez.inject.PlainComponent; public interface ViewComponentBuilderHost { <V extends View, B extends ViewComponentBuilder<V, ? extends PlainComponent<V>>> B getViewComponentBuilder(Class<V> viewKey, Class<B> builderType); }
trevjonez/Inject-Android
core/src/main/java/com/trevjonez/inject/view/ViewComponentBuilderHost.java
Java
apache-2.0
923
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for struct2tensor.reroot.""" from absl.testing import absltest from struct2tensor import calculate from struct2tensor import create_expression from struct2tensor import path from struct2tensor.expression_impl import proto_test_util from struct2tensor.expression_impl import reroot from struct2tensor.test import expression_test_util from struct2tensor.test import prensor_test_util from struct2tensor.test import test_pb2 import tensorflow as tf from tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import @test_util.run_all_in_graph_and_eager_modes class RerootTest(tf.test.TestCase): def test_reroot_and_create_proto_index(self): expr = create_expression.create_expression_from_prensor( prensor_test_util.create_big_prensor()) new_root = reroot.reroot(expr, path.Path(["doc"])) proto_index = reroot.create_proto_index_field( new_root, "proto_index").get_child("proto_index") new_field = new_root.get_child("bar") leaf_node = expression_test_util.calculate_value_slowly(new_field) proto_index_node = expression_test_util.calculate_value_slowly(proto_index) self.assertIsNotNone(new_field) self.assertTrue(new_field.is_repeated) self.assertEqual(new_field.type, tf.string) self.assertTrue(new_field.is_leaf) self.assertEqual(new_field.known_field_names(), frozenset()) self.assertEqual(leaf_node.values.dtype, tf.string) self.assertIsNotNone(proto_index) self.assertFalse(proto_index.is_repeated) self.assertEqual(proto_index.type, tf.int64) self.assertTrue(proto_index.is_leaf) self.assertEqual(proto_index.known_field_names(), frozenset()) self.assertEqual(proto_index_node.values.dtype, tf.int64) self.assertAllEqual([b"a", b"b", b"c", b"d"], leaf_node.values) self.assertAllEqual([0, 1, 1, 2], leaf_node.parent_index) self.assertAllEqual([0, 1, 1], proto_index_node.values) self.assertAllEqual([0, 1, 2], proto_index_node.parent_index) def test_reroot_and_create_proto_index_deep(self): expr = create_expression.create_expression_from_prensor( prensor_test_util.create_deep_prensor()) new_root = reroot.reroot(expr, path.Path(["event", "doc"])) proto_index = reroot.create_proto_index_field( new_root, "proto_index").get_child("proto_index") new_field = new_root.get_child("bar") leaf_node = expression_test_util.calculate_value_slowly(new_field) proto_index_node = expression_test_util.calculate_value_slowly(proto_index) self.assertIsNotNone(new_field) self.assertTrue(new_field.is_repeated) self.assertEqual(new_field.type, tf.string) self.assertTrue(new_field.is_leaf) self.assertEqual(new_field.known_field_names(), frozenset()) self.assertEqual(leaf_node.values.dtype, tf.string) self.assertIsNotNone(proto_index) self.assertFalse(proto_index.is_repeated) self.assertEqual(proto_index.type, tf.int64) self.assertTrue(proto_index.is_leaf) self.assertEqual(proto_index.known_field_names(), frozenset()) self.assertEqual(proto_index_node.values.dtype, tf.int64) self.assertAllEqual([b"a", b"b", b"c", b"d"], leaf_node.values) self.assertAllEqual([0, 1, 1, 2], leaf_node.parent_index) self.assertAllEqual([0, 1, 1], proto_index_node.values) self.assertAllEqual([0, 1, 2], proto_index_node.parent_index) def test_create_proto_index_directly_reroot_at_action(self): sessions = [ """ event { action {} action {} } event {} event { action {} } """, "", """ event {} event { action {} action {} } event { } """ ] expr = proto_test_util.text_to_expression(sessions, test_pb2.Session) reroot_expr = expr.reroot("event.action") # Reroot with a depth > 1 (all the other cases are depth == 1) proto_index_directly_reroot_at_action = ( reroot_expr.create_proto_index("proto_index_directly_reroot_at_action") .get_child_or_error("proto_index_directly_reroot_at_action")) self.assertFalse(proto_index_directly_reroot_at_action.is_repeated) result = expression_test_util.calculate_value_slowly( proto_index_directly_reroot_at_action) self.assertAllEqual(result.parent_index, [0, 1, 2, 3, 4]) self.assertAllEqual(result.values, [0, 0, 0, 2, 2]) def test_create_proto_index_directly_reroot_at_action_sparse_dense(self): sessions = [ """ event { action {} action {} } event {} event { action {} } """, "", """ event {} event { action {} action {} } event { } """ ] expr = proto_test_util.text_to_expression(sessions, test_pb2.Session) reroot_expr = expr.reroot("event.action") # Reroot with a depth > 1 (all the other cases are depth == 1) [prensor_tree] = calculate.calculate_prensors([ reroot_expr.create_proto_index("proto_index_directly_reroot_at_action") ]) proto_index_node = prensor_tree.get_child_or_error( "proto_index_directly_reroot_at_action").node self.assertFalse(proto_index_node.is_repeated) sparse_tensors = prensor_tree.get_sparse_tensors() proto_index_directly_reroot_at_action = sparse_tensors[path.Path( ["proto_index_directly_reroot_at_action"])] dense_value = tf.sparse.to_dense( proto_index_directly_reroot_at_action) sparse_value = proto_index_directly_reroot_at_action self.assertAllEqual(sparse_value.values, [0, 0, 0, 2, 2]) self.assertAllEqual(sparse_value.indices, [[0], [1], [2], [3], [4]]) self.assertAllEqual(sparse_value.dense_shape, [5]) self.assertAllEqual(dense_value, [0, 0, 0, 2, 2]) if __name__ == "__main__": absltest.main()
google/struct2tensor
struct2tensor/expression_impl/reroot_test.py
Python
apache-2.0
6,436
package me.scana.subscriptionsleak; import java.security.SecureRandom; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; import io.reactivex.Observable; public class RecommendMovieUseCase { private static final List<String> COOL_MOVIES = Arrays.asList("Fight Club", "The Departed", "Hot Fuzz"); private final Random random = new SecureRandom(); public Observable<String> recommendRandomMovie() { return Observable.just(getRandomMovie()).delay(3, TimeUnit.SECONDS); } private String getRandomMovie() { return COOL_MOVIES.get(random.nextInt(COOL_MOVIES.size())); } }
scana/subscriptions-leak-example
app/src/main/java/me/scana/subscriptionsleak/RecommendMovieUseCase.java
Java
apache-2.0
673
'use strict'; 'use console'; /* eslint-disable no-console */ /* eslint-disable no-await-in-loop */ const fs = require('fs-extra'); const prompt = require('syncprompt'); const _ = require('lodash'); const reply = require('../../lib/reply')(); const display = require('../../lib/display')(); module.exports = (cliConfig) => { const terasliceClient = require('teraslice-client-js')({ host: cliConfig.cluster_url }); const annotation = require('../../lib/annotation')(cliConfig); cliConfig.type = 'job'; async function showPrompt(actionIn) { let answer = false; const action = _.startCase(actionIn); const response = prompt(`${action} (Y/N)? > `); if (response === 'Y' || response === 'y') { answer = true; } return answer; } async function restart() { if (await stop()) { await start(); } if (cliConfig.add_annotation) { await annotation.add('Restart'); } } async function stop(action = 'stop') { let waitCountStop = 0; const waitMaxStop = 10; let stopTimedOut = false; let jobsStopped = 0; let allJobsStopped = false; let jobs = []; if (cliConfig.all_jobs) { jobs = await save(); } else { await checkForId(); jobs = await save(false); const id = _.find(jobs, { job_id: cliConfig.job_id }); if (id !== undefined) { jobs = []; jobs.push(id); console.log(`Stop job: ${cliConfig.job_id}`); } } if (jobs.length === 0) { reply.error(`No jobs to ${action}`); return; } if (jobs.length === 1) { cliConfig.yes = true; } if (cliConfig.yes || await showPrompt(action)) { while (!stopTimedOut) { if (waitCountStop >= waitMaxStop) { break; } try { await changeStatus(jobs, action); stopTimedOut = true; } catch (err) { stopTimedOut = false; reply.error(`> ${action} job(s) had an error [${err.message}]`); jobsStopped = await status(false, false); } waitCountStop += 1; } let waitCount = 0; const waitMax = 15; while (!allJobsStopped) { jobsStopped = await status(false, false); await _.delay(() => {}, 50); if (jobsStopped.length === 0) { allJobsStopped = true; } if (waitCount >= waitMax) { break; } waitCount += 1; } if (allJobsStopped) { console.log('> All jobs %s.', await setAction(action, 'past')); if (cliConfig.add_annotation) { console.log('adding annotation'); await annotation.add(_.startCase(action)); } } } return allJobsStopped; } async function checkForId() { if (!_.has(cliConfig, 'job_id')) { reply.fatal('job id required'); } } async function start(action = 'start') { let jobs = []; // start job with job file if (!cliConfig.all_jobs) { await checkForId(); const id = await terasliceClient.jobs.wrap(cliConfig.job_id).config(); if (id !== undefined) { id.slicer = {}; id.slicer.workers_active = id.workers; jobs.push(id); } } else { jobs = await fs.readJson(cliConfig.state_file); } if (jobs.length === 0) { reply.error(`No jobs to ${action}`); return; } if (cliConfig.info) { await displayInfo(); } await displayJobs(jobs, true); /* if (_.has(cliConfig, 'job_id')) { cliConfig.yes = true; } */ if (jobs.length === 1) { cliConfig.yes = true; } if (cliConfig.yes || await showPrompt(action)) { await changeStatus(jobs, action); let waitCount = 0; const waitMax = 10; let jobsStarted = 0; let allWorkersStarted = false; console.log('> Waiting for workers to start'); while (!allWorkersStarted || waitCount < waitMax) { jobsStarted = await status(false, false); waitCount += 1; allWorkersStarted = await checkWorkerCount(jobs, jobsStarted); } let allAddedWorkersStarted = false; if (allWorkersStarted) { // add extra workers waitCount = 0; await addWorkers(jobs, jobsStarted); while (!allAddedWorkersStarted || waitCount < waitMax) { jobsStarted = await status(false, false); waitCount += 1; allAddedWorkersStarted = await checkWorkerCount(jobs, jobsStarted, true); } } if (allAddedWorkersStarted) { await status(false, true); console.log('> All jobs and workers %s', await setAction(action, 'past')); if (cliConfig.add_annotation) { await annotation.add(_.startCase(action)); } } } else { console.log('bye!'); } } async function workers() { await checkForId(); const response = await terasliceClient.jobs.wrap(cliConfig.job_id) .changeWorkers(cliConfig.action, cliConfig.num); console.log(`> job: ${cliConfig.job_id} ${response}`); } async function pause() { await stop('pause'); } async function resume() { await start('resume'); } async function addWorkers(expectedJobs, actualJobs) { for (const job of actualJobs) { for (const expectedJob of expectedJobs) { let addWorkersOnce = true; if (expectedJob.job_id === job.job_id) { if (addWorkersOnce) { let workers2add = 0; if (_.has(expectedJob, 'slicer.workers_active')) { workers2add = expectedJob.slicer.workers_active - expectedJob.workers; } if (workers2add > 0) { console.log(`> Adding ${workers2add} worker(s) to ${job.job_id}`); await terasliceClient.jobs.wrap(job.job_id).changeWorkers('add', workers2add); await _.delay(() => {}, 50); } addWorkersOnce = false; } } } } } async function checkWorkerCount(expectedJobs, actualJobs, addedWorkers = false) { let allWorkersStartedCount = 0; let allWorkers = false; let expectedWorkers = 0; let activeWorkers = 0; for (const job of actualJobs) { for (const expectedJob of expectedJobs) { if (expectedJob.job_id === job.job_id) { if (addedWorkers) { if (_.has(expectedJob, 'slicer.workers_active')) { expectedWorkers = job.slicer.workers_active; } else { reply.fatal('no expected workers'); } } else { expectedWorkers = expectedJob.workers; } if (_.has(job, 'slicer.workers_active')) { activeWorkers = job.slicer.workers_active; } if (expectedWorkers === activeWorkers) { allWorkersStartedCount += 1; } } } } if (allWorkersStartedCount === expectedJobs.length) { allWorkers = true; } return allWorkers; } async function save() { return status(true, true); } async function status(saveState = false, showJobs = true) { const jobs = []; if (cliConfig.info) { await displayInfo(); } let controllers = ''; try { controllers = await terasliceClient.cluster.controllers(); } catch (e) { controllers = await terasliceClient.cluster.slicers(); } for (const jobStatus of cliConfig.statusList) { let jobsTemp = ''; const exResult = await terasliceClient.ex.list(jobStatus); jobsTemp = await controllerStatus(exResult, jobStatus, controllers); _.each(jobsTemp, (job) => { jobs.push(job); }); } if (jobs.length > 0) { if (showJobs) { await displayJobs(jobs); } if (saveState) { await fs.writeJson(cliConfig.state_file, jobs, { spaces: 4 }); } } else { reply.error(`no jobs on ${cliConfig.cluster}`); } return jobs; } async function list() { if (cliConfig.info) { await displayInfo(); } const jobs = await terasliceClient.jobs.list(); if (jobs.length > 0) { await displayJobsList(jobs, false); } return jobs; } async function run() { await start(); } async function recover() { const response = await terasliceClient.jobs.wrap(cliConfig.job_id).recover(); if (_.has(response, 'job_id')) { console.log(`> job_id ${cliConfig.job_id} recovered`); } else { console.log(response); } } async function view() { // view job on cluster await checkForId(); const response = await terasliceClient.jobs.wrap(cliConfig.job_id).config(); console.log(JSON.stringify(response, null, 4)); } async function errors() { await checkForId(); const response = await terasliceClient.jobs.wrap(cliConfig.job_id).errors(); if (response.length === 0) { console.log(`job_id:${cliConfig.job_id} no errors`); } else { let count = 0; const size = parseInt(cliConfig.size, 10); console.log(`Errors job_id:${cliConfig.job_id}`); _.each(response, (error) => { _.each(error, (value, key) => { console.log(`${key} : ${value}`); }); count += 1; console.log('-'.repeat(80)); if (count >= size) { return false; } }); } } async function displayJobs(jobs, file = false) { const headerJobs = await setHeaderDefaults(file); let jobsParsed = ''; if (cliConfig.output_style === 'txt') { jobsParsed = await parseJobResponseTxt(jobs, file); } else { jobsParsed = await parseJobResponse(jobs, file); } await display.display(headerJobs, jobsParsed, cliConfig.output_style); } async function displayJobsList(jobs, file = false) { const headerJobs = ['job_id', 'name', 'lifecycle', 'slicers', 'workers', '_created', '_updated']; let jobsParsed = ''; if (cliConfig.output_style === 'txt') { jobsParsed = await parseJobResponseTxt(jobs, true); } else { jobsParsed = await parseJobResponse(jobs, file, true); } await display.display(headerJobs, jobsParsed, cliConfig.output_style); } async function setAction(action, tense) { if (action === 'stop' && tense === 'past') { return 'stopped'; } if (action === 'stop' && tense === 'present') { return 'stopping'; } if (action === 'start' && tense === 'past') { return 'started'; } if (action === 'stop' && tense === 'present') { return 'starting'; } if (action === 'pause' && tense === 'past') { return 'paused'; } if (action === 'stop' && tense === 'present') { return 'pausing'; } if (action === 'restart' && tense === 'past') { return 'restarted'; } if (action === 'restart' && tense === 'present') { return 'restarting'; } if (action === 'resume' && tense === 'past') { return 'resumed'; } if (action === 'resume' && tense === 'present') { return 'resuming'; } return action; } async function displayInfo() { const header = ['host', 'state_file']; const rows = []; if (cliConfig.output_style === 'txt') { const row = {}; row.host = cliConfig.hostname; row.state_file = cliConfig.state_file; rows.push(row); } else { const row = []; row.push(cliConfig.hostname); row.push(cliConfig.state_file); rows.push(row); } await display.display(header, rows, cliConfig.output_style); } async function parseJobResponseTxt(response, isList = false) { if (!isList) { _.each(response, (value, node) => { if (_.has(response[node], 'slicer.workers_active')) { response[node].workers_active = response[node].slicer.workers_active; } else { response[node].workers_active = 0; } }); } return response; } async function parseJobResponse(response, file = false, isList = false) { const rows = []; _.each(response, (value, node) => { const row = []; row.push(response[node].job_id); row.push(response[node].name); if (!file || !isList) { row.push(response[node]._status); } row.push(response[node].lifecycle); row.push(response[node].slicers); row.push(response[node].workers); if (!isList) { if (_.has(response[node], 'slicer.workers_active')) { row.push(response[node].slicer.workers_active); } else { row.push(0); } } row.push(response[node]._created); row.push(response[node]._updated); rows.push(row); }); return rows; } async function setHeaderDefaults(file = false) { let defaults = []; if (file) { defaults = ['job_id', 'name', 'lifecycle', 'slicers', 'workers', 'workers_active', '_created', '_updated']; } else { defaults = ['job_id', 'name', '_status', 'lifecycle', 'slicers', 'workers', 'workers_active', '_created', '_updated']; } return defaults; } async function changeStatus(jobs, action) { console.log(`> Waiting for jobs to ${action}`); const response = jobs.map((job) => { if (action === 'stop') { return terasliceClient.jobs.wrap(job.job_id).stop() .then((stopResponse) => { if (stopResponse.status.status === 'stopped' || stopResponse.status === 'stopped') { return setAction(action, 'past') .then((setActionResult) => { console.log('> job: %s %s', job.job_id, setActionResult); }); } else { return setAction(action, 'present') .then((setActionResult) => { console.log('> job: %s error %s', job.job_id, setActionResult); }); } }); } if (action === 'start') { return terasliceClient.jobs.wrap(job.job_id).start() .then((startResponse) => { if (startResponse.job_id === job.job_id) { return setAction(action, 'past') .then((setActionResult) => { console.log('> job: %s %s', job.job_id, setActionResult); }); } else { return setAction(action, 'present') .then((setActionResult) => { console.log('> job: %s error %s', job.job_id, setActionResult); }); } }); } if (action === 'resume') { return terasliceClient.jobs.wrap(job.job_id).resume() .then((resumeResponse) => { if (resumeResponse.status.status === 'running' || resumeResponse.status === 'running') { return setAction(action, 'past') .then((setActionResult) => { console.log('> job: %s %s', job.job_id, setActionResult); }); } else { return setAction(action, 'present') .then((setActionResult) => { console.log('> job: %s error %s', job.job_id, setActionResult); }); } }); } if (action === 'pause') { return terasliceClient.jobs.wrap(job.job_id).pause() .then((pauseResponse) => { if (pauseResponse.status.status === 'paused' || pauseResponse.status === 'paused') { return setAction(action, 'past') .then((setActionResult) => { console.log('> job: %s %s', job.job_id, setActionResult); }); } else { return setAction(action, 'present') .then((setActionResult) => { reply.error('> job: %s error %s', job.job_id, setActionResult); }); } }); } }); return Promise.all(response); } async function controllerStatus(result, jobStatus, controllerList) { const jobs = []; for (const item of result) { if (jobStatus === 'running' || jobStatus === 'failing') { _.set(item, 'slicer', _.find(controllerList, { job_id: `${item.job_id}` })); } else { item.slicer = 0; } jobs.push(item); } return jobs; } return { errors, list, pause, recover, restart, resume, run, save, start, status, stop, workers, view, }; };
jsnoble/teraslice
packages/teraslice-cli/cmds/jobs/lib/index.js
JavaScript
apache-2.0
19,757
package android.support.v4.content; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.support.v4.os.CancellationSignal; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.Arrays; public class CursorLoader extends AsyncTaskLoader<Cursor> { CancellationSignal mCancellationSignal; Cursor mCursor; final Loader<Cursor>.android.support.v4.content.Loader.android.support.v4.content.Loader.android.support.v4.content.Loader.ForceLoadContentObserver mObserver = new Loader.ForceLoadContentObserver(this); public String[] mProjection; String mSelection; String[] mSelectionArgs; String mSortOrder; public Uri mUri; public CursorLoader(Context paramContext) { super(paramContext); } private void deliverResult(Cursor paramCursor) { if (this.mReset) { if (paramCursor != null) { paramCursor.close(); } } Cursor localCursor; do { return; localCursor = this.mCursor; this.mCursor = paramCursor; if (this.mStarted) { super.deliverResult(paramCursor); } } while ((localCursor == null) || (localCursor == paramCursor) || (localCursor.isClosed())); localCursor.close(); } /* Error */ public final void cancelLoadInBackground() { // Byte code: // 0: aload_0 // 1: invokespecial 60 android/support/v4/content/AsyncTaskLoader:cancelLoadInBackground ()V // 4: aload_0 // 5: monitorenter // 6: aload_0 // 7: getfield 62 android/support/v4/content/CursorLoader:mCancellationSignal Landroid/support/v4/os/CancellationSignal; // 10: ifnull +19 -> 29 // 13: aload_0 // 14: getfield 62 android/support/v4/content/CursorLoader:mCancellationSignal Landroid/support/v4/os/CancellationSignal; // 17: astore_2 // 18: aload_2 // 19: monitorenter // 20: aload_2 // 21: getfield 67 android/support/v4/os/CancellationSignal:mIsCanceled Z // 24: ifeq +8 -> 32 // 27: aload_2 // 28: monitorexit // 29: aload_0 // 30: monitorexit // 31: return // 32: aload_2 // 33: iconst_1 // 34: putfield 67 android/support/v4/os/CancellationSignal:mIsCanceled Z // 37: aload_2 // 38: iconst_1 // 39: putfield 70 android/support/v4/os/CancellationSignal:mCancelInProgress Z // 42: aload_2 // 43: getfield 74 android/support/v4/os/CancellationSignal:mCancellationSignalObj Ljava/lang/Object; // 46: astore 4 // 48: aload_2 // 49: monitorexit // 50: aload 4 // 52: ifnull +11 -> 63 // 55: aload 4 // 57: checkcast 76 android/os/CancellationSignal // 60: invokevirtual 79 android/os/CancellationSignal:cancel ()V // 63: aload_2 // 64: monitorenter // 65: aload_2 // 66: iconst_0 // 67: putfield 70 android/support/v4/os/CancellationSignal:mCancelInProgress Z // 70: aload_2 // 71: invokevirtual 84 java/lang/Object:notifyAll ()V // 74: aload_2 // 75: monitorexit // 76: goto -47 -> 29 // 79: astore 5 // 81: aload_2 // 82: monitorexit // 83: aload 5 // 85: athrow // 86: astore_1 // 87: aload_0 // 88: monitorexit // 89: aload_1 // 90: athrow // 91: astore_3 // 92: aload_2 // 93: monitorexit // 94: aload_3 // 95: athrow // 96: astore 6 // 98: aload_2 // 99: monitorenter // 100: aload_2 // 101: iconst_0 // 102: putfield 70 android/support/v4/os/CancellationSignal:mCancelInProgress Z // 105: aload_2 // 106: invokevirtual 84 java/lang/Object:notifyAll ()V // 109: aload_2 // 110: monitorexit // 111: aload 6 // 113: athrow // 114: astore 7 // 116: aload_2 // 117: monitorexit // 118: aload 7 // 120: athrow // Local variable table: // start length slot name signature // 0 121 0 this CursorLoader // 86 4 1 localObject1 java.lang.Object // 17 100 2 localCancellationSignal CancellationSignal // 91 4 3 localObject2 java.lang.Object // 46 10 4 localObject3 java.lang.Object // 79 5 5 localObject4 java.lang.Object // 96 16 6 localObject5 java.lang.Object // 114 5 7 localObject6 java.lang.Object // Exception table: // from to target type // 65 76 79 finally // 81 83 79 finally // 6 20 86 finally // 29 31 86 finally // 63 65 86 finally // 83 86 86 finally // 87 89 86 finally // 94 96 86 finally // 98 100 86 finally // 111 114 86 finally // 118 121 86 finally // 20 29 91 finally // 32 50 91 finally // 92 94 91 finally // 55 63 96 finally // 100 111 114 finally // 116 118 114 finally } public final void dump(String paramString, FileDescriptor paramFileDescriptor, PrintWriter paramPrintWriter, String[] paramArrayOfString) { super.dump(paramString, paramFileDescriptor, paramPrintWriter, paramArrayOfString); paramPrintWriter.print(paramString); paramPrintWriter.print("mUri="); paramPrintWriter.println(this.mUri); paramPrintWriter.print(paramString); paramPrintWriter.print("mProjection="); paramPrintWriter.println(Arrays.toString(this.mProjection)); paramPrintWriter.print(paramString); paramPrintWriter.print("mSelection="); paramPrintWriter.println(this.mSelection); paramPrintWriter.print(paramString); paramPrintWriter.print("mSelectionArgs="); paramPrintWriter.println(Arrays.toString(this.mSelectionArgs)); paramPrintWriter.print(paramString); paramPrintWriter.print("mSortOrder="); paramPrintWriter.println(this.mSortOrder); paramPrintWriter.print(paramString); paramPrintWriter.print("mCursor="); paramPrintWriter.println(this.mCursor); paramPrintWriter.print(paramString); paramPrintWriter.print("mContentChanged="); paramPrintWriter.println(this.mContentChanged); } /* Error */ public Cursor loadInBackground() { // Byte code: // 0: aload_0 // 1: monitorenter // 2: aload_0 // 3: getfield 145 android/support/v4/content/AsyncTaskLoader:mCancellingTask Landroid/support/v4/content/AsyncTaskLoader$LoadTask; // 6: ifnull +22 -> 28 // 9: iconst_1 // 10: istore_2 // 11: iload_2 // 12: ifeq +21 -> 33 // 15: new 147 android/support/v4/os/OperationCanceledException // 18: dup // 19: invokespecial 149 android/support/v4/os/OperationCanceledException:<init> ()V // 22: athrow // 23: astore_1 // 24: aload_0 // 25: monitorexit // 26: aload_1 // 27: athrow // 28: iconst_0 // 29: istore_2 // 30: goto -19 -> 11 // 33: aload_0 // 34: new 64 android/support/v4/os/CancellationSignal // 37: dup // 38: invokespecial 150 android/support/v4/os/CancellationSignal:<init> ()V // 41: putfield 62 android/support/v4/content/CursorLoader:mCancellationSignal Landroid/support/v4/os/CancellationSignal; // 44: aload_0 // 45: monitorexit // 46: aload_0 // 47: getfield 154 android/support/v4/content/Loader:mContext Landroid/content/Context; // 50: invokevirtual 160 android/content/Context:getContentResolver ()Landroid/content/ContentResolver; // 53: aload_0 // 54: getfield 100 android/support/v4/content/CursorLoader:mUri Landroid/net/Uri; // 57: aload_0 // 58: getfield 107 android/support/v4/content/CursorLoader:mProjection [Ljava/lang/String; // 61: aload_0 // 62: getfield 119 android/support/v4/content/CursorLoader:mSelection Ljava/lang/String; // 65: aload_0 // 66: getfield 123 android/support/v4/content/CursorLoader:mSelectionArgs [Ljava/lang/String; // 69: aload_0 // 70: getfield 127 android/support/v4/content/CursorLoader:mSortOrder Ljava/lang/String; // 73: aload_0 // 74: getfield 62 android/support/v4/content/CursorLoader:mCancellationSignal Landroid/support/v4/os/CancellationSignal; // 77: invokestatic 166 android/support/v4/content/ContentResolverCompat:query (Landroid/content/ContentResolver;Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;Landroid/support/v4/os/CancellationSignal;)Landroid/database/Cursor; // 80: astore 5 // 82: aload 5 // 84: ifnull +22 -> 106 // 87: aload 5 // 89: invokeinterface 170 1 0 // 94: pop // 95: aload 5 // 97: aload_0 // 98: getfield 31 android/support/v4/content/CursorLoader:mObserver Landroid/support/v4/content/Loader$ForceLoadContentObserver; // 101: invokeinterface 174 2 0 // 106: aload_0 // 107: monitorenter // 108: aload_0 // 109: aconst_null // 110: putfield 62 android/support/v4/content/CursorLoader:mCancellationSignal Landroid/support/v4/os/CancellationSignal; // 113: aload_0 // 114: monitorexit // 115: aload 5 // 117: areturn // 118: astore 7 // 120: aload 5 // 122: invokeinterface 45 1 0 // 127: aload 7 // 129: athrow // 130: astore_3 // 131: aload_0 // 132: monitorenter // 133: aload_0 // 134: aconst_null // 135: putfield 62 android/support/v4/content/CursorLoader:mCancellationSignal Landroid/support/v4/os/CancellationSignal; // 138: aload_0 // 139: monitorexit // 140: aload_3 // 141: athrow // 142: astore 6 // 144: aload_0 // 145: monitorexit // 146: aload 6 // 148: athrow // 149: astore 4 // 151: aload_0 // 152: monitorexit // 153: aload 4 // 155: athrow // Local variable table: // start length slot name signature // 0 156 0 this CursorLoader // 23 4 1 localObject1 java.lang.Object // 10 20 2 i int // 130 11 3 localObject2 java.lang.Object // 149 5 4 localObject3 java.lang.Object // 80 41 5 localCursor Cursor // 142 5 6 localObject4 java.lang.Object // 118 10 7 localRuntimeException java.lang.RuntimeException // Exception table: // from to target type // 2 9 23 finally // 15 23 23 finally // 24 26 23 finally // 33 46 23 finally // 87 106 118 java/lang/RuntimeException // 46 82 130 finally // 87 106 130 finally // 120 130 130 finally // 108 115 142 finally // 144 146 142 finally // 133 140 149 finally // 151 153 149 finally } protected final void onReset() { super.onReset(); cancelLoad(); if ((this.mCursor != null) && (!this.mCursor.isClosed())) { this.mCursor.close(); } this.mCursor = null; } protected final void onStartLoading() { if (this.mCursor != null) { deliverResult(this.mCursor); } if ((takeContentChanged()) || (this.mCursor == null)) { forceLoad(); } } protected final void onStopLoading() { cancelLoad(); } } /* Location: F:\apktool\apktool\Google_Play_Store6.0.5\classes-dex2jar.jar * Qualified Name: android.support.v4.content.CursorLoader * JD-Core Version: 0.7.0.1 */
ChiangC/FMTech
GooglePlay6.0.5/app/src/main/java/android/support/v4/content/CursorLoader.java
Java
apache-2.0
11,670
package com.lizhi.library.widget; import android.content.Context; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.AttributeSet; import android.widget.EditText; /** * Created by jacob on 15/7/15. */ public class NumericView extends EditText implements TextWatcher { private String value = ""; public NumericView(Context context) { super(context); addTextChangedListener(this); } public NumericView(Context context, AttributeSet attrs) { super(context, attrs); addTextChangedListener(this); } public NumericView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); addTextChangedListener(this); } @Override public void beforeTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable editable) { int dotNum = 0; String string = editable.toString(); for (int i = 0; i < string.length(); i++) { char mchar = string.charAt(i); if (i == 0 && mchar == '.') { editable.delete(0, 1); return; } else if (mchar == '.') { dotNum++; if (dotNum == 2) { editable.delete(i, i + 1); return; } } } if( string.length() > 2 && string.length() - string.indexOf('.') > 3 && string.contains(".")) { editable.delete(string.length() -2,string.length() - 1); } if (!TextUtils.isEmpty(string)) { if(string.charAt(string.length() - 1) == '.') { string = string.substring(0,string.length() -1); } float interger = Float.valueOf(string); if (interger > 65536) { System.out.println("string =" + string); if(string.contains(".")) { editable.delete(string.indexOf(".") - 1, string.length()-1); } else editable.delete(string.length() - 2, string.length()-1); } } } @Override public void onTextChanged(CharSequence string, int start, int end, int var4) { } }
xuhongjia/RxAndroidEvents
lzlibrary/src/main/java/com/lizhi/library/widget/NumericView.java
Java
apache-2.0
2,407
/** * Copyright 2018 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. */ import keyMirror from 'keymirror'; import { defineMessages } from 'react-intl'; export const CONFIG_DOWNLOAD_MESSAGE = 'CONFIG_DOWNLOAD_MESSAGE'; export const GET_DEPLOYMENT_STATUS_FAILED = 'GET_DEPLOYMENT_STATUS_FAILED'; export const GET_DEPLOYMENT_STATUS_SUCCESS = 'GET_DEPLOYMENT_STATUS_SUCCESS'; export const GET_DEPLOYMENT_STATUS_PENDING = 'GET_DEPLOYMENT_STATUS_PENDING'; export const START_DEPLOYMENT_FAILED = 'START_DEPLOYMENT_FAILED'; export const START_DEPLOYMENT_SUCCESS = 'START_DEPLOYMENT_SUCCESS'; export const START_DEPLOYMENT_PENDING = 'START_DEPLOYMENT_PENDING'; export const DEPLOYMENT_FAILED = 'DEPLOYMENT_FAILED'; export const DEPLOYMENT_SUCCESS = 'DEPLOYMENT_SUCCESS'; export const START_UNDEPLOY_FAILED = 'START_UNDEPLOY_FAILED'; export const START_UNDEPLOY_SUCCESS = 'START_UNDEPLOY_SUCCESS'; export const START_UNDEPLOY_PENDING = 'START_UNDEPLOY_PENDING'; export const UNDEPLOY_FAILED = 'UNDEPLOY_FAILED'; export const UNDEPLOY_SUCCESS = 'UNDEPLOY_SUCCESS'; export const RECOVER_DEPLOYMENT_STATUS_FAILED = 'RECOVER_DEPLOYMENT_STATUS_FAILED'; export const RECOVER_DEPLOYMENT_STATUS_SUCCESS = 'RECOVER_DEPLOYMENT_STATUS_SUCCESS'; export const RECOVER_DEPLOYMENT_STATUS_PENDING = 'RECOVER_DEPLOYMENT_STATUS_PENDING'; export const deploymentStates = keyMirror({ UNDEPLOYED: null, DEPLOY_SUCCESS: null, DEPLOYING: null, UNDEPLOYING: null, DEPLOY_FAILED: null, UNDEPLOY_FAILED: null, UNKNOWN: null }); export const shortDeploymentStatusMessages = defineMessages({ UNDEPLOYED: { id: 'DeploymentStatusShort.undeployed', defaultMessage: 'Not deployed' }, DEPLOY_SUCCESS: { id: 'DeploymentStatusShort.deployed', defaultMessage: 'Deployment succeeded' }, DEPLOYING: { id: 'DeploymentStatusShort.deploying', defaultMessage: 'Deployment in progress' }, UNDEPLOYING: { id: 'DeploymentStatusShort.undeploying', defaultMessage: 'Deployment deletion in progress' }, DEPLOY_FAILED: { id: 'DeploymentStatusShort.deploymentFailed', defaultMessage: 'Deployment failed' }, UNDEPLOY_FAILED: { id: 'DeploymentStatusShort.undeployFailed', defaultMessage: 'Undeploy failed' }, UNKNOWN: { id: 'DeploymentStatusShort.unknown', defaultMessage: 'Deployment status could not be loaded' } }); export const deploymentStatusMessages = defineMessages({ UNDEPLOYED: { id: 'DeploymentStatus.undeployed', defaultMessage: 'Deployment not started' }, DEPLOY_SUCCESS: { id: 'DeploymentStatus.deployed', defaultMessage: 'Deployment succeeded' }, DEPLOYING: { id: 'DeploymentStatus.deploying', defaultMessage: 'Deployment of {planName} plan is currently in progress' }, UNDEPLOYING: { id: 'DeploymentStatus.undeploying', defaultMessage: 'Deletion of {planName} plan deployment is currently in progress' }, DEPLOY_FAILED: { id: 'DeploymentStatus.deploymentFailed', defaultMessage: 'Deployment of {planName} plan failed' }, UNDEPLOY_FAILED: { id: 'DeploymentStatus.undeployFailed', defaultMessage: 'Undeploy failed' }, UNKNOWN: { id: 'DeploymentStatus.unknown', defaultMessage: 'Plan {planName} deployment status could not be loaded' } });
knowncitizen/tripleo-ui
src/js/constants/DeploymentConstants.js
JavaScript
apache-2.0
3,813
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rioproject.tools.cli; import net.jini.core.lookup.ServiceItem; import org.rioproject.cybernode.Cybernode; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * Handles enlistment and release of Cybernodes */ public class EnlistmentHandler { static final String ENLIST = "enlist"; static final String RELEASE = "release"; public static class EnlistHandler implements OptionHandler { @Override public String process(final String input, final BufferedReader br, final PrintStream out) { return handleRequest(input, br, out); } @Override public String getUsage() { return ("usage: enlist "); } } public static class ReleaseHandler implements OptionHandler { @Override public String process(final String input, final BufferedReader br, final PrintStream out) { return handleRequest(input, br, out); } @Override public String getUsage() { return ("usage: release"); } } private static ServiceItem[] getCybernodes(final String action) throws RemoteException { List<ServiceItem> list = new ArrayList<ServiceItem>(); ServiceItem[] items = CLI.getInstance().getServiceFinder().findCybernodes(null, null); for(ServiceItem item : items) { Cybernode c = (Cybernode)item.service; if(action.equals(RELEASE)) { if(c.isEnlisted()) { list.add(item); } } else { if(!c.isEnlisted()) { list.add(item); } } } return list.toArray(new ServiceItem[list.size()]); } private static void printRequest(final PrintStream out, final String action) { out.print("Enter cybernode to " + action + " or \"c\" to cancel : "); } private static String handleRequest(final String input, final BufferedReader br, final PrintStream out) { if (out == null) throw new IllegalArgumentException("Must have an output PrintStream"); BufferedReader reader = br; if (reader == null) reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(input); /* first token is "enlist" or "release" */ String action = tok.nextToken(); ServiceItem[] items; try { items = getCybernodes(action); } catch (RemoteException e) { e.printStackTrace(); return ("Problem checking cybernode enlistment status , " + "Exception : " + e.getLocalizedMessage() + "\n"); } if(items.length==0) { StringBuilder sb = new StringBuilder(); String word = action.equals(ENLIST)?"enlisted":"released"; sb.append("All cybernodes are ").append(word); return sb.toString(); } out.println(Formatter.asChoices(items) + "\n"); printRequest(out, action); while (true) { try { String response = reader.readLine(); if (response != null) { if (response.equals("c")) break; try { int num = Integer.parseInt(response); if (num < 1 || num > (items.length + 1)) { printRequest(out, action); } else { if (num == (items.length + 1)) { for(ServiceItem item : items) { Cybernode cybernode = (Cybernode)item.service; handleAction(cybernode, action); } } else { Cybernode cybernode = (Cybernode)items[num-1].service; handleAction(cybernode, action); } break; } } catch (NumberFormatException e) { out.println("Invalid choice [" + response + "]"); printRequest(out, action); } } } catch (IOException e) { e.printStackTrace(); } } return (""); } private static void handleAction(final Cybernode cybernode, final String action) throws RemoteException { if(action.equals(ENLIST)) cybernode.enlist(); else cybernode.release(true); } }
khartig/assimilator
rio-tools/rio-cli/src/main/java/org/rioproject/tools/cli/EnlistmentHandler.java
Java
apache-2.0
5,485
/* * Copyright 2014-2019 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.redshift.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * Describes a subnet group. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/ClusterSubnetGroup" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ClusterSubnetGroup implements Serializable, Cloneable { /** * <p> * The name of the cluster subnet group. * </p> */ private String clusterSubnetGroupName; /** * <p> * The description of the cluster subnet group. * </p> */ private String description; /** * <p> * The VPC ID of the cluster subnet group. * </p> */ private String vpcId; /** * <p> * The status of the cluster subnet group. Possible values are <code>Complete</code>, <code>Incomplete</code> and * <code>Invalid</code>. * </p> */ private String subnetGroupStatus; /** * <p> * A list of the VPC <a>Subnet</a> elements. * </p> */ private com.amazonaws.internal.SdkInternalList<Subnet> subnets; /** * <p> * The list of tags for the cluster subnet group. * </p> */ private com.amazonaws.internal.SdkInternalList<Tag> tags; /** * <p> * The name of the cluster subnet group. * </p> * * @param clusterSubnetGroupName * The name of the cluster subnet group. */ public void setClusterSubnetGroupName(String clusterSubnetGroupName) { this.clusterSubnetGroupName = clusterSubnetGroupName; } /** * <p> * The name of the cluster subnet group. * </p> * * @return The name of the cluster subnet group. */ public String getClusterSubnetGroupName() { return this.clusterSubnetGroupName; } /** * <p> * The name of the cluster subnet group. * </p> * * @param clusterSubnetGroupName * The name of the cluster subnet group. * @return Returns a reference to this object so that method calls can be chained together. */ public ClusterSubnetGroup withClusterSubnetGroupName(String clusterSubnetGroupName) { setClusterSubnetGroupName(clusterSubnetGroupName); return this; } /** * <p> * The description of the cluster subnet group. * </p> * * @param description * The description of the cluster subnet group. */ public void setDescription(String description) { this.description = description; } /** * <p> * The description of the cluster subnet group. * </p> * * @return The description of the cluster subnet group. */ public String getDescription() { return this.description; } /** * <p> * The description of the cluster subnet group. * </p> * * @param description * The description of the cluster subnet group. * @return Returns a reference to this object so that method calls can be chained together. */ public ClusterSubnetGroup withDescription(String description) { setDescription(description); return this; } /** * <p> * The VPC ID of the cluster subnet group. * </p> * * @param vpcId * The VPC ID of the cluster subnet group. */ public void setVpcId(String vpcId) { this.vpcId = vpcId; } /** * <p> * The VPC ID of the cluster subnet group. * </p> * * @return The VPC ID of the cluster subnet group. */ public String getVpcId() { return this.vpcId; } /** * <p> * The VPC ID of the cluster subnet group. * </p> * * @param vpcId * The VPC ID of the cluster subnet group. * @return Returns a reference to this object so that method calls can be chained together. */ public ClusterSubnetGroup withVpcId(String vpcId) { setVpcId(vpcId); return this; } /** * <p> * The status of the cluster subnet group. Possible values are <code>Complete</code>, <code>Incomplete</code> and * <code>Invalid</code>. * </p> * * @param subnetGroupStatus * The status of the cluster subnet group. Possible values are <code>Complete</code>, <code>Incomplete</code> * and <code>Invalid</code>. */ public void setSubnetGroupStatus(String subnetGroupStatus) { this.subnetGroupStatus = subnetGroupStatus; } /** * <p> * The status of the cluster subnet group. Possible values are <code>Complete</code>, <code>Incomplete</code> and * <code>Invalid</code>. * </p> * * @return The status of the cluster subnet group. Possible values are <code>Complete</code>, * <code>Incomplete</code> and <code>Invalid</code>. */ public String getSubnetGroupStatus() { return this.subnetGroupStatus; } /** * <p> * The status of the cluster subnet group. Possible values are <code>Complete</code>, <code>Incomplete</code> and * <code>Invalid</code>. * </p> * * @param subnetGroupStatus * The status of the cluster subnet group. Possible values are <code>Complete</code>, <code>Incomplete</code> * and <code>Invalid</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public ClusterSubnetGroup withSubnetGroupStatus(String subnetGroupStatus) { setSubnetGroupStatus(subnetGroupStatus); return this; } /** * <p> * A list of the VPC <a>Subnet</a> elements. * </p> * * @return A list of the VPC <a>Subnet</a> elements. */ public java.util.List<Subnet> getSubnets() { if (subnets == null) { subnets = new com.amazonaws.internal.SdkInternalList<Subnet>(); } return subnets; } /** * <p> * A list of the VPC <a>Subnet</a> elements. * </p> * * @param subnets * A list of the VPC <a>Subnet</a> elements. */ public void setSubnets(java.util.Collection<Subnet> subnets) { if (subnets == null) { this.subnets = null; return; } this.subnets = new com.amazonaws.internal.SdkInternalList<Subnet>(subnets); } /** * <p> * A list of the VPC <a>Subnet</a> elements. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setSubnets(java.util.Collection)} or {@link #withSubnets(java.util.Collection)} if you want to override * the existing values. * </p> * * @param subnets * A list of the VPC <a>Subnet</a> elements. * @return Returns a reference to this object so that method calls can be chained together. */ public ClusterSubnetGroup withSubnets(Subnet... subnets) { if (this.subnets == null) { setSubnets(new com.amazonaws.internal.SdkInternalList<Subnet>(subnets.length)); } for (Subnet ele : subnets) { this.subnets.add(ele); } return this; } /** * <p> * A list of the VPC <a>Subnet</a> elements. * </p> * * @param subnets * A list of the VPC <a>Subnet</a> elements. * @return Returns a reference to this object so that method calls can be chained together. */ public ClusterSubnetGroup withSubnets(java.util.Collection<Subnet> subnets) { setSubnets(subnets); return this; } /** * <p> * The list of tags for the cluster subnet group. * </p> * * @return The list of tags for the cluster subnet group. */ public java.util.List<Tag> getTags() { if (tags == null) { tags = new com.amazonaws.internal.SdkInternalList<Tag>(); } return tags; } /** * <p> * The list of tags for the cluster subnet group. * </p> * * @param tags * The list of tags for the cluster subnet group. */ public void setTags(java.util.Collection<Tag> tags) { if (tags == null) { this.tags = null; return; } this.tags = new com.amazonaws.internal.SdkInternalList<Tag>(tags); } /** * <p> * The list of tags for the cluster subnet group. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setTags(java.util.Collection)} or {@link #withTags(java.util.Collection)} if you want to override the * existing values. * </p> * * @param tags * The list of tags for the cluster subnet group. * @return Returns a reference to this object so that method calls can be chained together. */ public ClusterSubnetGroup withTags(Tag... tags) { if (this.tags == null) { setTags(new com.amazonaws.internal.SdkInternalList<Tag>(tags.length)); } for (Tag ele : tags) { this.tags.add(ele); } return this; } /** * <p> * The list of tags for the cluster subnet group. * </p> * * @param tags * The list of tags for the cluster subnet group. * @return Returns a reference to this object so that method calls can be chained together. */ public ClusterSubnetGroup withTags(java.util.Collection<Tag> tags) { setTags(tags); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getClusterSubnetGroupName() != null) sb.append("ClusterSubnetGroupName: ").append(getClusterSubnetGroupName()).append(","); if (getDescription() != null) sb.append("Description: ").append(getDescription()).append(","); if (getVpcId() != null) sb.append("VpcId: ").append(getVpcId()).append(","); if (getSubnetGroupStatus() != null) sb.append("SubnetGroupStatus: ").append(getSubnetGroupStatus()).append(","); if (getSubnets() != null) sb.append("Subnets: ").append(getSubnets()).append(","); if (getTags() != null) sb.append("Tags: ").append(getTags()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ClusterSubnetGroup == false) return false; ClusterSubnetGroup other = (ClusterSubnetGroup) obj; if (other.getClusterSubnetGroupName() == null ^ this.getClusterSubnetGroupName() == null) return false; if (other.getClusterSubnetGroupName() != null && other.getClusterSubnetGroupName().equals(this.getClusterSubnetGroupName()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getVpcId() == null ^ this.getVpcId() == null) return false; if (other.getVpcId() != null && other.getVpcId().equals(this.getVpcId()) == false) return false; if (other.getSubnetGroupStatus() == null ^ this.getSubnetGroupStatus() == null) return false; if (other.getSubnetGroupStatus() != null && other.getSubnetGroupStatus().equals(this.getSubnetGroupStatus()) == false) return false; if (other.getSubnets() == null ^ this.getSubnets() == null) return false; if (other.getSubnets() != null && other.getSubnets().equals(this.getSubnets()) == false) return false; if (other.getTags() == null ^ this.getTags() == null) return false; if (other.getTags() != null && other.getTags().equals(this.getTags()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getClusterSubnetGroupName() == null) ? 0 : getClusterSubnetGroupName().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getVpcId() == null) ? 0 : getVpcId().hashCode()); hashCode = prime * hashCode + ((getSubnetGroupStatus() == null) ? 0 : getSubnetGroupStatus().hashCode()); hashCode = prime * hashCode + ((getSubnets() == null) ? 0 : getSubnets().hashCode()); hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode()); return hashCode; } @Override public ClusterSubnetGroup clone() { try { return (ClusterSubnetGroup) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
jentfoo/aws-sdk-java
aws-java-sdk-redshift/src/main/java/com/amazonaws/services/redshift/model/ClusterSubnetGroup.java
Java
apache-2.0
14,288
#ifdef ENVOY_GOOGLE_GRPC #include "common/grpc/google_async_client_impl.h" #include "extensions/grpc_credentials/well_known_names.h" #endif #include "test/common/grpc/grpc_client_integration_test_harness.h" namespace Envoy { namespace Grpc { namespace { // Parameterize the loopback test server socket address and gRPC client type. INSTANTIATE_TEST_SUITE_P(IpVersionsClientType, GrpcClientIntegrationTest, GRPC_CLIENT_INTEGRATION_PARAMS, GrpcClientIntegrationParamTest::protocolTestParamsToString); // Validate that a simple request-reply stream works. TEST_P(GrpcClientIntegrationTest, BasicStream) { initialize(); auto stream = createStream(empty_metadata_); stream->sendRequest(); stream->sendServerInitialMetadata(empty_metadata_); stream->sendReply(); stream->sendServerTrailers(Status::GrpcStatus::Ok, "", empty_metadata_); dispatcher_helper_.runDispatcher(); } // Validate that a client destruction with open streams cleans up appropriately. TEST_P(GrpcClientIntegrationTest, ClientDestruct) { initialize(); auto stream = createStream(empty_metadata_); stream->sendRequest(); grpc_client_.reset(); } // Validate that a simple request-reply unary RPC works. TEST_P(GrpcClientIntegrationTest, BasicRequest) { initialize(); auto request = createRequest(empty_metadata_); request->sendReply(); dispatcher_helper_.runDispatcher(); } // Validate that multiple streams work. TEST_P(GrpcClientIntegrationTest, MultiStream) { initialize(); auto stream_0 = createStream(empty_metadata_); auto stream_1 = createStream(empty_metadata_); stream_0->sendRequest(); stream_1->sendRequest(); stream_0->sendServerInitialMetadata(empty_metadata_); stream_0->sendReply(); stream_1->sendServerTrailers(Status::GrpcStatus::Unavailable, "", empty_metadata_, true); stream_0->sendServerTrailers(Status::GrpcStatus::Ok, "", empty_metadata_); dispatcher_helper_.runDispatcher(); } // Validate that multiple request-reply unary RPCs works. TEST_P(GrpcClientIntegrationTest, MultiRequest) { initialize(); auto request_0 = createRequest(empty_metadata_); auto request_1 = createRequest(empty_metadata_); request_1->sendReply(); request_0->sendReply(); dispatcher_helper_.runDispatcher(); } // Validate that a non-200 HTTP status results in the expected gRPC error. TEST_P(GrpcClientIntegrationTest, HttpNon200Status) { initialize(); for (const auto http_response_status : {400, 401, 403, 404, 429, 431}) { auto stream = createStream(empty_metadata_); const Http::TestHeaderMapImpl reply_headers{{":status", std::to_string(http_response_status)}}; stream->expectInitialMetadata(empty_metadata_); stream->expectTrailingMetadata(empty_metadata_); // Technically this should be // https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md // as given by Grpc::Utility::httpToGrpcStatus(), but the Google gRPC client treats // this as GrpcStatus::Canceled. stream->expectGrpcStatus(Status::GrpcStatus::Canceled); stream->fake_stream_->encodeHeaders(reply_headers, true); dispatcher_helper_.runDispatcher(); } } // Validate that a non-200 HTTP status results in fallback to grpc-status. TEST_P(GrpcClientIntegrationTest, GrpcStatusFallback) { initialize(); auto stream = createStream(empty_metadata_); const Http::TestHeaderMapImpl reply_headers{ {":status", "404"}, {"grpc-status", std::to_string(enumToInt(Status::GrpcStatus::PermissionDenied))}, {"grpc-message", "error message"}}; stream->expectInitialMetadata(empty_metadata_); stream->expectTrailingMetadata(empty_metadata_); stream->expectGrpcStatus(Status::GrpcStatus::PermissionDenied); stream->fake_stream_->encodeHeaders(reply_headers, true); dispatcher_helper_.runDispatcher(); } // Validate that a HTTP-level reset is handled as an INTERNAL gRPC error. TEST_P(GrpcClientIntegrationTest, HttpReset) { initialize(); auto stream = createStream(empty_metadata_); stream->sendServerInitialMetadata(empty_metadata_); dispatcher_helper_.runDispatcher(); stream->expectTrailingMetadata(empty_metadata_); stream->expectGrpcStatus(Status::GrpcStatus::Internal); stream->fake_stream_->encodeResetStream(); dispatcher_helper_.runDispatcher(); } // Validate that a reply with bad gRPC framing (compressed frames with Envoy // client) is handled as an INTERNAL gRPC error. TEST_P(GrpcClientIntegrationTest, BadReplyGrpcFraming) { initialize(); // Only testing behavior of Envoy client, since Google client handles // compressed frames. SKIP_IF_GRPC_CLIENT(ClientType::GoogleGrpc); auto stream = createStream(empty_metadata_); stream->sendRequest(); stream->sendServerInitialMetadata(empty_metadata_); stream->expectTrailingMetadata(empty_metadata_); stream->expectGrpcStatus(Status::GrpcStatus::Internal); Buffer::OwnedImpl reply_buffer("\xde\xad\xbe\xef\x00", 5); stream->fake_stream_->encodeData(reply_buffer, true); dispatcher_helper_.runDispatcher(); } // Validate that a reply with bad protobuf is handled as an INTERNAL gRPC error. TEST_P(GrpcClientIntegrationTest, BadReplyProtobuf) { initialize(); auto stream = createStream(empty_metadata_); stream->sendRequest(); stream->sendServerInitialMetadata(empty_metadata_); stream->expectTrailingMetadata(empty_metadata_); stream->expectGrpcStatus(Status::GrpcStatus::Internal); Buffer::OwnedImpl reply_buffer("\x00\x00\x00\x00\x02\xff\xff", 7); stream->fake_stream_->encodeData(reply_buffer, true); dispatcher_helper_.runDispatcher(); } // Validate that an out-of-range gRPC status is handled as an INVALID_CODE gRPC // error. TEST_P(GrpcClientIntegrationTest, OutOfRangeGrpcStatus) { initialize(); // TODO(htuch): there is an UBSAN issue with Google gRPC client library // handling of out-of-range status codes, see // https://circleci.com/gh/envoyproxy/envoy/20234?utm_campaign=vcs-integration-link&utm_medium=referral&utm_source=github-build-link // Need to fix this issue upstream first. SKIP_IF_GRPC_CLIENT(ClientType::GoogleGrpc); auto stream = createStream(empty_metadata_); stream->sendServerInitialMetadata(empty_metadata_); stream->sendReply(); EXPECT_CALL(*stream, onReceiveTrailingMetadata_(_)).WillExitIfNeeded(); dispatcher_helper_.setStreamEventPending(); stream->expectGrpcStatus(Status::GrpcStatus::InvalidCode); const Http::TestHeaderMapImpl reply_trailers{{"grpc-status", std::to_string(0x1337)}}; stream->fake_stream_->encodeTrailers(reply_trailers); dispatcher_helper_.runDispatcher(); } // Validate that a missing gRPC status is handled as an UNKNOWN gRPC error. TEST_P(GrpcClientIntegrationTest, MissingGrpcStatus) { initialize(); auto stream = createStream(empty_metadata_); stream->sendServerInitialMetadata(empty_metadata_); stream->sendReply(); EXPECT_CALL(*stream, onReceiveTrailingMetadata_(_)).WillExitIfNeeded(); dispatcher_helper_.setStreamEventPending(); stream->expectGrpcStatus(Status::GrpcStatus::Unknown); const Http::TestHeaderMapImpl reply_trailers{{"some", "other header"}}; stream->fake_stream_->encodeTrailers(reply_trailers); dispatcher_helper_.runDispatcher(); } // Validate that a reply terminated without trailers is handled as a gRPC error. TEST_P(GrpcClientIntegrationTest, ReplyNoTrailers) { initialize(); auto stream = createStream(empty_metadata_); stream->sendRequest(); stream->sendServerInitialMetadata(empty_metadata_); helloworld::HelloReply reply; reply.set_message(HELLO_REPLY); EXPECT_CALL(*stream, onReceiveMessage_(HelloworldReplyEq(HELLO_REPLY))).WillExitIfNeeded(); dispatcher_helper_.setStreamEventPending(); stream->expectTrailingMetadata(empty_metadata_); stream->expectGrpcStatus(Status::GrpcStatus::InvalidCode); auto serialized_response = Grpc::Common::serializeBody(reply); stream->fake_stream_->encodeData(*serialized_response, true); stream->fake_stream_->encodeResetStream(); dispatcher_helper_.runDispatcher(); } // Validate that sending client initial metadata works. TEST_P(GrpcClientIntegrationTest, StreamClientInitialMetadata) { initialize(); const TestMetadata initial_metadata = { {Http::LowerCaseString("foo"), "bar"}, {Http::LowerCaseString("baz"), "blah"}, }; auto stream = createStream(initial_metadata); stream->sendServerTrailers(Status::GrpcStatus::Ok, "", empty_metadata_, true); dispatcher_helper_.runDispatcher(); } // Validate that sending client initial metadata works. TEST_P(GrpcClientIntegrationTest, RequestClientInitialMetadata) { initialize(); const TestMetadata initial_metadata = { {Http::LowerCaseString("foo"), "bar"}, {Http::LowerCaseString("baz"), "blah"}, }; auto request = createRequest(initial_metadata); request->sendReply(); dispatcher_helper_.runDispatcher(); } // Validate that setting service-wide client initial metadata works. TEST_P(GrpcClientIntegrationTest, RequestServiceWideInitialMetadata) { service_wide_initial_metadata_.emplace_back(Http::LowerCaseString("foo"), "bar"); service_wide_initial_metadata_.emplace_back(Http::LowerCaseString("baz"), "blah"); initialize(); auto request = createRequest(empty_metadata_); request->sendReply(); dispatcher_helper_.runDispatcher(); } // Validate that receiving server initial metadata works. TEST_P(GrpcClientIntegrationTest, ServerInitialMetadata) { initialize(); auto stream = createStream(empty_metadata_); stream->sendRequest(); const TestMetadata initial_metadata = { {Http::LowerCaseString("foo"), "bar"}, {Http::LowerCaseString("baz"), "blah"}, }; stream->sendServerInitialMetadata(initial_metadata); stream->sendReply(); stream->sendServerTrailers(Status::GrpcStatus::Ok, "", empty_metadata_); dispatcher_helper_.runDispatcher(); } // Validate that receiving server trailing metadata works. TEST_P(GrpcClientIntegrationTest, ServerTrailingMetadata) { initialize(); auto stream = createStream(empty_metadata_); stream->sendRequest(); stream->sendServerInitialMetadata(empty_metadata_); stream->sendReply(); const TestMetadata trailing_metadata = { {Http::LowerCaseString("foo"), "bar"}, {Http::LowerCaseString("baz"), "blah"}, }; stream->sendServerTrailers(Status::GrpcStatus::Ok, "", trailing_metadata); dispatcher_helper_.runDispatcher(); } // Validate that a trailers-only response is handled for streams. TEST_P(GrpcClientIntegrationTest, StreamTrailersOnly) { initialize(); auto stream = createStream(empty_metadata_); stream->sendServerTrailers(Status::GrpcStatus::Ok, "", empty_metadata_, true); dispatcher_helper_.runDispatcher(); } // Validate that a trailers-only response is handled for requests, where it is // an error. TEST_P(GrpcClientIntegrationTest, RequestTrailersOnly) { initialize(); auto request = createRequest(empty_metadata_); const Http::TestHeaderMapImpl reply_headers{{":status", "200"}, {"grpc-status", "0"}}; EXPECT_CALL(*request->child_span_, setTag(Tracing::Tags::get().GrpcStatusCode, "0")); EXPECT_CALL(*request->child_span_, setTag(Tracing::Tags::get().Error, Tracing::Tags::get().True)); EXPECT_CALL(*request, onFailure(Status::Internal, "", _)).WillExitIfNeeded(); dispatcher_helper_.setStreamEventPending(); EXPECT_CALL(*request->child_span_, finishSpan()); request->fake_stream_->encodeTrailers(reply_headers); dispatcher_helper_.runDispatcher(); } // Validate that a trailers RESOURCE_EXHAUSTED reply is handled. TEST_P(GrpcClientIntegrationTest, ResourceExhaustedError) { initialize(); auto stream = createStream(empty_metadata_); stream->sendServerInitialMetadata(empty_metadata_); stream->sendReply(); dispatcher_helper_.runDispatcher(); stream->sendServerTrailers(Status::GrpcStatus::ResourceExhausted, "error message", empty_metadata_); dispatcher_helper_.runDispatcher(); } // Validate that a trailers Unauthenticated reply is handled. TEST_P(GrpcClientIntegrationTest, UnauthenticatedError) { initialize(); auto stream = createStream(empty_metadata_); stream->sendServerInitialMetadata(empty_metadata_); stream->sendServerTrailers(Status::GrpcStatus::Unauthenticated, "error message", empty_metadata_); dispatcher_helper_.runDispatcher(); } // Validate that a trailers reply is still handled even if a grpc status code larger than // MaximumValid, is handled. TEST_P(GrpcClientIntegrationTest, MaximumValidPlusOne) { initialize(); auto stream = createStream(empty_metadata_); stream->sendServerInitialMetadata(empty_metadata_); stream->sendServerTrailers(static_cast<Status::GrpcStatus>(Status::GrpcStatus::MaximumValid + 1), "error message", empty_metadata_); dispatcher_helper_.runDispatcher(); } // Validate that we can continue to receive after a local close. TEST_P(GrpcClientIntegrationTest, ReceiveAfterLocalClose) { initialize(); auto stream = createStream(empty_metadata_); stream->sendRequest(true); stream->sendServerInitialMetadata(empty_metadata_); stream->sendReply(); stream->sendServerTrailers(Status::GrpcStatus::Ok, "", empty_metadata_); dispatcher_helper_.runDispatcher(); } // Validate that reset() doesn't explode on a half-closed stream (local). TEST_P(GrpcClientIntegrationTest, ResetAfterCloseLocal) { initialize(); auto stream = createStream(empty_metadata_); stream->grpc_stream_->closeStream(); ASSERT_TRUE(stream->fake_stream_->waitForEndStream(dispatcher_helper_.dispatcher_)); stream->grpc_stream_->resetStream(); dispatcher_helper_.dispatcher_.run(Event::Dispatcher::RunType::NonBlock); ASSERT_TRUE(stream->fake_stream_->waitForReset()); } // Validate that request cancel() works. TEST_P(GrpcClientIntegrationTest, CancelRequest) { initialize(); auto request = createRequest(empty_metadata_); EXPECT_CALL(*request->child_span_, setTag(Tracing::Tags::get().Status, Tracing::Tags::get().Canceled)); EXPECT_CALL(*request->child_span_, finishSpan()); request->grpc_request_->cancel(); dispatcher_helper_.dispatcher_.run(Event::Dispatcher::RunType::NonBlock); ASSERT_TRUE(request->fake_stream_->waitForReset()); } // Parameterize the loopback test server socket address and gRPC client type. INSTANTIATE_TEST_SUITE_P(SslIpVersionsClientType, GrpcSslClientIntegrationTest, GRPC_CLIENT_INTEGRATION_PARAMS, GrpcClientIntegrationParamTest::protocolTestParamsToString); // Validate that a simple request-reply unary RPC works with SSL. TEST_P(GrpcSslClientIntegrationTest, BasicSslRequest) { initialize(); auto request = createRequest(empty_metadata_); request->sendReply(); dispatcher_helper_.runDispatcher(); } // Validate that a simple request-reply unary RPC works with SSL + client certs. TEST_P(GrpcSslClientIntegrationTest, BasicSslRequestWithClientCert) { use_client_cert_ = true; initialize(); auto request = createRequest(empty_metadata_); request->sendReply(); dispatcher_helper_.runDispatcher(); } #ifdef ENVOY_GOOGLE_GRPC // AccessToken credential validation tests. class GrpcAccessTokenClientIntegrationTest : public GrpcSslClientIntegrationTest { public: void expectExtraHeaders(FakeStream& fake_stream) override { AssertionResult result = fake_stream.waitForHeadersComplete(); RELEASE_ASSERT(result, result.message()); Http::TestHeaderMapImpl stream_headers(fake_stream.headers()); if (access_token_value_ != "") { if (access_token_value_2_ == "") { EXPECT_EQ("Bearer " + access_token_value_, stream_headers.get_("authorization")); } else { EXPECT_EQ("Bearer " + access_token_value_ + ",Bearer " + access_token_value_2_, stream_headers.get_("authorization")); } } } virtual envoy::api::v2::core::GrpcService createGoogleGrpcConfig() override { auto config = GrpcClientIntegrationTest::createGoogleGrpcConfig(); auto* google_grpc = config.mutable_google_grpc(); google_grpc->set_credentials_factory_name(credentials_factory_name_); auto* ssl_creds = google_grpc->mutable_channel_credentials()->mutable_ssl_credentials(); ssl_creds->mutable_root_certs()->set_filename( TestEnvironment::runfilesPath("test/config/integration/certs/upstreamcacert.pem")); google_grpc->add_call_credentials()->set_access_token(access_token_value_); if (access_token_value_2_ != "") { google_grpc->add_call_credentials()->set_access_token(access_token_value_2_); } if (refresh_token_value_ != "") { google_grpc->add_call_credentials()->set_google_refresh_token(refresh_token_value_); } return config; } std::string access_token_value_{}; std::string access_token_value_2_{}; std::string refresh_token_value_{}; std::string credentials_factory_name_{}; }; // Parameterize the loopback test server socket address and gRPC client type. INSTANTIATE_TEST_SUITE_P(SslIpVersionsClientType, GrpcAccessTokenClientIntegrationTest, GRPC_CLIENT_INTEGRATION_PARAMS, GrpcClientIntegrationParamTest::protocolTestParamsToString); // Validate that a simple request-reply unary RPC works with AccessToken auth. TEST_P(GrpcAccessTokenClientIntegrationTest, AccessTokenAuthRequest) { SKIP_IF_GRPC_CLIENT(ClientType::EnvoyGrpc); access_token_value_ = "accesstokenvalue"; credentials_factory_name_ = Extensions::GrpcCredentials::GrpcCredentialsNames::get().AccessTokenExample; initialize(); auto request = createRequest(empty_metadata_); request->sendReply(); dispatcher_helper_.runDispatcher(); } // Validate that a simple request-reply stream RPC works with AccessToken auth.. TEST_P(GrpcAccessTokenClientIntegrationTest, AccessTokenAuthStream) { SKIP_IF_GRPC_CLIENT(ClientType::EnvoyGrpc); access_token_value_ = "accesstokenvalue"; credentials_factory_name_ = Extensions::GrpcCredentials::GrpcCredentialsNames::get().AccessTokenExample; initialize(); auto stream = createStream(empty_metadata_); stream->sendServerInitialMetadata(empty_metadata_); stream->sendRequest(); stream->sendReply(); stream->sendServerTrailers(Status::GrpcStatus::Ok, "", empty_metadata_); dispatcher_helper_.runDispatcher(); } // Validate that multiple access tokens are accepted TEST_P(GrpcAccessTokenClientIntegrationTest, MultipleAccessTokens) { SKIP_IF_GRPC_CLIENT(ClientType::EnvoyGrpc); access_token_value_ = "accesstokenvalue"; access_token_value_2_ = "accesstokenvalue2"; credentials_factory_name_ = Extensions::GrpcCredentials::GrpcCredentialsNames::get().AccessTokenExample; initialize(); auto request = createRequest(empty_metadata_); request->sendReply(); dispatcher_helper_.runDispatcher(); } // Validate that extra params are accepted TEST_P(GrpcAccessTokenClientIntegrationTest, ExtraCredentialParams) { SKIP_IF_GRPC_CLIENT(ClientType::EnvoyGrpc); access_token_value_ = "accesstokenvalue"; refresh_token_value_ = "refreshtokenvalue"; credentials_factory_name_ = Extensions::GrpcCredentials::GrpcCredentialsNames::get().AccessTokenExample; initialize(); auto request = createRequest(empty_metadata_); request->sendReply(); dispatcher_helper_.runDispatcher(); } // Validate that no access token still works TEST_P(GrpcAccessTokenClientIntegrationTest, NoAccessTokens) { SKIP_IF_GRPC_CLIENT(ClientType::EnvoyGrpc); credentials_factory_name_ = Extensions::GrpcCredentials::GrpcCredentialsNames::get().AccessTokenExample; initialize(); auto request = createRequest(empty_metadata_); request->sendReply(); dispatcher_helper_.runDispatcher(); } // Validate that an unknown credentials factory name throws an EnvoyException TEST_P(GrpcAccessTokenClientIntegrationTest, InvalidCredentialFactory) { SKIP_IF_GRPC_CLIENT(ClientType::EnvoyGrpc); credentials_factory_name_ = "unknown"; EXPECT_THROW_WITH_MESSAGE(initialize(), EnvoyException, "Unknown google grpc credentials factory: unknown"); } #endif } // namespace } // namespace Grpc } // namespace Envoy
dnoe/envoy
test/common/grpc/grpc_client_integration_test.cc
C++
apache-2.0
20,125
/** * Classes for working with and executing Bitcoin script programs, as embedded in inputs and outputs. */ package org.spreadcoinj.script;
bitbandi/spreadcoinj
core/src/main/java/org/spreadcoinj/script/package-info.java
Java
apache-2.0
141
import * as actionTypes from '../comm/actionTypes'; import {service} from '../comm/service'; function dayData(code,line){ let values=line.split('~'); let v={ code:code, name:values[1], close:parseFloat(values[3]), last:parseFloat(values[4]), open:parseFloat(values[5]), volume:parseInt(values[6]), buy1:values[9],buy1Vol:values[10], buy2:values[11],buy2Vol:values[12], buy3:values[13],buy3Vol:values[14], buy4:values[15],buy4Vol:values[16], buy5:values[17],buy5Vol:values[18], sell1:values[19],sell1Vol:values[20], sell2:values[21],sell2Vol:values[22], sell3:values[23],sell3Vol:values[24], sell4:values[25],sell4Vol:values[26], sell5:values[27],sell5Vol:values[28], time:values[30],high:values[33],low:values[34], amount:parseInt(values[37]), turnoverRate:values[38] }; if(code==='sh000001' || code==='sz399001'){ v.avg=''; }else{ v.avg=(v.amount/v.volume*100).toFixed(2); } return v; } export function fetchDay(codes){ return (dispatch,getState)=>{ service.stock.fetchData(codes).then(res=>{ let stocks={}; let data=res._bodyText.split('\n'); data.forEach(line=>{ if(line.length<10) return; let code=line.slice(2,10); stocks[code]=stocks[code]||{}; stocks[code]=Object.assign(stocks[code],dayData(code,line)); }); dispatch({type:actionTypes.FETCH_STOCK_DATA,data:stocks}); }); } } export function fetchMinutes(code){ return (dispatch,getState)=>{ service.stock.fetchMinData(code).then(res=>{ debugger; let data=res._bodyText; }); } } export function fetchDayK(code){ return (dispatch,getState)=>{ } }
jackz3/yunguba-onsenui
js/actions/stock.js
JavaScript
apache-2.0
1,655
""" Model classes for AppDynamics REST API .. moduleauthor:: Todd Radel <tradel@appdynamics.com> """ from . import JsonObject, JsonList class ConfigVariable(JsonObject): """ Represents a controller configuration variable. The following attributes are defined: .. data:: name Variable name. .. data:: value Current value. .. data:: description Optional description of the variable. .. data:: updateable If :const:`True`, value can be changed. .. data:: scope Scope of the variable. The scope can be ``'cluster'`` or ``'local'``. Variables with cluster scope are replicated across HA controllers; local variables are not. """ FIELDS = { 'name': '', 'description': '', 'scope': '', 'updateable': '', 'value': '' } def __init__(self, name='', description='', scope='cluster', updateable=True, value=None): (self.name, self.description, self.scope, self.updateable, self.value) = (name, description, scope, updateable, value) class ConfigVariables(JsonList): """ Represents a collection of :class:`ConfigVariable` objects. Extends :class:`UserList`, so it supports the standard array index and :keyword:`for` semantics. """ def __init__(self, initial_list=None): super(ConfigVariables, self).__init__(ConfigVariable, initial_list) def __getitem__(self, i): """ :rtype: ConfigVariable """ return self.data[i] def by_name(self, name): """ Finds a config variable with the matching name. :param str name: Variable name to find. :return: The matching config variable. :rtype: appd.model.ConfigVariable """ found = [x for x in self.data if x.name == name] try: return found[0] except IndexError: raise KeyError(name)
tradel/AppDynamicsREST
appd/model/config_variable.py
Python
apache-2.0
2,002
/********************************************************************** Copyright (c) 2005 Erik Bengtson and others. 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. Contributors: ... **********************************************************************/ package org.datanucleus.samples.identity.application; import java.io.Serializable; import java.util.StringTokenizer; import javax.jdo.InstanceCallbacks; import org.datanucleus.tests.TestObject; /** * Class with identity using two fields of type int. * @version $Revision: 1.1 $ */ public class ComposedIntIDBase extends TestObject implements InstanceCallbacks { private int code; // PK private int composed; // PK private String name; private String description; public int getComposed() { return composed; } public void setComposed(int composed) { this.composed = composed; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void jdoPostLoad() { } public void jdoPreStore() { } public void jdoPreClear() { } public void jdoPreDelete() { } public void fillRandom() { code = r.nextInt(); composed = r.nextInt(); fillUpdateRandom(); } public void fillUpdateRandom() { name = String.valueOf(r.nextDouble() * 1000); description = "Description " + this.getClass().toString() + " random: " + String.valueOf(r.nextDouble() * 1000); } public boolean compareTo(Object obj) { if (obj == this) return true; if (!(obj instanceof ComposedIntIDBase)) return false; ComposedIntIDBase other = (ComposedIntIDBase) obj; return code == other.code && name.equals(other.name) && composed == other.composed && description.equals(other.description); } public String toString() { StringBuffer s = new StringBuffer(super.toString()); s.append(" code = ").append(code); s.append('\n'); s.append(" name = ").append(name); s.append('\n'); s.append(" composed = ").append(composed); s.append('\n'); s.append(" description = ").append(description); s.append('\n'); return s.toString(); } public static class Key implements Serializable { private static final long serialVersionUID = 5781273055169032118L; public int code; public int composed; public Key() { } public Key(String str) { StringTokenizer toke = new StringTokenizer(str, "::"); str = toke.nextToken(); this.code = Integer.parseInt(str); str = toke.nextToken(); this.composed = Integer.parseInt(str); } public boolean equals(Object ob) { if (this == ob) { return true; } if (!(ob instanceof Key)) { return false; } Key other = (Key) ob; return ((this.code == other.code) && (this.composed == other.composed)); } public int hashCode() { return this.code ^ this.composed; } public String toString() { return String.valueOf(this.code) + "::" + String.valueOf(this.composed); } } }
datanucleus/tests
jdo/identity/src/java/org/datanucleus/samples/identity/application/ComposedIntIDBase.java
Java
apache-2.0
4,481
/** * Licensed to EsupPortail under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * EsupPortail 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.esupportail.filex.beans; import java.io.Serializable; public class Filex implements Serializable { private static final long serialVersionUID = 1L; private Uploads uploads; public Uploads getUploads() { return uploads; } public void setUploads(Uploads uploads) { this.uploads = uploads; } @Override public String toString() { return "Filex [uploads=" + uploads + "]"; } }
EsupPortail/esup-portlet-filex
src/main/java/org/esupportail/filex/beans/Filex.java
Java
apache-2.0
1,189
""" Knowledge combiners take: - Encoded representations of background facts related to the sentence - Attention weights over the background as a single tensor. These are then combined in some way to return a single representation of the background knowledge per sample. The simplest way for this to happen is simply taking a weighted average of the knowledge representations with respect to the attention weights. Input shapes: - (samples, knowledge_len, input_dim + 1) Output shape: - (samples, input_dim) """ from collections import OrderedDict from overrides import overrides from keras.engine import InputSpec from keras import backend as K from keras.layers import Layer from keras.layers.recurrent import GRU, _time_distributed_dense class WeightedAverageKnowledgeCombiner(Layer): ''' A WeightedAverageKnowledgeCombiner takes a tensor formed by prepending an attention mask onto an encoded representation of background knowledge. Here, we simply split off the attention mask and use it to take a weighted average of the background vectors. ''' def __init__(self, **kwargs): self.input_spec = [InputSpec(ndim=3)] self.name = kwargs.pop('name') # These parameters are passed for consistency with the # AttentiveGRUKnowlegeCombiner. They are not used here. kwargs.pop('output_dim') kwargs.pop('input_length') super(WeightedAverageKnowledgeCombiner, self).__init__(**kwargs) @overrides def call(self, inputs): attention = inputs[:, :, 0] # (samples, knowledge_length) inputs = inputs[:, :, 1:] # (samples, knowledge_length, word_dim) return K.sum(K.expand_dims(attention, 2) * inputs, 1) def compute_output_shape(self, input_shape): return (input_shape[0], input_shape[2] - 1) @overrides def get_config(self): config = { "output_dim": -1, "input_length": -1 } base_config = super(WeightedAverageKnowledgeCombiner, self).get_config() config.update(base_config) return config class AttentiveGRUKnowledgeCombiner(GRU): ''' GRUs typically operate over sequences of words. Here we are are operating over the background knowledge sentence representations as though they are a sequence (i.e. each background sentence has already been encoded into a single sentence representation). The motivation behind this encoding is that a weighted average loses ordering information in the background knowledge - for instance, this is important in the BABI tasks. See Dynamic Memory Networks for more information: https://arxiv.org/pdf/1603.01417v1.pdf. This class extends the Keras Gated Recurrent Unit by implementing a method which substitutes the GRU update gate (normally a vector, z - it is noted below where it is normally computed) for a scalar attention weight (one per input, such as from the output of a softmax over the input vectors), which is pre-computed. As mentioned above, instead of using word embedding sequences as input to the GRU, we are using sentence encoding sequences. The implementation of this class is subtle - it is only very slightly different from a standard GRU. When it is initialised, the Keras backend will call the build method. It uses this to check that inputs being passed to this function are the correct size, so we allow this to be the actual input size as normal. However, for the internal implementation, everywhere where this global shape is used, we override it to be one less, as we are passing in a tensor of shape (batch, knowledge_length, 1 + encoding_dim) as we are including the attention mask. Therefore, we need all of the weights to have shape (*, encoding_dim), NOT (*, 1 + encoding_dim). All of the below methods which are overridden use some form of this dimension, so we correct them. ''' def __init__(self, output_dim, input_length, **kwargs): self.name = kwargs.pop('name') super(AttentiveGRUKnowledgeCombiner, self).__init__(output_dim, input_length=input_length, input_dim=output_dim + 1, name=self.name, **kwargs) @overrides def step(self, inputs, states): # pylint: disable=invalid-name ''' The input to step is a tensor of shape (batch, 1 + encoding_dim), i.e. a timeslice of the input to this AttentiveGRU, where the time axis is the knowledge_length. Before we start, we strip off the attention from the beginning. Then we do the equations for a normal GRU, except we don't calculate the output gate z, substituting the attention weight for it instead. Note that there is some redundancy here - for instance, in the GPU mode, we do a larger matrix multiplication than required, as we don't use one part of it. However, for readability and similarity to the original GRU code in Keras, it has not been changed. In each section, there are commented out lines which contain code. If you were to uncomment these, remove the differences in the input size and replace the attention with the z gate at the output, you would have a standard GRU back again. We literally copied the Keras GRU code here, making some small modifications. ''' attention = inputs[:, 0] inputs = inputs[:, 1:] h_tm1 = states[0] # previous memory B_U = states[1] # dropout matrices for recurrent units B_W = states[2] if self.implementation == 2: matrix_x = K.dot(inputs * B_W[0], self.kernel) if self.use_bias: matrix_x = K.bias_add(matrix_x, self.bias) matrix_inner = K.dot(h_tm1 * B_U[0], self.recurrent_kernel[:, :2 * self.units]) x_r = matrix_x[:, self.units: 2 * self.units] inner_r = matrix_inner[:, self.units: 2 * self.units] # x_z = matrix_x[:, :self.units] # inner_z = matrix_inner[:, :self.units] # z = self.recurrent_activation(x_z + inner_z) r = self.recurrent_activation(x_r + inner_r) x_h = matrix_x[:, 2 * self.units:] inner_h = K.dot(r * h_tm1 * B_U[0], self.recurrent_kernel[:, 2 * self.units:]) hh = self.activation(x_h + inner_h) else: if self.implementation == 0: # x_z = inputs[:, :self.units] x_r = inputs[:, self.units: 2 * self.units] x_h = inputs[:, 2 * self.units:] elif self.implementation == 1: # x_z = K.dot(inputs * B_W[0], self.W_z) + self.b_z x_r = K.dot(inputs * B_W[1], self.kernel_r) x_h = K.dot(inputs * B_W[2], self.kernel_h) if self.use_bias: x_r = K.bias_add(x_r, self.bias_r) x_h = K.bias_add(x_h, self.bias_h) else: raise Exception('Unknown implementation') # z = self.recurrent_activation(x_z + K.dot(h_tm1 * B_U[0], self.U_z)) r = self.recurrent_activation(x_r + K.dot(h_tm1 * B_U[1], self.recurrent_kernel_r)) hh = self.activation(x_h + K.dot(r * h_tm1 * B_U[2], self.recurrent_kernel_h)) # Here is the KEY difference between a GRU and an AttentiveGRU. Instead of using # a learnt output gate (z), we use a scalar attention vector (batch, 1) for this # particular background knowledge vector. h = K.expand_dims(attention, 1) * hh + (1 - K.expand_dims(attention, 1)) * h_tm1 return h, [h] @overrides def build(self, input_shape): """ This is used by Keras to verify things, but also to build the weights. The only differences from the Keras GRU (which we copied exactly other than the below) are: - We generate weights with dimension input_dim[2] - 1, rather than dimension input_dim[2]. - There are a few variables which are created in non-'gpu' modes which are not required, and actually raise errors in Theano if you include them in the trainable weights(as Theano will alert you if you try to compute a gradient of a loss wrt a constant). These are commented out but left in for clarity below. """ new_input_shape = list(input_shape) new_input_shape[2] -= 1 super(AttentiveGRUKnowledgeCombiner, self).build(tuple(new_input_shape)) self.input_spec = [InputSpec(shape=input_shape)] @overrides def preprocess_input(self, inputs, training=None): ''' We have to override this preprocessing step, because if we are using the cpu, we do the weight - input multiplications in the internals of the GRU as seperate, smaller matrix multiplications and concatenate them after. Therefore, before this happens, we split off the attention and then add it back afterwards. ''' if self.implementation == 0: attention = inputs[:, :, 0] # Shape:(samples, knowledge_length) inputs = inputs[:, :, 1:] # Shape:(samples, knowledge_length, word_dim) input_shape = self.input_spec[0].shape input_dim = input_shape[2] - 1 timesteps = input_shape[1] x_z = _time_distributed_dense(inputs, self.kernel_z, self.bias_z, self.dropout, input_dim, self.units, timesteps, training=training) x_r = _time_distributed_dense(inputs, self.kernel_r, self.bias_r, self.dropout, input_dim, self.units, timesteps, training=training) x_h = _time_distributed_dense(inputs, self.kernel_h, self.bias_h, self.dropout, input_dim, self.units, timesteps, training=training) # Add attention back on to it's original place. return K.concatenate([K.expand_dims(attention, 2), x_z, x_r, x_h], axis=2) else: return inputs # The first item added here will be used as the default in some cases. knowledge_combiners = OrderedDict() # pylint: disable=invalid-name knowledge_combiners["weighted_average"] = WeightedAverageKnowledgeCombiner knowledge_combiners["attentive_gru"] = AttentiveGRUKnowledgeCombiner
RTHMaK/RPGOne
deep_qa-master/deep_qa/layers/knowledge_combiners.py
Python
apache-2.0
10,674
package marta.rodriguez.mercadonaapp.mercadona.api; import java.util.List; import marta.rodriguez.mercadonaapp.mercadona.Constants; import marta.rodriguez.mercadonaapp.mercadona.model.Supermarket; import retrofit.RestAdapter; import retrofit.http.GET; import retrofit.http.Path; /** * Created by marta.rodriguez on 28/05/14. */ public class ApiaryClient { private static SupermarketsApiInterface sSupermarketsService; public static SupermarketsApiInterface getSupermarketsApiClient() { if (sSupermarketsService == null) { RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(Constants.API_URL) .setLogLevel(RestAdapter.LogLevel.FULL) .build(); sSupermarketsService = restAdapter.create(SupermarketsApiInterface.class); } return sSupermarketsService; } public interface SupermarketsApiInterface { @GET("/supermarkets/{province}") List<Supermarket> getSupermarkets(@Path("province") String province); } }
marta-rodriguez/clean-mercadona
CleanMercadona/app/src/main/java/marta/rodriguez/mercadonaapp/mercadona/api/ApiaryClient.java
Java
apache-2.0
1,068