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 com.app.base.common.calculation; /** * 用来定义两个点之间的距离. * * @author tianyu912@yeah.net */ public class Space { /** * x,y轴需要增加或增小的距离. */ public float x_space = 0, y_space = 0; /** * */ public Space() { super(); } /** * 构造Space对象. * @param x_space x轴需要增加或增小的距离. * @param y_space y轴需要增加或增小的距离. */ public Space(float x_space, float y_space) { super(); this.x_space = x_space; this.y_space = y_space; } }
treason258/TreLibrary
LovelyReaderAS/appbase/src/main/java/com/app/base/common/calculation/Space.java
Java
apache-2.0
560
angular.module('asics').controller('ReportCtrl', [ '$mdToast', '$scope', '$interval', 'admin', '$stateParams', function ($mdToast, $scope, $interval, admin, $stateParams) { $scope.strings = {}; $scope.language = $stateParams.language; $scope.country_count = []; $scope.available_dates = []; $scope.current_date = []; angular.copy(adminReportStrings[$scope.language], $scope.strings); function get_reports(day) { admin.getReport(day) .then(readReportInformation) .catch(errorToast); } createDateList(); setCurrentDate(); function createDateList() { for (var day = 3; day < 22; day++) { $scope.available_dates.push({ date: day }); } } function setCurrentDate() { var d = new Date(); var day = d.getDate(); $scope.current_date = $.grep($scope.available_dates, function(e){ return e.date == day })[0]; } function readReportInformation(result) { angular.copy(result.country_count, $scope.country_count); } $scope.$watch('current_date', function () { get_reports($scope.current_date.date) }); function errorToast(error) { var toast = $mdToast.simple() .textContent(error) .position('top right') .hideDelay(3000) .theme('error-toast'); $mdToast.show(toast); } } ]); var adminReportStrings = { EN: { date: "Day", title: "Visitors list", description: "Select the date to look up the number of visitors per country on that day." }, PT: { date: "Dia", title: "Lista de visitantes", description: "Selecione a data para pesquisar o número de visitantes por país no dia." } };
d3estudio/asics-access
web/app/assets/javascripts/controllers/admin/reportCtrl.js
JavaScript
apache-2.0
1,736
package org.mimacom.commons.liferay.adapter6110; /* * Copyright (c) 2014 mimacom a.g. * * 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 java.io.File; import org.mimacom.commons.liferay.adapter.LiferayTools; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactory; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.FileUtil; import com.liferay.portal.kernel.util.HtmlUtil; import com.liferay.portal.kernel.util.ServerDetector; import com.liferay.portal.kernel.xml.SAXReaderUtil; import com.liferay.portal.util.FileImpl; import com.liferay.portal.util.HtmlImpl; import com.liferay.portal.util.PortalImpl; import com.liferay.portal.util.PortalUtil; import com.liferay.portal.xml.SAXReaderImpl; public class LiferayToolsImpl implements LiferayTools { public LiferayToolsImpl() { } static void addExtraContent(String appServerType, StringBuilder content) { if (ServerDetector.WEBSPHERE_ID.equals(appServerType)) { content.append("<context-param>"); content .append("<param-name>com.ibm.websphere.portletcontainer.PortletDeploymentEnabled</param-name>"); content.append("<param-value>false</param-value>"); content.append("</context-param>"); } } public String getVersion() { return "6.1.10"; } public void initLiferay() { new FileUtil().setFile(new FileImpl()); new SAXReaderUtil().setSAXReader(new SAXReaderImpl()); new PortalUtil().setPortal(new PortalImpl()); new HtmlUtil().setHtml(new HtmlImpl()); } public void mergeCss(File basedir) { // TODO stni // create the merged css uncompressed and compressed // String cssPath = new File(basedir, "css").getAbsolutePath(); // String unpacked = cssPath + "/everything_unpacked.css"; // new CSSBuilder(cssPath, unpacked); // YUICompressor.main(new String[] { "--type", "css", "-o", cssPath + // "/everything_packed.css", unpacked }); } public void initLog(final org.apache.maven.plugin.logging.Log log) { LogFactoryUtil.setLogFactory(new LogFactory() { public Log getLog(String name) { return new MavenLiferayLog(name, log); } public Log getLog(Class<?> c) { return new MavenLiferayLog(c.getSimpleName(), log); } }); } public void deployLayout(String serverType, File sourceDir) throws Exception { new StandaloneLayoutDeployer(serverType).deployFile(sourceDir,null); } public void deployPortlet(String version, String serverType, File sourceDir) throws Exception { new StandalonePortletDeployer(version, serverType).deployFile( sourceDir, null); } public void deployTheme(String serverType, File sourceDir) throws Exception { new StandaloneThemeDeployer(serverType).deployFile(sourceDir,null); } public void deployHook(String serverType, File sourceDir) throws Exception { new StandaloneHookDeployer(serverType).deployFile(sourceDir,null); } public void buildService(String arg0, String arg1, String arg2, String arg3, String arg4, String arg5, String arg6, String arg7, String arg8, String arg9, String arg10, String arg11, String arg12, String arg13, String arg14, String arg15, String arg16, String arg17, String arg18, String arg19, boolean arg20, String arg21, String arg22, String arg23, String arg24) { // TODO Auto-generated method stub } }
mimacom/maven-liferay-plugin
mimacom-liferay-adapter/mimacom-liferay-adapter-6.1.10/src/main/java/org/mimacom/commons/liferay/adapter6110/LiferayToolsImpl.java
Java
apache-2.0
3,832
/* * Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package cn.sherlock.com.sun.media.sound; /** * Connection blocks are used to connect source variable * to a destination variable. * For example Note On velocity can be connected to output gain. * In DLS this is called articulator and in SoundFonts (SF2) a modulator. * * @author Karl Helgason */ public class ModelConnectionBlock { // // source1 * source2 * scale -> destination // private final static ModelSource[] no_sources = new ModelSource[0]; private ModelSource[] sources = no_sources; private double scale = 1; private ModelDestination destination; public ModelConnectionBlock() { } public ModelConnectionBlock(double scale, ModelDestination destination) { this.scale = scale; this.destination = destination; } public ModelConnectionBlock(ModelSource source, ModelDestination destination) { if (source != null) { this.sources = new ModelSource[1]; this.sources[0] = source; } this.destination = destination; } public ModelConnectionBlock(ModelSource source, double scale, ModelDestination destination) { if (source != null) { this.sources = new ModelSource[1]; this.sources[0] = source; } this.scale = scale; this.destination = destination; } public ModelConnectionBlock(ModelSource source, ModelSource control, ModelDestination destination) { if (source != null) { if (control == null) { this.sources = new ModelSource[1]; this.sources[0] = source; } else { this.sources = new ModelSource[2]; this.sources[0] = source; this.sources[1] = control; } } this.destination = destination; } public ModelConnectionBlock(ModelSource source, ModelSource control, double scale, ModelDestination destination) { if (source != null) { if (control == null) { this.sources = new ModelSource[1]; this.sources[0] = source; } else { this.sources = new ModelSource[2]; this.sources[0] = source; this.sources[1] = control; } } this.scale = scale; this.destination = destination; } public ModelDestination getDestination() { return destination; } public void setDestination(ModelDestination destination) { this.destination = destination; } public double getScale() { return scale; } public void setScale(double scale) { this.scale = scale; } public ModelSource[] getSources() { return sources; } public void setSources(ModelSource[] source) { this.sources = source; } public void addSource(ModelSource source) { ModelSource[] oldsources = sources; sources = new ModelSource[oldsources.length + 1]; for (int i = 0; i < oldsources.length; i++) { sources[i] = oldsources[i]; } sources[sources.length - 1] = source; } }
KyoSherlock/SherlockMidi
sherlockmidi/src/main/java/cn/sherlock/com/sun/media/sound/ModelConnectionBlock.java
Java
apache-2.0
4,417
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.common.http.client.handler; import com.alibaba.nacos.common.http.HttpRestResult; import com.alibaba.nacos.common.http.client.response.HttpClientResponse; import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.utils.IoUtils; import org.apache.http.HttpStatus; import java.lang.reflect.Type; /** * Abstract response handler. * * @author mai.jh */ public abstract class AbstractResponseHandler<T> implements ResponseHandler<T> { private Type responseType; @Override public final void setResponseType(Type responseType) { this.responseType = responseType; } @Override public final HttpRestResult<T> handle(HttpClientResponse response) throws Exception { if (HttpStatus.SC_OK != response.getStatusCode()) { return handleError(response); } return convertResult(response, this.responseType); } private HttpRestResult<T> handleError(HttpClientResponse response) throws Exception { Header headers = response.getHeaders(); String message = IoUtils.toString(response.getBody(), headers.getCharset()); return new HttpRestResult<T>(headers, response.getStatusCode(), null, message); } /** * Abstract convertResult method, Different types of converters for expansion. * * @param response http client response * @param responseType responseType * @return HttpRestResult * @throws Exception ex */ public abstract HttpRestResult<T> convertResult(HttpClientResponse response, Type responseType) throws Exception; }
alibaba/nacos
common/src/main/java/com/alibaba/nacos/common/http/client/handler/AbstractResponseHandler.java
Java
apache-2.0
2,256
/** * */ package org.apache.hadoop.hdfs.server.namenodeFBT.rule; import org.apache.hadoop.hdfs.server.namenodeFBT.FBTDirectory; import org.apache.hadoop.hdfs.server.namenodeFBT.NameNodeFBTProcessor; import org.apache.hadoop.hdfs.server.namenodeFBT.NodeVisitor; import org.apache.hadoop.hdfs.server.namenodeFBT.NodeVisitorFactory; import org.apache.hadoop.hdfs.server.namenodeFBT.utils.StringUtility; /** * @author hanhlh * */ public class CompleteFileRule extends AbstractRule{ public CompleteFileRule(RuleManager manager) { super(manager); } @Override protected Class[] events() { return new Class[] { CompleteFileRequest.class }; } @Override protected void action(RuleEvent event) { StringUtility.debugSpace("CompleteFileRule action"); CompleteFileRequest request = (CompleteFileRequest) event; FBTDirectory directory = (FBTDirectory) NameNodeFBTProcessor. lookup(request.getDirectoryName()); NodeVisitorFactory visitorFactory = directory.getNodeVisitorFactory(); NodeVisitor visitor = visitorFactory.createCompleteFileVisitor(); visitor.setRequest(request); visitor.run(); _manager.dispatch(visitor.getResponse()); } }
hanhlh/hadoop-0.20.2_FatBTree
src/hdfs/org/apache/hadoop/hdfs/server/namenodeFBT/rule/CompleteFileRule.java
Java
apache-2.0
1,272
/* * Copyright (C) ExBin Project * * This application or library is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This application or library is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along this application. If not, see <http://www.gnu.org/licenses/>. */ package org.exbin.framework.editor.text.panel; import java.awt.Font; import java.awt.event.ItemEvent; import java.awt.font.TextAttribute; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.prefs.Preferences; import org.exbin.framework.gui.options.api.OptionsPanel; import org.exbin.framework.gui.options.api.OptionsPanel.ModifiedOptionListener; import org.exbin.framework.gui.options.api.OptionsPanel.PathItem; /** * Text font options panel. * * @version 0.2.0 2017/01/04 * @author ExBin Project (http://exbin.org) */ public class TextFontOptionsPanel extends javax.swing.JPanel implements OptionsPanel { public static final String PREFERENCES_TEXT_FONT_DEFAULT = "textFont.default"; public static final String PREFERENCES_TEXT_FONT_FAMILY = "textFont.family"; public static final String PREFERENCES_TEXT_FONT_SIZE = "textFont.size"; public static final String PREFERENCES_TEXT_FONT_UNDERLINE = "textFont.underline"; public static final String PREFERENCES_TEXT_FONT_STRIKETHROUGH = "textFont.strikethrough"; public static final String PREFERENCES_TEXT_FONT_STRONG = "textFont.strong"; public static final String PREFERENCES_TEXT_FONT_ITALIC = "textFont.italic"; public static final String PREFERENCES_TEXT_FONT_SUBSCRIPT = "textFont.subscript"; public static final String PREFERENCES_TEXT_FONT_SUPERSCRIPT = "textFont.superscript"; private ModifiedOptionListener modifiedOptionListener; private FontChangeAction fontChangeAction; private final ResourceBundle resourceBundle; private final TextFontPanelApi frame; private Font font; public TextFontOptionsPanel(TextFontPanelApi frame) { this.frame = frame; resourceBundle = java.util.ResourceBundle.getBundle("org/exbin/framework/editor/text/panel/resources/TextFontOptionsPanel"); initComponents(); } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); fontPreviewLabel.setEnabled(enabled); fillDefaultFontButton.setEnabled(enabled); fillCurrentFontButton.setEnabled(enabled); changeFontButton.setEnabled(enabled); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jColorChooser1 = new javax.swing.JColorChooser(); defaultFontCheckBox = new javax.swing.JCheckBox(); fillDefaultFontButton = new javax.swing.JButton(); changeFontButton = new javax.swing.JButton(); fontPreviewLabel = new javax.swing.JLabel(); fillCurrentFontButton = new javax.swing.JButton(); jColorChooser1.setName("jColorChooser1"); // NOI18N setName("Form"); // NOI18N defaultFontCheckBox.setSelected(true); defaultFontCheckBox.setText(resourceBundle.getString("TextFontOptionsPanel.defaultFontCheckBox.text")); // NOI18N defaultFontCheckBox.setName("defaultFontCheckBox"); // NOI18N defaultFontCheckBox.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { defaultFontCheckBoxItemStateChanged(evt); } }); fillDefaultFontButton.setText(resourceBundle.getString("TextFontOptionsPanel.fillDefaultFontButton.text")); // NOI18N fillDefaultFontButton.setEnabled(false); fillDefaultFontButton.setName("fillDefaultFontButton"); // NOI18N fillDefaultFontButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fillDefaultFontButtonActionPerformed(evt); } }); changeFontButton.setText(resourceBundle.getString("TextFontOptionsPanel.changeFontButton.text")); // NOI18N changeFontButton.setEnabled(false); changeFontButton.setName("changeFontButton"); // NOI18N changeFontButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { changeFontButtonActionPerformed(evt); } }); fontPreviewLabel.setBackground(java.awt.Color.white); fontPreviewLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); fontPreviewLabel.setText(resourceBundle.getString("TextFontOptionsPanel.fontPreviewLabel.text")); // NOI18N fontPreviewLabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); fontPreviewLabel.setEnabled(false); fontPreviewLabel.setName("fontPreviewLabel"); // NOI18N fontPreviewLabel.setOpaque(true); fillCurrentFontButton.setText(resourceBundle.getString("TextFontOptionsPanel.fillCurrentFontButton.text")); // NOI18N fillCurrentFontButton.setEnabled(false); fillCurrentFontButton.setName("fillCurrentFontButton"); // NOI18N fillCurrentFontButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fillCurrentFontButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(fontPreviewLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(defaultFontCheckBox, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(changeFontButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(fillDefaultFontButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(fillCurrentFontButton) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(defaultFontCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(fontPreviewLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(changeFontButton) .addComponent(fillDefaultFontButton) .addComponent(fillCurrentFontButton)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void defaultFontCheckBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_defaultFontCheckBoxItemStateChanged boolean selected = evt.getStateChange() != ItemEvent.SELECTED; fontPreviewLabel.setEnabled(selected); fillDefaultFontButton.setEnabled(selected); fillCurrentFontButton.setEnabled(selected); changeFontButton.setEnabled(selected); setModified(true); }//GEN-LAST:event_defaultFontCheckBoxItemStateChanged private void fillDefaultFontButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fillDefaultFontButtonActionPerformed fontPreviewLabel.setFont(frame.getDefaultFont()); setModified(true); }//GEN-LAST:event_fillDefaultFontButtonActionPerformed private void changeFontButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeFontButtonActionPerformed if (fontChangeAction != null) { Font resultFont = fontChangeAction.changeFont(fontPreviewLabel.getFont()); if (resultFont != null) { fontPreviewLabel.setFont(resultFont); setModified(true); } } }//GEN-LAST:event_changeFontButtonActionPerformed private void fillCurrentFontButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fillCurrentFontButtonActionPerformed fontPreviewLabel.setFont(frame.getCurrentFont()); setModified(true); }//GEN-LAST:event_fillCurrentFontButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton changeFontButton; private javax.swing.JCheckBox defaultFontCheckBox; private javax.swing.JButton fillCurrentFontButton; private javax.swing.JButton fillDefaultFontButton; private javax.swing.JLabel fontPreviewLabel; private javax.swing.JColorChooser jColorChooser1; // End of variables declaration//GEN-END:variables @Override public List<OptionsPanel.PathItem> getPath() { ArrayList<OptionsPanel.PathItem> path = new ArrayList<>(); path.add(new PathItem("apperance", "")); path.add(new PathItem("font", resourceBundle.getString("options.Path.0"))); return path; } @Override public void loadFromPreferences(Preferences preferences) { Boolean defaultColor = Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_DEFAULT, Boolean.toString(true))); defaultFontCheckBox.setSelected(defaultColor); setEnabled(!defaultColor); String value; Map<TextAttribute, Object> attribs = new HashMap<>(); value = preferences.get(PREFERENCES_TEXT_FONT_FAMILY, null); if (value != null) { attribs.put(TextAttribute.FAMILY, value); } value = preferences.get(PREFERENCES_TEXT_FONT_SIZE, null); if (value != null) { attribs.put(TextAttribute.SIZE, new Integer(value).floatValue()); } if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_UNDERLINE, null))) { attribs.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_LOW_ONE_PIXEL); } if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_STRIKETHROUGH, null))) { attribs.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); } if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_STRONG, null))) { attribs.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD); } if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_ITALIC, null))) { attribs.put(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE); } if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_SUBSCRIPT, null))) { attribs.put(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUB); } if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_SUPERSCRIPT, null))) { attribs.put(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER); } font = frame.getDefaultFont().deriveFont(attribs); fontPreviewLabel.setFont(font); } @Override public void saveToPreferences(Preferences preferences) { preferences.put(PREFERENCES_TEXT_FONT_DEFAULT, Boolean.toString(defaultFontCheckBox.isSelected())); Map<TextAttribute, ?> attribs = font.getAttributes(); String value = (String) attribs.get(TextAttribute.FAMILY); if (value != null) { preferences.put(PREFERENCES_TEXT_FONT_FAMILY, value); } else { preferences.remove(PREFERENCES_TEXT_FONT_FAMILY); } Float fontSize = (Float) attribs.get(TextAttribute.SIZE); if (fontSize != null) { preferences.put(PREFERENCES_TEXT_FONT_SIZE, Integer.toString((int) (float) fontSize)); } else { preferences.remove(PREFERENCES_TEXT_FONT_SIZE); } preferences.put(PREFERENCES_TEXT_FONT_UNDERLINE, Boolean.toString(TextAttribute.UNDERLINE_LOW_ONE_PIXEL.equals(attribs.get(TextAttribute.UNDERLINE)))); preferences.put(PREFERENCES_TEXT_FONT_STRIKETHROUGH, Boolean.toString(TextAttribute.STRIKETHROUGH_ON.equals(attribs.get(TextAttribute.STRIKETHROUGH)))); preferences.put(PREFERENCES_TEXT_FONT_STRONG, Boolean.toString(TextAttribute.WEIGHT_BOLD.equals(attribs.get(TextAttribute.WEIGHT)))); preferences.put(PREFERENCES_TEXT_FONT_ITALIC, Boolean.toString(TextAttribute.POSTURE_OBLIQUE.equals(attribs.get(TextAttribute.POSTURE)))); preferences.put(PREFERENCES_TEXT_FONT_SUBSCRIPT, Boolean.toString(TextAttribute.SUPERSCRIPT_SUB.equals(attribs.get(TextAttribute.SUPERSCRIPT)))); preferences.put(PREFERENCES_TEXT_FONT_SUPERSCRIPT, Boolean.toString(TextAttribute.SUPERSCRIPT_SUPER.equals(attribs.get(TextAttribute.SUPERSCRIPT)))); } @Override public void applyPreferencesChanges() { if (defaultFontCheckBox.isSelected()) { frame.setCurrentFont(frame.getDefaultFont()); } else { frame.setCurrentFont(font); } } private void setModified(boolean b) { if (modifiedOptionListener != null) { modifiedOptionListener.wasModified(); } } @Override public void setModifiedOptionListener(ModifiedOptionListener listener) { modifiedOptionListener = listener; } public void setFontChangeAction(FontChangeAction fontChangeAction) { this.fontChangeAction = fontChangeAction; } public static interface FontChangeAction { Font changeFont(Font currentFont); } }
hajdam/deltahex-netbeans
src/org/exbin/framework/editor/text/panel/TextFontOptionsPanel.java
Java
apache-2.0
15,094
<? $error = false; if (isset($_POST['action'])) { switch ($_POST['action']) { case 'crypt_set_key': $_SESSION['core']['install']['crypt']['key'] = $_POST['key']; break; } } ob_start(); ?> <!DOCTYPE html> <html lang="en-US"> <head> <title>Install Crypt</title> <meta charset="UTF-8"> <meta name="robots" content="none"> </head> <body> <h1>Install Crypt</h1> <? if (!$error) { if (!isset($_SESSION['core']['install']['crypt']['key'])) { $error = true; ?> <form method="post"> <input type="hidden" name="action" value="crypt_set_key"> <label for="key">Key</label> <br> <input type="text" name="key" value="<?= str_pad(bin2hex(openssl_random_pseudo_bytes(16)), 32, "\0") ?>"> <br><br> <input type="submit" value="Next"> </form> <? } } ?> </body> </html> <? $content = ob_get_contents(); ob_end_clean(); if ($error) { echo $content; exit; } // Install module $data->extractTo(ROOT); if (!APP::Module('Registry')->Get('module_crypt_key')) { APP::Module('Registry')->Add('module_crypt_key', $_SESSION['core']['install']['crypt']['key']); }
Tendors/phpshell
protected/modules/Crypt/install.php
PHP
apache-2.0
1,294
/* * Copyright 2012 GitHub Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.janela.mobile.ui.gist; import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP; import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.text.Editable; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.widget.CheckBox; import android.widget.EditText; import com.janela.mobile.R; import com.janela.mobile.ui.BaseActivity; import com.janela.mobile.ui.TextWatcherAdapter; import com.janela.mobile.util.ShareUtils; import org.eclipse.egit.github.core.Gist; /** * Activity to share a text selection as a public or private Gist */ public class CreateGistActivity extends BaseActivity { private EditText descriptionText; private EditText nameText; private EditText contentText; private CheckBox publicCheckBox; private MenuItem createItem; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.gist_create); descriptionText = finder.find(R.id.et_gist_description); nameText = finder.find(R.id.et_gist_name); contentText = finder.find(R.id.et_gist_content); publicCheckBox = finder.find(R.id.cb_public); ActionBar actionBar = getSupportActionBar(); actionBar.setTitle(R.string.new_gist); actionBar.setIcon(R.drawable.action_gist); actionBar.setDisplayHomeAsUpEnabled(true); String text = ShareUtils.getBody(getIntent()); if (!TextUtils.isEmpty(text)) contentText.setText(text); String subject = ShareUtils.getSubject(getIntent()); if (!TextUtils.isEmpty(subject)) descriptionText.setText(subject); contentText.addTextChangedListener(new TextWatcherAdapter() { @Override public void afterTextChanged(Editable s) { updateCreateMenu(s); } }); updateCreateMenu(); } private void updateCreateMenu() { if (contentText != null) updateCreateMenu(contentText.getText()); } private void updateCreateMenu(CharSequence text) { if (createItem != null) createItem.setEnabled(!TextUtils.isEmpty(text)); } @Override public boolean onCreateOptionsMenu(Menu options) { getMenuInflater().inflate(R.menu.gist_create, options); createItem = options.findItem(R.id.m_apply); updateCreateMenu(); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.m_apply: createGist(); return true; case android.R.id.home: finish(); Intent intent = new Intent(this, GistsActivity.class); intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } private void createGist() { final boolean isPublic = publicCheckBox.isChecked(); String enteredDescription = descriptionText.getText().toString().trim(); final String description = enteredDescription.length() > 0 ? enteredDescription : getString(R.string.gist_description_hint); String enteredName = nameText.getText().toString().trim(); final String name = enteredName.length() > 0 ? enteredName : getString(R.string.gist_file_name_hint); final String content = contentText.getText().toString(); new CreateGistTask(this, description, isPublic, name, content) { @Override protected void onSuccess(Gist gist) throws Exception { super.onSuccess(gist); startActivity(GistsViewActivity.createIntent(gist)); setResult(RESULT_OK); finish(); } }.create(); } }
DeLaSalleUniversity-Manila/forkhub-Janelaaa
app/src/main/java/com/janela/mobile/ui/gist/CreateGistActivity.java
Java
apache-2.0
4,694
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Rawr.CustomControls { public partial class ExtendedToolTipLabel : Label { private ToolTip _ToolTip; private string _ToolTipText; public ExtendedToolTipLabel() { InitializeComponent(); _ToolTip = new ToolTip(); this.MouseLeave += new EventHandler(ExtendedToolTipLabel_MouseLeave); this.MouseHover += new EventHandler(ExtendedToolTipLabel_MouseHover); } void ExtendedToolTipLabel_MouseHover(object sender, EventArgs e) { if (!String.IsNullOrEmpty(_ToolTipText)) { int x = PointToClient(MousePosition).X + 10; _ToolTip.Show(_ToolTipText, this, new Point(x, -10)); } } public string ToolTipText { get { return _ToolTipText; } set { _ToolTipText = value; } } void ExtendedToolTipLabel_MouseLeave(object sender, EventArgs e) { if (!String.IsNullOrEmpty(_ToolTipText)) { _ToolTip.Hide(this); } } } }
Alacant/Rawr-RG
Rawr.Base/CustomControls/ExtendedToolTipLabel.cs
C#
apache-2.0
1,292
package org.gradle.test.performance.mediummonolithicjavaproject.p388; import org.junit.Test; import static org.junit.Assert.*; public class Test7764 { Production7764 objectUnderTest = new Production7764(); @Test public void testProperty0() { String value = "value"; objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { String value = "value"; objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { String value = "value"; objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
oehme/analysing-gradle-performance
my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p388/Test7764.java
Java
apache-2.0
2,111
// Copyright 2015 The Serviced 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. // +build unit package rsync import ( "fmt" "testing" "github.com/control-center/serviced/volume" "github.com/stretchr/testify/assert" ) type ParseDFTest struct { label string inlabel string inbytes []byte out []volume.Usage outmsg string err error errmsg string } var parsedftests = []ParseDFTest{ { label: "output from df", inlabel: "volumelabel", inbytes: []byte(`Filesystem 1B-blocks Used Avail /dev/sdb1 1901233012736 172685119488 1631947202560`), out: []volume.Usage{ {Label: "volumelabel on /dev/sdb1", Type: "Total Bytes", Value: 1901233012736}, {Label: "volumelabel on /dev/sdb1", Type: "Used Bytes", Value: 172685119488}, {Label: "volumelabel on /dev/sdb1", Type: "Available Bytes", Value: 1631947202560}, }, outmsg: "output did not match expectation", err: nil, errmsg: "error was not nil", }, { label: "empty input handled gracefully", inlabel: "volumelabel", inbytes: []byte{}, out: []volume.Usage{}, outmsg: "output did not match expectation", err: nil, errmsg: "error was not nil", }, } func TestStub(t *testing.T) { assert.True(t, true, "Test environment set up properly.") } func TestParseDF(t *testing.T) { for _, tc := range parsedftests { result, err := parseDFCommand(tc.inlabel, tc.inbytes) assert.Equal(t, err, tc.err, fmt.Sprintf("%s: %s", tc.label, tc.errmsg)) assert.Equal(t, result, tc.out, fmt.Sprintf("%s: %s", tc.label, tc.outmsg)) } }
spindance/serviced-precomp
volume/rsync/rsync_unit_test.go
GO
apache-2.0
2,090
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.engine.fudgemsg; import java.util.ArrayList; import java.util.List; import org.fudgemsg.FudgeField; import org.fudgemsg.FudgeMsg; import org.fudgemsg.MutableFudgeMsg; import org.fudgemsg.mapping.FudgeBuilder; import org.fudgemsg.mapping.FudgeDeserializer; import org.fudgemsg.mapping.FudgeSerializer; import org.fudgemsg.mapping.GenericFudgeBuilderFor; import org.fudgemsg.wire.types.FudgeWireType; import com.opengamma.engine.value.ValueProperties; /** * Fudge message builder for {@link ValueProperties}. Messages can take the form: * <ul> * <li>The empty property set is an empty message. * <li>A simple property set has a field named {@code with} that contains a sub-message. This in turn contains a field per property - the name of * the field is the name of the property. This is either a: * <ul> * <li>Simple string value * <li>An indicator indicating a wild-card property value * <li>A sub-message containing un-named fields with each possible value of the property. * </ul> * If the property is optional, the sub-message form is used with a field named {@code optional}. If the field is an optional wild-card the sub-message * form is used which contains only the {@code optional} field. * <li>The infinite property set ({@link ValueProperties#all}) has a field named {@code without} that contains an empty sub-message. * <li>The near-infinite property set has a field named {@code without} that contains a field for each of absent entries, the string value of each field * is the property name. * </ul> */ @GenericFudgeBuilderFor(ValueProperties.class) public class ValuePropertiesFudgeBuilder implements FudgeBuilder<ValueProperties> { // TODO: The message format described above is not particularly efficient or convenient, but kept for compatibility /** * Field name for the sub-message containing property values. */ public static final String WITH_FIELD = "with"; /** * Field name for the sub-message representing the infinite or near-infinite property set. */ public static final String WITHOUT_FIELD = "without"; /** * Field name for the 'optional' flag. */ public static final String OPTIONAL_FIELD = "optional"; @Override public MutableFudgeMsg buildMessage(final FudgeSerializer serializer, final ValueProperties object) { final MutableFudgeMsg message = serializer.newMessage(); object.toFudgeMsg(message); return message; } @Override public ValueProperties buildObject(final FudgeDeserializer deserializer, final FudgeMsg message) { if (message.isEmpty()) { return ValueProperties.none(); } FudgeMsg subMsg = message.getMessage(WITHOUT_FIELD); if (subMsg != null) { if (subMsg.isEmpty()) { // Infinite return ValueProperties.all(); } // Near-infinite final ValueProperties.Builder builder = ValueProperties.all().copy(); for (final FudgeField field : subMsg) { if (field.getType().getTypeId() == FudgeWireType.STRING_TYPE_ID) { builder.withoutAny((String) field.getValue()); } } return builder.get(); } subMsg = message.getMessage(WITH_FIELD); if (subMsg == null) { return ValueProperties.none(); } final ValueProperties.Builder builder = ValueProperties.builder(); for (final FudgeField field : subMsg) { final String propertyName = field.getName(); switch (field.getType().getTypeId()) { case FudgeWireType.INDICATOR_TYPE_ID: builder.withAny(propertyName); break; case FudgeWireType.STRING_TYPE_ID: builder.with(propertyName, (String) field.getValue()); break; case FudgeWireType.SUB_MESSAGE_TYPE_ID: { final FudgeMsg subMsg2 = (FudgeMsg) field.getValue(); final List<String> values = new ArrayList<>(subMsg2.getNumFields()); for (final FudgeField field2 : subMsg2) { switch (field2.getType().getTypeId()) { case FudgeWireType.INDICATOR_TYPE_ID: builder.withOptional(propertyName); break; case FudgeWireType.STRING_TYPE_ID: values.add((String) field2.getValue()); break; } } if (!values.isEmpty()) { builder.with(propertyName, values); } break; } } } return builder.get(); } }
McLeodMoores/starling
projects/engine/src/main/java/com/opengamma/engine/fudgemsg/ValuePropertiesFudgeBuilder.java
Java
apache-2.0
4,577
/// <reference path="BaseCallback.d.ts" /> /// <reference path="CommonUtil.d.ts" /> /// <reference path="IServiceResultCallback.d.ts" /> /// <reference path="IServiceResultCallbackError.d.ts" /> /// <reference path="IServiceResultCallbackWarning.d.ts" /> /// <reference path="ServiceResponse.d.ts" /> /** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:carlos@adaptive.me> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:ferran.vila.conesa@gmail.com> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ declare module Adaptive { /** Interface for Managing the Services operations Auto-generated implementation of IServiceResultCallback specification. */ /** @property {Adaptive.Dictionary} registeredServiceResultCallback @member Adaptive @private ServiceResultCallback control dictionary. */ var registeredServiceResultCallback: Dictionary<IServiceResultCallback>; /** @method @private @member Adaptive @param {number} id @param {Adaptive.IServiceResultCallbackError} error */ function handleServiceResultCallbackError(id: number, error: IServiceResultCallbackError): void; /** @method @private @member Adaptive @param {number} id @param {Adaptive.ServiceResponse} response */ function handleServiceResultCallbackResult(id: number, response: ServiceResponse): void; /** @method @private @member Adaptive @param {number} id @param {Adaptive.ServiceResponse} response @param {Adaptive.IServiceResultCallbackWarning} warning */ function handleServiceResultCallbackWarning(id: number, response: ServiceResponse, warning: IServiceResultCallbackWarning): void; /** @class Adaptive.ServiceResultCallback @extends Adaptive.BaseCallback */ class ServiceResultCallback extends BaseCallback implements IServiceResultCallback { /** @private @property */ onErrorFunction: (error: IServiceResultCallbackError) => void; /** @private @property */ onResultFunction: (response: ServiceResponse) => void; /** @private @property */ onWarningFunction: (response: ServiceResponse, warning: IServiceResultCallbackWarning) => void; /** @method constructor Constructor with anonymous handler functions for callback. @param {Function} onErrorFunction Function receiving parameters of type: Adaptive.IServiceResultCallbackError @param {Function} onResultFunction Function receiving parameters of type: Adaptive.ServiceResponse @param {Function} onWarningFunction Function receiving parameters of type: Adaptive.ServiceResponse, Adaptive.IServiceResultCallbackWarning */ constructor(onErrorFunction: (error: IServiceResultCallbackError) => void, onResultFunction: (response: ServiceResponse) => void, onWarningFunction: (response: ServiceResponse, warning: IServiceResultCallbackWarning) => void); /** @method This method is called on Error @param {Adaptive.IServiceResultCallbackError} error error returned by the platform @since v2.0 */ onError(error: IServiceResultCallbackError): void; /** @method This method is called on Result @param {Adaptive.ServiceResponse} response response data @since v2.0 */ onResult(response: ServiceResponse): void; /** @method This method is called on Warning @param {Adaptive.ServiceResponse} response response data @param {Adaptive.IServiceResultCallbackWarning} warning warning returned by the platform @since v2.0 */ onWarning(response: ServiceResponse, warning: IServiceResultCallbackWarning): void; } }
AdaptiveMe/adaptive-arp-javascript
adaptive-arp-js/src_units/ServiceResultCallback.d.ts
TypeScript
apache-2.0
5,079
package voltric.io.data.arff; /** * Created by Fernando on 2/15/2017. */ public class ArffFolderReader { }
fernandoj92/mvca-parkinson
voltric-ltm-analysis/src/main/java/voltric/io/data/arff/ArffFolderReader.java
Java
apache-2.0
110
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 { StateParams, StateService } from '@uirouter/core'; import _ = require('lodash'); import { ApiService } from '../../../../../services/api.service'; import NotificationService from '../../../../../services/notification.service'; class ApiEndpointGroupController { private api: any; private group: any; private initialGroups: any; private discovery: any; private creation = false; private serviceDiscoveryJsonSchemaForm: string[]; private types: any[]; private serviceDiscoveryJsonSchema: any; private serviceDiscoveryConfigurationForm: any; constructor( private ApiService: ApiService, private NotificationService: NotificationService, private ServiceDiscoveryService, private $scope, private $rootScope: ng.IRootScopeService, private resolvedServicesDiscovery, private $state: StateService, private $stateParams: StateParams, private $timeout, ) { 'ngInject'; } $onInit() { this.api = this.$scope.$parent.apiCtrl.api; this.group = _.find(this.api.proxy.groups, { name: this.$stateParams.groupName }); this.$scope.duplicateEndpointNames = false; // Creation mode if (!this.group) { this.group = {}; this.creation = true; } this.serviceDiscoveryJsonSchemaForm = ['*']; this.types = this.resolvedServicesDiscovery.data; this.discovery = this.group.services && this.group.services.discovery; this.discovery = this.discovery || { enabled: false, configuration: {} }; this.initialGroups = _.cloneDeep(this.api.proxy.groups); this.$scope.lbs = [ { name: 'Round-Robin', value: 'ROUND_ROBIN', }, { name: 'Random', value: 'RANDOM', }, { name: 'Weighted Round-Robin', value: 'WEIGHTED_ROUND_ROBIN', }, { name: 'Weighted Random', value: 'WEIGHTED_RANDOM', }, ]; if (!this.group.load_balancing) { this.group.load_balancing = { type: this.$scope.lbs[0].value, }; } this.retrievePluginSchema(); } onTypeChange() { this.discovery.configuration = {}; this.retrievePluginSchema(); } retrievePluginSchema() { if (this.discovery.provider !== undefined) { this.ServiceDiscoveryService.getSchema(this.discovery.provider).then( ({ data }) => { this.serviceDiscoveryJsonSchema = data; }, (response) => { if (response.status === 404) { this.serviceDiscoveryJsonSchema = {}; return { schema: {}, }; } else { // todo manage errors this.NotificationService.showError('Unexpected error while loading service discovery schema for ' + this.discovery.provider); } }, ); } } update(api) { // include discovery service this.group.services = { discovery: this.discovery, }; if (!_.includes(api.proxy.groups, this.group)) { if (!api.proxy.groups) { api.proxy.groups = [this.group]; } else { api.proxy.groups.push(this.group); } } if (this.group.ssl.trustAll) { delete this.group.ssl.trustStore; } if (this.group.ssl.trustStore && (!this.group.ssl.trustStore.type || this.group.ssl.trustStore.type === '')) { delete this.group.ssl.trustStore; } if (this.group.ssl.keyStore && (!this.group.ssl.keyStore.type || this.group.ssl.keyStore.type === '')) { delete this.group.ssl.keyStore; } if (this.group.headers.length > 0) { this.group.headers = _.mapValues(_.keyBy(this.group.headers, 'name'), 'value'); } else { delete this.group.headers; } this.ApiService.update(api).then((updatedApi) => { this.api = updatedApi.data; this.api.etag = updatedApi.headers('etag'); this.onApiUpdate(); this.initialGroups = _.cloneDeep(api.proxy.groups); }); } onApiUpdate() { this.$rootScope.$broadcast('apiChangeSuccess', { api: this.api }); this.NotificationService.show('Group configuration saved'); this.$state.go('management.apis.detail.proxy.endpoints'); } reset() { this.$scope.duplicateEndpointNames = false; this.$state.reload(); } backToEndpointsConfiguration() { this.reset(); this.api.proxy.groups = _.cloneDeep(this.initialGroups); this.$state.go('management.apis.detail.proxy.endpoints'); } checkEndpointNameUniqueness() { this.$scope.duplicateEndpointNames = this.ApiService.isEndpointNameAlreadyUsed(this.api, this.group.name, this.creation); } } export default ApiEndpointGroupController;
gravitee-io/gravitee-management-webui
src/management/api/proxy/backend/endpoint/group.controller.ts
TypeScript
apache-2.0
5,282
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.optaplanner.core.impl.solver.scope; import java.util.List; import java.util.Random; import java.util.concurrent.Semaphore; import org.optaplanner.core.api.domain.solution.PlanningSolution; import org.optaplanner.core.api.score.Score; import org.optaplanner.core.api.solver.Solver; import org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor; import org.optaplanner.core.impl.phase.scope.AbstractPhaseScope; import org.optaplanner.core.impl.score.definition.ScoreDefinition; import org.optaplanner.core.impl.score.director.InnerScoreDirector; import org.optaplanner.core.impl.solver.termination.Termination; import org.optaplanner.core.impl.solver.thread.ChildThreadType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class SolverScope<Solution_> { protected final transient Logger logger = LoggerFactory.getLogger(getClass()); protected int startingSolverCount; protected Random workingRandom; protected InnerScoreDirector<Solution_, ?> scoreDirector; /** * Used for capping CPU power usage in multithreaded scenarios. */ protected Semaphore runnableThreadSemaphore = null; protected volatile Long startingSystemTimeMillis; protected volatile Long endingSystemTimeMillis; protected long childThreadsScoreCalculationCount = 0; protected Score startingInitializedScore; protected volatile Solution_ bestSolution; protected volatile Score bestScore; protected Long bestSolutionTimeMillis; // ************************************************************************ // Constructors and simple getters/setters // ************************************************************************ public int getStartingSolverCount() { return startingSolverCount; } public void setStartingSolverCount(int startingSolverCount) { this.startingSolverCount = startingSolverCount; } public Random getWorkingRandom() { return workingRandom; } public void setWorkingRandom(Random workingRandom) { this.workingRandom = workingRandom; } public InnerScoreDirector<Solution_, ?> getScoreDirector() { return scoreDirector; } public void setScoreDirector(InnerScoreDirector<Solution_, ?> scoreDirector) { this.scoreDirector = scoreDirector; } public void setRunnableThreadSemaphore(Semaphore runnableThreadSemaphore) { this.runnableThreadSemaphore = runnableThreadSemaphore; } public Long getStartingSystemTimeMillis() { return startingSystemTimeMillis; } public Long getEndingSystemTimeMillis() { return endingSystemTimeMillis; } public SolutionDescriptor<Solution_> getSolutionDescriptor() { return scoreDirector.getSolutionDescriptor(); } public ScoreDefinition getScoreDefinition() { return scoreDirector.getScoreDefinition(); } public Solution_ getWorkingSolution() { return scoreDirector.getWorkingSolution(); } public int getWorkingEntityCount() { return scoreDirector.getWorkingEntityCount(); } public List<Object> getWorkingEntityList() { return scoreDirector.getWorkingEntityList(); } public int getWorkingValueCount() { return scoreDirector.getWorkingValueCount(); } public Score calculateScore() { return scoreDirector.calculateScore(); } public void assertScoreFromScratch(Solution_ solution) { scoreDirector.getScoreDirectorFactory().assertScoreFromScratch(solution); } public Score getStartingInitializedScore() { return startingInitializedScore; } public void setStartingInitializedScore(Score startingInitializedScore) { this.startingInitializedScore = startingInitializedScore; } public void addChildThreadsScoreCalculationCount(long addition) { childThreadsScoreCalculationCount += addition; } public long getScoreCalculationCount() { return scoreDirector.getCalculationCount() + childThreadsScoreCalculationCount; } public Solution_ getBestSolution() { return bestSolution; } /** * The {@link PlanningSolution best solution} must never be the same instance * as the {@link PlanningSolution working solution}, it should be a (un)changed clone. * * @param bestSolution never null */ public void setBestSolution(Solution_ bestSolution) { this.bestSolution = bestSolution; } public Score getBestScore() { return bestScore; } public void setBestScore(Score bestScore) { this.bestScore = bestScore; } public Long getBestSolutionTimeMillis() { return bestSolutionTimeMillis; } public void setBestSolutionTimeMillis(Long bestSolutionTimeMillis) { this.bestSolutionTimeMillis = bestSolutionTimeMillis; } // ************************************************************************ // Calculated methods // ************************************************************************ public void startingNow() { startingSystemTimeMillis = System.currentTimeMillis(); endingSystemTimeMillis = null; } public Long getBestSolutionTimeMillisSpent() { return bestSolutionTimeMillis - startingSystemTimeMillis; } public void endingNow() { endingSystemTimeMillis = System.currentTimeMillis(); } public boolean isBestSolutionInitialized() { return bestScore.isSolutionInitialized(); } public long calculateTimeMillisSpentUpToNow() { long now = System.currentTimeMillis(); return now - startingSystemTimeMillis; } public long getTimeMillisSpent() { return endingSystemTimeMillis - startingSystemTimeMillis; } /** * @return at least 0, per second */ public long getScoreCalculationSpeed() { long timeMillisSpent = getTimeMillisSpent(); // Avoid divide by zero exception on a fast CPU return getScoreCalculationCount() * 1000L / (timeMillisSpent == 0L ? 1L : timeMillisSpent); } public void setWorkingSolutionFromBestSolution() { // The workingSolution must never be the same instance as the bestSolution. scoreDirector.setWorkingSolution(scoreDirector.cloneSolution(bestSolution)); } public SolverScope<Solution_> createChildThreadSolverScope(ChildThreadType childThreadType) { SolverScope<Solution_> childThreadSolverScope = new SolverScope<>(); childThreadSolverScope.startingSolverCount = startingSolverCount; // TODO FIXME use RandomFactory // Experiments show that this trick to attain reproducibility doesn't break uniform distribution childThreadSolverScope.workingRandom = new Random(workingRandom.nextLong()); childThreadSolverScope.scoreDirector = scoreDirector.createChildThreadScoreDirector(childThreadType); childThreadSolverScope.startingSystemTimeMillis = startingSystemTimeMillis; childThreadSolverScope.endingSystemTimeMillis = null; childThreadSolverScope.startingInitializedScore = null; childThreadSolverScope.bestSolution = null; childThreadSolverScope.bestScore = null; childThreadSolverScope.bestSolutionTimeMillis = null; return childThreadSolverScope; } public void initializeYielding() { if (runnableThreadSemaphore != null) { try { runnableThreadSemaphore.acquire(); } catch (InterruptedException e) { // TODO it will take a while before the BasicPlumbingTermination is called // The BasicPlumbingTermination will terminate the solver. Thread.currentThread().interrupt(); } } } /** * Similar to {@link Thread#yield()}, but allows capping the number of active solver threads * at less than the CPU processor count, so other threads (for example servlet threads that handle REST calls) * and other processes (such as SSH) have access to uncontested CPUs and don't suffer any latency. * <p> * Needs to be called <b>before</b> {@link Termination#isPhaseTerminated(AbstractPhaseScope)}, * so the decision to start a new iteration is after any yield waiting time has been consumed * (so {@link Solver#terminateEarly()} reacts immediately). */ public void checkYielding() { if (runnableThreadSemaphore != null) { runnableThreadSemaphore.release(); try { runnableThreadSemaphore.acquire(); } catch (InterruptedException e) { // The BasicPlumbingTermination will terminate the solver. Thread.currentThread().interrupt(); } } } public void destroyYielding() { if (runnableThreadSemaphore != null) { runnableThreadSemaphore.release(); } } }
droolsjbpm/optaplanner
optaplanner-core/src/main/java/org/optaplanner/core/impl/solver/scope/SolverScope.java
Java
apache-2.0
9,712
package org.flowcolab.account.service.client.dto.account; import org.flowcolab.account.service.client.dto.person.PersonCreateRequest; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.AssertTrue; import javax.validation.constraints.NotNull; public class AccountCreateRequest { @NotNull @NotEmpty private String username; @NotNull @NotEmpty private String password; @NotNull @NotEmpty @Email private String email; @AssertTrue private Boolean isTermsAccepted; @NotNull private PersonCreateRequest person; public AccountCreateRequest() { } public AccountCreateRequest(String username, String password, String email, Boolean isTermsAccepted, PersonCreateRequest person) { this.username = username; this.password = password; this.email = email; this.isTermsAccepted = isTermsAccepted; this.person = person; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Boolean getIsTermsAccepted() { return isTermsAccepted; } public void setIsTermsAccepted(Boolean isTermsAccepted) { this.isTermsAccepted = isTermsAccepted; } public PersonCreateRequest getPerson() { return person; } public void setPerson(PersonCreateRequest person) { this.person = person; } @Override public String toString() { return "AccountCreateRequest{" + "username='" + username + '\'' + ", email='" + email + '\'' + ", isTermsAccepted=" + isTermsAccepted + '}'; } }
omacarena/novaburst.flowcolab
app/modules/account/account.service.client/src/main/org/flowcolab/account/service/client/dto/account/AccountCreateRequest.java
Java
apache-2.0
2,219
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.credit.creditdefaultswap.pricing; import javax.time.calendar.ZonedDateTime; import com.opengamma.analytics.financial.credit.BuySellProtection; import com.opengamma.analytics.financial.credit.PriceType; import com.opengamma.analytics.financial.credit.cds.ISDACurve; import com.opengamma.analytics.financial.credit.creditdefaultswap.definition.LegacyCreditDefaultSwapDefinition; import com.opengamma.analytics.financial.credit.hazardratemodel.HazardRateCurve; import com.opengamma.analytics.financial.credit.schedulegeneration.GenerateCreditDefaultSwapIntegrationSchedule; import com.opengamma.analytics.financial.credit.schedulegeneration.GenerateCreditDefaultSwapPremiumLegSchedule; import com.opengamma.analytics.util.time.TimeCalculator; import com.opengamma.financial.convention.daycount.DayCount; import com.opengamma.financial.convention.daycount.DayCountFactory; import com.opengamma.util.ArgumentChecker; /** * Class containing methods for the valuation of a vanilla Legacy CDS */ public class PresentValueLegacyCreditDefaultSwap { // ------------------------------------------------------------------------------------------------- private static final DayCount ACT_365 = DayCountFactory.INSTANCE.getDayCount("ACT/365"); // Set the number of partitions to divide the timeline up into for the valuation of the contingent leg private static final int DEFAULT_N_POINTS = 30; private final int _numberOfIntegrationSteps; public PresentValueLegacyCreditDefaultSwap() { this(DEFAULT_N_POINTS); } public PresentValueLegacyCreditDefaultSwap(int numberOfIntegrationPoints) { _numberOfIntegrationSteps = numberOfIntegrationPoints; } // ------------------------------------------------------------------------------------------------- // TODO : Lots of ongoing work to do in this class - Work In Progress // TODO : Add a method to calc both the legs in one method (useful for performance reasons e.g. not computing survival probabilities and discount factors twice) // TODO : If valuationDate = adjustedMatDate - 1day have to be more careful in how the contingent leg integral is calculated // TODO : Fix the bug when val date is very close to mat date // TODO : Need to add the code for when the settlement date > 0 business days (just a discount factor) // TODO : Replace the while with a binary search function // TODO : Should build the cashflow schedules outside of the leg valuation routines to avoid repitition of calculations // TODO : Eventually replace the ISDACurve with a YieldCurve object (currently using ISDACurve built by RiskCare as this allows exact comparison with the ISDA model) // TODO : Replace the accrued schedule double with a ZonedDateTime object to make it consistent with other calculations // TODO : Tidy up the calculatePremiumLeg, valueFeeLegAccrualOnDefault and methods // TODO : Add the calculation for the settlement and stepin discount factors // ------------------------------------------------------------------------------------------------- // Public method for computing the PV of a CDS based on an input CDS contract (with a hazard rate curve calibrated to market observed data) public double getPresentValueCreditDefaultSwap(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) { // ------------------------------------------------------------- // Check input CDS, YieldCurve and SurvivalCurve objects are not null ArgumentChecker.notNull(cds, "LegacyCreditDefaultSwapDefinition"); ArgumentChecker.notNull(yieldCurve, "YieldCurve"); ArgumentChecker.notNull(hazardRateCurve, "HazardRateCurve"); // ------------------------------------------------------------- // Calculate the value of the premium leg (including accrued if required) double presentValuePremiumLeg = calculatePremiumLeg(cds, yieldCurve, hazardRateCurve); // Calculate the value of the contingent leg double presentValueContingentLeg = calculateContingentLeg(cds, yieldCurve, hazardRateCurve); // Calculate the PV of the CDS (assumes we are buying protection i.e. paying the premium leg, receiving the contingent leg) double presentValue = -(cds.getParSpread() / 10000.0) * presentValuePremiumLeg + presentValueContingentLeg; // ------------------------------------------------------------- // If we require the clean price, then calculate the accrued interest and add this to the PV if (cds.getPriceType() == PriceType.CLEAN) { presentValue += calculateAccruedInterest(cds, yieldCurve, hazardRateCurve); } // If we are selling protection, then reverse the direction of the premium and contingent leg cashflows if (cds.getBuySellProtection() == BuySellProtection.SELL) { presentValue = -1 * presentValue; } // ------------------------------------------------------------- return presentValue; } //------------------------------------------------------------------------------------------------- // Public method to calculate the par spread of a CDS at contract inception (with a hazard rate curve calibrated to market observed data) public double getParSpreadCreditDefaultSwap(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) { // ------------------------------------------------------------- // Check input CDS, YieldCurve and SurvivalCurve objects are not null ArgumentChecker.notNull(cds, "CDS field"); ArgumentChecker.notNull(yieldCurve, "YieldCurve field"); ArgumentChecker.notNull(hazardRateCurve, "HazardRateCurve field"); // ------------------------------------------------------------- double parSpread = 0.0; // ------------------------------------------------------------- // Construct a cashflow schedule object final GenerateCreditDefaultSwapPremiumLegSchedule cashflowSchedule = new GenerateCreditDefaultSwapPremiumLegSchedule(); // Check if the valuationDate equals the adjusted effective date (have to do this after the schedule is constructed) ArgumentChecker.isTrue(cds.getValuationDate().equals(cashflowSchedule.getAdjustedEffectiveDate(cds)), "Valuation Date should equal the adjusted effective date when computing par spreads"); // ------------------------------------------------------------- // Calculate the value of the premium leg double presentValuePremiumLeg = calculatePremiumLeg(cds, yieldCurve, hazardRateCurve); // Calculate the value of the contingent leg double presentValueContingentLeg = calculateContingentLeg(cds, yieldCurve, hazardRateCurve); // ------------------------------------------------------------- // Calculate the par spread (NOTE : Returned value is in bps) if (Double.doubleToLongBits(presentValuePremiumLeg) == 0.0) { throw new IllegalStateException("Warning : The premium leg has a PV of zero - par spread cannot be computed"); } else { parSpread = 10000.0 * presentValueContingentLeg / presentValuePremiumLeg; } // ------------------------------------------------------------- return parSpread; } // ------------------------------------------------------------------------------------------------- // Method to calculate the value of the premium leg of a CDS (with a hazard rate curve calibrated to market observed data) // The code for the accrued calc has just been lifted from RiskCare's implementation for now because it exactly reproduces the ISDA model - will replace with a better model in due course private double calculatePremiumLeg(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) { // ------------------------------------------------------------- // Local variable definitions int startIndex = 0; int endIndex = 0; double presentValuePremiumLeg = 0.0; double presentValueAccruedInterest = 0.0; // ------------------------------------------------------------- // Construct a cashflow schedule object for the premium leg final GenerateCreditDefaultSwapPremiumLegSchedule cashflowSchedule = new GenerateCreditDefaultSwapPremiumLegSchedule(); // Build the premium leg cashflow schedule from the contract specification ZonedDateTime[] premiumLegSchedule = cashflowSchedule.constructCreditDefaultSwapPremiumLegSchedule(cds); // Construct a schedule object for the accrued leg (this is not a cashflow schedule per se, but a set of time nodes for evaluating the accrued payment integral) GenerateCreditDefaultSwapIntegrationSchedule accruedSchedule = new GenerateCreditDefaultSwapIntegrationSchedule(); // Build the integration schedule for the calculation of the accrued leg double[] accruedLegIntegrationSchedule = accruedSchedule.constructCreditDefaultSwapAccruedLegIntegrationSchedule(cds, yieldCurve, hazardRateCurve); // Calculate the stepin time with the appropriate offset double offsetStepinTime = accruedSchedule.calculateCreditDefaultSwapOffsetStepinTime(cds, ACT_365); // ------------------------------------------------------------- // Get the date on which we want to calculate the MtM ZonedDateTime valuationDate = cds.getValuationDate(); // Get the (adjusted) maturity date of the trade ZonedDateTime adjustedMaturityDate = cashflowSchedule.getAdjustedMaturityDate(cds); // ------------------------------------------------------------- // If the valuationDate is after the adjusted maturity date then throw an exception (differs from check in ctor because of the adjusted maturity date) ArgumentChecker.isTrue(!valuationDate.isAfter(adjustedMaturityDate), "Valuation date {} must be on or before the adjusted maturity date {}", valuationDate, adjustedMaturityDate); // If the valuation date is exactly the adjusted maturity date then simply return zero if (valuationDate.equals(adjustedMaturityDate)) { return 0.0; } // ------------------------------------------------------------- // Determine where in the cashflow schedule the valuationDate is int startCashflowIndex = getCashflowIndex(cds, premiumLegSchedule, 1, 1); // ------------------------------------------------------------- // Calculate the value of the remaining premium and accrual payments (due after valuationDate) for (int i = startCashflowIndex; i < premiumLegSchedule.length; i++) { // Get the beginning and end dates of the current coupon ZonedDateTime accrualStart = premiumLegSchedule[i - 1]; ZonedDateTime accrualEnd = premiumLegSchedule[i]; // ------------------------------------------------------------- // Calculate the time between the valuation date (time at which survival probability is unity) and the current cashflow double t = TimeCalculator.getTimeBetween(valuationDate, accrualEnd, ACT_365); // Calculate the discount factor at time t double discountFactor = yieldCurve.getDiscountFactor(t); // ------------------------------------------------------------- // If protection starts at the beginning of the period ... if (cds.getProtectionStart()) { // ... Roll all but the last date back by 1/365 of a year if (i < premiumLegSchedule.length - 1) { t -= cds.getProtectionOffset(); } // This is a bit of a hack - need a more elegant way of dealing with the timing nuances if (i == 1) { accrualStart = accrualStart.minusDays(1); } // ... Roll the final maturity date forward by one day if (i == premiumLegSchedule.length - 1) { accrualEnd = accrualEnd.plusDays(1); } } // ------------------------------------------------------------- // Compute the daycount fraction for the current accrual period double dcf = cds.getDayCountFractionConvention().getDayCountFraction(accrualStart, accrualEnd); // Calculate the survival probability at the modified time t double survivalProbability = hazardRateCurve.getSurvivalProbability(t); // Add this discounted cashflow to the running total for the value of the premium leg presentValuePremiumLeg += dcf * discountFactor * survivalProbability; // ------------------------------------------------------------- // Now calculate the accrued leg component if required (need to re-write this code) if (cds.getIncludeAccruedPremium()) { double stepinDiscountFactor = 1.0; startIndex = endIndex; while (accruedLegIntegrationSchedule[endIndex] < t) { ++endIndex; } presentValueAccruedInterest += valueFeeLegAccrualOnDefault(dcf, accruedLegIntegrationSchedule, yieldCurve, hazardRateCurve, startIndex, endIndex, offsetStepinTime, stepinDiscountFactor); } // ------------------------------------------------------------- } // ------------------------------------------------------------- return cds.getNotional() * (presentValuePremiumLeg + presentValueAccruedInterest); // ------------------------------------------------------------- } //------------------------------------------------------------------------------------------------- // Need to re-write this code completely!! private double valueFeeLegAccrualOnDefault(final double amount, final double[] timeline, final ISDACurve yieldCurve, final HazardRateCurve hazardRateCurve, final int startIndex, final int endIndex, final double stepinTime, final double stepinDiscountFactor) { final double[] timePoints = timeline; //timeline.getTimePoints(); final double startTime = timePoints[startIndex]; final double endTime = timePoints[endIndex]; final double subStartTime = stepinTime > startTime ? stepinTime : startTime; final double accrualRate = amount / (endTime - startTime); double t0, t1, dt, survival0, survival1, discount0, discount1; double lambda, fwdRate, lambdaFwdRate, valueForTimeStep, value; t0 = subStartTime - startTime + 0.5 * (1.0 / 365.0); //HALF_DAY_ACT_365F; survival0 = hazardRateCurve.getSurvivalProbability(subStartTime); double PRICING_TIME = 0.0; discount0 = startTime < stepinTime || startTime < PRICING_TIME ? stepinDiscountFactor : yieldCurve.getDiscountFactor(timePoints[startIndex]); //discountFactors[startIndex]; value = 0.0; for (int i = startIndex + 1; i <= endIndex; ++i) { if (timePoints[i] <= stepinTime) { continue; } t1 = timePoints[i] - startTime + 0.5 * (1.0 / 365.0); //HALF_DAY_ACT_365F; dt = t1 - t0; survival1 = hazardRateCurve.getSurvivalProbability(timePoints[i]); discount1 = yieldCurve.getDiscountFactor(timePoints[i]); //discountFactors[i]; lambda = Math.log(survival0 / survival1) / dt; fwdRate = Math.log(discount0 / discount1) / dt; lambdaFwdRate = lambda + fwdRate + 1.0e-50; valueForTimeStep = lambda * accrualRate * survival0 * discount0 * (((t0 + 1.0 / lambdaFwdRate) / lambdaFwdRate) - ((t1 + 1.0 / lambdaFwdRate) / lambdaFwdRate) * survival1 / survival0 * discount1 / discount0); value += valueForTimeStep; t0 = t1; survival0 = survival1; discount0 = discount1; } return value; } // ------------------------------------------------------------------------------------------------- // If the cleanPrice flag is TRUE then this function is called to calculate the accrued interest between valuationDate and the previous coupon date private double calculateAccruedInterest(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) { // Construct a cashflow schedule object final GenerateCreditDefaultSwapPremiumLegSchedule cashflowSchedule = new GenerateCreditDefaultSwapPremiumLegSchedule(); // Build the premium leg cashflow schedule from the contract specification ZonedDateTime[] premiumLegSchedule = cashflowSchedule.constructCreditDefaultSwapPremiumLegSchedule(cds); // Assume the stepin date is the valuation date + 1 day (this is not business day adjusted) ZonedDateTime stepinDate = cds.getValuationDate().plusDays(1); // Determine where in the premium leg cashflow schedule the current valuation date is int startCashflowIndex = getCashflowIndex(cds, premiumLegSchedule, 0, 1); // Get the date of the last coupon before the current valuation date ZonedDateTime previousPeriod = premiumLegSchedule[startCashflowIndex - 1]; // Compute the amount of time between previousPeriod and stepinDate double dcf = cds.getDayCountFractionConvention().getDayCountFraction(previousPeriod, stepinDate); // Calculate the accrued interest gained in this period of time double accruedInterest = (cds.getParSpread() / 10000.0) * dcf * cds.getNotional(); return accruedInterest; } // ------------------------------------------------------------------------------------------------- // Method to determine where in the premium leg cashflow schedule the valuation date is private int getCashflowIndex(LegacyCreditDefaultSwapDefinition cds, ZonedDateTime[] premiumLegSchedule, final int startIndex, final int deltaDays) { int counter = startIndex; // Determine where in the cashflow schedule the valuationDate is while (!cds.getValuationDate().isBefore(premiumLegSchedule[counter].minusDays(deltaDays))) { counter++; } return counter; } // ------------------------------------------------------------------------------------------------- // Method to calculate the contingent leg (replicates the calculation in the ISDA model) private double calculateContingentLeg(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) { // ------------------------------------------------------------- // Local variable definitions double presentValueContingentLeg = 0.0; // ------------------------------------------------------------- // Construct an integration schedule object for the contingent leg GenerateCreditDefaultSwapIntegrationSchedule contingentLegSchedule = new GenerateCreditDefaultSwapIntegrationSchedule(); // Build the integration schedule for the calculation of the contingent leg double[] contingentLegIntegrationSchedule = contingentLegSchedule.constructCreditDefaultSwapContingentLegIntegrationSchedule(cds, yieldCurve, hazardRateCurve); // ------------------------------------------------------------- // Get the survival probability at the first point in the integration schedule double survivalProbability = hazardRateCurve.getSurvivalProbability(contingentLegIntegrationSchedule[0]); // Get the discount factor at the first point in the integration schedule double discountFactor = yieldCurve.getDiscountFactor(contingentLegIntegrationSchedule[0]); // ------------------------------------------------------------- // Loop over each of the points in the integration schedule for (int i = 1; i < contingentLegIntegrationSchedule.length; ++i) { // Calculate the time between adjacent points in the integration schedule double deltat = contingentLegIntegrationSchedule[i] - contingentLegIntegrationSchedule[i - 1]; // Set the probability of survival up to the previous point in the integration schedule double survivalProbabilityPrevious = survivalProbability; // Set the discount factor up to the previous point in the integration schedule double discountFactorPrevious = discountFactor; // Get the survival probability at this point in the integration schedule survivalProbability = hazardRateCurve.getSurvivalProbability(contingentLegIntegrationSchedule[i]); // Get the discount factor at this point in the integration schedule discountFactor = yieldCurve.getDiscountFactor(contingentLegIntegrationSchedule[i]); // Calculate the forward hazard rate over the interval deltat (assumes the hazard rate is constant over this period) double hazardRate = Math.log(survivalProbabilityPrevious / survivalProbability) / deltat; // Calculate the forward interest rate over the interval deltat (assumes the interest rate is constant over this period) double interestRate = Math.log(discountFactorPrevious / discountFactor) / deltat; // Calculate the contribution of the interval deltat to the overall contingent leg integral presentValueContingentLeg += (hazardRate / (hazardRate + interestRate)) * (1.0 - Math.exp(-(hazardRate + interestRate) * deltat)) * survivalProbabilityPrevious * discountFactorPrevious; } // ------------------------------------------------------------- return cds.getNotional() * (1 - cds.getRecoveryRate()) * presentValueContingentLeg; } // ------------------------------------------------------------------------------------------------- // Method to calculate the value of the contingent leg of a CDS (with a hazard rate curve calibrated to market observed data) - Currently not used but this is a more elegant calc than ISDA private double calculateContingentLegOld(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) { // ------------------------------------------------------------- // Construct a schedule generation object (to access the adjusted maturity date method) GenerateCreditDefaultSwapPremiumLegSchedule cashflowSchedule = new GenerateCreditDefaultSwapPremiumLegSchedule(); // Get the date when protection begins ZonedDateTime valuationDate = cds.getValuationDate(); // Get the date when protection ends ZonedDateTime adjustedMaturityDate = cashflowSchedule.getAdjustedMaturityDate(cds); // ------------------------------------------------------------- // If the valuationDate is after the adjusted maturity date then throw an exception (differs from check in ctor because of the adjusted maturity date) ArgumentChecker.isTrue(!valuationDate.isAfter(adjustedMaturityDate), "Valuation date {} must be on or before the adjusted maturity date {}", valuationDate, adjustedMaturityDate); // If the valuation date is exactly the adjusted maturity date then simply return zero if (valuationDate.equals(adjustedMaturityDate)) { return 0.0; } // ------------------------------------------------------------- double presentValueContingentLeg = 0.0; // ------------------------------------------------------------- // Calculate the partition of the time axis for the calculation of the integral in the contingent leg // The period of time for which protection is provided double protectionPeriod = TimeCalculator.getTimeBetween(valuationDate, adjustedMaturityDate.plusDays(1), /*cds.getDayCountFractionConvention()*/ACT_365); // Given the protection period, how many partitions should it be divided into int numberOfPartitions = (int) (_numberOfIntegrationSteps * protectionPeriod + 0.5); // The size of the time increments in the calculation of the integral double epsilon = protectionPeriod / numberOfPartitions; // ------------------------------------------------------------- // Calculate the integral for the contingent leg (note the limits of the loop) for (int k = 1; k <= numberOfPartitions; k++) { double t = k * epsilon; double tPrevious = (k - 1) * epsilon; double discountFactor = yieldCurve.getDiscountFactor(t); double survivalProbability = hazardRateCurve.getSurvivalProbability(t); double survivalProbabilityPrevious = hazardRateCurve.getSurvivalProbability(tPrevious); presentValueContingentLeg += discountFactor * (survivalProbabilityPrevious - survivalProbability); } // ------------------------------------------------------------- return cds.getNotional() * (1.0 - cds.getRecoveryRate()) * presentValueContingentLeg; } // ------------------------------------------------------------------------------------------------- }
charles-cooper/idylfin
src/com/opengamma/analytics/financial/credit/creditdefaultswap/pricing/PresentValueLegacyCreditDefaultSwap.java
Java
apache-2.0
24,342
package com.twu.biblioteca; public class MockMenuOption { }
archana-khanal/twu-biblioteca-archanakhanal
test/com/twu/biblioteca/MockMenuOption.java
Java
apache-2.0
61
<?php if (!defined('IN_IAEWEB')) exit(); /** * 图片路径自动补全 */ function image($url) { if (empty($url) || strlen($url) < 4) return SITE_PATH.'data/upload/nopic.gif'; if (substr($url, 0, 7) == 'http://') return $url; if (strpos($url, SITE_PATH) !== false && SITE_PATH != '/') return $url; if (substr($url, 0, 1) == '/') $url = substr($url, 1); return SITE_PATH.$url; } /** * 缩略图片 */ function thumb($img, $width = 200, $height = 200) { if (empty($img) || strlen($img) < 4) return SITE_PATH.'data/upload/nopic.gif'; if (file_exists(IAEWEB_PATH.$img)) { $ext = fileext($img); $thumb = $img.'.thumb.'.$width.'x'.$height.'.'.$ext; if (!file_exists(IAEWEB_PATH.$thumb)) { $image = iaeweb::load_class('image'); $image->thumb(IAEWEB_PATH.$img, IAEWEB_PATH.$thumb, $width, $height); // 生成图像缩略图 } return $thumb; } return $img; } /** * 字符截取 支持UTF8/GBK */ function strcut($string, $length, $dot = '') { if (strlen($string) <= $length) return $string; $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string); $strcut = ''; $n = $tn = $noc = 0; while ($n < strlen($string)) { $t = ord($string[$n]); if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) { $tn = 1; $n++; $noc++; } elseif (194 <= $t && $t <= 223) { $tn = 2; $n += 2; $noc += 2; } elseif (224 <= $t && $t <= 239) { $tn = 3; $n += 3; $noc += 2; } elseif (240 <= $t && $t <= 247) { $tn = 4; $n += 4; $noc += 2; } elseif (248 <= $t && $t <= 251) { $tn = 5; $n += 5; $noc += 2; } elseif ($t == 252 || $t == 253) { $tn = 6; $n += 6; $noc += 2; } else { $n++; } if ($noc >= $length) break; } if ($noc > $length) $n -= $tn; $strcut = substr($string, 0, $n); $strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut); return $strcut.$dot; } /** * 取得文件扩展 */ function fileext($filename) { return pathinfo($filename, PATHINFO_EXTENSION); } /** * 正则表达式验证email格式 */ function is_email($email) { return strlen($email) > 6 && strlen($email) <= 32 && preg_match("/^([A-Za-z0-9\-_.+]+)@([A-Za-z0-9\-]+[.][A-Za-z0-9\-.]+)$/", $email); } /** * 栏目面包屑导航 当前位置 */ function position($catid, $symbol = ' > ') { if (empty($catid)) return false; $cats = get_cache('category'); $catids = parentids($catid, $cats); $catids = array_filter(explode(',', $catids)); krsort($catids); $html = ''; foreach ($catids as $t) { $html .= "<a href=\"".$cats[$t]['url']."\" title=\"".$cats[$t]['catname']."\">".$cats[$t]['catname']."</a>"; if ($catid != $t) $html .= $symbol; } return $html; } /** * 递归获取上级栏目集合 */ function parentids($catid, $cats) { if (empty($catid)) return false; $catids = $catid.','; if ($cats[$catid]['parentid']) $catids .= parentids($cats[$catid]['parentid'], $cats); return $catids; } /** * 获取当前栏目顶级栏目 */ function get_top_cat($catid) { $cats = get_cache('category'); $cat = $cats[$catid]; if ($cat['parentid']) $cat = get_top_cat($cat['parentid']); return $cat; } /** * 程序执行时间 */ function runtime() { $temptime = explode(' ', SYS_START_TIME); $time = $temptime[1] + $temptime[0]; $temptime = explode(' ', microtime()); $now = $temptime[1] + $temptime[0]; return number_format($now - $time, 6); } /** * 返回经stripslashes处理过的字符串或数组 */ function new_stripslashes($string) { if (!is_array($string)) return stripslashes($string); foreach ($string as $key => $val) $string[$key] = new_stripslashes($val); return $string; } /** * 将字符串转换为数组 */ function string2array($data) { if ($data == '') return array(); return unserialize($data); } /** * 将数组转换为字符串 */ function array2string($data, $isformdata = 1) { if ($data == '') return ''; if ($isformdata) $data = new_stripslashes($data); return serialize($data); } /** * 字节格式化 */ function file_size_count($size, $dec = 2) { $a = array("B", "KB", "MB", "GB", "TB", "PB"); $pos = 0; while ($size >= 1024) { $size /= 1024; $pos++; } return round($size, $dec)." ".$a[$pos]; } /** * 汉字转为拼音 */ function word2pinyin($word) { if (empty($word)) return ''; $pin = iaeweb::load_class('pinyin'); return str_replace('/', '', $pin->output($word)); } /** * 判断是否手机访问 */ function is_mobile() { static $is_mobile; if (isset($is_mobile)) return $is_mobile; if (empty($_SERVER['HTTP_USER_AGENT'])) { $is_mobile = false; } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false // many mobile devices (all iPhone, iPad, etc.) || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false) { $is_mobile = true; } else { $is_mobile = false; } return $is_mobile; } /** * 判定微信端 */ function is_wechat() { static $is_wechat; if (isset($is_wechat)) return $is_wechat; if (empty($_SERVER['HTTP_USER_AGENT'])) { $is_wechat = false; } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) { $is_wechat = true; } else { $is_wechat = false; } return $is_wechat; } /** * 转化 \ 为 / */ function dir_path($path) { $path = str_replace('\\', '/', $path); if (substr($path, -1) != '/') $path = $path.'/'; return $path; } /** * 递归创建目录 */ function mkdirs($dir) { if (empty($dir)) return false; if (!is_dir($dir)) { mkdirs(dirname($dir)); mkdir($dir); } } /** * 删除目录及目录下面的所有文件 */ function delete_dir($dir) { $dir = dir_path($dir); if (!is_dir($dir)) return FALSE; $list = glob($dir.'*'); foreach ($list as $v) { is_dir($v) ? delete_dir($v) : @unlink($v); } return @rmdir($dir); } /** * 写入缓存 */ function set_cache($cache_file, $value) { if (!$cache_file) return false; $cache_file = DATA_DIR.'cache'.DIRECTORY_SEPARATOR.$cache_file.'.cache.php'; $value = (!is_array($value)) ? serialize(trim($value)) : serialize($value); //增加安全 $value = "<?php if (!defined('IN_IAEWEB')) exit(); ?>".$value; if (!is_dir(DATA_DIR.'cache'.DIRECTORY_SEPARATOR)) { mkdirs(DATA_DIR.'cache'.DIRECTORY_SEPARATOR); } return file_put_contents($cache_file, $value, LOCK_EX) ? true : false; } /** * 获取缓存 */ function get_cache($cache_file) { if (!$cache_file) return false; static $cacheid = array(); if (!isset($cacheid[$cache_file])) { $file = DATA_DIR.'cache'.DIRECTORY_SEPARATOR.$cache_file.'.cache.php'; if (is_file($file)) { $value=str_replace("<?php if (!defined('IN_IAEWEB')) exit(); ?>", "", file_get_contents($file)); //$value = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $value); $cacheid[$cache_file] = unserialize($value); } else { return false; } } return $cacheid[$cache_file]; } /** * 删除缓存 */ function delete_cache($cache_file) { if (!$cache_file) return true; $cache_file = DATA_DIR.'cache'.DIRECTORY_SEPARATOR.$cache_file.'.cache.php'; return is_file($cache_file) ? unlink($cache_file) : true; } /** * 组装url */ function url($route, $params = null) { if (!$route) return false; $arr = explode('/', $route); $arr = array_diff($arr, array('')); $url = 'index.php'; if (isset($arr[0]) && $arr[0]) { $url .= '?c='.strtolower($arr[0]); if (isset($arr[1]) && $arr[1] && $arr[1] != 'index') $url .= '&a='.strtolower($arr[1]); } if (!is_null($params) && is_array($params)) { $params_url = array(); foreach ($params as $key => $value) { $params_url[] = trim($key).'='.trim($value); } $url .= '&'.implode('&', $params_url); } $url = str_replace('//', '/', $url); return Base::get_base_url().$url; } /* hbsion PLUS*/ /** * 递归获取上级栏目路径 */ function get_parent_dir($catid, $symbol = '/') { if (empty($catid)) return false; $cats = get_cache('category'); $catids = parentids($catid, $cats); $catids = array_filter(explode(',', $catids)); krsort($catids); $catdirs = ''; foreach ($catids as $t) { $catdirs .= $cats[$t]['catdir']; if ($catid != $t) $catdirs .= $symbol; } return $catdirs; } /** * 字符串替换一次 */ function str_replace_once($needkeywords, $replacekeywords, $content) { $pos = strpos($content, $needkeywords); if ($pos === false) { return $content; } return substr_replace($content, $replacekeywords, $pos, strlen($needkeywords)); } //计算年龄 function birthday($birthday) { $age = strtotime($birthday); if ($age == false) { return false; } list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age)); $now = strtotime("now"); list($y2, $m2, $d2) = explode("-", date("Y-m-d", $now)); $age = $y2 - $y1; if ((int)($m2.$d2) < (int)($m1.$d1)) $age -= 1; return $age; } /* 采集 PLUS*/ require("spider.function.php");
xiaohaoyong/www.jzfupin.cn
core/library/global.function.php
PHP
apache-2.0
10,008
/* * Copyright (c) 2013-2015, Arjuna Technologies Limited, Newcastle-upon-Tyne, England. All rights reserved. */ package com.arjuna.databroker.metadata.client; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; public interface ContentProxy { @GET @Path("contents") @Produces(MediaType.APPLICATION_JSON) public List<String> listMetadata(@QueryParam("requesterId") String requesterId, @QueryParam("userId") String userId); @GET @Path("/content/{id}") @Produces(MediaType.TEXT_PLAIN) public String getMetadata(@PathParam("id") String id, @QueryParam("requesterId") String requesterId, @QueryParam("userId") String userId); @POST @Path("/contents") @Consumes(MediaType.APPLICATION_JSON) public String postMetadata(@QueryParam("requesterId") String requesterId, @QueryParam("userId") String userId, String content); @POST @Path("/contents") @Consumes(MediaType.APPLICATION_JSON) public String postMetadata(@QueryParam("parentId") String parentId, @QueryParam("requesterId") String requesterId, @QueryParam("userId") String userId, String content); @PUT @Path("/content/{id}") @Consumes(MediaType.TEXT_PLAIN) public void putMetadata(@PathParam("id") String id, @QueryParam("requesterId") String requesterId, @QueryParam("userId") String userId, String content); }
RISBIC/DataBroker
metadata-ws/src/main/java/com/arjuna/databroker/metadata/client/ContentProxy.java
Java
apache-2.0
1,572
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.devopsguru.model; import javax.annotation.Generated; /** * <p> * The request was denied due to a request throttling. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ThrottlingException extends com.amazonaws.services.devopsguru.model.AmazonDevOpsGuruException { private static final long serialVersionUID = 1L; /** * <p> * The code of the quota that was exceeded, causing the throttling exception. * </p> */ private String quotaCode; /** * <p> * The code of the service that caused the throttling exception. * </p> */ private String serviceCode; /** * <p> * The number of seconds after which the action that caused the throttling exception can be retried. * </p> */ private Integer retryAfterSeconds; /** * Constructs a new ThrottlingException with the specified error message. * * @param message * Describes the error encountered. */ public ThrottlingException(String message) { super(message); } /** * <p> * The code of the quota that was exceeded, causing the throttling exception. * </p> * * @param quotaCode * The code of the quota that was exceeded, causing the throttling exception. */ @com.fasterxml.jackson.annotation.JsonProperty("QuotaCode") public void setQuotaCode(String quotaCode) { this.quotaCode = quotaCode; } /** * <p> * The code of the quota that was exceeded, causing the throttling exception. * </p> * * @return The code of the quota that was exceeded, causing the throttling exception. */ @com.fasterxml.jackson.annotation.JsonProperty("QuotaCode") public String getQuotaCode() { return this.quotaCode; } /** * <p> * The code of the quota that was exceeded, causing the throttling exception. * </p> * * @param quotaCode * The code of the quota that was exceeded, causing the throttling exception. * @return Returns a reference to this object so that method calls can be chained together. */ public ThrottlingException withQuotaCode(String quotaCode) { setQuotaCode(quotaCode); return this; } /** * <p> * The code of the service that caused the throttling exception. * </p> * * @param serviceCode * The code of the service that caused the throttling exception. */ @com.fasterxml.jackson.annotation.JsonProperty("ServiceCode") public void setServiceCode(String serviceCode) { this.serviceCode = serviceCode; } /** * <p> * The code of the service that caused the throttling exception. * </p> * * @return The code of the service that caused the throttling exception. */ @com.fasterxml.jackson.annotation.JsonProperty("ServiceCode") public String getServiceCode() { return this.serviceCode; } /** * <p> * The code of the service that caused the throttling exception. * </p> * * @param serviceCode * The code of the service that caused the throttling exception. * @return Returns a reference to this object so that method calls can be chained together. */ public ThrottlingException withServiceCode(String serviceCode) { setServiceCode(serviceCode); return this; } /** * <p> * The number of seconds after which the action that caused the throttling exception can be retried. * </p> * * @param retryAfterSeconds * The number of seconds after which the action that caused the throttling exception can be retried. */ @com.fasterxml.jackson.annotation.JsonProperty("Retry-After") public void setRetryAfterSeconds(Integer retryAfterSeconds) { this.retryAfterSeconds = retryAfterSeconds; } /** * <p> * The number of seconds after which the action that caused the throttling exception can be retried. * </p> * * @return The number of seconds after which the action that caused the throttling exception can be retried. */ @com.fasterxml.jackson.annotation.JsonProperty("Retry-After") public Integer getRetryAfterSeconds() { return this.retryAfterSeconds; } /** * <p> * The number of seconds after which the action that caused the throttling exception can be retried. * </p> * * @param retryAfterSeconds * The number of seconds after which the action that caused the throttling exception can be retried. * @return Returns a reference to this object so that method calls can be chained together. */ public ThrottlingException withRetryAfterSeconds(Integer retryAfterSeconds) { setRetryAfterSeconds(retryAfterSeconds); return this; } }
aws/aws-sdk-java
aws-java-sdk-devopsguru/src/main/java/com/amazonaws/services/devopsguru/model/ThrottlingException.java
Java
apache-2.0
5,545
# Copyright 2016 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. """ Definition of block device actions to display in the CLI. """ from .._actions import PhysicalActions PHYSICAL_SUBCMDS = [ ( "list", dict( help="List information about blockdevs in the pool", args=[ ( "pool_name", dict(action="store", default=None, nargs="?", help="Pool name"), ) ], func=PhysicalActions.list_devices, ), ) ]
stratis-storage/stratis-cli
src/stratis_cli/_parser/_physical.py
Python
apache-2.0
1,060
package org.dongzhou.rescueTime; import java.net.URI; import java.net.URISyntaxException; import org.apache.http.client.methods.RequestBuilder; import org.apache.log4j.Logger; public class ApiUtil { private static Logger logger = Logger.getLogger(ApiUtil.class.getName()); private static final String KEY = "B63vb_55nMqMqfDXcvoNJQqYcavyMlGnClMPRLeT"; public static RequestBuilder createRequestBuilder(String uri) { return createRequestBuilder(createURI(uri)); } private static RequestBuilder createRequestBuilder(URI uri) { return RequestBuilder.get().setUri(uri).addParameter("key", KEY); } private static URI createURI(String uri) { try { return new URI(uri); } catch (URISyntaxException e) { logger.error(e); return null; } } }
zhou-dong/probabilistic-graphical-models
src/org/dongzhou/rescueTime/ApiUtil.java
Java
apache-2.0
767
// Copyright 2018 Prometheus 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 cli import ( "context" "errors" "github.com/prometheus/client_golang/api" "gopkg.in/alecthomas/kingpin.v2" "github.com/prometheus/alertmanager/cli/format" "github.com/prometheus/alertmanager/client" ) const configHelp = `View current config. The amount of output is controlled by the output selection flag: - Simple: Print just the running config - Extended: Print the running config as well as uptime and all version info - Json: Print entire config object as json ` // configCmd represents the config command func configureConfigCmd(app *kingpin.Application) { app.Command("config", configHelp).Action(queryConfig).PreAction(requireAlertManagerURL) } func queryConfig(ctx *kingpin.ParseContext) error { c, err := api.NewClient(api.Config{Address: alertmanagerURL.String()}) if err != nil { return err } statusAPI := client.NewStatusAPI(c) status, err := statusAPI.Get(context.Background()) if err != nil { return err } formatter, found := format.Formatters[output] if !found { return errors.New("unknown output formatter") } return formatter.FormatConfig(status) }
Kellel/alertmanager
cli/config.go
GO
apache-2.0
1,698
/** * Copyright (c) 2011-2013, Lukas Eder, lukas.eder@gmail.com * All rights reserved. * * This software is licensed to you under the Apache License, Version 2.0 * (the "License"); You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * . Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * . Neither the name "jOOR" nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.janeluo.jfinalplus.kit; import java.lang.reflect.InvocationTargetException; /** * A unchecked wrapper for any of Java's checked reflection exceptions: * <p> * These exceptions are * <ul> * <li> {@link ClassNotFoundException}</li> * <li> {@link IllegalAccessException}</li> * <li> {@link IllegalArgumentException}</li> * <li> {@link InstantiationException}</li> * <li> {@link InvocationTargetException}</li> * <li> {@link NoSuchMethodException}</li> * <li> {@link NoSuchFieldException}</li> * <li> {@link SecurityException}</li> * </ul> * * @author Lukas Eder */ public class ReflectException extends RuntimeException { /** * Generated UID */ private static final long serialVersionUID = -6213149635297151442L; public ReflectException(String message) { super(message); } public ReflectException(String message, Throwable cause) { super(message, cause); } public ReflectException() { super(); } public ReflectException(Throwable cause) { super(cause); } }
yangyining/JFinal-plus
src/main/java/com/janeluo/jfinalplus/kit/ReflectException.java
Java
apache-2.0
2,843
package org.dbflute.erflute.db; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Driver; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import java.util.StringTokenizer; import org.dbflute.erflute.core.util.Check; import org.dbflute.erflute.editor.model.settings.JDBCDriverSetting; import org.dbflute.erflute.preference.PreferenceInitializer; import org.dbflute.erflute.preference.jdbc.JDBCPathDialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.ui.PlatformUI; /** * @author modified by jflute (originated in ermaster) */ public abstract class DBManagerBase implements DBManager { private final Set<String> reservedWords; public DBManagerBase() { DBManagerFactory.addDB(this); this.reservedWords = getReservedWords(); } @Override public String getURL(String serverName, String dbName, int port) { String temp = serverName.replaceAll("\\\\", "\\\\\\\\"); String url = getURL().replaceAll("<SERVER NAME>", temp); url = url.replaceAll("<PORT>", String.valueOf(port)); temp = dbName.replaceAll("\\\\", "\\\\\\\\"); url = url.replaceAll("<DB NAME>", temp); return url; } @Override public Class<Driver> getDriverClass(String driverClassName) { String path = null; try { try { @SuppressWarnings("unchecked") final Class<Driver> clazz = (Class<Driver>) Class.forName(driverClassName); return clazz; } catch (final ClassNotFoundException e) { path = PreferenceInitializer.getJDBCDriverPath(getId(), driverClassName); if (Check.isEmpty(path)) { throw new IllegalStateException( String.format("JDBC Driver Class \"%s\" is not found.\rIs \"Preferences> ERFlute> JDBC Driver\" set correctly?", driverClassName)); } final ClassLoader loader = getClassLoader(path); @SuppressWarnings("unchecked") final Class<Driver> clazz = (Class<Driver>) loader.loadClass(driverClassName); return clazz; } } catch (final MalformedURLException | ClassNotFoundException e) { final JDBCPathDialog dialog = new JDBCPathDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), getId(), driverClassName, path, new ArrayList<JDBCDriverSetting>(), false); if (dialog.open() == IDialogConstants.OK_ID) { final JDBCDriverSetting newDriverSetting = new JDBCDriverSetting(getId(), dialog.getDriverClassName(), dialog.getPath()); final List<JDBCDriverSetting> driverSettingList = PreferenceInitializer.getJDBCDriverSettingList(); if (driverSettingList.contains(newDriverSetting)) { driverSettingList.remove(newDriverSetting); } driverSettingList.add(newDriverSetting); PreferenceInitializer.saveJDBCDriverSettingList(driverSettingList); return getDriverClass(dialog.getDriverClassName()); } } return null; } private ClassLoader getClassLoader(String uri) throws MalformedURLException { final StringTokenizer tokenizer = new StringTokenizer(uri, ";"); final int count = tokenizer.countTokens(); final URL[] urls = new URL[count]; for (int i = 0; i < urls.length; i++) { urls[i] = new URL("file", "", tokenizer.nextToken()); } return new URLClassLoader(urls, getClass().getClassLoader()); } protected abstract String getURL(); @Override public abstract String getDriverClassName(); protected Set<String> getReservedWords() { final Set<String> reservedWords = new HashSet<>(); final ResourceBundle bundle = ResourceBundle.getBundle(getClass().getPackage().getName() + ".reserved_word"); final Enumeration<String> keys = bundle.getKeys(); while (keys.hasMoreElements()) { reservedWords.add(keys.nextElement().toUpperCase()); } return reservedWords; } @Override public boolean isReservedWord(String str) { return reservedWords.contains(str.toUpperCase()); } @Override public boolean isSupported(int supportItem) { final int[] supportItems = getSupportItems(); for (int i = 0; i < supportItems.length; i++) { if (supportItems[i] == supportItem) { return true; } } return false; } @Override public boolean doesNeedURLDatabaseName() { return true; } @Override public boolean doesNeedURLServerName() { return true; } abstract protected int[] getSupportItems(); @Override public List<String> getImportSchemaList(Connection con) throws SQLException { final List<String> schemaList = new ArrayList<>(); final DatabaseMetaData metaData = con.getMetaData(); try { final ResultSet rs = metaData.getSchemas(); while (rs.next()) { schemaList.add(rs.getString(1)); } } catch (final SQLException ignored) { // when schema is not supported } return schemaList; } @Override public List<String> getSystemSchemaList() { return new ArrayList<>(); } }
dbflute-session/erflute
src/org/dbflute/erflute/db/DBManagerBase.java
Java
apache-2.0
5,834
package com.centurylink.mdw.model.request; import com.centurylink.mdw.model.Jsonable; import com.centurylink.mdw.xml.XmlPath; import org.apache.xmlbeans.XmlException; /** * Request handler spec. * TODO: JSONPath */ public class HandlerSpec implements Comparable<HandlerSpec>, Jsonable { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } private final String handlerClass; public String getHandlerClass() { return handlerClass; } private String path; public String getPath() { return path; } public void setPath(String path) { this.path = path; } private boolean contentRouting = true; public boolean isContentRouting() { return contentRouting; } public void setContentRouting(boolean contentRouting) { this.contentRouting = contentRouting; } public HandlerSpec(String name, String handlerClass) { this.name = name; this.handlerClass = handlerClass; } private XmlPath xpath; public XmlPath getXpath() throws XmlException { if (xpath == null) xpath = new XmlPath(path); return xpath; } private String assetPath; public String getAssetPath() { return assetPath; } public void setAssetPath(String assetPath) { this.assetPath = assetPath; } @Override public int compareTo(HandlerSpec other) { if (handlerClass.equals(other.handlerClass)) return path.compareToIgnoreCase(other.handlerClass); else return handlerClass.compareToIgnoreCase(other.handlerClass); } @Override public String toString() { return path + " -> " + handlerClass; } @Override public boolean equals(Object other) { return this.toString().equals(other.toString()); } @Override public int hashCode() { return toString().hashCode(); } }
CenturyLinkCloud/mdw
mdw-common/src/com/centurylink/mdw/model/request/HandlerSpec.java
Java
apache-2.0
1,912
package tk.zielony.carbonsamples.applibrary; import android.app.Activity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import java.util.Arrays; import java.util.List; import carbon.widget.RecyclerView; import tk.zielony.carbonsamples.R; /** * Created by Marcin on 2014-12-15. */ public class RecyclerCardsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recycler_cards); List<ViewModel> items = Arrays.asList(new ViewModel(), new ViewModel(), new ViewModel(), new ViewModel(), new ViewModel(), new ViewModel(), new ViewModel()); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); recyclerView.setAdapter(new RecyclerAdapter(items, R.layout.card)); recyclerView.setHeader(R.layout.header_scrollview); } }
sevoan/Carbon
samples/src/main/java/tk/zielony/carbonsamples/applibrary/RecyclerCardsActivity.java
Java
apache-2.0
1,051
package dk.lessismore.nojpa.net.link; import dk.lessismore.nojpa.serialization.Serializer; import java.net.Socket; import java.io.IOException; public class ClientLink extends AbstractLink { public ClientLink(String serverName, int port) throws IOException { this(serverName, port, null); } public ClientLink(String serverName, int port, Serializer serializer) throws IOException { super(serializer); socket = new Socket(serverName, port); socket.setKeepAlive(true); socket.setSoTimeout(0); // This implies that a read call will block forever. in = socket.getInputStream(); out = socket.getOutputStream(); } }
NoJPA-LESS-IS-MORE/NoJPA
nojpa_common/src/main/java/dk/lessismore/nojpa/net/link/ClientLink.java
Java
apache-2.0
687
/* * Copyright (C) 2014 Divide.io * * 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.divide.client.auth; import io.divide.shared.server.KeyManager; import io.divide.shared.util.Crypto; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; public class MockKeyManager implements KeyManager { private String encryptionKey; private String pushKey; private KeyPair keyPair; public MockKeyManager(String encryptionKey) throws NoSuchAlgorithmException { this.encryptionKey = encryptionKey; this.keyPair = Crypto.getNew(); } public PublicKey getPublicKey(){ return keyPair.getPublic(); } public PrivateKey getPrivateKey(){ return keyPair.getPrivate(); } public String getSymmetricKey(){ return encryptionKey; } public String getPushKey() { return pushKey; } }
HiddenStage/divide
Client/mock-client/src/main/java/io/divide/client/auth/MockKeyManager.java
Java
apache-2.0
1,473
def write(es,body,index,doc_type): try: res = es.index(index=index, doc_type=doc_type, body=body) return res except Exception, e: return e def search(es,body,index,doc_type,size=None): if size is None: size=1000 try: res = es.search(index=index, doc_type=doc_type, body=body, size=size) return res except Exception, e: return None def update(es,body,index,doc_type,id): res = es.update(index=index, id=id, doc_type=doc_type, body=body) return res def delete(es,index,doc_type,id): res = es.delete(index=index,doc_type=doc_type,id=id) return res def compare(d1,d2): d1_keys = set(d1.keys()) d2_keys = set(d2.keys()) intersect_keys = d1_keys.intersection(d2_keys) compared = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]} return compared def consolidate(mac,es,type): device1={} deviceQuery = {"query": {"match_phrase": {"mac": { "query": mac }}}} deviceInfo=search(es, deviceQuery, 'sweet_security', type) for device in deviceInfo['hits']['hits']: if len(device1) > 0: modifiedInfo = compare(device1['_source'],device['_source']) #usually just two, but we'll keep the oldest one, since that one has probably been modified if modifiedInfo['firstSeen'][0] < modifiedInfo['firstSeen'][1]: deleteID=device['_id'] else: deleteID=device1['_id'] delete(es,'sweet_security',type,deleteID) device1=device
TravisFSmith/SweetSecurity
apache/flask/webapp/es.py
Python
apache-2.0
1,377
package com.bottlerocketstudios.continuitysample.core.application; import android.app.Application; import android.databinding.DataBindingUtil; import com.bottlerocketstudios.continuitysample.core.databinding.PicassoDataBindingComponent; import com.bottlerocketstudios.continuitysample.core.injection.ServiceInitializer; import com.bottlerocketstudios.groundcontrol.convenience.GroundControl; public class ContinuitySampleApplication extends Application { @Override public void onCreate() { super.onCreate(); //Avoid adding a whole DI framework and all of that just to keep a few objects around. ServiceInitializer.initializeContext(this); /** * Set the default component for DataBinding to use Picasso. This could also be GlideDataBindingComponent(); * If there is an actual need to decide at launch which DataBindingComponent to use, it can be done here. * Avoid repeatedly calling setDefaultComponent to switch on the fly. It will cause your application * to behave unpredictably and is not thread safe. If a different DataBindingComponent is needed for a * specific layout, you can specify that DataBindingComponent when you inflate the layout/setContentView. */ DataBindingUtil.setDefaultComponent(new PicassoDataBindingComponent()); /** * GroundControl's default UI policy will use a built in cache. It isn't necessary and actually * causes confusion as the Presenters serve this role. */ GroundControl.disableCache(); } }
BottleRocketStudios/Android-Continuity
ContinuitySample/app/src/main/java/com/bottlerocketstudios/continuitysample/core/application/ContinuitySampleApplication.java
Java
apache-2.0
1,583
import subprocess from constants import get_migration_directory, JobStatus from models import ConvertConfigJob from multi_process import WorkUnit import os import re NOX_64_BINARY = "nox-linux-64.bin" NOX_64_MAC = "nox-mac64.bin" class ConvertConfigWorkUnit(WorkUnit): def __init__(self, job_id): WorkUnit.__init__(self) self.job_id = job_id def start(self, db_session, logger, process_name): self.db_session = db_session try: self.convert_config_job = self.db_session.query(ConvertConfigJob).filter(ConvertConfigJob.id == self.job_id).first() if self.convert_config_job is None: logger.error('Unable to retrieve convert config job: %s' % self.job_id) return self.convert_config_job.set_status("Converting the configurations") self.db_session.commit() file_path = self.convert_config_job.file_path nox_to_use = get_migration_directory() + NOX_64_BINARY # nox_to_use = get_migration_directory() + NOX_64_MAC print "start executing nox conversion..." try: commands = [subprocess.Popen(["chmod", "+x", nox_to_use]), subprocess.Popen([nox_to_use, "-f", file_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE) ] nox_output, nox_error = commands[1].communicate() print "the nox finished its job." except OSError: self.convert_config_job.set_status(JobStatus.FAILED) self.db_session.commit() logger.exception("Running the configuration migration tool " + "{} on config file {} hit OSError.".format(nox_to_use, file_path)) conversion_successful = False if nox_error: self.convert_config_job.set_status(JobStatus.FAILED) self.db_session.commit() logger.exception("Running the configuration migration tool {} ".format(nox_to_use) + "on config file {} hit error:\n {}".format(file_path, nox_error)) if re.search("Done \[.*\]", nox_output): path = "" filename = file_path if file_path.count("/") > 0: path_filename = file_path.rsplit("/", 1) path = path_filename[0] filename = path_filename[1] converted_filename = filename.rsplit('.', 1)[0] + ".csv" if os.path.isfile(os.path.join(path, converted_filename)): self.convert_config_job.set_status(JobStatus.COMPLETED) self.db_session.commit() conversion_successful = True if not conversion_successful: self.convert_config_job.set_status(JobStatus.FAILED) self.db_session.commit() logger.exception("Configuration migration tool failed to convert {}".format(file_path) + ": {}".format(nox_output)) finally: self.db_session.close() def get_unique_key(self): return 'convert_config_job_{}'.format(self.job_id)
csm-aut/csm
csmserver/work_units/convert_config_work_unit.py
Python
apache-2.0
3,413
/* * ------ * Adept * ----- * Copyright (C) 2012-2017 Raytheon BBN Technologies Corp. * ----- * 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 (C) 2016 Raytheon BBN Technologies Corp. * * 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 adept.example; import org.junit.Test; import java.util.List; import adept.common.Document; import adept.common.EntityMention; import adept.common.Sentence; import adept.common.TokenOffset; import adept.common.HltContentContainer; import adept.common.Passage; import adept.utilities.DocumentMaker; // TODO: Auto-generated Javadoc /** * Simple class to test the dummy NER module. */ public class ExampleNamedEntityTaggerTest { /** * The main method. * * @param args * the arguments */ @Test public void Test() { HltContentContainer hltContainer = new HltContentContainer(); Document doc = DocumentMaker.getInstance().createDocument( ClassLoader.getSystemResource("ExampleNamedEntityTaggerTest.txt").getFile(),hltContainer); for(Passage p : hltContainer.getPassages()) System.out.println("PASSAGE::: " + p.getTokenOffset().getBegin() + " " + p.getTokenOffset().getEnd()); // create a sentence from the document. Note that the offsets are random // here, // and do not reflect an actual grammatical sentence. Sentence s = new Sentence(0, new TokenOffset(0, 30), doc.getDefaultTokenStream()); ExampleNamedEntityTagger dummy = new ExampleNamedEntityTagger(); List<EntityMention> mentions = dummy.process(s); System.out.println("After process method"); for (EntityMention mention : mentions) { System.out.println(mention.getValue()); } } }
BBN-E/Adept
example/src/test/java/adept/example/ExampleNamedEntityTaggerTest.java
Java
apache-2.0
2,679
package debop4s.data.orm.hibernate.repository; import debop4s.core.collections.PaginatedList; import debop4s.data.orm.hibernate.HibernateParameter; import org.hibernate.*; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Example; import org.hibernate.criterion.Order; import org.hibernate.criterion.ProjectionList; import org.springframework.transaction.annotation.Transactional; import java.io.Serializable; import java.util.Collection; import java.util.List; /** * HibernateRepository * * @author 배성혁 sunghyouk.bae@gmail.com * @since 2013. 11. 8. 오후 3:49 * @deprecated use {@link debop4s.data.orm.hibernate.repository.HibernateDao} */ @Deprecated @Transactional(readOnly = true) public interface HibernateRepository<T> { Session getSession(); void flush(); T load(Serializable id); T load(Serializable id, LockOptions lockOptions); T get(Serializable id); T get(Serializable id, LockOptions lockOptions); List<T> getIn(Collection<? extends Serializable> ids); List<T> getIn(Serializable[] ids); ScrollableResults scroll(Class<?> clazz); ScrollableResults scroll(DetachedCriteria dc); ScrollableResults scroll(DetachedCriteria dc, ScrollMode scrollMode); ScrollableResults scroll(Criteria criteria); ScrollableResults scroll(Criteria criteria, ScrollMode scrollMode); ScrollableResults scroll(Query query, HibernateParameter... parameters); ScrollableResults scroll(Query query, ScrollMode scrollMode, HibernateParameter... parameters); List<T> findAll(); List<T> findAll(Order... orders); List<T> findAll(int firstResult, int maxResult, Order... orders); List<T> find(Criteria criteria, Order... orders); List<T> find(Criteria criteria, int firstResult, int maxResult, Order... orders); List<T> find(DetachedCriteria dc, Order... orders); List<T> find(DetachedCriteria dc, int firstResult, int maxResults, Order... orders); List<T> find(Query query, HibernateParameter... parameters); List<T> find(Query query, int firstResult, int maxResults, HibernateParameter... parameters); List<T> findByHql(final String hql, HibernateParameter... parameters); List<T> findByHql(final String hql, int firstResult, int maxResults, HibernateParameter... parameters); List<T> findByNamedQuery(String queryName, HibernateParameter... parameters); List<T> findByNamedQuery(final String queryName, int firstResult, int maxResults, HibernateParameter... parameters); List<T> findBySQLString(final String sqlString, HibernateParameter... parameters); List<T> findBySQLString(final String sqlString, int firstResult, int maxResults, HibernateParameter... parameters); List<T> findByExample(Example example); PaginatedList<T> getPage(Criteria criteria, int pageNo, int pageSize, Order... orders); PaginatedList<T> getPage(DetachedCriteria dc, int pageNo, int pageSize, Order... orders); PaginatedList<T> getPage(Query query, int pageNo, int pageSize, HibernateParameter... parameters); PaginatedList<T> getPageByHql(String hql, int pageNo, int pageSize, HibernateParameter... parameters); PaginatedList<T> getPageByNamedQuery(final String queryName, int pageNo, int pageSize, HibernateParameter... parameters); PaginatedList<T> getPageBySQLString(final String sqlString, int pageNo, int pageSize, HibernateParameter... parameters); /** * 지정한 엔티티에 대한 유일한 결과를 조회합니다. (결과가 없거나, 복수이면 예외가 발생합니다. * * @param criteria 조회 조건 * @return 조회된 엔티티 */ T findUnique(Criteria criteria); /** * 지정한 엔티티에 대한 유일한 결과를 조회합니다. (결과가 없거나, 복수이면 예외가 발생합니다. * * @param dc 조회 조건 * @return 조회된 엔티티 */ T findUnique(DetachedCriteria dc); /** * 지정한 엔티티에 대한 유일한 결과를 조회합니다. (결과가 없거나, 복수이면 예외가 발생합니다. * * @param query 조회 조건 * @return 조회된 엔티티 */ T findUnique(Query query, HibernateParameter... parameters); /** * 지정한 엔티티에 대한 유일한 결과를 조회합니다. (결과가 없거나, 복수이면 예외가 발생합니다. * * @param hql 조회 조건 * @return 조회된 엔티티 */ T findUniqueByHql(String hql, HibernateParameter... parameters); /** * 지정한 엔티티에 대한 유일한 결과를 조회합니다. (결과가 없거나, 복수이면 예외가 발생합니다. * * @param queryName 쿼리 명 * @return 조회된 엔티티 */ T findUniqueByNamedQuery(final String queryName, HibernateParameter... parameters); /** * 지정한 엔티티에 대한 유일한 결과를 조회합니다. (결과가 없거나, 복수이면 예외가 발생합니다. * * @param sqlString 쿼리 명 * @return 조회된 엔티티 */ T findUniqueBySQLString(final String sqlString, HibernateParameter... parameters); /** * 질의 조건에 만족하는 첫번째 엔티티를 반환합니다. * * @param criteria 조회 조건 * @return 조회된 엔티티 */ T findFirst(Criteria criteria, Order... orders); /** * 질의 조건에 만족하는 첫번째 엔티티를 반환합니다. * * @param dc 조회 조건 * @return 조회된 엔티티 */ T findFirst(DetachedCriteria dc, Order... orders); /** * 질의 조건에 만족하는 첫번째 엔티티를 반환합니다. * * @param query 조회 조건 * @return 조회된 엔티티 */ T findFirst(Query query, HibernateParameter... parameters); /** * 질의 조건에 만족하는 첫번째 엔티티를 반환합니다. * * @param hql 조회 조건 * @return 조회된 엔티티 */ T findFirstByHql(String hql, HibernateParameter... parameters); /** * 질의 조건에 만족하는 첫번째 엔티티를 반환합니다. * * @param queryName 쿼리 명 * @return 조회된 엔티티 */ T findFirstByNamedQuery(final String queryName, HibernateParameter... parameters); /** * 질의 조건에 만족하는 첫번째 엔티티를 반환합니다. * * @param sqlString 쿼리 명 * @return 조회된 엔티티 */ T findFirstBySQLString(final String sqlString, HibernateParameter... parameters); boolean exists(Class<?> clazz); boolean exists(Criteria criteria); boolean exists(DetachedCriteria dc); boolean exists(Query query, HibernateParameter... parameters); boolean existsByHql(String hql, HibernateParameter... parameters); boolean existsByNamedQuery(final String queryName, HibernateParameter... parameters); boolean existsBySQLString(final String sqlString, HibernateParameter... parameters); long count(); long count(Criteria criteria); long count(DetachedCriteria dc); long count(Query query, HibernateParameter... parameters); long countByHql(String hql, HibernateParameter... parameters); long countByNamedQuery(final String queryName, HibernateParameter... parameters); long countBySQLString(final String sqlString, HibernateParameter... parameters); T merge(T entity); @Transactional void persist(T entity); @Transactional Serializable save(T entity); @Transactional void saveOrUpdate(T entity); @Transactional void update(T entity); @Transactional void delete(T entity); @Transactional void deleteById(Serializable id); @Transactional void deleteAll(); @Transactional void deleteAll(Collection<? extends T> entities); @Transactional void deleteAll(Criteria criteria); @Transactional void deleteAll(DetachedCriteria dc); /** Cascade 적용 없이 엔티티들을 모두 삭제합니다. */ @Transactional int deleteAllWithoutCascade(); /** * 쿼리를 실행합니다. * * @param query 실행할 Query * @param parameters 인자 정보 * @return 실행에 영향 받은 행의 수 */ @Transactional int executeUpdate(Query query, HibernateParameter... parameters); /** * 지정한 HQL 구문 (insert, update, del) 을 수행합니다. * * @param hql 수행할 HQL 구문 * @param parameters 인자 정보 * @return 실행에 영향 받은 행의 수 */ @Transactional int executeUpdateByHql(String hql, HibernateParameter... parameters); /** * 지정한 쿼리 구문 (insert, update, del) 을 수행합니다. * * @param queryName 수행할 Query 명 * @param parameters 인자 정보 * @return 실행에 영향 받은 행의 수 */ @Transactional int executeUpdateByNamedQuery(final String queryName, HibernateParameter... parameters); /** * 지정한 쿼리 구문 (insert, update, del) 을 수행합니다. * * @param sqlString 수행할 Query * @param parameters 인자 정보 * @return 실행에 영향 받은 행의 수 */ @Transactional int executeUpdateBySQLString(final String sqlString, HibernateParameter... parameters); <P> P reportOne(Class<P> projectClass, ProjectionList projectionList, Criteria criteria); <P> P reportOne(Class<P> projectClass, ProjectionList projectionList, DetachedCriteria dc); <P> List<P> reportList(Class<P> projectClass, ProjectionList projectionList, Criteria criteria); <P> List<P> reportList(Class<P> projectClass, ProjectionList projectionList, Criteria criteria, int firstResult, int maxResults); <P> List<P> reportList(Class<P> projectClass, ProjectionList projectionList, DetachedCriteria dc); <P> List<P> reportList(Class<P> projectClass, ProjectionList projectionList, DetachedCriteria dc, int firstResult, int maxResults); <P> PaginatedList<P> reportPage(Class<P> projectClass, ProjectionList projectionList, Criteria criteria, int pageNo, int pageSize); <P> PaginatedList<P> reportPage(Class<P> projectClass, ProjectionList projectionList, DetachedCriteria dc, int pageNo, int pageSize); }
debop/debop4s
debop4s-data-orm/src/main/scala/debop4s/data/orm/hibernate/repository/HibernateRepository.java
Java
apache-2.0
10,406
/* * Copyright © 2019 Cask Data, 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 io.cdap.plugin.zuora.objects; import com.google.gson.annotations.SerializedName; import io.cdap.cdap.api.data.schema.Schema; import io.cdap.plugin.zuora.restobjects.annotations.ObjectDefinition; import io.cdap.plugin.zuora.restobjects.annotations.ObjectFieldDefinition; import io.cdap.plugin.zuora.restobjects.objects.BaseObject; import javax.annotation.Nullable; /** * Object name: ProxyModifyUnitOfMeasure (ProxyModifyUnitOfMeasure). * Related objects: **/ @SuppressWarnings("unused") @ObjectDefinition( Name = "ProxyModifyUnitOfMeasure", ObjectType = ObjectDefinition.ObjectDefinitionType.NESTED ) public class ProxyModifyUnitOfMeasure extends BaseObject { /** * Name: Active (Active), Type: boolean. * Options (custom, update, select): false, false, false **/ @Nullable @SerializedName("active") @ObjectFieldDefinition(FieldType = Schema.Type.BOOLEAN) private Boolean active; /** * Name: DecimalPlaces (DecimalPlaces), Type: integer. * Options (custom, update, select): false, false, false **/ @Nullable @SerializedName("decimalPlaces") @ObjectFieldDefinition(FieldType = Schema.Type.INT) private Integer decimalPlaces; /** * Name: DisplayedAs (DisplayedAs), Type: string. * Options (custom, update, select): false, false, false **/ @Nullable @SerializedName("displayedAs") @ObjectFieldDefinition(FieldType = Schema.Type.STRING) private String displayedAs; /** * Name: RoundingMode (RoundingMode), Type: string. * Options (custom, update, select): false, false, false **/ @Nullable @SerializedName("roundingMode") @ObjectFieldDefinition(FieldType = Schema.Type.STRING) private String roundingMode; /** * Name: UomName (UomName), Type: string. * Options (custom, update, select): false, false, false **/ @Nullable @SerializedName("uomName") @ObjectFieldDefinition(FieldType = Schema.Type.STRING) private String uomName; @Override public void addFields() { addCustomField("active", active, Boolean.class); addCustomField("decimalPlaces", decimalPlaces, Integer.class); addCustomField("displayedAs", displayedAs, String.class); addCustomField("roundingMode", roundingMode, String.class); addCustomField("uomName", uomName, String.class); } }
data-integrations/zuora
src/main/java/io/cdap/plugin/zuora/objects/ProxyModifyUnitOfMeasure.java
Java
apache-2.0
2,879
from mod_base import * class CmdPrefix(Command): """Check or set the command prefix that the bot will respond to.""" def run(self, win, user, data, caller=None): args = Args(data) if args.Empty(): cp = self.bot.config["cmd_prefix"] win.Send("current command prefix is: " + cp) return False self.bot.config["cmd_prefix"] = args[0] win.Send("done") module = { "class": CmdPrefix, "type": MOD_COMMAND, "level": 5, "zone": IRC_ZONE_BOTH }
richrd/bx
modules/cmdprefix.py
Python
apache-2.0
528
package se.ugli.habanero.j; public class HabaneroException extends RuntimeException { private static final long serialVersionUID = 8697180611643224014L; public HabaneroException(final String msg) { super(msg); } public HabaneroException(final Throwable t) { super(t); } }
ugli/habanero-java
src/main/java/se/ugli/habanero/j/HabaneroException.java
Java
apache-2.0
285
/* * Copyright 2010-2014 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. */ /* * Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.EC2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.EC2.Model.Internal.MarshallTransformations { /// <summary> /// AttachVpnGateway Request Marshaller /// </summary> public class AttachVpnGatewayRequestMarshaller : IMarshaller<IRequest, AttachVpnGatewayRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((AttachVpnGatewayRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(AttachVpnGatewayRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.EC2"); request.Parameters.Add("Action", "AttachVpnGateway"); request.Parameters.Add("Version", "2015-10-01"); if(publicRequest != null) { if(publicRequest.IsSetVpcId()) { request.Parameters.Add("VpcId", StringUtils.FromString(publicRequest.VpcId)); } if(publicRequest.IsSetVpnGatewayId()) { request.Parameters.Add("VpnGatewayId", StringUtils.FromString(publicRequest.VpnGatewayId)); } } return request; } } }
rafd123/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/Internal/MarshallTransformations/AttachVpnGatewayRequestMarshaller.cs
C#
apache-2.0
2,614
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2012-2017 Snowflake Computing Inc. All right reserved. # """ Concurrent test module """ from logging import getLogger from multiprocessing.pool import ThreadPool import pytest from parameters import (CONNECTION_PARAMETERS_ADMIN) logger = getLogger(__name__) import snowflake.connector from snowflake.connector.compat import TO_UNICODE def _run_more_query(meta): logger.debug("running queries in %s%s", meta['user'], meta['idx']) cnx = meta['cnx'] try: cnx.cursor().execute(""" select count(*) from (select seq8() seq from table(generator(timelimit => 4))) """) logger.debug("completed queries in %s%s", meta['user'], meta['idx']) return {'user': meta['user'], 'result': 1} except snowflake.connector.errors.ProgrammingError: logger.exception('failed to select') return {'user': meta['user'], 'result': 0} @pytest.mark.skipif(True or not CONNECTION_PARAMETERS_ADMIN, reason=""" Flaky tests. To be fixed """) def test_concurrent_multiple_user_queries(conn_cnx, db_parameters): """ Multithreaded multiple users tests """ max_per_user = 10 max_per_account = 20 max_per_instance = 10 with conn_cnx(user=db_parameters['sf_user'], password=db_parameters['sf_password'], account=db_parameters['sf_account']) as cnx: cnx.cursor().execute( "alter system set QUERY_GATEWAY_ENABLED=true") cnx.cursor().execute( "alter system set QUERY_GATEWAY_MAX_PER_USER={0}".format( max_per_user)) cnx.cursor().execute( "alter system set QUERY_GATEWAY_MAX_PER_ACCOUNT={0}".format( max_per_account)) cnx.cursor().execute( "alter system set QUERY_GATEWAY_MAX_PER_INSTANCE={0}".format( max_per_instance)) try: with conn_cnx() as cnx: cnx.cursor().execute( "create or replace warehouse regress1 " "warehouse_type='medium' warehouse_size=small") cnx.cursor().execute( "create or replace warehouse regress2 " "warehouse_type='medium' warehouse_size=small") cnx.cursor().execute("use role securityadmin") cnx.cursor().execute("create or replace user snowwoman " "password='test'") cnx.cursor().execute("use role accountadmin") cnx.cursor().execute("grant role sysadmin to user snowwoman") cnx.cursor().execute("grant all on warehouse regress2 to sysadmin") cnx.cursor().execute( "alter user snowwoman set default_role=sysadmin") suc_cnt1 = 0 suc_cnt2 = 0 with conn_cnx() as cnx1: with conn_cnx(user='snowwoman', password='test') as cnx2: cnx1.cursor().execute('use warehouse regress1') cnx2.cursor().execute('use warehouse regress2') number_of_threads = 50 meta = [] for i in range(number_of_threads): cnx = cnx1 if i < number_of_threads / 2 else cnx2 user = 'A' if i < number_of_threads / 2 else 'B' idx = TO_UNICODE(i + 1) \ if i < number_of_threads / 2 \ else TO_UNICODE(i + 1) meta.append({'user': user, 'idx': idx, 'cnx': cnx}) pool = ThreadPool(processes=number_of_threads) all_results = pool.map(_run_more_query, meta) assert len(all_results) == number_of_threads, \ 'total number of jobs' for r in all_results: if r['user'] == 'A' and r['result'] > 0: suc_cnt1 += 1 elif r['user'] == 'B' and r['result'] > 0: suc_cnt2 += 1 logger.debug("A success: %s", suc_cnt1) logger.debug("B success: %s", suc_cnt2) # NOTE: if the previous test cancels a query, the incoming # query counter may not be reduced asynchrously, so # the maximum number of runnable queries can be one less assert suc_cnt1 + suc_cnt2 in (max_per_instance * 2, max_per_instance * 2 - 1), \ 'success queries for user A and B' finally: with conn_cnx() as cnx: cnx.cursor().execute("use role accountadmin") cnx.cursor().execute("drop warehouse if exists regress2") cnx.cursor().execute("drop warehouse if exists regress1") cnx.cursor().execute("use role securityadmin") cnx.cursor().execute("drop user if exists snowwoman") with conn_cnx(user=db_parameters['sf_user'], password=db_parameters['sf_password'], account=db_parameters['sf_account']) as cnx: cnx.cursor().execute( "alter system set QUERY_GATEWAY_MAX_PER_USER=default") cnx.cursor().execute( "alter system set QUERY_GATEWAY_MAX_PER_INSTANCE=default") cnx.cursor().execute( "alter system set QUERY_GATEWAY_MAX_PER_ACCOUNT=default")
mayfield/snowflake-connector-python
test/test_concurrent_multi_users.py
Python
apache-2.0
5,324
package com.esm.employee.service.utils; import java.io.IOException; import java.time.LocalDate; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; public class LocalDateTimeSerializer extends JsonSerializer<LocalDate> { @Override public void serialize(LocalDate localDate, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeString(localDate.toString()); } }
esm-services/esm-employee-service
src/main/java/com/esm/employee/service/utils/LocalDateTimeSerializer.java
Java
apache-2.0
633
/* * Copyright 2010-2013 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. */ using System; using System.Threading; using Amazon.ElasticLoadBalancing.Model; using Amazon.ElasticLoadBalancing.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.ElasticLoadBalancing { /// <summary> /// Implementation for accessing AmazonElasticLoadBalancing. /// /// Elastic Load Balancing <para> Elastic Load Balancing is a cost-effective and easy to use web service to help you improve the availability /// and scalability of your application running on Amazon Elastic Cloud Compute (Amazon EC2). It makes it easy for you to distribute application /// loads between two or more EC2 instances. Elastic Load Balancing supports the growth in traffic of your application by enabling availability /// through redundancy. </para> <para>This guide provides detailed information about Elastic Load Balancing actions, data types, and parameters /// that can be used for sending a query request. Query requests are HTTP or HTTPS requests that use the HTTP verb GET or POST and a query /// parameter named Action or Operation. Action is used throughout this documentation, although Operation is supported for backward /// compatibility with other AWS Query APIs.</para> <para>For detailed information on constructing a query request using the actions, data /// types, and parameters mentioned in this guide, go to Using the Query API in the <i>Elastic Load Balancing Developer Guide</i> .</para> /// <para>For detailed information about Elastic Load Balancing features and their associated actions, go to Using Elastic Load Balancing in the /// <i>Elastic Load Balancing Developer Guide</i> .</para> <para>This reference guide is based on the current WSDL, which is available at: /// </para> /// </summary> public class AmazonElasticLoadBalancingClient : AmazonWebServiceClient, AmazonElasticLoadBalancing { AbstractAWSSigner signer = new AWS4Signer(); #region Constructors /// <summary> /// Constructs AmazonElasticLoadBalancingClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSAccessKey" value="********************"/&gt; /// &lt;add key="AWSSecretKey" value="****************************************"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonElasticLoadBalancingClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonElasticLoadBalancingConfig(), true, AuthenticationTypes.User) { } /// <summary> /// Constructs AmazonElasticLoadBalancingClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSAccessKey" value="********************"/&gt; /// &lt;add key="AWSSecretKey" value="****************************************"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonElasticLoadBalancingClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonElasticLoadBalancingConfig(){RegionEndpoint = region}, true, AuthenticationTypes.User) { } /// <summary> /// Constructs AmazonElasticLoadBalancingClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSAccessKey" value="********************"/&gt; /// &lt;add key="AWSSecretKey" value="****************************************"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonElasticLoadBalancing Configuration Object</param> public AmazonElasticLoadBalancingClient(AmazonElasticLoadBalancingConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config, true, AuthenticationTypes.User) { } /// <summary> /// Constructs AmazonElasticLoadBalancingClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonElasticLoadBalancingClient(AWSCredentials credentials) : this(credentials, new AmazonElasticLoadBalancingConfig()) { } /// <summary> /// Constructs AmazonElasticLoadBalancingClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonElasticLoadBalancingClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonElasticLoadBalancingConfig(){RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonElasticLoadBalancingClient with AWS Credentials and an /// AmazonElasticLoadBalancingClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonElasticLoadBalancingClient Configuration Object</param> public AmazonElasticLoadBalancingClient(AWSCredentials credentials, AmazonElasticLoadBalancingConfig clientConfig) : base(credentials, clientConfig, false, AuthenticationTypes.User) { } /// <summary> /// Constructs AmazonElasticLoadBalancingClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonElasticLoadBalancingClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonElasticLoadBalancingConfig()) { } /// <summary> /// Constructs AmazonElasticLoadBalancingClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonElasticLoadBalancingClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonElasticLoadBalancingConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonElasticLoadBalancingClient with AWS Access Key ID, AWS Secret Key and an /// AmazonElasticLoadBalancingClient Configuration object. If the config object's /// UseSecureStringForAwsSecretKey is false, the AWS Secret Key /// is stored as a clear-text string. Please use this option only /// if the application environment doesn't allow the use of SecureStrings. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonElasticLoadBalancingClient Configuration Object</param> public AmazonElasticLoadBalancingClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonElasticLoadBalancingConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig, AuthenticationTypes.User) { } #endregion #region DescribeLoadBalancerPolicyTypes /// <summary> /// <para> Returns meta-information on the specified LoadBalancer policies defined by the Elastic Load Balancing service. The policy types that /// are returned from this action can be used in a CreateLoadBalancerPolicy action to instantiate specific policy configurations that will be /// applied to an Elastic LoadBalancer. </para> /// </summary> /// /// <param name="describeLoadBalancerPolicyTypesRequest">Container for the necessary parameters to execute the DescribeLoadBalancerPolicyTypes /// service method on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the DescribeLoadBalancerPolicyTypes service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="PolicyTypeNotFoundException"/> public DescribeLoadBalancerPolicyTypesResponse DescribeLoadBalancerPolicyTypes(DescribeLoadBalancerPolicyTypesRequest describeLoadBalancerPolicyTypesRequest) { IAsyncResult asyncResult = invokeDescribeLoadBalancerPolicyTypes(describeLoadBalancerPolicyTypesRequest, null, null, true); return EndDescribeLoadBalancerPolicyTypes(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the DescribeLoadBalancerPolicyTypes operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancerPolicyTypes"/> /// </summary> /// /// <param name="describeLoadBalancerPolicyTypesRequest">Container for the necessary parameters to execute the DescribeLoadBalancerPolicyTypes /// operation on AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDescribeLoadBalancerPolicyTypes operation.</returns> public IAsyncResult BeginDescribeLoadBalancerPolicyTypes(DescribeLoadBalancerPolicyTypesRequest describeLoadBalancerPolicyTypesRequest, AsyncCallback callback, object state) { return invokeDescribeLoadBalancerPolicyTypes(describeLoadBalancerPolicyTypesRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the DescribeLoadBalancerPolicyTypes operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancerPolicyTypes"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeLoadBalancerPolicyTypes.</param> /// /// <returns>Returns a DescribeLoadBalancerPolicyTypesResult from AmazonElasticLoadBalancing.</returns> public DescribeLoadBalancerPolicyTypesResponse EndDescribeLoadBalancerPolicyTypes(IAsyncResult asyncResult) { return endOperation<DescribeLoadBalancerPolicyTypesResponse>(asyncResult); } IAsyncResult invokeDescribeLoadBalancerPolicyTypes(DescribeLoadBalancerPolicyTypesRequest describeLoadBalancerPolicyTypesRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new DescribeLoadBalancerPolicyTypesRequestMarshaller().Marshall(describeLoadBalancerPolicyTypesRequest); var unmarshaller = DescribeLoadBalancerPolicyTypesResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } /// <summary> /// <para> Returns meta-information on the specified LoadBalancer policies defined by the Elastic Load Balancing service. The policy types that /// are returned from this action can be used in a CreateLoadBalancerPolicy action to instantiate specific policy configurations that will be /// applied to an Elastic LoadBalancer. </para> /// </summary> /// /// <returns>The response from the DescribeLoadBalancerPolicyTypes service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="PolicyTypeNotFoundException"/> public DescribeLoadBalancerPolicyTypesResponse DescribeLoadBalancerPolicyTypes() { return DescribeLoadBalancerPolicyTypes(new DescribeLoadBalancerPolicyTypesRequest()); } #endregion #region ConfigureHealthCheck /// <summary> /// <para> Enables the client to define an application healthcheck for the instances. </para> /// </summary> /// /// <param name="configureHealthCheckRequest">Container for the necessary parameters to execute the ConfigureHealthCheck service method on /// AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the ConfigureHealthCheck service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="LoadBalancerNotFoundException"/> public ConfigureHealthCheckResponse ConfigureHealthCheck(ConfigureHealthCheckRequest configureHealthCheckRequest) { IAsyncResult asyncResult = invokeConfigureHealthCheck(configureHealthCheckRequest, null, null, true); return EndConfigureHealthCheck(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the ConfigureHealthCheck operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.ConfigureHealthCheck"/> /// </summary> /// /// <param name="configureHealthCheckRequest">Container for the necessary parameters to execute the ConfigureHealthCheck operation on /// AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndConfigureHealthCheck operation.</returns> public IAsyncResult BeginConfigureHealthCheck(ConfigureHealthCheckRequest configureHealthCheckRequest, AsyncCallback callback, object state) { return invokeConfigureHealthCheck(configureHealthCheckRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the ConfigureHealthCheck operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.ConfigureHealthCheck"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginConfigureHealthCheck.</param> /// /// <returns>Returns a ConfigureHealthCheckResult from AmazonElasticLoadBalancing.</returns> public ConfigureHealthCheckResponse EndConfigureHealthCheck(IAsyncResult asyncResult) { return endOperation<ConfigureHealthCheckResponse>(asyncResult); } IAsyncResult invokeConfigureHealthCheck(ConfigureHealthCheckRequest configureHealthCheckRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new ConfigureHealthCheckRequestMarshaller().Marshall(configureHealthCheckRequest); var unmarshaller = ConfigureHealthCheckResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region DetachLoadBalancerFromSubnets /// <summary> /// <para> Removes subnets from the set of configured subnets in the VPC for the LoadBalancer. </para> <para> After a subnet is removed all of /// the EndPoints registered with the LoadBalancer that are in the removed subnet will go into the <i>OutOfService</i> state. When a subnet is /// removed, the LoadBalancer will balance the traffic among the remaining routable subnets for the LoadBalancer. </para> /// </summary> /// /// <param name="detachLoadBalancerFromSubnetsRequest">Container for the necessary parameters to execute the DetachLoadBalancerFromSubnets /// service method on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the DetachLoadBalancerFromSubnets service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="InvalidConfigurationRequestException"/> /// <exception cref="LoadBalancerNotFoundException"/> public DetachLoadBalancerFromSubnetsResponse DetachLoadBalancerFromSubnets(DetachLoadBalancerFromSubnetsRequest detachLoadBalancerFromSubnetsRequest) { IAsyncResult asyncResult = invokeDetachLoadBalancerFromSubnets(detachLoadBalancerFromSubnetsRequest, null, null, true); return EndDetachLoadBalancerFromSubnets(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the DetachLoadBalancerFromSubnets operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DetachLoadBalancerFromSubnets"/> /// </summary> /// /// <param name="detachLoadBalancerFromSubnetsRequest">Container for the necessary parameters to execute the DetachLoadBalancerFromSubnets /// operation on AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDetachLoadBalancerFromSubnets operation.</returns> public IAsyncResult BeginDetachLoadBalancerFromSubnets(DetachLoadBalancerFromSubnetsRequest detachLoadBalancerFromSubnetsRequest, AsyncCallback callback, object state) { return invokeDetachLoadBalancerFromSubnets(detachLoadBalancerFromSubnetsRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the DetachLoadBalancerFromSubnets operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DetachLoadBalancerFromSubnets"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDetachLoadBalancerFromSubnets.</param> /// /// <returns>Returns a DetachLoadBalancerFromSubnetsResult from AmazonElasticLoadBalancing.</returns> public DetachLoadBalancerFromSubnetsResponse EndDetachLoadBalancerFromSubnets(IAsyncResult asyncResult) { return endOperation<DetachLoadBalancerFromSubnetsResponse>(asyncResult); } IAsyncResult invokeDetachLoadBalancerFromSubnets(DetachLoadBalancerFromSubnetsRequest detachLoadBalancerFromSubnetsRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new DetachLoadBalancerFromSubnetsRequestMarshaller().Marshall(detachLoadBalancerFromSubnetsRequest); var unmarshaller = DetachLoadBalancerFromSubnetsResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region DescribeLoadBalancerPolicies /// <summary> /// <para>Returns detailed descriptions of the policies. If you specify a LoadBalancer name, the operation returns either the descriptions of /// the specified policies, or descriptions of all the policies created for the LoadBalancer. If you don't specify a LoadBalancer name, the /// operation returns descriptions of the specified sample policies, or descriptions of all the sample policies. The names of the sample /// policies have the <c>ELBSample-</c> prefix. </para> /// </summary> /// /// <param name="describeLoadBalancerPoliciesRequest">Container for the necessary parameters to execute the DescribeLoadBalancerPolicies service /// method on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the DescribeLoadBalancerPolicies service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="PolicyNotFoundException"/> /// <exception cref="LoadBalancerNotFoundException"/> public DescribeLoadBalancerPoliciesResponse DescribeLoadBalancerPolicies(DescribeLoadBalancerPoliciesRequest describeLoadBalancerPoliciesRequest) { IAsyncResult asyncResult = invokeDescribeLoadBalancerPolicies(describeLoadBalancerPoliciesRequest, null, null, true); return EndDescribeLoadBalancerPolicies(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the DescribeLoadBalancerPolicies operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancerPolicies"/> /// </summary> /// /// <param name="describeLoadBalancerPoliciesRequest">Container for the necessary parameters to execute the DescribeLoadBalancerPolicies /// operation on AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDescribeLoadBalancerPolicies operation.</returns> public IAsyncResult BeginDescribeLoadBalancerPolicies(DescribeLoadBalancerPoliciesRequest describeLoadBalancerPoliciesRequest, AsyncCallback callback, object state) { return invokeDescribeLoadBalancerPolicies(describeLoadBalancerPoliciesRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the DescribeLoadBalancerPolicies operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancerPolicies"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeLoadBalancerPolicies.</param> /// /// <returns>Returns a DescribeLoadBalancerPoliciesResult from AmazonElasticLoadBalancing.</returns> public DescribeLoadBalancerPoliciesResponse EndDescribeLoadBalancerPolicies(IAsyncResult asyncResult) { return endOperation<DescribeLoadBalancerPoliciesResponse>(asyncResult); } IAsyncResult invokeDescribeLoadBalancerPolicies(DescribeLoadBalancerPoliciesRequest describeLoadBalancerPoliciesRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new DescribeLoadBalancerPoliciesRequestMarshaller().Marshall(describeLoadBalancerPoliciesRequest); var unmarshaller = DescribeLoadBalancerPoliciesResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } /// <summary> /// <para>Returns detailed descriptions of the policies. If you specify a LoadBalancer name, the operation returns either the descriptions of /// the specified policies, or descriptions of all the policies created for the LoadBalancer. If you don't specify a LoadBalancer name, the /// operation returns descriptions of the specified sample policies, or descriptions of all the sample policies. The names of the sample /// policies have the <c>ELBSample-</c> prefix. </para> /// </summary> /// /// <returns>The response from the DescribeLoadBalancerPolicies service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="PolicyNotFoundException"/> /// <exception cref="LoadBalancerNotFoundException"/> public DescribeLoadBalancerPoliciesResponse DescribeLoadBalancerPolicies() { return DescribeLoadBalancerPolicies(new DescribeLoadBalancerPoliciesRequest()); } #endregion #region SetLoadBalancerPoliciesOfListener /// <summary> /// <para> Associates, updates, or disables a policy with a listener on the LoadBalancer. You can associate multiple policies with a listener. /// </para> /// </summary> /// /// <param name="setLoadBalancerPoliciesOfListenerRequest">Container for the necessary parameters to execute the /// SetLoadBalancerPoliciesOfListener service method on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the SetLoadBalancerPoliciesOfListener service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="PolicyNotFoundException"/> /// <exception cref="InvalidConfigurationRequestException"/> /// <exception cref="LoadBalancerNotFoundException"/> /// <exception cref="ListenerNotFoundException"/> public SetLoadBalancerPoliciesOfListenerResponse SetLoadBalancerPoliciesOfListener(SetLoadBalancerPoliciesOfListenerRequest setLoadBalancerPoliciesOfListenerRequest) { IAsyncResult asyncResult = invokeSetLoadBalancerPoliciesOfListener(setLoadBalancerPoliciesOfListenerRequest, null, null, true); return EndSetLoadBalancerPoliciesOfListener(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the SetLoadBalancerPoliciesOfListener operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerPoliciesOfListener"/> /// </summary> /// /// <param name="setLoadBalancerPoliciesOfListenerRequest">Container for the necessary parameters to execute the /// SetLoadBalancerPoliciesOfListener operation on AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndSetLoadBalancerPoliciesOfListener operation.</returns> public IAsyncResult BeginSetLoadBalancerPoliciesOfListener(SetLoadBalancerPoliciesOfListenerRequest setLoadBalancerPoliciesOfListenerRequest, AsyncCallback callback, object state) { return invokeSetLoadBalancerPoliciesOfListener(setLoadBalancerPoliciesOfListenerRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the SetLoadBalancerPoliciesOfListener operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerPoliciesOfListener"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetLoadBalancerPoliciesOfListener.</param> /// /// <returns>Returns a SetLoadBalancerPoliciesOfListenerResult from AmazonElasticLoadBalancing.</returns> public SetLoadBalancerPoliciesOfListenerResponse EndSetLoadBalancerPoliciesOfListener(IAsyncResult asyncResult) { return endOperation<SetLoadBalancerPoliciesOfListenerResponse>(asyncResult); } IAsyncResult invokeSetLoadBalancerPoliciesOfListener(SetLoadBalancerPoliciesOfListenerRequest setLoadBalancerPoliciesOfListenerRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new SetLoadBalancerPoliciesOfListenerRequestMarshaller().Marshall(setLoadBalancerPoliciesOfListenerRequest); var unmarshaller = SetLoadBalancerPoliciesOfListenerResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region DisableAvailabilityZonesForLoadBalancer /// <summary> /// <para> Removes the specified EC2 Availability Zones from the set of configured Availability Zones for the LoadBalancer. </para> <para> There /// must be at least one Availability Zone registered with a LoadBalancer at all times. A client cannot remove all the Availability Zones from a /// LoadBalancer. Once an Availability Zone is removed, all the instances registered with the LoadBalancer that are in the removed Availability /// Zone go into the OutOfService state. Upon Availability Zone removal, the LoadBalancer attempts to equally balance the traffic among its /// remaining usable Availability Zones. Trying to remove an Availability Zone that was not associated with the LoadBalancer does nothing. /// </para> <para><b>NOTE:</b> In order for this call to be successful, the client must have created the LoadBalancer. The client must provide /// the same account credentials as those that were used to create the LoadBalancer. </para> /// </summary> /// /// <param name="disableAvailabilityZonesForLoadBalancerRequest">Container for the necessary parameters to execute the /// DisableAvailabilityZonesForLoadBalancer service method on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the DisableAvailabilityZonesForLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="InvalidConfigurationRequestException"/> /// <exception cref="LoadBalancerNotFoundException"/> public DisableAvailabilityZonesForLoadBalancerResponse DisableAvailabilityZonesForLoadBalancer(DisableAvailabilityZonesForLoadBalancerRequest disableAvailabilityZonesForLoadBalancerRequest) { IAsyncResult asyncResult = invokeDisableAvailabilityZonesForLoadBalancer(disableAvailabilityZonesForLoadBalancerRequest, null, null, true); return EndDisableAvailabilityZonesForLoadBalancer(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the DisableAvailabilityZonesForLoadBalancer operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DisableAvailabilityZonesForLoadBalancer"/> /// </summary> /// /// <param name="disableAvailabilityZonesForLoadBalancerRequest">Container for the necessary parameters to execute the /// DisableAvailabilityZonesForLoadBalancer operation on AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDisableAvailabilityZonesForLoadBalancer operation.</returns> public IAsyncResult BeginDisableAvailabilityZonesForLoadBalancer(DisableAvailabilityZonesForLoadBalancerRequest disableAvailabilityZonesForLoadBalancerRequest, AsyncCallback callback, object state) { return invokeDisableAvailabilityZonesForLoadBalancer(disableAvailabilityZonesForLoadBalancerRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the DisableAvailabilityZonesForLoadBalancer operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DisableAvailabilityZonesForLoadBalancer"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDisableAvailabilityZonesForLoadBalancer.</param> /// /// <returns>Returns a DisableAvailabilityZonesForLoadBalancerResult from AmazonElasticLoadBalancing.</returns> public DisableAvailabilityZonesForLoadBalancerResponse EndDisableAvailabilityZonesForLoadBalancer(IAsyncResult asyncResult) { return endOperation<DisableAvailabilityZonesForLoadBalancerResponse>(asyncResult); } IAsyncResult invokeDisableAvailabilityZonesForLoadBalancer(DisableAvailabilityZonesForLoadBalancerRequest disableAvailabilityZonesForLoadBalancerRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new DisableAvailabilityZonesForLoadBalancerRequestMarshaller().Marshall(disableAvailabilityZonesForLoadBalancerRequest); var unmarshaller = DisableAvailabilityZonesForLoadBalancerResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region DescribeInstanceHealth /// <summary> /// <para> Returns the current state of the instances of the specified LoadBalancer. If no instances are specified, the state of all the /// instances for the LoadBalancer is returned. </para> <para><b>NOTE:</b> The client must have created the specified input LoadBalancer in /// order to retrieve this information; the client must provide the same account credentials as those that were used to create the LoadBalancer. /// </para> /// </summary> /// /// <param name="describeInstanceHealthRequest">Container for the necessary parameters to execute the DescribeInstanceHealth service method on /// AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the DescribeInstanceHealth service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="LoadBalancerNotFoundException"/> /// <exception cref="InvalidInstanceException"/> public DescribeInstanceHealthResponse DescribeInstanceHealth(DescribeInstanceHealthRequest describeInstanceHealthRequest) { IAsyncResult asyncResult = invokeDescribeInstanceHealth(describeInstanceHealthRequest, null, null, true); return EndDescribeInstanceHealth(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the DescribeInstanceHealth operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeInstanceHealth"/> /// </summary> /// /// <param name="describeInstanceHealthRequest">Container for the necessary parameters to execute the DescribeInstanceHealth operation on /// AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDescribeInstanceHealth operation.</returns> public IAsyncResult BeginDescribeInstanceHealth(DescribeInstanceHealthRequest describeInstanceHealthRequest, AsyncCallback callback, object state) { return invokeDescribeInstanceHealth(describeInstanceHealthRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the DescribeInstanceHealth operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeInstanceHealth"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeInstanceHealth.</param> /// /// <returns>Returns a DescribeInstanceHealthResult from AmazonElasticLoadBalancing.</returns> public DescribeInstanceHealthResponse EndDescribeInstanceHealth(IAsyncResult asyncResult) { return endOperation<DescribeInstanceHealthResponse>(asyncResult); } IAsyncResult invokeDescribeInstanceHealth(DescribeInstanceHealthRequest describeInstanceHealthRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new DescribeInstanceHealthRequestMarshaller().Marshall(describeInstanceHealthRequest); var unmarshaller = DescribeInstanceHealthResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region DeleteLoadBalancerPolicy /// <summary> /// <para> Deletes a policy from the LoadBalancer. The specified policy must not be enabled for any listeners. </para> /// </summary> /// /// <param name="deleteLoadBalancerPolicyRequest">Container for the necessary parameters to execute the DeleteLoadBalancerPolicy service method /// on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the DeleteLoadBalancerPolicy service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="InvalidConfigurationRequestException"/> /// <exception cref="LoadBalancerNotFoundException"/> public DeleteLoadBalancerPolicyResponse DeleteLoadBalancerPolicy(DeleteLoadBalancerPolicyRequest deleteLoadBalancerPolicyRequest) { IAsyncResult asyncResult = invokeDeleteLoadBalancerPolicy(deleteLoadBalancerPolicyRequest, null, null, true); return EndDeleteLoadBalancerPolicy(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the DeleteLoadBalancerPolicy operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancerPolicy"/> /// </summary> /// /// <param name="deleteLoadBalancerPolicyRequest">Container for the necessary parameters to execute the DeleteLoadBalancerPolicy operation on /// AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDeleteLoadBalancerPolicy operation.</returns> public IAsyncResult BeginDeleteLoadBalancerPolicy(DeleteLoadBalancerPolicyRequest deleteLoadBalancerPolicyRequest, AsyncCallback callback, object state) { return invokeDeleteLoadBalancerPolicy(deleteLoadBalancerPolicyRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the DeleteLoadBalancerPolicy operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancerPolicy"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteLoadBalancerPolicy.</param> /// /// <returns>Returns a DeleteLoadBalancerPolicyResult from AmazonElasticLoadBalancing.</returns> public DeleteLoadBalancerPolicyResponse EndDeleteLoadBalancerPolicy(IAsyncResult asyncResult) { return endOperation<DeleteLoadBalancerPolicyResponse>(asyncResult); } IAsyncResult invokeDeleteLoadBalancerPolicy(DeleteLoadBalancerPolicyRequest deleteLoadBalancerPolicyRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new DeleteLoadBalancerPolicyRequestMarshaller().Marshall(deleteLoadBalancerPolicyRequest); var unmarshaller = DeleteLoadBalancerPolicyResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region CreateLoadBalancerPolicy /// <summary> /// <para> Creates a new policy that contains the necessary attributes depending on the policy type. Policies are settings that are saved for /// your Elastic LoadBalancer and that can be applied to the front-end listener, or the back-end application server, depending on your policy /// type. </para> /// </summary> /// /// <param name="createLoadBalancerPolicyRequest">Container for the necessary parameters to execute the CreateLoadBalancerPolicy service method /// on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the CreateLoadBalancerPolicy service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="PolicyTypeNotFoundException"/> /// <exception cref="InvalidConfigurationRequestException"/> /// <exception cref="DuplicatePolicyNameException"/> /// <exception cref="TooManyPoliciesException"/> /// <exception cref="LoadBalancerNotFoundException"/> public CreateLoadBalancerPolicyResponse CreateLoadBalancerPolicy(CreateLoadBalancerPolicyRequest createLoadBalancerPolicyRequest) { IAsyncResult asyncResult = invokeCreateLoadBalancerPolicy(createLoadBalancerPolicyRequest, null, null, true); return EndCreateLoadBalancerPolicy(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the CreateLoadBalancerPolicy operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancerPolicy"/> /// </summary> /// /// <param name="createLoadBalancerPolicyRequest">Container for the necessary parameters to execute the CreateLoadBalancerPolicy operation on /// AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndCreateLoadBalancerPolicy operation.</returns> public IAsyncResult BeginCreateLoadBalancerPolicy(CreateLoadBalancerPolicyRequest createLoadBalancerPolicyRequest, AsyncCallback callback, object state) { return invokeCreateLoadBalancerPolicy(createLoadBalancerPolicyRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the CreateLoadBalancerPolicy operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancerPolicy"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateLoadBalancerPolicy.</param> /// /// <returns>Returns a CreateLoadBalancerPolicyResult from AmazonElasticLoadBalancing.</returns> public CreateLoadBalancerPolicyResponse EndCreateLoadBalancerPolicy(IAsyncResult asyncResult) { return endOperation<CreateLoadBalancerPolicyResponse>(asyncResult); } IAsyncResult invokeCreateLoadBalancerPolicy(CreateLoadBalancerPolicyRequest createLoadBalancerPolicyRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new CreateLoadBalancerPolicyRequestMarshaller().Marshall(createLoadBalancerPolicyRequest); var unmarshaller = CreateLoadBalancerPolicyResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region EnableAvailabilityZonesForLoadBalancer /// <summary> /// <para> Adds one or more EC2 Availability Zones to the LoadBalancer. </para> <para> The LoadBalancer evenly distributes requests across all /// its registered Availability Zones that contain instances. As a result, the client must ensure that its LoadBalancer is appropriately scaled /// for each registered Availability Zone. </para> <para><b>NOTE:</b> The new EC2 Availability Zones to be added must be in the same EC2 Region /// as the Availability Zones for which the LoadBalancer was created. </para> /// </summary> /// /// <param name="enableAvailabilityZonesForLoadBalancerRequest">Container for the necessary parameters to execute the /// EnableAvailabilityZonesForLoadBalancer service method on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the EnableAvailabilityZonesForLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="LoadBalancerNotFoundException"/> public EnableAvailabilityZonesForLoadBalancerResponse EnableAvailabilityZonesForLoadBalancer(EnableAvailabilityZonesForLoadBalancerRequest enableAvailabilityZonesForLoadBalancerRequest) { IAsyncResult asyncResult = invokeEnableAvailabilityZonesForLoadBalancer(enableAvailabilityZonesForLoadBalancerRequest, null, null, true); return EndEnableAvailabilityZonesForLoadBalancer(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the EnableAvailabilityZonesForLoadBalancer operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.EnableAvailabilityZonesForLoadBalancer"/> /// </summary> /// /// <param name="enableAvailabilityZonesForLoadBalancerRequest">Container for the necessary parameters to execute the /// EnableAvailabilityZonesForLoadBalancer operation on AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndEnableAvailabilityZonesForLoadBalancer operation.</returns> public IAsyncResult BeginEnableAvailabilityZonesForLoadBalancer(EnableAvailabilityZonesForLoadBalancerRequest enableAvailabilityZonesForLoadBalancerRequest, AsyncCallback callback, object state) { return invokeEnableAvailabilityZonesForLoadBalancer(enableAvailabilityZonesForLoadBalancerRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the EnableAvailabilityZonesForLoadBalancer operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.EnableAvailabilityZonesForLoadBalancer"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginEnableAvailabilityZonesForLoadBalancer.</param> /// /// <returns>Returns a EnableAvailabilityZonesForLoadBalancerResult from AmazonElasticLoadBalancing.</returns> public EnableAvailabilityZonesForLoadBalancerResponse EndEnableAvailabilityZonesForLoadBalancer(IAsyncResult asyncResult) { return endOperation<EnableAvailabilityZonesForLoadBalancerResponse>(asyncResult); } IAsyncResult invokeEnableAvailabilityZonesForLoadBalancer(EnableAvailabilityZonesForLoadBalancerRequest enableAvailabilityZonesForLoadBalancerRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new EnableAvailabilityZonesForLoadBalancerRequestMarshaller().Marshall(enableAvailabilityZonesForLoadBalancerRequest); var unmarshaller = EnableAvailabilityZonesForLoadBalancerResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region CreateLoadBalancerListeners /// <summary> /// <para> Creates one or more listeners on a LoadBalancer for the specified port. If a listener with the given port does not already exist, it /// will be created; otherwise, the properties of the new listener must match the properties of the existing listener. </para> /// </summary> /// /// <param name="createLoadBalancerListenersRequest">Container for the necessary parameters to execute the CreateLoadBalancerListeners service /// method on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the CreateLoadBalancerListeners service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="InvalidConfigurationRequestException"/> /// <exception cref="DuplicateListenerException"/> /// <exception cref="CertificateNotFoundException"/> /// <exception cref="LoadBalancerNotFoundException"/> public CreateLoadBalancerListenersResponse CreateLoadBalancerListeners(CreateLoadBalancerListenersRequest createLoadBalancerListenersRequest) { IAsyncResult asyncResult = invokeCreateLoadBalancerListeners(createLoadBalancerListenersRequest, null, null, true); return EndCreateLoadBalancerListeners(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the CreateLoadBalancerListeners operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancerListeners"/> /// </summary> /// /// <param name="createLoadBalancerListenersRequest">Container for the necessary parameters to execute the CreateLoadBalancerListeners operation /// on AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndCreateLoadBalancerListeners operation.</returns> public IAsyncResult BeginCreateLoadBalancerListeners(CreateLoadBalancerListenersRequest createLoadBalancerListenersRequest, AsyncCallback callback, object state) { return invokeCreateLoadBalancerListeners(createLoadBalancerListenersRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the CreateLoadBalancerListeners operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancerListeners"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateLoadBalancerListeners.</param> /// /// <returns>Returns a CreateLoadBalancerListenersResult from AmazonElasticLoadBalancing.</returns> public CreateLoadBalancerListenersResponse EndCreateLoadBalancerListeners(IAsyncResult asyncResult) { return endOperation<CreateLoadBalancerListenersResponse>(asyncResult); } IAsyncResult invokeCreateLoadBalancerListeners(CreateLoadBalancerListenersRequest createLoadBalancerListenersRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new CreateLoadBalancerListenersRequestMarshaller().Marshall(createLoadBalancerListenersRequest); var unmarshaller = CreateLoadBalancerListenersResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region CreateLoadBalancer /// <summary> /// <para> Creates a new LoadBalancer. </para> <para> After the call has completed successfully, a new LoadBalancer is created; however, it will /// not be usable until at least one instance has been registered. When the LoadBalancer creation is completed, the client can check whether or /// not it is usable by using the DescribeInstanceHealth action. The LoadBalancer is usable as soon as any registered instance is /// <i>InService</i> . /// </para> <para><b>NOTE:</b> Currently, the client's quota of LoadBalancers is limited to ten per Region. </para> <para><b>NOTE:</b> /// LoadBalancer DNS names vary depending on the Region they're created in. For LoadBalancers created in the United States, the DNS name ends /// with: us-east-1.elb.amazonaws.com (for the US Standard Region) us-west-1.elb.amazonaws.com (for the Northern California Region) For /// LoadBalancers created in the EU (Ireland) Region, the DNS name ends with: eu-west-1.elb.amazonaws.com </para> <para>For information on using /// CreateLoadBalancer to create a new LoadBalancer in Amazon EC2, go to Using Query API section in the <i>Creating a Load Balancer With SSL /// Cipher Settings and Back-end Authentication</i> topic of the <i>Elastic Load Balancing Developer Guide</i> .</para> <para>For information on /// using CreateLoadBalancer to create a new LoadBalancer in Amazon VPC, go to Using Query API section in the <i>Creating a Basic Load Balancer /// in Amazon VPC</i> topic of the <i>Elastic Load Balancing Developer Guide</i> .</para> /// </summary> /// /// <param name="createLoadBalancerRequest">Container for the necessary parameters to execute the CreateLoadBalancer service method on /// AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the CreateLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="InvalidSubnetException"/> /// <exception cref="InvalidConfigurationRequestException"/> /// <exception cref="InvalidSecurityGroupException"/> /// <exception cref="CertificateNotFoundException"/> /// <exception cref="InvalidSchemeException"/> /// <exception cref="DuplicateLoadBalancerNameException"/> /// <exception cref="TooManyLoadBalancersException"/> /// <exception cref="SubnetNotFoundException"/> public CreateLoadBalancerResponse CreateLoadBalancer(CreateLoadBalancerRequest createLoadBalancerRequest) { IAsyncResult asyncResult = invokeCreateLoadBalancer(createLoadBalancerRequest, null, null, true); return EndCreateLoadBalancer(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the CreateLoadBalancer operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancer"/> /// </summary> /// /// <param name="createLoadBalancerRequest">Container for the necessary parameters to execute the CreateLoadBalancer operation on /// AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndCreateLoadBalancer operation.</returns> public IAsyncResult BeginCreateLoadBalancer(CreateLoadBalancerRequest createLoadBalancerRequest, AsyncCallback callback, object state) { return invokeCreateLoadBalancer(createLoadBalancerRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the CreateLoadBalancer operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLoadBalancer"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateLoadBalancer.</param> /// /// <returns>Returns a CreateLoadBalancerResult from AmazonElasticLoadBalancing.</returns> public CreateLoadBalancerResponse EndCreateLoadBalancer(IAsyncResult asyncResult) { return endOperation<CreateLoadBalancerResponse>(asyncResult); } IAsyncResult invokeCreateLoadBalancer(CreateLoadBalancerRequest createLoadBalancerRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new CreateLoadBalancerRequestMarshaller().Marshall(createLoadBalancerRequest); var unmarshaller = CreateLoadBalancerResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region DeleteLoadBalancer /// <summary> /// <para> Deletes the specified LoadBalancer. </para> <para> If attempting to recreate the LoadBalancer, the client must reconfigure all the /// settings. The DNS name associated with a deleted LoadBalancer will no longer be usable. Once deleted, the name and associated DNS record of /// the LoadBalancer no longer exist and traffic sent to any of its IP addresses will no longer be delivered to client instances. The client /// will not receive the same DNS name even if a new LoadBalancer with same LoadBalancerName is created. </para> <para> To successfully call /// this API, the client must provide the same account credentials as were used to create the LoadBalancer. </para> <para><b>NOTE:</b> By /// design, if the LoadBalancer does not exist or has already been deleted, DeleteLoadBalancer still succeeds. </para> /// </summary> /// /// <param name="deleteLoadBalancerRequest">Container for the necessary parameters to execute the DeleteLoadBalancer service method on /// AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the DeleteLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns> /// public DeleteLoadBalancerResponse DeleteLoadBalancer(DeleteLoadBalancerRequest deleteLoadBalancerRequest) { IAsyncResult asyncResult = invokeDeleteLoadBalancer(deleteLoadBalancerRequest, null, null, true); return EndDeleteLoadBalancer(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the DeleteLoadBalancer operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancer"/> /// </summary> /// /// <param name="deleteLoadBalancerRequest">Container for the necessary parameters to execute the DeleteLoadBalancer operation on /// AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDeleteLoadBalancer operation.</returns> public IAsyncResult BeginDeleteLoadBalancer(DeleteLoadBalancerRequest deleteLoadBalancerRequest, AsyncCallback callback, object state) { return invokeDeleteLoadBalancer(deleteLoadBalancerRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the DeleteLoadBalancer operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancer"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteLoadBalancer.</param> /// /// <returns>Returns a DeleteLoadBalancerResult from AmazonElasticLoadBalancing.</returns> public DeleteLoadBalancerResponse EndDeleteLoadBalancer(IAsyncResult asyncResult) { return endOperation<DeleteLoadBalancerResponse>(asyncResult); } IAsyncResult invokeDeleteLoadBalancer(DeleteLoadBalancerRequest deleteLoadBalancerRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new DeleteLoadBalancerRequestMarshaller().Marshall(deleteLoadBalancerRequest); var unmarshaller = DeleteLoadBalancerResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region SetLoadBalancerPoliciesForBackendServer /// <summary> /// <para> Replaces the current set of policies associated with a port on which the back-end server is listening with a new set of policies. /// After the policies have been created using CreateLoadBalancerPolicy, they can be applied here as a list. At this time, only the back-end /// server authentication policy type can be applied to the back-end ports; this policy type is composed of multiple public key policies. /// </para> /// </summary> /// /// <param name="setLoadBalancerPoliciesForBackendServerRequest">Container for the necessary parameters to execute the /// SetLoadBalancerPoliciesForBackendServer service method on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the SetLoadBalancerPoliciesForBackendServer service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="PolicyNotFoundException"/> /// <exception cref="InvalidConfigurationRequestException"/> /// <exception cref="LoadBalancerNotFoundException"/> public SetLoadBalancerPoliciesForBackendServerResponse SetLoadBalancerPoliciesForBackendServer(SetLoadBalancerPoliciesForBackendServerRequest setLoadBalancerPoliciesForBackendServerRequest) { IAsyncResult asyncResult = invokeSetLoadBalancerPoliciesForBackendServer(setLoadBalancerPoliciesForBackendServerRequest, null, null, true); return EndSetLoadBalancerPoliciesForBackendServer(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the SetLoadBalancerPoliciesForBackendServer operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerPoliciesForBackendServer"/> /// </summary> /// /// <param name="setLoadBalancerPoliciesForBackendServerRequest">Container for the necessary parameters to execute the /// SetLoadBalancerPoliciesForBackendServer operation on AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndSetLoadBalancerPoliciesForBackendServer operation.</returns> public IAsyncResult BeginSetLoadBalancerPoliciesForBackendServer(SetLoadBalancerPoliciesForBackendServerRequest setLoadBalancerPoliciesForBackendServerRequest, AsyncCallback callback, object state) { return invokeSetLoadBalancerPoliciesForBackendServer(setLoadBalancerPoliciesForBackendServerRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the SetLoadBalancerPoliciesForBackendServer operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerPoliciesForBackendServer"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetLoadBalancerPoliciesForBackendServer.</param> /// /// <returns>Returns a SetLoadBalancerPoliciesForBackendServerResult from AmazonElasticLoadBalancing.</returns> public SetLoadBalancerPoliciesForBackendServerResponse EndSetLoadBalancerPoliciesForBackendServer(IAsyncResult asyncResult) { return endOperation<SetLoadBalancerPoliciesForBackendServerResponse>(asyncResult); } IAsyncResult invokeSetLoadBalancerPoliciesForBackendServer(SetLoadBalancerPoliciesForBackendServerRequest setLoadBalancerPoliciesForBackendServerRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new SetLoadBalancerPoliciesForBackendServerRequestMarshaller().Marshall(setLoadBalancerPoliciesForBackendServerRequest); var unmarshaller = SetLoadBalancerPoliciesForBackendServerResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region DeleteLoadBalancerListeners /// <summary> /// <para> Deletes listeners from the LoadBalancer for the specified port. </para> /// </summary> /// /// <param name="deleteLoadBalancerListenersRequest">Container for the necessary parameters to execute the DeleteLoadBalancerListeners service /// method on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the DeleteLoadBalancerListeners service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="LoadBalancerNotFoundException"/> public DeleteLoadBalancerListenersResponse DeleteLoadBalancerListeners(DeleteLoadBalancerListenersRequest deleteLoadBalancerListenersRequest) { IAsyncResult asyncResult = invokeDeleteLoadBalancerListeners(deleteLoadBalancerListenersRequest, null, null, true); return EndDeleteLoadBalancerListeners(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the DeleteLoadBalancerListeners operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancerListeners"/> /// </summary> /// /// <param name="deleteLoadBalancerListenersRequest">Container for the necessary parameters to execute the DeleteLoadBalancerListeners operation /// on AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDeleteLoadBalancerListeners operation.</returns> public IAsyncResult BeginDeleteLoadBalancerListeners(DeleteLoadBalancerListenersRequest deleteLoadBalancerListenersRequest, AsyncCallback callback, object state) { return invokeDeleteLoadBalancerListeners(deleteLoadBalancerListenersRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the DeleteLoadBalancerListeners operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeleteLoadBalancerListeners"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteLoadBalancerListeners.</param> /// /// <returns>Returns a DeleteLoadBalancerListenersResult from AmazonElasticLoadBalancing.</returns> public DeleteLoadBalancerListenersResponse EndDeleteLoadBalancerListeners(IAsyncResult asyncResult) { return endOperation<DeleteLoadBalancerListenersResponse>(asyncResult); } IAsyncResult invokeDeleteLoadBalancerListeners(DeleteLoadBalancerListenersRequest deleteLoadBalancerListenersRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new DeleteLoadBalancerListenersRequestMarshaller().Marshall(deleteLoadBalancerListenersRequest); var unmarshaller = DeleteLoadBalancerListenersResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region DeregisterInstancesFromLoadBalancer /// <summary> /// <para> Deregisters instances from the LoadBalancer. Once the instance is deregistered, it will stop receiving traffic from the LoadBalancer. /// </para> <para> In order to successfully call this API, the same account credentials as those used to create the LoadBalancer must be /// provided. </para> /// </summary> /// /// <param name="deregisterInstancesFromLoadBalancerRequest">Container for the necessary parameters to execute the /// DeregisterInstancesFromLoadBalancer service method on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the DeregisterInstancesFromLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="LoadBalancerNotFoundException"/> /// <exception cref="InvalidInstanceException"/> public DeregisterInstancesFromLoadBalancerResponse DeregisterInstancesFromLoadBalancer(DeregisterInstancesFromLoadBalancerRequest deregisterInstancesFromLoadBalancerRequest) { IAsyncResult asyncResult = invokeDeregisterInstancesFromLoadBalancer(deregisterInstancesFromLoadBalancerRequest, null, null, true); return EndDeregisterInstancesFromLoadBalancer(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the DeregisterInstancesFromLoadBalancer operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeregisterInstancesFromLoadBalancer"/> /// </summary> /// /// <param name="deregisterInstancesFromLoadBalancerRequest">Container for the necessary parameters to execute the /// DeregisterInstancesFromLoadBalancer operation on AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDeregisterInstancesFromLoadBalancer operation.</returns> public IAsyncResult BeginDeregisterInstancesFromLoadBalancer(DeregisterInstancesFromLoadBalancerRequest deregisterInstancesFromLoadBalancerRequest, AsyncCallback callback, object state) { return invokeDeregisterInstancesFromLoadBalancer(deregisterInstancesFromLoadBalancerRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the DeregisterInstancesFromLoadBalancer operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeregisterInstancesFromLoadBalancer"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeregisterInstancesFromLoadBalancer.</param> /// /// <returns>Returns a DeregisterInstancesFromLoadBalancerResult from AmazonElasticLoadBalancing.</returns> public DeregisterInstancesFromLoadBalancerResponse EndDeregisterInstancesFromLoadBalancer(IAsyncResult asyncResult) { return endOperation<DeregisterInstancesFromLoadBalancerResponse>(asyncResult); } IAsyncResult invokeDeregisterInstancesFromLoadBalancer(DeregisterInstancesFromLoadBalancerRequest deregisterInstancesFromLoadBalancerRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new DeregisterInstancesFromLoadBalancerRequestMarshaller().Marshall(deregisterInstancesFromLoadBalancerRequest); var unmarshaller = DeregisterInstancesFromLoadBalancerResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region SetLoadBalancerListenerSSLCertificate /// <summary> /// <para> Sets the certificate that terminates the specified listener's SSL connections. The specified certificate replaces any prior /// certificate that was used on the same LoadBalancer and port. </para> <para>For information on using SetLoadBalancerListenerSSLCertificate, /// go to Using the Query API in <i>Updating an SSL Certificate for a Load Balancer</i> section of the <i>Elastic Load Balancing Developer /// Guide</i> .</para> /// </summary> /// /// <param name="setLoadBalancerListenerSSLCertificateRequest">Container for the necessary parameters to execute the /// SetLoadBalancerListenerSSLCertificate service method on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the SetLoadBalancerListenerSSLCertificate service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="InvalidConfigurationRequestException"/> /// <exception cref="CertificateNotFoundException"/> /// <exception cref="LoadBalancerNotFoundException"/> /// <exception cref="ListenerNotFoundException"/> public SetLoadBalancerListenerSSLCertificateResponse SetLoadBalancerListenerSSLCertificate(SetLoadBalancerListenerSSLCertificateRequest setLoadBalancerListenerSSLCertificateRequest) { IAsyncResult asyncResult = invokeSetLoadBalancerListenerSSLCertificate(setLoadBalancerListenerSSLCertificateRequest, null, null, true); return EndSetLoadBalancerListenerSSLCertificate(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the SetLoadBalancerListenerSSLCertificate operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerListenerSSLCertificate"/> /// </summary> /// /// <param name="setLoadBalancerListenerSSLCertificateRequest">Container for the necessary parameters to execute the /// SetLoadBalancerListenerSSLCertificate operation on AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndSetLoadBalancerListenerSSLCertificate operation.</returns> public IAsyncResult BeginSetLoadBalancerListenerSSLCertificate(SetLoadBalancerListenerSSLCertificateRequest setLoadBalancerListenerSSLCertificateRequest, AsyncCallback callback, object state) { return invokeSetLoadBalancerListenerSSLCertificate(setLoadBalancerListenerSSLCertificateRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the SetLoadBalancerListenerSSLCertificate operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.SetLoadBalancerListenerSSLCertificate"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetLoadBalancerListenerSSLCertificate.</param> /// /// <returns>Returns a SetLoadBalancerListenerSSLCertificateResult from AmazonElasticLoadBalancing.</returns> public SetLoadBalancerListenerSSLCertificateResponse EndSetLoadBalancerListenerSSLCertificate(IAsyncResult asyncResult) { return endOperation<SetLoadBalancerListenerSSLCertificateResponse>(asyncResult); } IAsyncResult invokeSetLoadBalancerListenerSSLCertificate(SetLoadBalancerListenerSSLCertificateRequest setLoadBalancerListenerSSLCertificateRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new SetLoadBalancerListenerSSLCertificateRequestMarshaller().Marshall(setLoadBalancerListenerSSLCertificateRequest); var unmarshaller = SetLoadBalancerListenerSSLCertificateResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region CreateLBCookieStickinessPolicy /// <summary> /// <para> Generates a stickiness policy with sticky session lifetimes controlled by the lifetime of the browser (user-agent) or a specified /// expiration period. This policy can be associated only with HTTP/HTTPS listeners. </para> <para> When a LoadBalancer implements this policy, /// the LoadBalancer uses a special cookie to track the backend server instance for each request. When the LoadBalancer receives a request, it /// first checks to see if this cookie is present in the request. If so, the LoadBalancer sends the request to the application server specified /// in the cookie. If not, the LoadBalancer sends the request to a server that is chosen based on the existing load balancing algorithm. </para> /// <para> A cookie is inserted into the response for binding subsequent requests from the same user to that server. The validity of the cookie /// is based on the cookie expiration time, which is specified in the policy configuration. </para> /// </summary> /// /// <param name="createLBCookieStickinessPolicyRequest">Container for the necessary parameters to execute the CreateLBCookieStickinessPolicy /// service method on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the CreateLBCookieStickinessPolicy service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="InvalidConfigurationRequestException"/> /// <exception cref="DuplicatePolicyNameException"/> /// <exception cref="TooManyPoliciesException"/> /// <exception cref="LoadBalancerNotFoundException"/> public CreateLBCookieStickinessPolicyResponse CreateLBCookieStickinessPolicy(CreateLBCookieStickinessPolicyRequest createLBCookieStickinessPolicyRequest) { IAsyncResult asyncResult = invokeCreateLBCookieStickinessPolicy(createLBCookieStickinessPolicyRequest, null, null, true); return EndCreateLBCookieStickinessPolicy(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the CreateLBCookieStickinessPolicy operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLBCookieStickinessPolicy"/> /// </summary> /// /// <param name="createLBCookieStickinessPolicyRequest">Container for the necessary parameters to execute the CreateLBCookieStickinessPolicy /// operation on AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndCreateLBCookieStickinessPolicy operation.</returns> public IAsyncResult BeginCreateLBCookieStickinessPolicy(CreateLBCookieStickinessPolicyRequest createLBCookieStickinessPolicyRequest, AsyncCallback callback, object state) { return invokeCreateLBCookieStickinessPolicy(createLBCookieStickinessPolicyRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the CreateLBCookieStickinessPolicy operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateLBCookieStickinessPolicy"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateLBCookieStickinessPolicy.</param> /// /// <returns>Returns a CreateLBCookieStickinessPolicyResult from AmazonElasticLoadBalancing.</returns> public CreateLBCookieStickinessPolicyResponse EndCreateLBCookieStickinessPolicy(IAsyncResult asyncResult) { return endOperation<CreateLBCookieStickinessPolicyResponse>(asyncResult); } IAsyncResult invokeCreateLBCookieStickinessPolicy(CreateLBCookieStickinessPolicyRequest createLBCookieStickinessPolicyRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new CreateLBCookieStickinessPolicyRequestMarshaller().Marshall(createLBCookieStickinessPolicyRequest); var unmarshaller = CreateLBCookieStickinessPolicyResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region AttachLoadBalancerToSubnets /// <summary> /// <para> Adds one or more subnets to the set of configured subnets in the VPC for the LoadBalancer. </para> <para> The Loadbalancers evenly /// distribute requests across all of the registered subnets. </para> /// </summary> /// /// <param name="attachLoadBalancerToSubnetsRequest">Container for the necessary parameters to execute the AttachLoadBalancerToSubnets service /// method on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the AttachLoadBalancerToSubnets service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="InvalidSubnetException"/> /// <exception cref="InvalidConfigurationRequestException"/> /// <exception cref="LoadBalancerNotFoundException"/> /// <exception cref="SubnetNotFoundException"/> public AttachLoadBalancerToSubnetsResponse AttachLoadBalancerToSubnets(AttachLoadBalancerToSubnetsRequest attachLoadBalancerToSubnetsRequest) { IAsyncResult asyncResult = invokeAttachLoadBalancerToSubnets(attachLoadBalancerToSubnetsRequest, null, null, true); return EndAttachLoadBalancerToSubnets(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the AttachLoadBalancerToSubnets operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.AttachLoadBalancerToSubnets"/> /// </summary> /// /// <param name="attachLoadBalancerToSubnetsRequest">Container for the necessary parameters to execute the AttachLoadBalancerToSubnets operation /// on AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndAttachLoadBalancerToSubnets operation.</returns> public IAsyncResult BeginAttachLoadBalancerToSubnets(AttachLoadBalancerToSubnetsRequest attachLoadBalancerToSubnetsRequest, AsyncCallback callback, object state) { return invokeAttachLoadBalancerToSubnets(attachLoadBalancerToSubnetsRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the AttachLoadBalancerToSubnets operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.AttachLoadBalancerToSubnets"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginAttachLoadBalancerToSubnets.</param> /// /// <returns>Returns a AttachLoadBalancerToSubnetsResult from AmazonElasticLoadBalancing.</returns> public AttachLoadBalancerToSubnetsResponse EndAttachLoadBalancerToSubnets(IAsyncResult asyncResult) { return endOperation<AttachLoadBalancerToSubnetsResponse>(asyncResult); } IAsyncResult invokeAttachLoadBalancerToSubnets(AttachLoadBalancerToSubnetsRequest attachLoadBalancerToSubnetsRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new AttachLoadBalancerToSubnetsRequestMarshaller().Marshall(attachLoadBalancerToSubnetsRequest); var unmarshaller = AttachLoadBalancerToSubnetsResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region CreateAppCookieStickinessPolicy /// <summary> /// <para> Generates a stickiness policy with sticky session lifetimes that follow that of an application-generated cookie. This policy can be /// associated only with HTTP/HTTPS listeners. </para> <para> This policy is similar to the policy created by CreateLBCookieStickinessPolicy, /// except that the lifetime of the special Elastic Load Balancing cookie follows the lifetime of the application-generated cookie specified in /// the policy configuration. The LoadBalancer only inserts a new stickiness cookie when the application response includes a new application /// cookie. </para> <para> If the application cookie is explicitly removed or expires, the session stops being sticky until a new application /// cookie is issued. </para> <para><b>NOTE:</b> An application client must receive and send two cookies: the application-generated cookie and /// the special Elastic Load Balancing cookie named AWSELB. This is the default behavior for many common web browsers. </para> /// </summary> /// /// <param name="createAppCookieStickinessPolicyRequest">Container for the necessary parameters to execute the CreateAppCookieStickinessPolicy /// service method on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the CreateAppCookieStickinessPolicy service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="InvalidConfigurationRequestException"/> /// <exception cref="DuplicatePolicyNameException"/> /// <exception cref="TooManyPoliciesException"/> /// <exception cref="LoadBalancerNotFoundException"/> public CreateAppCookieStickinessPolicyResponse CreateAppCookieStickinessPolicy(CreateAppCookieStickinessPolicyRequest createAppCookieStickinessPolicyRequest) { IAsyncResult asyncResult = invokeCreateAppCookieStickinessPolicy(createAppCookieStickinessPolicyRequest, null, null, true); return EndCreateAppCookieStickinessPolicy(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the CreateAppCookieStickinessPolicy operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateAppCookieStickinessPolicy"/> /// </summary> /// /// <param name="createAppCookieStickinessPolicyRequest">Container for the necessary parameters to execute the CreateAppCookieStickinessPolicy /// operation on AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndCreateAppCookieStickinessPolicy operation.</returns> public IAsyncResult BeginCreateAppCookieStickinessPolicy(CreateAppCookieStickinessPolicyRequest createAppCookieStickinessPolicyRequest, AsyncCallback callback, object state) { return invokeCreateAppCookieStickinessPolicy(createAppCookieStickinessPolicyRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the CreateAppCookieStickinessPolicy operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.CreateAppCookieStickinessPolicy"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateAppCookieStickinessPolicy.</param> /// /// <returns>Returns a CreateAppCookieStickinessPolicyResult from AmazonElasticLoadBalancing.</returns> public CreateAppCookieStickinessPolicyResponse EndCreateAppCookieStickinessPolicy(IAsyncResult asyncResult) { return endOperation<CreateAppCookieStickinessPolicyResponse>(asyncResult); } IAsyncResult invokeCreateAppCookieStickinessPolicy(CreateAppCookieStickinessPolicyRequest createAppCookieStickinessPolicyRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new CreateAppCookieStickinessPolicyRequestMarshaller().Marshall(createAppCookieStickinessPolicyRequest); var unmarshaller = CreateAppCookieStickinessPolicyResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region RegisterInstancesWithLoadBalancer /// <summary> /// <para> Adds new instances to the LoadBalancer. </para> <para> Once the instance is registered, it starts receiving traffic and requests from /// the LoadBalancer. Any instance that is not in any of the Availability Zones registered for the LoadBalancer will be moved to the /// <i>OutOfService</i> state. It will move to the <i>InService</i> state when the Availability Zone is added to the LoadBalancer. </para> /// <para><b>NOTE:</b> In order for this call to be successful, the client must have created the LoadBalancer. The client must provide the same /// account credentials as those that were used to create the LoadBalancer. </para> <para><b>NOTE:</b> Completion of this API does not guarantee /// that operation has completed. Rather, it means that the request has been registered and the changes will happen shortly. </para> /// </summary> /// /// <param name="registerInstancesWithLoadBalancerRequest">Container for the necessary parameters to execute the /// RegisterInstancesWithLoadBalancer service method on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the RegisterInstancesWithLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="LoadBalancerNotFoundException"/> /// <exception cref="InvalidInstanceException"/> public RegisterInstancesWithLoadBalancerResponse RegisterInstancesWithLoadBalancer(RegisterInstancesWithLoadBalancerRequest registerInstancesWithLoadBalancerRequest) { IAsyncResult asyncResult = invokeRegisterInstancesWithLoadBalancer(registerInstancesWithLoadBalancerRequest, null, null, true); return EndRegisterInstancesWithLoadBalancer(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the RegisterInstancesWithLoadBalancer operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.RegisterInstancesWithLoadBalancer"/> /// </summary> /// /// <param name="registerInstancesWithLoadBalancerRequest">Container for the necessary parameters to execute the /// RegisterInstancesWithLoadBalancer operation on AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndRegisterInstancesWithLoadBalancer operation.</returns> public IAsyncResult BeginRegisterInstancesWithLoadBalancer(RegisterInstancesWithLoadBalancerRequest registerInstancesWithLoadBalancerRequest, AsyncCallback callback, object state) { return invokeRegisterInstancesWithLoadBalancer(registerInstancesWithLoadBalancerRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the RegisterInstancesWithLoadBalancer operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.RegisterInstancesWithLoadBalancer"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginRegisterInstancesWithLoadBalancer.</param> /// /// <returns>Returns a RegisterInstancesWithLoadBalancerResult from AmazonElasticLoadBalancing.</returns> public RegisterInstancesWithLoadBalancerResponse EndRegisterInstancesWithLoadBalancer(IAsyncResult asyncResult) { return endOperation<RegisterInstancesWithLoadBalancerResponse>(asyncResult); } IAsyncResult invokeRegisterInstancesWithLoadBalancer(RegisterInstancesWithLoadBalancerRequest registerInstancesWithLoadBalancerRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new RegisterInstancesWithLoadBalancerRequestMarshaller().Marshall(registerInstancesWithLoadBalancerRequest); var unmarshaller = RegisterInstancesWithLoadBalancerResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region ApplySecurityGroupsToLoadBalancer /// <summary> /// <para> Associates one or more security groups with your LoadBalancer in VPC. The provided security group IDs will override any currently /// applied security groups. </para> /// </summary> /// /// <param name="applySecurityGroupsToLoadBalancerRequest">Container for the necessary parameters to execute the /// ApplySecurityGroupsToLoadBalancer service method on AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the ApplySecurityGroupsToLoadBalancer service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="InvalidConfigurationRequestException"/> /// <exception cref="InvalidSecurityGroupException"/> /// <exception cref="LoadBalancerNotFoundException"/> public ApplySecurityGroupsToLoadBalancerResponse ApplySecurityGroupsToLoadBalancer(ApplySecurityGroupsToLoadBalancerRequest applySecurityGroupsToLoadBalancerRequest) { IAsyncResult asyncResult = invokeApplySecurityGroupsToLoadBalancer(applySecurityGroupsToLoadBalancerRequest, null, null, true); return EndApplySecurityGroupsToLoadBalancer(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the ApplySecurityGroupsToLoadBalancer operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.ApplySecurityGroupsToLoadBalancer"/> /// </summary> /// /// <param name="applySecurityGroupsToLoadBalancerRequest">Container for the necessary parameters to execute the /// ApplySecurityGroupsToLoadBalancer operation on AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndApplySecurityGroupsToLoadBalancer operation.</returns> public IAsyncResult BeginApplySecurityGroupsToLoadBalancer(ApplySecurityGroupsToLoadBalancerRequest applySecurityGroupsToLoadBalancerRequest, AsyncCallback callback, object state) { return invokeApplySecurityGroupsToLoadBalancer(applySecurityGroupsToLoadBalancerRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the ApplySecurityGroupsToLoadBalancer operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.ApplySecurityGroupsToLoadBalancer"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginApplySecurityGroupsToLoadBalancer.</param> /// /// <returns>Returns a ApplySecurityGroupsToLoadBalancerResult from AmazonElasticLoadBalancing.</returns> public ApplySecurityGroupsToLoadBalancerResponse EndApplySecurityGroupsToLoadBalancer(IAsyncResult asyncResult) { return endOperation<ApplySecurityGroupsToLoadBalancerResponse>(asyncResult); } IAsyncResult invokeApplySecurityGroupsToLoadBalancer(ApplySecurityGroupsToLoadBalancerRequest applySecurityGroupsToLoadBalancerRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new ApplySecurityGroupsToLoadBalancerRequestMarshaller().Marshall(applySecurityGroupsToLoadBalancerRequest); var unmarshaller = ApplySecurityGroupsToLoadBalancerResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } #endregion #region DescribeLoadBalancers /// <summary> /// <para> Returns detailed configuration information for the specified LoadBalancers. If no LoadBalancers are specified, the operation returns /// configuration information for all LoadBalancers created by the caller. </para> <para><b>NOTE:</b> The client must have created the specified /// input LoadBalancers in order to retrieve this information; the client must provide the same account credentials as those that were used to /// create the LoadBalancer. </para> /// </summary> /// /// <param name="describeLoadBalancersRequest">Container for the necessary parameters to execute the DescribeLoadBalancers service method on /// AmazonElasticLoadBalancing.</param> /// /// <returns>The response from the DescribeLoadBalancers service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="LoadBalancerNotFoundException"/> public DescribeLoadBalancersResponse DescribeLoadBalancers(DescribeLoadBalancersRequest describeLoadBalancersRequest) { IAsyncResult asyncResult = invokeDescribeLoadBalancers(describeLoadBalancersRequest, null, null, true); return EndDescribeLoadBalancers(asyncResult); } /// <summary> /// Initiates the asynchronous execution of the DescribeLoadBalancers operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancers"/> /// </summary> /// /// <param name="describeLoadBalancersRequest">Container for the necessary parameters to execute the DescribeLoadBalancers operation on /// AmazonElasticLoadBalancing.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDescribeLoadBalancers operation.</returns> public IAsyncResult BeginDescribeLoadBalancers(DescribeLoadBalancersRequest describeLoadBalancersRequest, AsyncCallback callback, object state) { return invokeDescribeLoadBalancers(describeLoadBalancersRequest, callback, state, false); } /// <summary> /// Finishes the asynchronous execution of the DescribeLoadBalancers operation. /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DescribeLoadBalancers"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeLoadBalancers.</param> /// /// <returns>Returns a DescribeLoadBalancersResult from AmazonElasticLoadBalancing.</returns> public DescribeLoadBalancersResponse EndDescribeLoadBalancers(IAsyncResult asyncResult) { return endOperation<DescribeLoadBalancersResponse>(asyncResult); } IAsyncResult invokeDescribeLoadBalancers(DescribeLoadBalancersRequest describeLoadBalancersRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new DescribeLoadBalancersRequestMarshaller().Marshall(describeLoadBalancersRequest); var unmarshaller = DescribeLoadBalancersResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; } /// <summary> /// <para> Returns detailed configuration information for the specified LoadBalancers. If no LoadBalancers are specified, the operation returns /// configuration information for all LoadBalancers created by the caller. </para> <para><b>NOTE:</b> The client must have created the specified /// input LoadBalancers in order to retrieve this information; the client must provide the same account credentials as those that were used to /// create the LoadBalancer. </para> /// </summary> /// /// <returns>The response from the DescribeLoadBalancers service method, as returned by AmazonElasticLoadBalancing.</returns> /// /// <exception cref="LoadBalancerNotFoundException"/> public DescribeLoadBalancersResponse DescribeLoadBalancers() { return DescribeLoadBalancers(new DescribeLoadBalancersRequest()); } #endregion } }
emcvipr/dataservices-sdk-dotnet
AWSSDK/Amazon.ElasticLoadBalancing/AmazonElasticLoadBalancingClient.cs
C#
apache-2.0
111,516
(function(){'use strict'; module.exports = (function () { if (process.argv.indexOf('--no-color') !== -1) { return false; } if (process.argv.indexOf('--color') !== -1) { return true; } if (process.stdout && !process.stdout.isTTY) { return false; } if (process.platform === 'win32') { return true; } if ('COLORTERM' in process.env) { return true; } if (process.env.TERM === 'dumb') { return false; } if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { return true; } return false; })(); })();
durwasa-chakraborty/navigus
.demeteorized/bundle/programs/server/app/lib/node_modules/modulus/node_modules/update-notifier/node_modules/chalk/node_modules/has-color/index.js
JavaScript
apache-2.0
555
package com.nedap.archie.json; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.DatabindContext; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver; import com.fasterxml.jackson.databind.type.TypeFactory; import com.nedap.archie.base.OpenEHRBase; import com.nedap.archie.rminfo.ArchieAOMInfoLookup; import com.nedap.archie.rminfo.ArchieRMInfoLookup; import com.nedap.archie.rminfo.ModelInfoLookup; import com.nedap.archie.rminfo.RMTypeInfo; import java.io.IOException; /** * Class that handles naming of Archie RM and AOM objects for use in Jackson. * * The AOM class CComplexObject will get the type name "C_COMPLEX_OBJECT" * The RM class DvDateTime will get the type name "DV_DATE_TIME" */ public class OpenEHRTypeNaming extends ClassNameIdResolver { private ModelInfoLookup rmInfoLookup = ArchieRMInfoLookup.getInstance(); private ModelInfoLookup aomInfoLookup = ArchieAOMInfoLookup.getInstance(); protected OpenEHRTypeNaming() { super(TypeFactory.defaultInstance().constructType(OpenEHRBase.class), TypeFactory.defaultInstance()); } public JsonTypeInfo.Id getMechanism() { return JsonTypeInfo.Id.NAME; } @Override public String idFromValue(Object value) { RMTypeInfo typeInfo = rmInfoLookup.getTypeInfo(value.getClass()); if(typeInfo == null) { return rmInfoLookup.getNamingStrategy().getTypeName(value.getClass()); } else { //this case is faster and should always work. If for some reason it does not, the above case works fine instead. return typeInfo.getRmName(); } // This should work in all cases for openEHR-classes and this should not be used for other classes // Additional code for making this work on non-ehr-types: // } else { // return super.idFromValue(value); // } } @Deprecated // since 2.3 @Override public JavaType typeFromId(String id) { return _typeFromId(id, null); } @Override public JavaType typeFromId(DatabindContext context, String id) { return _typeFromId(id, context); } @Override protected JavaType _typeFromId(String typeName, DatabindContext ctxt) { Class result = rmInfoLookup.getClass(typeName); if(result == null) { //AOM class? result = aomInfoLookup.getClass(typeName); } if(result != null) { TypeFactory typeFactory = (ctxt == null) ? _typeFactory : ctxt.getTypeFactory(); return typeFactory.constructSpecializedType(_baseType, result); } return super._typeFromId(typeName, ctxt); } }
nedap/archie
src/main/java/com/nedap/archie/json/OpenEHRTypeNaming.java
Java
apache-2.0
2,751
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.opencl; /** * Native bindings to the <a href="http://www.khronos.org/registry/cl/extensions/intel/cl_intel_advanced_motion_estimation.txt">intel_advanced_motion_estimation</a> extension. * * <p>This extension builds upon the cl_intel_motion_estimation extension by providing block-based estimation and greater control over the estimation * algorithm.</p> * * <p>This extension reuses the set of host-callable functions and "motion estimation accelerator objects" defined in the cl_intel_motion_estimation * extension. This extension depends on the OpenCL 1.2 built-in kernel infrastructure and on the cl_intel_accelerator extension, which provides an * abstraction for domain-specific acceleration in the OpenCL runtime.</p> * * <p>Requires {@link INTELMotionEstimation intel_motion_estimation}.</p> */ public final class INTELAdvancedMotionEstimation { /** Accepted as arguments to clGetDeviceInfo. */ public static final int CL_DEVICE_ME_VERSION_INTEL = 0x407E; /** Accepted as flags passed to the kernel. */ public static final int CL_ME_CHROMA_INTRA_PREDICT_ENABLED_INTEL = 0x1, CL_ME_LUMA_INTRA_PREDICT_ENABLED_INTEL = 0x2, CL_ME_COST_PENALTY_NONE_INTEL = 0x0, CL_ME_COST_PENALTY_LOW_INTEL = 0x1, CL_ME_COST_PENALTY_NORMAL_INTEL = 0x2, CL_ME_COST_PENALTY_HIGH_INTEL = 0x3, CL_ME_COST_PRECISION_QPEL_INTEL = 0x0, CL_ME_COST_PRECISION_HEL_INTEL = 0x1, CL_ME_COST_PRECISION_PEL_INTEL = 0x2, CL_ME_COST_PRECISION_DPEL_INTEL = 0x3; /** Valid intra-search predictor mode constants. */ public static final int CL_ME_LUMA_PREDICTOR_MODE_VERTICAL_INTEL = 0x0, CL_ME_LUMA_PREDICTOR_MODE_HORIZONTAL_INTEL = 0x1, CL_ME_LUMA_PREDICTOR_MODE_DC_INTEL = 0x2, CL_ME_LUMA_PREDICTOR_MODE_DIAGONAL_DOWN_LEFT_INTEL = 0x3, CL_ME_LUMA_PREDICTOR_MODE_DIAGONAL_DOWN_RIGHT_INTEL = 0x4, CL_ME_LUMA_PREDICTOR_MODE_PLANE_INTEL = 0x4, CL_ME_LUMA_PREDICTOR_MODE_VERTICAL_RIGHT_INTEL = 0x5, CL_ME_LUMA_PREDICTOR_MODE_HORIZONTAL_DOWN_INTEL = 0x6, CL_ME_LUMA_PREDICTOR_MODE_VERTICAL_LEFT_INTEL = 0x7, CL_ME_LUMA_PREDICTOR_MODE_HORIZONTAL_UP_INTEL = 0x8, CL_ME_CHROMA_PREDICTOR_MODE_DC_INTEL = 0x0, CL_ME_CHROMA_PREDICTOR_MODE_HORIZONTAL_INTEL = 0x1, CL_ME_CHROMA_PREDICTOR_MODE_VERTICAL_INTEL = 0x2, CL_ME_CHROMA_PREDICTOR_MODE_PLANE_INTEL = 0x3; /** Valid constant values returned by clGetDeviceInfo. */ public static final int CL_ME_VERSION_ADVANCED_VER_1_INTEL = 0x1; /** Valid macroblock type constants. */ public static final int CL_ME_MB_TYPE_16x16_INTEL = 0x0, CL_ME_MB_TYPE_8x8_INTEL = 0x1, CL_ME_MB_TYPE_4x4_INTEL = 0x2; private INTELAdvancedMotionEstimation() {} }
VirtualGamer/SnowEngine
Dependencies/opencl/src/org/lwjgl/opencl/INTELAdvancedMotionEstimation.java
Java
apache-2.0
2,988
/* * Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.pricer.impl.rate; import static com.opengamma.strata.basics.index.IborIndices.GBP_LIBOR_3M; import static com.opengamma.strata.basics.index.IborIndices.GBP_LIBOR_6M; import static com.opengamma.strata.collect.TestHelper.date; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.Offset.offset; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.time.LocalDate; import java.util.Optional; import org.junit.jupiter.api.Test; import com.google.common.collect.ImmutableList; import com.opengamma.strata.basics.ReferenceData; import com.opengamma.strata.basics.index.IborIndexObservation; import com.opengamma.strata.collect.timeseries.LocalDateDoubleTimeSeries; import com.opengamma.strata.market.explain.ExplainKey; import com.opengamma.strata.market.explain.ExplainMap; import com.opengamma.strata.market.explain.ExplainMapBuilder; import com.opengamma.strata.market.sensitivity.PointSensitivities; import com.opengamma.strata.market.sensitivity.PointSensitivityBuilder; import com.opengamma.strata.pricer.rate.IborIndexRates; import com.opengamma.strata.pricer.rate.IborRateSensitivity; import com.opengamma.strata.pricer.rate.RatesProvider; import com.opengamma.strata.product.rate.IborInterpolatedRateComputation; /** * Test. */ public class ForwardIborInterpolatedRateComputationFnTest { private static final ReferenceData REF_DATA = ReferenceData.standard(); private static final LocalDate FIXING_DATE = date(2014, 6, 30); private static final LocalDate ACCRUAL_START_DATE = date(2014, 7, 2); private static final LocalDate ACCRUAL_END_DATE = date(2014, 11, 2); private static final double RATE3 = 0.0125d; private static final double RATE3TS = 0.0123d; private static final double RATE6 = 0.0234d; private static final IborIndexObservation GBP_LIBOR_3M_OBS = IborIndexObservation.of(GBP_LIBOR_3M, FIXING_DATE, REF_DATA); private static final IborIndexObservation GBP_LIBOR_6M_OBS = IborIndexObservation.of(GBP_LIBOR_6M, FIXING_DATE, REF_DATA); private static final IborRateSensitivity SENSITIVITY3 = IborRateSensitivity.of(GBP_LIBOR_3M_OBS, 1d); private static final IborRateSensitivity SENSITIVITY6 = IborRateSensitivity.of(GBP_LIBOR_6M_OBS, 1d); private static final double TOLERANCE_RATE = 1.0E-10; @Test public void test_rate() { RatesProvider mockProv = mock(RatesProvider.class); LocalDateDoubleTimeSeries timeSeries = LocalDateDoubleTimeSeries.of(FIXING_DATE, RATE3TS); IborIndexRates mockRates3M = new TestingIborIndexRates( GBP_LIBOR_3M, FIXING_DATE, LocalDateDoubleTimeSeries.empty(), timeSeries); IborIndexRates mockRates6M = new TestingIborIndexRates( GBP_LIBOR_6M, FIXING_DATE, LocalDateDoubleTimeSeries.of(FIXING_DATE, RATE6), LocalDateDoubleTimeSeries.empty()); when(mockProv.iborIndexRates(GBP_LIBOR_3M)).thenReturn(mockRates3M); when(mockProv.iborIndexRates(GBP_LIBOR_6M)).thenReturn(mockRates6M); IborInterpolatedRateComputation ro = IborInterpolatedRateComputation.of(GBP_LIBOR_3M, GBP_LIBOR_6M, FIXING_DATE, REF_DATA); ForwardIborInterpolatedRateComputationFn obs = ForwardIborInterpolatedRateComputationFn.DEFAULT; LocalDate fixingEndDate3M = GBP_LIBOR_3M_OBS.getMaturityDate(); LocalDate fixingEndDate6M = GBP_LIBOR_6M_OBS.getMaturityDate(); double days3M = fixingEndDate3M.toEpochDay() - FIXING_DATE.toEpochDay(); //nb days in 3M fixing period double days6M = fixingEndDate6M.toEpochDay() - FIXING_DATE.toEpochDay(); //nb days in 6M fixing period double daysCpn = ACCRUAL_END_DATE.toEpochDay() - FIXING_DATE.toEpochDay(); double weight3M = (days6M - daysCpn) / (days6M - days3M); double weight6M = (daysCpn - days3M) / (days6M - days3M); double rateExpected = (weight3M * RATE3TS + weight6M * RATE6); double rateComputed = obs.rate(ro, ACCRUAL_START_DATE, ACCRUAL_END_DATE, mockProv); assertThat(rateComputed).isCloseTo(rateExpected, offset(TOLERANCE_RATE)); // explain ExplainMapBuilder builder = ExplainMap.builder(); assertThat(obs.explainRate(ro, ACCRUAL_START_DATE, ACCRUAL_END_DATE, mockProv, builder)).isCloseTo(rateExpected, offset(TOLERANCE_RATE)); ExplainMap built = builder.build(); assertThat(built.get(ExplainKey.OBSERVATIONS)).isPresent(); assertThat(built.get(ExplainKey.OBSERVATIONS).get()).hasSize(2); assertThat(built.get(ExplainKey.OBSERVATIONS).get().get(0).get(ExplainKey.FIXING_DATE)).isEqualTo(Optional.of(FIXING_DATE)); assertThat(built.get(ExplainKey.OBSERVATIONS).get().get(0).get(ExplainKey.INDEX)).isEqualTo(Optional.of(GBP_LIBOR_3M)); assertThat(built.get(ExplainKey.OBSERVATIONS).get().get(0).get(ExplainKey.INDEX_VALUE)).isEqualTo(Optional.of(RATE3TS)); assertThat(built.get(ExplainKey.OBSERVATIONS).get().get(0).get(ExplainKey.WEIGHT)).isEqualTo(Optional.of(weight3M)); assertThat(built.get(ExplainKey.OBSERVATIONS).get().get(0).get(ExplainKey.FROM_FIXING_SERIES)).isEqualTo(Optional.of(Boolean.TRUE)); assertThat(built.get(ExplainKey.OBSERVATIONS).get().get(1).get(ExplainKey.FIXING_DATE)).isEqualTo(Optional.of(FIXING_DATE)); assertThat(built.get(ExplainKey.OBSERVATIONS).get().get(1).get(ExplainKey.INDEX)).isEqualTo(Optional.of(GBP_LIBOR_6M)); assertThat(built.get(ExplainKey.OBSERVATIONS).get().get(1).get(ExplainKey.INDEX_VALUE)).isEqualTo(Optional.of(RATE6)); assertThat(built.get(ExplainKey.OBSERVATIONS).get().get(1).get(ExplainKey.WEIGHT)).isEqualTo(Optional.of(weight6M)); assertThat(built.get(ExplainKey.OBSERVATIONS).get().get(1).get(ExplainKey.FROM_FIXING_SERIES)).isEqualTo(Optional.empty()); assertThat(built.get(ExplainKey.COMBINED_RATE)).isEqualTo(Optional.of(rateExpected)); } @Test public void test_rateSensitivity() { RatesProvider mockProv = mock(RatesProvider.class); IborIndexRates mockRates3M = mock(IborIndexRates.class); IborIndexRates mockRates6M = mock(IborIndexRates.class); when(mockProv.iborIndexRates(GBP_LIBOR_3M)).thenReturn(mockRates3M); when(mockProv.iborIndexRates(GBP_LIBOR_6M)).thenReturn(mockRates6M); when(mockRates3M.ratePointSensitivity(GBP_LIBOR_3M_OBS)).thenReturn(SENSITIVITY3); when(mockRates6M.ratePointSensitivity(GBP_LIBOR_6M_OBS)).thenReturn(SENSITIVITY6); IborInterpolatedRateComputation ro = IborInterpolatedRateComputation.of(GBP_LIBOR_3M, GBP_LIBOR_6M, FIXING_DATE, REF_DATA); ForwardIborInterpolatedRateComputationFn obsFn = ForwardIborInterpolatedRateComputationFn.DEFAULT; LocalDate fixingEndDate3M = GBP_LIBOR_3M_OBS.getMaturityDate(); LocalDate fixingEndDate6M = GBP_LIBOR_6M_OBS.getMaturityDate(); double days3M = fixingEndDate3M.toEpochDay() - FIXING_DATE.toEpochDay(); //nb days in 3M fixing period double days6M = fixingEndDate6M.toEpochDay() - FIXING_DATE.toEpochDay(); //nb days in 6M fixing period double daysCpn = ACCRUAL_END_DATE.toEpochDay() - FIXING_DATE.toEpochDay(); double weight3M = (days6M - daysCpn) / (days6M - days3M); double weight6M = (daysCpn - days3M) / (days6M - days3M); IborRateSensitivity sens3 = IborRateSensitivity.of(GBP_LIBOR_3M_OBS, weight3M); IborRateSensitivity sens6 = IborRateSensitivity.of(GBP_LIBOR_6M_OBS, weight6M); PointSensitivities expected = PointSensitivities.of(ImmutableList.of(sens3, sens6)); PointSensitivityBuilder test = obsFn.rateSensitivity(ro, ACCRUAL_START_DATE, ACCRUAL_END_DATE, mockProv); assertThat(test.build()).isEqualTo(expected); } @Test public void test_rateSensitivity_finiteDifference() { double eps = 1.0e-7; RatesProvider mockProv = mock(RatesProvider.class); IborIndexRates mockRates3M = mock(IborIndexRates.class); IborIndexRates mockRates6M = mock(IborIndexRates.class); when(mockProv.iborIndexRates(GBP_LIBOR_3M)).thenReturn(mockRates3M); when(mockProv.iborIndexRates(GBP_LIBOR_6M)).thenReturn(mockRates6M); when(mockRates3M.rate(GBP_LIBOR_3M_OBS)).thenReturn(RATE3); when(mockRates6M.rate(GBP_LIBOR_6M_OBS)).thenReturn(RATE6); when(mockRates3M.ratePointSensitivity(GBP_LIBOR_3M_OBS)).thenReturn(SENSITIVITY3); when(mockRates6M.ratePointSensitivity(GBP_LIBOR_6M_OBS)).thenReturn(SENSITIVITY6); IborInterpolatedRateComputation ro = IborInterpolatedRateComputation.of(GBP_LIBOR_3M, GBP_LIBOR_6M, FIXING_DATE, REF_DATA); ForwardIborInterpolatedRateComputationFn obs = ForwardIborInterpolatedRateComputationFn.DEFAULT; PointSensitivityBuilder test = obs.rateSensitivity(ro, ACCRUAL_START_DATE, ACCRUAL_END_DATE, mockProv); IborIndexRates mockRatesUp3M = mock(IborIndexRates.class); when(mockRatesUp3M.rate(GBP_LIBOR_3M_OBS)).thenReturn(RATE3 + eps); IborIndexRates mockRatesDw3M = mock(IborIndexRates.class); when(mockRatesDw3M.rate(GBP_LIBOR_3M_OBS)).thenReturn(RATE3 - eps); IborIndexRates mockRatesUp6M = mock(IborIndexRates.class); when(mockRatesUp6M.rate(GBP_LIBOR_6M_OBS)).thenReturn(RATE6 + eps); IborIndexRates mockRatesDw6M = mock(IborIndexRates.class); when(mockRatesDw6M.rate(GBP_LIBOR_6M_OBS)).thenReturn(RATE6 - eps); RatesProvider mockProvUp3M = mock(RatesProvider.class); when(mockProvUp3M.iborIndexRates(GBP_LIBOR_3M)).thenReturn(mockRatesUp3M); when(mockProvUp3M.iborIndexRates(GBP_LIBOR_6M)).thenReturn(mockRates6M); RatesProvider mockProvDw3M = mock(RatesProvider.class); when(mockProvDw3M.iborIndexRates(GBP_LIBOR_3M)).thenReturn(mockRatesDw3M); when(mockProvDw3M.iborIndexRates(GBP_LIBOR_6M)).thenReturn(mockRates6M); RatesProvider mockProvUp6M = mock(RatesProvider.class); when(mockProvUp6M.iborIndexRates(GBP_LIBOR_3M)).thenReturn(mockRates3M); when(mockProvUp6M.iborIndexRates(GBP_LIBOR_6M)).thenReturn(mockRatesUp6M); RatesProvider mockProvDw6M = mock(RatesProvider.class); when(mockProvDw6M.iborIndexRates(GBP_LIBOR_3M)).thenReturn(mockRates3M); when(mockProvDw6M.iborIndexRates(GBP_LIBOR_6M)).thenReturn(mockRatesDw6M); double rateUp3M = obs.rate(ro, ACCRUAL_START_DATE, ACCRUAL_END_DATE, mockProvUp3M); double rateDw3M = obs.rate(ro, ACCRUAL_START_DATE, ACCRUAL_END_DATE, mockProvDw3M); double senseExpected3M = 0.5 * (rateUp3M - rateDw3M) / eps; double rateUp6M = obs.rate(ro, ACCRUAL_START_DATE, ACCRUAL_END_DATE, mockProvUp6M); double rateDw6M = obs.rate(ro, ACCRUAL_START_DATE, ACCRUAL_END_DATE, mockProvDw6M); double senseExpected6M = 0.5 * (rateUp6M - rateDw6M) / eps; assertThat(test.build().getSensitivities().get(0).getSensitivity()).isCloseTo(senseExpected3M, offset(eps)); assertThat(test.build().getSensitivities().get(1).getSensitivity()).isCloseTo(senseExpected6M, offset(eps)); } }
OpenGamma/Strata
modules/pricer/src/test/java/com/opengamma/strata/pricer/impl/rate/ForwardIborInterpolatedRateComputationFnTest.java
Java
apache-2.0
10,827
/* * Copyright (c) 2017. Matsuda, Akihit (akihito104) * * 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.freshdigitable.udonroad; import android.content.Context; import android.support.v7.widget.AppCompatTextView; import android.util.AttributeSet; /** * LinkableTextView is a TextView which is acceptable ClickableSpan and is colored at pressed. * * Created by akihit on 2017/01/05. */ public class LinkableTextView extends AppCompatTextView { public LinkableTextView(Context context) { this(context, null); } public LinkableTextView(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.textViewStyle); } public LinkableTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); Utils.colorStateLinkify(this); } }
akihito104/UdonRoad
app/src/main/java/com/freshdigitable/udonroad/LinkableTextView.java
Java
apache-2.0
1,342
// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.syntax; import com.google.common.base.Joiner; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Interner; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.concurrent.BlazeInterners; import com.google.devtools.build.lib.events.Location; import com.google.devtools.build.lib.skylarkinterface.SkylarkValue; import com.google.devtools.build.lib.syntax.SkylarkList.MutableList; import com.google.devtools.build.lib.syntax.SkylarkList.Tuple; import com.google.devtools.build.lib.util.Preconditions; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.annotation.Nullable; /** * A class representing types available in Skylark. * * <p>A SkylarkType can be one of: * <ul> * <li>a Simple type that contains exactly the objects in a given class, * (including the special TOP and BOTTOM types that respectively contain * all the objects (Simple type for Object.class) and no object at all * (Simple type for EmptyType.class, isomorphic to Void.class). * <li>a Combination of a generic class (one of SET, selector) * and an argument type (that itself need not be Simple). * <li>a Union of a finite set of types * <li>a FunctionType associated with a name and a returnType * </ul> * * <p>In a style reminiscent of Java's null, Skylark's None is in all the types * as far as type inference goes, yet actually no type .contains(it). * * <p>The current implementation fails to distinguish between TOP and ANY, * between BOTTOM and EMPTY (VOID, ZERO, FALSE): * <ul> * <li>In type analysis, we often distinguish a notion of "the type of this object" * from the notion of "what I know about the type of this object". * Some languages have a Universal Base Class that contains all objects, and would be the ANY type. * The Skylark runtime, written in Java, has this ANY type, Java's Object.class. * But the Skylark validation engine doesn't really have a concept of an ANY class; * however, it does have a concept of a yet-undermined class, the TOP class * (called UNKOWN in previous code). In the future, we may have to distinguish between the two, * at which point type constructor classes would have to be generic in * "actual type" vs "partial knowledge of type". * <li>Similarly, and EMPTY type (also known as VOID, ZERO or FALSE, in other contexts) * is a type that has no instance, whereas the BOTTOM type is the type analysis that says * that there is no possible runtime type for the given object, which may imply that * the point in the program at which the object is evaluated cannot be reached, etc. * </ul> * So for now, we have puns between TOP and ANY, BOTTOM and EMPTY, between runtime (eval) and * validation-time (validate). Yet in the future, we may need to make a clear distinction, * especially if we are to have types such List(Any) vs List(Top), which contains the former, * but also plenty of other quite distinct types. And yet in a future future, the TOP type * would not be represented explicitly, instead a new type variable would be inserted everywhere * a type is unknown, to be unified with further type information as it becomes available. */ // TODO(bazel-team): move the FunctionType side-effect out of the type object // and into the validation environment. public abstract class SkylarkType implements Serializable { // The main primitives to override in subclasses /** Is the given value an element of this type? By default, no (empty type) */ public boolean contains(Object value) { return false; } /** * intersectWith() is the internal method from which function intersection(t1, t2) is computed. * OVERRIDE this method in your classes, but DO NOT TO CALL it: only call intersection(). * When computing intersection(t1, t2), whichever type defined before the other * knows nothing about the other and about their intersection, and returns BOTTOM; * the other knows about the former, and returns their intersection (which may be BOTTOM). * intersection() will call in one order then the other, and return whichever answer * isn't BOTTOM, if any. By default, types are disjoint and their intersection is BOTTOM. */ // TODO(bazel-team): should we define and use an Exception instead? protected SkylarkType intersectWith(SkylarkType other) { return BOTTOM; } /** @return true if any object of this SkylarkType can be cast to that Java class */ public boolean canBeCastTo(Class<?> type) { return SkylarkType.of(type).includes(this); } /** @return the smallest java Class known to contain all elements of this type */ // Note: most user-code should be using a variant that throws an Exception // if the result is Object.class but the type isn't TOP. public Class<?> getType() { return Object.class; } // The actual intersection function for users to use public static SkylarkType intersection(SkylarkType t1, SkylarkType t2) { if (t1.equals(t2)) { return t1; } SkylarkType t = t1.intersectWith(t2); if (t == BOTTOM) { return t2.intersectWith(t1); } else { return t; } } public boolean includes(SkylarkType other) { return intersection(this, other).equals(other); } public SkylarkType getArgType() { return TOP; } private static final class Empty {}; // Empty type, used as basis for Bottom // Notable types /** A singleton for the TOP type, that at analysis time means that any type is possible. */ public static final Simple TOP = new Top(); /** A singleton for the BOTTOM type, that contains no element */ public static final Simple BOTTOM = new Bottom(); /** NONE, the Unit type, isomorphic to Void, except its unique element prints as None */ // Note that we currently consider at validation time that None is in every type, // by declaring its type as TOP instead of NONE, even though at runtime, // we reject None from all types but NONE, and in particular from e.g. lists of Files. // TODO(bazel-team): resolve this inconsistency, one way or the other. public static final Simple NONE = Simple.forClass(Runtime.NoneType.class); /** The STRING type, for strings */ public static final Simple STRING = Simple.forClass(String.class); /** The INTEGER type, for 32-bit signed integers */ public static final Simple INT = Simple.forClass(Integer.class); /** The BOOLEAN type, that contains TRUE and FALSE */ public static final Simple BOOL = Simple.forClass(Boolean.class); /** The FUNCTION type, that contains all functions, otherwise dynamically typed at call-time */ public static final SkylarkFunctionType FUNCTION = new SkylarkFunctionType("unknown", TOP); /** The DICT type, that contains SkylarkDict */ public static final Simple DICT = Simple.forClass(SkylarkDict.class); /** The SEQUENCE type, that contains lists and tuples */ // TODO(bazel-team): this was added for backward compatibility with the BUILD language, // that doesn't make a difference between list and tuple, so that functions can be declared // that keep not making the difference. Going forward, though, we should investigate whether // we ever want to use this type, and if not, make sure no existing client code uses it. public static final Simple SEQUENCE = Simple.forClass(SkylarkList.class); /** The LIST type, that contains all MutableList-s */ public static final Simple LIST = Simple.forClass(MutableList.class); /** The TUPLE type, that contains all Tuple-s */ public static final Simple TUPLE = Simple.forClass(Tuple.class); /** The STRING_LIST type, a MutableList of strings */ public static final SkylarkType STRING_LIST = Combination.of(LIST, STRING); /** The INT_LIST type, a MutableList of integers */ public static final SkylarkType INT_LIST = Combination.of(LIST, INT); /** The SET type, that contains all SkylarkNestedSet-s, and the generic combinator for them */ public static final Simple SET = Simple.forClass(SkylarkNestedSet.class); // Common subclasses of SkylarkType /** the Top type contains all objects */ private static class Top extends Simple { private Top() { super(Object.class); } @Override public boolean contains(Object value) { return true; } @Override public SkylarkType intersectWith(SkylarkType other) { return other; } @Override public String toString() { return "Object"; } } /** the Bottom type contains no element */ private static class Bottom extends Simple { private Bottom() { super(Empty.class); } @Override public SkylarkType intersectWith(SkylarkType other) { return this; } @Override public String toString() { return "EmptyType"; } } /** a Simple type contains the instance of a Java class */ public static class Simple extends SkylarkType { private final Class<?> type; private Simple(Class<?> type) { this.type = type; } @Override public boolean contains(Object value) { return value != null && type.isInstance(value); } @Override public Class<?> getType() { return type; } @Override public boolean equals(Object other) { return this == other || (this.getClass() == other.getClass() && this.type.equals(((Simple) other).getType())); } @Override public int hashCode() { return 0x513973 + type.hashCode() * 503; // equal underlying types yield the same hashCode } @Override public String toString() { return EvalUtils.getDataTypeNameFromClass(type); } @Override public boolean canBeCastTo(Class<?> type) { return this.type == type || super.canBeCastTo(type); } private static final LoadingCache<Class<?>, Simple> simpleCache = CacheBuilder.newBuilder() .build( new CacheLoader<Class<?>, Simple>() { @Override public Simple load(Class<?> type) { return create(type); } }); private static Simple create(Class<?> type) { Simple simple; if (type == Object.class) { // Note that this is a bad encoding for "anything", not for "everything", i.e. // for skylark there isn't a type that contains everything, but there's a Top type // that corresponds to not knowing yet which more special type it will be. simple = TOP; } else if (type == Empty.class) { simple = BOTTOM; } else { // Consider all classes that have the same EvalUtils.getSkylarkType() as equivalent, // as a substitute to handling inheritance. Class<?> skylarkType = EvalUtils.getSkylarkType(type); if (skylarkType != type) { simple = Simple.forClass(skylarkType); } else { simple = new Simple(type); } } return simple; } /** * The way to create a Simple type. * * @param type a Class * @return the Simple type that contains exactly the instances of that Class */ // Only call this method from SkylarkType. Calling it from outside SkylarkType leads to // circular dependencies in class initialization, showing up as an NPE while initializing NONE. // You actually want to call SkylarkType.of(). private static Simple forClass(Class<?> type) { return simpleCache.getUnchecked(type); } } /** Combination of a generic type and an argument type */ public static class Combination extends SkylarkType { // For the moment, we can only combine a Simple type with a Simple type, // and the first one has to be a Java generic class, // and in practice actually one of SkylarkList or SkylarkNestedSet private final SkylarkType genericType; // actually always a Simple, for now. private final SkylarkType argType; // not always Simple private Combination(SkylarkType genericType, SkylarkType argType) { this.genericType = genericType; this.argType = argType; } @Override public boolean contains(Object value) { // The empty collection is member of compatible types if (value == null || !genericType.contains(value)) { return false; } else { SkylarkType valueArgType = getGenericArgType(value); return valueArgType == TOP // empty objects are universal || argType.includes(valueArgType); } } @Override public SkylarkType intersectWith(SkylarkType other) { // For now, we only accept generics with a single covariant parameter if (genericType.equals(other)) { return this; } if (other instanceof Combination) { SkylarkType generic = genericType.intersectWith(((Combination) other).getGenericType()); if (generic == BOTTOM) { return BOTTOM; } SkylarkType arg = intersection(argType, ((Combination) other).getArgType()); if (arg == BOTTOM) { return BOTTOM; } return Combination.of(generic, arg); } if (other instanceof Simple) { SkylarkType generic = genericType.intersectWith(other); if (generic == BOTTOM) { return BOTTOM; } return SkylarkType.of(generic, getArgType()); } return BOTTOM; } @Override public boolean equals(Object other) { if (this == other) { return true; } else if (this.getClass() == other.getClass()) { Combination o = (Combination) other; return genericType.equals(o.getGenericType()) && argType.equals(o.getArgType()); } else { return false; } } @Override public int hashCode() { // equal underlying types yield the same hashCode return 0x20B14A71 + genericType.hashCode() * 1009 + argType.hashCode() * 1013; } @Override public Class<?> getType() { return genericType.getType(); } SkylarkType getGenericType() { return genericType; } @Override public SkylarkType getArgType() { return argType; } @Override public String toString() { return genericType + " of " + argType + "s"; } private static final Interner<Combination> combinationInterner = BlazeInterners.<Combination>newWeakInterner(); public static SkylarkType of(SkylarkType generic, SkylarkType argument) { // assume all combinations with TOP are the same as the simple type, and canonicalize. Preconditions.checkArgument(generic instanceof Simple); if (argument == TOP) { return generic; } else { return combinationInterner.intern(new Combination(generic, argument)); } } public static SkylarkType of(Class<?> generic, Class<?> argument) { return of(Simple.forClass(generic), Simple.forClass(argument)); } } /** Union types, used a lot in "dynamic" languages such as Python or Skylark */ public static class Union extends SkylarkType { private final ImmutableList<SkylarkType> types; private Union(ImmutableList<SkylarkType> types) { this.types = types; } @Override public boolean contains(Object value) { for (SkylarkType type : types) { if (type.contains(value)) { return true; } } return false; } @Override public boolean equals(Object other) { if (this.getClass() == other.getClass()) { Union o = (Union) other; if (types.containsAll(o.types) && o.types.containsAll(types)) { return true; } } return false; } @Override public int hashCode() { // equal underlying types yield the same hashCode int h = 0x4104; for (SkylarkType type : types) { // Important: addition is commutative, like Union h += type.hashCode(); } return h; } @Override public String toString() { return Joiner.on(" or ").join(types); } public static List<SkylarkType> addElements(List<SkylarkType> list, SkylarkType type) { if (type instanceof Union) { list.addAll(((Union) type).types); } else if (type != BOTTOM) { list.add(type); } return list; } @Override public SkylarkType intersectWith(SkylarkType other) { List<SkylarkType> otherTypes = addElements(new ArrayList<SkylarkType>(), other); List<SkylarkType> results = new ArrayList<>(); for (SkylarkType element : types) { for (SkylarkType otherElement : otherTypes) { addElements(results, intersection(element, otherElement)); } } return Union.of(results); } public static SkylarkType of(List<SkylarkType> types) { // When making the union of many types, // canonicalize them into elementary (non-Union) types, // and then eliminate trivially redundant types from the list. // list of all types in the input ArrayList<SkylarkType> elements = new ArrayList<>(); for (SkylarkType type : types) { addElements(elements, type); } // canonicalized list of types ArrayList<SkylarkType> canonical = new ArrayList<>(); for (SkylarkType newType : elements) { boolean done = false; // done with this element? int i = 0; for (SkylarkType existingType : canonical) { SkylarkType both = intersection(newType, existingType); if (newType.equals(both)) { // newType already included done = true; break; } else if (existingType.equals(both)) { // newType supertype of existingType canonical.set(i, newType); done = true; break; } } if (!done) { canonical.add(newType); } } if (canonical.isEmpty()) { return BOTTOM; } else if (canonical.size() == 1) { return canonical.get(0); } else { return new Union(ImmutableList.<SkylarkType>copyOf(canonical)); } } public static SkylarkType of(SkylarkType... types) { return of(Arrays.asList(types)); } public static SkylarkType of(SkylarkType t1, SkylarkType t2) { return of(ImmutableList.<SkylarkType>of(t1, t2)); } public static SkylarkType of(Class<?> t1, Class<?> t2) { return of(Simple.forClass(t1), Simple.forClass(t2)); } } public static SkylarkType of(Class<?> type) { if (SkylarkNestedSet.class.isAssignableFrom(type)) { return SET; } else if (BaseFunction.class.isAssignableFrom(type)) { return new SkylarkFunctionType("unknown", TOP); } else { return Simple.forClass(type); } } public static SkylarkType of(SkylarkType t1, SkylarkType t2) { return Combination.of(t1, t2); } public static SkylarkType of(Class<?> t1, Class<?> t2) { return Combination.of(t1, t2); } /** * A class representing the type of a Skylark function. */ public static final class SkylarkFunctionType extends SkylarkType { private final String name; @Nullable private final SkylarkType returnType; @Override public SkylarkType intersectWith(SkylarkType other) { // This gives the wrong result if both return types are incompatibly updated later! if (other instanceof SkylarkFunctionType) { SkylarkFunctionType fun = (SkylarkFunctionType) other; SkylarkType type1 = returnType == null ? TOP : returnType; SkylarkType type2 = fun.returnType == null ? TOP : fun.returnType; SkylarkType bothReturnType = intersection(returnType, fun.returnType); if (type1.equals(bothReturnType)) { return this; } else if (type2.equals(bothReturnType)) { return fun; } else { return new SkylarkFunctionType(name, bothReturnType); } } else { return BOTTOM; } } @Override public Class<?> getType() { return BaseFunction.class; } @Override public String toString() { return (returnType == TOP || returnType == null ? "" : returnType + "-returning ") + "function"; } @Override public boolean contains(Object value) { // This returns true a bit too much, not looking at the result type. return value instanceof BaseFunction; } public static SkylarkFunctionType of(String name, SkylarkType returnType) { return new SkylarkFunctionType(name, returnType); } private SkylarkFunctionType(String name, SkylarkType returnType) { this.name = name; this.returnType = returnType; } } // Utility functions regarding types public static SkylarkType typeOf(Object value) { if (value == null) { return BOTTOM; } else if (value instanceof SkylarkNestedSet) { return of(SET, ((SkylarkNestedSet) value).getContentType()); } else { return Simple.forClass(value.getClass()); } } public static SkylarkType getGenericArgType(Object value) { if (value instanceof SkylarkNestedSet) { return ((SkylarkNestedSet) value).getContentType(); } else { return TOP; } } private static boolean isTypeAllowedInSkylark(Object object) { if (object instanceof NestedSet<?>) { return false; } else if (object instanceof List<?> && !(object instanceof SkylarkList)) { return false; } return true; } /** * Throws EvalException if the type of the object is not allowed to be present in Skylark. */ static void checkTypeAllowedInSkylark(Object object, Location loc) throws EvalException { if (!isTypeAllowedInSkylark(object)) { throw new EvalException( loc, "internal error: type '" + object.getClass().getSimpleName() + "' is not allowed"); } } /** * General purpose type-casting facility. * * @param value - the actual value of the parameter * @param type - the expected Class for the value * @param loc - the location info used in the EvalException * @param format - a format String * @param args - arguments to format, in case there's an exception */ public static <T> T cast(Object value, Class<T> type, Location loc, String format, Object... args) throws EvalException { try { return type.cast(value); } catch (ClassCastException e) { throw new EvalException(loc, String.format(format, args)); } } /** * General purpose type-casting facility. * * @param value - the actual value of the parameter * @param genericType - a generic class of one argument for the value * @param argType - a covariant argument for the generic class * @param loc - the location info used in the EvalException * @param format - a format String * @param args - arguments to format, in case there's an exception */ @SuppressWarnings("unchecked") public static <T> T cast(Object value, Class<T> genericType, Class<?> argType, Location loc, String format, Object... args) throws EvalException { if (of(genericType, argType).contains(value)) { return (T) value; } else { throw new EvalException(loc, String.format(format, args)); } } /** * Cast a Map object into an Iterable of Map entries of the given key, value types. * @param obj the Map object, where null designates an empty map * @param keyType the class of map keys * @param valueType the class of map values * @param what a string indicating what this is about, to include in case of error */ @SuppressWarnings("unchecked") public static <KEY_TYPE, VALUE_TYPE> Map<KEY_TYPE, VALUE_TYPE> castMap(Object obj, Class<KEY_TYPE> keyType, Class<VALUE_TYPE> valueType, String what) throws EvalException { if (obj == null) { return ImmutableMap.of(); } if (!(obj instanceof Map<?, ?>)) { throw new EvalException( null, String.format( "expected a dictionary for '%s' but got '%s' instead", what, EvalUtils.getDataTypeName(obj))); } for (Map.Entry<?, ?> input : ((Map<?, ?>) obj).entrySet()) { if (!keyType.isAssignableFrom(input.getKey().getClass()) || !valueType.isAssignableFrom(input.getValue().getClass())) { throw new EvalException( null, String.format( "expected <%s, %s> type for '%s' but got <%s, %s> instead", keyType.getSimpleName(), valueType.getSimpleName(), what, EvalUtils.getDataTypeName(input.getKey()), EvalUtils.getDataTypeName(input.getValue()))); } } return (Map<KEY_TYPE, VALUE_TYPE>) obj; } private static Class<?> getGenericTypeFromMethod(Method method) { // This is where we can infer generic type information, so SkylarkNestedSets can be // created in a safe way. Eventually we should probably do something with Lists and Maps too. ParameterizedType t = (ParameterizedType) method.getGenericReturnType(); Type type = t.getActualTypeArguments()[0]; if (type instanceof Class) { return (Class<?>) type; } if (type instanceof WildcardType) { WildcardType wildcard = (WildcardType) type; Type upperBound = wildcard.getUpperBounds()[0]; if (upperBound instanceof Class) { // i.e. List<? extends SuperClass> return (Class<?>) upperBound; } } // It means someone annotated a method with @SkylarkCallable with no specific generic type info. // We shouldn't annotate methods which return List<?> or List<T>. throw new IllegalStateException("Cannot infer type from method signature " + method); } /** * Converts an object retrieved from a Java method to a Skylark-compatible type. */ static Object convertToSkylark(Object object, Method method, @Nullable Environment env) { if (object instanceof NestedSet<?>) { return new SkylarkNestedSet(getGenericTypeFromMethod(method), (NestedSet<?>) object); } return convertToSkylark(object, env); } /** * Converts an object to a Skylark-compatible type if possible. */ public static Object convertToSkylark(Object object, @Nullable Environment env) { if (object instanceof List && !(object instanceof SkylarkList)) { return new MutableList<>((List<?>) object, env); } if (object instanceof SkylarkValue) { return object; } if (object instanceof Map) { return SkylarkDict.<Object, Object>copyOf(env, (Map<?, ?>) object); } // TODO(bazel-team): ensure everything is a SkylarkValue at all times. // Preconditions.checkArgument(EvalUtils.isSkylarkAcceptable( // object.getClass()), // "invalid object %s of class %s not convertible to a Skylark value", // object, // object.getClass()); return object; } public static void checkType(Object object, Class<?> type, @Nullable Object description) throws EvalException { if (!type.isInstance(object)) { throw new EvalException( null, Printer.format( "expected type '%r' %sbut got type '%s' instead", type, description == null ? "" : String.format("for %s ", description), EvalUtils.getDataTypeName(object))); } } }
juhalindfors/bazel-patches
src/main/java/com/google/devtools/build/lib/syntax/SkylarkType.java
Java
apache-2.0
28,377
/* * Copyright (c) 2016, WSO2 Inc. (http://wso2.com) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.msf4j.internal.router; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.junit.Assert; import org.junit.Test; import java.util.List; /** * Test the routing logic using String as the destination. */ public class PathRouterTest { @Test public void testPathRoutings() { PatternPathRouterWithGroups<String> pathRouter = PatternPathRouterWithGroups.create(); pathRouter.add("/foo/{baz}/b", "foobarb"); pathRouter.add("/foo/bar/baz", "foobarbaz"); pathRouter.add("/baz/bar", "bazbar"); pathRouter.add("/bar", "bar"); pathRouter.add("/foo/bar", "foobar"); pathRouter.add("//multiple/slash//route", "multipleslashroute"); pathRouter.add("/multi/match/**", "multi-match-*"); pathRouter.add("/multi/match/def", "multi-match-def"); pathRouter.add("/multi/maxmatch/**", "multi-max-match-*"); pathRouter.add("/multi/maxmatch/{id}", "multi-max-match-id"); pathRouter.add("/multi/maxmatch/foo", "multi-max-match-foo"); pathRouter.add("**/wildcard/{id}", "wildcard-id"); pathRouter.add("/**/wildcard/{id}", "slash-wildcard-id"); pathRouter.add("**/wildcard/**/foo/{id}", "wildcard-foo-id"); pathRouter.add("/**/wildcard/**/foo/{id}", "slash-wildcard-foo-id"); pathRouter.add("**/wildcard/**/foo/{id}/**", "wildcard-foo-id-2"); pathRouter.add("/**/wildcard/**/foo/{id}/**", "slash-wildcard-foo-id-2"); List<PatternPathRouterWithGroups.RoutableDestination<String>> routes; routes = pathRouter.getDestinations("/foo/bar/baz"); Assert.assertEquals(1, routes.size()); Assert.assertEquals("foobarbaz", routes.get(0).getDestination()); Assert.assertTrue(routes.get(0).getGroupNameValues().isEmpty()); routes = pathRouter.getDestinations("/baz/bar"); Assert.assertEquals(1, routes.size()); Assert.assertEquals("bazbar", routes.get(0).getDestination()); Assert.assertTrue(routes.get(0).getGroupNameValues().isEmpty()); routes = pathRouter.getDestinations("/foo/bar/baz/moo"); Assert.assertTrue(routes.isEmpty()); routes = pathRouter.getDestinations("/bar/121"); Assert.assertTrue(routes.isEmpty()); routes = pathRouter.getDestinations("/foo/bar/b"); Assert.assertEquals(1, routes.size()); Assert.assertEquals("foobarb", routes.get(0).getDestination()); Assert.assertEquals(1, routes.get(0).getGroupNameValues().size()); Assert.assertEquals("bar", routes.get(0).getGroupNameValues().get("baz")); routes = pathRouter.getDestinations("/foo/bar"); Assert.assertEquals(1, routes.size()); Assert.assertEquals("foobar", routes.get(0).getDestination()); Assert.assertTrue(routes.get(0).getGroupNameValues().isEmpty()); routes = pathRouter.getDestinations("/multiple/slash/route"); Assert.assertEquals(1, routes.size()); Assert.assertEquals("multipleslashroute", routes.get(0).getDestination()); Assert.assertTrue(routes.get(0).getGroupNameValues().isEmpty()); routes = pathRouter.getDestinations("/foo/bar/bazooka"); Assert.assertTrue(routes.isEmpty()); routes = pathRouter.getDestinations("/multi/match/def"); Assert.assertEquals(2, routes.size()); Assert.assertEquals(ImmutableSet.of("multi-match-def", "multi-match-*"), ImmutableSet.of(routes.get(0).getDestination(), routes.get(1).getDestination())); Assert.assertTrue(routes.get(0).getGroupNameValues().isEmpty()); Assert.assertTrue(routes.get(1).getGroupNameValues().isEmpty()); routes = pathRouter.getDestinations("/multi/match/ghi"); Assert.assertEquals(1, routes.size()); Assert.assertEquals("multi-match-*", routes.get(0).getDestination()); Assert.assertTrue(routes.get(0).getGroupNameValues().isEmpty()); routes = pathRouter.getDestinations("/multi/maxmatch/id1"); Assert.assertEquals(2, routes.size()); Assert.assertEquals(ImmutableSet.of("multi-max-match-id", "multi-max-match-*"), ImmutableSet.of(routes.get(0).getDestination(), routes.get(1).getDestination())); //noinspection Assert.assertEqualsBetweenInconvertibleTypes Assert.assertEquals(ImmutableSet.of(ImmutableMap.of("id", "id1"), ImmutableMap.<String, String>of()), ImmutableSet.of(routes.get(0).getGroupNameValues(), routes.get(1).getGroupNameValues()) ); routes = pathRouter.getDestinations("/multi/maxmatch/foo"); Assert.assertEquals(3, routes.size()); Assert.assertEquals(ImmutableSet.of("multi-max-match-id", "multi-max-match-*", "multi-max-match-foo"), ImmutableSet.of(routes.get(0).getDestination(), routes.get(1).getDestination(), routes.get(2).getDestination())); //noinspection Assert.assertEqualsBetweenInconvertibleTypes Assert.assertEquals(ImmutableSet.of(ImmutableMap.of("id", "foo"), ImmutableMap.<String, String>of()), ImmutableSet.of(routes.get(0).getGroupNameValues(), routes.get(1).getGroupNameValues()) ); routes = pathRouter.getDestinations("/foo/bar/wildcard/id1"); Assert.assertEquals(2, routes.size()); Assert.assertEquals(ImmutableSet.of("wildcard-id", "slash-wildcard-id"), ImmutableSet.of(routes.get(0).getDestination(), routes.get(1).getDestination())); //noinspection Assert.assertEqualsBetweenInconvertibleTypes Assert.assertEquals(ImmutableSet.of(ImmutableMap.of("id", "id1"), ImmutableMap.<String, String>of("id", "id1")), ImmutableSet.of(routes.get(0).getGroupNameValues(), routes.get(1).getGroupNameValues()) ); routes = pathRouter.getDestinations("/wildcard/id1"); Assert.assertEquals(1, routes.size()); Assert.assertEquals("wildcard-id", routes.get(0).getDestination()); Assert.assertEquals(ImmutableMap.of("id", "id1"), routes.get(0).getGroupNameValues()); routes = pathRouter.getDestinations("/foo/bar/wildcard/bar/foo/id1"); Assert.assertEquals(2, routes.size()); Assert.assertEquals(ImmutableSet.of("wildcard-foo-id", "slash-wildcard-foo-id"), ImmutableSet.of(routes.get(0).getDestination(), routes.get(1).getDestination())); //noinspection Assert.assertEqualsBetweenInconvertibleTypes Assert.assertEquals(ImmutableSet.of(ImmutableMap.of("id", "id1"), ImmutableMap.<String, String>of("id", "id1")), ImmutableSet.of(routes.get(0).getGroupNameValues(), routes.get(1).getGroupNameValues()) ); routes = pathRouter.getDestinations("/foo/bar/wildcard/bar/foo/id1/baz/bar"); Assert.assertEquals(2, routes.size()); Assert.assertEquals(ImmutableSet.of("wildcard-foo-id-2", "slash-wildcard-foo-id-2"), ImmutableSet.of(routes.get(0).getDestination(), routes.get(1).getDestination())); //noinspection Assert.assertEqualsBetweenInconvertibleTypes Assert.assertEquals(ImmutableSet.of(ImmutableMap.of("id", "id1"), ImmutableMap.<String, String>of("id", "id1")), ImmutableSet.of(routes.get(0).getGroupNameValues(), routes.get(1).getGroupNameValues()) ); routes = pathRouter.getDestinations("/wildcard/bar/foo/id1/baz/bar"); Assert.assertEquals(1, routes.size()); Assert.assertEquals("wildcard-foo-id-2", routes.get(0).getDestination()); Assert.assertEquals(ImmutableMap.of("id", "id1"), routes.get(0).getGroupNameValues()); } }
taniamahanama/product-msf4j
core/src/test/java/org/wso2/msf4j/internal/router/PathRouterTest.java
Java
apache-2.0
8,334
package org.soa; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.LinkedBlockingQueue; import jmetal.core.Variable; import jmetal.encodings.variable.Int; import jmetal.util.JMException; import java.util.Comparator; import org.femosaa.core.SASSolution; import org.ssase.objective.Objective; import org.ssase.objective.optimization.bb.BranchAndBoundRegion; import org.ssase.objective.optimization.femosaa.FEMOSAASolution; import org.ssase.primitive.ControlPrimitive; import org.ssase.primitive.EnvironmentalPrimitive; import org.ssase.primitive.Primitive; import org.ssase.primitive.SoftwareControlPrimitive; import org.ssase.region.Region; import org.ssase.util.Repository; /** * This is just for SOA case * @author tao * */ public class ExtendedBB extends Region{ protected static final long EXECUTION_TIME = 40000; @Override public LinkedHashMap<ControlPrimitive, Double> optimize() { LinkedHashMap<ControlPrimitive, Double> current = new LinkedHashMap<ControlPrimitive, Double>(); synchronized (lock) { while (waitingUpdateCounter != 0) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } isLocked = true; List<ControlPrimitive> tempList = Repository .getSortedControlPrimitives(objectives.get(0)); List<ControlPrimitive> list = new ArrayList<ControlPrimitive>(); list.addAll(tempList); addRemoveFeatureFor01Representation(list); sortForDependency(list); Map<Objective, Double> map = getBasis(); double[] currentDecision = new double[list.size()]; Node best = null; Double[] bestResult = null; for (Objective obj : objectives) { for (Primitive p : obj.getPrimitivesInput()) { if (p instanceof ControlPrimitive) { current.put((ControlPrimitive) p, (double) p.getProvision()); currentDecision[list.indexOf((ControlPrimitive) p)] = (double) p .getProvision(); } } } for (ControlPrimitive cp : list) { if (!current.containsKey(cp)) { current.put(cp, (double) cp.getProvision()); currentDecision[list.indexOf(cp)] = cp.getProvision(); } } LinkedBlockingQueue<Node> q = new LinkedBlockingQueue<Node>(); // for (double d : list.get(0).getValueVector()) { // q.offer(new Node(0, d, currentDecision)); // } for (int i = list.get(0).getValueVector().length-1; i >= 0 ; i--) { q.offer(new Node(0, list.get(0).getValueVector()[i], currentDecision)); } long start = System.currentTimeMillis(); int count = 0; do { // To avoid an extrmely long runtime if ((System.currentTimeMillis() - start) > EXECUTION_TIME) { break; } count++; // System.out.print("Run " + count + "\n"); Node node = q.poll(); Double[] v = doWeightSum(list, node.decision, map); if (bestResult == null || v[0] > bestResult[0]) { best = node; bestResult = v; } if (node.index + 1 < list.size()) { // for (double d : list.get(node.index + 1).getValueVector()) { // q.offer(new Node(node.index + 1, d, node.decision)); // } for (int i = list.get(0).getValueVector().length-1; i >= 0 ; i--) { q.offer(new Node(node.index + 1, list.get(0).getValueVector()[i], node.decision)); } } } while (!q.isEmpty()); q.clear(); for (int i = 0; i < best.decision.length; i++) { current.put(list.get(i), best.decision[i]); } for (ControlPrimitive cp : list) { if (!tempList.contains(cp)) { current.remove(cp); } } list = tempList; // Starting the dependency check and log double[][] optionalVariables = new double[list.size()][]; for (int i = 0; i < optionalVariables.length; i++) { optionalVariables[i] = list.get(i).getValueVector(); } // This is a static method SASSolution.init(optionalVariables); SASSolution.clearAndStoreForValidationOnly(); FEMOSAASolution dummy = new FEMOSAASolution(); dummy.init(objectives, null); Variable[] variables = new Variable[list.size()]; for (int i = 0; i < list.size(); i++) { variables[i] = new Int(0, list.get(i).getValueVector().length - 1); } dummy.setDecisionVariables(variables); for (int i = 0; i < list.size(); i++) { double v = current.get(list.get(i)); double value = 0; for (int j = 0; j < list.get(i).getValueVector().length; j++) { if (list.get(i).getValueVector()[j] == v) { value = j; break; } } //System.out.print(list.get(i).getName() + ", v=" + v + ", index=" + value +"\n"); try { dummy.getDecisionVariables()[i].setValue(value); } catch (JMException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Region.logDependencyForFinalSolution(dummy); if (!dummy.isSolutionValid()) { try { dummy.correctDependency(); current.clear(); for (int i = 0; i < list.size(); i++) { current.put(list.get(i), list.get(i).getValueVector()[ (int)dummy.getDecisionVariables()[i].getValue()]); } System.out .print("The final result does not satisfy all dependency, thus correct it\n"); } catch (JMException e) { // TODO Auto-generated catch block e.printStackTrace(); } } print(current); isLocked = false; lock.notifyAll(); } System.out .print("================= Finish optimization ! =================\n"); return current; } private Double[] doWeightSum(List<ControlPrimitive> list, double[] decision, Map<Objective, Double> map) { double result = 0; double satisfied = 1; double[] xValue; double w = 1.0 / objectives.size(); for (Objective obj : objectives) { xValue = new double[obj.getPrimitivesInput().size()]; // System.out.print(obj.getPrimitivesInput().size()+"\n"); for (int i = 0; i < obj.getPrimitivesInput().size(); i++) { if (obj.getPrimitivesInput().get(i) instanceof ControlPrimitive) { xValue[i] = decision[list.indexOf(obj.getPrimitivesInput() .get(i))]; } else { xValue[i] = ((EnvironmentalPrimitive) obj .getPrimitivesInput().get(i)).getLatest(); } } if (!obj.isSatisfied(xValue)) { // System.out.print(obj.getName() + " is not satisfied " + // obj.predict(xValue) + "\n"); // throw new RuntimeException(); satisfied = -1; } result = obj.isMin() ? result - w * (obj.predict(xValue) / (1 + map.get(obj))) : result + w * (obj.predict(xValue) / (1 + map.get(obj))); } return new Double[] { result, satisfied }; } private Map<Objective, Double> getBasis() throws RuntimeException { Map<Objective, Double> map = new HashMap<Objective, Double>(); double[] xValue; for (Objective obj : objectives) { xValue = new double[obj.getPrimitivesInput().size()]; // System.out.print(obj.getPrimitivesInput().size()+"\n"); for (int i = 0; i < obj.getPrimitivesInput().size(); i++) { if (obj.getPrimitivesInput().get(i) instanceof ControlPrimitive) { xValue[i] = obj.getPrimitivesInput().get(i).getProvision(); } else { xValue[i] = ((EnvironmentalPrimitive) obj .getPrimitivesInput().get(i)).getLatest(); } } map.put(obj, obj.predict(xValue)); } return map; } protected double[] getValueVector(Node node, List<ControlPrimitive> list) { //System.out.print("count " + list.get(node.index).getName() +"\n"); if (list.get(node.index).getName().equals("CS12")) { double[] r = null; for (int i = 0; i < node.index; i++) { if (list.get(i).getName().equals("CS11") && node.decision[i] != 0.0) { return new double[] { 0.0 }; } if (r != null) { return r; } } } if (list.get(node.index).getName().equals("CS15")) { double[] r = null; for (int i = 0; i < node.index; i++) { if (list.get(i).getName().equals("CS11") && node.decision[i] != 0.0) { return new double[] { 0.0 }; } if (r != null) { return r; } } } if (list.get(node.index).getName().equals("CS22")) { double[] r = null; for (int i = 0; i < node.index; i++) { if (list.get(i).getName().equals("CS13") && node.decision[i] == 0.0) { return new double[] { 0.0 }; } if (r != null) { return r; } } } if (list.get(node.index).getName().equals("CS14")) { double[] r = null; int count = 0; for (int i = 0; i < node.index; i++) { if (list.get(i).getName().equals("CS11") && node.decision[i] == 0.0) { count++; } if (list.get(i).getName().equals("CS12") && node.decision[i] == 0.0) { count++; } if (list.get(i).getName().equals("CS13") && node.decision[i] == 0.0) { count++; } if (list.get(i).getName().equals("CS15") && node.decision[i] == 0.0) { count++; } } if(count == 4) { return new double[] { 1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0 }; } } if (list.get(node.index).getName().equals("CS24")) { double[] r = null; int count = 0; for (int i = 0; i < node.index; i++) { if (list.get(i).getName().equals("CS21") && node.decision[i] == 0.0) { count++; } if (list.get(i).getName().equals("CS22") && node.decision[i] == 0.0) { count++; } if (list.get(i).getName().equals("CS23") && node.decision[i] == 0.0) { count++; } } if(count == 3) { return new double[] { 1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0 }; } } if (list.get(node.index).getName().equals("CS34")) { double[] r = null; int count = 0; for (int i = 0; i < node.index; i++) { if (list.get(i).getName().equals("CS31") && node.decision[i] == 0.0) { count++; } if (list.get(i).getName().equals("CS32") && node.decision[i] == 0.0) { count++; } if (list.get(i).getName().equals("CS33") && node.decision[i] == 0.0) { count++; } } if(count == 3) { return new double[] { 1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0 }; } } if (list.get(node.index).getName().equals("CS42")) { double[] r = null; int count = 0; for (int i = 0; i < node.index; i++) { if (list.get(i).getName().equals("CS41") && node.decision[i] == 0.0) { count++; } } if(count == 1) { return new double[] { 1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0 }; } } if (list.get(node.index).getName().equals("CS53")) { double[] r = null; int count = 0; for (int i = 0; i < node.index; i++) { if (list.get(i).getName().equals("CS51") && node.decision[i] == 0.0) { count++; } if (list.get(i).getName().equals("CS52") && node.decision[i] == 0.0) { count++; } } if(count == 2) { return new double[] { 1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0 }; } } return list.get(node.index).getValueVector(); } private void sortForDependency(List<ControlPrimitive> list) { // Collections.sort(list, new Comparator(){ // // public int compare(Object o1, Object o2) { // //System.out.print(((ControlPrimitive)o1).getName() + "*****\n"); // int i1 = Integer.parseInt(((ControlPrimitive)o1).getName().substring(2, 3)); // int i2 = Integer.parseInt(((ControlPrimitive)o2).getName().substring(2, 3)); // return i1 < i2? -1 : 1; // } // // }); // // ControlPrimitive cp3 = list.get(3); // list.remove(3); // list.add(4, cp3); // // System.out.print("after sorted\n"); // for (ControlPrimitive cp : list) { // System.out.print(cp.getName() + "\n"); // } Collections.shuffle(list); } private void addRemoveFeatureFor01Representation(List<ControlPrimitive> list) { // SoftwareControlPrimitive c = null; // // c = new SoftwareControlPrimitive("cache", "sas", false, null, null, 1, // 1, 1, 1, 1, 1, 1, true); // c.setValueVector(new double[] { 0, 1 }); // c.setProvision(1); // list.add(c); // // c = new SoftwareControlPrimitive("cache_config", "sas", false, null, // null, 1, 1, 1, 1, 1, 1, 1, true); // c.setValueVector(new double[] { 1 }); // c.setProvision(1); // list.add(c); // // c = new SoftwareControlPrimitive("thread_pool", "sas", false, null, // null, 1, 1, 1, 1, 1, 1, 1, true); // c.setValueVector(new double[] { 1 }); // c.setProvision(1); // list.add(c); // // c = new SoftwareControlPrimitive("connection_pool", "sas", false, null, // null, 1, 1, 1, 1, 1, 1, 1, true); // c.setValueVector(new double[] { 1 }); // c.setProvision(1); // list.add(c); // // c = new SoftwareControlPrimitive("database", "sas", false, null, null, // 1, 1, 1, 1, 1, 1, 1, true); // c.setValueVector(new double[] { 1 }); // c.setProvision(1); // list.add(c); // // c = new SoftwareControlPrimitive("database", "sas", false, null, null, // 1, 1, 1, 1, 1, 1, 1, true); // c.setValueVector(new double[] { 1 }); // c.setProvision(1); // list.add(c); } protected class Node { protected int index; protected double[] decision; public Node(int index, double value, double[] given) { this.index = index; decision = new double[given.length]; for (int i = 0; i < given.length; i++) { decision[i] = given[i]; } decision[index] = value; } } }
taochen/ssase
adaptable-software/soa/src/main/java/org/soa/ExtendedBB.java
Java
apache-2.0
13,454
/* Copyright 2013 The jeo project. 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 io.jeo.mongo; public class MongoGeoJSONTest extends MongoTest { @Override protected MongoTestData createTestData() { return new GeoJSONTestData(); } }
jeo/jeo
contrib/mongo/src/test/java/io/jeo/mongo/MongoGeoJSONTest.java
Java
apache-2.0
800
// Code generated by go-swagger; DO NOT EDIT. package cluster // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "net/http" "time" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" "github.com/netapp/trident/storage_drivers/ontap/api/rest/models" ) // NewClusterNtpServersCreateParams creates a new ClusterNtpServersCreateParams object, // with the default timeout for this client. // // Default values are not hydrated, since defaults are normally applied by the API server side. // // To enforce default values in parameter, use SetDefaults or WithDefaults. func NewClusterNtpServersCreateParams() *ClusterNtpServersCreateParams { return &ClusterNtpServersCreateParams{ timeout: cr.DefaultTimeout, } } // NewClusterNtpServersCreateParamsWithTimeout creates a new ClusterNtpServersCreateParams object // with the ability to set a timeout on a request. func NewClusterNtpServersCreateParamsWithTimeout(timeout time.Duration) *ClusterNtpServersCreateParams { return &ClusterNtpServersCreateParams{ timeout: timeout, } } // NewClusterNtpServersCreateParamsWithContext creates a new ClusterNtpServersCreateParams object // with the ability to set a context for a request. func NewClusterNtpServersCreateParamsWithContext(ctx context.Context) *ClusterNtpServersCreateParams { return &ClusterNtpServersCreateParams{ Context: ctx, } } // NewClusterNtpServersCreateParamsWithHTTPClient creates a new ClusterNtpServersCreateParams object // with the ability to set a custom HTTPClient for a request. func NewClusterNtpServersCreateParamsWithHTTPClient(client *http.Client) *ClusterNtpServersCreateParams { return &ClusterNtpServersCreateParams{ HTTPClient: client, } } /* ClusterNtpServersCreateParams contains all the parameters to send to the API endpoint for the cluster ntp servers create operation. Typically these are written to a http.Request. */ type ClusterNtpServersCreateParams struct { /* Info. Information specification */ Info *models.NtpServer /* ReturnRecords. The default is false. If set to true, the records are returned. */ ReturnRecordsQueryParameter *bool /* ReturnTimeout. The number of seconds to allow the call to execute before returning. When doing a POST, PATCH, or DELETE operation on a single record, the default is 0 seconds. This means that if an asynchronous operation is started, the server immediately returns HTTP code 202 (Accepted) along with a link to the job. If a non-zero value is specified for POST, PATCH, or DELETE operations, ONTAP waits that length of time to see if the job completes so it can return something other than 202. */ ReturnTimeoutQueryParameter *int64 timeout time.Duration Context context.Context HTTPClient *http.Client } // WithDefaults hydrates default values in the cluster ntp servers create params (not the query body). // // All values with no default are reset to their zero value. func (o *ClusterNtpServersCreateParams) WithDefaults() *ClusterNtpServersCreateParams { o.SetDefaults() return o } // SetDefaults hydrates default values in the cluster ntp servers create params (not the query body). // // All values with no default are reset to their zero value. func (o *ClusterNtpServersCreateParams) SetDefaults() { var ( returnRecordsQueryParameterDefault = bool(false) returnTimeoutQueryParameterDefault = int64(0) ) val := ClusterNtpServersCreateParams{ ReturnRecordsQueryParameter: &returnRecordsQueryParameterDefault, ReturnTimeoutQueryParameter: &returnTimeoutQueryParameterDefault, } val.timeout = o.timeout val.Context = o.Context val.HTTPClient = o.HTTPClient *o = val } // WithTimeout adds the timeout to the cluster ntp servers create params func (o *ClusterNtpServersCreateParams) WithTimeout(timeout time.Duration) *ClusterNtpServersCreateParams { o.SetTimeout(timeout) return o } // SetTimeout adds the timeout to the cluster ntp servers create params func (o *ClusterNtpServersCreateParams) SetTimeout(timeout time.Duration) { o.timeout = timeout } // WithContext adds the context to the cluster ntp servers create params func (o *ClusterNtpServersCreateParams) WithContext(ctx context.Context) *ClusterNtpServersCreateParams { o.SetContext(ctx) return o } // SetContext adds the context to the cluster ntp servers create params func (o *ClusterNtpServersCreateParams) SetContext(ctx context.Context) { o.Context = ctx } // WithHTTPClient adds the HTTPClient to the cluster ntp servers create params func (o *ClusterNtpServersCreateParams) WithHTTPClient(client *http.Client) *ClusterNtpServersCreateParams { o.SetHTTPClient(client) return o } // SetHTTPClient adds the HTTPClient to the cluster ntp servers create params func (o *ClusterNtpServersCreateParams) SetHTTPClient(client *http.Client) { o.HTTPClient = client } // WithInfo adds the info to the cluster ntp servers create params func (o *ClusterNtpServersCreateParams) WithInfo(info *models.NtpServer) *ClusterNtpServersCreateParams { o.SetInfo(info) return o } // SetInfo adds the info to the cluster ntp servers create params func (o *ClusterNtpServersCreateParams) SetInfo(info *models.NtpServer) { o.Info = info } // WithReturnRecordsQueryParameter adds the returnRecords to the cluster ntp servers create params func (o *ClusterNtpServersCreateParams) WithReturnRecordsQueryParameter(returnRecords *bool) *ClusterNtpServersCreateParams { o.SetReturnRecordsQueryParameter(returnRecords) return o } // SetReturnRecordsQueryParameter adds the returnRecords to the cluster ntp servers create params func (o *ClusterNtpServersCreateParams) SetReturnRecordsQueryParameter(returnRecords *bool) { o.ReturnRecordsQueryParameter = returnRecords } // WithReturnTimeoutQueryParameter adds the returnTimeout to the cluster ntp servers create params func (o *ClusterNtpServersCreateParams) WithReturnTimeoutQueryParameter(returnTimeout *int64) *ClusterNtpServersCreateParams { o.SetReturnTimeoutQueryParameter(returnTimeout) return o } // SetReturnTimeoutQueryParameter adds the returnTimeout to the cluster ntp servers create params func (o *ClusterNtpServersCreateParams) SetReturnTimeoutQueryParameter(returnTimeout *int64) { o.ReturnTimeoutQueryParameter = returnTimeout } // WriteToRequest writes these params to a swagger request func (o *ClusterNtpServersCreateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { if err := r.SetTimeout(o.timeout); err != nil { return err } var res []error if o.Info != nil { if err := r.SetBodyParam(o.Info); err != nil { return err } } if o.ReturnRecordsQueryParameter != nil { // query param return_records var qrReturnRecords bool if o.ReturnRecordsQueryParameter != nil { qrReturnRecords = *o.ReturnRecordsQueryParameter } qReturnRecords := swag.FormatBool(qrReturnRecords) if qReturnRecords != "" { if err := r.SetQueryParam("return_records", qReturnRecords); err != nil { return err } } } if o.ReturnTimeoutQueryParameter != nil { // query param return_timeout var qrReturnTimeout int64 if o.ReturnTimeoutQueryParameter != nil { qrReturnTimeout = *o.ReturnTimeoutQueryParameter } qReturnTimeout := swag.FormatInt64(qrReturnTimeout) if qReturnTimeout != "" { if err := r.SetQueryParam("return_timeout", qReturnTimeout); err != nil { return err } } } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
NetApp/trident
storage_drivers/ontap/api/rest/client/cluster/cluster_ntp_servers_create_parameters.go
GO
apache-2.0
7,672
/** * @module utils */ const crypto = require( 'crypto' ); const config = require( '../models/config-model' ).server; const validUrl = require( 'valid-url' ); // var debug = require( 'debug' )( 'utils' ); /** * Returns a unique, predictable openRosaKey from a survey oject * * @static * @param {module:survey-model~SurveyObject} survey * @param {string} [prefix] * @return {string|null} openRosaKey */ function getOpenRosaKey( survey, prefix ) { if ( !survey || !survey.openRosaServer || !survey.openRosaId ) { return null; } prefix = prefix || 'or:'; // Server URL is not case sensitive, form ID is case-sensitive return `${prefix + cleanUrl( survey.openRosaServer )},${survey.openRosaId.trim()}`; } /** * Returns a XForm manifest hash. * * @static * @param {Array} manifest * @param {string} type - Webform type * @return {string} Hash */ function getXformsManifestHash( manifest, type ) { const hash = ''; if ( !manifest || manifest.length === 0 ) { return hash; } if ( type === 'all' ) { return md5( JSON.stringify( manifest ) ); } if ( type ) { const filtered = manifest.map( mediaFile => mediaFile[ type ] ); return md5( JSON.stringify( filtered ) ); } return hash; } /** * Cleans a Server URL so it becomes useful as a db key * It strips the protocol, removes a trailing slash, removes www, and converts to lowercase * * @static * @param {string} url - Url to be cleaned up * @return {string} Cleaned up url */ function cleanUrl( url ) { url = url.trim(); if ( url.lastIndexOf( '/' ) === url.length - 1 ) { url = url.substring( 0, url.length - 1 ); } const matches = url.match( /https?:\/\/(www\.)?(.+)/ ); if ( matches && matches.length > 2 ) { return matches[ 2 ].toLowerCase(); } return url; } /** * The name of this function is deceiving. It checks for a valid server URL and therefore doesn't approve of: * - fragment identifiers * - query strings * * @static * @param {string} url - Url to be validated * @return {boolean} Whether the url is valid */ function isValidUrl( url ) { return !!validUrl.isWebUri( url ) && !( /\?/.test( url ) ) && !( /#/.test( url ) ); } /** * Returns md5 hash of given message * * @static * @param {string} message - Message to be hashed * @return {string} Hash string */ function md5( message ) { const hash = crypto.createHash( 'md5' ); hash.update( message ); return hash.digest( 'hex' ); } /** * This is not secure encryption as it doesn't use a random cipher. Therefore the result is * always the same for each text & pw (which is desirable in this case). * This means the password is vulnerable to be cracked, * and we should use a dedicated low-importance password for this. * * @static * @param {string} text - The text to be encrypted * @param {string} pw - The password to use for encryption * @return {string} The encrypted result */ function insecureAes192Encrypt( text, pw ) { let encrypted; const cipher = crypto.createCipher( 'aes192', pw ); encrypted = cipher.update( text, 'utf8', 'hex' ); encrypted += cipher.final( 'hex' ); return encrypted; } /** * Decrypts encrypted text. * * @static * @param {*} encrypted - The text to be decrypted * @param {*} pw - The password to use for decryption * @return {string} The decrypted result */ function insecureAes192Decrypt( encrypted, pw ) { let decrypted; const decipher = crypto.createDecipher( 'aes192', pw ); decrypted = decipher.update( encrypted, 'hex', 'utf8' ); decrypted += decipher.final( 'utf8' ); return decrypted; } /** * Returns random howMany-lengthed string from provided characters. * * @static * @param {number} [howMany] - Desired length of string * @param {string} [chars] - Characters to use * @return {string} Random string */ function randomString( howMany = 8, chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ) { const rnd = crypto.randomBytes( howMany ); return new Array( howMany ) .fill() // create indices, so map can iterate .map( ( val, i ) => chars[ rnd[ i ] % chars.length ] ) .join( '' ); } /** * Returns random item from array. * * @static * @param {Array} array - Target array * @return {*|null} Random array item */ function pickRandomItemFromArray( array ) { if ( !Array.isArray( array ) || array.length === 0 ) { return null; } const random = Math.floor( Math.random() * array.length ); if ( !array[ random ] ) { return null; } return array[ random ]; } /** * Compares two objects by shallow properties. * * @static * @param {object} a - First object to be compared * @param {object} b - Second object to be compared * @return {null|boolean} Whether objects are equal (`null` for invalid arguments) */ function areOwnPropertiesEqual( a, b ) { let prop; const results = []; if ( typeof a !== 'object' || typeof b !== 'object' ) { return null; } for ( prop in a ) { if ( Object.prototype.hasOwnProperty.call( a, prop ) ) { if ( a[ prop ] !== b[ prop ] ) { return false; } results[ prop ] = true; } } for ( prop in b ) { if ( !results[ prop ] && Object.prototype.hasOwnProperty.call( b, prop ) ) { if ( b[ prop ] !== a[ prop ] ) { return false; } } } return true; } /** * Converts a url to a local (proxied) url. * * @static * @param {string} url - The url to convert * @return {string} The converted url */ function toLocalMediaUrl( url ) { const localUrl = `${config[ 'base path' ]}/media/get/${url.replace( /(https?):\/\//, '$1/' )}`; return localUrl; } module.exports = { getOpenRosaKey, getXformsManifestHash, cleanUrl, isValidUrl, md5, randomString, pickRandomItemFromArray, areOwnPropertiesEqual, insecureAes192Decrypt, insecureAes192Encrypt, toLocalMediaUrl };
kobotoolbox/enketo-express
app/lib/utils.js
JavaScript
apache-2.0
6,115
package org.spanna.reflect; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; public interface ReflectiveObject { public boolean locate(ClassReader cr); public boolean initializeReference(); public String getName(); public String getObfuscatedName(); public boolean isInitialized(); public boolean isFound(); }
SpannaProject/SpannaAPI
src/main/java/org/spanna/reflect/ReflectiveObject.java
Java
apache-2.0
371
package org.neotech.library.retainabletasks.internal; import androidx.annotation.RestrictTo; import org.neotech.library.retainabletasks.TaskManager; /** * Created by Rolf on 4-3-2016. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public class TaskRetainingFragmentLogic { private final BaseTaskManager taskManager = new BaseTaskManager(); public BaseTaskManager getTaskManager(){ return taskManager; } public void assertActivityTasksAreDetached(){ if(!TaskManager.isStrictDebugModeEnabled()){ return; } taskManager.assertAllTasksDetached(); } }
NeoTech-Software/Android-Retainable-Tasks
library/src/main/java/org/neotech/library/retainabletasks/internal/TaskRetainingFragmentLogic.java
Java
apache-2.0
618
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.phearom.um.playback; import android.content.res.Resources; import android.graphics.Bitmap; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.session.MediaSessionCompat; import com.phearom.um.AlbumArtCache; import com.phearom.um.R; import com.phearom.um.model.MusicProvider; import com.phearom.um.model.MyMusicProvider; import com.phearom.um.utils.LogHelper; import com.phearom.um.utils.MediaIDHelper; import com.phearom.um.utils.QueueHelper; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Simple data provider for queues. Keeps track of a current queue and a current index in the * queue. Also provides methods to set the current queue based on common queries, relying on a * given MusicProvider to provide the actual media metadata. */ public class QueueManager { private static final String TAG = LogHelper.makeLogTag(QueueManager.class); private MyMusicProvider mMusicProvider; private MetadataUpdateListener mListener; private Resources mResources; // "Now playing" queue: private List<MediaSessionCompat.QueueItem> mPlayingQueue; private int mCurrentIndex; public QueueManager(@NonNull MyMusicProvider musicProvider, @NonNull Resources resources, @NonNull MetadataUpdateListener listener) { this.mMusicProvider = musicProvider; this.mListener = listener; this.mResources = resources; mPlayingQueue = Collections.synchronizedList(new ArrayList<MediaSessionCompat.QueueItem>()); mCurrentIndex = 0; } public boolean isSameBrowsingCategory(@NonNull String mediaId) { String[] newBrowseHierarchy = MediaIDHelper.getHierarchy(mediaId); MediaSessionCompat.QueueItem current = getCurrentMusic(); if (current == null) { return false; } String[] currentBrowseHierarchy = MediaIDHelper.getHierarchy( current.getDescription().getMediaId()); return Arrays.equals(newBrowseHierarchy, currentBrowseHierarchy); } private void setCurrentQueueIndex(int index) { if (index >= 0 && index < mPlayingQueue.size()) { mCurrentIndex = index; mListener.onCurrentQueueIndexUpdated(mCurrentIndex); } } public boolean setCurrentQueueItem(long queueId) { // set the current index on queue from the queue Id: int index = QueueHelper.getMusicIndexOnQueue(mPlayingQueue, queueId); setCurrentQueueIndex(index); return index >= 0; } public boolean setCurrentQueueItem(String mediaId) { // set the current index on queue from the music Id: int index = QueueHelper.getMusicIndexOnQueue(mPlayingQueue, mediaId); setCurrentQueueIndex(index); return index >= 0; } public boolean skipQueuePosition(int amount) { int index = mCurrentIndex + amount; if (index < 0) { // skip backwards before the first song will keep you on the first song index = 0; } else { // skip forwards when in last song will cycle back to start of the queue index %= mPlayingQueue.size(); } if (!QueueHelper.isIndexPlayable(index, mPlayingQueue)) { LogHelper.e(TAG, "Cannot increment queue index by ", amount, ". Current=", mCurrentIndex, " queue length=", mPlayingQueue.size()); return false; } mCurrentIndex = index; return true; } public boolean setQueueFromSearch(String query, Bundle extras) { List<MediaSessionCompat.QueueItem> queue = QueueHelper.getPlayingQueueFromSearch(query, extras, mMusicProvider); setCurrentQueue(mResources.getString(R.string.search_queue_title), queue); return queue != null && !queue.isEmpty(); } public void setRandomQueue() { setCurrentQueue(mResources.getString(R.string.random_queue_title), QueueHelper.getRandomQueue(mMusicProvider)); } public void setQueueFromMusic(String mediaId) { LogHelper.d(TAG, "setQueueFromMusic", mediaId); // The mediaId used here is not the unique musicId. This one comes from the // MediaBrowser, and is actually a "hierarchy-aware mediaID": a concatenation of // the hierarchy in MediaBrowser and the actual unique musicID. This is necessary // so we can build the correct playing queue, based on where the track was // selected from. boolean canReuseQueue = false; if (isSameBrowsingCategory(mediaId)) { canReuseQueue = setCurrentQueueItem(mediaId); } if (!canReuseQueue) { String queueTitle = mResources.getString(R.string.browse_musics_by_genre_subtitle, MediaIDHelper.extractBrowseCategoryValueFromMediaID(mediaId)); setCurrentQueue(queueTitle, QueueHelper.getPlayingQueue(mediaId, mMusicProvider), mediaId); } updateMetadata(); } public MediaSessionCompat.QueueItem getCurrentMusic() { if (!QueueHelper.isIndexPlayable(mCurrentIndex, mPlayingQueue)) { return null; } return mPlayingQueue.get(mCurrentIndex); } public int getCurrentQueueSize() { if (mPlayingQueue == null) { return 0; } return mPlayingQueue.size(); } protected void setCurrentQueue(String title, List<MediaSessionCompat.QueueItem> newQueue) { setCurrentQueue(title, newQueue, null); } protected void setCurrentQueue(String title, List<MediaSessionCompat.QueueItem> newQueue, String initialMediaId) { mPlayingQueue = newQueue; int index = 0; if (initialMediaId != null) { index = QueueHelper.getMusicIndexOnQueue(mPlayingQueue, initialMediaId); } mCurrentIndex = Math.max(index, 0); mListener.onQueueUpdated(title, newQueue); } public void updateMetadata() { MediaSessionCompat.QueueItem currentMusic = getCurrentMusic(); if (currentMusic == null) { mListener.onMetadataRetrieveError(); return; } final String musicId = MediaIDHelper.extractMusicIDFromMediaID( currentMusic.getDescription().getMediaId()); MediaMetadataCompat metadata = mMusicProvider.getMusic(musicId); if (metadata == null) { throw new IllegalArgumentException("Invalid musicId " + musicId); } mListener.onMetadataChanged(metadata); // Set the proper album artwork on the media session, so it can be shown in the // locked screen and in other places. if (metadata.getDescription().getIconBitmap() == null && metadata.getDescription().getIconUri() != null) { String albumUri = metadata.getDescription().getIconUri().toString(); AlbumArtCache.getInstance().fetch(albumUri, new AlbumArtCache.FetchListener() { @Override public void onFetched(String artUrl, Bitmap bitmap, Bitmap icon) { mMusicProvider.updateMusicArt(musicId, bitmap, icon); // If we are still playing the same music, notify the listeners: MediaSessionCompat.QueueItem currentMusic = getCurrentMusic(); if (currentMusic == null) { return; } String currentPlayingId = MediaIDHelper.extractMusicIDFromMediaID( currentMusic.getDescription().getMediaId()); if (musicId.equals(currentPlayingId)) { mListener.onMetadataChanged(mMusicProvider.getMusic(currentPlayingId)); } } }); } } public interface MetadataUpdateListener { void onMetadataChanged(MediaMetadataCompat metadata); void onMetadataRetrieveError(); void onCurrentQueueIndexUpdated(int queueIndex); void onQueueUpdated(String title, List<MediaSessionCompat.QueueItem> newQueue); } }
povphearom/UMusicPlayer
app/src/main/java/com/phearom/um/playback/QueueManager.java
Java
apache-2.0
8,980
# # Cookbook Name:: tabelle # Recipe:: default # # Copyright 2016, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute #
pimu/chef-repo
cookbooks/tabelle/recipes/default.rb
Ruby
apache-2.0
133
// Copyright 2017 Jose Luis Rovira Martin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; namespace Essence.Util.Collections.Iterators { public struct ListIt<TValue> { public ListIt(IList<TValue> list, int i = 0) { this.list = list; this.i = i; } public static bool operator ==(ListIt<TValue> it1, ListIt<TValue> it2) { return it1.i == it2.i; } public static bool operator !=(ListIt<TValue> it1, ListIt<TValue> it2) { return it1.i != it2.i; } public void Inc(int c) { this.i += c; } public void Inc() { this.i++; } public void Dec() { this.i--; } public TValue Get() { return this.list[this.i]; } #region private private readonly IList<TValue> list; private int i; #endregion #region object public override bool Equals(object obj) { if (!(obj is ListIt<TValue>)) { return false; } ListIt<TValue> other = (ListIt<TValue>)obj; return this.i == other.i; } public override int GetHashCode() { return this.i.GetHashCode(); } public override string ToString() { return this.i.ToString(); } #endregion } }
jlroviramartin/Essence
Essence.Util/Collections/Iterators/ListIt.cs
C#
apache-2.0
2,147
/* * Copyright 2015 Open Networking Laboratory * * 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.onosproject.driver.query; import java.util.Set; import java.util.stream.IntStream; import org.onlab.packet.VlanId; import org.onlab.util.GuavaCollectors; import org.onosproject.net.PortNumber; import org.onosproject.net.behaviour.VlanQuery; import org.onosproject.net.driver.AbstractHandlerBehaviour; import com.google.common.annotations.Beta; /** * Driver which always responds that all VLAN IDs are available for the Device. */ @Beta public class FullVlanAvailable extends AbstractHandlerBehaviour implements VlanQuery { private static final int MAX_VLAN_ID = VlanId.MAX_VLAN; private static final Set<VlanId> ENTIRE_VLAN = getEntireVlans(); @Override public Set<VlanId> queryVlanIds(PortNumber port) { return ENTIRE_VLAN; } private static Set<VlanId> getEntireVlans() { return IntStream.range(0, MAX_VLAN_ID) .mapToObj(x -> VlanId.vlanId((short) x)) .collect(GuavaCollectors.toImmutableSet()); } }
sonu283304/onos
drivers/default/src/main/java/org/onosproject/driver/query/FullVlanAvailable.java
Java
apache-2.0
1,617
<?php $cs = Yii::app()->getClientScript(); $cssAnsScriptFilesModule = array( '/assets/css/rooms/header.css' ); HtmlHelper::registerCssAndScriptsFiles($cssAnsScriptFilesModule, Yii::app()->theme->baseUrl); $cssAnsScriptFilesModule = array( // '/survey/css/mixitup/reset.css', '/js/actionRooms/actionRooms.js' ); HtmlHelper::registerCssAndScriptsFiles($cssAnsScriptFilesModule, $this->module->assetsUrl); ?> <style> .assemblyHeadSection { <?php $bg = (@$archived) ? "assemblyParisDayArchived" : "assemblyParisDay";?> /*background-image:url(<?php echo $this->module->assetsUrl; ?>/images/city/<?php echo $bg; ?>.jpg); */ background-image:url(<?php echo $this->module->assetsUrl; ?>/images/city/dda-connexion-lines.jpg); background-repeat: no-repeat !important; background-size: 100% 400px !important; background-position: 0px 0px !important; } .bgDDA .modal .modal-header{ background-image:url(<?php echo $this->module->assetsUrl; ?>/images/city/dda-connexion-lines.jpg); background-repeat: no-repeat !important; background-size: auto; } .contentProposal{ background-color: white; } .header-parent-space{ margin: -15px 10px; padding: 15px 8px 8px; border-radius: 7px 7px 0px 0px; background-color: rgba(255, 255, 255, 0); } #room-container{ min-height:300px; } .btn-select-room{ margin-top: 5px; border: none; font-size: 20px; font-weight: 200; width: 100%; text-align: center; border-radius:100px; } .btn-select-room.bg-dark:hover{ background-color:#58829B !important; } .modal .room-item{ width:100%; padding:15px; font-size:16px; border-bottom:1px solid #DBDBDB; border-top:1px solid rgba(230, 230, 230, 0); float:left; } .modal .room-item:hover{ background-color: rgb(230, 230, 230) !important; border-top:1px solid rgb(192, 192, 192); } .title-conseil-citoyen { background-color: rgba(255, 255, 255, 0); margin: 0px; padding: 10px; border-radius: 12px; -moz-box-shadow: 0px 3px 10px 1px #656565; -webkit-box-shadow: 0px 3px 10px 1px #656565; -o-box-shadow: 0px 3px 10px 1px #656565; box-shadow: 0px 3px 10px 1px rgb(101, 101, 101); margin-bottom: 10px; } .link-tools a:hover{ text-decoration: underline; } .fileupload-new.thumbnail{ width:unset; } h1.citizenAssembly-header { font-size: 30px; } .img-room-modal img{ max-width: 35px; margin-top: -5px; margin-right: 10px; border-radius: 4px; } #room-container .badge-danger { margin-bottom: 2px; margin-left: 2px; } </style> <h1 class="text-dark citizenAssembly-header"> <?php $urlPhotoProfil = ""; if(!@$parent){ if($parentType == Project::COLLECTION) { $parent = Project::getById($parentId); } if($parentType == Organization::COLLECTION) { $parent = Organization::getById($parentId); } if($parentType == Person::COLLECTION) { $parent = Person::getById($parentId); } if($parentType == City::COLLECTION) { $parent = City::getByUnikey($parentId); } } if(isset($parent['profilImageUrl']) && $parent['profilImageUrl'] != ""){ $urlPhotoProfil = Yii::app()->getRequest()->getBaseUrl(true).$parent['profilImageUrl']; } // else{ // if($parentType == Person::COLLECTION) // $urlPhotoProfil = $this->module->assetsUrl.'/images/thumb/project-default-image.png'; // if($parentType == Organization::COLLECTION) // $urlPhotoProfil = $this->module->assetsUrl.'/images/thumb/orga-default-image.png'; // if($parentType == Project::COLLECTION) // $urlPhotoProfil = $this->module->assetsUrl.'/images/thumb/default.png'; // } $icon = "comments"; $colorName = "dark"; if($parentType == Project::COLLECTION) { $icon = "lightbulb-o"; $colorName = "purple"; } if($parentType == Organization::COLLECTION) { $icon = "group"; $colorName = "green"; } if($parentType == Person::COLLECTION) { $icon = "user"; $colorName = "dark"; } if($parentType == City::COLLECTION) { $icon = "university"; $colorName = "red"; } ?> <?php //création de l'url sur le nom du parent $urlParent = Element::getControlerByCollection($parentType).".detail.id.".$parentId; if($parentType == City::COLLECTION) $urlParent = Element::getControlerByCollection($parentType).".detail.insee.".$parent["insee"].".postalCode.".$parent["cp"]; ?> <div class="row header-parent-space"> <?php if($parentType != City::COLLECTION && $urlPhotoProfil != ""){ ?> <div class="col-md-3 col-sm-3 col-xs-12 center"> <img class="thumbnail img-responsive" id="thumb-profil-parent" src="<?php echo $urlPhotoProfil; ?>" alt="image" > </div> <?php }else if($parentType == City::COLLECTION){ ?> <div class="col-md-3 col-sm-3 col-xs-12 center"> <h1 class="homestead title-conseil-citoyen center text-red"><i class="fa fa-group"></i><br>Conseil Citoyen</h1> </div> <?php } ?> <?php if($parentType == City::COLLECTION || $urlPhotoProfil != "") $colSize="9"; else $colSize="12"; ?> <div class="col-md-<?php echo $colSize; ?> col-sm-<?php echo $colSize; ?>"> <div class="col-md-12 no-padding margin-bottom-15"> <a href="javascript:loadByHash('#<?php echo $urlParent; ?>');" class="text-<?php echo $colorName; ?> homestead"> <i class="fa fa-<?php echo $icon; ?>"></i> <?php if($parentType == City::COLLECTION) echo "Commune de "; echo $parent['name']; ?> </a> </div> <?php if(!@$mainPage){ $rooms = ActionRoom::getAllRoomsByTypeId($parentType, $parentId); $discussions = $rooms["discussions"]; $votes = $rooms["votes"]; $actions = $rooms["actions"]; $history = $rooms["history"]; } ?> <div class="col-md-4 no-padding"> <button type="button" class="btn btn-default bg-dark btn-select-room" data-toggle="modal" data-target="#modal-select-room1"> <i class="fa fa-comments"></i> Discuter <span class="badge"><?php if(@$discussions) echo count($discussions); else echo "0"; ?></span> </button><br> </div> <div class="col-md-4"> <button type="button" class="btn btn-default bg-dark btn-select-room" data-toggle="modal" data-target="#modal-select-room2"> <i class="fa fa-archive"></i> Décider <span class="badge"><?php if(@$votes) echo count($votes); else echo "0"; ?></span> </button><br> </div> <div class="col-md-4 no-padding"> <button type="button" class="btn btn-default bg-dark btn-select-room" data-toggle="modal" data-target="#modal-select-room3"> <i class="fa fa-cogs"></i> Agir <span class="badge"><?php if(@$actions) echo count($actions); else echo "0"; ?></span> </button> </div> <div class="col-md-12 margin-top-15 link-tools"> <a href="javascript:showRoom('all', '<?php echo $parentId; ?>')" class="pull-left text-dark" style="font-size:15px;"><i class="fa fa-list"></i> Afficher tout</a> <?php if(@$_GET["archived"] == null){ ?> <a href="javascript:loadByHash(location.hash+'.archived.1')" class="pull-left text-red" style="font-size:15px;margin-left:30px;"><i class="fa fa-times"></i> Archives</a> <?php } ?> <?php //if(@$history && !empty($history)){ ?> <a href="javascript:" class="pull-right text-dark" style="font-size:15px;" data-toggle="modal" data-target="#modal-select-room4"> <i class="fa fa-clock-o"></i> Mon historique </a> <?php //} ?> </div> <div class="col-md-12 no-padding" style="margin: 15px 0 15px 0 !important;"> <?php $btnLbl = "<i class='fa fa-sign-in'></i> ".Yii::t("rooms","JOIN TO PARTICIPATE", null, Yii::app()->controller->module->id); $ctrl = Element::getControlerByCollection($parentType); $btnUrl = "loadByHash('#".$ctrl.".detail.id.".$parentId."')"; if( $parentType == City::COLLECTION || ($parentType != Person::COLLECTION && Authorisation::canParticipate(Yii::app()->session['userId'],$parentType,$parentId) )) { $btnLbl = "<i class='fa fa-plus'></i> ".Yii::t("rooms","Add an Action Room", null, Yii::app()->controller->module->id); $btnUrl = "loadByHash('#rooms.editroom.type.".$parentType.".id.".$parentId."')"; } if(!isset(Yii::app()->session['userId'])){ $btnLbl = "<i class='fa fa-sign-in'></i> ".Yii::t("rooms","LOGIN TO PARTICIPATE", null, Yii::app()->controller->module->id); $btnUrl = "showPanel('box-login');"; } $addBtn = ( $parentType != Person::COLLECTION ) ? ' <i class="fa fa-angle-right"></i> <a class="filter btn btn-xs btn-primary Helvetica" href="javascript:;" onclick="'.$btnUrl.'">'.$btnLbl.'</a>' : ""; ?> <!-- <span class="breadscrum"> <a class='text-dark' href='javascript:loadByHash("#rooms.index.type.<?php //echo $parentType ?>.id.<?php //echo $parentId ?>.tab.1")'> <i class="fa fa-connectdevelop"></i> <?php //echo Yii::t("rooms","Action Rooms", null, Yii::app()->controller->module->id) ?> </a> <?php //if( $parentType != Person::COLLECTION ){ // echo (@$textTitle) ? "/ ".$textTitle : // ' <i class="fa fa-angle-right"></i> <a class="filter btn btn-default Helvetica" href="javascript:;" onclick="'.$btnUrl.'">'.$btnLbl.'</a>'; //} ?> </span> --> </div> </div> </h1> <?php if( isset(Yii::app()->session['userId']) && Authorisation::canParticipate(Yii::app()->session['userId'], $parentType, $parentId ) ){ ?> <div class="modal fade" id="modal-create-room" tabindex="-1" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header text-dark"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h2 class="modal-title text-left"> <i class="fa fa-angle-down"></i> <i class="fa fa-plus"></i> Créer un espace </h2> </div> <div class="modal-body no-padding"> <div class="panel-body" id="form-create-room"> <?php $listRoomTypes = Lists::getListByName("listRoomTypes"); foreach ($listRoomTypes as $key => $value) { //error_log("translate ".$value); $listRoomTypes[$key] = Yii::t("rooms",$value, null, Yii::app()->controller->module->id); } $tagsList = Lists::getListByName("tags"); $params = array( "listRoomTypes" => $listRoomTypes, "tagsList" => $tagsList, "id" => $parentId, "type" => $parentType ); $this->renderPartial('../rooms/editRoomSV', $params); ?> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button> <button type="button" class="btn btn-success" onclick="javascript:saveNewRoom();"> <i class="fa fa-save"></i> Enregistrer </button> </div> </div> </div> </div> </div> <?php } ?> <?php createModalRoom($discussions,$parentType, $parentId, 1, "Sélectionnez un espace de discussion", "comments", "discuss", "Aucun espace de discussion"); createModalRoom($votes,$parentType, $parentId, 2, "Sélectionnez un espace de décision", "archive", "vote", "Aucun espace de décision"); createModalRoom($actions,$parentType, $parentId, 3, "Sélectionnez un espace d'action", "cogs", "actions", "Aucun espace d'action"); createModalRoom($history,$parentType, $parentId, 4, "Historique de votre activité", "clock-o", "history", "Aucune activité"); //$where = Yii::app()->controller->id.'.'.Yii::app()->controller->action->id; //if( in_array($where, array("rooms.action","survey.entry"))){ createModalRoom( array_merge($votes,$actions) ,$parentType, $parentId, 5, "Choisir un nouvel espace", "share-alt", "move", "Aucun espace","move",$faTitle); //} function createModalRoom($elements, $parentType, $parentId, $index, $title, $icon, $typeNew, $endLbl,$action=null,$context=null){ $iconType = array("discuss"=>"comments", "entry" => "archive", "actions" => "cogs"); echo '<div class="panel panel-default no-margin">'; echo '<div class="modal fade" id="modal-select-room'.$index.'" tabindex="-1" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header text-dark"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h2 class="modal-title text-left"> <i class="fa fa-angle-down"></i> <i class="fa fa-'.$icon.'"></i> <span class="">'.$title.' <span class="badge">'.count($elements).'</span> </h2> </div> <div class="modal-body no-padding"> <div class="panel-body no-padding">'; if(!empty($elements)) foreach ($elements as $key => $value) { if(isset($value["_id"])) { $created = ( @$value["created"] ) ? date("d/m/y h:i",$value["created"]) : ""; //if($typeNew == "history") var_dump($value); error_log($value["type"]); if($typeNew == "history" && @$value["type"]){ //error_log($value["type"]); $type = $value["type"]; if(@$iconType[$type]) $icon = $iconType[$type]; } $col = Survey::COLLECTION; $attr = 'survey'; if( @$value["type"] == ActionRoom::TYPE_ACTIONS ){ $col = ActionRoom::TYPE_ACTIONS; $attr = 'room'; } $onclick = 'showRoom(\''.$typeNew.'\', \''.(string)$value["_id"].'\')'; $skip = false; if( $action == "move"){ $icon = ($value["type"] == ActionRoom::TYPE_ACTIONS) ? "cogs" : "archive"; $type = ($context == "cogs") ? "action" : "survey"; $onclick = 'move(\''.$type.'\', \''.(string)$value["_id"].'\')'; //remove the current context room destination //if((string)$value["_id"] == ) //we are missing the current room object in header } $imgIcon = ''; if(isset($value['profilImageUrl']) && $value['profilImageUrl'] != ""){ $urlPhotoProfil = Yii::app()->getRequest()->getBaseUrl(true).$value['profilImageUrl']; $imgIcon = '<img src="'.$urlPhotoProfil.'">'; } $count = 0; if( @$value["type"] == ActionRoom::TYPE_VOTE ) $count = PHDB::count(Survey::COLLECTION,array("survey"=>(string)$value["_id"])); else if( @$value["type"] == ActionRoom::TYPE_ACTIONS ) $count = PHDB::count(Survey::COLLECTION,array("room"=>(string)$value["_id"])); else if( @$value["type"] == ActionRoom::TYPE_DISCUSS ) $count = (empty($value["commentCount"])?0:$value["commentCount"]); if(!$skip){ echo '<a href="javascript:" onclick="'.$onclick.'" class="text-dark room-item" data-dismiss="modal">'. '<i class="fa fa-angle-right"></i> <i class="fa fa-'.$icon.'"></i> '.$value["name"]. " <span class='badge badge-success pull-right'>". $count. //PHDB::count($col,array($attr=>(string)$value["_id"])). "</span>". " <span class='pull-right img-room-modal'>". $imgIcon. "</span>". '</a>'; } } } if(empty($elements)) echo '<div class="panel-body "><i class="fa fa-times"></i> '.$endLbl.'</div>'; echo '</div>'; echo '</div>'; echo '<div class="modal-footer">'; if($typeNew != "history" && $typeNew != "move" && Authorisation::canParticipate(Yii::app()->session['userId'],$parentType,$parentId) ) echo '<button type="button" class="btn btn-default pull-left" onclick="javascript:selectRoomType(\''.$typeNew.'\')" data-dismiss="modal" data-toggle="modal" data-target="#modal-create-room">'. '<i class="fa fa-plus"></i> <i class="fa fa-'.$icon.'"></i> Créer un nouvel espace'. '</button>'; echo '<button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>'; echo '</div>'; echo '</div>'; echo '</div>'; echo '</div>'; echo '</div>'; } ?> <script type="text/javascript"> jQuery(document).ready(function() { $('#form-create-room #btn-submit-form').addClass("hidden"); }); function saveNewRoom(){ $('#form-create-room #btn-submit-form').click(); } function selectRoomType(type){ mylog.log("selectRoomType",type); $("#roomType").val(type); var msg = "Nouvel espace"; if(type=="discuss") msg = "<i class='fa fa-comments'></i> " + msg + " de discussion"; if(type=="framapad") msg = "<i class='fa fa-file-text-o'></i> " + msg + " framapad"; if(type=="vote") msg = "<i class='fa fa-gavel'></i> " + msg + " de décision"; if(type=="actions") msg = "<i class='fa fa-cogs'></i> Nouvelle Liste d'actions"; $("#proposerloiFormLabel").html(msg); $("#proposerloiFormLabel").addClass("text-dark"); // $("#btn-submit-form").html('<?php echo Yii::t("common", "Submit"); ?> <i class="fa fa-arrow-circle-right"></i>'); //$("#first-step-create-space").hide(400); $(".roomTypeselect").addClass("hidden"); } function showRoom(type, id){ var mapUrl = { "all": { "url" : "rooms/index/type/<?php echo $parentType; ?>", "hash" : "rooms.index.type.<?php echo $parentType; ?>" } , "discuss": { "url" : "comment/index/type/actionRooms", "hash" : "comment.index.type.actionRooms" } , "vote": { "url" : "survey/entries", "hash" : "survey.entries" } , "entry" : { "url" : "survey/entry", "hash" : "survey.entry", }, "actions": { "url" : "rooms/actions", "hash" : "rooms.actions" } , "action": { "url" : "rooms/action", "hash" : "rooms.action", } } var url = mapUrl[type]["url"]+"/id/"+id; var hash = mapUrl[type]["hash"]+".id."+id; $("#room-container").hide(200); $.blockUI({ message : "<h4 style='font-weight:300' class='text-dark padding-10'><i class='fa fa-spin fa-circle-o-notch'></i><br>Chargement en cours ...</span></h4>" }); getAjax('#room-container',baseUrl+'/'+moduleId+'/'+url+"?renderPartial=true", function(){ history.pushState(null, "New Title", "communecter#" + hash); $("#room-container").show(200); $.unblockUI(); },"html"); } </script>
pixelhumain/communecter
views/rooms/header.php
PHP
apache-2.0
18,400
/* * 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.ignite.internal.processors.cache; import java.nio.ByteBuffer; import javax.cache.processor.EntryProcessor; import javax.cache.processor.MutableEntry; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.internal.GridDirectTransient; import org.apache.ignite.internal.util.tostring.GridToStringInclude; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.plugin.extensions.communication.Message; import org.apache.ignite.plugin.extensions.communication.MessageReader; import org.apache.ignite.plugin.extensions.communication.MessageWriter; import org.jetbrains.annotations.Nullable; /** * */ public class CacheInvokeDirectResult implements Message { /** */ private static final long serialVersionUID = 0L; /** */ private KeyCacheObject key; /** */ @GridToStringInclude private transient Object unprepareRes; /** */ @GridToStringInclude private CacheObject res; /** */ @GridToStringInclude(sensitive = true) @GridDirectTransient private Exception err; /** */ private byte[] errBytes; /** * Required for {@link Message}. */ public CacheInvokeDirectResult() { // No-op. } /** * @param key Key. * @param res Result. */ public CacheInvokeDirectResult(KeyCacheObject key, CacheObject res) { this.key = key; this.res = res; } /** * Constructs CacheInvokeDirectResult with unprepared res, to avoid object marshaling while holding topology locks. * * @param key Key. * @param res Result. * @return a new instance of CacheInvokeDirectResult. */ static CacheInvokeDirectResult lazyResult(KeyCacheObject key, Object res) { CacheInvokeDirectResult res0 = new CacheInvokeDirectResult(); res0.key = key; res0.unprepareRes = res; return res0; } /** * @param key Key. * @param err Exception thrown by {@link EntryProcessor#process(MutableEntry, Object...)}. */ public CacheInvokeDirectResult(KeyCacheObject key, Exception err) { this.key = key; this.err = err; } /** * @return Key. */ public KeyCacheObject key() { return key; } /** * @return Result. */ public CacheObject result() { return res; } /** * @return Error. */ @Nullable public Exception error() { return err; } /** * @param ctx Cache context. * @throws IgniteCheckedException If failed. */ public void prepareMarshal(GridCacheContext ctx) throws IgniteCheckedException { key.prepareMarshal(ctx.cacheObjectContext()); if (err != null && errBytes == null) { try { errBytes = U.marshal(ctx.marshaller(), err); } catch (IgniteCheckedException e) { // Try send exception even if it's unable to marshal. IgniteCheckedException exc = new IgniteCheckedException(err.getMessage()); exc.setStackTrace(err.getStackTrace()); exc.addSuppressed(e); errBytes = U.marshal(ctx.marshaller(), exc); } } if (unprepareRes != null) { res = ctx.toCacheObject(unprepareRes); unprepareRes = null; } if (res != null) res.prepareMarshal(ctx.cacheObjectContext()); } /** * @param ctx Cache context. * @param ldr Class loader. * @throws IgniteCheckedException If failed. */ public void finishUnmarshal(GridCacheContext ctx, ClassLoader ldr) throws IgniteCheckedException { key.finishUnmarshal(ctx.cacheObjectContext(), ldr); if (errBytes != null && err == null) err = U.unmarshal(ctx.marshaller(), errBytes, U.resolveClassLoader(ldr, ctx.gridConfig())); if (res != null) res.finishUnmarshal(ctx.cacheObjectContext(), ldr); } /** {@inheritDoc} */ @Override public void onAckReceived() { // No-op. } /** {@inheritDoc} */ @Override public short directType() { return 93; } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeByteArray("errBytes", errBytes)) return false; writer.incrementState(); case 1: if (!writer.writeMessage("key", key)) return false; writer.incrementState(); case 2: if (!writer.writeMessage("res", res)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; switch (reader.state()) { case 0: errBytes = reader.readByteArray("errBytes"); if (!reader.isLastRead()) return false; reader.incrementState(); case 1: key = reader.readMessage("key"); if (!reader.isLastRead()) return false; reader.incrementState(); case 2: res = reader.readMessage("res"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(CacheInvokeDirectResult.class); } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 3; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(CacheInvokeDirectResult.class, this); } }
sk0x50/ignite
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheInvokeDirectResult.java
Java
apache-2.0
7,063
<?php // +---------------------------------------------------------------------- // | Fanwe 方维o2o商业系统 // +---------------------------------------------------------------------- // | Copyright (c) 2011 http://www.fanwe.com All rights reserved. // +---------------------------------------------------------------------- // | Author: 云淡风轻(88522820@qq.com) // +---------------------------------------------------------------------- //会员整合的接口 interface integrate{ //用户登录 /** * 返回 array('status'=>'',data=>'',msg=>'') msg存放整合接口返回的字符串 * @param $user_data */ function login($user_name,$user_pwd); //用户登出 /** * 返回 array('status'=>'',data=>'',msg=>'') msg存放整合接口返回的字符串 */ function logout(); //用户注册 /** * 返回 array('status'=>'',data=>'',msg=>'') msg存放整合接口的消息 * @param $user_data */ function add_user($user_name,$user_pwd,$email); //用户修改密码 /** * 返回bool * @param $user_data */ function edit_user($user_data,$user_new_pwd); //删除会员 function delete_user($user_data); //安装时执行的部份操作 //返回 array('status'=>'','msg'=>'') function install($config_seralized); //卸载时执行的部份操作 //无返回 function uninstall(); } ?>
hushulin/zsh_admin
system/libs/integrate.php
PHP
apache-2.0
1,402
package com.sequenceiq.cloudbreak.validation.customimage; import com.sequenceiq.cloudbreak.api.endpoint.v4.customimage.request.CustomImageCatalogV4VmImageRequest; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class UniqueRegionValidatorTest { private UniqueRegionValidator victim; @Before public void setUp() { victim = new UniqueRegionValidator(); } @Test public void testValid() { assertTrue(victim.isValid(withRegions("region1", "region2"), null)); } @Test public void testValidEmpty() { assertTrue(victim.isValid(Collections.emptySet(), null)); } @Test public void testValidNull() { assertTrue(victim.isValid(null, null)); } @Test public void testInvalid() { assertFalse(victim.isValid(withRegions("region1", "region1"), null)); } private Set<CustomImageCatalogV4VmImageRequest> withRegions(String... regions) { return Arrays.stream(regions).map(r -> { CustomImageCatalogV4VmImageRequest item = new CustomImageCatalogV4VmImageRequest(); item.setRegion(r); return item; }).collect(Collectors.toSet()); } }
hortonworks/cloudbreak
core-api/src/test/java/com/sequenceiq/cloudbreak/validation/customimage/UniqueRegionValidatorTest.java
Java
apache-2.0
1,393
package buildah import ( "context" "encoding/json" "runtime" "strings" "time" "github.com/containers/buildah/docker" "github.com/containers/image/v5/manifest" "github.com/containers/image/v5/transports" "github.com/containers/image/v5/types" "github.com/containers/storage/pkg/stringid" ociv1 "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) // unmarshalConvertedConfig obtains the config blob of img valid for the wantedManifestMIMEType format // (either as it exists, or converting the image if necessary), and unmarshals it into dest. // NOTE: The MIME type is of the _manifest_, not of the _config_ that is returned. func unmarshalConvertedConfig(ctx context.Context, dest interface{}, img types.Image, wantedManifestMIMEType string) error { _, actualManifestMIMEType, err := img.Manifest(ctx) if err != nil { return errors.Wrapf(err, "error getting manifest MIME type for %q", transports.ImageName(img.Reference())) } if wantedManifestMIMEType != actualManifestMIMEType { updatedImg, err := img.UpdatedImage(ctx, types.ManifestUpdateOptions{ ManifestMIMEType: wantedManifestMIMEType, InformationOnly: types.ManifestUpdateInformation{ // Strictly speaking, every value in here is invalid. But… Destination: nil, // Destination is technically required, but actually necessary only for conversion _to_ v2s1. Leave it nil, we will crash if that ever changes. LayerInfos: nil, // LayerInfos is necessary for size information in v2s2/OCI manifests, but the code can work with nil, and we are not reading the converted manifest at all. LayerDiffIDs: nil, // LayerDiffIDs are actually embedded in the converted manifest, but the code can work with nil, and the values are not needed until pushing the finished image, at which time containerImageRef.NewImageSource builds the values from scratch. }, }) if err != nil { return errors.Wrapf(err, "error converting image %q from %q to %q", transports.ImageName(img.Reference()), actualManifestMIMEType, wantedManifestMIMEType) } img = updatedImg } config, err := img.ConfigBlob(ctx) if err != nil { return errors.Wrapf(err, "error reading %s config from %q", wantedManifestMIMEType, transports.ImageName(img.Reference())) } if err := json.Unmarshal(config, dest); err != nil { return errors.Wrapf(err, "error parsing %s configuration %q from %q", wantedManifestMIMEType, string(config), transports.ImageName(img.Reference())) } return nil } func (b *Builder) initConfig(ctx context.Context, img types.Image) error { if img != nil { // A pre-existing image, as opposed to a "FROM scratch" new one. rawManifest, manifestMIMEType, err := img.Manifest(ctx) if err != nil { return errors.Wrapf(err, "error reading image manifest for %q", transports.ImageName(img.Reference())) } rawConfig, err := img.ConfigBlob(ctx) if err != nil { return errors.Wrapf(err, "error reading image configuration for %q", transports.ImageName(img.Reference())) } b.Manifest = rawManifest b.Config = rawConfig dimage := docker.V2Image{} if err := unmarshalConvertedConfig(ctx, &dimage, img, manifest.DockerV2Schema2MediaType); err != nil { return err } b.Docker = dimage oimage := ociv1.Image{} if err := unmarshalConvertedConfig(ctx, &oimage, img, ociv1.MediaTypeImageManifest); err != nil { return err } b.OCIv1 = oimage if manifestMIMEType == ociv1.MediaTypeImageManifest { // Attempt to recover format-specific data from the manifest. v1Manifest := ociv1.Manifest{} if err := json.Unmarshal(b.Manifest, &v1Manifest); err != nil { return errors.Wrapf(err, "error parsing OCI manifest %q", string(b.Manifest)) } b.ImageAnnotations = v1Manifest.Annotations } } b.fixupConfig() return nil } func (b *Builder) fixupConfig() { if b.Docker.Config != nil { // Prefer image-level settings over those from the container it was built from. b.Docker.ContainerConfig = *b.Docker.Config } b.Docker.Config = &b.Docker.ContainerConfig b.Docker.DockerVersion = "" now := time.Now().UTC() if b.Docker.Created.IsZero() { b.Docker.Created = now } if b.OCIv1.Created == nil || b.OCIv1.Created.IsZero() { b.OCIv1.Created = &now } if b.OS() == "" { b.SetOS(runtime.GOOS) } if b.Architecture() == "" { b.SetArchitecture(runtime.GOARCH) } if b.Format == Dockerv2ImageManifest && b.Hostname() == "" { b.SetHostname(stringid.TruncateID(stringid.GenerateRandomID())) } } // Annotations returns a set of key-value pairs from the image's manifest. func (b *Builder) Annotations() map[string]string { return copyStringStringMap(b.ImageAnnotations) } // SetAnnotation adds or overwrites a key's value from the image's manifest. // Note: this setting is not present in the Docker v2 image format, so it is // discarded when writing images using Docker v2 formats. func (b *Builder) SetAnnotation(key, value string) { if b.ImageAnnotations == nil { b.ImageAnnotations = map[string]string{} } b.ImageAnnotations[key] = value } // UnsetAnnotation removes a key and its value from the image's manifest, if // it's present. func (b *Builder) UnsetAnnotation(key string) { delete(b.ImageAnnotations, key) } // ClearAnnotations removes all keys and their values from the image's // manifest. func (b *Builder) ClearAnnotations() { b.ImageAnnotations = map[string]string{} } // CreatedBy returns a description of how this image was built. func (b *Builder) CreatedBy() string { return b.ImageCreatedBy } // SetCreatedBy sets the description of how this image was built. func (b *Builder) SetCreatedBy(how string) { b.ImageCreatedBy = how } // OS returns a name of the OS on which the container, or a container built // using an image built from this container, is intended to be run. func (b *Builder) OS() string { return b.OCIv1.OS } // SetOS sets the name of the OS on which the container, or a container built // using an image built from this container, is intended to be run. func (b *Builder) SetOS(os string) { b.OCIv1.OS = os b.Docker.OS = os } // Architecture returns a name of the architecture on which the container, or a // container built using an image built from this container, is intended to be // run. func (b *Builder) Architecture() string { return b.OCIv1.Architecture } // SetArchitecture sets the name of the architecture on which the container, or // a container built using an image built from this container, is intended to // be run. func (b *Builder) SetArchitecture(arch string) { b.OCIv1.Architecture = arch b.Docker.Architecture = arch } // Maintainer returns contact information for the person who built the image. func (b *Builder) Maintainer() string { return b.OCIv1.Author } // SetMaintainer sets contact information for the person who built the image. func (b *Builder) SetMaintainer(who string) { b.OCIv1.Author = who b.Docker.Author = who } // User returns information about the user as whom the container, or a // container built using an image built from this container, should be run. func (b *Builder) User() string { return b.OCIv1.Config.User } // SetUser sets information about the user as whom the container, or a // container built using an image built from this container, should be run. // Acceptable forms are a user name or ID, optionally followed by a colon and a // group name or ID. func (b *Builder) SetUser(spec string) { b.OCIv1.Config.User = spec b.Docker.Config.User = spec } // OnBuild returns the OnBuild value from the container. func (b *Builder) OnBuild() []string { return copyStringSlice(b.Docker.Config.OnBuild) } // ClearOnBuild removes all values from the OnBuild structure func (b *Builder) ClearOnBuild() { b.Docker.Config.OnBuild = []string{} } // SetOnBuild sets a trigger instruction to be executed when the image is used // as the base of another image. // Note: this setting is not present in the OCIv1 image format, so it is // discarded when writing images using OCIv1 formats. func (b *Builder) SetOnBuild(onBuild string) { if onBuild != "" && b.Format != Dockerv2ImageManifest { logrus.Warnf("ONBUILD is not supported for OCI image format, %s will be ignored. Must use `docker` format", onBuild) } b.Docker.Config.OnBuild = append(b.Docker.Config.OnBuild, onBuild) } // WorkDir returns the default working directory for running commands in the // container, or in a container built using an image built from this container. func (b *Builder) WorkDir() string { return b.OCIv1.Config.WorkingDir } // SetWorkDir sets the location of the default working directory for running // commands in the container, or in a container built using an image built from // this container. func (b *Builder) SetWorkDir(there string) { b.OCIv1.Config.WorkingDir = there b.Docker.Config.WorkingDir = there } // Shell returns the default shell for running commands in the // container, or in a container built using an image built from this container. func (b *Builder) Shell() []string { return copyStringSlice(b.Docker.Config.Shell) } // SetShell sets the default shell for running // commands in the container, or in a container built using an image built from // this container. // Note: this setting is not present in the OCIv1 image format, so it is // discarded when writing images using OCIv1 formats. func (b *Builder) SetShell(shell []string) { if len(shell) > 0 && b.Format != Dockerv2ImageManifest { logrus.Warnf("SHELL is not supported for OCI image format, %s will be ignored. Must use `docker` format", shell) } b.Docker.Config.Shell = copyStringSlice(shell) } // Env returns a list of key-value pairs to be set when running commands in the // container, or in a container built using an image built from this container. func (b *Builder) Env() []string { return copyStringSlice(b.OCIv1.Config.Env) } // SetEnv adds or overwrites a value to the set of environment strings which // should be set when running commands in the container, or in a container // built using an image built from this container. func (b *Builder) SetEnv(k string, v string) { reset := func(s *[]string) { n := []string{} for i := range *s { if !strings.HasPrefix((*s)[i], k+"=") { n = append(n, (*s)[i]) } } n = append(n, k+"="+v) *s = n } reset(&b.OCIv1.Config.Env) reset(&b.Docker.Config.Env) } // UnsetEnv removes a value from the set of environment strings which should be // set when running commands in this container, or in a container built using // an image built from this container. func (b *Builder) UnsetEnv(k string) { unset := func(s *[]string) { n := []string{} for i := range *s { if !strings.HasPrefix((*s)[i], k+"=") { n = append(n, (*s)[i]) } } *s = n } unset(&b.OCIv1.Config.Env) unset(&b.Docker.Config.Env) } // ClearEnv removes all values from the set of environment strings which should // be set when running commands in this container, or in a container built // using an image built from this container. func (b *Builder) ClearEnv() { b.OCIv1.Config.Env = []string{} b.Docker.Config.Env = []string{} } // Cmd returns the default command, or command parameters if an Entrypoint is // set, to use when running a container built from an image built from this // container. func (b *Builder) Cmd() []string { return copyStringSlice(b.OCIv1.Config.Cmd) } // SetCmd sets the default command, or command parameters if an Entrypoint is // set, to use when running a container built from an image built from this // container. func (b *Builder) SetCmd(cmd []string) { b.OCIv1.Config.Cmd = copyStringSlice(cmd) b.Docker.Config.Cmd = copyStringSlice(cmd) } // Entrypoint returns the command to be run for containers built from images // built from this container. func (b *Builder) Entrypoint() []string { if len(b.OCIv1.Config.Entrypoint) > 0 { return copyStringSlice(b.OCIv1.Config.Entrypoint) } return nil } // SetEntrypoint sets the command to be run for in containers built from images // built from this container. func (b *Builder) SetEntrypoint(ep []string) { b.OCIv1.Config.Entrypoint = copyStringSlice(ep) b.Docker.Config.Entrypoint = copyStringSlice(ep) } // Labels returns a set of key-value pairs from the image's runtime // configuration. func (b *Builder) Labels() map[string]string { return copyStringStringMap(b.OCIv1.Config.Labels) } // SetLabel adds or overwrites a key's value from the image's runtime // configuration. func (b *Builder) SetLabel(k string, v string) { if b.OCIv1.Config.Labels == nil { b.OCIv1.Config.Labels = map[string]string{} } b.OCIv1.Config.Labels[k] = v if b.Docker.Config.Labels == nil { b.Docker.Config.Labels = map[string]string{} } b.Docker.Config.Labels[k] = v } // UnsetLabel removes a key and its value from the image's runtime // configuration, if it's present. func (b *Builder) UnsetLabel(k string) { delete(b.OCIv1.Config.Labels, k) delete(b.Docker.Config.Labels, k) } // ClearLabels removes all keys and their values from the image's runtime // configuration. func (b *Builder) ClearLabels() { b.OCIv1.Config.Labels = map[string]string{} b.Docker.Config.Labels = map[string]string{} } // Ports returns the set of ports which should be exposed when a container // based on an image built from this container is run. func (b *Builder) Ports() []string { p := []string{} for k := range b.OCIv1.Config.ExposedPorts { p = append(p, k) } return p } // SetPort adds or overwrites an exported port in the set of ports which should // be exposed when a container based on an image built from this container is // run. func (b *Builder) SetPort(p string) { if b.OCIv1.Config.ExposedPorts == nil { b.OCIv1.Config.ExposedPorts = map[string]struct{}{} } b.OCIv1.Config.ExposedPorts[p] = struct{}{} if b.Docker.Config.ExposedPorts == nil { b.Docker.Config.ExposedPorts = make(docker.PortSet) } b.Docker.Config.ExposedPorts[docker.Port(p)] = struct{}{} } // UnsetPort removes an exposed port from the set of ports which should be // exposed when a container based on an image built from this container is run. func (b *Builder) UnsetPort(p string) { delete(b.OCIv1.Config.ExposedPorts, p) delete(b.Docker.Config.ExposedPorts, docker.Port(p)) } // ClearPorts empties the set of ports which should be exposed when a container // based on an image built from this container is run. func (b *Builder) ClearPorts() { b.OCIv1.Config.ExposedPorts = map[string]struct{}{} b.Docker.Config.ExposedPorts = docker.PortSet{} } // Volumes returns a list of filesystem locations which should be mounted from // outside of the container when a container built from an image built from // this container is run. func (b *Builder) Volumes() []string { v := []string{} for k := range b.OCIv1.Config.Volumes { v = append(v, k) } if len(v) > 0 { return v } return nil } // CheckVolume returns True if the location exists in the image's list of locations // which should be mounted from outside of the container when a container // based on an image built from this container is run func (b *Builder) CheckVolume(v string) bool { _, OCIv1Volume := b.OCIv1.Config.Volumes[v] _, DockerVolume := b.Docker.Config.Volumes[v] return OCIv1Volume || DockerVolume } // AddVolume adds a location to the image's list of locations which should be // mounted from outside of the container when a container based on an image // built from this container is run. func (b *Builder) AddVolume(v string) { if b.OCIv1.Config.Volumes == nil { b.OCIv1.Config.Volumes = map[string]struct{}{} } b.OCIv1.Config.Volumes[v] = struct{}{} if b.Docker.Config.Volumes == nil { b.Docker.Config.Volumes = map[string]struct{}{} } b.Docker.Config.Volumes[v] = struct{}{} } // RemoveVolume removes a location from the list of locations which should be // mounted from outside of the container when a container based on an image // built from this container is run. func (b *Builder) RemoveVolume(v string) { delete(b.OCIv1.Config.Volumes, v) delete(b.Docker.Config.Volumes, v) } // ClearVolumes removes all locations from the image's list of locations which // should be mounted from outside of the container when a container based on an // image built from this container is run. func (b *Builder) ClearVolumes() { b.OCIv1.Config.Volumes = map[string]struct{}{} b.Docker.Config.Volumes = map[string]struct{}{} } // Hostname returns the hostname which will be set in the container and in // containers built using images built from the container. func (b *Builder) Hostname() string { return b.Docker.Config.Hostname } // SetHostname sets the hostname which will be set in the container and in // containers built using images built from the container. // Note: this setting is not present in the OCIv1 image format, so it is // discarded when writing images using OCIv1 formats. func (b *Builder) SetHostname(name string) { b.Docker.Config.Hostname = name } // Domainname returns the domainname which will be set in the container and in // containers built using images built from the container. func (b *Builder) Domainname() string { return b.Docker.Config.Domainname } // SetDomainname sets the domainname which will be set in the container and in // containers built using images built from the container. // Note: this setting is not present in the OCIv1 image format, so it is // discarded when writing images using OCIv1 formats. func (b *Builder) SetDomainname(name string) { if name != "" && b.Format != Dockerv2ImageManifest { logrus.Warnf("DOMAINNAME is not supported for OCI image format, domainname %s will be ignored. Must use `docker` format", name) } b.Docker.Config.Domainname = name } // SetDefaultMountsFilePath sets the mounts file path for testing purposes func (b *Builder) SetDefaultMountsFilePath(path string) { b.DefaultMountsFilePath = path } // Comment returns the comment which will be set in the container and in // containers built using images built from the container func (b *Builder) Comment() string { return b.Docker.Comment } // SetComment sets the comment which will be set in the container and in // containers built using images built from the container. // Note: this setting is not present in the OCIv1 image format, so it is // discarded when writing images using OCIv1 formats. func (b *Builder) SetComment(comment string) { if comment != "" && b.Format != Dockerv2ImageManifest { logrus.Warnf("COMMENT is not supported for OCI image format, comment %s will be ignored. Must use `docker` format", comment) } b.Docker.Comment = comment } // HistoryComment returns the comment which will be used in the history item // which will describe the latest layer when we commit an image. func (b *Builder) HistoryComment() string { return b.ImageHistoryComment } // SetHistoryComment sets the comment which will be used in the history item // which will describe the latest layer when we commit an image. func (b *Builder) SetHistoryComment(comment string) { b.ImageHistoryComment = comment } // StopSignal returns the signal which will be set in the container and in // containers built using images buiilt from the container func (b *Builder) StopSignal() string { return b.Docker.Config.StopSignal } // SetStopSignal sets the signal which will be set in the container and in // containers built using images built from the container. func (b *Builder) SetStopSignal(stopSignal string) { b.OCIv1.Config.StopSignal = stopSignal b.Docker.Config.StopSignal = stopSignal } // Healthcheck returns information that recommends how a container engine // should check if a running container is "healthy". func (b *Builder) Healthcheck() *docker.HealthConfig { if b.Docker.Config.Healthcheck == nil { return nil } return &docker.HealthConfig{ Test: copyStringSlice(b.Docker.Config.Healthcheck.Test), Interval: b.Docker.Config.Healthcheck.Interval, Timeout: b.Docker.Config.Healthcheck.Timeout, StartPeriod: b.Docker.Config.Healthcheck.StartPeriod, Retries: b.Docker.Config.Healthcheck.Retries, } } // SetHealthcheck sets recommended commands to run in order to verify that a // running container based on this image is "healthy", along with information // specifying how often that test should be run, and how many times the test // should fail before the container should be considered unhealthy. // Note: this setting is not present in the OCIv1 image format, so it is // discarded when writing images using OCIv1 formats. func (b *Builder) SetHealthcheck(config *docker.HealthConfig) { b.Docker.Config.Healthcheck = nil if config != nil { if b.Format != Dockerv2ImageManifest { logrus.Warnf("Healthcheck is not supported for OCI image format and will be ignored. Must use `docker` format") } b.Docker.Config.Healthcheck = &docker.HealthConfig{ Test: copyStringSlice(config.Test), Interval: config.Interval, Timeout: config.Timeout, StartPeriod: config.StartPeriod, Retries: config.Retries, } } } // AddPrependedEmptyLayer adds an item to the history that we'll create when // committing the image, after any history we inherit from the base image, but // before the history item that we'll use to describe the new layer that we're // adding. func (b *Builder) AddPrependedEmptyLayer(created *time.Time, createdBy, author, comment string) { if created != nil { copiedTimestamp := *created created = &copiedTimestamp } b.PrependedEmptyLayers = append(b.PrependedEmptyLayers, ociv1.History{ Created: created, CreatedBy: createdBy, Author: author, Comment: comment, EmptyLayer: true, }) } // ClearPrependedEmptyLayers clears the list of history entries that we'll add // to the committed image before the entry for the layer that we're adding. func (b *Builder) ClearPrependedEmptyLayers() { b.PrependedEmptyLayers = nil } // AddAppendedEmptyLayer adds an item to the history that we'll create when // committing the image, after the history item that we'll use to describe the // new layer that we're adding. func (b *Builder) AddAppendedEmptyLayer(created *time.Time, createdBy, author, comment string) { if created != nil { copiedTimestamp := *created created = &copiedTimestamp } b.AppendedEmptyLayers = append(b.AppendedEmptyLayers, ociv1.History{ Created: created, CreatedBy: createdBy, Author: author, Comment: comment, EmptyLayer: true, }) } // ClearAppendedEmptyLayers clears the list of history entries that we'll add // to the committed image after the entry for the layer that we're adding. func (b *Builder) ClearAppendedEmptyLayers() { b.AppendedEmptyLayers = nil }
projectatomic/buildah
config.go
GO
apache-2.0
22,655
package toolbox_test import ( "github.com/stretchr/testify/assert" "github.com/viant/toolbox" "github.com/viant/toolbox/url" "testing" ) func TestExtractURIParameters(t *testing.T) { { parameters, matched := toolbox.ExtractURIParameters("/v1/path/{app}/{version}/", "/v1/path/app/1.0/?v=12") assert.True(t, matched) if !matched { t.FailNow() } assert.Equal(t, 2, len(parameters)) assert.Equal(t, "app", parameters["app"]) assert.Equal(t, "1.0", parameters["version"]) } { parameters, matched := toolbox.ExtractURIParameters("/v1/path/{ids}/{sub}/a/{name}", "/v1/path/1,2,3,4,5/subpath/a/abc") assert.True(t, matched) assert.Equal(t, 3, len(parameters)) assert.Equal(t, "1,2,3,4,5", parameters["ids"]) assert.Equal(t, "subpath", parameters["sub"]) assert.Equal(t, "abc", parameters["name"]) } { parameters, matched := toolbox.ExtractURIParameters("/v1/path/{ids}", "/v1/path/this-is-test") assert.True(t, matched) assert.Equal(t, 1, len(parameters)) assert.Equal(t, "this-is-test", parameters["ids"]) } { _, matched := toolbox.ExtractURIParameters("/v2/path/{ids}/{sub}/a/{name}", "/v1/path/1,2,3,4,5/subpath/a/abc") assert.False(t, matched) } { _, matched := toolbox.ExtractURIParameters("/v1/path1/{ids}/{sub}/a/{name}", "/v1/path/1,2,3,4,5/subpath/a/abc") assert.False(t, matched) } { _, matched := toolbox.ExtractURIParameters("/v1/path1/{ids}/{sub}/a/{name}", "/v1/path/1,2,3,4,5/subpath/a/abc") assert.False(t, matched) } { _, matched := toolbox.ExtractURIParameters("/v1/path/{ids}", "/v1/path/1") assert.True(t, matched) } { _, matched := toolbox.ExtractURIParameters("/v1/reverse/", "/v1/reverse/") assert.True(t, matched) } { parameters, matched := toolbox.ExtractURIParameters("/v1/path/{ids}/{sub}/a/{name}", "/v1/path/1,2,3,4,5/subpath/a/abcwrwr") assert.True(t, matched) assert.Equal(t, 3, len(parameters)) assert.Equal(t, "1,2,3,4,5", parameters["ids"]) assert.Equal(t, "subpath", parameters["sub"]) assert.Equal(t, "abcwrwr", parameters["name"]) } } func TestURLBase(t *testing.T) { URL := "http://github.com/abc" baseURL := toolbox.URLBase(URL) assert.Equal(t, "http://github.com", baseURL) } func TestURLSplit(t *testing.T) { { URL := "http://github.com/abc/trter/rds" parentURL, resource := toolbox.URLSplit(URL) assert.Equal(t, "http://github.com/abc/trter", parentURL) assert.Equal(t, "rds", resource) } } func TestURLStripPath(t *testing.T) { { URL := "http://github.com/abc" assert.EqualValues(t, "http://github.com", toolbox.URLStripPath(URL)) } { URL := "http://github.com" assert.EqualValues(t, "http://github.com", toolbox.URLStripPath(URL)) } } func TestURL_Rename(t *testing.T) { { URL := "http://github.com/abc/" resource := url.NewResource(URL) resource.Rename("/tmp/abc") assert.Equal(t, "http://github.com//tmp/abc", resource.URL) } } func TestURLPathJoin(t *testing.T) { { URL := "http://github.com/abc" assert.EqualValues(t, "http://github.com/abc/path/a.txt", toolbox.URLPathJoin(URL, "path/a.txt")) } { URL := "http://github.com/abc/" assert.EqualValues(t, "http://github.com/abc/path/a.txt", toolbox.URLPathJoin(URL, "path/a.txt")) } { URL := "http://github.com/abc/" assert.EqualValues(t, "http://github.com/a.txt", toolbox.URLPathJoin(URL, "/a.txt")) } }
viant/toolbox
uri_test.go
GO
apache-2.0
3,363
package gov.cdc.sdp.cbr; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.camel.CamelContext; import org.apache.camel.EndpointInject; import org.apache.camel.Exchange; import org.apache.camel.Produce; import org.apache.camel.ProducerTemplate; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.impl.DefaultExchange; import org.apache.camel.test.spring.CamelSpringJUnit4ClassRunner; import org.apache.camel.test.spring.CamelTestContextBootstrapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.PropertySource; import org.springframework.test.context.BootstrapWith; import org.springframework.test.context.ContextConfiguration; import de.saly.javamail.mock2.MockMailbox; @RunWith(CamelSpringJUnit4ClassRunner.class) @BootstrapWith(CamelTestContextBootstrapper.class) @ContextConfiguration(locations = { "classpath:EmailOnException.xml" }) @PropertySource("classpath:application.properties") public class EmailOnExceptionTest extends BaseDBTest { Object lock = new Object(); String address = "cbr_errors@cdc.gov"; @Autowired protected CamelContext camelContext; @EndpointInject(uri = "mock:mock_endpoint") protected MockEndpoint mockEndpoint; @Produce(uri = "direct:start") protected ProducerTemplate template; @Before public void setup() throws SQLException, IOException { MockMailbox.resetAll(); synchronized (lock) { mockEndpoint.reset(); DataSource ds = (DataSource) camelContext.getRegistry().lookupByName("sdpqDataSource"); super.setupDb(ds); } } @Test public void noS3AtUriTest() throws Exception { assertEquals("Should be 0 messages in inbox", 0, MockMailbox.get(address).getInbox().getMessageCount()); mockEndpoint.expectedMessageCount(1); Exchange exchange = new DefaultExchange(camelContext); template.send(exchange); mockEndpoint.assertIsSatisfied(); assertEquals("Should be 1 message in inbox", 1, MockMailbox.get(address).getInbox().getMessageCount()); } }
CDCgov/SDP-CBR
phinms/src/test/java/gov/cdc/sdp/cbr/EmailOnExceptionTest.java
Java
apache-2.0
2,315
using UnityEngine; using System.Collections; public class CanvasHandler : MonoBehaviour { // Use this for initialization void Awake() { LeanTween.addListener((int)Events.ENERGYPOWERIN, OnEnergyPowerIn); LeanTween.addListener((int)Events.ENERGYPOWEROUT, OnEnergyPowerOut); } public void OnDestroy() { LeanTween.removeListener((int)Events.ENERGYPOWERIN, OnEnergyPowerIn); LeanTween.removeListener((int)Events.ENERGYPOWEROUT, OnEnergyPowerOut); } void OnEnergyPowerIn(LTEvent evt) { gameObject.SetActive(false); } void OnEnergyPowerOut(LTEvent evt) { gameObject.SetActive(true); } }
yantian001/2DShooting
Assets/2DShooting/Scripts/UI/CanvasHandler.cs
C#
apache-2.0
692
public class SuperWildCardDemo { public static void main(String[] args) { GenericStack<String> stack1 = new GenericStack<String>(); GenericStack<Object> stack2 = new GenericStack<Object>(); stack2.push("Java"); stack2.push(2); stack1.push("Sun"); add(stack1, stack2); AnyWildCardDemo.print(stack2); } public static <T> void add(GenericStack<T> stack1, GenericStack<? super T> stack2) { while (!stack1.isEmpty()) stack2.push(stack1.pop()); } }
txs72/BUPTJava
slides/19/examples/SuperWildCardDemo.java
Java
apache-2.0
511
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import warnings from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.ads.googleads.v9.resources.types import bidding_strategy from google.ads.googleads.v9.services.types import bidding_strategy_service from .base import BiddingStrategyServiceTransport, DEFAULT_CLIENT_INFO class BiddingStrategyServiceGrpcTransport(BiddingStrategyServiceTransport): """gRPC backend transport for BiddingStrategyService. Service to manage bidding strategies. This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation and call it. It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ def __init__( self, *, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ self._ssl_channel_credentials = ssl_channel_credentials if channel: # Sanity check: Ensure that channel and credentials are not both # provided. credentials = False # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None elif api_mtls_endpoint: warnings.warn( "api_mtls_endpoint and client_cert_source are deprecated", DeprecationWarning, ) host = ( api_mtls_endpoint if ":" in api_mtls_endpoint else api_mtls_endpoint + ":443" ) if credentials is None: credentials, _ = google.auth.default( scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id ) # Create SSL credentials with client_cert_source or application # default SSL credentials. if client_cert_source: cert, key = client_cert_source() ssl_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) else: ssl_credentials = SslCredentials().ssl_credentials # create a new channel. The provided one is ignored. self._grpc_channel = type(self).create_channel( host, credentials=credentials, credentials_file=credentials_file, ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) self._ssl_channel_credentials = ssl_credentials else: host = host if ":" in host else host + ":443" if credentials is None: credentials, _ = google.auth.default(scopes=self.AUTH_SCOPES) # create a new channel. The provided one is ignored. self._grpc_channel = type(self).create_channel( host, credentials=credentials, ssl_credentials=ssl_channel_credentials, scopes=self.AUTH_SCOPES, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) self._stubs = {} # type: Dict[str, Callable] # Run the base constructor. super().__init__( host=host, credentials=credentials, client_info=client_info, ) @classmethod def create_channel( cls, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, scopes: Optional[Sequence[str]] = None, **kwargs, ) -> grpc.Channel: """Create and return a gRPC channel object. Args: address (Optionsl[str]): The host for the channel to use. credentials (Optional[~.Credentials]): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: grpc.Channel: A gRPC channel object. """ return grpc_helpers.create_channel( host, credentials=credentials, scopes=scopes or cls.AUTH_SCOPES, **kwargs, ) def close(self): self.grpc_channel.close() @property def grpc_channel(self) -> grpc.Channel: """Return the channel designed to connect to this service. """ return self._grpc_channel @property def get_bidding_strategy( self, ) -> Callable[ [bidding_strategy_service.GetBiddingStrategyRequest], bidding_strategy.BiddingStrategy, ]: r"""Return a callable for the get bidding strategy method over gRPC. Returns the requested bidding strategy in full detail. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `HeaderError <>`__ `InternalError <>`__ `QuotaError <>`__ `RequestError <>`__ Returns: Callable[[~.GetBiddingStrategyRequest], ~.BiddingStrategy]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_bidding_strategy" not in self._stubs: self._stubs["get_bidding_strategy"] = self.grpc_channel.unary_unary( "/google.ads.googleads.v9.services.BiddingStrategyService/GetBiddingStrategy", request_serializer=bidding_strategy_service.GetBiddingStrategyRequest.serialize, response_deserializer=bidding_strategy.BiddingStrategy.deserialize, ) return self._stubs["get_bidding_strategy"] @property def mutate_bidding_strategies( self, ) -> Callable[ [bidding_strategy_service.MutateBiddingStrategiesRequest], bidding_strategy_service.MutateBiddingStrategiesResponse, ]: r"""Return a callable for the mutate bidding strategies method over gRPC. Creates, updates, or removes bidding strategies. Operation statuses are returned. List of thrown errors: `AdxError <>`__ `AuthenticationError <>`__ `AuthorizationError <>`__ `BiddingError <>`__ `BiddingStrategyError <>`__ `ContextError <>`__ `DatabaseError <>`__ `DateError <>`__ `DistinctError <>`__ `FieldError <>`__ `FieldMaskError <>`__ `HeaderError <>`__ `IdError <>`__ `InternalError <>`__ `MutateError <>`__ `NewResourceCreationError <>`__ `NotEmptyError <>`__ `NullError <>`__ `OperationAccessDeniedError <>`__ `OperatorError <>`__ `QuotaError <>`__ `RangeError <>`__ `RequestError <>`__ `SizeLimitError <>`__ `StringFormatError <>`__ `StringLengthError <>`__ Returns: Callable[[~.MutateBiddingStrategiesRequest], ~.MutateBiddingStrategiesResponse]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "mutate_bidding_strategies" not in self._stubs: self._stubs[ "mutate_bidding_strategies" ] = self.grpc_channel.unary_unary( "/google.ads.googleads.v9.services.BiddingStrategyService/MutateBiddingStrategies", request_serializer=bidding_strategy_service.MutateBiddingStrategiesRequest.serialize, response_deserializer=bidding_strategy_service.MutateBiddingStrategiesResponse.deserialize, ) return self._stubs["mutate_bidding_strategies"] __all__ = ("BiddingStrategyServiceGrpcTransport",)
googleads/google-ads-python
google/ads/googleads/v9/services/services/bidding_strategy_service/transports/grpc.py
Python
apache-2.0
12,551
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace iWay.RemoteControlBase.Protocol.RemoteExplorer.Requests { public class RenameContentReq : BasicReq { public string ContentPath; public string NewContentName; } }
iWay7/RemoteControl
RemoteControlBase/Protocol/RemoteExplorer/Requests/RenameContentReq.cs
C#
apache-2.0
291
/** * @license * Copyright 2016 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. */ import {GL} from 'neuroglancer/webgl/context'; /** * Sets parameters to make a texture suitable for use as a raw array: NEAREST * filtering, clamping. */ export function setRawTextureParameters(gl: WebGLRenderingContext) { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); // Prevents s-coordinate wrapping (repeating). Repeating not // permitted for non-power-of-2 textures. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); // Prevents t-coordinate wrapping (repeating). Repeating not // permitted for non-power-of-2 textures. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); } export function resizeTexture( gl: GL, texture: WebGLTexture|null, width: number, height: number, format: number = gl.RGBA, dataType: number = gl.UNSIGNED_BYTE) { gl.activeTexture(gl.TEXTURE0 + gl.tempTextureUnit); gl.bindTexture(gl.TEXTURE_2D, texture); setRawTextureParameters(gl); gl.texImage2D( gl.TEXTURE_2D, 0, /*internalformat=*/format, /*width=*/width, /*height=*/height, /*border=*/0, /*format=*/format, dataType, <any>null); gl.bindTexture(gl.TEXTURE_2D, null); }
funkey/neuroglancer
src/neuroglancer/webgl/texture.ts
TypeScript
apache-2.0
1,865
/** * Copyright (C) 2010-2013 Alibaba Group Holding Limited * * 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.jiumao.remote.exception; /** * 异步调用或者Oneway调用,堆积的请求超过信号量最大值 * * @author shijia.wxr<vintage.wang@gmail.com> * @since 2013-7-13 */ public class RemotingTooMuchRequestException extends RemotingException { private static final long serialVersionUID = 4326919581254519654L; public RemotingTooMuchRequestException(String message) { super(message); } }
jiumao-org/wechat-mall
mall-remoting/src/main/java/org/jiumao/remote/exception/RemotingTooMuchRequestException.java
Java
apache-2.0
1,085
/** * Copyright (C) 2015 Zalando SE (http://tech.zalando.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zalando.stups.tokens; import java.io.File; import com.fasterxml.jackson.databind.ObjectMapper; public abstract class AbstractJsonFileBackedCredentialsProvider { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private final FileSupplier fileSupplier; public AbstractJsonFileBackedCredentialsProvider(final String filename) { this.fileSupplier = new FileSupplier(filename); } public AbstractJsonFileBackedCredentialsProvider(final File file) { this.fileSupplier = new FileSupplier(file); } protected File getFile() { return fileSupplier.get(); } protected <T> T read(final Class<T> cls) { try { return OBJECT_MAPPER.readValue(getFile(), cls); } catch (final Throwable e) { throw new CredentialsUnavailableException(e.getMessage(), e); } } }
zalando-stups/tokens
src/main/java/org/zalando/stups/tokens/AbstractJsonFileBackedCredentialsProvider.java
Java
apache-2.0
1,522
package io.quarkus.arc.test.unused; import static org.junit.jupiter.api.Assertions.assertTrue; import io.quarkus.arc.Arc; import io.quarkus.arc.ArcContainer; import io.quarkus.arc.test.ArcTestContainer; import javax.enterprise.context.Dependent; import javax.enterprise.event.Observes; import javax.enterprise.inject.spi.InterceptionType; import javax.enterprise.util.AnnotationLiteral; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; public class RemoveUnusedInterceptorTest extends RemoveUnusedComponentsTest { @RegisterExtension public ArcTestContainer container = ArcTestContainer.builder() .beanClasses(HasObserver.class, Alpha.class, AlphaInterceptor.class, Counter.class, Bravo.class, BravoInterceptor.class) .removeUnusedBeans(true) .build(); @SuppressWarnings("serial") @Test public void testRemoval() { ArcContainer container = Arc.container(); assertPresent(HasObserver.class); assertNotPresent(Counter.class); // Both AlphaInterceptor and BravoInterceptor were removed assertTrue(container.beanManager().resolveInterceptors(InterceptionType.AROUND_INVOKE, new AnnotationLiteral<Alpha>() { }).isEmpty()); assertTrue(container.beanManager().resolveInterceptors(InterceptionType.AROUND_INVOKE, new AnnotationLiteral<Bravo>() { }).isEmpty()); } @Dependent static class HasObserver { void observe(@Observes String event) { } } }
quarkusio/quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/unused/RemoveUnusedInterceptorTest.java
Java
apache-2.0
1,563
__author__ = 'wangxun' """def double(list): i=0 while i <len(list): print i list[i]=list[i]*2 i+=1 return(list) """ def doulbe(list): i=0 [list[i]=list[i]*2 while i<len(list)] return(list) print double([1,2,3,4])
wonstonx/wxgittest
day2 test1.py
Python
apache-2.0
266
package net.orangemile.informatica.powercenter.domain; import java.util.ArrayList; import java.util.List; import net.orangemile.informatica.powercenter.domain.constant.InstanceType; import net.orangemile.informatica.powercenter.domain.constant.PortType; public class Transformation implements Box, Cloneable { private String name; private String description; private String type; private String objectVersion; private Boolean reusable; private String isVsamNormalizer; private String refSourceName; private String refDbdName; private String templateId; private String templateName; private String parent; private ParentType parentType; private String versionNumber; private String crcValue; private List<Group> groupList; private List<SourceField> sourceFieldList; private List<TransformField> transformFieldList; private List<TableAttribute> tableAttributeList; private List<InitProp> initPropList; private List<MetaDataExtension> metaDataExtensionList; private List<TransformFieldAttrDef> transformFieldAttrDefList; private List<FieldDependency> fieldDependencyList; private FlatFile flatFileList; public Transformation() {} public Transformation( String name, String description, InstanceType type ) { this.name = name; this.description = description; this.type = type.getInstanceType(); } public List<TransformField> getInputPorts() { ArrayList<TransformField> fields = new ArrayList<TransformField>(); for ( TransformField field : transformFieldList ) { if ( PortType.isInputPort(field.getPortType()) ) { fields.add( field ); } } return fields; } public List<TransformField> getOutputPorts() { ArrayList<TransformField> fields = new ArrayList<TransformField>(); for ( TransformField field : transformFieldList ) { if ( PortType.isOutputPort(field.getPortType()) ) { fields.add( field ); } } return fields; } public String getCrcValue() { return crcValue; } public void setCrcValue(String crcValue) { this.crcValue = crcValue; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<FieldDependency> getFieldDependencyList() { return fieldDependencyList; } public void setFieldDependencyList(ArrayList<FieldDependency> fieldDependencyList) { this.fieldDependencyList = fieldDependencyList; } public FlatFile getFlatFileList() { return flatFileList; } public void setFlatFileList(FlatFile flatFileList) { this.flatFileList = flatFileList; } public List<Group> getGroupList() { return groupList; } public void setGroupList(ArrayList<Group> groupList) { this.groupList = groupList; } public List<InitProp> getInitPropList() { return initPropList; } public void setInitPropList(ArrayList<InitProp> initPropList) { this.initPropList = initPropList; } public String getIsVsamNormalizer() { return isVsamNormalizer; } public void setIsVsamNormalizer(String isVsamNormalizer) { this.isVsamNormalizer = isVsamNormalizer; } public List<MetaDataExtension> getMetaDataExtensionList() { return metaDataExtensionList; } public void setMetaDataExtensionList(ArrayList<MetaDataExtension> metaDataExtensionList) { this.metaDataExtensionList = metaDataExtensionList; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getObjectVersion() { return objectVersion; } public void setObjectVersion(String objectVersion) { this.objectVersion = objectVersion; } public String getParent() { return parent; } public void setParent(String parent) { this.parent = parent; } public ParentType getParentType() { return parentType; } public void setParentType(ParentType parentType) { this.parentType = parentType; } public String getRefDbdName() { return refDbdName; } public void setRefDbdName(String refDbdName) { this.refDbdName = refDbdName; } public String getRefSourceName() { return refSourceName; } public void setRefSourceName(String refSourceName) { this.refSourceName = refSourceName; } public Boolean isReusable() { return reusable; } public void setReusable(Boolean reusable) { this.reusable = reusable; } public List<SourceField> getSourceFieldList() { return sourceFieldList; } public void setSourceFieldList(List<SourceField> sourceFieldList) { this.sourceFieldList = sourceFieldList; } public List<TableAttribute> getTableAttributeList() { return tableAttributeList; } public void setTableAttributeList(List<TableAttribute> tableAttributeList) { this.tableAttributeList = tableAttributeList; } public String getTemplateId() { return templateId; } public void setTemplateId(String templateId) { this.templateId = templateId; } public String getTemplateName() { return templateName; } public void setTemplateName(String templateName) { this.templateName = templateName; } public List<TransformFieldAttrDef> getTransformFieldAttrDefList() { return transformFieldAttrDefList; } public void setTransformFieldAttrDefList(ArrayList<TransformFieldAttrDef> transformFieldAttrDefList) { this.transformFieldAttrDefList = transformFieldAttrDefList; } public List<TransformField> getTransformFieldList() { return transformFieldList; } public void setTransformFieldList(List<TransformField> transformFieldList) { this.transformFieldList = transformFieldList; } public void addTransformField( TransformField transformField ) { if ( transformFieldList == null ) { transformFieldList = new ArrayList<TransformField>(); } transformFieldList.add( transformField ); } public void addTransformFields( List<TransformField> transformFields ){ if ( transformFieldList == null ) { transformFieldList = new ArrayList<TransformField>(); } for( TransformField field : transformFields ) { transformFieldList.add(field); } } /** * Adds the given transform field after the given field * @param transformField * @param afterFieldName */ public void addTransformField( TransformField transformField, String afterFieldName ) { if ( transformFieldList == null ) { throw new RuntimeException("TransformFieldList is null"); } for ( int i=0;i<transformFieldList.size();i++) { if ( transformFieldList.get(i).getName().equalsIgnoreCase(afterFieldName) ) { transformFieldList.add(i + 1, transformField); return; } } throw new RuntimeException("Field not found - " + afterFieldName ); } public TransformField getTransformField( String name ) { for ( TransformField field : transformFieldList ) { if ( field.getName().equalsIgnoreCase(name) ) { return field; } } return null; } public String getInstanceType() { return type; } public void setType(String type) { this.type = type; } public String getVersionNumber() { return versionNumber; } public void setVersionNumber(String versionNumber) { this.versionNumber = versionNumber; } public enum ParentType { MAPPING, MAPPLET } @Override public Object clone() { try { return super.clone(); } catch ( CloneNotSupportedException e ) { throw new RuntimeException(e); } } /**************************************** * Utility Methods ****************************************/ /** * Returns the associated table attribute * @param key * @return */ public TableAttribute getTableAttribute( String key ) { for ( TableAttribute ta : tableAttributeList ) { if ( ta.getName().equalsIgnoreCase(key) ) { return ta; } } return null; } }
autodidacticon/informatica-powercenter-automation
src/app/java/net/orangemile/informatica/powercenter/domain/Transformation.java
Java
apache-2.0
7,970
''' Created on 04/11/2015 @author: S41nz ''' class TBTAFMetadataType(object): ''' Simple enumeration class that describes the types of metadata that can be discovered within a source code asset ''' #Verdict enumeration types #The verdict for a passing test TEST_CODE="Test Code" #The verdict for a failed test PRODUCT_CODE="Product Code"
S41nz/TBTAF
tbtaf/common/enums/metadata_type.py
Python
apache-2.0
379
package showcaseview; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import ganggongui.dalkomsoft02.com.myapplication.R; /** * Created by ganggongui on 15. 1. 21.. */ public class Fragment_thred extends Fragment { private View view; // 첫번째 프래그 먼트로 돌아가는 // 버튼 입니다. private ImageButton backbtn; // 엑티비와의 통신을 위한 // 인터페이스 변수를 선언 합니다. private onBackButtonListener backButtonListener; public interface onBackButtonListener { public void goBack(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); // 프레그먼트는 액티비티를 상속하지 않았으므로 // 콘텐스트 정보를 얻기위해 엑티비티를 형변환하여 // 값으로 넣어줍니다. backButtonListener = (onBackButtonListener) activity; } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { this.view = inflater.inflate(R.layout.fragment_thred, container, false); return this.view; } @Override public void onStart() { super.onStart(); backbtn = (ImageButton) view.findViewById(R.id.btn1); backbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 버튼 클릭시 인터페이스의 메소드를 // 이용하여 엑티비티와 통신합니다. backButtonListener.goBack(); } }); } }
kiss5331/Android
FakeStudyApp/FakeStudy_s/app/src/main/java/showcaseview/Fragment_thred.java
Java
apache-2.0
1,888
package com.decker.jdclassifier; import java.util.ArrayDeque; import java.util.Queue; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringTokenizer extends AbstractTokenizer { Queue<Token> tokenQueue = new ArrayDeque<Token>(); Token buffer = null; int line = 0; public StringTokenizer(String[] strings) { Pattern pattern = Pattern.compile("\\b[A-Za-z0-9_'-]{2,32}\\b|^[A-Za-z0-9_'-]{2,32}\\b|\\b[A-Za-z0-9_'-]{2,32}$"); for(String string : strings) { Matcher matcher = pattern.matcher(string); while(matcher.find()) { String match = matcher.group(); if(!stopwords.contains(match)) this.tokenQueue.add(new Token(string.toLowerCase(), line, matcher.start())); } line++; } } @Override public boolean hasNext() { if(buffer != null) return true; buffer = this.tokenQueue.poll(); return buffer != null; } @Override public Token next() { if(buffer == null) hasNext(); Token token = this.buffer; this.buffer = null; return token; } }
zig158/jdclassifier
jdclassifier/src/com/decker/jdclassifier/StringTokenizer.java
Java
apache-2.0
1,043
package com.bindstone.graphbank.rest; import com.bindstone.graphbank.service.DatabaseService; import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc; import io.restassured.RestAssured; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; @Transactional public class DatabaseRestTest extends AbstractRestTest { private static final String ROOT = "/database/"; @Autowired protected WebApplicationContext wac; @Autowired private DatabaseService databaseService; @Before public void tearDown() { System.out.println("Test execution port:" + port); RestAssured.port = port; RestAssuredMockMvc.webAppContextSetup(wac); } @Test public void clear() throws Exception { Assert.assertNotNull("Service validation", databaseService); RestAssuredMockMvc .delete(ROOT + "action/clear") .then().statusCode(200); } }
bindstone/graphbank
Backend/src/test/java/com/bindstone/graphbank/rest/DatabaseRestTest.java
Java
apache-2.0
1,140
package com.mnknowledge.dp.behavioral.observer.wheather; public class CurrentView implements Observer, DisplayElement { private float temperature; private float humidity; @SuppressWarnings("unused") private Subject weatherAPI; public CurrentView(Subject weatherData) { this.weatherAPI = weatherData; weatherData.registerObserver(this); } public void update(float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; display(); } public void display() { System.out.println("Current conditions: " + temperature + "C degrees and " + humidity + "% humidity"); } }
stapetro/mnk_designpatterns
dpsamples/src/main/java/com/mnknowledge/dp/behavioral/observer/wheather/CurrentView.java
Java
apache-2.0
705
package net.falappa.swing.table; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import javax.swing.BorderFactory; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.table.DefaultTableCellRenderer; /* * Highlight only the area occupied by text, not the entire background */ class SelectAllRenderer extends DefaultTableCellRenderer { private Color selectionBackground; private Border editBorder = BorderFactory.createLineBorder(Color.BLACK); private boolean isPaintSelection; public SelectAllRenderer() { this(UIManager.getColor("TextField.selectionBackground")); } public SelectAllRenderer(Color selectionBackground) { this.selectionBackground = selectionBackground; } public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); // This variable is used by the paintComponent() method to control when // the background painting (to mimic the text selection) is done. if (hasFocus && table.isCellEditable(row, column) && !getText().equals("")) { isPaintSelection = true; } else { isPaintSelection = false; } return this; } /* * Override to control the background painting of the renderer */ protected void paintComponent(Graphics g) { // Paint the background manually so we can simulate highlighting the text, // therefore we need to make the renderer non-opaque if (isPaintSelection) { setBorder(editBorder); g.setColor(UIManager.getColor("Table.focusCellBackground")); g.fillRect(0, 0, getSize().width, getSize().height); g.setColor(selectionBackground); g.fillRect(0, 0, getPreferredSize().width, getSize().height); setOpaque(false); } super.paintComponent(g); setOpaque(true); } }
AlexFalappa/hcc
af-toolkit/src/main/java/net/falappa/swing/table/SelectAllRenderer.java
Java
apache-2.0
2,222
input = """ f(1). :- f(X). """ output = """ f(1). :- f(X). """
veltri/DLV2
tests/parser/grounding_only.2.test.py
Python
apache-2.0
71
package net.moopa3376.guard.fliter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.moopa3376.guard.config.GuardConfigs; import net.moopa3376.guard.jwt.JwtWrapper; /** * Created by Moopa on 17/07/2017. * blog: moopa.net * * @autuor : Moopa */ public class TokenFilter implements Filter{ public static long expireIntervalTime = 12000; public void init(FilterConfig filterConfig) throws ServletException { } /** * 该方法主要是针对即将过期的jwt token进行更新 * @param servletRequest * @param servletResponse * @param filterChain * @throws IOException * @throws ServletException */ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { filterChain.doFilter(servletRequest,servletResponse); //首先获取token String token = ((HttpServletRequest)servletRequest).getHeader("X-token"); //token == null 表示该请求并不需要登录 - 因为前面已经有guard在过滤了 if(token == null){ return; } long current = System.currentTimeMillis(); String expire = JwtWrapper.getValInPayload(token,"expire"); long expire_l = Long.valueOf(expire); if(expire_l - current <= expireIntervalTime){ //更新token String res = JwtWrapper.updateJwt(token,expire, String.valueOf(current+Long.valueOf(GuardConfigs.get("expire_time")))); //在response中更新token ((HttpServletResponse)servletResponse).setHeader("X-token",res); } } public void destroy() { } }
moopa3376/guard
guard-web/src/main/java/net/moopa3376/guard/fliter/TokenFilter.java
Java
apache-2.0
1,987
package don.sphere; import don.sphere.exif.IFDEntry; import okio.Buffer; import okio.ByteString; import java.io.EOFException; import java.io.IOException; import java.text.ParseException; /** * Created by Don on 30.07.2015. */ public class ExifUtil extends SectionParser<SectionExif> { public static final ByteString EXIF_HEADER = ByteString.encodeUtf8("Exif\0\0"); public static final int EXIF_HEADER_SIZE = 6; public static final ByteString ALIGN_INTEL = ByteString.decodeHex("49492A00"); public static final ByteString ALIGN_MOTOROLA = ByteString.decodeHex("4d4d002A"); @Override public String toString() { return "ExifUtil{}"; } @Override public boolean canParse(int marker, int length, Buffer data) { if (marker != JpegParser.JPG_APP1) return false; Log.d("EXIF", "MAYBE PARSE - " + data.indexOfElement(EXIF_HEADER)); return data.indexOfElement(EXIF_HEADER) == 0; } @Override public SectionExif parse(int marker, int length, Buffer data) throws ParseException, IOException { data.skip(EXIF_HEADER_SIZE); SectionExif sectionExif = new SectionExif(); final ByteString alignemnt = data.readByteString(4); if (alignemnt.rangeEquals(0, ALIGN_INTEL, 0, 4)) sectionExif.setByteOrder(SectionExif.ByteOrder.INTEL); else if (alignemnt.rangeEquals(0, ALIGN_MOTOROLA, 0, 4)) sectionExif.setByteOrder(SectionExif.ByteOrder.MOTOROLA); else throw new ParseException("Couldnt parse exif section. Unknown ALignment", 2); if (sectionExif.getByteOrder() == SectionExif.ByteOrder.INTEL) parseIntelByteOrder(sectionExif, data); else parseIntelByteOrder(sectionExif, data); return sectionExif; } private void parseMotorolaByteOrder(SectionExif exif, Buffer source) { } private void parseIntelByteOrder(SectionExif exif, Buffer source) throws EOFException { //Read first IFD OFFSET AND SKIP final int offset = source.readIntLe() - 8; source.skip(offset); while (true) { final int ifdEntries = source.readShortLe(); Log.d("IFD BLOCK", "START==== " + ifdEntries + " Entries"); int tag, dataFormat, dataComponents, dataBlock; for (int i = 0; i < ifdEntries; i++) { //PARSE IFD ENTRY tag = source.readShortLe(); dataFormat = source.readShortLe(); dataComponents = source.readIntLe(); Buffer offsetBuffer = new Buffer(); if (IFDEntry.tagBytes(dataFormat) * dataComponents > 4) { source.copyTo(offsetBuffer, (exif.getByteOrder() == SectionExif.ByteOrder.INTEL) ? source.readIntLe() : source.readInt(), dataComponents); } else { source.copyTo(offsetBuffer, 0, 4); } exif.addIFDEntry(IFDEntry.create(exif.getByteOrder(), tag, dataFormat, dataComponents, offsetBuffer)); offsetBuffer.close(); } int ifdBlockOffset = source.readIntLe(); if (ifdBlockOffset == 0) { //No further ifd block Log.d("IFD BLOCK", "LAST===="); break; } else { Log.d("IFD BLOCK", "NEXT BLOCK OFFSET: " + ifdBlockOffset); source.skip(ifdBlockOffset); } Log.d("IFD BLOCK", "END===="); } } }
donmahallem/SphereEdit
src/main/java/don/sphere/ExifUtil.java
Java
apache-2.0
3,530
/* eslint-env browser */ (function() { 'use strict'; // Check to make sure service workers are supported in the current browser, // and that the current page is accessed from a secure origin. Using a // service worker from an insecure origin will trigger JS console errors. See // http://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features var isLocalhost = Boolean(window.location.hostname === 'localhost' || // [::1] is the IPv6 localhost address. window.location.hostname === '[::1]' || // 127.0.0.1/8 is considered localhost for IPv4. window.location.hostname.match( /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ ) ); if ('serviceWorker' in navigator && (window.location.protocol === 'https:' || isLocalhost)) { navigator.serviceWorker.register('service-worker.js') .then(function(registration) { // Check to see if there's an updated version of service-worker.js with // new files to cache: // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-registration-update-method if (typeof registration.update === 'function') { registration.update(); } // updatefound is fired if service-worker.js changes. registration.onupdatefound = function() { // updatefound is also fired the very first time the SW is installed, // and there's no need to prompt for a reload at that point. // So check here to see if the page is already controlled, // i.e. whether there's an existing service worker. if (navigator.serviceWorker.controller) { // The updatefound event implies that registration.installing is set: // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event var installingWorker = registration.installing; installingWorker.onstatechange = function() { switch (installingWorker.state) { case 'installed': // At this point, the old content will have been purged and the // fresh content will have been added to the cache. // It's the perfect time to display a 'New content is // available; please refresh.' message in the page's interface. break; case 'redundant': throw new Error('The installing ' + 'service worker became redundant.'); default: // Ignore } }; } }; }).catch(function(e) { console.error('Error during service worker registration:', e); }); } // Your custom JavaScript goes here // var rss_tuoitre = 'http://tuoitre.vn/rss/tt-tin-moi-nhat.rss'; // var rss_vnexpress = 'http://vnexpress.net/rss/tin-moi-nhat.rss'; var rssReader = 'yql'; var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor); function urlBuilder(type, url) { if (type === "rss") { if (rssReader === 'google') { return 'https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=20&q=' + url; } else if (rssReader === 'yql') { return 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20rss%20where%20url%3D%22' + url + '%22&format=json'; } } else { return url; } } var displayDiv = document.getElementById('mainContent'); // Part 1 - Create a function that returns a promise function getJsonAsync(url) { // Promises require two functions: one for success, one for failure return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onload = () => { if (xhr.readyState == 4 && xhr.status === 200) { // We can resolve the promise resolve(xhr.response); } else { // It's a failure, so let's reject the promise reject('Unable to load RSS'); } } xhr.onerror = () => { // It's a failure, so let's reject the promise reject('Unable to load RSS'); }; xhr.send(); }); } function getNewsDetail(type, link, callback) { if (type === "json") { callback(news[link]); return; } // get news detail by using rest api which are created by import.io showLoading(); var connector = 'e920a944-d799-4ed7-a017-322eb25ace70'; if (link.indexOf('tuoitre.vn') > -1) { connector = 'bdf72c89-c94b-48f4-967b-b5bc3f8288f7'; } else if (link.indexOf('vnexpress.net') > -1 || link.indexOf('gamethu.net') > -1) { connector = 'e920a944-d799-4ed7-a017-322eb25ace70'; } $.ajax({ url: 'https://api.import.io/store/connector/' + connector + '/_query', data: { input: 'webpage/url:' + link, _apikey: '59531d5e38004cbd944872b657c479fb6eb8a951555700c13023482aad713db52a65da670cd35dbe42a8fc32301bb78f419cba619c4c1c2e66ecde01de25b90dc014dece32953d8ad7c9de7ad788a261' }, success: function(response) { callback(response.results[0]); }, error: function(error) { showDialog({ title: 'Error', text: error }) }, complete: function() { hideLoading(); } }); } var news = []; function loadNews(type, url) { showLoading(); url = urlBuilder(type, url); var promise = $.ajax({ url: url, // crossDomain: true, // dataType: "jsonp" }); promise.done(function(response) { displayDiv.innerHTML = ''; if (type === "rss") { if (rssReader === 'google') { if (response.responseData.feed) { news = response.responseData.feed.entries; } else { news = response.query.results.item; } } else if (rssReader === 'yql') { news = response.query.results.item; } } else if (type === "json") { news = response.results.results || response.results.items || response.results.collection1; } news.forEach(item => { displayDiv.innerHTML += getTemplateNews(item); }); $('button.simple-ajax-popup').on('click', function(e) { e.preventDefault(); var link = $(this).data('link'); console.log(link); if (!link) { showDialog({ title: 'no link', text: link }) return; } if (type === "json") { link = $(this).parents('.news-item').index(); }; getNewsDetail(type, link, function(detail) { var content_html = detail.content_html || detail.content; if (!isChrome) { content_html = content_html.replace(new RegExp('.webp', 'g'), ''); } var $content = $('<div>' + content_html + '</div'); $content.find('.nocontent').remove(); // var $content = $(content_html).siblings(".nocontent").remove(); showDialog({ title: detail.title, text: $content.html() }) }) }); }).complete(function() { hideLoading(); }); } function getTemplateNews(news) { if (!news.content) { news.content = news.description || ""; } news.content = news.content.replace(new RegExp('/s146/', 'g'), '/s440/'); news.summary = news.summary || news.content; if (!news.image && news.summary.indexOf('<img ') === -1 && news.content.indexOf('<img ') > -1) { news.image = $(news.content).find('img:first-child').attr('src'); } news.image = (news.image) ? `<img src="${news.image.replace(new RegExp('/s146/', 'g'), '/s440/')}" />` : ''; if (!isChrome) { news.image = news.image.replace(new RegExp('.webp', 'g'), ''); } news.time = news.time || news.publishedDate || news.pubDate || ''; news.link = news.link || news.url; news.sourceText = news.source ? ' - ' + news.source.text : ''; return `<div class='news-item mdl-color-text--grey-700 mdl-shadow--2dp'> <div class='news-item__title'> <div class='news-item__title-text mdl-typography--title'> ${news.title} </div> <div class='news-item__title-time'>${news.time} <b>${news.sourceText}</b></div> </div> <div class='news-item__content'> ${news.image} ${news.summary} </div> <div class='news-item__actions'> <button data-link='${news.link}' class='mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect simple-ajax-popup'> View more </button> <a href='${news.link}' target='_blank' class='mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect simple-ajax-popup'> Open web </a> </div> </div>` } $('.change-news').click(function(e) { loadNews($(this).data('type'), $(this).data('url')); $(".mdl-layout__obfuscator").click(); }); $('.change-news:first-child').click(); // PLUGIN mdl-jquery-modal-dialog.js function showLoading() { // remove existing loaders $('.loading-container').remove(); $('<div id="orrsLoader" class="loading-container"><div><div class="mdl-spinner mdl-js-spinner is-active"></div></div></div>').appendTo("body"); componentHandler.upgradeElements($('.mdl-spinner').get()); setTimeout(function() { $('#orrsLoader').css({ opacity: 1 }); }, 1); } function hideLoading() { $('#orrsLoader').css({ opacity: 0 }); setTimeout(function() { $('#orrsLoader').remove(); }, 400); } function showDialog(options) { options = $.extend({ id: 'orrsDiag', title: null, text: null, negative: false, positive: false, cancelable: true, contentStyle: null, onLoaded: false }, options); // remove existing dialogs $('.dialog-container').remove(); $(document).unbind("keyup.dialog"); $('<div id="' + options.id + '" class="dialog-container"><div class="mdl-card mdl-shadow--16dp"></div></div>').appendTo("body"); var dialog = $('#orrsDiag'); var content = dialog.find('.mdl-card'); if (options.contentStyle != null) content.css(options.contentStyle); if (options.title != null) { $('<h5>' + options.title + '</h5>').appendTo(content); } if (options.text != null) { $('<p>' + options.text + '</p>').appendTo(content); } if (options.negative || options.positive) { var buttonBar = $('<div class="mdl-card__actions dialog-button-bar"></div>'); if (options.negative) { options.negative = $.extend({ id: 'negative', title: 'Cancel', onClick: function() { return false; } }, options.negative); var negButton = $('<button class="mdl-button mdl-js-button mdl-js-ripple-effect" id="' + options.negative.id + '">' + options.negative.title + '</button>'); negButton.click(function(e) { e.preventDefault(); if (!options.negative.onClick(e)) hideDialog(dialog) }); negButton.appendTo(buttonBar); } if (options.positive) { options.positive = $.extend({ id: 'positive', title: 'OK', onClick: function() { return false; } }, options.positive); var posButton = $('<button class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect" id="' + options.positive.id + '">' + options.positive.title + '</button>'); posButton.click(function(e) { e.preventDefault(); if (!options.positive.onClick(e)) hideDialog(dialog) }); posButton.appendTo(buttonBar); } buttonBar.appendTo(content); } componentHandler.upgradeDom(); if (options.cancelable) { dialog.click(function() { hideDialog(dialog); }); $(document).bind("keyup.dialog", function(e) { if (e.which == 27) hideDialog(dialog); }); content.click(function(e) { e.stopPropagation(); }); } setTimeout(function() { dialog.css({ opacity: 1 }); if (options.onLoaded) options.onLoaded(); }, 1); } function hideDialog(dialog) { $(document).unbind("keyup.dialog"); dialog.css({ opacity: 0 }); setTimeout(function() { dialog.remove(); }, 400); } })();
leetrunghoo/surfnews
app/scripts/main.js
JavaScript
apache-2.0
15,008
<?php defined('XAPP') || require_once(dirname(__FILE__) . '/../../../Core/core.php'); xapp_import('xapp.Log.Exception'); /** * Log writer exception class * * @package Log * @subpackage Log_Writer * @class Xapp_Log_Writer_Exception * @author Frank Mueller <support@xapp-studio.com> */ class Xapp_Log_Writer_Exception extends Xapp_Log_Exception { /** * error exception class constructor directs instance * to error xapp error handling * * @param string $message excepts error message * @param int $code expects error code * @param int $severity expects severity flag */ public function __construct($message, $code = 0, $severity = XAPP_ERROR_ERROR) { parent::__construct($message, $code, $severity); xapp_error($this); } }
back1992/ticool
components/com_xas/xapp/lib/rpc/lib/vendor/xapp/Log/Writer/Exception/Exception.php
PHP
apache-2.0
797
package com.turnos.cliente.conexion; import java.util.Date; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status.Family; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; import com.turnos.datos.WebServUtils; import com.turnos.datos.vo.ComentarioBean; import com.turnos.datos.vo.ETLTBean; import com.turnos.datos.vo.FestivoBean; import com.turnos.datos.vo.MensajeBean; import com.turnos.datos.vo.MunicipioBean; import com.turnos.datos.vo.PaisBean; import com.turnos.datos.vo.PropuestaCambioBean; import com.turnos.datos.vo.ProvinciaBean; import com.turnos.datos.vo.ResidenciaBean; import com.turnos.datos.vo.RespuestaBean; import com.turnos.datos.vo.ServicioBean; import com.turnos.datos.vo.SesionBean; import com.turnos.datos.vo.TrabajadorBean; import com.turnos.datos.vo.TurnoBean; import com.turnos.datos.vo.TurnoTrabajadorDiaBean; import com.turnos.datos.vo.UsuarioBean; public class ClienteREST { public static enum MetodoHTTP{GET, POST, PUT, DELETE, OPTIONS, HEAD}; public static SesionBean login(String tokenLogin, Aplicacion aplicacion) { Hashtable<String, String> headerParams = new Hashtable<String, String>(1); headerParams.put("tokenLogin", tokenLogin); RespuestaBean<SesionBean> respuesta = llamada(aplicacion, new SesionBean(), WebServUtils.PREF_AUTH_PATH + WebServUtils.PREF_LOGIN_PATH, MetodoHTTP.GET, null, null, headerParams, null); if (respuesta != null && respuesta.getResultado() != null) { return respuesta.getResultado(); } else { //TODO ( probablemente lanzar excepcion (??) ) return null; } } /* public static ResidenciaBean residenciaGetResidencia(String codRes, boolean incGeo, Sesion sesion) { Hashtable<String, String> queryParams = new Hashtable<String, String>(1); queryParams.put(WebServUtils.Q_PARAM_INC_GEO, Boolean.toString(incGeo)); RespuestaBean<ResidenciaBean> respuesta = llamada(sesion, new ResidenciaBean(), WebServUtils.PREF_RES_PATH + '/' + codRes, MetodoHTTP.GET, queryParams, null, null, null); if (respuesta != null && respuesta.getResultado() != null) { return respuesta.getResultado(); } else { //TODO ( probablemente lanzar excepcion (??) ) return null; } } public static List<ResidenciaBean> residenciaListaResidencias(String pais, String provincia, String municipio, boolean incGeo, int limite, int offset, Sesion sesion) { Hashtable<String, String> queryParams = new Hashtable<String, String>(6); if (pais != null) { queryParams.put(WebServUtils.Q_PARAM_COD_PAIS, pais); } if (provincia != null) { queryParams.put(WebServUtils.Q_PARAM_COD_PROV, provincia); } if (municipio != null) { queryParams.put(WebServUtils.Q_PARAM_COD_MUNI, municipio); } if (limite > 0) { queryParams.put(WebServUtils.Q_PARAM_LIMITE, Integer.toString(limite)); } if (offset > 0) { queryParams.put(WebServUtils.Q_PARAM_OFFSET, Integer.toString(offset)); } queryParams.put(WebServUtils.Q_PARAM_INC_GEO, Boolean.toString(incGeo)); RespuestaBean<ResidenciaBean> respuesta = llamada(sesion, new ResidenciaBean(), WebServUtils.PREF_RES_PATH, MetodoHTTP.GET, queryParams, null, null, null); if (respuesta != null && respuesta.getResultado() != null) { return respuesta.getListaResultados(); } else { //TODO ( probablemente lanzar excepcion (??) ) return null; } } public static TrabajadorBean trabajadorGetTrabajador(String codRes, String codTrab, Sesion sesion) { RespuestaBean<TrabajadorBean> respuesta = llamada(sesion, new TrabajadorBean(), WebServUtils.PREF_RES_PATH + '/' + codRes + WebServUtils.PREF_TRAB_PATH + '/' + codTrab, MetodoHTTP.GET, null, null, null, null); if (respuesta != null && respuesta.getResultado() != null) { return respuesta.getResultado(); } else { //TODO ( probablemente lanzar excepcion (??) ) return null; } } //*/ /* ************************************ */ public static MensajeBean mensajeGetMensaje(long arg0, long arg1, int arg2, boolean arg3, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static int mensajeGetNumMensajes(long arg0, boolean arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return -1; } public static int mensajeGetNumRespuestas(long arg0, long arg1, boolean arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return -1; } public static List<MensajeBean> mensajeListaMensajes(long arg0, String arg1, boolean arg2, boolean arg3, int arg4, int arg5, int arg6, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<MensajeBean> mensajeListaRespuestas(long arg0, long arg1, boolean arg2, boolean arg3, int arg4, int arg5, int arg6, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static MensajeBean mensajeNuevoMensaje(MensajeBean arg0, long arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static boolean mensajeSetMensajeLeido(long arg0, long arg1, boolean arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static boolean mensajeSetMensajeNoLeido(long arg0, long arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static boolean mensajeSetMensajeSiLeido(long arg0, long arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static UsuarioBean usuarioCambiaNivelUsuario(int arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static UsuarioBean usuarioGetUsuario(int arg0, boolean arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static UsuarioBean usuarioModUsuario(UsuarioBean arg0, int arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static UsuarioBean usuarioNuevoUsuario(UsuarioBean arg0, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static boolean turnoBorraTurno(String arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static TurnoBean turnoGetTurno(String arg0, String arg1, boolean arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<TurnoBean> turnoListaTurnos(String arg0, String arg1, boolean arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static TurnoBean turnoModTurno(TurnoBean arg0, String arg1, String arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static TurnoBean turnoNuevoTurno(TurnoBean arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<FestivoBean> municipioGetFestivosMunicipio(String codPais, String codProvincia, String codMunicipio, Date time_ini, Date time_fin, boolean completo, boolean inc_geo, int limite, int offset, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static MunicipioBean municipioGetMunicipio(String arg0, String arg1, String arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<ResidenciaBean> municipioGetResidenciasMunicipio(String arg0, String arg1, String arg2, boolean arg3, int arg4, int arg5, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<MunicipioBean> municipioListaMunicipios(String arg0, String arg1, int arg2, int arg3, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static boolean residenciaBorraResidencia(String arg0, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static List<FestivoBean> residenciaGetDiasFestivos(String arg0, Date time_ini, Date time_fin, int arg3, int arg4, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<TurnoTrabajadorDiaBean> residenciaGetHorarioCompletoDia(String arg0, Date time, int arg2, int arg3, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static ResidenciaBean residenciaGetResidencia(String codRes, boolean incGeo, Sesion sesion) { Hashtable<String, String> queryParams = new Hashtable<String, String>(1); queryParams.put(WebServUtils.Q_PARAM_INC_GEO, Boolean.toString(incGeo)); RespuestaBean<ResidenciaBean> respuesta = llamada(sesion, new ResidenciaBean(), WebServUtils.PREF_RES_PATH + '/' + codRes, MetodoHTTP.GET, queryParams, null, null, null); if (respuesta != null && respuesta.getResultado() != null) { return respuesta.getResultado(); } else { //TODO ( probablemente lanzar excepcion (??) ) return null; } } public static List<ResidenciaBean> residenciaListaResidencias(String pais, String provincia, String municipio, boolean incGeo, int limite, int offset, Sesion sesion) { Hashtable<String, String> queryParams = new Hashtable<String, String>(6); if (pais != null) { queryParams.put(WebServUtils.Q_PARAM_COD_PAIS, pais); } if (provincia != null) { queryParams.put(WebServUtils.Q_PARAM_COD_PROV, provincia); } if (municipio != null) { queryParams.put(WebServUtils.Q_PARAM_COD_MUNI, municipio); } if (limite > 0) { queryParams.put(WebServUtils.Q_PARAM_LIMITE, Integer.toString(limite)); } if (offset > 0) { queryParams.put(WebServUtils.Q_PARAM_OFFSET, Integer.toString(offset)); } queryParams.put(WebServUtils.Q_PARAM_INC_GEO, Boolean.toString(incGeo)); RespuestaBean<ResidenciaBean> respuesta = llamada(sesion, new ResidenciaBean(), WebServUtils.PREF_RES_PATH, MetodoHTTP.GET, queryParams, null, null, null); if (respuesta != null && respuesta.getResultado() != null) { return respuesta.getListaResultados(); } else { //TODO ( probablemente lanzar excepcion (??) ) return null; } } public static ResidenciaBean residenciaModResidencia(ResidenciaBean arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static ResidenciaBean residenciaNuevaResidencia(ResidenciaBean arg0, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static boolean servicioBorraServicio(String arg0, String arg1, long arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static ServicioBean servicioGetServicio(String arg0, String arg1, long arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<ServicioBean> servicioListaServicios(String arg0, String arg1, int arg2, int arg3, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static ServicioBean servicioModServicio(ServicioBean arg0, String arg1, String arg2, long arg3, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static ServicioBean servicioNuevoServicio(ServicioBean arg0, String arg1, String arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static boolean festivoBorraDiaFestivo(long arg0, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static FestivoBean festivoGetDiaFestivo(long arg0, boolean arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<FestivoBean> festivoListaDiasFestivos(String codPais, String codProvincia, String codMunicipio, String tipoStr, Date time_ini, Date time_fin, boolean completo, boolean incGeo, int limite, int offset, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static FestivoBean festivoModDiaFestivo(FestivoBean arg0, long arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static FestivoBean festivoNuevoDiaFestivo(FestivoBean arg0, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static boolean comentarioBorraComentario(long arg1, long arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static ComentarioBean comentarioNuevoComentario(ComentarioBean arg0, long arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<FestivoBean> paisGetFestivosPais(String codPais, Date time_ini, Date time_fin, boolean inc_geo, int limite, int offset, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static PaisBean paisGetPais(String arg0, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<ResidenciaBean> paisGetResidenciasPais(String arg0, boolean arg1, int arg2, int arg3, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<PaisBean> paisListaPaises(int arg0, int arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<FestivoBean> provinciaGetFestivosProvincia(String codPais, String codProvincia, Date time_ini, Date time_fin, boolean completo, boolean inc_geo, int limite, int offset, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static ProvinciaBean provinciaGetProvincia(String arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<ResidenciaBean> provinciaGetResidenciasProvincia(String arg0, String arg1, boolean arg2, int arg3, int arg4, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<ProvinciaBean> provinciaListaProvincias(String arg0, int arg1, int arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static boolean trabajadorBorraTrabajador(String arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static TurnoTrabajadorDiaBean trabajadorGetHorarioTrabajadorDia(String arg0, String arg1, int arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<TurnoTrabajadorDiaBean> trabajadorGetHorarioTrabajadorRango(String arg0, String arg1, int arg2, int arg3, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static int trabajadorGetNumPropuestasCambio(String arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return -1; } public static List<PropuestaCambioBean> trabajadorGetPropuestasCambio(String arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static TrabajadorBean trabajadorGetTrabajador(String codRes, String codTrab, Sesion sesion) { RespuestaBean<TrabajadorBean> respuesta = llamada(sesion, new TrabajadorBean(), WebServUtils.PREF_RES_PATH + '/' + codRes + WebServUtils.PREF_TRAB_PATH + '/' + codTrab, MetodoHTTP.GET, null, null, null, null); if (respuesta != null && respuesta.getResultado() != null) { return respuesta.getResultado(); } else { //TODO ( probablemente lanzar excepcion (??) ) return null; } } public static List<TrabajadorBean> trabajadorListaTrabajadores(String arg0, int arg1, int arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static TrabajadorBean trabajadorModTrabajador(TrabajadorBean arg0, String arg1, String arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static TrabajadorBean trabajadorNuevoTrabajador(TrabajadorBean arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static PropuestaCambioBean propuestacambioNuevoPropuestaCambio( PropuestaCambioBean rawBean, Sesion sesion) { // TODO Auto-generated method stub return null; } public static PropuestaCambioBean propuestacambioModPropuestaCambio( PropuestaCambioBean rawBean, long id_cambio, Sesion sesion) { // TODO Auto-generated method stub return null; } public static List<PropuestaCambioBean> propuestacambioListaPropuestaCambios(String estado, Sesion sesion) { // TODO Auto-generated method stub return null; } public static PropuestaCambioBean propuestacambioGetPropuestaCambio(long id_cambio, boolean b, Sesion sesion) { // TODO Auto-generated method stub return null; } public static boolean propuestacambioBorraPropuestaCambio(long id_cambio, Sesion sesion) { // TODO Auto-generated method stub return false; } /* ************************************ */ private static <T extends ETLTBean> RespuestaBean<T> llamada( Aplicacion aplicacion, T tipo, String recurso, MetodoHTTP metodo, Map<String, String> queryParams, Map<String, String> postParams, Map<String, String> headerParams, String jsonBody) { System.out.println(" ***** LLAMANDO *** (" + recurso + ", " + metodo + ", " + queryParams + ", " + jsonBody + ") *****"); RespuestaBean<T> res = new RespuestaBean<T>(); Client client = null; try { client = ClientBuilder.newClient().register(JacksonJaxbJsonProvider.class); WebTarget target = client.target(aplicacion.baseURL).path(recurso); if(queryParams != null && !queryParams.isEmpty()) { for(Entry<String, String> entry: queryParams.entrySet()) { target = target.queryParam(entry.getKey(), entry.getValue()); } } Builder b = target.request(MediaType.APPLICATION_JSON_TYPE); if (headerParams == null) { headerParams = new Hashtable<String, String>(1); } headerParams.put("publicKey", aplicacion.publicKey); b = b.headers(new MultivaluedHashMap<String, Object>(headerParams)); Response rp; switch(metodo) { case GET: rp = b.get(); break; case POST: rp = b.post(Entity.entity(jsonBody, MediaType.APPLICATION_JSON_TYPE)); break; case PUT: rp = b.put(Entity.entity(jsonBody, MediaType.APPLICATION_JSON_TYPE)); break; case DELETE: rp = b.delete(); break; default: return null; } if (rp.getStatusInfo().getFamily() == Family.SUCCESSFUL) { res = rp.readEntity(RespuestaBean.class); } else { //TODO // System.out.println("****** MAL ******" + rp); } } finally { if(client != null) client.close(); } return res; } public static <T extends ETLTBean> RespuestaBean<T> llamada(Sesion sesion, T tipo, String recurso, MetodoHTTP metodo, Map<String, String> queryParams, Map<String, String> postParams, Map<String, String> headerParams, String jsonBody) { if (headerParams == null) { headerParams = new Hashtable<String, String>(1); } headerParams.put("tokenSesion", sesion.getTokenSesion()); return llamada(sesion.aplicacion, tipo, recurso, metodo, queryParams, postParams, headerParams, jsonBody); } }
catoyos-turnos/ETLT-DESA
ClienteAPI/1.0/ETLTClienteAPI_1.0/src/com/turnos/cliente/conexion/ClienteREST.java
Java
apache-2.0
20,545
package de.atomfrede.jenkins.domain.coverage; import java.io.Serializable; public class ClassCoverage implements Serializable { private static final long serialVersionUID = -8132894251774828498L; private int percentage; private float percentageFloat; public int getPercentage() { return percentage; } public void setPercentage(int percentage) { this.percentage = percentage; } public float getPercentageFloat() { return percentageFloat; } public void setPercentageFloat(float percentageFloat) { this.percentageFloat = percentageFloat; } }
atomfrede/animated-octo-adventure
jenkins.service/src/main/java/de/atomfrede/jenkins/domain/coverage/ClassCoverage.java
Java
apache-2.0
568
#!/usr/bin/ruby # # Author:: api.sgomes@gmail.com (Sérgio Gomes) # # Copyright:: Copyright 2011, Google Inc. All Rights Reserved. # # License:: 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. # # This example illustrates how to update an ad, setting its status to 'PAUSED'. # To create ads, run add_ads.rb. # # Tags: AdGroupAdService.mutate require 'rubygems' gem 'google-adwords-api' require 'adwords_api' API_VERSION = :v201003 def update_ad() # AdwordsApi::Api will read a config file from ENV['HOME']/adwords_api.yml # when called without parameters. adwords = AdwordsApi::Api.new ad_group_ad_srv = adwords.service(:AdGroupAdService, API_VERSION) ad_group_id = 'INSERT_AD_GROUP_ID_HERE'.to_i ad_id = 'INSERT_AD_ID_HERE'.to_i # Prepare for updating ad. operation = { :operator => 'SET', :operand => { :ad_group_id => ad_group_id, :status => 'PAUSED', :ad => { :id => ad_id } } } # Update ad. response = ad_group_ad_srv.mutate([operation]) if response and response[:value] ad = response[:value].first puts 'Ad id %d was successfully updated, status set to %s.' % [ad[:ad][:id], ad[:status]] else puts 'No ads were updated.' end end if __FILE__ == $0 # To enable logging of SOAP requests, set the ADWORDSAPI_DEBUG environment # variable to 'true'. This can be done either from your operating system # environment or via code, as done below. ENV['ADWORDSAPI_DEBUG'] = 'false' begin update_ad() # Connection error. Likely transitory. rescue Errno::ECONNRESET, SOAP::HTTPStreamError, SocketError => e puts 'Connection Error: %s' % e puts 'Source: %s' % e.backtrace.first # API Error. rescue AdwordsApi::Errors::ApiException => e puts 'API Exception caught.' puts 'Message: %s' % e.message puts 'Code: %d' % e.code if e.code puts 'Trigger: %s' % e.trigger if e.trigger puts 'Errors:' if e.errors e.errors.each_with_index do |error, index| puts ' %d. Error type is %s. Fields:' % [index + 1, error[:xsi_type]] error.each_pair do |field, value| if field != :xsi_type puts ' %s: %s' % [field, value] end end end end end end
sylow/google-adwords-api
examples/v201003/update_ad.rb
Ruby
apache-2.0
2,835
package com.jarvis.cache.serializer.hession; import com.caucho.hessian.io.AbstractHessianInput; import com.caucho.hessian.io.AbstractMapDeserializer; import com.caucho.hessian.io.IOExceptionWrapper; import java.io.IOException; import java.lang.ref.WeakReference; /** * */ public class WeakReferenceDeserializer extends AbstractMapDeserializer { @Override public Object readObject(AbstractHessianInput in, Object[] fields) throws IOException { try { WeakReference<Object> obj = instantiate(); in.addRef(obj); Object value = in.readObject(); obj = null; return new WeakReference<Object>(value); } catch (IOException e) { throw e; } catch (Exception e) { throw new IOExceptionWrapper(e); } } protected WeakReference<Object> instantiate() throws Exception { Object obj = new Object(); return new WeakReference<Object>(obj); } }
qiujiayu/AutoLoadCache
autoload-cache-serializer/autoload-cache-serializer-hessian/src/main/java/com/jarvis/cache/serializer/hession/WeakReferenceDeserializer.java
Java
apache-2.0
985
/** * */ package jdk13.String; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; /** * @author yinxb */ class StringTest { @Test void test() { String html = """ <html> <body> <p>Hello, world</p> </body> </html> """; } }
zooltech/samples
java/jdk/src/test/java/jdk13/String/StringTest.java
Java
apache-2.0
396
/* * ../../../..//fonts/HTML-CSS/TeX/png/AMS/Regular/BBBold.js * * Copyright (c) 2009-2018 The MathJax Consortium * * 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. */ /************************************************************* * * MathJax/fonts/HTML-CSS/TeX/png/AMS/Regular/BBBold.js * * Defines the image size data needed for the HTML-CSS OutputJax * to display mathematics using fallback images when the fonts * are not available to the client browser. * * --------------------------------------------------------------------- * * Copyright (c) 2009-2013 The MathJax Consortium * * 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 * * 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. * */ MathJax.OutputJax["HTML-CSS"].defineImageData({ MathJax_AMS: { 0x20: [ // SPACE [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0] ], 0x41: [ // LATIN CAPITAL LETTER A [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 10, 0], [12, 12, 0], [14, 14, 0], [17, 16, 0], [20, 19, 0], [23, 23, 0], [28, 27, 0], [33, 33, 0], [39, 39, 0], [46, 46, 0] ], 0x42: [ // LATIN CAPITAL LETTER B [5, 5, 0], [6, 6, 0], [7, 7, 0], [8, 8, 0], [9, 9, 0], [11, 11, 0], [13, 13, 0], [15, 16, 0], [18, 19, 0], [21, 22, 0], [25, 27, 0], [29, 32, 0], [35, 38, 0], [41, 45, 0] ], 0x43: [ // LATIN CAPITAL LETTER C [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 10, 0], [12, 12, 0], [14, 14, 0], [16, 16, 0], [19, 21, 2], [23, 24, 1], [27, 28, 1], [32, 34, 1], [38, 40, 1], [45, 48, 2] ], 0x44: [ // LATIN CAPITAL LETTER D [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [14, 13, 0], [16, 16, 0], [20, 19, 0], [23, 22, 0], [27, 27, 0], [32, 32, 0], [39, 38, 0], [46, 45, 0] ], 0x45: [ // LATIN CAPITAL LETTER E [5, 5, 0], [6, 6, 0], [7, 7, 0], [8, 8, 0], [9, 9, 0], [11, 11, 0], [13, 13, 0], [15, 16, 0], [18, 19, 0], [22, 22, 0], [26, 27, 0], [30, 32, 0], [36, 38, 0], [43, 45, 0] ], 0x46: [ // LATIN CAPITAL LETTER F [5, 5, 0], [5, 6, 0], [6, 7, 0], [7, 8, 0], [9, 9, 0], [10, 11, 0], [12, 13, 0], [14, 16, 0], [17, 19, 0], [20, 22, 0], [23, 27, 0], [27, 32, 0], [33, 38, 0], [39, 45, 0] ], 0x47: [ // LATIN CAPITAL LETTER G [6, 5, 0], [7, 6, 0], [8, 7, 0], [9, 8, 0], [11, 10, 0], [13, 12, 0], [15, 14, 0], [18, 16, 0], [21, 19, 0], [25, 24, 1], [30, 29, 2], [35, 33, 0], [42, 40, 1], [50, 47, 1] ], 0x48: [ // LATIN CAPITAL LETTER H [6, 5, 0], [7, 6, 0], [8, 7, 0], [9, 8, 0], [11, 9, 0], [13, 11, 0], [15, 13, 0], [18, 16, 0], [22, 19, 0], [26, 22, 0], [30, 27, 0], [36, 32, 0], [43, 38, 0], [51, 45, 0] ], 0x49: [ // LATIN CAPITAL LETTER I [3, 5, 0], [4, 6, 0], [4, 7, 0], [5, 8, 0], [6, 9, 0], [7, 11, 0], [8, 13, 0], [9, 16, 0], [11, 19, 0], [13, 22, 0], [15, 27, 0], [18, 32, 0], [21, 38, 0], [25, 45, 0] ], 0x4a: [ // LATIN CAPITAL LETTER J [4, 6, 1], [4, 7, 1], [5, 8, 1], [6, 9, 1], [7, 11, 2], [8, 13, 2], [10, 15, 2], [12, 18, 2], [14, 21, 2], [16, 26, 4], [19, 30, 3], [23, 35, 3], [27, 42, 4], [32, 50, 5] ], 0x4b: [ // LATIN CAPITAL LETTER K [6, 5, 0], [7, 6, 0], [8, 7, 0], [10, 8, 0], [11, 9, 0], [13, 11, 0], [15, 13, 0], [18, 16, 0], [22, 19, 0], [26, 22, 0], [31, 27, 0], [36, 32, 0], [43, 38, 0], [51, 45, 0] ], 0x4c: [ // LATIN CAPITAL LETTER L [5, 5, 0], [6, 6, 0], [7, 7, 0], [8, 8, 0], [9, 9, 0], [11, 11, 0], [13, 13, 0], [15, 16, 0], [18, 19, 0], [22, 22, 0], [26, 27, 0], [30, 32, 0], [36, 38, 0], [43, 45, 0] ], 0x4d: [ // LATIN CAPITAL LETTER M [7, 5, 0], [8, 6, 0], [10, 7, 0], [11, 8, 0], [13, 9, 0], [16, 11, 0], [19, 13, 0], [22, 16, 0], [26, 19, 0], [31, 22, 0], [37, 27, 0], [44, 32, 0], [52, 38, 0], [61, 45, 0] ], 0x4e: [ // LATIN CAPITAL LETTER N [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 9, 0], [10, 10, 0], [12, 12, 0], [14, 14, 0], [17, 17, 0], [20, 21, 1], [24, 24, 1], [28, 29, 1], [33, 34, 1], [39, 40, 1], [47, 48, 2] ], 0x4f: [ // LATIN CAPITAL LETTER O [6, 5, 0], [7, 6, 0], [8, 7, 0], [9, 8, 0], [11, 10, 0], [13, 12, 0], [15, 14, 0], [18, 16, 0], [21, 21, 2], [25, 24, 1], [30, 28, 1], [35, 34, 1], [42, 40, 1], [49, 48, 2] ], 0x50: [ // LATIN CAPITAL LETTER P [5, 5, 0], [5, 6, 0], [6, 7, 0], [8, 8, 0], [9, 9, 0], [10, 11, 0], [12, 13, 0], [14, 16, 0], [17, 19, 0], [20, 22, 0], [24, 27, 0], [28, 32, 0], [34, 38, 0], [40, 45, 0] ], 0x51: [ // LATIN CAPITAL LETTER Q [6, 6, 1], [7, 8, 2], [8, 9, 2], [9, 10, 2], [11, 12, 2], [13, 15, 3], [15, 17, 3], [18, 20, 4], [21, 24, 5], [25, 30, 7], [30, 35, 8], [35, 41, 8], [42, 49, 10], [49, 58, 12] ], 0x52: [ // LATIN CAPITAL LETTER R [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [14, 13, 0], [17, 16, 0], [20, 19, 0], [24, 22, 0], [28, 27, 0], [33, 32, 0], [39, 38, 0], [47, 45, 0] ], 0x53: [ // LATIN CAPITAL LETTER S [4, 5, 0], [5, 6, 0], [6, 7, 0], [7, 8, 0], [8, 10, 0], [9, 12, 0], [11, 14, 0], [13, 16, 0], [15, 19, 0], [18, 23, 0], [21, 27, 0], [25, 33, 0], [30, 40, 1], [35, 47, 1] ], 0x54: [ // LATIN CAPITAL LETTER T [5, 5, 0], [6, 6, 0], [7, 7, 0], [8, 8, 0], [9, 9, 0], [11, 11, 0], [13, 13, 0], [15, 16, 0], [18, 19, 0], [21, 22, 0], [25, 27, 0], [30, 32, 0], [36, 38, 0], [42, 45, 0] ], 0x55: [ // LATIN CAPITAL LETTER U [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [14, 13, 0], [17, 16, 0], [20, 19, 0], [24, 22, 0], [28, 28, 1], [33, 33, 1], [40, 39, 1], [47, 46, 1] ], 0x56: [ // LATIN CAPITAL LETTER V [5, 5, 0], [6, 6, 0], [8, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [15, 13, 0], [17, 16, 0], [20, 20, 1], [24, 24, 2], [29, 28, 1], [34, 33, 1], [40, 39, 1], [48, 46, 1] ], 0x57: [ // LATIN CAPITAL LETTER W [7, 5, 0], [9, 6, 0], [10, 7, 0], [12, 8, 0], [14, 9, 0], [17, 11, 0], [20, 13, 0], [24, 16, 0], [28, 20, 1], [33, 24, 2], [39, 28, 1], [47, 33, 1], [55, 39, 1], [66, 47, 2] ], 0x58: [ // LATIN CAPITAL LETTER X [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [14, 13, 0], [17, 16, 0], [20, 19, 0], [24, 22, 0], [28, 27, 0], [33, 32, 0], [39, 38, 0], [47, 45, 0] ], 0x59: [ // LATIN CAPITAL LETTER Y [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [14, 13, 0], [17, 16, 0], [20, 19, 0], [24, 22, 0], [28, 27, 0], [33, 32, 0], [39, 38, 0], [47, 45, 0] ], 0x5a: [ // LATIN CAPITAL LETTER Z [5, 5, 0], [6, 6, 0], [7, 7, 0], [8, 8, 0], [9, 9, 0], [11, 11, 0], [13, 13, 0], [15, 16, 0], [18, 19, 0], [21, 22, 0], [25, 27, 0], [30, 32, 0], [36, 38, 0], [42, 45, 0] ], 0x6b: [ // LATIN SMALL LETTER K [4, 5, 0], [5, 6, 0], [6, 7, 0], [7, 8, 0], [8, 10, 0], [9, 12, 0], [11, 14, 0], [13, 16, 0], [15, 19, 0], [18, 23, 0], [21, 27, 0], [25, 32, 0], [30, 38, 0], [36, 45, 0] ] } }); MathJax.Ajax.loadComplete( MathJax.OutputJax["HTML-CSS"].imgDir + "/AMS/Regular" + MathJax.OutputJax["HTML-CSS"].imgPacked + "/BBBold.js" );
GerHobbelt/MathJax
fonts/HTML-CSS/TeX/png/AMS/Regular/BBBold.js
JavaScript
apache-2.0
10,460
package com.ourcode.models.input; import com.google.gson.annotations.SerializedName; import com.graphhopper.jsprit.core.problem.job.Break; import java.util.ArrayList; /** * Created by LEOLEOl on 5/19/2017. */ public class OCBreak { @SerializedName("breakCode") private String breakCode; @SerializedName("serviceTime") private double serviceTime; // (in hours) @SerializedName("timeWindows") public ArrayList<OCTimeWindow> timeWindows; // (in hours) private Break j_break; public Break _getJ_break() { return j_break; } public double getServiceTime() {return serviceTime;} public void setServiceTime(double serviceTime) {this.serviceTime = serviceTime;} public OCBreak(OCBreak ocBreak) { this.breakCode = ocBreak.breakCode; this.serviceTime = ocBreak.serviceTime; this.timeWindows = new ArrayList<>(); for (OCTimeWindow timeWindow: ocBreak.timeWindows) this.timeWindows.add(new OCTimeWindow(timeWindow)); } public OCBreak build() { Break.Builder builder = Break.Builder.newInstance(breakCode); builder.setServiceTime(serviceTime); for (OCTimeWindow timeWindow: timeWindows) builder.addTimeWindow(timeWindow.build()._getJ_timeWindow()); j_break = builder.build(); return this; } }
LEOLEOl/jsprit-me
viet-jsprit/src/main/java/com/ourcode/models/input/OCBreak.java
Java
apache-2.0
1,371
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.dataflow.examples.complete.game; import com.google.cloud.dataflow.examples.complete.game.UserScore.GameActionInfo; import com.google.cloud.dataflow.examples.complete.game.UserScore.ParseEventFn; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.testing.PAssert; import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.Filter; import com.google.cloud.dataflow.sdk.transforms.MapElements; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; import org.joda.time.Instant; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.Serializable; import java.util.Arrays; import java.util.List; /** * Tests of HourlyTeamScore. * Because the pipeline was designed for easy readability and explanations, it lacks good * modularity for testing. See our testing documentation for better ideas: * https://cloud.google.com/dataflow/pipelines/testing-your-pipeline. */ @RunWith(JUnit4.class) public class HourlyTeamScoreTest implements Serializable { static final String[] GAME_EVENTS_ARRAY = new String[] { "user0_MagentaKangaroo,MagentaKangaroo,3,1447955630000,2015-11-19 09:53:53.444", "user13_ApricotQuokka,ApricotQuokka,15,1447955630000,2015-11-19 09:53:53.444", "user6_AmberNumbat,AmberNumbat,11,1447955630000,2015-11-19 09:53:53.444", "user7_AlmondWallaby,AlmondWallaby,15,1447955630000,2015-11-19 09:53:53.444", "user7_AndroidGreenKookaburra,AndroidGreenKookaburra,12,1447955630000,2015-11-19 09:53:53.444", "user7_AndroidGreenKookaburra,AndroidGreenKookaburra,11,1447955630000,2015-11-19 09:53:53.444", "user19_BisqueBilby,BisqueBilby,6,1447955630000,2015-11-19 09:53:53.444", "user19_BisqueBilby,BisqueBilby,8,1447955630000,2015-11-19 09:53:53.444", // time gap... "user0_AndroidGreenEchidna,AndroidGreenEchidna,0,1447965690000,2015-11-19 12:41:31.053", "user0_MagentaKangaroo,MagentaKangaroo,4,1447965690000,2015-11-19 12:41:31.053", "user2_AmberCockatoo,AmberCockatoo,13,1447965690000,2015-11-19 12:41:31.053", "user18_BananaEmu,BananaEmu,7,1447965690000,2015-11-19 12:41:31.053", "user3_BananaEmu,BananaEmu,17,1447965690000,2015-11-19 12:41:31.053", "user18_BananaEmu,BananaEmu,1,1447965690000,2015-11-19 12:41:31.053", "user18_ApricotCaneToad,ApricotCaneToad,14,1447965690000,2015-11-19 12:41:31.053" }; static final List<String> GAME_EVENTS = Arrays.asList(GAME_EVENTS_ARRAY); // Used to check the filtering. static final KV[] FILTERED_EVENTS = new KV[] { KV.of("user0_AndroidGreenEchidna", 0), KV.of("user0_MagentaKangaroo", 4), KV.of("user2_AmberCockatoo", 13), KV.of("user18_BananaEmu", 7), KV.of("user3_BananaEmu", 17), KV.of("user18_BananaEmu", 1), KV.of("user18_ApricotCaneToad", 14) }; /** Test the filtering. */ @Test @Category(RunnableOnService.class) public void testUserScoresFilter() throws Exception { Pipeline p = TestPipeline.create(); final Instant startMinTimestamp = new Instant(1447965680000L); PCollection<String> input = p.apply(Create.of(GAME_EVENTS).withCoder(StringUtf8Coder.of())); PCollection<KV<String, Integer>> output = input .apply(ParDo.named("ParseGameEvent").of(new ParseEventFn())) .apply("FilterStartTime", Filter.byPredicate( (GameActionInfo gInfo) -> gInfo.getTimestamp() > startMinTimestamp.getMillis())) // run a map to access the fields in the result. .apply(MapElements .via((GameActionInfo gInfo) -> KV.of(gInfo.getUser(), gInfo.getScore())) .withOutputType(new TypeDescriptor<KV<String, Integer>>() {})); PAssert.that(output).containsInAnyOrder(FILTERED_EVENTS); p.run(); } }
shakamunyi/beam
examples/java8/src/test/java/com/google/cloud/dataflow/examples/complete/game/HourlyTeamScoreTest.java
Java
apache-2.0
5,012
/* * UniformBuffer.hpp * * Created on: 21/08/2013 * Author: svp */ #ifndef UNIFORMBUFFER_HPP_ #define UNIFORMBUFFER_HPP_ #include <stddef.h> typedef unsigned int GLuint; typedef unsigned int GLenum; typedef int GLint; namespace renderer { namespace resources { class UniformBuffer { public: UniformBuffer(); virtual ~UniformBuffer(); void enable() const; void disable() const; void bind(GLuint index) const; void data(size_t size, const void* data) const; GLuint buffer; }; } /* namespace resources */ } /* namespace renderer */ #endif /* UNIFORMBUFFER_HPP_ */
vinther/rmit-rendering
include/renderer/resources/UniformBuffer.hpp
C++
apache-2.0
609
package warden import ( "net/http" "net/url" "github.com/ory-am/fosite" "github.com/ory-am/hydra/firewall" "github.com/ory-am/hydra/pkg" "github.com/pkg/errors" "golang.org/x/net/context" "golang.org/x/oauth2" "golang.org/x/oauth2/clientcredentials" ) type HTTPWarden struct { Client *http.Client Dry bool Endpoint *url.URL } func (w *HTTPWarden) TokenFromRequest(r *http.Request) string { return fosite.AccessTokenFromRequest(r) } func (w *HTTPWarden) SetClient(c *clientcredentials.Config) { w.Client = c.Client(oauth2.NoContext) } // TokenAllowed checks if a token is valid and if the token owner is allowed to perform an action on a resource. // This endpoint requires a token, a scope, a resource name, an action name and a context. // // The HTTP API is documented at http://docs.hydra13.apiary.io/#reference/warden:-access-control-for-resource-providers/check-if-an-access-tokens-subject-is-allowed-to-do-something func (w *HTTPWarden) TokenAllowed(ctx context.Context, token string, a *firewall.TokenAccessRequest, scopes ...string) (*firewall.Context, error) { var resp = struct { *firewall.Context Allowed bool `json:"allowed"` }{} var ep = *w.Endpoint ep.Path = TokenAllowedHandlerPath agent := &pkg.SuperAgent{URL: ep.String(), Client: w.Client} if err := agent.POST(&wardenAccessRequest{ wardenAuthorizedRequest: &wardenAuthorizedRequest{ Token: token, Scopes: scopes, }, TokenAccessRequest: a, }, &resp); err != nil { return nil, err } else if !resp.Allowed { return nil, errors.New("Token is not valid") } return resp.Context, nil } // IsAllowed checks if an arbitrary subject is allowed to perform an action on a resource. // // The HTTP API is documented at http://docs.hydra13.apiary.io/#reference/warden:-access-control-for-resource-providers/check-if-a-subject-is-allowed-to-do-something func (w *HTTPWarden) IsAllowed(ctx context.Context, a *firewall.AccessRequest) error { var allowed = struct { Allowed bool `json:"allowed"` }{} var ep = *w.Endpoint ep.Path = AllowedHandlerPath agent := &pkg.SuperAgent{URL: ep.String(), Client: w.Client} if err := agent.POST(a, &allowed); err != nil { return err } else if !allowed.Allowed { return errors.Wrap(fosite.ErrRequestForbidden, "") } return nil }
Bridg/hydra-1
warden/warden_http.go
GO
apache-2.0
2,295
package gumtree.spoon.diff.operations; import com.github.gumtreediff.actions.model.Move; public class MoveOperation extends AdditionOperation<Move> { public MoveOperation(Move action) { super(action); } }
XuSihan/gumtree-spoon-ast-diff
src/main/java/gumtree/spoon/diff/operations/MoveOperation.java
Java
apache-2.0
211