repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
sergeXu/JavaStudy
hrmApp/src/cn/serge/domain/Dept.java
683
package cn.serge.domain; import java.io.Serializable; public class Dept implements Serializable { private Integer id; private String name; private String remark;//ÃèÊö public Dept() { super(); // TODO Auto-generated constructor stub } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } @Override public String toString() { return "Dept [id=" + id + ", name=" + name + ", remark=" + remark + "]"; } }
apache-2.0
DPSablowski/silent
SILENT/fpe.cpp
2280
#include "fpe.h" #include "ui_fpe.h" #include <cmath> FPE::FPE(QWidget *parent) : QDialog(parent), ui(new Ui::FPE) { ui->setupUi(this); this->setWindowTitle("Fabry-Perot-Etalon Tool"); ui->doubleSpinBox->setValue(3); ui->doubleSpinBox_2->setValue(1); ui->doubleSpinBox_3->setValue(0.9); ui->doubleSpinBox_6->setValue(0); ui->customPlot->axisRect()->setupFullAxesBox(true); ui->customPlot->xAxis->setLabel("Wavelength [nm]"); ui->customPlot->yAxis->setLabel("rel. Transmission"); connect(ui->customPlot, SIGNAL(mouseMove(QMouseEvent*)), this ,SLOT(showPointToolTip(QMouseEvent*))); } FPE::~FPE() { delete ui; } //******************************************************** //show mouse coordinates //******************************************************** void FPE::showPointToolTip(QMouseEvent *event) { double xc = ui->customPlot->xAxis->pixelToCoord(event->pos().x()); double yc = ui->customPlot->yAxis->pixelToCoord(event->pos().y()); setToolTip(QString("%1 , %2").arg(xc).arg(yc)); } //********************************* // Plot Transmission //********************************* void FPE::on_pushButton_2_clicked() { ui->customPlot->clearGraphs(); double d = ui->doubleSpinBox->value()*1000000; double n = ui->doubleSpinBox_2->value(); double R = ui->doubleSpinBox_3->value(); double Fr = 4*R/(pow((1-R),2)); double theta = ui->doubleSpinBox_6->value(); double lw = ui->doubleSpinBox_4->value(); double uw = ui->doubleSpinBox_5->value(); double mw = (uw+lw)/2; double OPD = d*2*pow((pow(n,2)-pow(sin(theta),2)),0.5); int points = ui->spinBox->value(); //int fl = ui->spinBox_2->value(); //int pl = ui->spinBox_3->value(); //double Ffl = fl/(2*1.414*n*cos(theta)); //double Fpl = pl/(2*n*cos(theta)); //double F = pow(1/(1/pow(Fr,2)+1/pow(Ffl,2)+1/pow(Fpl,2)),0.5); double dl = pow(mw,2)/OPD/points; int steps = (uw-lw)/dl; QVector<double> wl(steps), It(steps); for(int i =0; i<steps; i++){ wl[i] = lw+i*dl; It[i] = 1/(1+Fr*pow(sin(OPD*M_PI/wl[i]),2)); } ui->customPlot->addGraph(); ui->customPlot->graph()->addData(wl, It); ui->customPlot->rescaleAxes(); ui->customPlot->replot(); }
apache-2.0
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/aaa/aaagroup_authorizationpolicy_binding.java
11096
/* * Copyright (c) 2008-2015 Citrix Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.citrix.netscaler.nitro.resource.config.aaa; import com.citrix.netscaler.nitro.resource.base.*; import com.citrix.netscaler.nitro.service.nitro_service; import com.citrix.netscaler.nitro.service.options; import com.citrix.netscaler.nitro.util.*; import com.citrix.netscaler.nitro.exception.nitro_exception; class aaagroup_authorizationpolicy_binding_response extends base_response { public aaagroup_authorizationpolicy_binding[] aaagroup_authorizationpolicy_binding; } /** * Binding class showing the authorizationpolicy that can be bound to aaagroup. */ public class aaagroup_authorizationpolicy_binding extends base_resource { private String policy; private Long priority; private Long acttype; private String intranetapplication; private String urlname; private String groupname; private Long __count; /** * <pre> * Priority to assign to the policy, as an integer. A lower number indicates a higher priority. Required when binding a group to a policy. Not relevant to any other type of group binding. * </pre> */ public void set_priority(long priority) throws Exception { this.priority = new Long(priority); } /** * <pre> * Priority to assign to the policy, as an integer. A lower number indicates a higher priority. Required when binding a group to a policy. Not relevant to any other type of group binding. * </pre> */ public void set_priority(Long priority) throws Exception{ this.priority = priority; } /** * <pre> * Priority to assign to the policy, as an integer. A lower number indicates a higher priority. Required when binding a group to a policy. Not relevant to any other type of group binding. * </pre> */ public Long get_priority() throws Exception { return this.priority; } /** * <pre> * The intranet url. * </pre> */ public void set_urlname(String urlname) throws Exception{ this.urlname = urlname; } /** * <pre> * The intranet url. * </pre> */ public String get_urlname() throws Exception { return this.urlname; } /** * <pre> * The policy name. * </pre> */ public void set_policy(String policy) throws Exception{ this.policy = policy; } /** * <pre> * The policy name. * </pre> */ public String get_policy() throws Exception { return this.policy; } /** * <pre> * Name of the group that you are binding.<br> Minimum length = 1 * </pre> */ public void set_groupname(String groupname) throws Exception{ this.groupname = groupname; } /** * <pre> * Name of the group that you are binding.<br> Minimum length = 1 * </pre> */ public String get_groupname() throws Exception { return this.groupname; } /** * <pre> * Bind the group to the specified intranet VPN application. * </pre> */ public void set_intranetapplication(String intranetapplication) throws Exception{ this.intranetapplication = intranetapplication; } /** * <pre> * Bind the group to the specified intranet VPN application. * </pre> */ public String get_intranetapplication() throws Exception { return this.intranetapplication; } /** * <pre> * . * </pre> */ public Long get_acttype() throws Exception { return this.acttype; } /** * <pre> * converts nitro response into object and returns the object array in case of get request. * </pre> */ protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception{ aaagroup_authorizationpolicy_binding_response result = (aaagroup_authorizationpolicy_binding_response) service.get_payload_formatter().string_to_resource(aaagroup_authorizationpolicy_binding_response.class, response); if(result.errorcode != 0) { if (result.errorcode == 444) { service.clear_session(); } if(result.severity != null) { if (result.severity.equals("ERROR")) throw new nitro_exception(result.message,result.errorcode); } else { throw new nitro_exception(result.message,result.errorcode); } } return result.aaagroup_authorizationpolicy_binding; } /** * <pre> * Returns the value of object identifier argument * </pre> */ protected String get_object_name() { return this.groupname; } public static base_response add(nitro_service client, aaagroup_authorizationpolicy_binding resource) throws Exception { aaagroup_authorizationpolicy_binding updateresource = new aaagroup_authorizationpolicy_binding(); updateresource.groupname = resource.groupname; updateresource.policy = resource.policy; updateresource.priority = resource.priority; updateresource.intranetapplication = resource.intranetapplication; updateresource.urlname = resource.urlname; return updateresource.update_resource(client); } public static base_responses add(nitro_service client, aaagroup_authorizationpolicy_binding resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { aaagroup_authorizationpolicy_binding updateresources[] = new aaagroup_authorizationpolicy_binding[resources.length]; for (int i=0;i<resources.length;i++){ updateresources[i] = new aaagroup_authorizationpolicy_binding(); updateresources[i].groupname = resources[i].groupname; updateresources[i].policy = resources[i].policy; updateresources[i].priority = resources[i].priority; updateresources[i].intranetapplication = resources[i].intranetapplication; updateresources[i].urlname = resources[i].urlname; } result = update_bulk_request(client, updateresources); } return result; } public static base_response delete(nitro_service client, aaagroup_authorizationpolicy_binding resource) throws Exception { aaagroup_authorizationpolicy_binding deleteresource = new aaagroup_authorizationpolicy_binding(); deleteresource.groupname = resource.groupname; deleteresource.policy = resource.policy; deleteresource.intranetapplication = resource.intranetapplication; deleteresource.urlname = resource.urlname; return deleteresource.delete_resource(client); } public static base_responses delete(nitro_service client, aaagroup_authorizationpolicy_binding resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { aaagroup_authorizationpolicy_binding deleteresources[] = new aaagroup_authorizationpolicy_binding[resources.length]; for (int i=0;i<resources.length;i++){ deleteresources[i] = new aaagroup_authorizationpolicy_binding(); deleteresources[i].groupname = resources[i].groupname; deleteresources[i].policy = resources[i].policy; deleteresources[i].intranetapplication = resources[i].intranetapplication; deleteresources[i].urlname = resources[i].urlname; } result = delete_bulk_request(client, deleteresources); } return result; } /** * Use this API to fetch aaagroup_authorizationpolicy_binding resources of given name . */ public static aaagroup_authorizationpolicy_binding[] get(nitro_service service, String groupname) throws Exception{ aaagroup_authorizationpolicy_binding obj = new aaagroup_authorizationpolicy_binding(); obj.set_groupname(groupname); aaagroup_authorizationpolicy_binding response[] = (aaagroup_authorizationpolicy_binding[]) obj.get_resources(service); return response; } /** * Use this API to fetch filtered set of aaagroup_authorizationpolicy_binding resources. * filter string should be in JSON format.eg: "port:80,servicetype:HTTP". */ public static aaagroup_authorizationpolicy_binding[] get_filtered(nitro_service service, String groupname, String filter) throws Exception{ aaagroup_authorizationpolicy_binding obj = new aaagroup_authorizationpolicy_binding(); obj.set_groupname(groupname); options option = new options(); option.set_filter(filter); aaagroup_authorizationpolicy_binding[] response = (aaagroup_authorizationpolicy_binding[]) obj.getfiltered(service, option); return response; } /** * Use this API to fetch filtered set of aaagroup_authorizationpolicy_binding resources. * set the filter parameter values in filtervalue object. */ public static aaagroup_authorizationpolicy_binding[] get_filtered(nitro_service service, String groupname, filtervalue[] filter) throws Exception{ aaagroup_authorizationpolicy_binding obj = new aaagroup_authorizationpolicy_binding(); obj.set_groupname(groupname); options option = new options(); option.set_filter(filter); aaagroup_authorizationpolicy_binding[] response = (aaagroup_authorizationpolicy_binding[]) obj.getfiltered(service, option); return response; } /** * Use this API to count aaagroup_authorizationpolicy_binding resources configued on NetScaler. */ public static long count(nitro_service service, String groupname) throws Exception{ aaagroup_authorizationpolicy_binding obj = new aaagroup_authorizationpolicy_binding(); obj.set_groupname(groupname); options option = new options(); option.set_count(true); aaagroup_authorizationpolicy_binding response[] = (aaagroup_authorizationpolicy_binding[]) obj.get_resources(service,option); if (response != null) { return response[0].__count; } return 0; } /** * Use this API to count the filtered set of aaagroup_authorizationpolicy_binding resources. * filter string should be in JSON format.eg: "port:80,servicetype:HTTP". */ public static long count_filtered(nitro_service service, String groupname, String filter) throws Exception{ aaagroup_authorizationpolicy_binding obj = new aaagroup_authorizationpolicy_binding(); obj.set_groupname(groupname); options option = new options(); option.set_count(true); option.set_filter(filter); aaagroup_authorizationpolicy_binding[] response = (aaagroup_authorizationpolicy_binding[]) obj.getfiltered(service, option); if (response != null) { return response[0].__count; } return 0; } /** * Use this API to count the filtered set of aaagroup_authorizationpolicy_binding resources. * set the filter parameter values in filtervalue object. */ public static long count_filtered(nitro_service service, String groupname, filtervalue[] filter) throws Exception{ aaagroup_authorizationpolicy_binding obj = new aaagroup_authorizationpolicy_binding(); obj.set_groupname(groupname); options option = new options(); option.set_count(true); option.set_filter(filter); aaagroup_authorizationpolicy_binding[] response = (aaagroup_authorizationpolicy_binding[]) obj.getfiltered(service, option); if (response != null) { return response[0].__count; } return 0; } }
apache-2.0
alexruiz/fest-assert-1.x
src/main/java/org/fest/assertions/RGBColor.java
1684
/* * Created on Mar 25, 2009 * * 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 @2009-2013 the original author or authors. */ package org.fest.assertions; import org.jetbrains.annotations.NotNull; import static java.lang.Math.abs; /** * A color. * * @author Alex Ruiz */ final class RGBColor { private final int r; private final int g; private final int b; RGBColor(int rgb) { this(r(rgb), g(rgb), b(rgb)); } RGBColor(int r, int g, int b) { this.r = r; this.g = g; this.b = b; } private static int r(int rgb) { return (rgb >> 16) & 0xFF; } private static int g(int rgb) { return (rgb >> 8) & 0xFF; } private static int b(int rgb) { return (rgb >> 0) & 0xFF; } int r() { return r; } int g() { return g; } int b() { return b; } boolean isEqualTo(@NotNull RGBColor color, int threshold) { if (abs(r - color.r) > threshold) { return false; } if (abs(g - color.g) > threshold) { return false; } return abs(b - color.b) <= threshold; } @Override public String toString() { return String.format("color[r=%d,g=%d,b=%d]", r, g, b); } }
apache-2.0
jorgevillaverde/dacs
java/loan-app/savings-account-service/src/main/java/ar/edu/utn/frre/dacs/loan/savings/model/Transaction.java
2271
/* * Copyright (C) 2015-2018 UTN-FRRe * * 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 ar.edu.utn.frre.dacs.loan.savings.model; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import com.fasterxml.jackson.annotation.JsonIgnore; @Entity public class Transaction implements Serializable { /** * */ private static final long serialVersionUID = 1L; // Properties ------------------------------------------------------------- @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @JsonIgnore @ManyToOne(fetch = FetchType.LAZY) private SavingsAccount savingsAccount; private Date date; private TransactionType type; private BigDecimal ammount; // Getters/Setters -------------------------------------------------------- public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public TransactionType getType() { return type; } public void setType(TransactionType type) { this.type = type; } public BigDecimal getAmmount() { return ammount; } public void setAmmount(BigDecimal ammount) { this.ammount = ammount; } public SavingsAccount getSavingsAccount() { return savingsAccount; } public void setSavingsAccount(SavingsAccount savingsAccount) { this.savingsAccount = savingsAccount; } }
apache-2.0
moosbusch/xbLIDO
src/net/opengis/gml/impl/AxisDirectionDocumentImpl.java
2431
/* * Copyright 2013 Gunnar Kappei. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.opengis.gml.impl; /** * A document containing one axisDirection(@http://www.opengis.net/gml) element. * * This is a complex type. */ public class AxisDirectionDocumentImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements net.opengis.gml.AxisDirectionDocument { private static final long serialVersionUID = 1L; public AxisDirectionDocumentImpl(org.apache.xmlbeans.SchemaType sType) { super(sType); } private static final javax.xml.namespace.QName AXISDIRECTION$0 = new javax.xml.namespace.QName("http://www.opengis.net/gml", "axisDirection"); /** * Gets the "axisDirection" element */ public net.opengis.gml.CodeType getAxisDirection() { synchronized (monitor()) { check_orphaned(); net.opengis.gml.CodeType target = null; target = (net.opengis.gml.CodeType)get_store().find_element_user(AXISDIRECTION$0, 0); if (target == null) { return null; } return target; } } /** * Sets the "axisDirection" element */ public void setAxisDirection(net.opengis.gml.CodeType axisDirection) { generatedSetterHelperImpl(axisDirection, AXISDIRECTION$0, 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON); } /** * Appends and returns a new empty "axisDirection" element */ public net.opengis.gml.CodeType addNewAxisDirection() { synchronized (monitor()) { check_orphaned(); net.opengis.gml.CodeType target = null; target = (net.opengis.gml.CodeType)get_store().add_element_user(AXISDIRECTION$0); return target; } } }
apache-2.0
dbeaver/dbeaver
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/access/DBAAuthProfile.java
2271
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2022 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.model.access; import org.jkiss.dbeaver.model.connection.DBPAuthModelDescriptor; import org.jkiss.dbeaver.model.connection.DBPConfigurationProfile; import org.jkiss.dbeaver.runtime.DBWorkbench; /** * Auth profile. * Authentication properties. */ public class DBAAuthProfile extends DBPConfigurationProfile { private String authModelId; private String userName; private String userPassword; private boolean savePassword; public DBAAuthProfile() { } public DBAAuthProfile(DBAAuthProfile source) { super(source); this.authModelId = source.authModelId; this.userName = source.userName; this.userPassword = source.userPassword; this.savePassword = source.savePassword; } public String getAuthModelId() { return authModelId; } public void setAuthModelId(String authModelId) { this.authModelId = authModelId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public boolean isSavePassword() { return savePassword; } public void setSavePassword(boolean savePassword) { this.savePassword = savePassword; } public DBPAuthModelDescriptor getAuthModel() { return DBWorkbench.getPlatform().getDataSourceProviderRegistry().getAuthModel(authModelId); } }
apache-2.0
consulo/consulo-python
python-psi-api/src/main/java/com/jetbrains/python/psi/types/PyClassMembersProvider.java
1369
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.psi.types; import java.util.Collection; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.psi.PsiElement; import com.jetbrains.python.codeInsight.PyCustomMember; /** * @author Dennis.Ushakov */ public interface PyClassMembersProvider { ExtensionPointName<PyClassMembersProvider> EP_NAME = ExtensionPointName.create("consulo.python.pyClassMembersProvider"); @Nonnull Collection<PyCustomMember> getMembers(final PyClassType clazz, PsiElement location, @Nullable TypeEvalContext typeEvalContext); @Nullable PsiElement resolveMember(PyClassType clazz, String name, @Nullable PsiElement location, @Nullable TypeEvalContext context); }
apache-2.0
kashiwasan/symfony-advanced
lib/filter/saEmojiFilter.class.php
1217
<?php /** * This file is part of the SfAdvanced package. * (c) SfAdvanced Project (http://www.sfadvanced.jp/) * * For the full copyright and license information, please view the LICENSE * file and the NOTICE file that were distributed with this source code. */ /** * saEmojiFilter converts Emoji symbols in the response text * * Emoji is the picture characters or emoticons used in Japan. * * @package SfAdvanced * @subpackage filter * @author Kousuke Ebihara <ebihara@tejimaya.com> */ class saEmojiFilter extends sfFilter { /** * Executes this filter. * * @param sfFilterChain $filterChain A sfFilterChain instance */ public function execute($filterChain) { $filterChain->execute(); $response = $this->getContext()->getResponse(); $request = $this->getContext()->getRequest(); $content = $response->getContent(); if (!$request->isMobile()) { list($list, $content) = saToolkit::replacePatternsToMarker($content); } $content = SfAdvanced_KtaiEmoji::convertEmoji($content); if (!$request->isMobile()) { $content = str_replace(array_keys($list), array_values($list), $content); } $response->setContent($content); } }
apache-2.0
forcedotcom/aura
aura-impl/src/main/java/org/auraframework/impl/java/type/converter/LocalizedDateToStringConverter.java
1805
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.auraframework.impl.java.type.converter; import java.util.Date; import org.auraframework.annotations.Annotations.ServiceComponent; import org.auraframework.impl.java.type.LocalizedConverter; import org.auraframework.util.AuraLocale; import org.auraframework.util.date.DateService; import org.auraframework.util.date.DateServiceImpl; @ServiceComponent public class LocalizedDateToStringConverter implements LocalizedConverter<Date, String> { @Override public String convert(Date value, AuraLocale locale) { DateService dateService = DateServiceImpl.get(); return dateService.getDateTimeISO8601Converter().format(value, locale.getTimeZone()); } @Override public String convert(Date value) { if (value == null) { return null; } DateService dateService = DateServiceImpl.get(); return dateService.getDateTimeISO8601Converter().format(value); } @Override public Class<Date> getFrom() { return Date.class; } @Override public Class<String> getTo() { return String.class; } @Override public Class<?>[] getToParameters() { return null; } }
apache-2.0
Medium/closure-templates
java/src/com/google/template/soy/logging/SoyLogger.java
1528
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.template.soy.logging; import com.google.template.soy.data.LogStatement; import com.google.template.soy.data.LoggingFunctionInvocation; /** * Experimental logging interface for soy. * * <p>This implements a callback protocol with the {@code velog} syntax. */ public interface SoyLogger { /** Called when a {@code velog} statement is entered. */ void enter(LogStatement statement); /** Called when a {@code velog} statement is exited. */ void exit(); // called to format a logging function value. String evalLoggingFunction(LoggingFunctionInvocation value); static final SoyLogger NO_OP = new SoyLogger() { @Override public void enter(LogStatement statement) {} @Override public void exit() {} @Override public String evalLoggingFunction(LoggingFunctionInvocation value) { return value.placeholderValue(); } }; }
apache-2.0
lunisolar/magma
magma-asserts/src/main/java/eu/lunisolar/magma/asserts/func/consumer/primitives/obj/LBiObjIntConsumerAssert.java
3805
/* * This file is part of "lunisolar-magma". * * (C) Copyright 2014-2019 Lunisolar (http://lunisolar.eu/). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.lunisolar.magma.asserts.func.consumer.primitives.obj; import eu.lunisolar.magma.basics.asserts.*; // NOSONAR import javax.annotation.Nonnull; // NOSONAR import javax.annotation.Nullable; // NOSONAR import org.assertj.core.api.*; // NOSONAR import eu.lunisolar.magma.basics.meta.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR import eu.lunisolar.magma.func.action.*; // NOSONAR import java.util.function.*; import eu.lunisolar.magma.func.consumer.primitives.obj.*; import eu.lunisolar.magma.func.action.*; // NOSONAR import eu.lunisolar.magma.func.consumer.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR import eu.lunisolar.magma.func.function.*; // NOSONAR import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR import eu.lunisolar.magma.func.function.from.*; // NOSONAR import eu.lunisolar.magma.func.function.to.*; // NOSONAR import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR import eu.lunisolar.magma.func.predicate.*; // NOSONAR import eu.lunisolar.magma.func.supplier.*; // NOSONAR import static org.assertj.core.api.Fail.fail; /** Assert class for LBiObjIntConsumer. */ public interface LBiObjIntConsumerAssert<S extends LBiObjIntConsumerAssert<S, A, T1, T2>, A extends LBiObjIntConsumer<T1, T2>, T1, T2> extends Assert<S, A>, FunctionalAssert.Simple<S, LBiObjIntConsumer<T1, T2>, A> { @Nonnull public static <A extends LBiObjIntConsumer<T1, T2>, T1, T2> LBiObjIntConsumerAssert.The<A, T1, T2> attestBiObjIntCons(LBiObjIntConsumer<T1, T2> func) { return new LBiObjIntConsumerAssert.The(func); } @Nonnull SemiEvaluation<S, LBiObjIntConsumer<T1, T2>, A> doesAccept(T1 a1, T2 a2, int a3); /** Convenience implementation - if you want instantiate not to extend (uses one less generic parameter). */ final class The<A extends LBiObjIntConsumer<T1, T2>, T1, T2> extends Base<The<A, T1, T2>, A, T1, T2> { public The(A actual) { super(actual, The.class); } } /** Base implementation. For potential extending (requires to define all generic parameters). */ class Base<S extends Base<S, A, T1, T2>, A extends LBiObjIntConsumer<T1, T2>, T1, T2> extends FunctionalAssert.Simple.Base<S, LBiObjIntConsumer<T1, T2>, A> implements LBiObjIntConsumerAssert<S, A, T1, T2> { public Base(A actual, Class<?> selfType) { super(actual, selfType); } @Nonnull public SemiEvaluation<S, LBiObjIntConsumer<T1, T2>, A> doesAccept(T1 a1, T2 a2, int a3) { return evaluation(() -> String.format("(%s,%s,%s)", a1, a2, a3), pc -> { if (pc != null) { pc.accept(a1, a2, a3); } actual.accept(a1, a2, a3); return null; }); } } }
apache-2.0
stuhood/cassandra-old
src/java/org/apache/cassandra/utils/CloseableIterator.java
1081
package org.apache.cassandra.utils; /* * * 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. * */ import java.io.IOError; import java.util.Iterator; // so we can instantiate anonymous classes implementing both interfaces public interface CloseableIterator<T> extends Iterator<T> { public void close() throws IOError; }
apache-2.0
lin2020/csapp
app/src/main/java/club/baidu/hust/edu/cn/csapp/view/RayMenu.java
11859
package club.baidu.hust.edu.cn.csapp.view; import android.content.Context; import android.content.Intent; import android.content.res.TypedArray; import android.support.v4.view.ScrollingView; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.RotateAnimation; import android.view.animation.ScaleAnimation; import android.view.animation.TranslateAnimation; import club.baidu.hust.edu.cn.csapp.R; import club.baidu.hust.edu.cn.csapp.activity.NewsCommentActivity; /** * Created by jiadong on 2015/7/11. */ public class RayMenu extends ViewGroup implements View.OnClickListener{ private static final int POS_LEFT_TOP = 0; private static final int POS_LEFT_BOTTOM = 1; private static final int POS_RIGHT_TOP = 2; private static final int POS_RIGHT_BOTTOM = 3; private Position mPosition = Position.RIGHT_BOTTOM; private int mRadius; /** * 菜单的状态 */ private Status mCurrentStatus = Status.CLOSE; /** * 菜单的主按钮 */ private View mCButton; private mMenuItemClickListener mMenuItemClickListener; /** * 菜单位置枚举类 */ public enum Status { OPEN, CLOSE } /** * 菜单位置枚举类 */ public enum Position { LEFT_TOP, LEFT_BOTTOM, RIGHT_TOP, RIGHT_BOTTOM } /** * 点击子菜单项的回调接口 */ public interface mMenuItemClickListener { void onClick(View view, int pos); } public void setmMenuItemClickListener(mMenuItemClickListener mMenuItemClickListener) { this.mMenuItemClickListener = mMenuItemClickListener; } public RayMenu(Context context) { this(context, null); } public RayMenu(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RayMenu(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mRadius = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics()); //获取自定义属性 TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.RayMenu, defStyle, 0); int pos = a.getInt(R.styleable.RayMenu_position, 3); switch (pos) { case POS_LEFT_TOP: mPosition = Position.LEFT_TOP; break; case POS_LEFT_BOTTOM: mPosition = Position.LEFT_BOTTOM; break; case POS_RIGHT_TOP: mPosition = Position.RIGHT_TOP; break; case POS_RIGHT_BOTTOM: mPosition = Position.RIGHT_BOTTOM; break; } mRadius = (int) a.getDimension(R.styleable.RayMenu_radius, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics())); a.recycle(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int count = getChildCount(); for (int i = 0; i < count; i++) { //测量child measureChild(getChildAt(i), widthMeasureSpec, heightMeasureSpec); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } /** * 定位主菜单和子菜单布局 * * @param changed * @param l * @param t * @param r * @param b */ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { if (changed) { layoutCButton(); int count = getChildCount(); for (int i = 0; i < count - 1; i++) { View child = getChildAt(i + 1); mCButton = getChildAt(0); child.setVisibility(View.GONE); int cleft = getMeasuredWidth(); int ctop = getMeasuredHeight() - mRadius / (count - 2) * (i + 1); int cWidth = child.getMeasuredWidth(); int cHeight = child.getMeasuredHeight(); int Width = mCButton.getMeasuredWidth(); int Height = mCButton.getMeasuredHeight(); child.layout(cleft - (int) (0.5 * cWidth) - (int) (1.0 * Width), ctop - cHeight - (int) (1.0 * Height), cleft + (int) (0.5 * cWidth) - (int) (1.0 * Width), ctop - (int) (1.0 * Height)); } } } /** * 定位主菜单按钮 */ private void layoutCButton() { mCButton = getChildAt(0); mCButton.setOnClickListener(this); int left = 0; int top = 0; int width = mCButton.getMeasuredWidth(); int height = mCButton.getMeasuredHeight(); switch (mPosition) { case LEFT_TOP: left = 0; top = 0; break; case LEFT_BOTTOM: left = 0; top = getMeasuredHeight() - height; break; case RIGHT_TOP: left = getMeasuredWidth() - width; top = 0; break; case RIGHT_BOTTOM: left = getMeasuredWidth() - width; top = getMeasuredHeight() - height; break; } mCButton.layout(left - (int) (0.5 * width), top - (int) (0.5 * height), left + (int) (0.5 * width), top + (int) (0.5 * height)); } @Override public void onClick(View v) { rotateCButton(v, 0f, 360f, 300); toggleMenu(300); } /** * 主菜单的旋转动画 * * @param v * @param start * @param end * @param duration */ private void rotateCButton(View v, float start, float end, int duration) { RotateAnimation anim = new RotateAnimation(start, end, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); anim.setDuration(duration); anim.setFillAfter(true); v.startAnimation(anim); } /** * 切换菜单 */ private void toggleMenu(int duration) { //为menuItem添加平移动画和旋转动画 int count = getChildCount(); for (int i = 0; i < count - 1; i++) { final View childView = getChildAt(i + 1); childView.setVisibility(View.VISIBLE); //平移动画 //获取childView开始的位置(也就是CButton的位置) //两种平移方式: // 展开:从childView开始的位置到childView本身的位置 // 收回:从childView本身的位置到childView开始的位置 int cHeight = childView.getMeasuredHeight(); int cleft = 0; int ctop = mRadius / (count - 2) * (i + 1) + (int) (0.5 * cHeight); AnimationSet animset = new AnimationSet(true); Animation tranAnim = null; //如果状态是CLOSE就平移展开,如果是OPEN就平移收回 if (mCurrentStatus == Status.CLOSE) { tranAnim = new TranslateAnimation(cleft, 0, ctop, 0); childView.setClickable(true); childView.setFocusable(true); } else { tranAnim = new TranslateAnimation(0, cleft, 0, ctop); childView.setClickable(false); childView.setFocusable(false); } //设置结束状态 tranAnim.setFillAfter(true); //设置平移的时间间隔 tranAnim.setDuration(duration); //设置平移开始的时间间隔 tranAnim.setStartOffset((i * 100) / count); //设置子菜单的可见性,如果平移结束后的状态是CLOSE就将子菜单设置为不可见 tranAnim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { if (mCurrentStatus == Status.CLOSE) { childView.setVisibility(View.GONE); } } @Override public void onAnimationRepeat(Animation animation) { } }); //旋转动画 RotateAnimation rotateAnim = new RotateAnimation(0, 720, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); rotateAnim.setDuration(duration); rotateAnim.setFillAfter(true); animset.addAnimation(rotateAnim); animset.addAnimation(tranAnim); childView.startAnimation(animset); final int pos = i + 1; childView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mMenuItemClickListener.onClick(childView, pos); menuItemAnim(pos - 1); changeStatus(); } }); } //切换菜单状态 changeStatus(); } /** * 切换菜单状态 */ private void changeStatus() { mCurrentStatus = (mCurrentStatus == Status.CLOSE ? Status.OPEN : Status.CLOSE); } /** * 添加menuItem的点击动画 * * @param pos */ private void menuItemAnim(int pos) { for (int i = 0; i < getChildCount() - 1; i++) { View childView = getChildAt(i + 1); if (i == pos) { childView.startAnimation(scaleBigAnim(300)); } else { childView.startAnimation(scaleSmallAnim(300)); } //把childView设置为不可点击 childView.setClickable(false); } } /** * 为当前点击的Item设置变大和透明度降低的动画 * * @param duration * @return */ private Animation scaleBigAnim(int duration) { AnimationSet animationSet = new AnimationSet(true); //从原来大小放大到2.4倍 ScaleAnimation scaleAnim = new ScaleAnimation(1.0f, 2.4f, 1.0f, 2.4f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); //从完全可见变化到完全不可见 AlphaAnimation alphaAnim = new AlphaAnimation(1f, 0f); //把动画添加到动画管理器上 animationSet.addAnimation(scaleAnim); animationSet.addAnimation(alphaAnim); //设置时间间隔和结束状态 animationSet.setDuration(duration); animationSet.setFillAfter(true); //返回动画设置 return animationSet; } /** * 为其他未点击的Item设置变小和透明度降低 * * @param duration * @return */ private Animation scaleSmallAnim(int duration) { AnimationSet animationSet = new AnimationSet(true); //从原来大小缩小到0 ScaleAnimation scaleAnim = new ScaleAnimation(1.0f, 0f, 1.0f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); //从完全可见变化到完全不可见 AlphaAnimation alphaAnim = new AlphaAnimation(1f, 0f); //把动画添加到动画管理器上 animationSet.addAnimation(scaleAnim); animationSet.addAnimation(alphaAnim); //设置时间间隔和结束状态 animationSet.setDuration(duration); animationSet.setFillAfter(true); //返回动画设置 return animationSet; } }
apache-2.0
ankor-io/ankor-framework
ankor-js/src/main/webapp/js/wrap-end.frag.js
271
//The modules for your project will be inlined above //this snippet. Ask almond to synchronously require the //module value for 'main' here and return it as the //value to use for the public API for the built file. return require('ankor/ankor'); }));
apache-2.0
roboconf/roboconf-web-administration
src/app/commands/commands.directive.history.js
2841
(function() { 'use strict'; angular .module('roboconf.commands') .directive('rbcfCommandsHistory', rbcfCommandsHistory); function rbcfCommandsHistory() { return { restrict: 'E', templateUrl: 'templates/commands/html/_commands_history_directive.html', controller: rbcfCommandsHistoryDirectiveController }; } rbcfCommandsHistoryDirectiveController.$inject = ['$scope', '$route', 'rClient', 'rUtils', '$routeParams', '$translate']; function rbcfCommandsHistoryDirectiveController($scope, $route, rClient, rUtils, $routeParams, $translate) { // Fields var itemsPerPage = 25; $scope.showAppColumn = $route.current.showAppName; $scope.responseStatus = -1; $scope.sortingCriteria = 'start'; $scope.sortingOrder = 'desc'; $scope.pageCount = 0; $scope.items = []; $scope.datePattern = ''; $scope.pageNumber = 1; var pageNumber = parseInt($routeParams.pageNumber); if (!! pageNumber && pageNumber > 0) { $scope.pageNumber = pageNumber; } // Function declarations $scope.setCriteria = setCriteria; // Initial actions: find the history for the given application (if any) if ($routeParams.appName) { rClient.findApplication($routeParams.appName).then(function(app) { $scope.app = app; if (app.fake) { $scope.responseStatus = 404; } else { loadCommandsHistory($scope.sortingCriteria, $scope.sortingOrder); } }); } // Otherwise, get the history directly else { loadCommandsHistory($scope.sortingCriteria, $scope.sortingOrder); } // Get the page count too rClient.getCommandsHistoryPageCount(itemsPerPage, $routeParams.appName).then(function(count) { $scope.pageCount = count; }); // And find the date pattern $translate('COMMON_DATE_PATTERN').then(function(translatedValue) { $scope.datePattern = translatedValue; }); // Functions function setCriteria(sortingCriteria) { if (sortingCriteria !== $scope.sortingCriteria) { loadCommandsHistory(sortingCriteria, $scope.sortingOrder); } else { var sortingOrder = $scope.sortingOrder === 'asc' ? 'desc' : 'asc'; loadCommandsHistory($scope.sortingCriteria, sortingOrder); } } function loadCommandsHistory(sortingCriteria, sortingOrder) { rClient.loadCommandsHistory( $scope.pageNumber, itemsPerPage, sortingCriteria, sortingOrder, $routeParams.appName).then(function(items) { $scope.responseStatus = 0; $scope.sortingCriteria = sortingCriteria; $scope.sortingOrder = sortingOrder; $scope.items = items; }, function(response) { $scope.responseStatus = response.status; }); } } })();
apache-2.0
Inlustra/UoG-Web-Services
app/database/migrations/2014_11_15_151509_create_posts.php
1427
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePosts extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users'); $table->string('location',8); $table->string('title', 45); $table->decimal('lat',18,12); $table->decimal('lon',18,12); $table->string('content'); $table->boolean('pinned')->default(false); $table->boolean('removed')->default(false); $table->boolean('locked')->default(false); $table->timestamps(); }); Schema::create('post_sitter_types', function (Blueprint $table) { $table->integer('post_id')->unsigned(); $table->foreign('post_id')->references('id')->on('posts'); $table->integer('sitter_type_id')->unsigned(); $table->foreign('sitter_type_id')->references('id')->on('sitter_types'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('post_sitter_types'); Schema::drop('posts'); } }
apache-2.0
aaronmontague/ud851-Exercises
Lesson02-GitHub-Repo-Search/T02.02-Exercise-AddMenu/app/src/main/java/com/example/android/datafrominternet/MainActivity.java
3340
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.datafrominternet; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private EditText mSearchBoxEditText; private TextView mUrlDisplayTextView; private TextView mSearchResultsTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSearchBoxEditText = (EditText) findViewById(R.id.et_search_box); mUrlDisplayTextView = (TextView) findViewById(R.id.tv_url_display); mSearchResultsTextView = (TextView) findViewById(R.id.tv_github_search_results_json); } // Do 2 - 7 in menu.xml /////////////////////////////////////////////////////////////////////// // TODO (2) Create a menu xml called 'main.xml' in the res->menu folder // TODO (3) Add one menu item to your menu // TODO (4) Give the menu item an id of @+id/action_search // TODO (5) Set the orderInCategory to 1 // TODO (6) Show this item if there is room (use app:showAsAction, not android:showAsAction) // TODO (7) Set the title to the search string ("Search") from strings.xml // Do 2 - 7 in menu.xml /////////////////////////////////////////////////////////////////////// // TODO (8) Override onCreateOptionsMenu // TODO (9) Within onCreateOptionsMenu, use getMenuInflater().inflate to inflate the menu // TODO (10) Return true to display your menu @Override public boolean onCreateOptionsMenu(Menu menu){ getMenuInflater().inflate(R.menu.main, menu); return true; } // TODO (11) Override onOptionsItemSelected // TODO (12) Within onOptionsItemSelected, get the ID of the item that was selected // TODO (13) If the item's ID is R.id.action_search, show a Toast and return true to tell Android that you've handled this menu click // TODO (14) Don't forgot to call .show() on your Toast // TODO (15) If you do NOT handle the menu click, return super.onOptionsItemSelected to let Android handle the menu click @Override public boolean onOptionsItemSelected(MenuItem item) { int menuItemSelected = item.getItemId(); if (menuItemSelected == R.id.action_search){ Context context = MainActivity.this; String message = "Search Clicked"; Toast.makeText(context,message,Toast.LENGTH_LONG).show(); } return super.onOptionsItemSelected(item); } }
apache-2.0
thabart/SimpleIdentityServer
SimpleIdentityServer/src/Apis/Uma/SimpleIdentityServer.Uma.Core/Constants.cs
2435
#region copyright // Copyright 2015 Habart Thierry // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace SimpleIdentityServer.Uma.Core { internal static class Constants { public static string IdTokenType = "http://openid.net/specs/openid-connect-core-1_0.html#IDToken"; public static class RptClaims { public const string Ticket = "ticket"; public const string Scopes = "scopes"; public const string ResourceSetId = "resource_id"; } public static class AddPermissionNames { public const string ResourceSetId = "resource_set_id"; public const string Scopes = "scopes"; } public static class AddPolicyParameterNames { public const string ResourceSetIds = "resource_set_ids"; public const string Rules = "rules"; } public static class AddResourceSetParameterNames { public const string PolicyId = "_id"; public const string ResourceSet = "resources"; } public static class AddPolicyRuleParameterNames { public const string Script = "script"; public const string Scopes = "scopes"; public const string ClientIdsAllowed = "allowed_clients"; } public static class ErrorDetailNames { public const string RequestingPartyClaims = "requesting_party_claims"; public const string RequiredClaims = "required_claims"; public const string ClaimName = "name"; public const string ClaimFriendlyName = "friendly_name"; public const string ClaimIssuer = "issuer"; public const string RedirectUser = "redirect_user"; } public static class LanguageCodes { public const string Csharp = "csharp"; } } }
apache-2.0
keepsl/keepsmis
ksxtmanager/src/main/java/com/keeps/ksxtmanager/utils/aliyunoss/OSSClientConstants.java
806
package com.keeps.ksxtmanager.utils.aliyunoss; /** * <p>Title: OSSClientConstants.java</p> * <p>Description: @TODO </p> * <p>Copyright: Copyright (c) KEEPS</p> * @author keeps * @version v 1.00 * @date 创建日期:2017年4月27日 * 修改日期: * 修改人: * 复审人: */ public class OSSClientConstants { //阿里云API的外网域名 public static final String ENDPOINT = "oss-cn-shanghai.aliyuncs.com"; //阿里云API的密钥Access Key ID public static final String ACCESS_KEY_ID = "LTAICMgEyrQKscag"; //阿里云API的密钥Access Key Secret public static final String ACCESS_KEY_SECRET = "ROGST3eBKNdouluyoGmnHWtGB13GiK"; //阿里云API的bucket名称 public static final String BACKET_NAME = "keepsl"; }
apache-2.0
InceptionFactory/hamlet
app/src/main/java/com/genesis/hamlet/util/BaseFragmentInteractionListener.java
1204
package com.genesis.hamlet.util; import android.os.Bundle; import android.support.v4.app.Fragment; import com.genesis.hamlet.data.DataRepository; /** * Base {@link Fragment} listener interface to be implemented by the hosting * {@link android.support.v4.app.ActivityCompat}. It should be extended by a * Fragment custom listener interface if any. */ public interface BaseFragmentInteractionListener { /** * Expands {@link android.support.v7.widget.Toolbar} to normal position if collapsed. */ void resetToolBarScroll(); /** * Used by a {@link Fragment} to show another Fragment. * * @param fragmentClass a {@link Fragment} class * @param variant is used to create uniquely tagged instances. Could be null * @param bundle a {@link Bundle} to pass arguments, Could be null * @param addToBackStack a boolean to add transaction to fragment back stack * @param <T> a generic type to indicate type/subclass of {@link Fragment} */ <T extends Fragment> void showFragment(Class<T> fragmentClass, String variant, Bundle bundle, boolean addToBackStack); DataRepository getDataRepository(); void setTitle(String s); }
apache-2.0
moto-timo/robotframework
utest/utils/test_text.py
11531
import unittest import os from os.path import abspath from robot.utils.asserts import * from robot.utils.text import (cut_long_message, get_console_length, pad_console_length, split_tags_from_doc, split_args_from_name_or_path, _count_line_lengths, _MAX_ERROR_LINES, _MAX_ERROR_LINE_LENGTH, _ERROR_CUT_EXPLN) _HALF_ERROR_LINES = _MAX_ERROR_LINES // 2 class NoCutting(unittest.TestCase): def test_empty_string(self): self._assert_no_cutting('') def test_short_message(self): self._assert_no_cutting('bar') def test_few_short_lines(self): self._assert_no_cutting('foo\nbar\zap\hello World!') def test_max_number_of_short_lines(self): self._assert_no_cutting('short line\n' * _MAX_ERROR_LINES) def _assert_no_cutting(self, msg): assert_equal(cut_long_message(msg), msg) class TestCutting(unittest.TestCase): def setUp(self): self.lines = ['my error message %d' % i for i in range(_MAX_ERROR_LINES+1)] self.result = cut_long_message('\n'.join(self.lines)).splitlines() self.limit = _HALF_ERROR_LINES def test_more_than_max_number_of_lines(self): assert_equal(len(self.result), _MAX_ERROR_LINES+1) def test_cut_message_is_present(self): assert_true(_ERROR_CUT_EXPLN in self.result) def test_cut_message_starts_with_original_lines(self): expected = self.lines[:self.limit] actual = self.result[:self.limit] assert_equal(actual, expected) def test_cut_message_ends_with_original_lines(self): expected = self.lines[-self.limit:] actual = self.result[-self.limit:] assert_equal(actual, expected) class TestCuttingWithLinesLongerThanMax(unittest.TestCase): def setUp(self): self.lines = ['line %d' % i for i in range(_MAX_ERROR_LINES-1)] self.lines.append('x' * (_MAX_ERROR_LINE_LENGTH+1)) self.result = cut_long_message('\n'.join(self.lines)).splitlines() def test_cut_message_present(self): assert_true(_ERROR_CUT_EXPLN in self.result) def test_correct_number_of_lines(self): assert_equal(sum(_count_line_lengths(self.result)), _MAX_ERROR_LINES+1) def test_correct_lines(self): expected = self.lines[:_HALF_ERROR_LINES] + [_ERROR_CUT_EXPLN] \ + self.lines[-_HALF_ERROR_LINES+1:] assert_equal(self.result, expected) def test_every_line_longer_than_limit(self): # sanity check lines = [('line %d' % i) * _MAX_ERROR_LINE_LENGTH for i in range(_MAX_ERROR_LINES+2)] result = cut_long_message('\n'.join(lines)).splitlines() assert_true(_ERROR_CUT_EXPLN in result) assert_equal(result[0], lines[0]) assert_equal(result[-1], lines[-1]) assert_true(sum(_count_line_lengths(result)) <= _MAX_ERROR_LINES+1) class TestCutHappensInsideLine(unittest.TestCase): def test_long_line_cut_before_cut_message(self): lines = ['line %d' % i for i in range(_MAX_ERROR_LINES)] index = _HALF_ERROR_LINES - 1 lines[index] = 'abcdefgh' * _MAX_ERROR_LINE_LENGTH result = cut_long_message('\n'.join(lines)).splitlines() self._assert_basics(result, lines) expected = lines[index][:_MAX_ERROR_LINE_LENGTH-3] + '...' assert_equal(result[index], expected) def test_long_line_cut_after_cut_message(self): lines = ['line %d' % i for i in range(_MAX_ERROR_LINES)] index = _HALF_ERROR_LINES lines[index] = 'abcdefgh' * _MAX_ERROR_LINE_LENGTH result = cut_long_message('\n'.join(lines)).splitlines() self._assert_basics(result, lines) expected = '...' + lines[index][-_MAX_ERROR_LINE_LENGTH+3:] assert_equal(result[index+1], expected) def test_one_huge_line(self): result = cut_long_message('0123456789' * _MAX_ERROR_LINES * _MAX_ERROR_LINE_LENGTH) self._assert_basics(result.splitlines()) assert_true(result.startswith('0123456789')) assert_true(result.endswith('0123456789')) assert_true('...\n'+_ERROR_CUT_EXPLN+'\n...' in result) def _assert_basics(self, result, input=None): assert_equal(sum(_count_line_lengths(result)), _MAX_ERROR_LINES+1) assert_true(_ERROR_CUT_EXPLN in result) if input: assert_equal(result[0], input[0]) assert_equal(result[-1], input[-1]) class TestCountLines(unittest.TestCase): def test_no_lines(self): assert_equal(_count_line_lengths([]), []) def test_empty_line(self): assert_equal(_count_line_lengths(['']), [1]) def test_shorter_than_max_lines(self): lines = ['', '1', 'foo', 'barz and fooz', '', 'a bit longer line', '', 'This is a somewhat longer (but not long enough) error message'] assert_equal(_count_line_lengths(lines), [1] * len(lines)) def test_longer_than_max_lines(self): lines = [ '1' * i * (_MAX_ERROR_LINE_LENGTH+3) for i in range(4) ] assert_equal(_count_line_lengths(lines), [1,2,3,4]) def test_boundary(self): b = _MAX_ERROR_LINE_LENGTH lengths = [b-1, b, b+1, 2*b-1, 2*b, 2*b+1, 7*b-1, 7*b, 7*b+1] lines = [ 'e'*length for length in lengths ] assert_equal(_count_line_lengths(lines), [1, 1, 2, 2, 2, 3, 7, 7, 8]) class TestConsoleWidth(unittest.TestCase): len16_asian = u'\u6c49\u5b57\u5e94\u8be5\u6b63\u786e\u5bf9\u9f50' ten_normal = u'1234567890' mixed_26 = u'012345\u6c49\u5b57\u5e94\u8be5\u6b63\u786e\u5bf9\u9f567890' nfd = u'A\u030Abo' def test_console_width(self): assert_equal(get_console_length(self.ten_normal), 10) def test_east_asian_width(self): assert_equal(get_console_length(self.len16_asian), 16) def test_combining_width(self): assert_equal(get_console_length(self.nfd), 3) def test_cut_right(self): assert_equal(pad_console_length(self.ten_normal, 5), '12...') assert_equal(pad_console_length(self.ten_normal, 15), self.ten_normal+' '*5) assert_equal(pad_console_length(self.ten_normal, 10), self.ten_normal) def test_cut_east_asian(self): assert_equal(pad_console_length(self.len16_asian, 10), u'\u6c49\u5b57\u5e94... ') assert_equal(pad_console_length(self.mixed_26, 11), u'012345\u6c49...') class TestDocSplitter(unittest.TestCase): def test_doc_without_tags(self): docs = ["Single doc line.", """Hello, we dont have tags here. No sir. No tags.""", "Now Tags: must, start from beginning of the row", " We strip the trailing whitespace \n \n"] for doc in docs: self._assert_doc_and_tags(doc, doc.rstrip(), []) def _assert_doc_and_tags(self, original, expected_doc, expected_tags): doc, tags = split_tags_from_doc(original) assert_equal(doc, expected_doc) assert_equal(tags, expected_tags) def test_doc_with_tags(self): sets = [ ('Tags: foo, bar', '', ['foo', 'bar']), (' Tags: foo ', '', ['foo']), ('Hello\nTags: foo, bar', 'Hello', ['foo', 'bar']), ('Tags: bar\n Tags: foo ', 'Tags: bar', ['foo']), ('Tags: bar, Tags:, foo ', '', ['bar', 'Tags:', 'foo']), ('tags: foo', '', ['foo']), (' tags: foo , bar ', '', ['foo', 'bar']), ('Hello\n taGS: foo, bar', 'Hello', ['foo', 'bar']), (' Hello\n taGS: f, b \n\n \n', ' Hello', ['f', 'b']), ('Hello\nNl \n \nTags: foo', 'Hello\nNl', ['foo']), ] for original, exp_doc, exp_tags in sets: self._assert_doc_and_tags(original, exp_doc, exp_tags) self._assert_doc_and_tags(original+'\n', exp_doc, exp_tags) class TestSplitArgsFromNameOrPath(unittest.TestCase): def setUp(self): self.method = split_args_from_name_or_path def test_with_no_args(self): assert not os.path.exists('name'), 'does not work if you have name folder!' assert_equals(self.method('name'), ('name', [])) def test_with_args(self): assert not os.path.exists('name'), 'does not work if you have name folder!' assert_equals(self.method('name:arg'), ('name', ['arg'])) assert_equals(self.method('listener:v1:v2:v3'), ('listener', ['v1', 'v2', 'v3'])) assert_equals(self.method('aa:bb:cc'), ('aa', ['bb', 'cc'])) def test_empty_args(self): assert not os.path.exists('foo'), 'does not work if you have foo folder!' assert_equals(self.method('foo:'), ('foo', [''])) assert_equals(self.method('bar:arg1::arg3'), ('bar', ['arg1', '', 'arg3'])) assert_equals(self.method('3:'), ('3', [''])) def test_semicolon_as_separator(self): assert_equals(self.method('name;arg'), ('name', ['arg'])) assert_equals(self.method('name;1;2;3'), ('name', ['1', '2', '3'])) assert_equals(self.method('name;'), ('name', [''])) def test_alternative_separator_in_value(self): assert_equals(self.method('name;v:1;v:2'), ('name', ['v:1', 'v:2'])) assert_equals(self.method('name:v;1:v;2'), ('name', ['v;1', 'v;2'])) def test_windows_path_without_args(self): assert_equals(self.method('C:\\name.py'), ('C:\\name.py', [])) assert_equals(self.method('X:\\APPS\\listener'), ('X:\\APPS\\listener', [])) assert_equals(self.method('C:/varz.py'), ('C:/varz.py', [])) def test_windows_path_with_args(self): assert_equals(self.method('C:\\name.py:arg1'), ('C:\\name.py', ['arg1'])) assert_equals(self.method('D:\\APPS\\listener:v1:b2:z3'), ('D:\\APPS\\listener', ['v1', 'b2', 'z3'])) assert_equals(self.method('C:/varz.py:arg'), ('C:/varz.py', ['arg'])) assert_equals(self.method('C:\\file.py:arg;with;alternative;separator'), ('C:\\file.py', ['arg;with;alternative;separator'])) def test_windows_path_with_semicolon_separator(self): assert_equals(self.method('C:\\name.py;arg1'), ('C:\\name.py', ['arg1'])) assert_equals(self.method('D:\\APPS\\listener;v1;b2;z3'), ('D:\\APPS\\listener', ['v1', 'b2', 'z3'])) assert_equals(self.method('C:/varz.py;arg'), ('C:/varz.py', ['arg'])) assert_equals(self.method('C:\\file.py;arg:with:alternative:separator'), ('C:\\file.py', ['arg:with:alternative:separator'])) def test_existing_paths_are_made_absolute(self): path = 'robot-framework-unit-test-file-12q3405909qasf' open(path, 'w').close() try: assert_equals(self.method(path), (abspath(path), [])) assert_equals(self.method(path+':arg'), (abspath(path), ['arg'])) finally: os.remove(path) def test_existing_path_with_colons(self): # Colons aren't allowed in Windows paths (other than in "c:") if os.sep == '\\': return path = 'robot:framework:test:1:2:42' os.mkdir(path) try: assert_equals(self.method(path), (abspath(path), [])) finally: os.rmdir(path) if __name__ == '__main__': unittest.main()
apache-2.0
googleapis/google-cloud-dotnet
apis/Google.Cloud.ArtifactRegistry.V1Beta2/Google.Cloud.ArtifactRegistry.V1Beta2/FileResourceNames.g.cs
16004
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcav = Google.Cloud.ArtifactRegistry.V1Beta2; using sys = System; namespace Google.Cloud.ArtifactRegistry.V1Beta2 { /// <summary>Resource name for the <c>File</c> resource.</summary> public sealed partial class FileName : gax::IResourceName, sys::IEquatable<FileName> { /// <summary>The possible contents of <see cref="FileName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/repositories/{repository}/files/{file}</c>. /// </summary> ProjectLocationRepositoryFile = 1, } private static gax::PathTemplate s_projectLocationRepositoryFile = new gax::PathTemplate("projects/{project}/locations/{location}/repositories/{repository}/files/{file}"); /// <summary>Creates a <see cref="FileName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="FileName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static FileName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new FileName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="FileName"/> with the pattern /// <c>projects/{project}/locations/{location}/repositories/{repository}/files/{file}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fileId">The <c>File</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="FileName"/> constructed from the provided ids.</returns> public static FileName FromProjectLocationRepositoryFile(string projectId, string locationId, string repositoryId, string fileId) => new FileName(ResourceNameType.ProjectLocationRepositoryFile, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), repositoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId)), fileId: gax::GaxPreconditions.CheckNotNullOrEmpty(fileId, nameof(fileId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="FileName"/> with pattern /// <c>projects/{project}/locations/{location}/repositories/{repository}/files/{file}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fileId">The <c>File</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="FileName"/> with pattern /// <c>projects/{project}/locations/{location}/repositories/{repository}/files/{file}</c>. /// </returns> public static string Format(string projectId, string locationId, string repositoryId, string fileId) => FormatProjectLocationRepositoryFile(projectId, locationId, repositoryId, fileId); /// <summary> /// Formats the IDs into the string representation of this <see cref="FileName"/> with pattern /// <c>projects/{project}/locations/{location}/repositories/{repository}/files/{file}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fileId">The <c>File</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="FileName"/> with pattern /// <c>projects/{project}/locations/{location}/repositories/{repository}/files/{file}</c>. /// </returns> public static string FormatProjectLocationRepositoryFile(string projectId, string locationId, string repositoryId, string fileId) => s_projectLocationRepositoryFile.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId)), gax::GaxPreconditions.CheckNotNullOrEmpty(fileId, nameof(fileId))); /// <summary>Parses the given resource name string into a new <see cref="FileName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/repositories/{repository}/files/{file}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="fileName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="FileName"/> if successful.</returns> public static FileName Parse(string fileName) => Parse(fileName, false); /// <summary> /// Parses the given resource name string into a new <see cref="FileName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/repositories/{repository}/files/{file}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="fileName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="FileName"/> if successful.</returns> public static FileName Parse(string fileName, bool allowUnparsed) => TryParse(fileName, allowUnparsed, out FileName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary>Tries to parse the given resource name string into a new <see cref="FileName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/repositories/{repository}/files/{file}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="fileName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="FileName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string fileName, out FileName result) => TryParse(fileName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="FileName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/repositories/{repository}/files/{file}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="fileName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="FileName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string fileName, bool allowUnparsed, out FileName result) { gax::GaxPreconditions.CheckNotNull(fileName, nameof(fileName)); gax::TemplatedResourceName resourceName; if (s_projectLocationRepositoryFile.TryParseName(fileName, out resourceName)) { result = FromProjectLocationRepositoryFile(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(fileName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private FileName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string fileId = null, string locationId = null, string projectId = null, string repositoryId = null) { Type = type; UnparsedResource = unparsedResourceName; FileId = fileId; LocationId = locationId; ProjectId = projectId; RepositoryId = repositoryId; } /// <summary> /// Constructs a new instance of a <see cref="FileName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/repositories/{repository}/files/{file}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fileId">The <c>File</c> ID. Must not be <c>null</c> or empty.</param> public FileName(string projectId, string locationId, string repositoryId, string fileId) : this(ResourceNameType.ProjectLocationRepositoryFile, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), repositoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId)), fileId: gax::GaxPreconditions.CheckNotNullOrEmpty(fileId, nameof(fileId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>File</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FileId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Repository</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string RepositoryId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationRepositoryFile: return s_projectLocationRepositoryFile.Expand(ProjectId, LocationId, RepositoryId, FileId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as FileName); /// <inheritdoc/> public bool Equals(FileName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(FileName a, FileName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(FileName a, FileName b) => !(a == b); } public partial class File { /// <summary> /// <see cref="gcav::FileName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::FileName FileName { get => string.IsNullOrEmpty(Name) ? null : gcav::FileName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
apache-2.0
pepstock-org/Charba
src/org/pepstock/charba/client/commons/NativeJsObjectImage.java
1725
/** Copyright 2017 Andrea "Stock" Stocchero Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.pepstock.charba.client.commons; import org.pepstock.charba.client.dom.elements.Img; import jsinterop.annotations.JsPackage; import jsinterop.annotations.JsType; /** * A java script property setter and getter of {@link Img}. * * @author Andrea "Stock" Stocchero */ @JsType(isNative = true, name = NativeName.JS_OBJECT_IMAGE_HELPER, namespace = JsPackage.GLOBAL) final class NativeJsObjectImage { /** * To avoid any instantiation */ private NativeJsObjectImage() { // do nothing } /** * Allows you to get a property on an object. * * @param target the target object on which to get the property * @param key the name of the property to get * @return the value of the property */ static native Img get(NativeObject target, String key); /** * Allows you to set a property on an object. * * @param target the target object on which to set the property * @param key the name of the property to set * @param value the value to set */ static native void set(NativeObject target, String key, Img value); }
apache-2.0
TNG/ArchUnit
archunit/src/test/java/com/tngtech/archunit/core/importer/testexamples/integration/ClassA.java
405
package com.tngtech.archunit.core.importer.testexamples.integration; public class ClassA implements InterfaceOfClassA { private String init; private String state; int accessibleField = 5; public ClassA(String init) { this.init = init; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
apache-2.0
aaronwalker/camel
components/camel-aws/src/test/java/org/apache/camel/component/aws/s3/AmazonS3ClientMock.java
18887
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.aws.s3; import java.io.File; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.List; import junit.framework.Assert; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.AmazonWebServiceRequest; import com.amazonaws.HttpMethod; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.S3ResponseMetadata; import com.amazonaws.services.s3.model.AbortMultipartUploadRequest; import com.amazonaws.services.s3.model.AccessControlList; import com.amazonaws.services.s3.model.Bucket; import com.amazonaws.services.s3.model.BucketLoggingConfiguration; import com.amazonaws.services.s3.model.BucketNotificationConfiguration; import com.amazonaws.services.s3.model.BucketPolicy; import com.amazonaws.services.s3.model.BucketVersioningConfiguration; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.amazonaws.services.s3.model.CompleteMultipartUploadRequest; import com.amazonaws.services.s3.model.CompleteMultipartUploadResult; import com.amazonaws.services.s3.model.CopyObjectRequest; import com.amazonaws.services.s3.model.CopyObjectResult; import com.amazonaws.services.s3.model.CreateBucketRequest; import com.amazonaws.services.s3.model.DeleteBucketRequest; import com.amazonaws.services.s3.model.DeleteObjectRequest; import com.amazonaws.services.s3.model.DeleteVersionRequest; import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest; import com.amazonaws.services.s3.model.GetObjectMetadataRequest; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadResult; import com.amazonaws.services.s3.model.ListBucketsRequest; import com.amazonaws.services.s3.model.ListMultipartUploadsRequest; import com.amazonaws.services.s3.model.ListObjectsRequest; import com.amazonaws.services.s3.model.ListPartsRequest; import com.amazonaws.services.s3.model.ListVersionsRequest; import com.amazonaws.services.s3.model.MultipartUploadListing; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.Owner; import com.amazonaws.services.s3.model.PartListing; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.model.PutObjectResult; import com.amazonaws.services.s3.model.Region; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectSummary; import com.amazonaws.services.s3.model.SetBucketLoggingConfigurationRequest; import com.amazonaws.services.s3.model.SetBucketVersioningConfigurationRequest; import com.amazonaws.services.s3.model.StorageClass; import com.amazonaws.services.s3.model.UploadPartRequest; import com.amazonaws.services.s3.model.UploadPartResult; import com.amazonaws.services.s3.model.VersionListing; public class AmazonS3ClientMock extends AmazonS3Client { List<S3Object> objects = new ArrayList<S3Object>(); List<PutObjectRequest> putObjectRequests = new ArrayList<PutObjectRequest>(); private boolean nonExistingBucketCreated; public AmazonS3ClientMock() { super(new BasicAWSCredentials("myAccessKey", "mySecretKey")); } @Override public VersionListing listNextBatchOfVersions(VersionListing previousVersionListing) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public VersionListing listVersions(String bucketName, String prefix) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public VersionListing listVersions(String bucketName, String prefix, String keyMarker, String versionIdMarker, String delimiter, Integer maxKeys) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public VersionListing listVersions(ListVersionsRequest listVersionsRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public ObjectListing listObjects(String bucketName) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public ObjectListing listObjects(String bucketName, String prefix) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public ObjectListing listObjects(ListObjectsRequest listObjectsRequest) throws AmazonClientException, AmazonServiceException { if ("nonExistingBucket".equals(listObjectsRequest.getBucketName()) && !nonExistingBucketCreated) { AmazonServiceException ex = new AmazonServiceException("Unknow bucket"); ex.setStatusCode(404); throw ex; } ObjectListing objectListing = new ObjectListing(); int capacity = listObjectsRequest.getMaxKeys(); for (int index = 0; index < objects.size() && index < capacity; index++) { S3ObjectSummary s3ObjectSummary = new S3ObjectSummary(); s3ObjectSummary.setBucketName(objects.get(index).getBucketName()); s3ObjectSummary.setKey(objects.get(index).getKey()); objectListing.getObjectSummaries().add(s3ObjectSummary); } return objectListing; } @Override public ObjectListing listNextBatchOfObjects(ObjectListing previousObjectListing) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public Owner getS3AccountOwner() throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public List<Bucket> listBuckets(ListBucketsRequest listBucketsRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public List<Bucket> listBuckets() throws AmazonClientException, AmazonServiceException { return new ArrayList<Bucket>(); } @Override public String getBucketLocation(String bucketName) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public Bucket createBucket(String bucketName) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public Bucket createBucket(String bucketName, Region region) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public Bucket createBucket(String bucketName, String region) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public Bucket createBucket(CreateBucketRequest createBucketRequest) throws AmazonClientException, AmazonServiceException { if ("nonExistingBucket".equals(createBucketRequest.getBucketName())) { nonExistingBucketCreated = true; } Bucket bucket = new Bucket(); bucket.setName(createBucketRequest.getBucketName()); bucket.setCreationDate(new Date()); bucket.setOwner(new Owner("c2efc7302b9011ba9a78a92ac5fd1cd47b61790499ab5ddf5a37c31f0638a8fc ", "Christian Mueller")); return bucket; } @Override public AccessControlList getObjectAcl(String bucketName, String key) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public AccessControlList getObjectAcl(String bucketName, String key, String versionId) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public void setObjectAcl(String bucketName, String key, AccessControlList acl) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public void setObjectAcl(String bucketName, String key, CannedAccessControlList acl) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public void setObjectAcl(String bucketName, String key, String versionId, AccessControlList acl) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public void setObjectAcl(String bucketName, String key, String versionId, CannedAccessControlList acl) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public AccessControlList getBucketAcl(String bucketName) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public void setBucketAcl(String bucketName, AccessControlList acl) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public void setBucketAcl(String bucketName, CannedAccessControlList acl) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public ObjectMetadata getObjectMetadata(String bucketName, String key) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public ObjectMetadata getObjectMetadata(GetObjectMetadataRequest getObjectMetadataRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public S3Object getObject(String bucketName, String key) throws AmazonClientException, AmazonServiceException { for (S3Object s3Object : objects) { if (bucketName.equals(s3Object.getBucketName()) && key.equals(s3Object.getKey())) { return s3Object; } } return null; } @Override public boolean doesBucketExist(String bucketName) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public void changeObjectStorageClass(String bucketName, String key, StorageClass newStorageClass) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public S3Object getObject(GetObjectRequest getObjectRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public ObjectMetadata getObject(GetObjectRequest getObjectRequest, File destinationFile) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public void deleteBucket(String bucketName) throws AmazonClientException, AmazonServiceException { // noop } @Override public void deleteBucket(DeleteBucketRequest deleteBucketRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public PutObjectResult putObject(String bucketName, String key, File file) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public PutObjectResult putObject(String bucketName, String key, InputStream input, ObjectMetadata metadata) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public PutObjectResult putObject(PutObjectRequest putObjectRequest) throws AmazonClientException, AmazonServiceException { putObjectRequests.add(putObjectRequest); S3Object s3Object = new S3Object(); s3Object.setBucketName(putObjectRequest.getBucketName()); s3Object.setKey(putObjectRequest.getKey()); s3Object.setObjectContent(putObjectRequest.getInputStream()); objects.add(s3Object); PutObjectResult putObjectResult = new PutObjectResult(); putObjectResult.setETag("3a5c8b1ad448bca04584ecb55b836264"); return putObjectResult; } @Override public CopyObjectResult copyObject(String sourceBucketName, String sourceKey, String destinationBucketName, String destinationKey) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public CopyObjectResult copyObject(CopyObjectRequest copyObjectRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public void deleteObject(String bucketName, String key) throws AmazonClientException, AmazonServiceException { //noop } @Override public void deleteObject(DeleteObjectRequest deleteObjectRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public void deleteVersion(String bucketName, String key, String versionId) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public void deleteVersion(DeleteVersionRequest deleteVersionRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public void setBucketVersioningConfiguration(SetBucketVersioningConfigurationRequest setBucketVersioningConfigurationRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public BucketVersioningConfiguration getBucketVersioningConfiguration(String bucketName) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public void setBucketNotificationConfiguration(String bucketName, BucketNotificationConfiguration bucketNotificationConfiguration) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public BucketNotificationConfiguration getBucketNotificationConfiguration(String bucketName) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public BucketLoggingConfiguration getBucketLoggingConfiguration(String bucketName) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public void setBucketLoggingConfiguration(SetBucketLoggingConfigurationRequest setBucketLoggingConfigurationRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public BucketPolicy getBucketPolicy(String bucketName) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public void setBucketPolicy(String bucketName, String policyText) throws AmazonClientException, AmazonServiceException { Assert.assertEquals("nonExistingBucket", bucketName); Assert.assertEquals("xxx", policyText); } @Override public void deleteBucketPolicy(String bucketName) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public URL generatePresignedUrl(String bucketName, String key, Date expiration) throws AmazonClientException { throw new UnsupportedOperationException(); } @Override public URL generatePresignedUrl(String bucketName, String key, Date expiration, HttpMethod method) throws AmazonClientException { throw new UnsupportedOperationException(); } @Override public URL generatePresignedUrl(GeneratePresignedUrlRequest generatePresignedUrlRequest) throws AmazonClientException { throw new UnsupportedOperationException(); } @Override public void abortMultipartUpload(AbortMultipartUploadRequest abortMultipartUploadRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public CompleteMultipartUploadResult completeMultipartUpload(CompleteMultipartUploadRequest completeMultipartUploadRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public InitiateMultipartUploadResult initiateMultipartUpload(InitiateMultipartUploadRequest initiateMultipartUploadRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public MultipartUploadListing listMultipartUploads(ListMultipartUploadsRequest listMultipartUploadsRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public PartListing listParts(ListPartsRequest listPartsRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public UploadPartResult uploadPart(UploadPartRequest uploadPartRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); } @Override public S3ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request) { throw new UnsupportedOperationException(); } }
apache-2.0
vaikas-google/deployment-manager
cmd/helm/create.go
2357
/* Copyright 2016 The Kubernetes 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 main import ( "errors" "fmt" "io" "path/filepath" "github.com/spf13/cobra" "k8s.io/helm/pkg/chartutil" "k8s.io/helm/pkg/proto/hapi/chart" ) const createDesc = ` This command creates a chart directory along with the common files and directories used in a chart. For example, 'helm create foo' will create a directory structure that looks something like this: foo/ | |- .helmignore # Contains patterns to ignore when packaging Helm charts. | |- Chart.yaml # Information about your chart | |- values.yaml # The default values for your templates | |- charts/ # Charts that this chart depends on | |- templates/ # The template files 'helm create' takes a path for an argument. If directories in the given path do not exist, Helm will attempt to create them as it goes. If the given destination exists and there are files in that directory, conflicting files will be overwritten, but other files will be left alone. ` type createCmd struct { name string out io.Writer } func newCreateCmd(out io.Writer) *cobra.Command { cc := &createCmd{ out: out, } cmd := &cobra.Command{ Use: "create NAME", Short: "create a new chart with the given name", Long: createDesc, RunE: func(cmd *cobra.Command, args []string) error { if len(args) == 0 { return errors.New("the name of the new chart is required") } cc.name = args[0] return cc.run() }, } return cmd } func (c *createCmd) run() error { fmt.Fprintf(c.out, "Creating %s\n", c.name) chartname := filepath.Base(c.name) cfile := &chart.Metadata{ Name: chartname, Description: "A Helm chart for Kubernetes", Version: "0.1.0", } _, err := chartutil.Create(cfile, filepath.Dir(c.name)) return err }
apache-2.0
booz-allen-hamilton/culvert
culvert-main/src/main/java/com/bah/culvert/constraints/filter/ResultFilter.java
10993
/** * Copyright 2011 Booz Allen Hamilton. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. Booz Allen Hamilton * 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.bah.culvert.constraints.filter; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.ObjectWritable; import com.bah.culvert.adapter.TableAdapter; import com.bah.culvert.constraints.Constraint; import com.bah.culvert.data.CColumn; import com.bah.culvert.data.CKeyValue; import com.bah.culvert.data.CRange; import com.bah.culvert.data.Result; import com.bah.culvert.iterators.SeekingCurrentIterator; import com.bah.culvert.transactions.Get; import com.bah.culvert.util.Bytes; /** * Filter results from the subconstraint or direct table lookup. * <p> * Picks out exclusively the wanted columns from the result set. Unless no * columns are specified, columns not selected for are explicitly removed. * <p> * Currently does not provide implementation for filtering timestamps, but this * can be implemented in a subclass later. */ public class ResultFilter extends Constraint { private static final ObjectWritable ow = new ObjectWritable(); static { Configuration conf = new Configuration(); ow.setConf(conf); } private TableAdapter table; private Constraint subConstraint; private CColumn[] columns; private CRange range; /** * for use with {@link #readFields(DataInput)} */ public ResultFilter() { } /** * Select the specified columns from the range of specified keys, according to * a specified sub-constraint * @param subConstraint to apply when getting results * @param range of keys to select from * @param columns to select. */ public ResultFilter(Constraint subConstraint, CRange range, CColumn... columns) { this.range = range; this.columns = columns; this.subConstraint = subConstraint; this.table = null; } /** * Select the columns from rows in the matching range * @param primaryTable To read results from * @param range of rows to check * @param columns to return */ public ResultFilter(TableAdapter primaryTable, CRange range, CColumn... columns) { this((Constraint) null, range, columns); this.table = primaryTable; } /** * Select all columns from the range of specified keys, according to a * specified sub-constraint. * @param range of keys to select from * @param subConstraint to apply when getting results */ public ResultFilter(CRange range, Constraint subConstraint) { this(subConstraint, range, new CColumn[0]); } /** * Select all columns from the range of specified keys from the specified * table * @param primaryTable to read from * @param range of keys to select from */ public ResultFilter(TableAdapter primaryTable, CRange range) { this(primaryTable, range, new CColumn[0]); } /** * Select the specified columns from the entire range of keys, according to a * specified sub-constraint. Gets the specified columns from the entire table, * after applying the subconstraint. * @param subConstraint to apply when getting results * @param columns to select. */ public ResultFilter(Constraint subConstraint, CColumn... columns) { this(subConstraint, CRange.FULL_TABLE_RANGE, columns); } /** * Select the specified columns from the entire range of keys of the specified * table * @param primaryTable to filter when getting results * @param columns to select. */ public ResultFilter(TableAdapter primaryTable, CColumn... columns) { this(primaryTable, CRange.FULL_TABLE_RANGE, columns); } /** * Select all columns and rows from the specified table * @param primaryTable to select from */ public ResultFilter(TableAdapter primaryTable) { this(primaryTable, CRange.FULL_TABLE_RANGE); } @Override public boolean equals(Object compareto) { if (!(compareto instanceof ResultFilter)) { return false; } // has to be a logic ResultFilter compare = (ResultFilter) compareto; if (this.subConstraint == null && compare.subConstraint != null) { return false; } if (this.subConstraint != null && compare.subConstraint == null) { return false; } if (this.subConstraint != null) { if (this.subConstraint.equals(compare.subConstraint) && Arrays.equals(this.columns, compare.columns) && this.range.compareTo(compare.range) == 0) { return true; } else { return false; } } return true; } @Override public int hashCode() { return this.subConstraint.hashCode() + this.columns.hashCode(); } @Override public String toString() { String s = "SelectFields(" + this.columns.toString() + ", " + this.subConstraint.toString() + ")"; return s; } @Override public SeekingCurrentIterator getResultIterator() { SeekingCurrentIterator results; // if there is no subconstraint, just do the get on the table if (this.subConstraint == null) { Get get = new Get(this.range); for (CColumn column : this.columns) get.addColumn(column.getColumnFamily(), column.getColumnQualifier()); results = table.get(get); } else results = this.subConstraint.getResultIterator(); // check to see if we need to filter the columns if (this.columns == null || this.columns.length == 0) return results; // if we do, return a filtered version return new FilteringIterator(this.columns, results); } @Override public void readFields(DataInput in) throws IOException { if (in.readBoolean()) this.subConstraint = Constraint.readFromStream(in); // read in the columns ow.readFields(in); this.columns = (CColumn[]) ow.get(); // read in the range this.range = new CRange(); this.range.readFields(in); // read in the table if (in.readBoolean()) { ow.readFields(in); this.table = (TableAdapter) ow.get(); } } @Override public void write(DataOutput out) throws IOException { if (this.subConstraint == null) out.writeBoolean(false); else { out.writeBoolean(true); // write out the subconstraint Constraint.write(this.subConstraint, out); } // write out the columns ow.set(this.columns); ow.write(out); // write out the range this.range.write(out); if (this.table == null) out.writeBoolean(false); else { out.writeBoolean(true); // write out the table new ObjectWritable(this.table).write(out); } } /** * Use another {@link SeekingCurrentIterator} and filter the results so that * only results are returned with matching columns. If there are less columns * than specified in the query, only the matching columns are returned. * */ private static class FilteringIterator implements SeekingCurrentIterator { private final CColumn[] columns; private final SeekingCurrentIterator delegate; private Result current = null; private Result next = null; public FilteringIterator(CColumn[] columns, SeekingCurrentIterator results) { this.columns = columns; this.delegate = results; this.next = getNext(); } @Override public boolean hasNext() { if (this.next == null) markDoneWith(); return this.next != null; } @Override public Result next() { // get the next result this.current = this.next; this.next = getNext(); return this.current; } /** * @return the next valid result */ private Result getNext() { // while there are more delegate results while (this.delegate.hasNext()) { Result r = this.delegate.next(); List<CKeyValue> values = filterKeys(r.getKeyValues()); if (values.size() == 0) continue; return new Result(values); } return null; } private List<CKeyValue> filterKeys(Iterable<CKeyValue> keyValues) { List<CKeyValue> values = new ArrayList<CKeyValue>(); for (CKeyValue value : keyValues) { // if there are no checked columns, then add the value if (this.columns == null || this.columns.length == 0) { values.add(value); continue; } // now we need to check each of the columns to see if we include the // value for (CColumn column : this.columns) { // check the column family // if empty column, add the value if (column.getColumnFamily() == null || column.getColumnFamily().length == 0) values.add(value); // now check that they actually match for the column else if (Bytes.compareTo(column.getColumnFamily(), value.getFamily()) == 0) { // check the column qualifier, for blanket acceptance or matching if (column.getColumnQualifier() == null || column.getColumnQualifier().length == 0 || Bytes.compareTo(column.getColumnQualifier(), value.getQualifier()) == 0) // TODO add timestamp filtering // assumes that the underlying table only returns the most recent // value values.add(value); } } } return values; } @Override public void remove() { throw new UnsupportedOperationException( "Cannot remove results from a query iterator."); } @Override public Result current() { return this.current; } @Override public void seek(byte[] key) { this.delegate.seek(key); Result r = this.delegate.current(); // set the current if (r == null) this.current = null; else { List<CKeyValue> kvs = filterKeys(r.getKeyValues()); this.current = kvs.size() == 0 ? null : new Result(kvs); } // set the next this.next = this.delegate.hasNext() ? getNext() : null; } @Override public void markDoneWith() { this.delegate.markDoneWith(); } @Override public boolean isMarkedDoneWith() { return this.delegate.isMarkedDoneWith(); } } }
apache-2.0
lithiumtech/lithium-sdk
templates/directive/_directive_.js
383
'use strict'; angular.module('li.<%= type %>s.<%= subModule %>.<%= name %>', []) /** * @module <%= subModule %> * @ngdoc <%= type %> * @name <%= name %> * * @restrict AE * * @description * TODO: add description */ .directive('<%= directiveName %>', function () { return { restrict: 'AE', templateUrl: '<%= subModule %>/<%= name %>/<%= name %>.tpl.html' }; });
apache-2.0
adaptivdesign/odooku-compat
odooku/addons/cdn/models/ir_qweb.py
3985
# -*- coding: utf-8 -*- import ast import odoo from odoo import models, tools, SUPERUSER_ID from odoo.http import request from odoo.addons.base.ir.ir_qweb.assetsbundle import AssetsBundle from odooku.backends import get_backend from odooku.params import params CDN_ENABLED = getattr(params, 'CDN_ENABLED', False) s3_backend = get_backend('s3') class IrQWeb(models.AbstractModel): _inherit = 'ir.qweb' CDN_TRIGGERS = { 'link': 'href', 'script': 'src', 'img': 'src', } def _cdn_url(self, url): parts = url.split('/') cr, env = request.cr, request.env if url.startswith('/web/content/'): IrAttachment = env['ir.attachment'] attachments = IrAttachment.search([('url', '=like', url)]) if attachments: # /filestore/<dbname/<attachment> url = s3_backend.get_url('filestore', cr.dbname, attachments[0].store_fname) elif len(parts) > 3 and parts[2] == 'static': # /<module>/static url = s3_backend.get_url(url[1:]) return url def _cdn_build_attribute(self, tagName, name, value, options, values): return self._cdn_url(value) def _wrap_cdn_build_attributes(self, el, items, options): if (options.get('rendering_bundle') or not CDN_ENABLED or not s3_backend or el.tag not in self.CDN_TRIGGERS): # Shortcircuit return items cdn_att = self.CDN_TRIGGERS.get(el.tag) def process(item): if isinstance(item, tuple) and item[0] == cdn_att: return (item[0], ast.Call( func=ast.Attribute( value=ast.Name(id='self', ctx=ast.Load()), attr='_cdn_build_attribute', ctx=ast.Load() ), args=[ ast.Str(el.tag), ast.Str(item[0]), item[1], ast.Name(id='options', ctx=ast.Load()), ast.Name(id='values', ctx=ast.Load()), ], keywords=[], starargs=None, kwargs=None )) else: return item return map(process, items) def _compile_static_attributes(self, el, options): items = super(IrQWeb, self)._compile_static_attributes(el, options) return self._wrap_cdn_build_attributes(el, items, options) def _compile_dynamic_attributes(self, el, options): items = super(IrQWeb, self)._compile_dynamic_attributes(el, options) return self._wrap_cdn_build_attributes(el, items, options) def _get_dynamic_att(self, tagName, atts, options, values): atts = super(IrQWeb, self)._get_dynamic_att(tagName, atts, options, values) if (options.get('rendering_bundle') or not CDN_ENABLED or not s3_backend or tagName not in self.CDN_TRIGGERS): # Shortcircuit return atts for name, value in atts.iteritems(): atts[name] = self._cdn_build_attribute(tagName, name, value, options, values) return atts def _is_static_node(self, el): cdn_att = self.CDN_TRIGGERS.get(el.tag, False) return super(IrQWeb, self)._is_static_node(el) and \ (not cdn_att or not el.get(cdn_att)) def _get_asset(self, xmlid, options, css=True, js=True, debug=False, async=False, values=None): # Commit_assetsbundle is assigned when rendering a pdf. # We use it to distinguish between web and pdf report asset url's. # hackish !! if CDN_ENABLED and s3_backend and not options.get('commit_assetsbundle'): values = dict(values or {}, url_for=self._cdn_url) return super(IrQWeb, self)._get_asset(xmlid, options, css, js, debug, async, values)
apache-2.0
NinjaVault/NinjaHive
NinjaHive.Core/Extensions/CollectionExtensions.cs
619
using System.Collections.Generic; using System.Collections.ObjectModel; namespace NinjaHive.Core.Extensions { public static class CollectionExtensions { public static IReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T> list) { var localList = new List<T>(list); return new ReadOnlyCollection<T>(localList); } public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> listToAdd) { foreach(var item in listToAdd) { collection.Add(item); } } } }
apache-2.0
YanTangZhai/tf
tensorflow/core/kernels/cast_op_gpu.cu.cc
1786
/* Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #if GOOGLE_CUDA #define EIGEN_USE_GPU #include "tensorflow/core/framework/bfloat16.h" #include "tensorflow/core/kernels/cast_op.h" namespace tensorflow { namespace functor { typedef Eigen::GpuDevice GPUDevice; template <typename O, typename I> struct CastFunctor<GPUDevice, O, I> { void operator()(const GPUDevice& d, typename TTypes<O>::Flat o, typename TTypes<I>::ConstFlat i) { Cast<GPUDevice, O, I>(d, o, i); } }; #define DEFINE(O, I) template struct CastFunctor<GPUDevice, O, I> #define DEFINE_ALL_FROM(in_type) \ DEFINE(in_type, bool); \ DEFINE(in_type, uint8); \ DEFINE(in_type, int16); \ DEFINE(in_type, int32); \ DEFINE(in_type, int64); \ DEFINE(in_type, float); \ DEFINE(in_type, double) DEFINE_ALL_FROM(bool); DEFINE_ALL_FROM(uint8); DEFINE_ALL_FROM(int16); DEFINE_ALL_FROM(int32); DEFINE_ALL_FROM(int64); DEFINE_ALL_FROM(float); DEFINE_ALL_FROM(double); DEFINE(bfloat16, float); DEFINE(float, bfloat16); #undef DEFINE_ALL_FROM #undef DEFINE } // end namespace functor } // end namespace tensorflow #endif // GOOGLE_CUDA
apache-2.0
mongodb/mongo-ruby-driver
spec/mongo/operation/remove_user_spec.rb
1230
# frozen_string_literal: true # encoding: utf-8 require 'spec_helper' describe Mongo::Operation::RemoveUser do require_no_required_api_version let(:context) { Mongo::Operation::Context.new } describe '#execute' do before do users = root_authorized_client.database.users if users.info('durran').any? users.remove('durran') end users.create( 'durran', password: 'password', roles: [ Mongo::Auth::Roles::READ_WRITE ] ) end let(:operation) do described_class.new(user_name: 'durran', db_name: SpecConfig.instance.test_db) end context 'when user removal was successful' do let!(:response) do operation.execute(root_authorized_primary, context: context) end it 'removes the user from the database' do expect(response).to be_successful end end context 'when removal was not successful' do before do operation.execute(root_authorized_primary, context: context) end it 'raises an exception' do expect { operation.execute(root_authorized_primary, context: context) }.to raise_error(Mongo::Error::OperationFailure) end end end end
apache-2.0
yahoo/athenz
servers/zts/src/test/java/com/yahoo/athenz/zts/cert/impl/HttpCertSignerTest.java
14507
/* * Copyright 2016 Yahoo 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.yahoo.athenz.zts.cert.impl; import static org.testng.Assert.*; import java.util.concurrent.TimeoutException; import com.yahoo.athenz.common.server.cert.CertSigner; import com.yahoo.athenz.instance.provider.InstanceProvider; import com.yahoo.athenz.zts.ResourceException; import com.yahoo.athenz.zts.ZTSConsts; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Request; import org.mockito.Mockito; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class HttpCertSignerTest { @BeforeClass public void setup() { System.setProperty(ZTSConsts.ZTS_PROP_CERTSIGN_BASE_URI, "https://localhost:443/certsign/v2"); } @Test public void testHttpCertSignerFactory() { HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); assertNotNull(certFactory); CertSigner certSigner = certFactory.create(); assertNotNull(certSigner); certSigner.close(); } @Test public void testGenerateX509CertificateException() throws Exception { HttpClient httpClient = Mockito.mock(HttpClient.class); HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); HttpCertSigner certSigner = (HttpCertSigner) certFactory.create(); certSigner.setHttpClient(httpClient); Request request = Mockito.mock(Request.class); Mockito.when(httpClient.POST("https://localhost:443/certsign/v2/x509")).thenReturn(request); Mockito.when(request.send()).thenThrow(new TimeoutException()); assertNull(certSigner.generateX509Certificate("aws", "us-west-2", "csr", null, 0)); certSigner.close(); } @Test public void testGenerateX509CertificateInvalidStatus() throws Exception { HttpClient httpClient = Mockito.mock(HttpClient.class); HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); HttpCertSigner certSigner = (HttpCertSigner) certFactory.create(); certSigner.setHttpClient(httpClient); Request request = Mockito.mock(Request.class); Mockito.when(httpClient.POST("https://localhost:443/certsign/v2/x509")).thenReturn(request); ContentResponse response = Mockito.mock(ContentResponse.class); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.getStatus()).thenReturn(400); assertNull(certSigner.generateX509Certificate("aws", "us-west-2", "csr", null, 0)); certSigner.close(); } @Test public void testGenerateX509CertificateResponseNull() throws Exception { HttpClient httpClient = Mockito.mock(HttpClient.class); HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); HttpCertSigner certSigner = (HttpCertSigner) certFactory.create(); certSigner.setHttpClient(httpClient); Request request = Mockito.mock(Request.class); Mockito.when(httpClient.POST("https://localhost:443/certsign/v2/x509")).thenReturn(request); ContentResponse response = Mockito.mock(ContentResponse.class); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.getStatus()).thenReturn(201); Mockito.when(response.getContentAsString()).thenReturn(null); assertNull(certSigner.generateX509Certificate("aws", "us-west-2", "csr", null, 0)); certSigner.close(); } @Test public void testGenerateX509CertificateResponseEmpty() throws Exception { HttpClient httpClient = Mockito.mock(HttpClient.class); HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); HttpCertSigner certSigner = (HttpCertSigner) certFactory.create(); certSigner.setHttpClient(httpClient); Request request = Mockito.mock(Request.class); Mockito.when(httpClient.POST("https://localhost:443/certsign/v2/x509")).thenReturn(request); ContentResponse response = Mockito.mock(ContentResponse.class); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.getStatus()).thenReturn(201); Mockito.when(response.getContentAsString()).thenReturn(""); assertNull(certSigner.generateX509Certificate("aws", "us-west-2", "csr", null, 0)); certSigner.close(); } @Test public void testGenerateX509Certificate() throws Exception { HttpClient httpClient = Mockito.mock(HttpClient.class); HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); HttpCertSigner certSigner = (HttpCertSigner) certFactory.create(); certSigner.setHttpClient(httpClient); Request request = Mockito.mock(Request.class); Mockito.when(httpClient.POST("https://localhost:443/certsign/v2/x509")).thenReturn(request); ContentResponse response = Mockito.mock(ContentResponse.class); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.getStatus()).thenReturn(201); Mockito.when(response.getContentAsString()).thenReturn("{\"pem\": \"pem-value\"}"); String pem = certSigner.generateX509Certificate("aws", "us-west-2", "csr", null, 0); assertEquals(pem, "pem-value"); pem = certSigner.generateX509Certificate("aws", "us-west-2", "csr", InstanceProvider.ZTS_CERT_USAGE_CLIENT, 0); assertEquals(pem, "pem-value"); pem = certSigner.generateX509Certificate("aws", "us-west-2", "csr", InstanceProvider.ZTS_CERT_USAGE_CLIENT, 30); assertEquals(pem, "pem-value"); certSigner.requestTimeout = 120; pem = certSigner.generateX509Certificate("aws", "us-west-2", "csr", InstanceProvider.ZTS_CERT_USAGE_CLIENT, 30); assertEquals(pem, "pem-value"); certSigner.close(); } @Test public void testGenerateX509CertificateInvalidData() throws Exception { HttpClient httpClient = Mockito.mock(HttpClient.class); HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); HttpCertSigner certSigner = (HttpCertSigner) certFactory.create(); certSigner.setHttpClient(httpClient); Request request = Mockito.mock(Request.class); Mockito.when(httpClient.POST("https://localhost:443/certsign/v2/x509")).thenReturn(request); ContentResponse response = Mockito.mock(ContentResponse.class); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.getStatus()).thenReturn(201); Mockito.when(response.getContentAsString()).thenReturn("{\"pem2\": \"pem-value\"}"); assertNull(certSigner.generateX509Certificate("aws", "us-west-2", "csr", null, 0)); Mockito.when(response.getContentAsString()).thenReturn("invalid-json"); assertNull(certSigner.generateX509Certificate("aws", "us-west-2", "csr", null, 0)); certSigner.close(); } @Test public void testGetCACertificateException() throws Exception { HttpClient httpClient = Mockito.mock(HttpClient.class); HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); HttpCertSigner certSigner = (HttpCertSigner) certFactory.create(); certSigner.setHttpClient(httpClient); Mockito.when(httpClient.GET("https://localhost:443/certsign/v2/x509")).thenThrow(new TimeoutException()); assertNull(certSigner.getCACertificate("aws")); certSigner.close(); } @Test public void testGetCACertificateInvalidStatus() throws Exception { HttpClient httpClient = Mockito.mock(HttpClient.class); HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); HttpCertSigner certSigner = (HttpCertSigner) certFactory.create(); certSigner.setHttpClient(httpClient); ContentResponse response = Mockito.mock(ContentResponse.class); Mockito.when(httpClient.GET("https://localhost:443/certsign/v2/x509")).thenReturn(response); Mockito.when(response.getStatus()).thenReturn(400); assertNull(certSigner.getCACertificate("aws")); certSigner.close(); } @Test public void testGetCACertificateResponseNull() throws Exception { HttpClient httpClient = Mockito.mock(HttpClient.class); HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); HttpCertSigner certSigner = (HttpCertSigner) certFactory.create(); certSigner.setHttpClient(httpClient); ContentResponse response = Mockito.mock(ContentResponse.class); Mockito.when(httpClient.GET("https://localhost:443/certsign/v2/x509")).thenReturn(response); Mockito.when(response.getStatus()).thenReturn(200); Mockito.when(response.getContentAsString()).thenReturn(null); assertNull(certSigner.getCACertificate("aws")); certSigner.close(); } @Test public void testGetCACertificateResponseEmpty() throws Exception { HttpClient httpClient = Mockito.mock(HttpClient.class); HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); HttpCertSigner certSigner = (HttpCertSigner) certFactory.create(); certSigner.setHttpClient(httpClient); ContentResponse response = Mockito.mock(ContentResponse.class); Mockito.when(httpClient.GET("https://localhost:443/certsign/v2/x509")).thenReturn(response); Mockito.when(response.getStatus()).thenReturn(200); Mockito.when(response.getContentAsString()).thenReturn(""); assertNull(certSigner.getCACertificate("aws")); certSigner.close(); } @Test public void testGetCACertificate() throws Exception { HttpClient httpClient = Mockito.mock(HttpClient.class); HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); HttpCertSigner certSigner = (HttpCertSigner) certFactory.create(); certSigner.setHttpClient(httpClient); ContentResponse response = Mockito.mock(ContentResponse.class); Mockito.when(httpClient.GET("https://localhost:443/certsign/v2/x509")).thenReturn(response); Mockito.when(response.getStatus()).thenReturn(200); Mockito.when(response.getContentAsString()).thenReturn("{\"pem\": \"pem-value\"}"); String pem = certSigner.getCACertificate("aws"); assertEquals(pem, "pem-value"); certSigner.close(); } @Test public void testGetCACertificateInvalidData() throws Exception { HttpClient httpClient = Mockito.mock(HttpClient.class); HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); HttpCertSigner certSigner = (HttpCertSigner) certFactory.create(); certSigner.setHttpClient(httpClient); ContentResponse response = Mockito.mock(ContentResponse.class); Mockito.when(httpClient.GET("https://localhost:443/certsign/v2/x509")).thenReturn(response); Mockito.when(response.getStatus()).thenReturn(200); Mockito.when(response.getContentAsString()).thenReturn("{\"pem2\": \"pem-value\"}"); assertNull(certSigner.getCACertificate("aws")); Mockito.when(response.getContentAsString()).thenReturn("invalid-json"); assertNull(certSigner.getCACertificate("aws")); certSigner.close(); } @Test public void testGetMaxCertExpiryTime() { System.clearProperty(ZTSConsts.ZTS_PROP_CERTSIGN_MAX_EXPIRY_TIME); HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); HttpCertSigner certSigner = (HttpCertSigner) certFactory.create(); assertEquals(certSigner.getMaxCertExpiryTimeMins(), 43200); certSigner.close(); System.setProperty(ZTSConsts.ZTS_PROP_CERTSIGN_MAX_EXPIRY_TIME, "1200"); certSigner = (HttpCertSigner) certFactory.create(); assertEquals(certSigner.getMaxCertExpiryTimeMins(), 1200); certSigner.close(); System.clearProperty(ZTSConsts.ZTS_PROP_CERTSIGN_MAX_EXPIRY_TIME); } @Test public void testInitInvalidUri() { System.clearProperty(ZTSConsts.ZTS_PROP_CERTSIGN_BASE_URI); HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); try { certFactory.create(); fail(); } catch (ResourceException ex) { assertTrue(ex.getMessage().contains("No CertSigner base uri specified")); } System.setProperty(ZTSConsts.ZTS_PROP_CERTSIGN_BASE_URI, "https://localhost:443/certsign/v2"); } @Test public void testSetupHttpClient() throws Exception { HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); HttpCertSigner certSigner = (HttpCertSigner) certFactory.create(); HttpClient client = Mockito.mock(HttpClient.class); Mockito.doThrow(new Exception("Invalid client")).when(client).start(); try { certSigner.setupHttpClient(client, 120, 120); fail(); } catch (ResourceException ex) { assertEquals(ex.getCode(), 500); } } @Test public void testStopNullHttpClient() { HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); HttpCertSigner certSigner = (HttpCertSigner) certFactory.create(); certSigner.setHttpClient(null); certSigner.close(); } @Test public void testLoadServicePrivateKeyInvalid() { System.setProperty(ZTSConsts.ZTS_PROP_PRIVATE_KEY_STORE_FACTORY_CLASS, "invalid.class"); try { HttpCertSignerFactory certFactory = new HttpCertSignerFactory(); certFactory.create(); fail(); } catch (IllegalArgumentException ex) { assertTrue(ex.getMessage().contains("Invalid private key store")); } System.clearProperty(ZTSConsts.ZTS_PROP_PRIVATE_KEY_STORE_FACTORY_CLASS); } }
apache-2.0
envoyproxy/protoc-gen-validate
templates/cc/register.go
11474
package cc import ( "fmt" "reflect" "strconv" "strings" "text/template" "github.com/envoyproxy/protoc-gen-validate/templates/shared" "github.com/iancoleman/strcase" pgs "github.com/lyft/protoc-gen-star" pgsgo "github.com/lyft/protoc-gen-star/lang/go" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" ) func RegisterModule(tpl *template.Template, params pgs.Parameters) { fns := CCFuncs{pgsgo.InitContext(params)} tpl.Funcs(map[string]interface{}{ "accessor": fns.accessor, "byteStr": fns.byteStr, "class": fns.className, "cmt": pgs.C80, "ctype": fns.cType, "durGt": fns.durGt, "durLit": fns.durLit, "durStr": fns.durStr, "err": fns.err, "errCause": fns.errCause, "errIdx": fns.errIdx, "errIdxCause": fns.errIdxCause, "hasAccessor": fns.hasAccessor, "inKey": fns.inKey, "inType": fns.inType, "isBytes": fns.isBytes, "lit": fns.lit, "lookup": fns.lookup, "oneof": fns.oneofTypeName, "output": fns.output, "package": fns.packageName, "quote": fns.quote, "staticVarName": fns.staticVarName, "tsGt": fns.tsGt, "tsLit": fns.tsLit, "tsStr": fns.tsStr, "typ": fns.Type, "unimplemented": fns.failUnimplemented, "unwrap": fns.unwrap, }) template.Must(tpl.Parse(moduleFileTpl)) template.Must(tpl.New("msg").Parse(msgTpl)) template.Must(tpl.New("const").Parse(constTpl)) template.Must(tpl.New("ltgt").Parse(ltgtTpl)) template.Must(tpl.New("in").Parse(inTpl)) template.Must(tpl.New("required").Parse(requiredTpl)) template.Must(tpl.New("none").Parse(noneTpl)) template.Must(tpl.New("float").Parse(numTpl)) template.Must(tpl.New("double").Parse(numTpl)) template.Must(tpl.New("int32").Parse(numTpl)) template.Must(tpl.New("int64").Parse(numTpl)) template.Must(tpl.New("uint32").Parse(numTpl)) template.Must(tpl.New("uint64").Parse(numTpl)) template.Must(tpl.New("sint32").Parse(numTpl)) template.Must(tpl.New("sint64").Parse(numTpl)) template.Must(tpl.New("fixed32").Parse(numTpl)) template.Must(tpl.New("fixed64").Parse(numTpl)) template.Must(tpl.New("sfixed32").Parse(numTpl)) template.Must(tpl.New("sfixed64").Parse(numTpl)) template.Must(tpl.New("bool").Parse(constTpl)) template.Must(tpl.New("string").Parse(strTpl)) template.Must(tpl.New("bytes").Parse(bytesTpl)) template.Must(tpl.New("email").Parse(emailTpl)) template.Must(tpl.New("hostname").Parse(hostTpl)) template.Must(tpl.New("address").Parse(hostTpl)) template.Must(tpl.New("uuid").Parse(uuidTpl)) template.Must(tpl.New("enum").Parse(enumTpl)) template.Must(tpl.New("message").Parse(messageTpl)) template.Must(tpl.New("repeated").Parse(repTpl)) template.Must(tpl.New("map").Parse(mapTpl)) template.Must(tpl.New("any").Parse(anyTpl)) template.Must(tpl.New("duration").Parse(durationTpl)) template.Must(tpl.New("timestamp").Parse(timestampTpl)) template.Must(tpl.New("wrapper").Parse(wrapperTpl)) } func RegisterHeader(tpl *template.Template, params pgs.Parameters) { fns := CCFuncs{pgsgo.InitContext(params)} tpl.Funcs(map[string]interface{}{ "class": fns.className, "output": fns.output, "screaming_snake_case": strcase.ToScreamingSnake, }) template.Must(tpl.Parse(headerFileTpl)) template.Must(tpl.New("decl").Parse(declTpl)) } // TODO(rodaine): break pgsgo dependency here (with equivalent pgscc subpackage) type CCFuncs struct{ pgsgo.Context } func CcFilePath(f pgs.File, ctx pgsgo.Context, tpl *template.Template) *pgs.FilePath { out := pgs.FilePath(f.Name().String()) out = out.SetExt(".pb.validate." + tpl.Name()) return &out } func (fns CCFuncs) methodName(name interface{}) string { nameStr := fmt.Sprintf("%s", name) switch nameStr { case "const": return "const_" case "inline": return "inline_" default: return nameStr } } func (fns CCFuncs) accessor(ctx shared.RuleContext) string { if ctx.AccessorOverride != "" { return ctx.AccessorOverride } return fmt.Sprintf( "m.%s()", fns.methodName(ctx.Field.Name())) } func (fns CCFuncs) hasAccessor(ctx shared.RuleContext) string { if ctx.AccessorOverride != "" { return "true" } return fmt.Sprintf( "m.has_%s()", fns.methodName(ctx.Field.Name())) } type childEntity interface { pgs.Entity Parent() pgs.ParentEntity } func (fns CCFuncs) classBaseName(ent childEntity) string { if m, ok := ent.Parent().(pgs.Message); ok { return fmt.Sprintf("%s_%s", fns.classBaseName(m), ent.Name().String()) } return ent.Name().String() } func (fns CCFuncs) className(ent childEntity) string { return fns.packageName(ent) + "::" + fns.classBaseName(ent) } func (fns CCFuncs) packageName(msg pgs.Entity) string { return "::" + strings.Join(msg.Package().ProtoName().Split(), "::") } func (fns CCFuncs) quote(s interface { String() string }) string { return strconv.Quote(s.String()) } func (fns CCFuncs) err(ctx shared.RuleContext, reason ...interface{}) string { return fns.errIdxCause(ctx, "", "nil", reason...) } func (fns CCFuncs) errCause(ctx shared.RuleContext, cause string, reason ...interface{}) string { return fns.errIdxCause(ctx, "", cause, reason...) } func (fns CCFuncs) errIdx(ctx shared.RuleContext, idx string, reason ...interface{}) string { return fns.errIdxCause(ctx, idx, "nil", reason...) } func (fns CCFuncs) errIdxCause(ctx shared.RuleContext, idx, cause string, reason ...interface{}) string { f := ctx.Field errName := fmt.Sprintf("%sValidationError", f.Message().Name()) output := []string{ "{", `std::ostringstream msg("invalid ");`, } if ctx.OnKey { output = append(output, `msg << "key for ";`) } output = append(output, fmt.Sprintf(`msg << %q << "." << %s;`, errName, fns.lit(pgsgo.PGGUpperCamelCase(f.Name())))) if idx != "" { output = append(output, fmt.Sprintf(`msg << "[" << %s << "]";`, idx)) } else if ctx.Index != "" { output = append(output, fmt.Sprintf(`msg << "[" << %s << "]";`, ctx.Index)) } output = append(output, fmt.Sprintf(`msg << ": " << %q;`, fmt.Sprint(reason...))) if cause != "nil" && cause != "" { output = append(output, fmt.Sprintf(`msg << " | caused by " << %s;`, cause)) } output = append(output, "*err = msg.str();", "return false;", "}") return strings.Join(output, "\n") } func (fns CCFuncs) lookup(f pgs.Field, name string) string { return fmt.Sprintf( "_%s_%s_%s", pgsgo.PGGUpperCamelCase(f.Message().Name()), pgsgo.PGGUpperCamelCase(f.Name()), name, ) } func (fns CCFuncs) lit(x interface{}) string { val := reflect.ValueOf(x) if val.Kind() == reflect.Interface { val = val.Elem() } if val.Kind() == reflect.Ptr { val = val.Elem() } switch val.Kind() { case reflect.String: return fmt.Sprintf("%q", x) case reflect.Uint8: return fmt.Sprintf("%d", x) case reflect.Slice: els := make([]string, val.Len()) switch reflect.TypeOf(x).Elem().Kind() { case reflect.Uint8: for i, l := 0, val.Len(); i < l; i++ { els[i] = fmt.Sprintf("\\x%x", val.Index(i).Interface()) } return fmt.Sprintf("\"%s\"", strings.Join(els, "")) default: panic(fmt.Sprintf("don't know how to format literals of type %v", val.Kind())) } case reflect.Float32: return fmt.Sprintf("%fF", x) default: return fmt.Sprint(x) } } func (fns CCFuncs) isBytes(f interface { ProtoType() pgs.ProtoType }) bool { return f.ProtoType() == pgs.BytesT } func (fns CCFuncs) byteStr(x []byte) string { elms := make([]string, len(x)) for i, b := range x { elms[i] = fmt.Sprintf(`\x%X`, b) } return fmt.Sprintf(`"%s"`, strings.Join(elms, "")) } func (fns CCFuncs) oneofTypeName(f pgs.Field) pgsgo.TypeName { return pgsgo.TypeName(fmt.Sprintf("%s::%sCase::k%s", fns.className(f.Message()), pgsgo.PGGUpperCamelCase(f.OneOf().Name()), strings.ReplaceAll(pgsgo.PGGUpperCamelCase(f.Name()).String(), "_", ""))) } func (fns CCFuncs) inType(f pgs.Field, x interface{}) string { switch f.Type().ProtoType() { case pgs.BytesT: return "string" case pgs.MessageT: switch x.(type) { case []string: return "string" case []*durationpb.Duration: return "pgv::protobuf_wkt::Duration" default: return fns.className(f.Type().Element().Embed()) } default: return fns.cType(f.Type()) } } func (fns CCFuncs) cType(t pgs.FieldType) string { if t.IsEmbed() { return fns.className(t.Embed()) } if t.IsRepeated() { if t.ProtoType() == pgs.MessageT { return fns.className(t.Element().Embed()) } // Strip the leading [] return fns.cTypeOfString(fns.Type(t.Field()).String()[2:]) } else if t.IsMap() { if t.Element().IsEmbed() { return fns.className(t.Element().Embed()) } return fns.cTypeOfString(fns.Type(t.Field()).Element().String()) } return fns.cTypeOfString(fns.Type(t.Field()).String()) } func (fns CCFuncs) cTypeOfString(s string) string { switch s { case "float32": return "float" case "float64": return "double" case "int32": return "int32_t" case "int64": return "int64_t" case "uint32": return "uint32_t" case "uint64": return "uint64_t" case "[]byte": return "string" default: return s } } func (fns CCFuncs) inKey(f pgs.Field, x interface{}) string { switch f.Type().ProtoType() { case pgs.BytesT: return fns.byteStr(x.([]byte)) case pgs.MessageT: switch x := x.(type) { case *durationpb.Duration: return fns.durLit(x) default: return fns.lit(x) } case pgs.EnumT: return fmt.Sprintf("%s(%d)", fns.cType(f.Type()), x.(int32)) default: return fns.lit(x) } } func (fns CCFuncs) durLit(dur *durationpb.Duration) string { return fmt.Sprintf( "pgv::protobuf::util::TimeUtil::SecondsToDuration(%d) + pgv::protobuf::util::TimeUtil::NanosecondsToDuration(%d)", dur.GetSeconds(), dur.GetNanos()) } func (fns CCFuncs) durStr(dur *durationpb.Duration) string { d := dur.AsDuration() return d.String() } func (fns CCFuncs) durGt(a, b *durationpb.Duration) bool { ad := a.AsDuration() bd := b.AsDuration() return ad > bd } func (fns CCFuncs) tsLit(ts *timestamppb.Timestamp) string { return fmt.Sprintf( "time.Unix(%d, %d)", ts.GetSeconds(), ts.GetNanos(), ) } func (fns CCFuncs) tsGt(a, b *timestamppb.Timestamp) bool { at := a.AsTime() bt := b.AsTime() return !bt.Before(at) } func (fns CCFuncs) tsStr(ts *timestamppb.Timestamp) string { t := ts.AsTime() return t.String() } func (fns CCFuncs) unwrap(ctx shared.RuleContext, name string) (shared.RuleContext, error) { ctx, err := ctx.Unwrap("wrapper") if err != nil { return ctx, err } ctx.AccessorOverride = fmt.Sprintf("%s.%s()", name, ctx.Field.Type().Embed().Fields()[0].Name()) return ctx, nil } func (fns CCFuncs) failUnimplemented(message string) string { if len(message) == 0 { return "throw pgv::UnimplementedException();" } return fmt.Sprintf(`throw pgv::UnimplementedException(%q);`, message) } func (fns CCFuncs) staticVarName(msg pgs.Message) string { return "validator_" + strings.Replace(fns.className(msg), ":", "_", -1) } func (fns CCFuncs) output(file pgs.File, ext string) string { return pgs.FilePath(file.Name().String()).SetExt(".pb" + ext).String() } func (fns CCFuncs) Type(f pgs.Field) pgsgo.TypeName { typ := fns.Context.Type(f) if f.Type().IsEnum() { parts := strings.Split(typ.String(), ".") typ = pgsgo.TypeName(parts[len(parts)-1]) } return typ }
apache-2.0
pascalgrimaud/qualitoast
src/main/webapp/app/entities/campagne/campagne.module.ts
1376
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { RouterModule } from '@angular/router'; import { QualiToastSharedModule } from '../../shared'; import { ChartModule } from 'primeng/primeng'; import { CampagneService, CampagnePopupService, CampagneComponent, CampagneDetailComponent, CampagneDialogComponent, CampagnePopupComponent, CampagneDeletePopupComponent, CampagneDeleteDialogComponent, campagneRoute, campagnePopupRoute, CampagneResolvePagingParams, } from './'; const ENTITY_STATES = [ ...campagneRoute, ...campagnePopupRoute, ]; @NgModule({ imports: [ QualiToastSharedModule, ChartModule, RouterModule.forChild(ENTITY_STATES) ], declarations: [ CampagneComponent, CampagneDetailComponent, CampagneDialogComponent, CampagneDeleteDialogComponent, CampagnePopupComponent, CampagneDeletePopupComponent, ], entryComponents: [ CampagneComponent, CampagneDialogComponent, CampagnePopupComponent, CampagneDeleteDialogComponent, CampagneDeletePopupComponent, ], providers: [ CampagneService, CampagnePopupService, CampagneResolvePagingParams, ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class QualiToastCampagneModule {}
apache-2.0
openstack/smaug
karbor/tests/unit/db/test_models.py
35884
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for Models Database.""" from datetime import datetime from datetime import timedelta from oslo_config import cfg from oslo_utils import uuidutils import six import uuid from karbor import context from karbor import db from karbor import exception from karbor.tests import base from oslo_utils import timeutils CONF = cfg.CONF class ModelBaseTestCase(base.TestCase): """Base Test cases which supplies assert Objects equal or not.""" def _dict_from_object(self, obj, ignored_keys): if ignored_keys is None: ignored_keys = [] if isinstance(obj, dict): items = obj.items() else: items = obj.iteritems() return {k: v for k, v in items if k not in ignored_keys} def _assertEqualObjects(self, obj1, obj2, ignored_keys=None): obj1 = self._dict_from_object(obj1, ignored_keys) obj2 = self._dict_from_object(obj2, ignored_keys) self.assertEqual( len(obj1), len(obj2), "Keys mismatch: %s" % six.text_type( set(obj1.keys()) ^ set(obj2.keys()))) for key, value in obj1.items(): self.assertEqual(value, obj2[key]) class ServicesDbTestCase(base.TestCase): """Test cases for Services database table.""" def setUp(self): super(ServicesDbTestCase, self).setUp() self.ctxt = context.RequestContext(user_id='user_id', project_id='project_id', is_admin=True) def test_services_create(self): service_ref = db.service_create(self.ctxt, {'host': 'hosttest', 'binary': 'binarytest', 'topic': 'topictest', 'report_count': 0}) self.assertEqual('hosttest', service_ref['host']) def test_services_get(self): service_ref = db.service_create(self.ctxt, {'host': 'hosttest1', 'binary': 'binarytest1', 'topic': 'topictest1', 'report_count': 0}) service_get_ref = db.service_get(self.ctxt, service_ref['id']) self.assertEqual('hosttest1', service_ref['host']) self.assertEqual('hosttest1', service_get_ref['host']) def test_service_destroy(self): service_ref = db.service_create(self.ctxt, {'host': 'hosttest2', 'binary': 'binarytest2', 'topic': 'topictest2', 'report_count': 0}) service_id = service_ref['id'] db.service_destroy(self.ctxt, service_id) self.assertRaises(exception.ServiceNotFound, db.service_get, self.ctxt, service_id) def test_service_update(self): service_ref = db.service_create(self.ctxt, {'host': 'hosttest3', 'binary': 'binarytest3', 'topic': 'topictest3', 'report_count': 0}) service_id = service_ref['id'] service_update_ref = db.service_update(self.ctxt, service_id, {'host': 'hosttest4', 'binary': 'binarytest4', 'topic': 'topictest4', 'report_count': 0}) self.assertEqual('hosttest3', service_ref['host']) self.assertEqual('hosttest4', service_update_ref['host']) def test_service_get_by_host_and_topic(self): service_ref = db.service_create(self.ctxt, {'host': 'hosttest5', 'binary': 'binarytest5', 'topic': 'topictest5', 'report_count': 0}) service_get_ref = db.service_get_by_host_and_topic(self.ctxt, 'hosttest5', 'topictest5') self.assertEqual('hosttest5', service_ref['host']) self.assertEqual('hosttest5', service_get_ref['host']) class TriggerTestCase(base.TestCase): """Test cases for triggers table.""" def setUp(self): super(TriggerTestCase, self).setUp() self.ctxt = context.RequestContext(user_id='user_id', project_id='project_id') def _create_trigger(self): values = { 'id': "0354ca9ddcd046b693340d78759fd274", 'name': 'first trigger', 'project_id': self.ctxt.tenant, 'type': 'time', 'properties': '{}', } return db.trigger_create(self.ctxt, values) def test_trigger_create(self): trigger_ref = self._create_trigger() self.assertEqual('time', trigger_ref['type']) def test_trigger_delete(self): trigger_ref = self._create_trigger() db.trigger_delete(self.ctxt, trigger_ref['id']) self.assertRaises(exception.TriggerNotFound, db.trigger_delete, self.ctxt, trigger_ref['id']) self.assertRaises(exception.TriggerNotFound, db.trigger_get, self.ctxt, trigger_ref['id']) self.assertRaises(exception.TriggerNotFound, db.trigger_delete, self.ctxt, '100') def test_trigger_update(self): trigger_ref = self._create_trigger() id = trigger_ref['id'] trigger_ref = db.trigger_update(self.ctxt, id, {'type': 'event'}) self.assertEqual('event', trigger_ref['type']) trigger_ref = db.trigger_get(self.ctxt, id) self.assertEqual('event', trigger_ref['type']) self.assertRaises(exception.TriggerNotFound, db.trigger_update, self.ctxt, '100', {"type": "event"}) def test_trigger_get(self): trigger_ref = self._create_trigger() trigger_ref = db.trigger_get(self.ctxt, trigger_ref['id']) self.assertEqual('time', trigger_ref['type']) class ScheduledOperationTestCase(base.TestCase): """Test cases for scheduled_operations table.""" def setUp(self): super(ScheduledOperationTestCase, self).setUp() self.ctxt = context.RequestContext(user_id='user_id', project_id='project_id') def _create_scheduled_operation(self): values = { 'id': '0354ca9ddcd046b693340d78759fd274', 'name': 'protect vm', 'description': 'protect vm resource', 'operation_type': 'protect', 'user_id': self.ctxt.user_id, 'project_id': self.ctxt.tenant, 'trigger_id': '0354ca9ddcd046b693340d78759fd275', 'operation_definition': '{}' } return db.scheduled_operation_create(self.ctxt, values) def test_scheduled_operation_create(self): operation_ref = self._create_scheduled_operation() self.assertEqual('protect', operation_ref['operation_type']) self.assertTrue(operation_ref['enabled']) def test_scheduled_operation_delete(self): operation_ref = self._create_scheduled_operation() db.scheduled_operation_delete(self.ctxt, operation_ref['id']) self.assertRaises(exception.ScheduledOperationNotFound, db.scheduled_operation_delete, self.ctxt, operation_ref['id']) self.assertRaises(exception.ScheduledOperationNotFound, db.scheduled_operation_get, self.ctxt, operation_ref['id']) self.assertRaises(exception.ScheduledOperationNotFound, db.scheduled_operation_delete, self.ctxt, '100') def test_scheduled_operation_update(self): operation_ref = self._create_scheduled_operation() id = operation_ref['id'] operation_ref = db.scheduled_operation_update(self.ctxt, id, {"name": "abc"}) self.assertEqual('abc', operation_ref['name']) operation_ref = db.scheduled_operation_get(self.ctxt, id) self.assertEqual('abc', operation_ref['name']) self.assertRaises(exception.ScheduledOperationNotFound, db.scheduled_operation_update, self.ctxt, '100', {"name": "abc"}) def test_scheduled_operation_get(self): operation_ref = self._create_scheduled_operation() operation_ref = db.scheduled_operation_get(self.ctxt, operation_ref['id']) self.assertEqual('protect', operation_ref['operation_type']) def test_scheduled_operation_get_join_trigger(self): def _create_trigger(): values = { 'id': "0354ca9ddcd046b693340d78759fd275", 'name': 'first trigger', 'project_id': self.ctxt.tenant, 'type': 'time', 'properties': '{}', } return db.trigger_create(self.ctxt, values) trigger_ref = _create_trigger() operation_ref = self._create_scheduled_operation() operation_ref = db.scheduled_operation_get( self.ctxt, operation_ref['id'], ['trigger']) self.assertEqual('protect', operation_ref['operation_type']) self.assertEqual(trigger_ref['type'], operation_ref.trigger['type']) class ScheduledOperationStateTestCase(base.TestCase): """Test cases for scheduled_operation_states table.""" def setUp(self): super(ScheduledOperationStateTestCase, self).setUp() self.ctxt = context.RequestContext(user_id='user_id', project_id='project_id') def _create_scheduled_operation_state(self): values = { 'operation_id': '0354ca9ddcd046b693340d78759fd274', 'service_id': 1, 'trust_id': '123', 'state': 'init', } return db.scheduled_operation_state_create(self.ctxt, values) def test_scheduled_operation_state_create(self): state_ref = self._create_scheduled_operation_state() self.assertEqual('init', state_ref['state']) def test_scheduled_operation_state_delete(self): state_ref = self._create_scheduled_operation_state() db.scheduled_operation_state_delete(self.ctxt, state_ref['operation_id']) self.assertRaises(exception.ScheduledOperationStateNotFound, db.scheduled_operation_state_delete, self.ctxt, state_ref['operation_id']) self.assertRaises(exception.ScheduledOperationStateNotFound, db.scheduled_operation_state_get, self.ctxt, state_ref['operation_id']) self.assertRaises(exception.ScheduledOperationStateNotFound, db.scheduled_operation_state_delete, self.ctxt, 100) def test_scheduled_operation_state_update(self): state_ref = self._create_scheduled_operation_state() operation_id = state_ref['operation_id'] state_ref = db.scheduled_operation_state_update(self.ctxt, operation_id, {"state": "success"}) self.assertEqual('success', state_ref['state']) state_ref = db.scheduled_operation_state_get(self.ctxt, operation_id) self.assertEqual('success', state_ref['state']) self.assertRaises(exception.ScheduledOperationStateNotFound, db.scheduled_operation_state_update, self.ctxt, '100', {"state": "success"}) def test_scheduled_operation_state_get(self): state_ref = self._create_scheduled_operation_state() state_ref = db.scheduled_operation_state_get(self.ctxt, state_ref['operation_id']) self.assertEqual('init', state_ref['state']) def test_scheduled_operation_state_get_join_operation(self): def _create_scheduled_operation(): values = { 'id': '0354ca9ddcd046b693340d78759fd274', 'name': 'protect vm', 'operation_type': 'protect', 'user_id': self.ctxt.user_id, 'project_id': self.ctxt.tenant, 'trigger_id': '0354ca9ddcd046b693340d78759fd275', 'operation_definition': '{}' } return db.scheduled_operation_create(self.ctxt, values) operation_ref = _create_scheduled_operation() self._create_scheduled_operation_state() state_ref = db.scheduled_operation_state_get( self.ctxt, operation_ref['id'], ['operation']) self.assertEqual(operation_ref['id'], state_ref.operation['id']) class ScheduledOperationLogTestCase(base.TestCase): """Test cases for scheduled_operation_logs table.""" def setUp(self): super(ScheduledOperationLogTestCase, self).setUp() self.ctxt = context.get_admin_context() self.operation_id = '0354ca9ddcd046b693340d78759fd274' def _create_scheduled_operation_log(self, state='in_progress', created_at=datetime.now()): values = { 'operation_id': self.operation_id, 'state': state, 'created_at': created_at } return db.scheduled_operation_log_create(self.ctxt, values) def test_scheduled_operation_log_create(self): log_ref = self._create_scheduled_operation_log() self.assertEqual('in_progress', log_ref['state']) def test_scheduled_operation_log_delete(self): log_ref = self._create_scheduled_operation_log() db.scheduled_operation_log_delete(self.ctxt, log_ref['id']) self.assertRaises(exception.ScheduledOperationLogNotFound, db.scheduled_operation_log_delete, self.ctxt, log_ref['id']) self.assertRaises(exception.ScheduledOperationLogNotFound, db.scheduled_operation_log_get, self.ctxt, log_ref['id']) self.assertRaises(exception.ScheduledOperationLogNotFound, db.scheduled_operation_log_delete, self.ctxt, 100) def test_scheduled_operation_log_delete_oldest(self): log_ids = [] states = ['success', 'in_progress', 'success', 'success'] for i in range(4): t = datetime.now() + timedelta(hours=i) log = self._create_scheduled_operation_log( states[i], t) log_ids.append(log['id']) db.scheduled_operation_log_delete_oldest( self.ctxt, self.operation_id, 3) self.assertRaises(exception.ScheduledOperationLogNotFound, db.scheduled_operation_log_get, self.ctxt, log_ids[0]) db.scheduled_operation_log_delete_oldest( self.ctxt, self.operation_id, 1, ['in_progress']) log_ref = db.scheduled_operation_log_get(self.ctxt, log_ids[1]) self.assertEqual('in_progress', log_ref['state']) self.assertRaises(exception.ScheduledOperationLogNotFound, db.scheduled_operation_log_get, self.ctxt, log_ids[2]) def test_scheduled_operation_log_update(self): log_ref = self._create_scheduled_operation_log() log_id = log_ref['id'] log_ref = db.scheduled_operation_log_update(self.ctxt, log_id, {"state": "success"}) self.assertEqual('success', log_ref['state']) log_ref = db.scheduled_operation_log_get(self.ctxt, log_id) self.assertEqual('success', log_ref['state']) self.assertRaises(exception.ScheduledOperationLogNotFound, db.scheduled_operation_log_update, self.ctxt, 100, {"state": "success"}) def test_scheduled_operation_log_get(self): log_ref = self._create_scheduled_operation_log() log_ref = db.scheduled_operation_log_get(self.ctxt, log_ref['id']) self.assertEqual('in_progress', log_ref['state']) class PlanDbTestCase(ModelBaseTestCase): """Unit tests for karbor.db.api.plan_*.""" fake_plan = { 'name': 'My 3 tier application', 'description': 'My 3 tier application protection plan', 'provider_id': 'efc6a88b-9096-4bb6-8634-cda182a6e12a', 'status': 'suspended', 'project_id': '39bb894794b741e982bd26144d2949f6', 'resources': [], 'parameters': '{OS::Nova::Server: {consistency: os}}' } fake_plan_with_resources = { 'name': 'My 3 tier application', 'description': 'My 3 tier application protection plan', 'provider_id': 'efc6a88b-9096-4bb6-8634-cda182a6e12a', 'status': 'suspended', 'project_id': '39bb894794b741e982bd26144d2949f6', 'resources': [{ "id": "64e51e85-4f31-441f-9a5d-6e93e3196628", "type": "OS::Nova::Server", "name": "vm1"}], 'parameters': '{OS::Nova::Server: {consistency: os}}' } def setUp(self): super(PlanDbTestCase, self).setUp() self.ctxt = context.get_admin_context() def test_plan_create(self): plan = db.plan_create(self.ctxt, self.fake_plan) self.assertTrue(uuidutils.is_uuid_like(plan['id'])) self.assertEqual('suspended', plan.status) def test_plan_get(self): plan = db.plan_create(self.ctxt, self.fake_plan) self._assertEqualObjects(plan, db.plan_get(self.ctxt, plan['id']), ignored_keys='resources') def test_plan_destroy(self): plan = db.plan_create(self.ctxt, self.fake_plan) db.plan_destroy(self.ctxt, plan['id']) self.assertRaises(exception.PlanNotFound, db.plan_get, self.ctxt, plan['id']) def test_plan_update(self): plan = db.plan_create(self.ctxt, self.fake_plan) db.plan_update(self.ctxt, plan['id'], {'status': 'started'}) plan = db.plan_get(self.ctxt, plan['id']) self.assertEqual('started', plan['status']) def test_plan_update_nonexistent(self): self.assertRaises(exception.PlanNotFound, db.plan_update, self.ctxt, 42, {}) def test_plan_resources_update(self): resources2 = [{ "id": "61e51e85-4f31-441f-9a5d-6e93e3194444", "type": "OS::Cinder::Volume", "name": "vm2", "extra_info": "{'availability_zone': 'az1'}"}] plan = db.plan_create(self.ctxt, self.fake_plan) db_meta = db.plan_resources_update(self.ctxt, plan["id"], resources2) self.assertEqual("OS::Cinder::Volume", db_meta[0]["resource_type"]) self.assertEqual("vm2", db_meta[0]["resource_name"]) self.assertEqual("{'availability_zone': 'az1'}", db_meta[0]["resource_extra_info"]) class RestoreDbTestCase(ModelBaseTestCase): """Unit tests for karbor.db.api.restore_*.""" fake_restore = { "id": "36ea41b2-c358-48a7-9117-70cb7617410a", "project_id": "586cc6ce-e286-40bd-b2b5-dd32694d9944", "provider_id": "2220f8b1-975d-4621-a872-fa9afb43cb6c", "checkpoint_id": "09edcbdc-d1c2-49c1-a212-122627b20968", "restore_target": "192.168.1.2/identity/", "parameters": "{'username': 'admin'}", "status": "SUCCESS" } def setUp(self): super(RestoreDbTestCase, self).setUp() self.ctxt = context.get_admin_context() def test_restore_create(self): restore = db.restore_create(self.ctxt, self.fake_restore) self.assertTrue(uuidutils.is_uuid_like(restore['id'])) self.assertEqual('SUCCESS', restore.status) def test_restore_get(self): restore = db.restore_create(self.ctxt, self.fake_restore) self._assertEqualObjects(restore, db.restore_get(self.ctxt, restore['id'])) def test_restore_destroy(self): restore = db.restore_create(self.ctxt, self.fake_restore) db.restore_destroy(self.ctxt, restore['id']) self.assertRaises(exception.RestoreNotFound, db.restore_get, self.ctxt, restore['id']) def test_restore_update(self): restore = db.restore_create(self.ctxt, self.fake_restore) db.restore_update(self.ctxt, restore['id'], {'status': 'INIT'}) restore = db.restore_get(self.ctxt, restore['id']) self.assertEqual('INIT', restore['status']) def test_restore_update_nonexistent(self): self.assertRaises(exception.RestoreNotFound, db.restore_update, self.ctxt, 42, {}) class VerificationDbTestCase(ModelBaseTestCase): """Unit tests for karbor.db.api.verification_*.""" fake_verification = { "id": "36ea41b2-c358-48a7-9117-70cb7617410a", "project_id": "586cc6ce-e286-40bd-b2b5-dd32694d9944", "provider_id": "2220f8b1-975d-4621-a872-fa9afb43cb6c", "checkpoint_id": "09edcbdc-d1c2-49c1-a212-122627b20968", "parameters": "{'username': 'admin'}", "status": "SUCCESS" } def setUp(self): super(VerificationDbTestCase, self).setUp() self.ctxt = context.get_admin_context() def test_verification_create(self): verification = db.verification_create(self.ctxt, self.fake_verification) self.assertTrue(uuidutils.is_uuid_like(verification['id'])) self.assertEqual('SUCCESS', verification.status) def test_verification_get(self): verification = db.verification_create(self.ctxt, self.fake_verification) self._assertEqualObjects(verification, db.verification_get( self.ctxt, verification['id'])) def test_verification_destroy(self): verification = db.verification_create(self.ctxt, self.fake_verification) db.verification_destroy(self.ctxt, verification['id']) self.assertRaises(exception.VerificationNotFound, db.verification_get, self.ctxt, verification['id']) def test_verification_update(self): verification = db.verification_create(self.ctxt, self.fake_verification) db.verification_update(self.ctxt, verification['id'], {'status': 'INIT'}) verification = db.verification_get(self.ctxt, verification['id']) self.assertEqual('INIT', verification['status']) def test_verification_update_nonexistent(self): self.assertRaises(exception.VerificationNotFound, db.verification_update, self.ctxt, 42, {}) class OperationLogTestCase(ModelBaseTestCase): """Unit tests for karbor.db.api.operation_log_*.""" fake_operation_log = { "id": "36ea41b2-c358-48a7-9117-70cb7617410a", "project_id": "586cc6ce-e286-40bd-b2b5-dd32694d9944", "operation_type": "protect", "checkpoint_id": "dcb20606-ad71-40a3-80e4-ef0fafdad0c3", "plan_id": "cf56bd3e-97a7-4078-b6d5-f36246333fd9", "provider_id": "23902b02-5666-4ee6-8dfe-962ac09c3994", "scheduled_operation_id": "2220f8b1-975d-4621-a872-fa9afb43cb6c", "status": "failed", "error_info": "Could not access bank", "extra_info": "[entries:{'timestamp': '2015-08-27T09:50:51-05:00'," "'message': 'Doing things'}]" } def setUp(self): super(OperationLogTestCase, self).setUp() self.ctxt = context.get_admin_context() def test_operation_log_create(self): operation_log = db.operation_log_create(self.ctxt, self.fake_operation_log) self.assertTrue(uuidutils.is_uuid_like(operation_log['id'])) self.assertEqual('failed', operation_log.status) def test_operation_log_get(self): operation_log = db.operation_log_create(self.ctxt, self.fake_operation_log) self._assertEqualObjects(operation_log, db.operation_log_get( self.ctxt, operation_log['id'])) def test_operation_log_destroy(self): operation_log = db.operation_log_create(self.ctxt, self.fake_operation_log) db.operation_log_destroy(self.ctxt, operation_log['id']) self.assertRaises(exception.OperationLogNotFound, db.operation_log_get, self.ctxt, operation_log['id']) def test_operation_log_update(self): operation_log = db.operation_log_create(self.ctxt, self.fake_operation_log) db.operation_log_update(self.ctxt, operation_log['id'], {'status': 'finished'}) operation_log = db.operation_log_get(self.ctxt, operation_log['id']) self.assertEqual('finished', operation_log['status']) def test_operation_log_update_nonexistent(self): self.assertRaises(exception.OperationLogNotFound, db.operation_log_update, self.ctxt, 42, {}) class CheckpointRecordTestCase(ModelBaseTestCase): """Unit tests for karbor.db.api.checkpoint_record_*.""" fake_checkpoint_record = { "id": "36ea41b2-c358-48a7-9117-70cb7617410a", "project_id": "586cc6ce-e286-40bd-b2b5-dd32694d9944", "checkpoint_id": "2220f8b1-975d-4621-a872-fa9afb43cb6c", "checkpoint_status": "available", "provider_id": "39bb894794b741e982bd26144d2949f6", "plan_id": "efc6a88b-9096-4bb6-8634-cda182a6e12b", "operation_id": "64e51e85-4f31-441f-9a5d-6e93e3196628", "create_by": "operation-engine", "extend_info": "[{" "'id': '0354ca9d-dcd0-46b6-9334-0d78759fd275'," "'type': 'OS::Nova::Server'," "'name': 'vm1'" "}]" } def setUp(self): super(CheckpointRecordTestCase, self).setUp() self.ctxt = context.get_admin_context() def test_checkpoint_record_create(self): checkpoint_record = db.checkpoint_record_create( self.ctxt, self.fake_checkpoint_record) self.assertTrue(uuidutils.is_uuid_like(checkpoint_record['id'])) self.assertEqual('available', checkpoint_record.checkpoint_status) def test_checkpoint_record_get(self): checkpoint_record = db.checkpoint_record_create( self.ctxt, self.fake_checkpoint_record) self._assertEqualObjects(checkpoint_record, db.checkpoint_record_get( self.ctxt, checkpoint_record['id'])) def test_checkpoint_record_destroy(self): checkpoint_record = db.checkpoint_record_create( self.ctxt, self.fake_checkpoint_record) db.checkpoint_record_destroy(self.ctxt, checkpoint_record['id']) self.assertRaises(exception.CheckpointRecordNotFound, db.checkpoint_record_get, self.ctxt, checkpoint_record['id']) def test_checkpoint_record_update(self): checkpoint_record = db.checkpoint_record_create( self.ctxt, self.fake_checkpoint_record) db.checkpoint_record_update(self.ctxt, checkpoint_record['id'], {'checkpoint_status': 'error'}) checkpoint_record = db.checkpoint_record_get( self.ctxt, checkpoint_record['id']) self.assertEqual('error', checkpoint_record['checkpoint_status']) def test_checkpoint_record_update_nonexistent(self): self.assertRaises(exception.CheckpointRecordNotFound, db.checkpoint_record_update, self.ctxt, 42, {}) class QuotaDbTestCase(ModelBaseTestCase): """Unit tests for karbor.db.api.quota_*.""" def setUp(self): super(QuotaDbTestCase, self).setUp() self.ctxt = context.get_admin_context() self.project_id = "586cc6ce-e286-40bd-b2b5-dd32694d9944" self.resource = "volume_backups" self.limit = 10 def test_quota_create(self): quota = db.quota_create(self.ctxt, self.project_id, self.resource, self.limit) self.assertEqual("volume_backups", quota.resource) db.quota_destroy(self.ctxt, self.project_id, self.resource) def test_quota_get(self): quota = db.quota_create(self.ctxt, self.project_id, self.resource, self.limit) self._assertEqualObjects(quota, db.quota_get( self.ctxt, quota.project_id, quota.resource)) db.quota_destroy(self.ctxt, self.project_id, self.resource) def test_quota_destroy(self): quota = db.quota_create(self.ctxt, self.project_id, self.resource, self.limit) db.quota_destroy(self.ctxt, quota.project_id, quota.resource) self.assertRaises(exception.ProjectQuotaNotFound, db.quota_get, self.ctxt, quota.project_id, quota.resource) def test_quota_update(self): quota = db.quota_create(self.ctxt, self.project_id, self.resource, self.limit) db.quota_update(self.ctxt, quota.project_id, quota.resource, 20) quota = db.quota_get(self.ctxt, self.project_id, self.resource) self.assertEqual(20, quota.hard_limit) class QuotaClassDbTestCase(ModelBaseTestCase): """Unit tests for karbor.db.api.quota_class_*.""" def setUp(self): super(QuotaClassDbTestCase, self).setUp() self.ctxt = context.get_admin_context() self.class_name = "default" self.resource = "volume_backups" self.limit = 10 def test_quota_class_create(self): quota_class = db.quota_class_create(self.ctxt, self.class_name, self.resource, self.limit) self.assertEqual("volume_backups", quota_class.resource) db.quota_class_destroy(self.ctxt, self.class_name, self.resource) def test_quota_class_get(self): quota_class = db.quota_class_create(self.ctxt, self.class_name, self.resource, self.limit) self._assertEqualObjects(quota_class, db.quota_class_get( self.ctxt, quota_class.class_name, quota_class.resource)) db.quota_class_destroy(self.ctxt, self.class_name, self.resource) def test_quota_class_destroy(self): quota_class = db.quota_class_create(self.ctxt, self.class_name, self.resource, self.limit) db.quota_class_destroy(self.ctxt, self.class_name, self.resource) self.assertRaises(exception.QuotaClassNotFound, db.quota_class_get, self.ctxt, quota_class.class_name, quota_class.resource) def test_quota_class_update(self): quota_class = db.quota_class_create(self.ctxt, self.class_name, self.resource, self.limit) db.quota_class_update(self.ctxt, quota_class.class_name, quota_class.resource, 20) quota_class = db.quota_class_get(self.ctxt, self.class_name, self.resource) self.assertEqual(20, quota_class.hard_limit) class QuotaUsageDbTestCase(ModelBaseTestCase): """Unit tests for karbor.db.api.quota_usage_*.""" def setUp(self): super(QuotaUsageDbTestCase, self).setUp() self.ctxt = context.get_admin_context() self.project_id = "586cc6ce-e286-40bd-b2b5-dd32694d9944" self.resource = "volume_backups" self.in_use = 10 self.reserved = 10 self.until_refresh = 0 def test_quota_usage_create(self): quota_usage = db.quota_usage_create( self.ctxt, self.project_id, "volume_backups", self.in_use, self.reserved, self.until_refresh) self.assertEqual("volume_backups", quota_usage.resource) def test_quota_usage_get(self): quota_usage = db.quota_usage_create( self.ctxt, self.project_id, "volume_backups_get", self.in_use, self.reserved, self.until_refresh) self._assertEqualObjects(quota_usage, db.quota_usage_get( self.ctxt, self.project_id, "volume_backups_get")) class ReservationDbTestCase(ModelBaseTestCase): """Unit tests for karbor.db.api.reservation_*.""" def setUp(self): super(ReservationDbTestCase, self).setUp() self.ctxt = context.get_admin_context() self.project_id = "586cc6ce-e286-40bd-b2b5-dd32694d9944" self.resource = "volume_backups" self.in_use = 10 self.reserved = 10 self.until_refresh = 0 def test_reservation_create(self): quota_usage = db.quota_usage_create( self.ctxt, self.project_id, "volume_backups", self.in_use, self.reserved, self.until_refresh) reservation = db.reservation_create( self.ctxt, str(uuid.uuid4()), quota_usage, self.project_id, "volume_backups", 1, timeutils.utcnow()) self.assertEqual("volume_backups", quota_usage.resource) self.assertEqual("volume_backups", reservation.resource) def test_reservation_get(self): quota_usage = db.quota_usage_create( self.ctxt, self.project_id, "volume_backups_get", self.in_use, self.reserved, self.until_refresh) reservation = db.reservation_create( self.ctxt, str(uuid.uuid4()), quota_usage, self.project_id, "volume_backups_get", 1, timeutils.utcnow()) self._assertEqualObjects(reservation, db.reservation_get( self.ctxt, reservation.uuid))
apache-2.0
klmitch/python-keystoneclient
keystoneclient/session.py
41619
# 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 argparse import functools import hashlib import logging import os import socket import time import warnings from debtcollector import removals from oslo_config import cfg from oslo_serialization import jsonutils from oslo_utils import encodeutils from oslo_utils import importutils from oslo_utils import strutils from positional import positional import requests import six from six.moves import urllib from keystoneclient import exceptions from keystoneclient.i18n import _, _LI, _LW osprofiler_web = importutils.try_import("osprofiler.web") USER_AGENT = 'python-keystoneclient' _logger = logging.getLogger(__name__) def _positive_non_zero_float(argument_value): if argument_value is None: return None try: value = float(argument_value) except ValueError: msg = _("%s must be a float") % argument_value raise argparse.ArgumentTypeError(msg) if value <= 0: msg = _("%s must be greater than 0") % argument_value raise argparse.ArgumentTypeError(msg) return value def request(url, method='GET', **kwargs): return Session().request(url, method=method, **kwargs) def _remove_service_catalog(body): try: data = jsonutils.loads(body) # V3 token if 'token' in data and 'catalog' in data['token']: data['token']['catalog'] = '<removed>' return jsonutils.dumps(data) # V2 token if 'serviceCatalog' in data['access']: data['access']['serviceCatalog'] = '<removed>' return jsonutils.dumps(data) except Exception: # Don't fail trying to clean up the request body. pass return body class Session(object): """Maintains client communication state and common functionality. As much as possible the parameters to this class reflect and are passed directly to the requests library. :param auth: An authentication plugin to authenticate the session with. (optional, defaults to None) :type auth: :py:class:`keystoneclient.auth.base.BaseAuthPlugin` :param requests.Session session: A requests session object that can be used for issuing requests. (optional) :param string original_ip: The original IP of the requesting user which will be sent to identity service in a 'Forwarded' header. (optional) :param verify: The verification arguments to pass to requests. These are of the same form as requests expects, so True or False to verify (or not) against system certificates or a path to a bundle or CA certs to check against or None for requests to attempt to locate and use certificates. (optional, defaults to True) :param cert: A client certificate to pass to requests. These are of the same form as requests expects. Either a single filename containing both the certificate and key or a tuple containing the path to the certificate then a path to the key. (optional) :param float timeout: A timeout to pass to requests. This should be a numerical value indicating some amount (or fraction) of seconds or 0 for no timeout. (optional, defaults to 0) :param string user_agent: A User-Agent header string to use for the request. If not provided a default is used. (optional, defaults to 'python-keystoneclient') :param int/bool redirect: Controls the maximum number of redirections that can be followed by a request. Either an integer for a specific count or True/False for forever/never. (optional, default to 30) """ user_agent = None _REDIRECT_STATUSES = (301, 302, 303, 305, 307) REDIRECT_STATUSES = _REDIRECT_STATUSES """This property is deprecated as of the 1.7.0 release and may be removed in the 2.0.0 release.""" _DEFAULT_REDIRECT_LIMIT = 30 DEFAULT_REDIRECT_LIMIT = _DEFAULT_REDIRECT_LIMIT """This property is deprecated as of the 1.7.0 release and may be removed in the 2.0.0 release.""" @positional(2, enforcement=positional.WARN) def __init__(self, auth=None, session=None, original_ip=None, verify=True, cert=None, timeout=None, user_agent=None, redirect=_DEFAULT_REDIRECT_LIMIT): warnings.warn( 'keystoneclient.session.Session is deprecated as of the 2.1.0 ' 'release in favor of keystoneauth1.session.Session. It will be ' 'removed in future releases.', DeprecationWarning) if not session: session = requests.Session() # Use TCPKeepAliveAdapter to fix bug 1323862 for scheme in list(session.adapters): session.mount(scheme, TCPKeepAliveAdapter()) self.auth = auth self.session = session self.original_ip = original_ip self.verify = verify self.cert = cert self.timeout = None self.redirect = redirect if timeout is not None: self.timeout = float(timeout) # don't override the class variable if none provided if user_agent is not None: self.user_agent = user_agent @staticmethod def _process_header(header): """Redacts the secure headers to be logged.""" secure_headers = ('authorization', 'x-auth-token', 'x-subject-token',) if header[0].lower() in secure_headers: token_hasher = hashlib.sha1() token_hasher.update(header[1].encode('utf-8')) token_hash = token_hasher.hexdigest() return (header[0], '{SHA1}%s' % token_hash) return header @positional() def _http_log_request(self, url, method=None, data=None, headers=None, logger=_logger): if not logger.isEnabledFor(logging.DEBUG): # NOTE(morganfainberg): This whole debug section is expensive, # there is no need to do the work if we're not going to emit a # debug log. return string_parts = ['REQ: curl -g -i'] # NOTE(jamielennox): None means let requests do its default validation # so we need to actually check that this is False. if self.verify is False: string_parts.append('--insecure') elif isinstance(self.verify, six.string_types): string_parts.append('--cacert "%s"' % self.verify) if method: string_parts.extend(['-X', method]) string_parts.append(url) if headers: for header in six.iteritems(headers): string_parts.append('-H "%s: %s"' % self._process_header(header)) if data: string_parts.append("-d '%s'" % data) try: logger.debug(' '.join(string_parts)) except UnicodeDecodeError: logger.debug("Replaced characters that could not be decoded" " in log output, original caused UnicodeDecodeError") string_parts = [ encodeutils.safe_decode( part, errors='replace') for part in string_parts] logger.debug(' '.join(string_parts)) def _http_log_response(self, response, logger): if not logger.isEnabledFor(logging.DEBUG): return text = _remove_service_catalog(response.text) string_parts = [ 'RESP:', '[%s]' % response.status_code ] for header in six.iteritems(response.headers): string_parts.append('%s: %s' % self._process_header(header)) if text: string_parts.append('\nRESP BODY: %s\n' % strutils.mask_password(text)) logger.debug(' '.join(string_parts)) @positional(enforcement=positional.WARN) def request(self, url, method, json=None, original_ip=None, user_agent=None, redirect=None, authenticated=None, endpoint_filter=None, auth=None, requests_auth=None, raise_exc=True, allow_reauth=True, log=True, endpoint_override=None, connect_retries=0, logger=_logger, **kwargs): """Send an HTTP request with the specified characteristics. Wrapper around `requests.Session.request` to handle tasks such as setting headers, JSON encoding/decoding, and error handling. Arguments that are not handled are passed through to the requests library. :param string url: Path or fully qualified URL of HTTP request. If only a path is provided then endpoint_filter must also be provided such that the base URL can be determined. If a fully qualified URL is provided then endpoint_filter will be ignored. :param string method: The http method to use. (e.g. 'GET', 'POST') :param string original_ip: Mark this request as forwarded for this ip. (optional) :param dict headers: Headers to be included in the request. (optional) :param json: Some data to be represented as JSON. (optional) :param string user_agent: A user_agent to use for the request. If present will override one present in headers. (optional) :param int/bool redirect: the maximum number of redirections that can be followed by a request. Either an integer for a specific count or True/False for forever/never. (optional) :param int connect_retries: the maximum number of retries that should be attempted for connection errors. (optional, defaults to 0 - never retry). :param bool authenticated: True if a token should be attached to this request, False if not or None for attach if an auth_plugin is available. (optional, defaults to None) :param dict endpoint_filter: Data to be provided to an auth plugin with which it should be able to determine an endpoint to use for this request. If not provided then URL is expected to be a fully qualified URL. (optional) :param str endpoint_override: The URL to use instead of looking up the endpoint in the auth plugin. This will be ignored if a fully qualified URL is provided but take priority over an endpoint_filter. (optional) :param auth: The auth plugin to use when authenticating this request. This will override the plugin that is attached to the session (if any). (optional) :type auth: :py:class:`keystoneclient.auth.base.BaseAuthPlugin` :param requests_auth: A requests library auth plugin that cannot be passed via kwarg because the `auth` kwarg collides with our own auth plugins. (optional) :type requests_auth: :py:class:`requests.auth.AuthBase` :param bool raise_exc: If True then raise an appropriate exception for failed HTTP requests. If False then return the request object. (optional, default True) :param bool allow_reauth: Allow fetching a new token and retrying the request on receiving a 401 Unauthorized response. (optional, default True) :param bool log: If True then log the request and response data to the debug log. (optional, default True) :param logger: The logger object to use to log request and responses. If not provided the keystoneclient.session default logger will be used. :type logger: logging.Logger :param kwargs: any other parameter that can be passed to requests.Session.request (such as `headers`). Except: 'data' will be overwritten by the data in 'json' param. 'allow_redirects' is ignored as redirects are handled by the session. :raises keystoneclient.exceptions.ClientException: For connection failure, or to indicate an error response code. :returns: The response to the request. """ headers = kwargs.setdefault('headers', dict()) if authenticated is None: authenticated = bool(auth or self.auth) if authenticated: auth_headers = self.get_auth_headers(auth) if auth_headers is None: msg = _('No valid authentication is available') raise exceptions.AuthorizationFailure(msg) headers.update(auth_headers) if osprofiler_web: headers.update(osprofiler_web.get_trace_id_headers()) # if we are passed a fully qualified URL and an endpoint_filter we # should ignore the filter. This will make it easier for clients who # want to overrule the default endpoint_filter data added to all client # requests. We check fully qualified here by the presence of a host. if not urllib.parse.urlparse(url).netloc: base_url = None if endpoint_override: base_url = endpoint_override elif endpoint_filter: base_url = self.get_endpoint(auth, **endpoint_filter) if not base_url: service_type = (endpoint_filter or {}).get('service_type', 'unknown') msg = _('Endpoint for %s service') % service_type raise exceptions.EndpointNotFound(msg) url = '%s/%s' % (base_url.rstrip('/'), url.lstrip('/')) if self.cert: kwargs.setdefault('cert', self.cert) if self.timeout is not None: kwargs.setdefault('timeout', self.timeout) if user_agent: headers['User-Agent'] = user_agent elif self.user_agent: user_agent = headers.setdefault('User-Agent', self.user_agent) else: user_agent = headers.setdefault('User-Agent', USER_AGENT) if self.original_ip: headers.setdefault('Forwarded', 'for=%s;by=%s' % (self.original_ip, user_agent)) if json is not None: headers['Content-Type'] = 'application/json' kwargs['data'] = jsonutils.dumps(json) kwargs.setdefault('verify', self.verify) if requests_auth: kwargs['auth'] = requests_auth if log: self._http_log_request(url, method=method, data=kwargs.get('data'), headers=headers, logger=logger) # Force disable requests redirect handling. We will manage this below. kwargs['allow_redirects'] = False if redirect is None: redirect = self.redirect send = functools.partial(self._send_request, url, method, redirect, log, logger, connect_retries) try: connection_params = self.get_auth_connection_params(auth=auth) except exceptions.MissingAuthPlugin: # NOTE(jamielennox): If we've gotten this far without an auth # plugin then we should be happy with allowing no additional # connection params. This will be the typical case for plugins # anyway. pass else: if connection_params: kwargs.update(connection_params) resp = send(**kwargs) # handle getting a 401 Unauthorized response by invalidating the plugin # and then retrying the request. This is only tried once. if resp.status_code == 401 and authenticated and allow_reauth: if self.invalidate(auth): auth_headers = self.get_auth_headers(auth) if auth_headers is not None: headers.update(auth_headers) resp = send(**kwargs) if raise_exc and resp.status_code >= 400: logger.debug('Request returned failure status: %s', resp.status_code) raise exceptions.from_response(resp, method, url) return resp def _send_request(self, url, method, redirect, log, logger, connect_retries, connect_retry_delay=0.5, **kwargs): # NOTE(jamielennox): We handle redirection manually because the # requests lib follows some browser patterns where it will redirect # POSTs as GETs for certain statuses which is not want we want for an # API. See: https://en.wikipedia.org/wiki/Post/Redirect/Get # NOTE(jamielennox): The interaction between retries and redirects are # handled naively. We will attempt only a maximum number of retries and # redirects rather than per request limits. Otherwise the extreme case # could be redirects * retries requests. This will be sufficient in # most cases and can be fixed properly if there's ever a need. try: try: resp = self.session.request(method, url, **kwargs) except requests.exceptions.SSLError as e: msg = _('SSL exception connecting to %(url)s: ' '%(error)s') % {'url': url, 'error': e} raise exceptions.SSLError(msg) except requests.exceptions.Timeout: msg = _('Request to %s timed out') % url raise exceptions.RequestTimeout(msg) except requests.exceptions.ConnectionError: msg = _('Unable to establish connection to %s') % url raise exceptions.ConnectionRefused(msg) except (exceptions.RequestTimeout, exceptions.ConnectionRefused) as e: if connect_retries <= 0: raise logger.info(_LI('Failure: %(e)s. Retrying in %(delay).1fs.'), {'e': e, 'delay': connect_retry_delay}) time.sleep(connect_retry_delay) return self._send_request( url, method, redirect, log, logger, connect_retries=connect_retries - 1, connect_retry_delay=connect_retry_delay * 2, **kwargs) if log: self._http_log_response(resp, logger) if resp.status_code in self._REDIRECT_STATUSES: # be careful here in python True == 1 and False == 0 if isinstance(redirect, bool): redirect_allowed = redirect else: redirect -= 1 redirect_allowed = redirect >= 0 if not redirect_allowed: return resp try: location = resp.headers['location'] except KeyError: logger.warning(_LW("Failed to redirect request to %s as new " "location was not provided."), resp.url) else: # NOTE(jamielennox): We don't pass through connect_retry_delay. # This request actually worked so we can reset the delay count. new_resp = self._send_request( location, method, redirect, log, logger, connect_retries=connect_retries, **kwargs) if not isinstance(new_resp.history, list): new_resp.history = list(new_resp.history) new_resp.history.insert(0, resp) resp = new_resp return resp def head(self, url, **kwargs): """Perform a HEAD request. This calls :py:meth:`.request()` with ``method`` set to ``HEAD``. """ return self.request(url, 'HEAD', **kwargs) def get(self, url, **kwargs): """Perform a GET request. This calls :py:meth:`.request()` with ``method`` set to ``GET``. """ return self.request(url, 'GET', **kwargs) def post(self, url, **kwargs): """Perform a POST request. This calls :py:meth:`.request()` with ``method`` set to ``POST``. """ return self.request(url, 'POST', **kwargs) def put(self, url, **kwargs): """Perform a PUT request. This calls :py:meth:`.request()` with ``method`` set to ``PUT``. """ return self.request(url, 'PUT', **kwargs) def delete(self, url, **kwargs): """Perform a DELETE request. This calls :py:meth:`.request()` with ``method`` set to ``DELETE``. """ return self.request(url, 'DELETE', **kwargs) def patch(self, url, **kwargs): """Perform a PATCH request. This calls :py:meth:`.request()` with ``method`` set to ``PATCH``. """ return self.request(url, 'PATCH', **kwargs) @classmethod def construct(cls, kwargs): """Handles constructing a session from both old and new arguments. Support constructing a session from the old :py:class:`~keystoneclient.httpclient.HTTPClient` args as well as the new request-style arguments. .. warning:: *DEPRECATED as of 1.7.0*: This function is purely for bridging the gap between older client arguments and the session arguments that they relate to. It is not intended to be used as a generic Session Factory. This function may be removed in the 2.0.0 release. This function purposefully modifies the input kwargs dictionary so that the remaining kwargs dict can be reused and passed on to other functions without session arguments. """ warnings.warn( 'Session.construct() is deprecated as of the 1.7.0 release in ' 'favor of using session constructor and may be removed in the ' '2.0.0 release.', DeprecationWarning) return cls._construct(kwargs) @classmethod def _construct(cls, kwargs): params = {} for attr in ('verify', 'cacert', 'cert', 'key', 'insecure', 'timeout', 'session', 'original_ip', 'user_agent'): try: params[attr] = kwargs.pop(attr) except KeyError: pass return cls._make(**params) @classmethod def _make(cls, insecure=False, verify=None, cacert=None, cert=None, key=None, **kwargs): """Create a session with individual certificate parameters. Some parameters used to create a session don't lend themselves to be loaded from config/CLI etc. Create a session by converting those parameters into session __init__ parameters. """ if verify is None: if insecure: verify = False else: verify = cacert or True if cert and key: warnings.warn( 'Passing cert and key together is deprecated as of the 1.7.0 ' 'release in favor of the requests library form of having the ' 'cert and key as a tuple and may be removed in the 2.0.0 ' 'release.', DeprecationWarning) cert = (cert, key) return cls(verify=verify, cert=cert, **kwargs) def _auth_required(self, auth, msg): if not auth: auth = self.auth if not auth: raise exceptions.MissingAuthPlugin(msg) return auth def get_auth_headers(self, auth=None, **kwargs): """Return auth headers as provided by the auth plugin. :param auth: The auth plugin to use for token. Overrides the plugin on the session. (optional) :type auth: :py:class:`keystoneclient.auth.base.BaseAuthPlugin` :raises keystoneclient.exceptions.AuthorizationFailure: if a new token fetch fails. :raises keystoneclient.exceptions.MissingAuthPlugin: if a plugin is not available. :returns: Authentication headers or None for failure. :rtype: dict """ msg = _('An auth plugin is required to fetch a token') auth = self._auth_required(auth, msg) return auth.get_headers(self, **kwargs) @removals.remove(message='Use get_auth_headers instead.', version='1.7.0', removal_version='2.0.0') def get_token(self, auth=None): """Return a token as provided by the auth plugin. :param auth: The auth plugin to use for token. Overrides the plugin on the session. (optional) :type auth: :py:class:`keystoneclient.auth.base.BaseAuthPlugin` :raises keystoneclient.exceptions.AuthorizationFailure: if a new token fetch fails. :raises keystoneclient.exceptions.MissingAuthPlugin: if a plugin is not available. .. warning:: This method is deprecated as of the 1.7.0 release in favor of :meth:`get_auth_headers` and may be removed in the 2.0.0 release. This method assumes that the only header that is used to authenticate a message is 'X-Auth-Token' which may not be correct. :returns: A valid token. :rtype: string """ return (self.get_auth_headers(auth) or {}).get('X-Auth-Token') def get_endpoint(self, auth=None, **kwargs): """Get an endpoint as provided by the auth plugin. :param auth: The auth plugin to use for token. Overrides the plugin on the session. (optional) :type auth: :py:class:`keystoneclient.auth.base.BaseAuthPlugin` :raises keystoneclient.exceptions.MissingAuthPlugin: if a plugin is not available. :returns: An endpoint if available or None. :rtype: string """ msg = _('An auth plugin is required to determine endpoint URL') auth = self._auth_required(auth, msg) return auth.get_endpoint(self, **kwargs) def get_auth_connection_params(self, auth=None, **kwargs): """Return auth connection params as provided by the auth plugin. An auth plugin may specify connection parameters to the request like providing a client certificate for communication. We restrict the values that may be returned from this function to prevent an auth plugin overriding values unrelated to connection parameters. The values that are currently accepted are: - `cert`: a path to a client certificate, or tuple of client certificate and key pair that are used with this request. - `verify`: a boolean value to indicate verifying SSL certificates against the system CAs or a path to a CA file to verify with. These values are passed to the requests library and further information on accepted values may be found there. :param auth: The auth plugin to use for tokens. Overrides the plugin on the session. (optional) :type auth: keystoneclient.auth.base.BaseAuthPlugin :raises keystoneclient.exceptions.AuthorizationFailure: if a new token fetch fails. :raises keystoneclient.exceptions.MissingAuthPlugin: if a plugin is not available. :raises keystoneclient.exceptions.UnsupportedParameters: if the plugin returns a parameter that is not supported by this session. :returns: Authentication headers or None for failure. :rtype: dict """ msg = _('An auth plugin is required to fetch connection params') auth = self._auth_required(auth, msg) params = auth.get_connection_params(self, **kwargs) # NOTE(jamielennox): There needs to be some consensus on what # parameters are allowed to be modified by the auth plugin here. # Ideally I think it would be only the send() parts of the request # flow. For now lets just allow certain elements. params_copy = params.copy() for arg in ('cert', 'verify'): try: kwargs[arg] = params_copy.pop(arg) except KeyError: pass if params_copy: raise exceptions.UnsupportedParameters(list(params_copy)) return params def invalidate(self, auth=None): """Invalidate an authentication plugin. :param auth: The auth plugin to invalidate. Overrides the plugin on the session. (optional) :type auth: :py:class:`keystoneclient.auth.base.BaseAuthPlugin` """ msg = _('An auth plugin is required to validate') auth = self._auth_required(auth, msg) return auth.invalidate() def get_user_id(self, auth=None): """Return the authenticated user_id as provided by the auth plugin. :param auth: The auth plugin to use for token. Overrides the plugin on the session. (optional) :type auth: keystoneclient.auth.base.BaseAuthPlugin :raises keystoneclient.exceptions.AuthorizationFailure: if a new token fetch fails. :raises keystoneclient.exceptions.MissingAuthPlugin: if a plugin is not available. :returns string: Current user_id or None if not supported by plugin. """ msg = _('An auth plugin is required to get user_id') auth = self._auth_required(auth, msg) return auth.get_user_id(self) def get_project_id(self, auth=None): """Return the authenticated project_id as provided by the auth plugin. :param auth: The auth plugin to use for token. Overrides the plugin on the session. (optional) :type auth: keystoneclient.auth.base.BaseAuthPlugin :raises keystoneclient.exceptions.AuthorizationFailure: if a new token fetch fails. :raises keystoneclient.exceptions.MissingAuthPlugin: if a plugin is not available. :returns string: Current project_id or None if not supported by plugin. """ msg = _('An auth plugin is required to get project_id') auth = self._auth_required(auth, msg) return auth.get_project_id(self) @positional.classmethod() def get_conf_options(cls, deprecated_opts=None): """Get oslo_config options that are needed for a :py:class:`.Session`. These may be useful without being registered for config file generation or to manipulate the options before registering them yourself. The options that are set are: :cafile: The certificate authority filename. :certfile: The client certificate file to present. :keyfile: The key for the client certificate. :insecure: Whether to ignore SSL verification. :timeout: The max time to wait for HTTP connections. :param dict deprecated_opts: Deprecated options that should be included in the definition of new options. This should be a dict from the name of the new option to a list of oslo.DeprecatedOpts that correspond to the new option. (optional) For example, to support the ``ca_file`` option pointing to the new ``cafile`` option name:: old_opt = oslo_cfg.DeprecatedOpt('ca_file', 'old_group') deprecated_opts={'cafile': [old_opt]} :returns: A list of oslo_config options. """ if deprecated_opts is None: deprecated_opts = {} return [cfg.StrOpt('cafile', deprecated_opts=deprecated_opts.get('cafile'), help='PEM encoded Certificate Authority to use ' 'when verifying HTTPs connections.'), cfg.StrOpt('certfile', deprecated_opts=deprecated_opts.get('certfile'), help='PEM encoded client certificate cert file'), cfg.StrOpt('keyfile', deprecated_opts=deprecated_opts.get('keyfile'), help='PEM encoded client certificate key file'), cfg.BoolOpt('insecure', default=False, deprecated_opts=deprecated_opts.get('insecure'), help='Verify HTTPS connections.'), cfg.IntOpt('timeout', deprecated_opts=deprecated_opts.get('timeout'), help='Timeout value for http requests'), ] @positional.classmethod() def register_conf_options(cls, conf, group, deprecated_opts=None): """Register the oslo_config options that are needed for a session. The options that are set are: :cafile: The certificate authority filename. :certfile: The client certificate file to present. :keyfile: The key for the client certificate. :insecure: Whether to ignore SSL verification. :timeout: The max time to wait for HTTP connections. :param oslo_config.Cfg conf: config object to register with. :param string group: The ini group to register options in. :param dict deprecated_opts: Deprecated options that should be included in the definition of new options. This should be a dict from the name of the new option to a list of oslo.DeprecatedOpts that correspond to the new option. (optional) For example, to support the ``ca_file`` option pointing to the new ``cafile`` option name:: old_opt = oslo_cfg.DeprecatedOpt('ca_file', 'old_group') deprecated_opts={'cafile': [old_opt]} :returns: The list of options that was registered. """ opts = cls.get_conf_options(deprecated_opts=deprecated_opts) conf.register_group(cfg.OptGroup(group)) conf.register_opts(opts, group=group) return opts @classmethod def load_from_conf_options(cls, conf, group, **kwargs): """Create a session object from an oslo_config object. The options must have been previously registered with register_conf_options. :param oslo_config.Cfg conf: config object to register with. :param string group: The ini group to register options in. :param dict kwargs: Additional parameters to pass to session construction. :returns: A new session object. :rtype: :py:class:`.Session` """ c = conf[group] kwargs['insecure'] = c.insecure kwargs['cacert'] = c.cafile if c.certfile and c.keyfile: kwargs['cert'] = (c.certfile, c.keyfile) kwargs['timeout'] = c.timeout return cls._make(**kwargs) @staticmethod def register_cli_options(parser): """Register the argparse arguments that are needed for a session. :param argparse.ArgumentParser parser: parser to add to. """ parser.add_argument('--insecure', default=False, action='store_true', help='Explicitly allow client to perform ' '"insecure" TLS (https) requests. The ' 'server\'s certificate will not be verified ' 'against any certificate authorities. This ' 'option should be used with caution.') parser.add_argument('--os-cacert', metavar='<ca-certificate>', default=os.environ.get('OS_CACERT'), help='Specify a CA bundle file to use in ' 'verifying a TLS (https) server certificate. ' 'Defaults to env[OS_CACERT].') parser.add_argument('--os-cert', metavar='<certificate>', default=os.environ.get('OS_CERT'), help='Defaults to env[OS_CERT].') parser.add_argument('--os-key', metavar='<key>', default=os.environ.get('OS_KEY'), help='Defaults to env[OS_KEY].') parser.add_argument('--timeout', default=600, type=_positive_non_zero_float, metavar='<seconds>', help='Set request timeout (in seconds).') @classmethod def load_from_cli_options(cls, args, **kwargs): """Create a :py:class:`.Session` object from CLI arguments. The CLI arguments must have been registered with :py:meth:`.register_cli_options`. :param Namespace args: result of parsed arguments. :returns: A new session object. :rtype: :py:class:`.Session` """ kwargs['insecure'] = args.insecure kwargs['cacert'] = args.os_cacert if args.os_cert and args.os_key: kwargs['cert'] = (args.os_cert, args.os_key) kwargs['timeout'] = args.timeout return cls._make(**kwargs) class TCPKeepAliveAdapter(requests.adapters.HTTPAdapter): """The custom adapter used to set TCP Keep-Alive on all connections. This Adapter also preserves the default behaviour of Requests which disables Nagle's Algorithm. See also: http://blogs.msdn.com/b/windowsazurestorage/archive/2010/06/25/nagle-s-algorithm-is-not-friendly-towards-small-requests.aspx """ def init_poolmanager(self, *args, **kwargs): if 'socket_options' not in kwargs: socket_options = [ # Keep Nagle's algorithm off (socket.IPPROTO_TCP, socket.TCP_NODELAY, 1), # Turn on TCP Keep-Alive (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1), ] # Some operating systems (e.g., OSX) do not support setting # keepidle if hasattr(socket, 'TCP_KEEPIDLE'): socket_options += [ # Wait 60 seconds before sending keep-alive probes (socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60) ] # TODO(claudiub): Windows does not contain the TCP_KEEPCNT and # TCP_KEEPINTVL socket attributes. Instead, it contains # SIO_KEEPALIVE_VALS, which can be set via ioctl, which should be # set once it is available in requests. # https://msdn.microsoft.com/en-us/library/dd877220%28VS.85%29.aspx if hasattr(socket, 'TCP_KEEPCNT'): socket_options += [ # Set the maximum number of keep-alive probes (socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 4) ] if hasattr(socket, 'TCP_KEEPINTVL'): socket_options += [ # Send keep-alive probes every 15 seconds (socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 15) ] # After waiting 60 seconds, and then sending a probe once every 15 # seconds 4 times, these options should ensure that a connection # hands for no longer than 2 minutes before a ConnectionError is # raised. kwargs['socket_options'] = socket_options super(TCPKeepAliveAdapter, self).init_poolmanager(*args, **kwargs)
apache-2.0
googleapis/python-pubsub
tests/unit/pubsub_v1/subscriber/test_histogram.py
2378
# Copyright 2017, Google LLC 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. from google.cloud.pubsub_v1.subscriber._protocol import histogram def test_init(): data = {} histo = histogram.Histogram(data=data) assert histo._data is data assert len(histo) == 0 def test_contains(): histo = histogram.Histogram() histo.add(10) histo.add(20) assert 10 in histo assert 20 in histo assert 30 not in histo def test_max(): histo = histogram.Histogram() assert histo.max == histogram.MAX_ACK_DEADLINE histo.add(120) assert histo.max == 120 histo.add(150) assert histo.max == 150 histo.add(20) assert histo.max == 150 def test_min(): histo = histogram.Histogram() assert histo.min == histogram.MIN_ACK_DEADLINE histo.add(60) assert histo.min == 60 histo.add(30) assert histo.min == 30 histo.add(120) assert histo.min == 30 def test_add(): histo = histogram.Histogram() histo.add(60) assert histo._data[60] == 1 histo.add(60) assert histo._data[60] == 2 def test_add_lower_limit(): histo = histogram.Histogram() low_value = histogram.MIN_ACK_DEADLINE - 1 histo.add(low_value) assert low_value not in histo assert histogram.MIN_ACK_DEADLINE in histo def test_add_upper_limit(): histo = histogram.Histogram() high_value = histogram.MAX_ACK_DEADLINE + 1 histo.add(high_value) assert high_value not in histo assert histogram.MAX_ACK_DEADLINE in histo def test_percentile(): histo = histogram.Histogram() assert histo.percentile(42) == histogram.MIN_ACK_DEADLINE # default when empty [histo.add(i) for i in range(101, 201)] assert histo.percentile(100) == 200 assert histo.percentile(101) == 200 assert histo.percentile(99) == 199 assert histo.percentile(1) == 101
apache-2.0
cyr62110/fmrcxx
test/internal/LimitingIteratorTest.cpp
574
#include "../catch.hpp" #include <fmrcxx/Range.h> #include <fmrcxx/internal/LimitingIterator.h> using namespace fmrcxx; using namespace fmrcxx::internal; TEST_CASE( "LimitingIterator doComputeNext", "[LimitingIterator]" ) { Range<int> range1(1, 5); LimitingIterator<int, Range<int>> it(0, std::move(range1)); REQUIRE( it.doComputeNext() == nullptr ); Range<int> range2(1, 5); LimitingIterator<int, Range<int>> it2(2, std::move(range2)); REQUIRE( *(it2.doComputeNext()) == 1 ); REQUIRE( *(it2.doComputeNext()) == 2 ); REQUIRE( it2.doComputeNext() == nullptr ); }
apache-2.0
KarloKnezevic/Ferko
src/java/hr/fer/zemris/util/scheduling/algorithms/GENETIC/DatedTimeSpan.java
1000
package hr.fer.zemris.util.scheduling.algorithms.GENETIC; import hr.fer.zemris.util.time.DateStamp; import hr.fer.zemris.util.time.TimeSpan; public class DatedTimeSpan { private DateStamp date; private TimeSpan span; public DatedTimeSpan(DateStamp date, TimeSpan span) { this.date = date; this.span = span; } public DateStamp getDate() { return this.date; } public TimeSpan getSpan() { return this.span; } @Override public String toString() { return (this.date + " " + this.span); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DatedTimeSpan other = (DatedTimeSpan) obj; if (date == null) { if (other.date != null) return false; } else if (!date.equals(other.date)) return false; if (span == null) { if (other.span != null) return false; } else if (!span.equals(other.span)) return false; return true; } }
apache-2.0
eddremonts86/Drupal-8
Modules/ED_Others/articlestreamprovider/js/artstream_jscritp.js
38
/** * Created by edd on 4/24/17. */
apache-2.0
tzou24/BPS
BPS/src/com/frameworkset/platform/cms/util/GetFileNamesException.java
378
/** 获取指定路径和文件后缀名的文件名列表 Exception Author:GongChunQuan Date:2003.05.16 */ package com.frameworkset.platform.cms.util; public class GetFileNamesException extends FileOperException implements java.io.Serializable { public GetFileNamesException() { super("获取指定路径和文件后缀名的文件名列表.失败."); } }
apache-2.0
chef-cookbooks/ark
spec/fixtures/cookbooks/ark_spec/recipes/dump.rb
279
ark 'test_dump' do url 'https://github.com/sous-chefs/ark/raw/main/files/default/foo.zip' checksum 'deea3a324115c9ca0f3078362f807250080bf1b27516f7eca9d34aad863a11e0' path '/usr/local/foo_dump' creates 'foo1.txt' owner 'foobarbaz' group 'foobarbaz' action :dump end
apache-2.0
simbest/simbest-bps
src/main/java/com/simbest/bps/query/web/MyTaskController.java
7825
package com.simbest.bps.query.web; import com.github.pagehelper.PageInfo; import com.google.common.collect.Maps; import com.simbest.bps.query.model.ActBusinessStatus; import com.simbest.bps.query.service.IActBusinessStatusService; import com.simbest.cores.model.JsonResponse; import com.simbest.cores.shiro.AppUserSession; import com.simbest.cores.utils.configs.CoreConfig; import com.simbest.cores.utils.pages.PageSupport; import com.wordnik.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; import java.util.Map; /** * 查询待办信息 * @author LJW * */ @Controller @RequestMapping(value = {"/action/sso/bps/myTask", "/action/bps/myTask"}) public class MyTaskController { @Autowired protected CoreConfig config; @Autowired private IActBusinessStatusService statusService; @Autowired private AppUserSession appUserSession; /** * 查询我的待办 * * @return * @throws Exception */ @RequestMapping(value = "/queryMyTask", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody @ApiOperation(value = "查询我的待办", httpMethod = "POST", notes = "查询我的待办", produces="application/json",consumes="application/application/x-www-form-urlencoded") public JsonResponse queryMyTask(int pageindex,int pagesize,ActBusinessStatus o) throws Exception { JsonResponse response = new JsonResponse(); response.setResponseid(1); PageSupport<ActBusinessStatus> list = statusService.queryMyTask(appUserSession.getCurrentUser().getUniqueCode(), o,pageindex, pagesize); Map<String, Object> dataMap = wrapQueryResult(list); response.setData(dataMap); return response; } /** * 查询所有流程信息供维护使用 * * @return * @throws Exception */ @RequestMapping(value = "/queryManagerFlow", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody @ApiOperation(value = "查询所有流程信息供维护使用", httpMethod = "POST", notes = "查询所有流程信息供维护使用", produces="application/json",consumes="application/application/x-www-form-urlencoded") public JsonResponse queryManagerFlow(int pageindex,int pagesize,ActBusinessStatus actBusinessStatus) throws Exception { JsonResponse response = new JsonResponse(); response.setResponseid(1); PageSupport<ActBusinessStatus> list = statusService.queryManagerFlow(actBusinessStatus,pageindex, pagesize); Map<String, Object> dataMap = wrapQueryResult(list); response.setData(dataMap); return response; } /** * 查询我的待办总数 * * @return * @throws Exception */ @RequestMapping(value = "/queryMyTaskCount", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody @ApiOperation(value = "查询我的待办总数", httpMethod = "POST", notes = "查询我的待办总数", produces="application/json",consumes="application/application/x-www-form-urlencoded") public JsonResponse queryMyTaskCount() throws Exception { JsonResponse response = new JsonResponse(); response.setResponseid(1); // Integer count = taskApi.queryMyTaskCount(appUserSession.getCurrentUser().getUniqueCode()); // response.setData(count); return response; } /** * 查询我的申请 * * @return * @throws Exception */ @RequestMapping(value = "/queryMyApply", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody @ApiOperation(value = "查询我的申请", httpMethod = "POST", notes = "查询我的申请", produces="application/json",consumes="application/application/x-www-form-urlencoded") public JsonResponse queryMyApply( int pageindex, int pagesize) throws Exception { JsonResponse response = new JsonResponse(); response.setResponseid(1); // PageSupport<ActBusinessStatus> list = taskApi.queryMyApply(appUserSession.getCurrentUser().getUniqueCode(), pageindex, pagesize); // Map<String, Object> dataMap = wrapQueryResult(list); // response.setData(dataMap); return response; } /** * 查询我的草稿 * * @return * @throws Exception */ @RequestMapping(value = "/queryMyDraft", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody @ApiOperation(value = "查询我的草稿", httpMethod = "POST", notes = "查询我的草稿", produces="application/json",consumes="application/application/x-www-form-urlencoded") public JsonResponse queryMyDraft( int pageindex, int pagesize) throws Exception { JsonResponse response = new JsonResponse(); response.setResponseid(1); // PageSupport<ActBusinessStatus> list = taskApi.queryMyDraft(appUserSession.getCurrentUser().getUniqueCode(), pageindex, pagesize); // Map<String, Object> dataMap = wrapQueryResult(list); // response.setData(dataMap); return response; } /** * 查询我的已办 * * @return * @throws Exception */ @RequestMapping(value = "/queryMyJoin", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody @ApiOperation(value = "查询我的已办", httpMethod = "POST", notes = "查询我的已办", produces="application/json",consumes="application/application/x-www-form-urlencoded") public JsonResponse queryMyJoin( int pageindex, int pagesize,ActBusinessStatus o) throws Exception { JsonResponse response = new JsonResponse(); response.setResponseid(1); PageSupport<ActBusinessStatus> list = statusService.queryMyJoin(appUserSession.getCurrentUser().getUniqueCode(), o,pageindex, pagesize); Map<String, Object> dataMap = wrapQueryResult(list); response.setData(dataMap); return response; } /** * 分页使用 * @param list 数据对象 * @return */ protected Map<String, Object> wrapQueryResult(List<?> list) { Map<String, Object> dataMap = Maps.newHashMap(); PageInfo info = new PageInfo(list); if (config.getValue("js.framework").equals("zjs")) { //前端没有传递pageindex和pagesize参数,GenericMapperService和GenericSQLService没有按照分页模式查询,因此info.getList()返回空值 if (info.getList() == null) { dataMap.put("TotalPages", ((int) list.size() / 20) + 1); dataMap.put("TotalRows", list.size()); dataMap.put("Datas", list); } else { dataMap.put("TotalPages", info.getPages()); dataMap.put("TotalRows", info.getTotal()); dataMap.put("Datas", info.getList()); } } return dataMap; } /** * 分页使用 * @param ps 分页数据对象 * @return */ protected Map<String, Object> wrapQueryResult(PageSupport<?> ps) { Map<String, Object> dataMap = Maps.newHashMap(); if (config.getValue("js.framework").equals("zjs")) { dataMap.put("TotalPages", ps.getTotalPages()); dataMap.put("TotalRows", ps.getTotalRecords()); dataMap.put("Datas", ps.getItems()); } return dataMap; } }
apache-2.0
pacozaa/BoofCV
main/ip/src/boofcv/alg/filter/convolve/border/ConvolveJustBorder_General.java
13702
/* * Copyright (c) 2011-2015, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.alg.filter.convolve.border; import boofcv.core.image.border.ImageBorder_F32; import boofcv.core.image.border.ImageBorder_S32; import boofcv.struct.convolve.Kernel1D_F32; import boofcv.struct.convolve.Kernel1D_I32; import boofcv.struct.convolve.Kernel2D_F32; import boofcv.struct.convolve.Kernel2D_I32; import boofcv.struct.image.ImageFloat32; import boofcv.struct.image.ImageInt16; import boofcv.struct.image.ImageSInt32; /** * <p> * Convolves just the image's border. How the border condition is handled is specified by the {@link boofcv.core.image.border.ImageBorder} * passed in. For 1D kernels only the horizontal or vertical borders are processed. * </p> * * <p> * WARNING: Do not modify. Automatically generated by {@link GenerateConvolveJustBorder_General}. * </p> * * @author Peter Abeles */ public class ConvolveJustBorder_General { public static void horizontal(Kernel1D_F32 kernel, ImageBorder_F32 input, ImageFloat32 output ) { final float[] dataDst = output.data; final float[] dataKer = kernel.data; final int offset = kernel.getOffset(); final int kernelWidth = kernel.getWidth(); final int width = output.getWidth(); final int height = output.getHeight(); final int borderRight = kernelWidth-offset-1; for (int y = 0; y < height; y++) { int indexDest = output.startIndex + y * output.stride; for ( int x = 0; x < offset; x++ ) { float total = 0; for (int k = 0; k < kernelWidth; k++) { total += input.get(x+k-offset,y) * dataKer[k]; } dataDst[indexDest++] = total; } indexDest = output.startIndex + y * output.stride + width-borderRight; for ( int x = width-borderRight; x < width; x++ ) { float total = 0; for (int k = 0; k < kernelWidth; k++) { total += input.get(x+k-offset,y) * dataKer[k]; } dataDst[indexDest++] = total; } } } public static void vertical(Kernel1D_F32 kernel, ImageBorder_F32 input, ImageFloat32 output ) { final float[] dataDst = output.data; final float[] dataKer = kernel.data; final int offset = kernel.getOffset(); final int kernelWidth = kernel.getWidth(); final int width = output.getWidth(); final int height = output.getHeight(); final int borderBottom = kernelWidth-offset-1; for ( int x = 0; x < width; x++ ) { int indexDest = output.startIndex + x; for (int y = 0; y < offset; y++, indexDest += output.stride) { float total = 0; for (int k = 0; k < kernelWidth; k++) { total += input.get(x,y+k-offset) * dataKer[k]; } dataDst[indexDest] = total; } indexDest = output.startIndex + (height-borderBottom) * output.stride + x; for (int y = height-borderBottom; y < height; y++, indexDest += output.stride) { float total = 0; for (int k = 0; k < kernelWidth; k++ ) { total += input.get(x,y+k-offset) * dataKer[k]; } dataDst[indexDest] = total; } } } public static void convolve(Kernel2D_F32 kernel, ImageBorder_F32 input, ImageFloat32 output ) { final float[] dataDst = output.data; final float[] dataKer = kernel.data; final int offsetL = kernel.getOffset(); final int offsetR = kernel.getWidth()-offsetL-1; final int width = output.getWidth(); final int height = output.getHeight(); // convolve along the left and right borders for (int y = 0; y < height; y++) { int indexDest = output.startIndex + y * output.stride; for ( int x = 0; x < offsetL; x++ ) { float total = 0; int indexKer = 0; for( int i = -offsetL; i <= offsetR; i++ ) { for (int j = -offsetL; j <= offsetR; j++) { total += input.get(x+j,y+i) * dataKer[indexKer++]; } } dataDst[indexDest++] = total; } indexDest = output.startIndex + y * output.stride + width-offsetR; for ( int x = width-offsetR; x < width; x++ ) { float total = 0; int indexKer = 0; for( int i = -offsetL; i <= offsetR; i++ ) { for (int j = -offsetL; j <= offsetR; j++) { total += input.get(x+j,y+i) * dataKer[indexKer++]; } } dataDst[indexDest++] = total; } } // convolve along the top and bottom borders for ( int x = offsetL; x < width-offsetR; x++ ) { int indexDest = output.startIndex + x; for (int y = 0; y < offsetL; y++, indexDest += output.stride) { float total = 0; int indexKer = 0; for( int i = -offsetL; i <= offsetR; i++ ) { for (int j = -offsetL; j <= offsetR; j++) { total += input.get(x+j,y+i) * dataKer[indexKer++]; } } dataDst[indexDest] = total; } indexDest = output.startIndex + (height-offsetR) * output.stride + x; for (int y = height-offsetR; y < height; y++, indexDest += output.stride) { float total = 0; int indexKer = 0; for( int i = -offsetL; i <= offsetR; i++ ) { for (int j = -offsetL; j <= offsetR; j++) { total += input.get(x+j,y+i) * dataKer[indexKer++]; } } dataDst[indexDest] = total; } } } public static void horizontal(Kernel1D_I32 kernel, ImageBorder_S32 input, ImageInt16 output ) { final short[] dataDst = output.data; final int[] dataKer = kernel.data; final int offset = kernel.getOffset(); final int kernelWidth = kernel.getWidth(); final int width = output.getWidth(); final int height = output.getHeight(); final int borderRight = kernelWidth-offset-1; for (int y = 0; y < height; y++) { int indexDest = output.startIndex + y * output.stride; for ( int x = 0; x < offset; x++ ) { int total = 0; for (int k = 0; k < kernelWidth; k++) { total += input.get(x+k-offset,y) * dataKer[k]; } dataDst[indexDest++] = (short)total; } indexDest = output.startIndex + y * output.stride + width-borderRight; for ( int x = width-borderRight; x < width; x++ ) { int total = 0; for (int k = 0; k < kernelWidth; k++) { total += input.get(x+k-offset,y) * dataKer[k]; } dataDst[indexDest++] = (short)total; } } } public static void vertical(Kernel1D_I32 kernel, ImageBorder_S32 input, ImageInt16 output ) { final short[] dataDst = output.data; final int[] dataKer = kernel.data; final int offset = kernel.getOffset(); final int kernelWidth = kernel.getWidth(); final int width = output.getWidth(); final int height = output.getHeight(); final int borderBottom = kernelWidth-offset-1; for ( int x = 0; x < width; x++ ) { int indexDest = output.startIndex + x; for (int y = 0; y < offset; y++, indexDest += output.stride) { int total = 0; for (int k = 0; k < kernelWidth; k++) { total += input.get(x,y+k-offset) * dataKer[k]; } dataDst[indexDest] = (short)total; } indexDest = output.startIndex + (height-borderBottom) * output.stride + x; for (int y = height-borderBottom; y < height; y++, indexDest += output.stride) { int total = 0; for (int k = 0; k < kernelWidth; k++ ) { total += input.get(x,y+k-offset) * dataKer[k]; } dataDst[indexDest] = (short)total; } } } public static void convolve(Kernel2D_I32 kernel, ImageBorder_S32 input, ImageInt16 output ) { final short[] dataDst = output.data; final int[] dataKer = kernel.data; final int offsetL = kernel.getOffset(); final int offsetR = kernel.getWidth()-offsetL-1; final int width = output.getWidth(); final int height = output.getHeight(); // convolve along the left and right borders for (int y = 0; y < height; y++) { int indexDest = output.startIndex + y * output.stride; for ( int x = 0; x < offsetL; x++ ) { int total = 0; int indexKer = 0; for( int i = -offsetL; i <= offsetR; i++ ) { for (int j = -offsetL; j <= offsetR; j++) { total += input.get(x+j,y+i) * dataKer[indexKer++]; } } dataDst[indexDest++] = (short)total; } indexDest = output.startIndex + y * output.stride + width-offsetR; for ( int x = width-offsetR; x < width; x++ ) { int total = 0; int indexKer = 0; for( int i = -offsetL; i <= offsetR; i++ ) { for (int j = -offsetL; j <= offsetR; j++) { total += input.get(x+j,y+i) * dataKer[indexKer++]; } } dataDst[indexDest++] = (short)total; } } // convolve along the top and bottom borders for ( int x = offsetL; x < width-offsetR; x++ ) { int indexDest = output.startIndex + x; for (int y = 0; y < offsetL; y++, indexDest += output.stride) { int total = 0; int indexKer = 0; for( int i = -offsetL; i <= offsetR; i++ ) { for (int j = -offsetL; j <= offsetR; j++) { total += input.get(x+j,y+i) * dataKer[indexKer++]; } } dataDst[indexDest] = (short)total; } indexDest = output.startIndex + (height-offsetR) * output.stride + x; for (int y = height-offsetR; y < height; y++, indexDest += output.stride) { int total = 0; int indexKer = 0; for( int i = -offsetL; i <= offsetR; i++ ) { for (int j = -offsetL; j <= offsetR; j++) { total += input.get(x+j,y+i) * dataKer[indexKer++]; } } dataDst[indexDest] = (short)total; } } } public static void horizontal(Kernel1D_I32 kernel, ImageBorder_S32 input, ImageSInt32 output ) { final int[] dataDst = output.data; final int[] dataKer = kernel.data; final int offset = kernel.getOffset(); final int kernelWidth = kernel.getWidth(); final int width = output.getWidth(); final int height = output.getHeight(); final int borderRight = kernelWidth-offset-1; for (int y = 0; y < height; y++) { int indexDest = output.startIndex + y * output.stride; for ( int x = 0; x < offset; x++ ) { int total = 0; for (int k = 0; k < kernelWidth; k++) { total += input.get(x+k-offset,y) * dataKer[k]; } dataDst[indexDest++] = total; } indexDest = output.startIndex + y * output.stride + width-borderRight; for ( int x = width-borderRight; x < width; x++ ) { int total = 0; for (int k = 0; k < kernelWidth; k++) { total += input.get(x+k-offset,y) * dataKer[k]; } dataDst[indexDest++] = total; } } } public static void vertical(Kernel1D_I32 kernel, ImageBorder_S32 input, ImageSInt32 output ) { final int[] dataDst = output.data; final int[] dataKer = kernel.data; final int offset = kernel.getOffset(); final int kernelWidth = kernel.getWidth(); final int width = output.getWidth(); final int height = output.getHeight(); final int borderBottom = kernelWidth-offset-1; for ( int x = 0; x < width; x++ ) { int indexDest = output.startIndex + x; for (int y = 0; y < offset; y++, indexDest += output.stride) { int total = 0; for (int k = 0; k < kernelWidth; k++) { total += input.get(x,y+k-offset) * dataKer[k]; } dataDst[indexDest] = total; } indexDest = output.startIndex + (height-borderBottom) * output.stride + x; for (int y = height-borderBottom; y < height; y++, indexDest += output.stride) { int total = 0; for (int k = 0; k < kernelWidth; k++ ) { total += input.get(x,y+k-offset) * dataKer[k]; } dataDst[indexDest] = total; } } } public static void convolve(Kernel2D_I32 kernel, ImageBorder_S32 input, ImageSInt32 output ) { final int[] dataDst = output.data; final int[] dataKer = kernel.data; final int offsetL = kernel.getOffset(); final int offsetR = kernel.getWidth()-offsetL-1; final int width = output.getWidth(); final int height = output.getHeight(); // convolve along the left and right borders for (int y = 0; y < height; y++) { int indexDest = output.startIndex + y * output.stride; for ( int x = 0; x < offsetL; x++ ) { int total = 0; int indexKer = 0; for( int i = -offsetL; i <= offsetR; i++ ) { for (int j = -offsetL; j <= offsetR; j++) { total += input.get(x+j,y+i) * dataKer[indexKer++]; } } dataDst[indexDest++] = total; } indexDest = output.startIndex + y * output.stride + width-offsetR; for ( int x = width-offsetR; x < width; x++ ) { int total = 0; int indexKer = 0; for( int i = -offsetL; i <= offsetR; i++ ) { for (int j = -offsetL; j <= offsetR; j++) { total += input.get(x+j,y+i) * dataKer[indexKer++]; } } dataDst[indexDest++] = total; } } // convolve along the top and bottom borders for ( int x = offsetL; x < width-offsetR; x++ ) { int indexDest = output.startIndex + x; for (int y = 0; y < offsetL; y++, indexDest += output.stride) { int total = 0; int indexKer = 0; for( int i = -offsetL; i <= offsetR; i++ ) { for (int j = -offsetL; j <= offsetR; j++) { total += input.get(x+j,y+i) * dataKer[indexKer++]; } } dataDst[indexDest] = total; } indexDest = output.startIndex + (height-offsetR) * output.stride + x; for (int y = height-offsetR; y < height; y++, indexDest += output.stride) { int total = 0; int indexKer = 0; for( int i = -offsetL; i <= offsetR; i++ ) { for (int j = -offsetL; j <= offsetR; j++) { total += input.get(x+j,y+i) * dataKer[indexKer++]; } } dataDst[indexDest] = total; } } } }
apache-2.0
dushougudu/CraneAlert
CraneAlert/CraneAlert/manage/AddMonitor.aspx.designer.cs
12224
//------------------------------------------------------------------------------ // <自动生成> // 此代码由工具生成。 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </自动生成> //------------------------------------------------------------------------------ namespace CraneAlert.manage { public partial class AddMonitor { /// <summary> /// form1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// IdDevice 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox IdDevice; /// <summary> /// Id_customized 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox Id_customized; /// <summary> /// Factory 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox Factory; /// <summary> /// StandardNo 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox StandardNo; /// <summary> /// OutDate 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox OutDate; /// <summary> /// OutSerial 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox OutSerial; /// <summary> /// DevType 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.DropDownList DevType; /// <summary> /// RegSerial 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox RegSerial; /// <summary> /// WorkAreaNo 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.DropDownList WorkAreaNo; /// <summary> /// Id_prj_no 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox Id_prj_no; /// <summary> /// DoneUnitName 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox DoneUnitName; /// <summary> /// InchargePerson 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox InchargePerson; /// <summary> /// Telephone 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox Telephone; /// <summary> /// UnitNo 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.DropDownList UnitNo; /// <summary> /// memo 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox memo; /// <summary> /// Online 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.DropDownList Online; /// <summary> /// px 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox px; /// <summary> /// py 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox py; /// <summary> /// BodyHeight 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox BodyHeight; /// <summary> /// HeadHeight 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox HeadHeight; /// <summary> /// LoadArmLength 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox LoadArmLength; /// <summary> /// BalanceArmLength 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox BalanceArmLength; /// <summary> /// LoadRopeLength 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox LoadRopeLength; /// <summary> /// MaxWeight 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox MaxWeight; /// <summary> /// MaxWindSpeed 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox MaxWindSpeed; /// <summary> /// Liju 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox Liju; /// <summary> /// Angle 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox Angle; /// <summary> /// Radius 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox Radius; /// <summary> /// HasAlertDevice 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.DropDownList HasAlertDevice; /// <summary> /// AlertDeviceIP 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox AlertDeviceIP; /// <summary> /// CommInterval 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox CommInterval; /// <summary> /// ParaMemo 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox ParaMemo; /// <summary> /// Button1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Button Button1; } }
apache-2.0
amischler/JRebirth
org.jrebirth/archetype/src/main/resources/archetype-resources/src/main/java/command/SampleCommand.java
1096
#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}.command; import org.jrebirth.core.command.DefaultCommand; import org.jrebirth.core.exception.CoreException; import org.jrebirth.core.wave.Wave; import org.jrebirth.sample.command.SampleCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The class <strong>SampleCommand</strong> used to process short action into the JRebirth Internal Thread. * * @author */ public final class SampleCommand extends DefaultCommand { /** The class logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(SampleCommand.class); /** * {@inheritDoc} */ @Override public void ready() throws CoreException { // You must put your initialization code here (if any) } /** * {@inheritDoc} */ @Override protected void execute(final Wave wave) { LOGGER.info("Perform a short action JIT"); LOGGER.info("Be careful it locks wave processing"); } }
apache-2.0
ROKIRA/TENDERS
app/config/app.php
7584
<?php return array( /* |-------------------------------------------------------------------------- | Application Debug Mode |-------------------------------------------------------------------------- | | When your application is in debug mode, detailed error messages with | stack traces will be shown on every error that occurs within your | application. If disabled, a simple generic error page is shown. | */ 'debug' => true, /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => 'http://localhost', /* |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'UTC', /* |-------------------------------------------------------------------------- | Application Locale Configuration |-------------------------------------------------------------------------- | | The application locale determines the default locale that will be used | by the translation service provider. You are free to set this value | to any of the locales which will be supported by the application. | */ 'locale' => 'en', /* |-------------------------------------------------------------------------- | Application Fallback Locale |-------------------------------------------------------------------------- | | The fallback locale determines the locale to use when the current one | is not available. You may change the value to correspond to any of | the language folders that are provided through your application. | */ 'fallback_locale' => 'en', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | */ 'key' => 'gUltvHVBOyYWOIxUCqDqxV8sz5BRZhx0', 'cipher' => MCRYPT_RIJNDAEL_128, /* |-------------------------------------------------------------------------- | Autoloaded Service Providers |-------------------------------------------------------------------------- | | The service providers listed here will be automatically loaded on the | request to your application. Feel free to add your own services to | this array to grant expanded functionality to your applications. | */ 'providers' => array( 'Illuminate\Foundation\Providers\ArtisanServiceProvider', 'Illuminate\Auth\AuthServiceProvider', 'Illuminate\Cache\CacheServiceProvider', 'Illuminate\Session\CommandsServiceProvider', 'Illuminate\Foundation\Providers\ConsoleSupportServiceProvider', 'Illuminate\Routing\ControllerServiceProvider', 'Illuminate\Cookie\CookieServiceProvider', 'Illuminate\Database\DatabaseServiceProvider', 'Illuminate\Encryption\EncryptionServiceProvider', 'Illuminate\Filesystem\FilesystemServiceProvider', 'Illuminate\Hashing\HashServiceProvider', 'Illuminate\Html\HtmlServiceProvider', 'Illuminate\Log\LogServiceProvider', 'Illuminate\Mail\MailServiceProvider', 'Illuminate\Database\MigrationServiceProvider', 'Illuminate\Pagination\PaginationServiceProvider', 'Illuminate\Queue\QueueServiceProvider', 'Illuminate\Redis\RedisServiceProvider', 'Illuminate\Remote\RemoteServiceProvider', 'Illuminate\Auth\Reminders\ReminderServiceProvider', 'Illuminate\Database\SeedServiceProvider', 'Illuminate\Session\SessionServiceProvider', 'Illuminate\Translation\TranslationServiceProvider', 'Illuminate\Validation\ValidationServiceProvider', 'Illuminate\View\ViewServiceProvider', 'Illuminate\Workbench\WorkbenchServiceProvider', 'Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider', 'Barryvdh\Debugbar\ServiceProvider', ), /* |-------------------------------------------------------------------------- | Service Provider Manifest |-------------------------------------------------------------------------- | | The service provider manifest is used by Laravel to lazy load service | providers which are not needed for each request, as well to keep a | list of all of the services. Here, you may set its storage spot. | */ 'manifest' => storage_path().'/meta', /* |-------------------------------------------------------------------------- | Class Aliases |-------------------------------------------------------------------------- | | This array of class aliases will be registered when this application | is started. However, feel free to register as many as you wish as | the aliases are "lazy" loaded so they don't hinder performance. | */ 'aliases' => array( 'App' => 'Illuminate\Support\Facades\App', 'Artisan' => 'Illuminate\Support\Facades\Artisan', 'Auth' => 'Illuminate\Support\Facades\Auth', 'Blade' => 'Illuminate\Support\Facades\Blade', 'Cache' => 'Illuminate\Support\Facades\Cache', 'ClassLoader' => 'Illuminate\Support\ClassLoader', 'Config' => 'Illuminate\Support\Facades\Config', 'Controller' => 'Illuminate\Routing\Controller', 'Cookie' => 'Illuminate\Support\Facades\Cookie', 'Crypt' => 'Illuminate\Support\Facades\Crypt', 'DB' => 'Illuminate\Support\Facades\DB', 'Eloquent' => 'Illuminate\Database\Eloquent\Model', 'Event' => 'Illuminate\Support\Facades\Event', 'File' => 'Illuminate\Support\Facades\File', 'Form' => 'Illuminate\Support\Facades\Form', 'Hash' => 'Illuminate\Support\Facades\Hash', 'HTML' => 'Illuminate\Support\Facades\HTML', 'Input' => 'Illuminate\Support\Facades\Input', 'Lang' => 'Illuminate\Support\Facades\Lang', 'Log' => 'Illuminate\Support\Facades\Log', 'Mail' => 'Illuminate\Support\Facades\Mail', 'Paginator' => 'Illuminate\Support\Facades\Paginator', 'Password' => 'Illuminate\Support\Facades\Password', 'Queue' => 'Illuminate\Support\Facades\Queue', 'Redirect' => 'Illuminate\Support\Facades\Redirect', 'Redis' => 'Illuminate\Support\Facades\Redis', 'Request' => 'Illuminate\Support\Facades\Request', 'Response' => 'Illuminate\Support\Facades\Response', 'Route' => 'Illuminate\Support\Facades\Route', 'Schema' => 'Illuminate\Support\Facades\Schema', 'Seeder' => 'Illuminate\Database\Seeder', 'Session' => 'Illuminate\Support\Facades\Session', 'SoftDeletingTrait' => 'Illuminate\Database\Eloquent\SoftDeletingTrait', 'SSH' => 'Illuminate\Support\Facades\SSH', 'Str' => 'Illuminate\Support\Str', 'URL' => 'Illuminate\Support\Facades\URL', 'Validator' => 'Illuminate\Support\Facades\Validator', 'View' => 'Illuminate\Support\Facades\View', ), );
apache-2.0
bulldog2011/luxun
src/main/java/com/leansoft/luxun/api/generated/ProduceRequest.java
15559
/** * Autogenerated by Thrift Compiler (0.9.3) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package com.leansoft.luxun.api.generated; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import javax.annotation.Generated; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"}) @Generated(value = "Autogenerated by Thrift Compiler (0.9.3)", date = "2016-09-24") public class ProduceRequest implements org.apache.thrift.TBase<ProduceRequest, ProduceRequest._Fields>, java.io.Serializable, Cloneable, Comparable<ProduceRequest> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ProduceRequest"); private static final org.apache.thrift.protocol.TField ITEM_FIELD_DESC = new org.apache.thrift.protocol.TField("item", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField TOPIC_FIELD_DESC = new org.apache.thrift.protocol.TField("topic", org.apache.thrift.protocol.TType.STRING, (short)2); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new ProduceRequestStandardSchemeFactory()); schemes.put(TupleScheme.class, new ProduceRequestTupleSchemeFactory()); } private ByteBuffer item; // required private String topic; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ITEM((short)1, "item"), TOPIC((short)2, "topic"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // ITEM return ITEM; case 2: // TOPIC return TOPIC; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ITEM, new org.apache.thrift.meta_data.FieldMetaData("item", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true))); tmpMap.put(_Fields.TOPIC, new org.apache.thrift.meta_data.FieldMetaData("topic", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ProduceRequest.class, metaDataMap); } public ProduceRequest() { } public ProduceRequest( ByteBuffer item, String topic) { this(); this.item = org.apache.thrift.TBaseHelper.copyBinary(item); this.topic = topic; } /** * Performs a deep copy on <i>other</i>. */ public ProduceRequest(ProduceRequest other) { if (other.isSetItem()) { this.item = org.apache.thrift.TBaseHelper.copyBinary(other.item); } if (other.isSetTopic()) { this.topic = other.topic; } } public ProduceRequest deepCopy() { return new ProduceRequest(this); } @Override public void clear() { this.item = null; this.topic = null; } public byte[] getItem() { setItem(org.apache.thrift.TBaseHelper.rightSize(item)); return item == null ? null : item.array(); } public ByteBuffer bufferForItem() { return org.apache.thrift.TBaseHelper.copyBinary(item); } public void setItem(byte[] item) { this.item = item == null ? (ByteBuffer)null : ByteBuffer.wrap(Arrays.copyOf(item, item.length)); } public void setItem(ByteBuffer item) { this.item = org.apache.thrift.TBaseHelper.copyBinary(item); } public void unsetItem() { this.item = null; } /** Returns true if field item is set (has been assigned a value) and false otherwise */ public boolean isSetItem() { return this.item != null; } public void setItemIsSet(boolean value) { if (!value) { this.item = null; } } public String getTopic() { return this.topic; } public void setTopic(String topic) { this.topic = topic; } public void unsetTopic() { this.topic = null; } /** Returns true if field topic is set (has been assigned a value) and false otherwise */ public boolean isSetTopic() { return this.topic != null; } public void setTopicIsSet(boolean value) { if (!value) { this.topic = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case ITEM: if (value == null) { unsetItem(); } else { setItem((ByteBuffer)value); } break; case TOPIC: if (value == null) { unsetTopic(); } else { setTopic((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case ITEM: return getItem(); case TOPIC: return getTopic(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case ITEM: return isSetItem(); case TOPIC: return isSetTopic(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof ProduceRequest) return this.equals((ProduceRequest)that); return false; } public boolean equals(ProduceRequest that) { if (that == null) return false; boolean this_present_item = true && this.isSetItem(); boolean that_present_item = true && that.isSetItem(); if (this_present_item || that_present_item) { if (!(this_present_item && that_present_item)) return false; if (!this.item.equals(that.item)) return false; } boolean this_present_topic = true && this.isSetTopic(); boolean that_present_topic = true && that.isSetTopic(); if (this_present_topic || that_present_topic) { if (!(this_present_topic && that_present_topic)) return false; if (!this.topic.equals(that.topic)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_item = true && (isSetItem()); list.add(present_item); if (present_item) list.add(item); boolean present_topic = true && (isSetTopic()); list.add(present_topic); if (present_topic) list.add(topic); return list.hashCode(); } @Override public int compareTo(ProduceRequest other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetItem()).compareTo(other.isSetItem()); if (lastComparison != 0) { return lastComparison; } if (isSetItem()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.item, other.item); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetTopic()).compareTo(other.isSetTopic()); if (lastComparison != 0) { return lastComparison; } if (isSetTopic()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.topic, other.topic); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("ProduceRequest("); boolean first = true; sb.append("item:"); if (this.item == null) { sb.append("null"); } else { org.apache.thrift.TBaseHelper.toString(this.item, sb); } first = false; if (!first) sb.append(", "); sb.append("topic:"); if (this.topic == null) { sb.append("null"); } else { sb.append(this.topic); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields if (!isSetItem()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'item' is unset! Struct:" + toString()); } if (!isSetTopic()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'topic' is unset! Struct:" + toString()); } // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class ProduceRequestStandardSchemeFactory implements SchemeFactory { public ProduceRequestStandardScheme getScheme() { return new ProduceRequestStandardScheme(); } } private static class ProduceRequestStandardScheme extends StandardScheme<ProduceRequest> { public void read(org.apache.thrift.protocol.TProtocol iprot, ProduceRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // ITEM if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.item = iprot.readBinary(); struct.setItemIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TOPIC if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.topic = iprot.readString(); struct.setTopicIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, ProduceRequest struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.item != null) { oprot.writeFieldBegin(ITEM_FIELD_DESC); oprot.writeBinary(struct.item); oprot.writeFieldEnd(); } if (struct.topic != null) { oprot.writeFieldBegin(TOPIC_FIELD_DESC); oprot.writeString(struct.topic); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class ProduceRequestTupleSchemeFactory implements SchemeFactory { public ProduceRequestTupleScheme getScheme() { return new ProduceRequestTupleScheme(); } } private static class ProduceRequestTupleScheme extends TupleScheme<ProduceRequest> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, ProduceRequest struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; oprot.writeBinary(struct.item); oprot.writeString(struct.topic); } @Override public void read(org.apache.thrift.protocol.TProtocol prot, ProduceRequest struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; struct.item = iprot.readBinary(); struct.setItemIsSet(true); struct.topic = iprot.readString(); struct.setTopicIsSet(true); } } }
apache-2.0
hxf0801/jbpm
jbpm-services/jbpm-kie-services/src/test/java/org/jbpm/kie/services/test/store/DeploymentStoreTest.java
3500
package org.jbpm.kie.services.test.store; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.Collection; import java.util.Date; import java.util.HashSet; import org.jbpm.kie.services.impl.KModuleDeploymentUnit; import org.jbpm.kie.services.impl.store.DeploymentStore; import org.jbpm.kie.test.util.AbstractBaseTest; import org.jbpm.runtime.manager.impl.jpa.EntityManagerFactoryManager; import org.jbpm.services.api.model.DeploymentUnit; import org.jbpm.shared.services.impl.TransactionalCommandService; import org.junit.After; import org.junit.Before; import org.junit.Test; public class DeploymentStoreTest extends AbstractBaseTest { private DeploymentStore store; @Before public void setup() { buildDatasource(); emf = EntityManagerFactoryManager.get().getOrCreate("org.jbpm.domain"); store = new DeploymentStore(); store.setCommandService(new TransactionalCommandService(emf)); } @After public void cleanup() { close(); } @Test public void testEnableAndGetActiveDeployments() { Collection<DeploymentUnit> enabled = store.getEnabledDeploymentUnits(); assertNotNull(enabled); assertEquals(0, enabled.size()); KModuleDeploymentUnit unit = new KModuleDeploymentUnit("org.jbpm", "test", "1.0"); store.enableDeploymentUnit(unit); enabled = store.getEnabledDeploymentUnits(); assertNotNull(enabled); assertEquals(1, enabled.size()); } @Test public void testEnableAndGetAndDisableActiveDeployments() { Collection<DeploymentUnit> enabled = store.getEnabledDeploymentUnits(); assertNotNull(enabled); assertEquals(0, enabled.size()); KModuleDeploymentUnit unit = new KModuleDeploymentUnit("org.jbpm", "test", "1.0"); store.enableDeploymentUnit(unit); enabled = store.getEnabledDeploymentUnits(); assertNotNull(enabled); assertEquals(1, enabled.size()); store.disableDeploymentUnit(unit); enabled = store.getEnabledDeploymentUnits(); assertNotNull(enabled); assertEquals(0, enabled.size()); } @Test public void testEnableAndGetByDateActiveDeployments() { Collection<DeploymentUnit> enabled = store.getEnabledDeploymentUnits(); assertNotNull(enabled); assertEquals(0, enabled.size()); Date date = new Date(); KModuleDeploymentUnit unit = new KModuleDeploymentUnit("org.jbpm", "test", "1.0"); store.enableDeploymentUnit(unit); unit = new KModuleDeploymentUnit("org.jbpm", "prod", "1.0"); store.enableDeploymentUnit(unit); Collection<DeploymentUnit> unitsEnabled = new HashSet<DeploymentUnit>(); Collection<DeploymentUnit> unitsDisabled = new HashSet<DeploymentUnit>(); Collection<DeploymentUnit> unitsActivated = new HashSet<DeploymentUnit>(); Collection<DeploymentUnit> unitsDeactivated = new HashSet<DeploymentUnit>(); store.getDeploymentUnitsByDate(date, unitsEnabled, unitsDisabled, unitsActivated, unitsDeactivated); assertNotNull(unitsEnabled); assertEquals(2, unitsEnabled.size()); assertNotNull(unitsDisabled); assertEquals(0, unitsDisabled.size()); date = new Date(); store.disableDeploymentUnit(unit); // verify unitsEnabled.clear(); unitsDisabled.clear(); unitsActivated.clear(); unitsDeactivated.clear(); store.getDeploymentUnitsByDate(date, unitsEnabled, unitsDisabled, unitsActivated, unitsDeactivated); assertNotNull(unitsEnabled); assertEquals(0, unitsEnabled.size()); assertNotNull(unitsDisabled); assertEquals(1, unitsDisabled.size()); } }
apache-2.0
jdilallo/jdilallo-test
examples/dfp/v201311/report_service/run_reach_report.py
2004
#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This code example runs a reach report.""" __author__ = ('Nicholas Chen', 'Joseph DiLallo') import tempfile # Import appropriate classes from the client library. from googleads import dfp from googleads import errors def main(client): # Initialize a DataDownloader. report_downloader = client.GetDataDownloader(version='v201311') # Create report job. report_job = { 'reportQuery': { 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], 'columns': ['REACH_FREQUENCY', 'REACH_AVERAGE_REVENUE', 'REACH'], 'dateRangeType': 'REACH_LIFETIME' } } try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) except errors.DfpReportError, e: print 'Failed to generate report. Error was: %s' % e else: # Change to your preferred export format. export_format = 'CSV_DUMP' report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) # Download report data. report_downloader.DownloadReportToFile( report_job_id, export_format, report_file) report_file.close() # Display results. print 'Report job with id \'%s\' downloaded to:\n%s' % ( report_job_id, report_file.name) if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() main(dfp_client)
apache-2.0
yssk22/gaecouch
futon/script/couch_tests.js
4298
// 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. // Used by replication test if (typeof window == 'undefined' || !window) { CouchDB.host = "127.0.0.1:5984"; CouchDB.inBrowser = false; } else { CouchDB.host = window.location.host; CouchDB.inBrowser = true; } CouchDB.urlPrefix = ".."; var couchTests = {}; function loadTest(file) { loadScript("script/test/"+file); }; // keep first loadTest("basics.js"); // keep sorted loadTest("all_docs.js"); loadTest("attachments.js"); loadTest("attachments_multipart.js"); loadTest("attachment_names.js"); loadTest("attachment_paths.js"); loadTest("attachment_views.js"); loadTest("batch_save.js"); loadTest("bulk_docs.js"); loadTest("changes.js"); loadTest("compact.js"); loadTest("config.js"); loadTest("conflicts.js"); loadTest("content_negotiation.js"); loadTest("cookie_auth.js"); loadTest("copy_doc.js"); loadTest("delayed_commits.js"); loadTest("design_docs.js"); loadTest("design_options.js"); loadTest("design_paths.js"); loadTest("erlang_views.js"); loadTest("etags_head.js"); loadTest("etags_views.js"); loadTest("form_submit.js"); loadTest("http.js"); loadTest("invalid_docids.js"); loadTest("jsonp.js"); loadTest("large_docs.js"); loadTest("list_views.js"); loadTest("lots_of_docs.js"); loadTest("multiple_rows.js"); loadScript("script/oauth.js"); loadScript("script/sha1.js"); loadTest("oauth.js"); loadTest("proxyauth.js"); loadTest("purge.js"); loadTest("reader_acl.js"); loadTest("recreate_doc.js"); loadTest("reduce.js"); loadTest("reduce_builtin.js"); loadTest("reduce_false.js"); loadTest("reduce_false_temp.js"); loadTest("replication.js"); loadTest("rev_stemming.js"); loadTest("rewrite.js"); loadTest("security_validation.js"); loadTest("show_documents.js"); loadTest("stats.js"); loadTest("update_documents.js"); loadTest("users_db.js"); loadTest("utf8.js"); loadTest("uuids.js"); loadTest("view_collation.js"); loadTest("view_collation_raw.js"); loadTest("view_conflicts.js"); loadTest("view_errors.js"); loadTest("view_include_docs.js"); loadTest("view_multi_key_all_docs.js"); loadTest("view_multi_key_design.js"); loadTest("view_multi_key_temp.js"); loadTest("view_offsets.js"); loadTest("view_pagination.js"); loadTest("view_sandboxing.js"); loadTest("view_xml.js"); // keep sorted function makeDocs(start, end, templateDoc) { var templateDocSrc = templateDoc ? JSON.stringify(templateDoc) : "{}" if (end === undefined) { end = start; start = 0; } var docs = [] for (var i = start; i < end; i++) { var newDoc = eval("(" + templateDocSrc + ")"); newDoc._id = (i).toString(); newDoc.integer = i; newDoc.string = (i).toString(); docs.push(newDoc) } return docs; } function run_on_modified_server(settings, fun) { try { // set the settings for(var i=0; i < settings.length; i++) { var s = settings[i]; var xhr = CouchDB.request("PUT", "/_config/" + s.section + "/" + s.key, { body: JSON.stringify(s.value), headers: {"X-Couch-Persist": "false"} }); CouchDB.maybeThrowError(xhr); s.oldValue = xhr.responseText; } // run the thing fun(); } finally { // unset the settings for(var j=0; j < i; j++) { var s = settings[j]; if(s.oldValue == "\"\"\n") { // unset value CouchDB.request("DELETE", "/_config/" + s.section + "/" + s.key, { headers: {"X-Couch-Persist": "false"} }); } else { CouchDB.request("PUT", "/_config/" + s.section + "/" + s.key, { body: s.oldValue, headers: {"X-Couch-Persist": "false"} }); } } } } function stringFun(fun) { var string = fun.toSource ? fun.toSource() : "(" + fun.toString() + ")"; return string; } function restartServer() { CouchDB.request("POST", "/_restart"); }
apache-2.0
Re-Rabbit/pandola
script/build.js
156
var gulp = require('gulp') var build = require('./libbuild') function main() { gulp.task('default', gulp.series(build.clean, build.buildAll)) } main()
apache-2.0
NativeScript/nativescript-cli
lib/services/analytics/analytics-service.ts
14298
import { ChildProcess } from "child_process"; import * as path from "path"; import * as _ from "lodash"; import { cache } from "../../common/decorators"; import { isInteractive, toBoolean } from "../../common/helpers"; import { DeviceTypes, AnalyticsClients } from "../../common/constants"; import { TrackActionNames } from "../../constants"; import { IOptions } from "../../declarations"; import { IProjectDataService } from "../../definitions/project"; import { IAnalyticsService, IDisposable, IDictionary, AnalyticsStatus, IUserSettingsService, IAnalyticsSettingsService, IChildProcess, IProjectHelper, GoogleAnalyticsDataType, IStringDictionary, TrackingTypes, } from "../../common/declarations"; import { IGoogleAnalyticsTrackingInformation, ITrackingInformation, IExceptionsTrackingInformation, } from "./analytics"; import { IGoogleAnalyticsEventData, IGoogleAnalyticsData, IEventActionData, } from "../../common/definitions/google-analytics"; import { injector } from "../../common/yok"; export class AnalyticsService implements IAnalyticsService, IDisposable { private static ANALYTICS_BROKER_START_TIMEOUT = 10 * 1000; private brokerProcess: ChildProcess; private shouldDisposeInstance: boolean = true; private analyticsStatuses: IDictionary<AnalyticsStatus> = {}; constructor( private $logger: ILogger, private $options: IOptions, private $staticConfig: Config.IStaticConfig, private $prompter: IPrompter, private $userSettingsService: IUserSettingsService, private $analyticsSettingsService: IAnalyticsSettingsService, private $childProcess: IChildProcess, private $projectDataService: IProjectDataService, private $mobileHelper: Mobile.IMobileHelper, private $projectHelper: IProjectHelper ) {} public setShouldDispose(shouldDispose: boolean): void { this.shouldDisposeInstance = shouldDispose; } public async checkConsent(): Promise<void> { if (await this.$analyticsSettingsService.canDoRequest()) { const initialTrackFeatureUsageStatus = await this.getStatus( this.$staticConfig.TRACK_FEATURE_USAGE_SETTING_NAME ); let trackFeatureUsage = initialTrackFeatureUsageStatus === AnalyticsStatus.enabled; if ( (await this.isNotConfirmed( this.$staticConfig.TRACK_FEATURE_USAGE_SETTING_NAME )) && isInteractive() ) { const message = `Do you want to help us improve ${this.$analyticsSettingsService.getClientName()} by automatically sending anonymous usage statistics? We will not use this information to identify or contact you.`; trackFeatureUsage = await this.$prompter.confirm(message, () => true); await this.setStatus( this.$staticConfig.TRACK_FEATURE_USAGE_SETTING_NAME, trackFeatureUsage ); await this.trackAcceptFeatureUsage({ acceptTrackFeatureUsage: trackFeatureUsage, }); } const isErrorReportingUnset = await this.isNotConfirmed( this.$staticConfig.ERROR_REPORT_SETTING_NAME ); const isUsageReportingConfirmed = !(await this.isNotConfirmed( this.$staticConfig.TRACK_FEATURE_USAGE_SETTING_NAME )); if (isErrorReportingUnset && isUsageReportingConfirmed) { await this.setStatus( this.$staticConfig.ERROR_REPORT_SETTING_NAME, trackFeatureUsage ); } } } public async setStatus(settingName: string, enabled: boolean): Promise<void> { this.analyticsStatuses[settingName] = enabled ? AnalyticsStatus.enabled : AnalyticsStatus.disabled; await this.$userSettingsService.saveSetting( settingName, enabled.toString() ); } public async isEnabled(settingName: string): Promise<boolean> { const analyticsStatus = await this.getStatus(settingName); return analyticsStatus === AnalyticsStatus.enabled; } public getStatusMessage( settingName: string, jsonFormat: boolean, readableSettingName: string ): Promise<string> { if (jsonFormat) { return this.getJsonStatusMessage(settingName); } return this.getHumanReadableStatusMessage(settingName, readableSettingName); } public async trackAcceptFeatureUsage(settings: { acceptTrackFeatureUsage: boolean; }): Promise<void> { const acceptTracking = !!(settings && settings.acceptTrackFeatureUsage); const googleAnalyticsEventData: IGoogleAnalyticsEventData = { googleAnalyticsDataType: GoogleAnalyticsDataType.Event, action: TrackActionNames.AcceptTracking, label: acceptTracking.toString(), }; await this.forcefullyTrackInGoogleAnalytics(googleAnalyticsEventData); } public async trackInGoogleAnalytics( gaSettings: IGoogleAnalyticsData ): Promise<void> { await this.initAnalyticsStatuses(); if ( !this.$staticConfig.disableAnalytics && this.analyticsStatuses[ this.$staticConfig.TRACK_FEATURE_USAGE_SETTING_NAME ] === AnalyticsStatus.enabled ) { return this.forcefullyTrackInGoogleAnalytics(gaSettings); } } public async trackEventActionInGoogleAnalytics( data: IEventActionData ): Promise<void> { const device = data.device; const platform = device ? device.deviceInfo.platform : data.platform; const normalizedPlatform = platform ? this.$mobileHelper.normalizePlatformName(platform) : platform; const isForDevice = device ? !device.isEmulator : data.isForDevice; let label: string = ""; label = this.addDataToLabel(label, normalizedPlatform); // In some cases (like in case action is Build and platform is Android), we do not know if the deviceType is emulator or device. // Just exclude the device_type in this case. if (isForDevice !== null && isForDevice !== undefined) { const deviceType = isForDevice ? DeviceTypes.Device : this.$mobileHelper.isAndroidPlatform(platform) ? DeviceTypes.Emulator : DeviceTypes.Simulator; label = this.addDataToLabel(label, deviceType); } if (device) { label = this.addDataToLabel(label, device.deviceInfo.version); } if (data.additionalData) { label = this.addDataToLabel(label, data.additionalData); } const customDimensions: IStringDictionary = {}; this.setProjectRelatedCustomDimensions(customDimensions, data.projectDir); const googleAnalyticsEventData: IGoogleAnalyticsEventData = { googleAnalyticsDataType: GoogleAnalyticsDataType.Event, action: data.action, label, customDimensions, value: data.value, }; await this.trackInGoogleAnalytics(googleAnalyticsEventData); } public async trackPreviewAppData( platform: string, projectDir: string ): Promise<void> { // const customDimensions: IStringDictionary = {}; // this.setProjectRelatedCustomDimensions(customDimensions, projectDir); // // let label: string = ""; // label = this.addDataToLabel( // label, // this.$mobileHelper.normalizePlatformName(platform) // ); // // const eventActionData = { // googleAnalyticsDataType: GoogleAnalyticsDataType.Event, // action: TrackActionNames.PreviewAppData, // platform, // label, // customDimensions, // type: TrackingTypes.PreviewAppData, // }; // // await this.trackInGoogleAnalytics(eventActionData); } public async finishTracking(): Promise<void> { return new Promise((resolve, reject) => { if (this.brokerProcess && this.brokerProcess.connected) { let timer: NodeJS.Timer; const handler = (data: string) => { if (data === DetachedProcessMessages.ProcessFinishedTasks) { this.brokerProcess.removeListener("message", handler); clearTimeout(timer); resolve(); } }; timer = setTimeout(() => { this.brokerProcess.removeListener("message", handler); resolve(); }, 3000); this.brokerProcess.on("message", handler); const msg = { type: TrackingTypes.FinishTracking }; this.brokerProcess.send(msg, (err: Error) => this.$logger.trace(`Error while sending ${JSON.stringify(msg)}`) ); } else { resolve(); } }); } private forcefullyTrackInGoogleAnalytics( gaSettings: IGoogleAnalyticsData ): Promise<void> { gaSettings.customDimensions = gaSettings.customDimensions || {}; gaSettings.customDimensions[GoogleAnalyticsCustomDimensions.client] = this.$options.analyticsClient || (isInteractive() ? AnalyticsClients.Cli : AnalyticsClients.Unknown); this.setProjectRelatedCustomDimensions(gaSettings.customDimensions); const googleAnalyticsData: IGoogleAnalyticsTrackingInformation = _.merge( { type: TrackingTypes.GoogleAnalyticsData, category: AnalyticsClients.Cli, }, gaSettings ); this.$logger.trace( "Will send the following information to Google Analytics:", googleAnalyticsData ); return this.sendMessageToBroker(googleAnalyticsData); } private setProjectRelatedCustomDimensions( customDimensions: IStringDictionary, projectDir?: string ): IStringDictionary { if (!projectDir) { try { projectDir = this.$projectHelper.projectDir; } catch (err) { // In case there's no project dir here, the above getter will fail. this.$logger.trace( "Unable to get the projectDir from projectHelper", err ); } } if (projectDir) { const projectData = this.$projectDataService.getProjectData(projectDir); customDimensions[GoogleAnalyticsCustomDimensions.projectType] = projectData.projectType; customDimensions[ GoogleAnalyticsCustomDimensions.isShared ] = projectData.isShared.toString(); } return customDimensions; } public dispose(): void { if (this.brokerProcess && this.shouldDisposeInstance) { this.brokerProcess.disconnect(); } } private addDataToLabel(label: string, newData: string): string { if (newData && label) { return `${label}_${newData}`; } return label || newData || ""; } @cache() private getAnalyticsBroker(): Promise<ChildProcess> { return new Promise<ChildProcess>((resolve, reject) => { const brokerProcessArgs = this.getBrokerProcessArgs(); const broker = this.$childProcess.spawn( process.execPath, brokerProcessArgs, { stdio: ["ignore", "ignore", "ignore", "ipc"], detached: true, } ); broker.unref(); let isSettled = false; const timeoutId = setTimeout(() => { if (!isSettled) { reject(new Error("Unable to start Analytics Broker process.")); } }, AnalyticsService.ANALYTICS_BROKER_START_TIMEOUT); broker.on("error", (err: Error) => { clearTimeout(timeoutId); if (!isSettled) { isSettled = true; reject(err); } }); broker.on("message", (data: any) => { if (data === DetachedProcessMessages.ProcessReadyToReceive) { clearTimeout(timeoutId); if (!isSettled) { isSettled = true; this.brokerProcess = broker; resolve(broker); } } }); }); } private getBrokerProcessArgs(): string[] { const brokerProcessArgs = [ path.join(__dirname, "analytics-broker-process.js"), this.$staticConfig.PATH_TO_BOOTSTRAP, ]; if (this.$options.analyticsLogFile) { brokerProcessArgs.push(this.$options.analyticsLogFile); } return brokerProcessArgs; } private async sendInfoForTracking( trackingInfo: ITrackingInformation, settingName: string ): Promise<void> { await this.initAnalyticsStatuses(); if ( !this.$staticConfig.disableAnalytics && this.analyticsStatuses[settingName] === AnalyticsStatus.enabled ) { return this.sendMessageToBroker(trackingInfo); } } private async sendMessageToBroker( message: ITrackingInformation ): Promise<void> { let broker: ChildProcess; try { broker = await this.getAnalyticsBroker(); } catch (err) { this.$logger.trace("Unable to get broker instance due to error: ", err); return; } return new Promise<void>((resolve, reject) => { if (broker && broker.connected) { try { broker.send(message, (error: Error) => resolve()); } catch (err) { this.$logger.trace( "Error while trying to send message to broker:", err ); resolve(); } } else { this.$logger.trace("Broker not found or not connected."); resolve(); } }); } @cache() private async initAnalyticsStatuses(): Promise<void> { if (await this.$analyticsSettingsService.canDoRequest()) { this.$logger.trace("Initializing analytics statuses."); const settingsNames = [ this.$staticConfig.TRACK_FEATURE_USAGE_SETTING_NAME, this.$staticConfig.ERROR_REPORT_SETTING_NAME, ]; for (const settingName of settingsNames) { await this.getStatus(settingName); } this.$logger.trace("Analytics statuses: ", this.analyticsStatuses); } } private async getStatus(settingName: string): Promise<AnalyticsStatus> { if (!_.has(this.analyticsStatuses, settingName)) { const settingValue = await this.$userSettingsService.getSettingValue< string >(settingName); if (settingValue) { const isEnabled = toBoolean(settingValue); if (isEnabled) { this.analyticsStatuses[settingName] = AnalyticsStatus.enabled; } else { this.analyticsStatuses[settingName] = AnalyticsStatus.disabled; } } else { this.analyticsStatuses[settingName] = AnalyticsStatus.notConfirmed; } } return this.analyticsStatuses[settingName]; } private async isNotConfirmed(settingName: string): Promise<boolean> { const analyticsStatus = await this.getStatus(settingName); return analyticsStatus === AnalyticsStatus.notConfirmed; } private async getHumanReadableStatusMessage( settingName: string, readableSettingName: string ): Promise<string> { let status: string = null; if (await this.isNotConfirmed(settingName)) { status = "disabled until confirmed"; } else { status = await this.getStatus(settingName); } return `${readableSettingName} is ${status}.`; } private async getJsonStatusMessage(settingName: string): Promise<string> { const status = await this.getStatus(settingName); const enabled = status === AnalyticsStatus.notConfirmed ? null : status === AnalyticsStatus.enabled; return JSON.stringify({ enabled }); } public trackException(exception: any, message: string): Promise<void> { const data: IExceptionsTrackingInformation = { type: TrackingTypes.Exception, exception, message, }; return this.sendInfoForTracking( data, this.$staticConfig.ERROR_REPORT_SETTING_NAME ); } } injector.register("analyticsService", AnalyticsService);
apache-2.0
vespa-engine/vespa
storage/src/tests/distributor/throttlingoperationstartertest.cpp
5557
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/storage/distributor/throttlingoperationstarter.h> #include <tests/distributor/maintenancemocks.h> #include <vespa/document/test/make_document_bucket.h> #include <vespa/vespalib/gtest/gtest.h> namespace storage::distributor { using document::BucketId; using document::test::makeDocumentBucket; using namespace ::testing; namespace { const MockOperation& as_mock_operation(const Operation& operation) { return dynamic_cast<const MockOperation&>(operation); } } struct ThrottlingOperationStarterTest : Test { std::shared_ptr<Operation> createMockOperation() { return std::make_shared<MockOperation>(makeDocumentBucket(BucketId(16, 1))); } std::unique_ptr<MockOperationStarter> _starterImpl; std::unique_ptr<ThrottlingOperationStarter> _operationStarter; void SetUp() override; void TearDown() override; }; void ThrottlingOperationStarterTest::SetUp() { _starterImpl = std::make_unique<MockOperationStarter>(); _operationStarter = std::make_unique<ThrottlingOperationStarter>(*_starterImpl); } void ThrottlingOperationStarterTest::TearDown() { // Must clear before _operationStarter goes out of scope, or operation // destructors will try to call method on destroyed object. _starterImpl->getOperations().clear(); } TEST_F(ThrottlingOperationStarterTest, operation_not_throttled_when_slot_available) { auto operation = createMockOperation(); EXPECT_TRUE(_operationStarter->start(operation, OperationStarter::Priority(0))); EXPECT_FALSE(as_mock_operation(*operation).get_was_throttled()); } TEST_F(ThrottlingOperationStarterTest, operation_starting_is_forwarded_to_implementation) { ASSERT_TRUE(_operationStarter->start(createMockOperation(), OperationStarter::Priority(0))); EXPECT_EQ("Bucket(BucketSpace(0x0000000000000001), BucketId(0x4000000000000001)), pri 0\n", _starterImpl->toString()); } TEST_F(ThrottlingOperationStarterTest, operation_throttled_when_no_available_slots) { _operationStarter->setMaxPendingRange(0, 0); auto operation = createMockOperation(); EXPECT_FALSE(_operationStarter->may_allow_operation_with_priority(OperationStarter::Priority(0))); EXPECT_FALSE(_operationStarter->start(operation, OperationStarter::Priority(0))); EXPECT_TRUE(as_mock_operation(*operation).get_was_throttled()); } TEST_F(ThrottlingOperationStarterTest, throttling_with_max_pending_range) { _operationStarter->setMaxPendingRange(0, 1); EXPECT_FALSE(_operationStarter->canStart(0, OperationStarter::Priority(255))); EXPECT_TRUE(_operationStarter->canStart(0, OperationStarter::Priority(0))); _operationStarter->setMaxPendingRange(1, 1); EXPECT_TRUE(_operationStarter->canStart(0, OperationStarter::Priority(255))); EXPECT_TRUE(_operationStarter->canStart(0, OperationStarter::Priority(0))); _operationStarter->setMaxPendingRange(1, 3); EXPECT_FALSE(_operationStarter->canStart(1, OperationStarter::Priority(255))); EXPECT_TRUE(_operationStarter->canStart(1, OperationStarter::Priority(100))); EXPECT_TRUE(_operationStarter->canStart(1, OperationStarter::Priority(0))); EXPECT_TRUE(_operationStarter->canStart(2, OperationStarter::Priority(0))); EXPECT_FALSE(_operationStarter->canStart(3, OperationStarter::Priority(0))); EXPECT_FALSE(_operationStarter->canStart(4, OperationStarter::Priority(0))); } TEST_F(ThrottlingOperationStarterTest, starting_operations_fills_up_pending_window) { _operationStarter->setMaxPendingRange(1, 3); EXPECT_TRUE(_operationStarter->may_allow_operation_with_priority(OperationStarter::Priority(255))); EXPECT_TRUE(_operationStarter->start(createMockOperation(), OperationStarter::Priority(255))); EXPECT_FALSE(_operationStarter->may_allow_operation_with_priority(OperationStarter::Priority(255))); EXPECT_FALSE(_operationStarter->start(createMockOperation(), OperationStarter::Priority(255))); EXPECT_TRUE(_operationStarter->may_allow_operation_with_priority(OperationStarter::Priority(100))); EXPECT_TRUE(_operationStarter->start(createMockOperation(), OperationStarter::Priority(100))); EXPECT_FALSE(_operationStarter->may_allow_operation_with_priority(OperationStarter::Priority(255))); EXPECT_FALSE(_operationStarter->start(createMockOperation(), OperationStarter::Priority(100))); EXPECT_TRUE(_operationStarter->may_allow_operation_with_priority(OperationStarter::Priority(0))); EXPECT_TRUE(_operationStarter->start(createMockOperation(), OperationStarter::Priority(0))); EXPECT_FALSE(_operationStarter->may_allow_operation_with_priority(OperationStarter::Priority(0))); EXPECT_FALSE(_operationStarter->start(createMockOperation(), OperationStarter::Priority(0))); } TEST_F(ThrottlingOperationStarterTest, finishing_operations_allows_more_to_start) { _operationStarter->setMaxPendingRange(1, 1); EXPECT_TRUE(_operationStarter->start(createMockOperation(), OperationStarter::Priority(255))); EXPECT_FALSE(_operationStarter->start(createMockOperation(), OperationStarter::Priority(255))); EXPECT_FALSE(_starterImpl->getOperations().empty()); _starterImpl->getOperations().pop_back(); EXPECT_TRUE(_operationStarter->may_allow_operation_with_priority(OperationStarter::Priority(255))); EXPECT_TRUE(_operationStarter->start(createMockOperation(), OperationStarter::Priority(255))); EXPECT_FALSE(_starterImpl->getOperations().empty()); } }
apache-2.0
ryandcarter/hybris-connector
src/main/java/org/mule/modules/hybris/model/BtgQuantityOfProductInCartOperandsDTO.java
2541
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.11.29 at 12:35:53 PM GMT // package org.mule.modules.hybris.model; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for btgQuantityOfProductInCartOperandsDTO complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="btgQuantityOfProductInCartOperandsDTO"> * &lt;complexContent> * &lt;extension base="{}abstractCollectionDTO"> * &lt;sequence> * &lt;element ref="{}btgquantityofproductincartoperand" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "btgQuantityOfProductInCartOperandsDTO", propOrder = { "btgquantityofproductincartoperand" }) public class BtgQuantityOfProductInCartOperandsDTO extends AbstractCollectionDTO { protected List<BtgQuantityOfProductInCartOperandDTO> btgquantityofproductincartoperand; /** * Gets the value of the btgquantityofproductincartoperand property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the btgquantityofproductincartoperand property. * * <p> * For example, to add a new item, do as follows: * <pre> * getBtgquantityofproductincartoperand().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link BtgQuantityOfProductInCartOperandDTO } * * */ public List<BtgQuantityOfProductInCartOperandDTO> getBtgquantityofproductincartoperand() { if (btgquantityofproductincartoperand == null) { btgquantityofproductincartoperand = new ArrayList<BtgQuantityOfProductInCartOperandDTO>(); } return this.btgquantityofproductincartoperand; } }
apache-2.0
canoo/dolphin-platform
platform/dolphin-platform-remoting-server/src/main/java/com/canoo/dp/impl/server/servlet/InterruptServlet.java
1981
/* * Copyright 2015-2018 Canoo Engineering AG. * * 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.canoo.dp.impl.server.servlet; import com.canoo.dp.impl.platform.core.Assert; import com.canoo.dp.impl.server.context.DolphinContext; import com.canoo.dp.impl.server.context.DolphinContextProvider; import org.apiguardian.api.API; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static org.apiguardian.api.API.Status.INTERNAL; @API(since = "0.x", status = INTERNAL) public class InterruptServlet extends HttpServlet { private final DolphinContextProvider dolphinContextProvider; public InterruptServlet(final DolphinContextProvider dolphinContextProvider) { this.dolphinContextProvider = Assert.requireNonNull(dolphinContextProvider, "dolphinContextProvider"); } @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse response) throws ServletException, IOException { Assert.requireNonNull(response, "response"); final DolphinContext currentContext = dolphinContextProvider.getCurrentDolphinContext(); if(currentContext == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing or wrong client session id"); } else { currentContext.interrupt(); } } }
apache-2.0
cautiontowind/alpha-vantage
src/main/java/com/jalpha_vantage/exception/InvalidApiKeyException.java
175
package com.jalpha_vantage.exception; public class InvalidApiKeyException extends Exception { public InvalidApiKeyException(String value) { super(value); } }
apache-2.0
spinnaker/deck
packages/cloudfoundry/src/presentation/widgets/accountRegionClusterSelector/AccountRegionClusterSelector.spec.tsx
15140
import type { IScope } from 'angular'; import { mock, noop } from 'angular'; import { mount, shallow } from 'enzyme'; import React from 'react'; import type { Application, ApplicationDataSource, IMoniker, IServerGroup } from '@spinnaker/core'; import { ApplicationModelBuilder, REACT_MODULE } from '@spinnaker/core'; import type { IAccountRegionClusterSelectorProps } from './AccountRegionClusterSelector'; import { AccountRegionClusterSelector } from './AccountRegionClusterSelector'; describe('<AccountRegionClusterSelector />', () => { let $scope: IScope; let application: Application; function createServerGroup(account: string, cluster: string, name: string, region: string): IServerGroup { return { account, cloudProvider: 'cloud-provider', cluster, name, region, instances: [{ health: null, id: 'instance-id', launchTime: 0, name: 'instance-name', zone: 'GMT' }], instanceCounts: { up: 1, down: 0, starting: 0, succeeded: 1, failed: 0, unknown: 0, outOfService: 0 }, moniker: { app: 'my-app', cluster, detail: 'my-detail', stack: 'my-stack', sequence: 1 }, } as IServerGroup; } beforeEach(mock.module(REACT_MODULE)); beforeEach( mock.inject(($rootScope: IScope) => { $scope = $rootScope.$new(); application = ApplicationModelBuilder.createApplicationForTests('app', { key: 'serverGroups', loaded: true, data: [ createServerGroup('account-name-one', 'app-stack-detailOne', 'app', 'region-one'), createServerGroup('account-name-two', 'app-stack-detailTwo', 'app', 'region-two'), createServerGroup('account-name-one', 'app-stack-detailOne', 'app', 'region-three'), createServerGroup('account-name-one', 'app-stack-detailThree', 'app', 'region-one'), createServerGroup('account-name-one', 'app-stack-detailFour', 'app', 'region-three'), createServerGroup('account-name-one', 'app-stack-detailFive', 'app', 'region-two'), ], defaultData: [] as IServerGroup[], } as ApplicationDataSource<IServerGroup[]>); }), ); it('initializes properly with provided component', () => { const accountRegionClusterProps: IAccountRegionClusterSelectorProps = { accounts: [ { accountId: 'account-id-one', name: 'account-name-one', requiredGroupMembership: [], type: 'account-type', }, ], application, cloudProvider: 'cloud-provider', onComponentUpdate: noop, component: { credentials: 'account-name-one', regions: ['region-one'], }, }; const component = shallow<AccountRegionClusterSelector>( <AccountRegionClusterSelector {...accountRegionClusterProps} />, ); $scope.$digest(); expect(component.state().availableRegions.length).toBe(3, 'number of available regions does not match'); expect(component.state().availableRegions).toContain('region-one'); expect(component.state().availableRegions).toContain('region-two'); expect(component.state().availableRegions).toContain('region-three'); expect(component.state().clusters.length).toBe(2, 'number of clusters does not match'); expect(component.state().clusters).toContain('app-stack-detailOne'); expect(component.state().clusters).toContain('app-stack-detailThree'); expect(component.state().clusterField).toBe('cluster'); expect(component.state().componentName).toBe(''); }); it('retrieves the correct list of regions when account is changed', () => { let credentials = ''; let region = 'SHOULD-CHANGE'; let regions = ['SHOULD-CHANGE']; let cluster = 'SHOULD-CHANGE'; const accountRegionClusterProps: IAccountRegionClusterSelectorProps = { accounts: [ { accountId: 'account-id-two', name: 'account-name-two', requiredGroupMembership: [], type: 'account-type', }, { accountId: 'account-id-one', name: 'account-name-one', requiredGroupMembership: [], type: 'account-type', }, ], application, cloudProvider: 'cloud-provider', onComponentUpdate: (value: any) => { credentials = value.credentials; region = value.region; regions = value.regions; cluster = value.cluster; }, component: { credentials: 'account-name-one', regions: ['region-one'], }, }; const component = mount<AccountRegionClusterSelector>( <AccountRegionClusterSelector {...accountRegionClusterProps} />, ); $scope.$digest(); expect(component.state().availableRegions.length).toBe(3, 'number of available regions does not match'); expect(component.state().availableRegions).toContain('region-one'); expect(component.state().availableRegions).toContain('region-two'); expect(component.state().availableRegions).toContain('region-three'); expect(component.state().clusters.length).toBe(2, 'number of clusters does not match'); expect(component.state().clusters).toContain('app-stack-detailOne'); expect(component.state().clusters).toContain('app-stack-detailThree'); const accountSelectComponent = component.find('Select[name="credentials"] .Select-control input'); accountSelectComponent.simulate('mouseDown'); accountSelectComponent.simulate('change', { target: { value: 'account-name-two' } }); accountSelectComponent.simulate('keyDown', { keyCode: 9, key: 'Tab' }); $scope.$digest(); expect(component.state().availableRegions.length).toBe(1, 'number of available regions does not match'); expect(component.state().availableRegions).toContain('region-two'); expect(component.state().clusters.length).toBe(0, 'number of clusters does not match'); expect(region).toEqual('', 'selected region is not cleared'); expect(regions.length).toBe(0, 'selected regions list is not cleared'); expect(credentials).toContain('account-name-two'); expect(cluster).toBeUndefined('selected cluster is not cleared'); }); it('retrieves the correct list of clusters when the selector is multi-region and the region is changed', () => { let regions: string[] = []; let cluster = 'SHOULD-CHANGE'; const accountRegionClusterProps: IAccountRegionClusterSelectorProps = { accounts: [ { accountId: 'account-id-two', name: 'account-name-two', requiredGroupMembership: [], type: 'account-type', }, { accountId: 'account-id-one', name: 'account-name-one', requiredGroupMembership: [], type: 'account-type', }, ], application, cloudProvider: 'cloud-provider', clusterField: 'newCluster', onComponentUpdate: (value: any) => { regions = value.regions; cluster = value.newCluster; }, component: { credentials: 'account-name-one', regions: ['region-one'], }, }; const component = mount<AccountRegionClusterSelector>( <AccountRegionClusterSelector {...accountRegionClusterProps} />, ); $scope.$digest(); expect(component.state().availableRegions.length).toBe(3, 'number of available regions does not match'); expect(component.state().availableRegions).toContain('region-one'); expect(component.state().availableRegions).toContain('region-two'); expect(component.state().availableRegions).toContain('region-three'); expect(component.state().clusters.length).toBe(2, 'number of clusters does not match'); expect(component.state().clusters).toContain('app-stack-detailOne'); expect(component.state().clusters).toContain('app-stack-detailThree'); const accountSelectComponent = component.find('Select[name="regions"] .Select-control input'); accountSelectComponent.simulate('mouseDown'); accountSelectComponent.simulate('change', { target: { value: 'region-three' } }); accountSelectComponent.simulate('keyDown', { keyCode: 9, key: 'Tab' }); $scope.$digest(); expect(component.state().clusters.length).toBe(3, 'number of clusters does not match'); expect(component.state().clusters).toContain('app-stack-detailOne'); expect(component.state().clusters).toContain('app-stack-detailThree'); expect(component.state().clusters).toContain('app-stack-detailFour'); expect(cluster).toBeUndefined('selected cluster is not cleared'); expect(regions.length).toBe(2); expect(regions).toContain('region-one'); expect(regions).toContain('region-three'); }); it('retrieves the correct list of clusters on startup and the selector is single-region', () => { const accountRegionClusterProps: IAccountRegionClusterSelectorProps = { accounts: [ { accountId: 'account-id-two', name: 'account-name-two', requiredGroupMembership: [], type: 'account-type', }, { accountId: 'account-id-one', name: 'account-name-one', requiredGroupMembership: [], type: 'account-type', }, ], application, cloudProvider: 'cloud-provider', onComponentUpdate: (_value: any) => {}, component: { cluster: 'app-stack-detailOne', credentials: 'account-name-one', region: 'region-one', }, isSingleRegion: true, }; const component = mount<AccountRegionClusterSelector>( <AccountRegionClusterSelector {...accountRegionClusterProps} />, ); $scope.$digest(); expect(component.state().availableRegions.length).toBe(3, 'number of available regions does not match'); expect(component.state().availableRegions).toContain('region-one'); expect(component.state().availableRegions).toContain('region-two'); expect(component.state().availableRegions).toContain('region-three'); expect(component.state().clusters.length).toBe(2, 'number of clusters does not match'); expect(component.state().clusters).toContain('app-stack-detailOne'); expect(component.state().clusters).toContain('app-stack-detailThree'); }); it('the cluster value is updated in the component when cluster is changed', () => { let cluster = ''; let moniker: IMoniker = { app: '' }; const accountRegionClusterProps: IAccountRegionClusterSelectorProps = { accounts: [ { accountId: 'account-id-two', name: 'account-name-two', requiredGroupMembership: [], type: 'account-type', }, { accountId: 'account-id-one', name: 'account-name-one', requiredGroupMembership: [], type: 'account-type', }, ], application, cloudProvider: 'cloud-provider', clusterField: 'newCluster', onComponentUpdate: (value: any) => { cluster = value.newCluster; moniker = value.moniker; }, component: { cluster: 'app-stack-detailOne', credentials: 'account-name-one', regions: ['region-one'], }, }; const expectedMoniker = { app: 'my-app', cluster: 'app-stack-detailThree', detail: 'my-detail', stack: 'my-stack', sequence: null, } as IMoniker; const component = mount<AccountRegionClusterSelector>( <AccountRegionClusterSelector {...accountRegionClusterProps} />, ); $scope.$digest(); expect(component.state().availableRegions.length).toBe(3, 'number of available regions does not match'); expect(component.state().availableRegions).toContain('region-one'); expect(component.state().availableRegions).toContain('region-two'); expect(component.state().availableRegions).toContain('region-three'); expect(component.state().clusters.length).toBe(2, 'number of clusters does not match'); expect(component.state().clusters).toContain('app-stack-detailOne'); expect(component.state().clusters).toContain('app-stack-detailThree'); const clusterSelectComponent = component.find('Select[name="newCluster"] .Select-control input'); clusterSelectComponent.simulate('mouseDown'); clusterSelectComponent.simulate('change', { target: { value: 'app-stack-detailThree' } }); clusterSelectComponent.simulate('keyDown', { keyCode: 9, key: 'Tab' }); $scope.$digest(); expect(cluster).toBe('app-stack-detailThree'); expect(moniker).toEqual(expectedMoniker); }); it('the cluster value is updated in the component when cluster is changed to freeform value', () => { let cluster = ''; let moniker: IMoniker = { app: '' }; const accountRegionClusterProps: IAccountRegionClusterSelectorProps = { accounts: [ { accountId: 'account-id-two', name: 'account-name-two', requiredGroupMembership: [], type: 'account-type', }, { accountId: 'account-id-one', name: 'account-name-one', requiredGroupMembership: [], type: 'account-type', }, ], application, cloudProvider: 'cloud-provider', clusterField: 'newCluster', onComponentUpdate: (value: any) => { cluster = value.newCluster; moniker = value.moniker; }, component: { cluster: 'app-stack-detailOne', credentials: 'account-name-one', regions: ['region-one'], }, }; const component = mount<AccountRegionClusterSelector>( <AccountRegionClusterSelector {...accountRegionClusterProps} />, ); $scope.$digest(); const clusterSelectComponent = component.find('Select[name="newCluster"] .Select-control input'); clusterSelectComponent.simulate('mouseDown'); clusterSelectComponent.simulate('change', { target: { value: 'app-stack-freeform' } }); clusterSelectComponent.simulate('keyDown', { keyCode: 9, key: 'Tab' }); $scope.$digest(); expect(cluster).toBe('app-stack-freeform'); expect(moniker).toBeUndefined(); expect(component.state().clusters).toContain('app-stack-freeform'); }); it('initialize with form names', () => { const accountRegionClusterProps: IAccountRegionClusterSelectorProps = { accounts: [ { accountId: 'account-id-one', name: 'account-name-one', requiredGroupMembership: [], type: 'account-type', }, ], application, cloudProvider: 'cloud-provider', onComponentUpdate: noop, componentName: 'form', component: { credentials: 'account-name-one', regions: ['region-one'], }, }; const component = shallow(<AccountRegionClusterSelector {...accountRegionClusterProps} />); $scope.$digest(); expect(component.find('Select[name="form.credentials"]').length).toBe(1, 'select for account not found'); expect(component.find('Select[name="form.regions"]').length).toBe(1, 'select for regions not found'); expect(component.find('StageConfigField [name="form.cluster"]').length).toBe(1, 'select for cluster not found'); }); });
apache-2.0
tomtom-international/speedtools-examples
src/main/java/com/tomtom/examples/exampleUsingLbsServices/ExampleLbsModule.java
1947
/* * Copyright (C) 2012-2021, TomTom (http://tomtom.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tomtom.examples.exampleUsingLbsServices; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; /** * This is an example Guice module of how to bind service implementations to their interfaces. This examples binds a * "version 1" and "version 2" interfaces of a REST API to 2 different implementations. It also binds a rudimentary * database implementation to a database interface. */ public class ExampleLbsModule implements Module { private static final Logger LOG = LoggerFactory.getLogger(ExampleLbsModule.class); @Override public void configure(@Nonnull final Binder binder) { assert binder != null; // Bind APIs to their implementation. binder.bind(ExampleLbsResource.class).to(ExampleLbsResourceImpl.class).in(Singleton.class); /** * Show some start-up information about this example application. */ LOG.info("configure:"); LOG.info("configure: GET /lbs/traceme Issue a trace event to MongoDB"); LOG.info("configure: GET /lbs/geocode/<query> Perform geo-coding request"); LOG.info("configure: GET /lbs/route/<from>/<to> Calculate route"); } }
apache-2.0
SimY4/xpath-to-xml
xpath-to-xml-jdom/src/main/java/com/github/simy4/xpath/jdom/navigator/node/JDomElement.java
3411
package com.github.simy4.xpath.jdom.navigator.node; import com.github.simy4.xpath.XmlBuilderException; import org.jdom2.Attribute; import org.jdom2.Content; import org.jdom2.Element; import org.jdom2.IllegalAddException; import org.jdom2.Text; import org.jdom2.filter.Filter; import org.jdom2.filter.Filters; import javax.xml.namespace.QName; public final class JDomElement extends AbstractJDomNode<Element> { private static final long serialVersionUID = 1L; public JDomElement(Element element) { super(element); } @Override public QName getName() { return new QName(getNode().getNamespaceURI(), getNode().getName(), getNode().getNamespacePrefix()); } @Override public String getText() { return getNode().getText(); } @Override public JDomNode getRoot() { return new JDomDocument(getNode().getDocument()); } @Override @SuppressWarnings("ReferenceEquality") public JDomNode getParent() { final var node = getNode(); final var parent = node.getParent(); return null == parent ? node.getDocument().getRootElement() == node ? getRoot() : null : new JDomElement((Element) parent); } @Override public Iterable<? extends JDomNode> elements() { return (Iterable<JDomElement>) () -> getNode().getChildren().stream() .map(JDomElement::new) .iterator(); } @Override public Iterable<? extends JDomNode> attributes() { return (Iterable<JDomAttribute>) () -> getNode().getAttributes().stream() .map(JDomAttribute::new) .iterator(); } @Override public JDomNode appendAttribute(Attribute attribute) throws XmlBuilderException { try { getNode().setAttribute(attribute); return new JDomAttribute(attribute); } catch (IllegalAddException iae) { throw new XmlBuilderException("Unable to append an attribute to " + getNode(), iae); } } @Override public JDomNode appendElement(Element element) throws XmlBuilderException { try { getNode().addContent(element); return new JDomElement(element); } catch (IllegalAddException iae) { throw new XmlBuilderException("Unable to append an element to " + getNode(), iae); } } @Override public void prependCopy() throws XmlBuilderException { final var node = getNode(); final var parent = node.getParent(); if (null == parent) { throw new XmlBuilderException("Unable to prepend - no parent found of " + node); } final var prependIndex = parent.indexOf(node); final var copy = node.clone(); parent.addContent(prependIndex, copy); } @Override @SuppressWarnings("unchecked") public void setText(String text) throws XmlBuilderException { try { final var filter = (Filter<Content>) Filters.text().negate(); final var content = getNode().getContent(filter); getNode().setContent(content); getNode().addContent(new Text(text)); } catch (IllegalAddException iae) { throw new XmlBuilderException("Unable to set value to " + getNode(), iae); } } @Override public void remove() { getNode().detach(); } }
apache-2.0
Pronoy999/Project-OneX
One X/One X/Assembler.Designer.cs
8904
namespace One_X { partial class Assembler { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.insts = new System.Windows.Forms.ListView(); this.stubColumn = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.addressLC = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.mnemonicLC = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.hexcodeLC = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.bytesLC = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.mcycleLC = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.tstateLC = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.rightPanel = new System.Windows.Forms.Panel(); this.startAddressGB = new System.Windows.Forms.GroupBox(); this.startAddressBox = new System.Windows.Forms.TextBox(); this.setAddressButton = new System.Windows.Forms.Button(); this.rightPanel.SuspendLayout(); this.startAddressGB.SuspendLayout(); this.SuspendLayout(); // // insts // this.insts.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.stubColumn, this.addressLC, this.mnemonicLC, this.hexcodeLC, this.bytesLC, this.mcycleLC, this.tstateLC}); this.insts.Dock = System.Windows.Forms.DockStyle.Fill; this.insts.FullRowSelect = true; this.insts.Location = new System.Drawing.Point(0, 0); this.insts.MultiSelect = false; this.insts.Name = "insts"; this.insts.Size = new System.Drawing.Size(532, 366); this.insts.TabIndex = 4; this.insts.UseCompatibleStateImageBehavior = false; this.insts.View = System.Windows.Forms.View.Details; // // stubColumn // this.stubColumn.Text = ""; this.stubColumn.Width = 32; // // addressLC // this.addressLC.Text = "Address"; this.addressLC.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.addressLC.Width = 70; // // mnemonicLC // this.mnemonicLC.Text = "Mnemonic"; this.mnemonicLC.Width = 125; // // hexcodeLC // this.hexcodeLC.Text = "Hex"; this.hexcodeLC.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // bytesLC // this.bytesLC.Text = "Bytes"; this.bytesLC.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.bytesLC.Width = 50; // // mcycleLC // this.mcycleLC.Text = "M-Cycles"; this.mcycleLC.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.mcycleLC.Width = 75; // // tstateLC // this.tstateLC.Text = "T-States"; this.tstateLC.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.tstateLC.Width = 75; // // rightPanel // this.rightPanel.Controls.Add(this.startAddressGB); this.rightPanel.Dock = System.Windows.Forms.DockStyle.Right; this.rightPanel.Location = new System.Drawing.Point(532, 0); this.rightPanel.MinimumSize = new System.Drawing.Size(172, 281); this.rightPanel.Name = "rightPanel"; this.rightPanel.Size = new System.Drawing.Size(172, 366); this.rightPanel.TabIndex = 6; // // startAddressGB // this.startAddressGB.Controls.Add(this.startAddressBox); this.startAddressGB.Controls.Add(this.setAddressButton); this.startAddressGB.Location = new System.Drawing.Point(13, 12); this.startAddressGB.Name = "startAddressGB"; this.startAddressGB.Size = new System.Drawing.Size(146, 66); this.startAddressGB.TabIndex = 5; this.startAddressGB.TabStop = false; this.startAddressGB.Text = "Set Start Address"; // // startAddressBox // this.startAddressBox.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper; this.startAddressBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 17F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.startAddressBox.Location = new System.Drawing.Point(6, 25); this.startAddressBox.Name = "startAddressBox"; this.startAddressBox.Size = new System.Drawing.Size(62, 33); this.startAddressBox.TabIndex = 1; this.startAddressBox.TabStop = false; this.startAddressBox.Text = "0000"; this.startAddressBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.startAddressBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.startAddressBox_KeyPress); // // setAddressButton // this.setAddressButton.Location = new System.Drawing.Point(78, 25); this.setAddressButton.Name = "setAddressButton"; this.setAddressButton.Size = new System.Drawing.Size(62, 34); this.setAddressButton.TabIndex = 0; this.setAddressButton.Text = "SET"; this.setAddressButton.UseVisualStyleBackColor = true; this.setAddressButton.Click += new System.EventHandler(this.setAddressButton_Click); // // Assembler // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 18F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(704, 366); this.Controls.Add(this.insts); this.Controls.Add(this.rightPanel); this.Font = new System.Drawing.Font("Trebuchet MS", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.MaximizeBox = false; this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(720, 405); this.Name = "Assembler"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Assembler"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Assembler_FormClosing); this.Load += new System.EventHandler(this.Assembler_Load); this.rightPanel.ResumeLayout(false); this.startAddressGB.ResumeLayout(false); this.startAddressGB.PerformLayout(); this.ResumeLayout(false); } #endregion public System.Windows.Forms.ListView insts; private System.Windows.Forms.ColumnHeader stubColumn; private System.Windows.Forms.ColumnHeader addressLC; private System.Windows.Forms.ColumnHeader mnemonicLC; private System.Windows.Forms.ColumnHeader hexcodeLC; private System.Windows.Forms.ColumnHeader bytesLC; private System.Windows.Forms.ColumnHeader mcycleLC; private System.Windows.Forms.ColumnHeader tstateLC; private System.Windows.Forms.Panel rightPanel; private System.Windows.Forms.GroupBox startAddressGB; public System.Windows.Forms.TextBox startAddressBox; private System.Windows.Forms.Button setAddressButton; } }
apache-2.0
dbeaver/dbeaver
plugins/org.jkiss.dbeaver.ext.oracle/src/org/jkiss/dbeaver/ext/oracle/model/OracleTable.java
19135
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2022 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.oracle.model; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.*; import org.jkiss.dbeaver.model.data.DBDPseudoAttribute; import org.jkiss.dbeaver.model.data.DBDPseudoAttributeContainer; import org.jkiss.dbeaver.model.exec.DBCException; import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement; import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet; import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession; import org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement; import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils; import org.jkiss.dbeaver.model.meta.Association; import org.jkiss.dbeaver.model.meta.LazyProperty; import org.jkiss.dbeaver.model.meta.Property; import org.jkiss.dbeaver.model.meta.PropertyGroup; import org.jkiss.dbeaver.model.preferences.DBPPropertySource; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.utils.ByteNumberFormat; import org.jkiss.utils.CommonUtils; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; /** * OracleTable */ public class OracleTable extends OracleTablePhysical implements DBPScriptObject, DBDPseudoAttributeContainer, DBPObjectStatistics, DBPImageProvider, DBPReferentialIntegrityController { private static final Log log = Log.getLog(OracleTable.class); private static final CharSequence TABLE_NAME_PLACEHOLDER = "%table_name%"; private static final CharSequence FOREIGN_KEY_NAME_PLACEHOLDER = "%foreign_key_name%"; private static final String DISABLE_REFERENTIAL_INTEGRITY_STATEMENT = "ALTER TABLE " + TABLE_NAME_PLACEHOLDER + " MODIFY CONSTRAINT " + FOREIGN_KEY_NAME_PLACEHOLDER + " DISABLE"; private static final String ENABLE_REFERENTIAL_INTEGRITY_STATEMENT = "ALTER TABLE " + TABLE_NAME_PLACEHOLDER + " MODIFY CONSTRAINT " + FOREIGN_KEY_NAME_PLACEHOLDER + " ENABLE"; private OracleDataType tableType; private String iotType; private String iotName; private boolean temporary; private boolean secondary; private boolean nested; private transient volatile Long tableSize; public class AdditionalInfo extends TableAdditionalInfo { private int pctFree; private int pctUsed; private int iniTrans; private int maxTrans; private int initialExtent; private int nextExtent; private int minExtents; private int maxExtents; private int pctIncrease; private int freelists; private int freelistGroups; private int blocks; private int emptyBlocks; private int avgSpace; private int chainCount; private int avgRowLen; private int avgSpaceFreelistBlocks; private int numFreelistBlocks; @Property(category = DBConstants.CAT_STATISTICS, order = 31) public int getPctFree() { return pctFree; } @Property(category = DBConstants.CAT_STATISTICS, order = 32) public int getPctUsed() { return pctUsed; } @Property(category = DBConstants.CAT_STATISTICS, order = 33) public int getIniTrans() { return iniTrans; } @Property(category = DBConstants.CAT_STATISTICS, order = 34) public int getMaxTrans() { return maxTrans; } @Property(category = DBConstants.CAT_STATISTICS, order = 35) public int getInitialExtent() { return initialExtent; } @Property(category = DBConstants.CAT_STATISTICS, order = 36) public int getNextExtent() { return nextExtent; } @Property(category = DBConstants.CAT_STATISTICS, order = 37) public int getMinExtents() { return minExtents; } @Property(category = DBConstants.CAT_STATISTICS, order = 38) public int getMaxExtents() { return maxExtents; } @Property(category = DBConstants.CAT_STATISTICS, order = 39) public int getPctIncrease() { return pctIncrease; } @Property(category = DBConstants.CAT_STATISTICS, order = 40) public int getFreelists() { return freelists; } @Property(category = DBConstants.CAT_STATISTICS, order = 41) public int getFreelistGroups() { return freelistGroups; } @Property(category = DBConstants.CAT_STATISTICS, order = 42) public int getBlocks() { return blocks; } @Property(category = DBConstants.CAT_STATISTICS, order = 43) public int getEmptyBlocks() { return emptyBlocks; } @Property(category = DBConstants.CAT_STATISTICS, order = 44) public int getAvgSpace() { return avgSpace; } @Property(category = DBConstants.CAT_STATISTICS, order = 45) public int getChainCount() { return chainCount; } @Property(category = DBConstants.CAT_STATISTICS, order = 46) public int getAvgRowLen() { return avgRowLen; } @Property(category = DBConstants.CAT_STATISTICS, order = 47) public int getAvgSpaceFreelistBlocks() { return avgSpaceFreelistBlocks; } @Property(category = DBConstants.CAT_STATISTICS, order = 48) public int getNumFreelistBlocks() { return numFreelistBlocks; } } private final AdditionalInfo additionalInfo = new AdditionalInfo(); public OracleTable(OracleSchema schema, String name) { super(schema, name); } public OracleTable( DBRProgressMonitor monitor, OracleSchema schema, ResultSet dbResult) { super(schema, dbResult); String typeOwner = JDBCUtils.safeGetString(dbResult, "TABLE_TYPE_OWNER"); if (!CommonUtils.isEmpty(typeOwner)) { tableType = OracleDataType.resolveDataType( monitor, schema.getDataSource(), typeOwner, JDBCUtils.safeGetString(dbResult, "TABLE_TYPE")); } this.iotType = JDBCUtils.safeGetString(dbResult, "IOT_TYPE"); this.iotName = JDBCUtils.safeGetString(dbResult, "IOT_NAME"); this.temporary = JDBCUtils.safeGetBoolean(dbResult, "TEMPORARY", "Y"); this.secondary = JDBCUtils.safeGetBoolean(dbResult, "SECONDARY", "Y"); this.nested = JDBCUtils.safeGetBoolean(dbResult, "NESTED", "Y"); if (!CommonUtils.isEmpty(iotName)) { //this.setName(iotName); } } @Override public TableAdditionalInfo getAdditionalInfo() { return additionalInfo; } @PropertyGroup() @LazyProperty(cacheValidator = AdditionalInfoValidator.class) public AdditionalInfo getAdditionalInfo(DBRProgressMonitor monitor) throws DBException { synchronized (additionalInfo) { if (!additionalInfo.loaded && monitor != null) { loadAdditionalInfo(monitor); } return additionalInfo; } } /////////////////////////////////// // Statistics @Override public boolean hasStatistics() { return tableSize != null; } @Override public long getStatObjectSize() { return tableSize == null ? 0 : tableSize; } @Nullable @Override public DBPPropertySource getStatProperties() { return null; } @Property(viewable = false, category = DBConstants.CAT_STATISTICS, formatter = ByteNumberFormat.class) public Long getTableSize(DBRProgressMonitor monitor) throws DBCException { if (tableSize == null) { loadSize(monitor); } return tableSize; } public void setTableSize(Long tableSize) { this.tableSize = tableSize; } private void loadSize(DBRProgressMonitor monitor) throws DBCException { tableSize = null; try (JDBCSession session = DBUtils.openMetaSession(monitor, this, "Load table status")) { boolean hasDBA = getDataSource().isViewAvailable(monitor, OracleConstants.SCHEMA_SYS, "DBA_SEGMENTS"); try (JDBCPreparedStatement dbStat = session.prepareStatement( "SELECT SUM(bytes) TABLE_SIZE\n" + "FROM " + OracleUtils.getSysSchemaPrefix(getDataSource()) + (hasDBA ? "DBA_SEGMENTS" : "USER_SEGMENTS") + " s\n" + "WHERE S.SEGMENT_TYPE='TABLE' AND s.SEGMENT_NAME = ?" + (hasDBA ? " AND s.OWNER = ?" : ""))) { dbStat.setString(1, getName()); if (hasDBA) { dbStat.setString(2, getSchema().getName()); } try (JDBCResultSet dbResult = dbStat.executeQuery()) { if (dbResult.next()) { fetchTableSize(dbResult); } } } } catch (Exception e) { log.error("Error reading table statistics", e); } finally { if (tableSize == null) { tableSize = 0L; } } } void fetchTableSize(JDBCResultSet dbResult) throws SQLException { tableSize = dbResult.getLong("TABLE_SIZE"); } @Override protected String getTableTypeName() { return "TABLE"; } @Override public boolean isView() { return false; } @Property(viewable = false, order = 5) public OracleDataType getTableType() { return tableType; } @Property(viewable = false, order = 6) public String getIotType() { return iotType; } @Property(viewable = false, order = 7) public String getIotName() { return iotName; } @Property(viewable = false, order = 10) public boolean isTemporary() { return temporary; } @Property(viewable = false, order = 11) public boolean isSecondary() { return secondary; } @Property(viewable = false, order = 12) public boolean isNested() { return nested; } @Override public OracleTableColumn getAttribute(@NotNull DBRProgressMonitor monitor, @NotNull String attributeName) throws DBException { /* // Fake XML attribute handle if (tableType != null && tableType.getName().equals(OracleConstants.TYPE_NAME_XML) && OracleConstants.XML_COLUMN_NAME.equals(attributeName)) { OracleTableColumn col = getXMLColumn(monitor); if (col != null) return col; } */ return super.getAttribute(monitor, attributeName); } @Nullable private OracleTableColumn getXMLColumn(DBRProgressMonitor monitor) throws DBException { for (OracleTableColumn col : CommonUtils.safeCollection(getAttributes(monitor))) { if (col.getDataType() == tableType) { return col; } } return null; } @Override public Collection<OracleTableForeignKey> getReferences(@NotNull DBRProgressMonitor monitor) throws DBException { List<OracleTableForeignKey> refs = new ArrayList<>(); // This is dummy implementation // Get references from this schema only final Collection<OracleTableForeignKey> allForeignKeys = getContainer().foreignKeyCache.getObjects(monitor, getContainer(), null); for (OracleTableForeignKey constraint : allForeignKeys) { if (constraint.getReferencedTable() == this) { refs.add(constraint); } } return refs; } @Override @Association public Collection<OracleTableForeignKey> getAssociations(@NotNull DBRProgressMonitor monitor) throws DBException { return getContainer().foreignKeyCache.getObjects(monitor, getContainer(), this); } @Override public DBSObject refreshObject(@NotNull DBRProgressMonitor monitor) throws DBException { getContainer().foreignKeyCache.clearObjectCache(this); tableSize = null; return super.refreshObject(monitor); } @Override public DBDPseudoAttribute[] getPseudoAttributes() throws DBException { if (CommonUtils.isEmpty(this.iotType) && getDataSource().getContainer().getPreferenceStore().getBoolean(OracleConstants.PREF_SUPPORT_ROWID)) { // IOT tables have index id instead of ROWID return new DBDPseudoAttribute[] { OracleConstants.PSEUDO_ATTR_ROWID }; } else { return null; } } @Override protected void appendSelectSource(DBRProgressMonitor monitor, StringBuilder query, String tableAlias, DBDPseudoAttribute rowIdAttribute) { if (tableType != null && tableType.getName().equals(OracleConstants.TYPE_NAME_XML)) { try { OracleTableColumn xmlColumn = getXMLColumn(monitor); if (xmlColumn != null) { query.append("XMLType(").append(tableAlias).append(".").append(xmlColumn.getName()).append(".getClobval()) as ").append(xmlColumn.getName()); if (rowIdAttribute != null) { query.append(",").append(rowIdAttribute.translateExpression(tableAlias)); } return; } } catch (DBException e) { log.warn(e); } } super.appendSelectSource(monitor, query, tableAlias, rowIdAttribute); } @Override public String getObjectDefinitionText(DBRProgressMonitor monitor, Map<String, Object> options) throws DBException { return getDDL(monitor, OracleDDLFormat.getCurrentFormat(getDataSource()), options); } @Nullable @Override public DBPImage getObjectImage() { if (CommonUtils.isEmpty(iotType)) { return DBIcon.TREE_TABLE; } else { return DBIcon.TREE_TABLE_INDEX; } } private void loadAdditionalInfo(DBRProgressMonitor monitor) throws DBException { if (!isPersisted()) { additionalInfo.loaded = true; return; } try (JDBCSession session = DBUtils.openMetaSession(monitor, this, "Load table status")) { try (JDBCPreparedStatement dbStat = session.prepareStatement( "SELECT * FROM " + OracleUtils.getAdminAllViewPrefix(monitor, getDataSource(), "TABLES") + " WHERE OWNER=? AND TABLE_NAME=?")) { dbStat.setString(1, getContainer().getName()); dbStat.setString(2, getName()); try (JDBCResultSet dbResult = dbStat.executeQuery()) { if (dbResult.next()) { additionalInfo.pctFree = JDBCUtils.safeGetInt(dbResult, "PCT_FREE"); additionalInfo.pctUsed = JDBCUtils.safeGetInt(dbResult, "PCT_USED"); additionalInfo.iniTrans = JDBCUtils.safeGetInt(dbResult, "INI_TRANS"); additionalInfo.maxTrans = JDBCUtils.safeGetInt(dbResult, "MAX_TRANS"); additionalInfo.initialExtent = JDBCUtils.safeGetInt(dbResult, "INITIAL_EXTENT"); additionalInfo.nextExtent = JDBCUtils.safeGetInt(dbResult, "NEXT_EXTENT"); additionalInfo.minExtents = JDBCUtils.safeGetInt(dbResult, "MIN_EXTENTS"); additionalInfo.maxExtents = JDBCUtils.safeGetInt(dbResult, "MAX_EXTENTS"); additionalInfo.pctIncrease = JDBCUtils.safeGetInt(dbResult, "PCT_INCREASE"); additionalInfo.freelists = JDBCUtils.safeGetInt(dbResult, "FREELISTS"); additionalInfo.freelistGroups = JDBCUtils.safeGetInt(dbResult, "FREELIST_GROUPS"); additionalInfo.blocks = JDBCUtils.safeGetInt(dbResult, "BLOCKS"); additionalInfo.emptyBlocks = JDBCUtils.safeGetInt(dbResult, "EMPTY_BLOCKS"); additionalInfo.avgSpace = JDBCUtils.safeGetInt(dbResult, "AVG_SPACE"); additionalInfo.chainCount = JDBCUtils.safeGetInt(dbResult, "CHAIN_CNT"); additionalInfo.avgRowLen = JDBCUtils.safeGetInt(dbResult, "AVG_ROW_LEN"); additionalInfo.avgSpaceFreelistBlocks = JDBCUtils.safeGetInt(dbResult, "AVG_SPACE_FREELIST_BLOCKS"); additionalInfo.numFreelistBlocks = JDBCUtils.safeGetInt(dbResult, "NUM_FREELIST_BLOCKS"); } else { log.warn("Cannot find table '" + getFullyQualifiedName(DBPEvaluationContext.UI) + "' metadata"); } additionalInfo.loaded = true; } } catch (SQLException e) { throw new DBCException(e, session.getExecutionContext()); } } } @Override public void enableReferentialIntegrity(@NotNull DBRProgressMonitor monitor, boolean enable) throws DBException { Collection<OracleTableForeignKey> foreignKeys = getAssociations(monitor); if (CommonUtils.isEmpty(foreignKeys)) { return; } String template; if (enable) { template = ENABLE_REFERENTIAL_INTEGRITY_STATEMENT; } else { template = DISABLE_REFERENTIAL_INTEGRITY_STATEMENT; } template = template.replace(TABLE_NAME_PLACEHOLDER, getFullyQualifiedName(DBPEvaluationContext.DDL)); try (JDBCSession session = DBUtils.openMetaSession(monitor, this, "Changing referential integrity")) { try (JDBCStatement statement = session.createStatement()) { for (DBPNamedObject fk: foreignKeys) { String sql = template.replace(FOREIGN_KEY_NAME_PLACEHOLDER, fk.getName()); statement.executeUpdate(sql); } } catch (SQLException e) { throw new DBException("Unable to change referential integrity", e); } } } @Override public boolean supportsChangingReferentialIntegrity(@NotNull DBRProgressMonitor monitor) throws DBException { return !CommonUtils.isEmpty(getAssociations(monitor)); } @Nullable @Override public String getChangeReferentialIntegrityStatement(@NotNull DBRProgressMonitor monitor, boolean enable) throws DBException { if (!supportsChangingReferentialIntegrity(monitor)) { return null; } if (enable) { return ENABLE_REFERENTIAL_INTEGRITY_STATEMENT; } return DISABLE_REFERENTIAL_INTEGRITY_STATEMENT; } }
apache-2.0
senotrusov/rubymq
lib/rubymq/tcp_transport/transmiting.rb
1109
# # Copyright 2006-2008 Stanislav Senotrusov <senotrusov@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module RubyMQ::TCPTransport::Transmiting def send frame @socket.write frame.bytestream end def recv frame = RubyMQ::IncomingFrame.new(@socket.read_with_timeout(RubyMQ::IncomingFrame::INITIAL_OCTETS, @timeout, &@timeout_callback)) frame.payload = @socket.read_with_timeout(frame.payload_length, @timeout, &@timeout_callback) frame end def inspect "#{self.class} peer:#{(@socket.peeraddr rescue (["AF_INET", @port, @address])).inspect}" end end
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-cloudidentity/v1/1.30.1/com/google/api/services/cloudidentity/v1/model/GoogleAppsCloudidentityDevicesV1ApproveDeviceUserRequest.java
3295
/* * 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 code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.cloudidentity.v1.model; /** * Request message for approving the device to access user data. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Identity API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleAppsCloudidentityDevicesV1ApproveDeviceUserRequest extends com.google.api.client.json.GenericJson { /** * Required. [Resource name](https://cloud.google.com/apis/design/resource_names) of the customer. * If you're using this API for your own organization, use `customers/my_customer` If you're using * this API to manage another organization, use `customers/{customer_id}`, where customer_id is * the customer to whom the device belongs. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String customer; /** * Required. [Resource name](https://cloud.google.com/apis/design/resource_names) of the customer. * If you're using this API for your own organization, use `customers/my_customer` If you're using * this API to manage another organization, use `customers/{customer_id}`, where customer_id is * the customer to whom the device belongs. * @return value or {@code null} for none */ public java.lang.String getCustomer() { return customer; } /** * Required. [Resource name](https://cloud.google.com/apis/design/resource_names) of the customer. * If you're using this API for your own organization, use `customers/my_customer` If you're using * this API to manage another organization, use `customers/{customer_id}`, where customer_id is * the customer to whom the device belongs. * @param customer customer or {@code null} for none */ public GoogleAppsCloudidentityDevicesV1ApproveDeviceUserRequest setCustomer(java.lang.String customer) { this.customer = customer; return this; } @Override public GoogleAppsCloudidentityDevicesV1ApproveDeviceUserRequest set(String fieldName, Object value) { return (GoogleAppsCloudidentityDevicesV1ApproveDeviceUserRequest) super.set(fieldName, value); } @Override public GoogleAppsCloudidentityDevicesV1ApproveDeviceUserRequest clone() { return (GoogleAppsCloudidentityDevicesV1ApproveDeviceUserRequest) super.clone(); } }
apache-2.0
ruspl-afed/dbeaver
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/exec/DBCExecutionPurpose.java
1782
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org) * * 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.jkiss.dbeaver.model.exec; /** * Execution purpose. * * Each query which executed withing application have some purpose. * Some of queries are instantiated by user, some are executed internally to obtain metadata, etc. * This enum defines different query purposes. * * Note: for sure, we can't detect ALL executed queries. Some of them are executed by drivers internally, * some are executed by plugins and not reported to query manager. */ public enum DBCExecutionPurpose { USER(true), // User query USER_FILTERED(true), // User query with additional filters USER_SCRIPT(true), // User script query UTIL(false), // Utility query (utility method initialized by user) META(false), // Metadata query, processed by data source providers internally META_DDL(false),; private final boolean user; DBCExecutionPurpose(boolean user) { this.user = user; } public boolean isUser() { return user; } // Metadata modifications (DDL) }
apache-2.0
leafclick/intellij-community
java/java-impl/src/com/intellij/refactoring/replaceConstructorWithBuilder/ReplaceConstructorWithBuilderHandler.java
3071
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring.replaceConstructorWithBuilder; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.HelpID; import com.intellij.refactoring.RefactoringActionHandler; import com.intellij.refactoring.util.CommonRefactoringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class ReplaceConstructorWithBuilderHandler implements RefactoringActionHandler { @Override public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file, final DataContext dataContext) { final int offset = editor.getCaretModel().getOffset(); final PsiElement element = file.findElementAt(offset); final PsiClass psiClass = getParentNamedClass(element); if (psiClass == null) { showErrorMessage("The caret should be positioned inside a class which constructors are to be replaced with builder.", project, editor); return; } final PsiMethod[] constructors = psiClass.getConstructors(); if (constructors.length == 0) { showErrorMessage("Current class doesn't have constructors to replace with builder.", project, editor); return; } new ReplaceConstructorWithBuilderDialog(project, constructors).show(); } @Nullable public static PsiClass getParentNamedClass(PsiElement element) { if (element != null) { final PsiElement parent = element.getParent(); if (parent instanceof PsiJavaCodeReferenceElement) { final PsiElement resolve = ((PsiJavaCodeReferenceElement)parent).resolve(); if (resolve instanceof PsiClass) return (PsiClass)resolve; } } final PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class); if (psiClass instanceof PsiAnonymousClass) { return getParentNamedClass(psiClass); } return psiClass; } @Override public void invoke(@NotNull final Project project, final PsiElement @NotNull [] elements, final DataContext dataContext) { throw new UnsupportedOperationException(); } private static void showErrorMessage(String message, Project project, Editor editor) { CommonRefactoringUtil.showErrorHint(project, editor, message, ReplaceConstructorWithBuilderProcessor.REFACTORING_NAME, HelpID.REPLACE_CONSTRUCTOR_WITH_BUILDER); } }
apache-2.0
chengduoZH/Paddle
paddle/fluid/operators/quantize_op.cc
1722
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "paddle/fluid/operators/quantize_op.h" #ifdef PADDLE_WITH_MKLDNN #include "paddle/fluid/platform/mkldnn_helper.h" #endif namespace paddle { namespace operators { framework::OpKernelType QuantOp::GetExpectedKernelType( const framework::ExecutionContext& ctx) const { framework::LibraryType library_ = framework::LibraryType::kMKLDNN; framework::DataLayout layout_ = framework::DataLayout::kMKLDNN; return framework::OpKernelType( OperatorWithKernel::IndicateVarDataType(ctx, "Input"), ctx.GetPlace(), layout_, library_); } void QuantOpMaker::Make() { AddInput("Input", "input data"); AddOutput("Output", "output data"); AddAttr<bool>("is_negative_input", "(bool, default false) Only used in mkldnn INT8 kernel") .SetDefault(false); AddAttr<float>("Scale", "scale data").SetDefault({1.0f}); AddComment(R"DOC(This op will quantize data from FP32 to INT8)DOC"); } } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(quantize, ops::QuantOp, ops::QuantOpMaker);
apache-2.0
UnquietCode/UQCLib
src/main/java/unquietcode/stately/closure/Closure0.java
1091
/******************************************************************************* Copyright 2009-2011 Benjamin Fagin 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. Read the included LICENSE.TXT for more information. ******************************************************************************/ package unquietcode.stately.closure; import unquietcode.stately.closure.view.Closure0View; import unquietcode.stately.closure.view.ClosureView; /** * @author Benjamin Fagin * @version 01-23-2011 */ public interface Closure0<Z> extends ClosureInterfaceBase<Z> { Z run(); Closure0View<Z> getView(); }
apache-2.0
dbflute-test/dbflute-test-dbms-mysql
src/main/java/org/docksidestage/mysql/dbflute/cbean/cq/bs/AbstractBsWhiteEscapedNumberInitialCQ.java
32178
/* * Copyright 2004-2013 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.docksidestage.mysql.dbflute.cbean.cq.bs; import java.util.*; import org.dbflute.cbean.*; import org.dbflute.cbean.chelper.*; import org.dbflute.cbean.ckey.*; import org.dbflute.cbean.coption.*; import org.dbflute.cbean.cvalue.ConditionValue; import org.dbflute.cbean.ordering.*; import org.dbflute.cbean.scoping.*; import org.dbflute.cbean.sqlclause.SqlClause; import org.dbflute.dbmeta.DBMetaProvider; import org.docksidestage.mysql.dbflute.allcommon.*; import org.docksidestage.mysql.dbflute.cbean.*; import org.docksidestage.mysql.dbflute.cbean.cq.*; /** * The abstract condition-query of white_escaped_number_initial. * @author DBFlute(AutoGenerator) */ public abstract class AbstractBsWhiteEscapedNumberInitialCQ extends AbstractConditionQuery { // =================================================================================== // Constructor // =========== public AbstractBsWhiteEscapedNumberInitialCQ(ConditionQuery referrerQuery, SqlClause sqlClause, String aliasName, int nestLevel) { super(referrerQuery, sqlClause, aliasName, nestLevel); } // =================================================================================== // DB Meta // ======= @Override protected DBMetaProvider xgetDBMetaProvider() { return DBMetaInstanceHandler.getProvider(); } public String asTableDbName() { return "white_escaped_number_initial"; } // =================================================================================== // Query // ===== /** * Equal(=). And NullOrEmptyIgnored, OnlyOnceRegistered. <br> * NUMBER_INITIAL_CODE: {PK, NotNull, CHAR(3), classification=EscapedNumberInitialCls} * @param numberInitialCode The value of numberInitialCode as equal. (basically NotNull, NotEmpty: error as default, or no condition as option) */ protected void setNumberInitialCode_Equal(String numberInitialCode) { doSetNumberInitialCode_Equal(fRES(numberInitialCode)); } /** * Equal(=). As EscapedNumberInitialCls. And NullOrEmptyIgnored, OnlyOnceRegistered. <br> * NUMBER_INITIAL_CODE: {PK, NotNull, CHAR(3), classification=EscapedNumberInitialCls} <br> * 6 * @param cdef The instance of classification definition (as ENUM type). (basically NotNull: error as default, or no condition as option) */ public void setNumberInitialCode_Equal_AsEscapedNumberInitialCls(CDef.EscapedNumberInitialCls cdef) { doSetNumberInitialCode_Equal(cdef != null ? cdef.code() : null); } /** * Equal(=). As N1Foo (1FO). And OnlyOnceRegistered. <br> * 1Foo */ public void setNumberInitialCode_Equal_N1Foo() { setNumberInitialCode_Equal_AsEscapedNumberInitialCls(CDef.EscapedNumberInitialCls.N1Foo); } /** * Equal(=). As N3Bar (3BA). And OnlyOnceRegistered. <br> * 3Bar */ public void setNumberInitialCode_Equal_N3Bar() { setNumberInitialCode_Equal_AsEscapedNumberInitialCls(CDef.EscapedNumberInitialCls.N3Bar); } /** * Equal(=). As N7Qux (7QU). And OnlyOnceRegistered. <br> * 7Qux */ public void setNumberInitialCode_Equal_N7Qux() { setNumberInitialCode_Equal_AsEscapedNumberInitialCls(CDef.EscapedNumberInitialCls.N7Qux); } /** * Equal(=). As Corge9 (CO9). And OnlyOnceRegistered. <br> * Corge9 */ public void setNumberInitialCode_Equal_Corge9() { setNumberInitialCode_Equal_AsEscapedNumberInitialCls(CDef.EscapedNumberInitialCls.Corge9); } protected void doSetNumberInitialCode_Equal(String numberInitialCode) { regNumberInitialCode(CK_EQ, numberInitialCode); } /** * NotEqual(&lt;&gt;). And NullOrEmptyIgnored, OnlyOnceRegistered. <br> * NUMBER_INITIAL_CODE: {PK, NotNull, CHAR(3), classification=EscapedNumberInitialCls} * @param numberInitialCode The value of numberInitialCode as notEqual. (basically NotNull, NotEmpty: error as default, or no condition as option) */ protected void setNumberInitialCode_NotEqual(String numberInitialCode) { doSetNumberInitialCode_NotEqual(fRES(numberInitialCode)); } /** * NotEqual(&lt;&gt;). As EscapedNumberInitialCls. And NullOrEmptyIgnored, OnlyOnceRegistered. <br> * NUMBER_INITIAL_CODE: {PK, NotNull, CHAR(3), classification=EscapedNumberInitialCls} <br> * 6 * @param cdef The instance of classification definition (as ENUM type). (basically NotNull: error as default, or no condition as option) */ public void setNumberInitialCode_NotEqual_AsEscapedNumberInitialCls(CDef.EscapedNumberInitialCls cdef) { doSetNumberInitialCode_NotEqual(cdef != null ? cdef.code() : null); } /** * NotEqual(&lt;&gt;). As N1Foo (1FO). And OnlyOnceRegistered. <br> * 1Foo */ public void setNumberInitialCode_NotEqual_N1Foo() { setNumberInitialCode_NotEqual_AsEscapedNumberInitialCls(CDef.EscapedNumberInitialCls.N1Foo); } /** * NotEqual(&lt;&gt;). As N3Bar (3BA). And OnlyOnceRegistered. <br> * 3Bar */ public void setNumberInitialCode_NotEqual_N3Bar() { setNumberInitialCode_NotEqual_AsEscapedNumberInitialCls(CDef.EscapedNumberInitialCls.N3Bar); } /** * NotEqual(&lt;&gt;). As N7Qux (7QU). And OnlyOnceRegistered. <br> * 7Qux */ public void setNumberInitialCode_NotEqual_N7Qux() { setNumberInitialCode_NotEqual_AsEscapedNumberInitialCls(CDef.EscapedNumberInitialCls.N7Qux); } /** * NotEqual(&lt;&gt;). As Corge9 (CO9). And OnlyOnceRegistered. <br> * Corge9 */ public void setNumberInitialCode_NotEqual_Corge9() { setNumberInitialCode_NotEqual_AsEscapedNumberInitialCls(CDef.EscapedNumberInitialCls.Corge9); } protected void doSetNumberInitialCode_NotEqual(String numberInitialCode) { regNumberInitialCode(CK_NES, numberInitialCode); } /** * InScope {in ('a', 'b')}. And NullOrEmptyIgnored, NullOrEmptyElementIgnored, SeveralRegistered. <br> * NUMBER_INITIAL_CODE: {PK, NotNull, CHAR(3), classification=EscapedNumberInitialCls} * @param numberInitialCodeList The collection of numberInitialCode as inScope. (basically NotNull, NotEmpty: error as default, or no condition as option) */ protected void setNumberInitialCode_InScope(Collection<String> numberInitialCodeList) { doSetNumberInitialCode_InScope(numberInitialCodeList); } /** * InScope {in ('a', 'b')}. As EscapedNumberInitialCls. And NullOrEmptyIgnored, NullOrEmptyElementIgnored, SeveralRegistered. <br> * NUMBER_INITIAL_CODE: {PK, NotNull, CHAR(3), classification=EscapedNumberInitialCls} <br> * 6 * @param cdefList The list of classification definition (as ENUM type). (basically NotNull, NotEmpty: error as default, or no condition as option) */ public void setNumberInitialCode_InScope_AsEscapedNumberInitialCls(Collection<CDef.EscapedNumberInitialCls> cdefList) { doSetNumberInitialCode_InScope(cTStrL(cdefList)); } protected void doSetNumberInitialCode_InScope(Collection<String> numberInitialCodeList) { regINS(CK_INS, cTL(numberInitialCodeList), xgetCValueNumberInitialCode(), "NUMBER_INITIAL_CODE"); } /** * NotInScope {not in ('a', 'b')}. And NullOrEmptyIgnored, NullOrEmptyElementIgnored, SeveralRegistered. <br> * NUMBER_INITIAL_CODE: {PK, NotNull, CHAR(3), classification=EscapedNumberInitialCls} * @param numberInitialCodeList The collection of numberInitialCode as notInScope. (basically NotNull, NotEmpty: error as default, or no condition as option) */ protected void setNumberInitialCode_NotInScope(Collection<String> numberInitialCodeList) { doSetNumberInitialCode_NotInScope(numberInitialCodeList); } /** * NotInScope {not in ('a', 'b')}. As EscapedNumberInitialCls. And NullOrEmptyIgnored, NullOrEmptyElementIgnored, SeveralRegistered. <br> * NUMBER_INITIAL_CODE: {PK, NotNull, CHAR(3), classification=EscapedNumberInitialCls} <br> * 6 * @param cdefList The list of classification definition (as ENUM type). (basically NotNull, NotEmpty: error as default, or no condition as option) */ public void setNumberInitialCode_NotInScope_AsEscapedNumberInitialCls(Collection<CDef.EscapedNumberInitialCls> cdefList) { doSetNumberInitialCode_NotInScope(cTStrL(cdefList)); } protected void doSetNumberInitialCode_NotInScope(Collection<String> numberInitialCodeList) { regINS(CK_NINS, cTL(numberInitialCodeList), xgetCValueNumberInitialCode(), "NUMBER_INITIAL_CODE"); } /** * IsNull {is null}. And OnlyOnceRegistered. <br> * NUMBER_INITIAL_CODE: {PK, NotNull, CHAR(3), classification=EscapedNumberInitialCls} */ public void setNumberInitialCode_IsNull() { regNumberInitialCode(CK_ISN, DOBJ); } /** * IsNotNull {is not null}. And OnlyOnceRegistered. <br> * NUMBER_INITIAL_CODE: {PK, NotNull, CHAR(3), classification=EscapedNumberInitialCls} */ public void setNumberInitialCode_IsNotNull() { regNumberInitialCode(CK_ISNN, DOBJ); } protected void regNumberInitialCode(ConditionKey ky, Object vl) { regQ(ky, vl, xgetCValueNumberInitialCode(), "NUMBER_INITIAL_CODE"); } protected abstract ConditionValue xgetCValueNumberInitialCode(); /** * Equal(=). And NullOrEmptyIgnored, OnlyOnceRegistered. <br> * NUMBER_INITIAL_NAME: {VARCHAR(20)} * @param numberInitialName The value of numberInitialName as equal. (basically NotNull, NotEmpty: error as default, or no condition as option) */ public void setNumberInitialName_Equal(String numberInitialName) { doSetNumberInitialName_Equal(fRES(numberInitialName)); } protected void doSetNumberInitialName_Equal(String numberInitialName) { regNumberInitialName(CK_EQ, numberInitialName); } /** * NotEqual(&lt;&gt;). And NullOrEmptyIgnored, OnlyOnceRegistered. <br> * NUMBER_INITIAL_NAME: {VARCHAR(20)} * @param numberInitialName The value of numberInitialName as notEqual. (basically NotNull, NotEmpty: error as default, or no condition as option) */ public void setNumberInitialName_NotEqual(String numberInitialName) { doSetNumberInitialName_NotEqual(fRES(numberInitialName)); } protected void doSetNumberInitialName_NotEqual(String numberInitialName) { regNumberInitialName(CK_NES, numberInitialName); } /** * InScope {in ('a', 'b')}. And NullOrEmptyIgnored, NullOrEmptyElementIgnored, SeveralRegistered. <br> * NUMBER_INITIAL_NAME: {VARCHAR(20)} * @param numberInitialNameList The collection of numberInitialName as inScope. (basically NotNull, NotEmpty: error as default, or no condition as option) */ public void setNumberInitialName_InScope(Collection<String> numberInitialNameList) { doSetNumberInitialName_InScope(numberInitialNameList); } protected void doSetNumberInitialName_InScope(Collection<String> numberInitialNameList) { regINS(CK_INS, cTL(numberInitialNameList), xgetCValueNumberInitialName(), "NUMBER_INITIAL_NAME"); } /** * NotInScope {not in ('a', 'b')}. And NullOrEmptyIgnored, NullOrEmptyElementIgnored, SeveralRegistered. <br> * NUMBER_INITIAL_NAME: {VARCHAR(20)} * @param numberInitialNameList The collection of numberInitialName as notInScope. (basically NotNull, NotEmpty: error as default, or no condition as option) */ public void setNumberInitialName_NotInScope(Collection<String> numberInitialNameList) { doSetNumberInitialName_NotInScope(numberInitialNameList); } protected void doSetNumberInitialName_NotInScope(Collection<String> numberInitialNameList) { regINS(CK_NINS, cTL(numberInitialNameList), xgetCValueNumberInitialName(), "NUMBER_INITIAL_NAME"); } /** * LikeSearch with various options. (versatile) {like '%xxx%' escape ...}. And NullOrEmptyIgnored, SeveralRegistered. <br> * NUMBER_INITIAL_NAME: {VARCHAR(20)} <br> * <pre>e.g. setNumberInitialName_LikeSearch("xxx", op <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> op.<span style="color: #CC4747">likeContain()</span>);</pre> * @param numberInitialName The value of numberInitialName as likeSearch. (basically NotNull, NotEmpty: error as default, or no condition as option) * @param opLambda The callback for option of like-search. (NotNull) */ public void setNumberInitialName_LikeSearch(String numberInitialName, ConditionOptionCall<LikeSearchOption> opLambda) { setNumberInitialName_LikeSearch(numberInitialName, xcLSOP(opLambda)); } /** * LikeSearch with various options. (versatile) {like '%xxx%' escape ...}. And NullOrEmptyIgnored, SeveralRegistered. <br> * NUMBER_INITIAL_NAME: {VARCHAR(20)} <br> * <pre>e.g. setNumberInitialName_LikeSearch("xxx", new <span style="color: #CC4747">LikeSearchOption</span>().likeContain());</pre> * @param numberInitialName The value of numberInitialName as likeSearch. (basically NotNull, NotEmpty: error as default, or no condition as option) * @param likeSearchOption The option of like-search. (NotNull) */ public void setNumberInitialName_LikeSearch(String numberInitialName, LikeSearchOption likeSearchOption) { regLSQ(CK_LS, fRES(numberInitialName), xgetCValueNumberInitialName(), "NUMBER_INITIAL_NAME", likeSearchOption); } /** * NotLikeSearch with various options. (versatile) {not like 'xxx%' escape ...} <br> * And NullOrEmptyIgnored, SeveralRegistered. <br> * NUMBER_INITIAL_NAME: {VARCHAR(20)} * @param numberInitialName The value of numberInitialName as notLikeSearch. (basically NotNull, NotEmpty: error as default, or no condition as option) * @param opLambda The callback for option of like-search. (NotNull) */ public void setNumberInitialName_NotLikeSearch(String numberInitialName, ConditionOptionCall<LikeSearchOption> opLambda) { setNumberInitialName_NotLikeSearch(numberInitialName, xcLSOP(opLambda)); } /** * NotLikeSearch with various options. (versatile) {not like 'xxx%' escape ...} <br> * And NullOrEmptyIgnored, SeveralRegistered. <br> * NUMBER_INITIAL_NAME: {VARCHAR(20)} * @param numberInitialName The value of numberInitialName as notLikeSearch. (basically NotNull, NotEmpty: error as default, or no condition as option) * @param likeSearchOption The option of not-like-search. (NotNull) */ public void setNumberInitialName_NotLikeSearch(String numberInitialName, LikeSearchOption likeSearchOption) { regLSQ(CK_NLS, fRES(numberInitialName), xgetCValueNumberInitialName(), "NUMBER_INITIAL_NAME", likeSearchOption); } /** * IsNull {is null}. And OnlyOnceRegistered. <br> * NUMBER_INITIAL_NAME: {VARCHAR(20)} */ public void setNumberInitialName_IsNull() { regNumberInitialName(CK_ISN, DOBJ); } /** * IsNullOrEmpty {is null or empty}. And OnlyOnceRegistered. <br> * NUMBER_INITIAL_NAME: {VARCHAR(20)} */ public void setNumberInitialName_IsNullOrEmpty() { regNumberInitialName(CK_ISNOE, DOBJ); } /** * IsNotNull {is not null}. And OnlyOnceRegistered. <br> * NUMBER_INITIAL_NAME: {VARCHAR(20)} */ public void setNumberInitialName_IsNotNull() { regNumberInitialName(CK_ISNN, DOBJ); } protected void regNumberInitialName(ConditionKey ky, Object vl) { regQ(ky, vl, xgetCValueNumberInitialName(), "NUMBER_INITIAL_NAME"); } protected abstract ConditionValue xgetCValueNumberInitialName(); // =================================================================================== // ScalarCondition // =============== /** * Prepare ScalarCondition as equal. <br> * {where FOO = (select max(BAR) from ...)} * <pre> * cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span> * <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True(); * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSLCFunction<WhiteEscapedNumberInitialCB> scalar_Equal() { return xcreateSLCFunction(CK_EQ, WhiteEscapedNumberInitialCB.class); } /** * Prepare ScalarCondition as equal. <br> * {where FOO &lt;&gt; (select max(BAR) from ...)} * <pre> * cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span> * <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True(); * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSLCFunction<WhiteEscapedNumberInitialCB> scalar_NotEqual() { return xcreateSLCFunction(CK_NES, WhiteEscapedNumberInitialCB.class); } /** * Prepare ScalarCondition as greaterThan. <br> * {where FOO &gt; (select max(BAR) from ...)} * <pre> * cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span> * <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True(); * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSLCFunction<WhiteEscapedNumberInitialCB> scalar_GreaterThan() { return xcreateSLCFunction(CK_GT, WhiteEscapedNumberInitialCB.class); } /** * Prepare ScalarCondition as lessThan. <br> * {where FOO &lt; (select max(BAR) from ...)} * <pre> * cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span> * <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True(); * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSLCFunction<WhiteEscapedNumberInitialCB> scalar_LessThan() { return xcreateSLCFunction(CK_LT, WhiteEscapedNumberInitialCB.class); } /** * Prepare ScalarCondition as greaterEqual. <br> * {where FOO &gt;= (select max(BAR) from ...)} * <pre> * cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span> * <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True(); * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSLCFunction<WhiteEscapedNumberInitialCB> scalar_GreaterEqual() { return xcreateSLCFunction(CK_GE, WhiteEscapedNumberInitialCB.class); } /** * Prepare ScalarCondition as lessEqual. <br> * {where FOO &lt;= (select max(BAR) from ...)} * <pre> * cb.query().<span style="color: #CC4747">scalar_LessEqual()</span>.max(new SubQuery&lt;WhiteEscapedNumberInitialCB&gt;() { * public void query(WhiteEscapedNumberInitialCB subCB) { * subCB.specify().setFoo... <span style="color: #3F7E5E">// derived column for function</span> * subCB.query().setBar... * } * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSLCFunction<WhiteEscapedNumberInitialCB> scalar_LessEqual() { return xcreateSLCFunction(CK_LE, WhiteEscapedNumberInitialCB.class); } @SuppressWarnings("unchecked") protected <CB extends ConditionBean> void xscalarCondition(String fn, SubQuery<CB> sq, String rd, HpSLCCustomized<CB> cs, ScalarConditionOption op) { assertObjectNotNull("subQuery", sq); WhiteEscapedNumberInitialCB cb = xcreateScalarConditionCB(); sq.query((CB)cb); String pp = keepScalarCondition(cb.query()); // for saving query-value cs.setPartitionByCBean((CB)xcreateScalarConditionPartitionByCB()); // for using partition-by registerScalarCondition(fn, cb.query(), pp, rd, cs, op); } public abstract String keepScalarCondition(WhiteEscapedNumberInitialCQ sq); protected WhiteEscapedNumberInitialCB xcreateScalarConditionCB() { WhiteEscapedNumberInitialCB cb = newMyCB(); cb.xsetupForScalarCondition(this); return cb; } protected WhiteEscapedNumberInitialCB xcreateScalarConditionPartitionByCB() { WhiteEscapedNumberInitialCB cb = newMyCB(); cb.xsetupForScalarConditionPartitionBy(this); return cb; } // =================================================================================== // MyselfDerived // ============= public void xsmyselfDerive(String fn, SubQuery<WhiteEscapedNumberInitialCB> sq, String al, DerivedReferrerOption op) { assertObjectNotNull("subQuery", sq); WhiteEscapedNumberInitialCB cb = new WhiteEscapedNumberInitialCB(); cb.xsetupForDerivedReferrer(this); lockCall(() -> sq.query(cb)); String pp = keepSpecifyMyselfDerived(cb.query()); String pk = "NUMBER_INITIAL_CODE"; registerSpecifyMyselfDerived(fn, cb.query(), pk, pk, pp, "myselfDerived", al, op); } public abstract String keepSpecifyMyselfDerived(WhiteEscapedNumberInitialCQ sq); /** * Prepare for (Query)MyselfDerived (correlated sub-query). * @return The object to set up a function for myself table. (NotNull) */ public HpQDRFunction<WhiteEscapedNumberInitialCB> myselfDerived() { return xcreateQDRFunctionMyselfDerived(WhiteEscapedNumberInitialCB.class); } @SuppressWarnings("unchecked") protected <CB extends ConditionBean> void xqderiveMyselfDerived(String fn, SubQuery<CB> sq, String rd, Object vl, DerivedReferrerOption op) { assertObjectNotNull("subQuery", sq); WhiteEscapedNumberInitialCB cb = new WhiteEscapedNumberInitialCB(); cb.xsetupForDerivedReferrer(this); sq.query((CB)cb); String pk = "NUMBER_INITIAL_CODE"; String sqpp = keepQueryMyselfDerived(cb.query()); // for saving query-value. String prpp = keepQueryMyselfDerivedParameter(vl); registerQueryMyselfDerived(fn, cb.query(), pk, pk, sqpp, "myselfDerived", rd, vl, prpp, op); } public abstract String keepQueryMyselfDerived(WhiteEscapedNumberInitialCQ sq); public abstract String keepQueryMyselfDerivedParameter(Object vl); // =================================================================================== // MyselfExists // ============ /** * Prepare for MyselfExists (correlated sub-query). * @param subCBLambda The implementation of sub-query. (NotNull) */ public void myselfExists(SubQuery<WhiteEscapedNumberInitialCB> subCBLambda) { assertObjectNotNull("subCBLambda", subCBLambda); WhiteEscapedNumberInitialCB cb = new WhiteEscapedNumberInitialCB(); cb.xsetupForMyselfExists(this); lockCall(() -> subCBLambda.query(cb)); String pp = keepMyselfExists(cb.query()); registerMyselfExists(cb.query(), pp); } public abstract String keepMyselfExists(WhiteEscapedNumberInitialCQ sq); // =================================================================================== // Full Text Search // ================ /** * Match for full-text search. <br> * Bind variable is unused because the condition value should be literal in MySQL. * @param textColumn The text column. (NotNull, StringColumn, TargetTableColumn) * @param conditionValue The condition value embedded without binding (by MySQL restriction) but escaped. (NullAllowed: if null or empty, no condition) * @param modifier The modifier of full-text search. (NullAllowed: If the value is null, No modifier specified) */ public void match(org.dbflute.dbmeta.info.ColumnInfo textColumn , String conditionValue , org.dbflute.dbway.WayOfMySQL.FullTextSearchModifier modifier) { assertObjectNotNull("textColumn", textColumn); match(newArrayList(textColumn), conditionValue, modifier); } /** * Match for full-text search. <br> * Bind variable is unused because the condition value should be literal in MySQL. * @param textColumnList The list of text column. (NotNull, NotEmpty, StringColumn, TargetTableColumn) * @param conditionValue The condition value embedded without binding (by MySQL restriction) but escaped. (NullAllowed: if null or empty, no condition) * @param modifier The modifier of full-text search. (NullAllowed: If the value is null, no modifier specified) */ public void match(List<org.dbflute.dbmeta.info.ColumnInfo> textColumnList , String conditionValue , org.dbflute.dbway.WayOfMySQL.FullTextSearchModifier modifier) { xdoMatchForMySQL(textColumnList, conditionValue, modifier); } // =================================================================================== // Manual Order // ============ /** * Order along manual ordering information. * <pre> * cb.query().addOrderBy_Birthdate_Asc().<span style="color: #CC4747">withManualOrder</span>(<span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">op</span>.<span style="color: #CC4747">when_GreaterEqual</span>(priorityDate); <span style="color: #3F7E5E">// e.g. 2000/01/01</span> * }); * <span style="color: #3F7E5E">// order by </span> * <span style="color: #3F7E5E">// case</span> * <span style="color: #3F7E5E">// when BIRTHDATE &gt;= '2000/01/01' then 0</span> * <span style="color: #3F7E5E">// else 1</span> * <span style="color: #3F7E5E">// end asc, ...</span> * * cb.query().addOrderBy_MemberStatusCode_Asc().<span style="color: #CC4747">withManualOrder</span>(<span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">op</span>.<span style="color: #CC4747">when_Equal</span>(CDef.MemberStatus.Withdrawal); * <span style="color: #553000">op</span>.<span style="color: #CC4747">when_Equal</span>(CDef.MemberStatus.Formalized); * <span style="color: #553000">op</span>.<span style="color: #CC4747">when_Equal</span>(CDef.MemberStatus.Provisional); * }); * <span style="color: #3F7E5E">// order by </span> * <span style="color: #3F7E5E">// case</span> * <span style="color: #3F7E5E">// when MEMBER_STATUS_CODE = 'WDL' then 0</span> * <span style="color: #3F7E5E">// when MEMBER_STATUS_CODE = 'FML' then 1</span> * <span style="color: #3F7E5E">// when MEMBER_STATUS_CODE = 'PRV' then 2</span> * <span style="color: #3F7E5E">// else 3</span> * <span style="color: #3F7E5E">// end asc, ...</span> * </pre> * <p>This function with Union is unsupported!</p> * <p>The order values are bound (treated as bind parameter).</p> * @param opLambda The callback for option of manual-order containing order values. (NotNull) */ public void withManualOrder(ManualOrderOptionCall opLambda) { // is user public! xdoWithManualOrder(cMOO(opLambda)); } // =================================================================================== // Small Adjustment // ================ // =================================================================================== // Very Internal // ============= protected WhiteEscapedNumberInitialCB newMyCB() { return new WhiteEscapedNumberInitialCB(); } // very internal (for suppressing warn about 'Not Use Import') protected String xabUDT() { return Date.class.getName(); } protected String xabCQ() { return WhiteEscapedNumberInitialCQ.class.getName(); } protected String xabLSO() { return LikeSearchOption.class.getName(); } protected String xabSLCS() { return HpSLCSetupper.class.getName(); } protected String xabSCP() { return SubQuery.class.getName(); } }
apache-2.0
dcloudio/uni-app
src/platforms/app-plus-nvue/runtime/components/icon.js
1843
const iconChars = { 'success': '\uEA06', 'info': '\uEA03', 'warn': '\uEA0B', 'waiting': '\uEA09', 'safe_success': '\uEA04', 'safe_warn': '\uEA05', 'success_circle': '\uEA07', 'success_no_circle': '\uEA08', 'waiting_circle': '\uEA0A', 'circle': '\uEA01', 'download': '\uEA02', 'info_circle': '\uEA0C', 'cancel': '\uEA0D', 'search': '\uEA0E', 'clear': '\uEA0F' } // 测试中发现通过动态绑定 class 来设置样式没生效,暂时这样列出来通过 style 来处理。 const iconColors = { 'success': '#007aff', 'info': '#10aeff', 'warn': '#f76260', 'waiting': '#10aeff', 'safe_success': '#007aff', 'safe_warn': '#ffbe00', 'success_circle': '#007aff', 'success_no_circle': '#007aff', 'waiting_circle': '#10aeff', 'circle': '#c9c9c9', 'download': '#007aff', 'info_circle': '#007aff', 'cancel': '#f43530', 'search': '#b2b2b2', 'clear': '#b2b2b2' } function getIcon (weex) { return { name: 'Icon', props: { type: { type: String, default: '' }, size: { type: [String, Number], default: 23 }, color: { type: String, default: '' } }, data () { return { iconChars } }, beforeCreate () { }, computed: { styles () { return { color: this.color || iconColors[this.type], fontSize: this.size } } }, render (createElement) { const _vm = this return createElement('u-text', _vm._g({ staticClass: ['uni-icon'], style: _vm.styles }, _vm.$listeners), [_vm.iconChars[_vm.type]]) }, style: { 'uni-icon': { 'fontFamily': 'unincomponents' } } } } export default function init (Vue, weex) { Vue.component('icon', getIcon(weex)) }
apache-2.0
beautifultable/phpwind
phpwind9/src/service/forum/srv/post/PwReplyPost.php
5429
<?php defined('WEKIT_VERSION') || exit('Forbidden'); /** * 回复发布相关服务 * * @author Jianmin Chen <sky_hold@163.com> * @copyright ©2003-2103 phpwind.com * @license http://www.phpwind.com * * @version $Id: PwReplyPost.php 28950 2013-05-31 05:58:25Z jieyin $ */ class PwReplyPost extends PwPostAction { public $tid; protected $pid; protected $info; public function __construct($tid, PwUserBo $user = null) { $this->tid = $tid; $this->info = $this->_getThreadsService()->getThread($tid); parent::__construct($this->info['fid'], $user); } /** * @see PwPostAction.isInit */ public function isInit() { return ! empty($this->info); } /** * @see PwPostAction.check */ public function check() { if (($result = $this->forum->allowReply($this->user)) !== true) { return new PwError('BBS:forum.permissions.reply.allow', ['{grouptitle}' => $this->user->getGroupInfo('name')]); } if (! $this->forum->foruminfo['allow_reply'] && ! $this->user->getPermission('allow_reply')) { return new PwError('permission.reply.allow', ['{grouptitle}' => $this->user->getGroupInfo('name')]); } if (Pw::getstatus($this->info['tpcstatus'], PwThread::STATUS_LOCKED) && ! $this->user->getPermission('reply_locked_threads')) { return new PwError('permission.reply.fail.locked', ['{grouptitle}' => $this->user->getGroupInfo('name')]); } if ($this->forum->forumset['locktime'] && ($this->info['created_time'] + $this->forum->forumset['locktime'] * 86400) < Pw::getTime()) { return new PwError('BBS:forum.thread.locked.not'); } if (($result = $this->checkPostNum()) !== true) { return $result; } if (($result = $this->checkPostPertime()) !== true) { return $result; } return true; } /** * @see PwPostAction.getDm */ public function getDm() { return new PwReplyDm(0, $this->forum, $this->user); } /** * @see PwPostAction.getInfo */ public function getInfo() { return $this->info; } /** * @see PwPostAction.getAttachs */ public function getAttachs() { return []; } /** * @see PwPostAction.dataProcessing */ public function dataProcessing(PwPostDm $postDm) { $postDm->setTid($this->tid) ->setFid($this->forum->fid) ->setAuthor($this->user->uid, $this->user->username, $this->user->ip) ->setCreatedTime(Pw::getTime()) ->setDisabled($this->isDisabled()); if (($result = $this->checkContentHash($postDm->getContent())) !== true) { return $result; } if (($postDm = $this->runWithFilters('dataProcessing', $postDm)) instanceof PwError) { return $postDm; } $this->postDm = $postDm; return true; } /** * @see PwPostAction.execute */ public function execute() { $result = $this->_getThreadsService()->addPost($this->postDm); if ($result instanceof PwError) { return $result; } $this->pid = $result; $this->afterPost(); return true; } /** * 回帖后续操作<更新版块、缓存等信息>. */ public function afterPost() { if ($rpid = $this->postDm->getField('rpid')) { Wekit::load('forum.PwPostsReply')->add($this->pid, $rpid); } if ($this->postDm->getIscheck()) { $title = $this->postDm->getTitle() ? $this->postDm->getTitle() : 'Re:'.$this->info['subject']; $this->forum->addPost($this->tid, $this->user->username, $title); $dm = new PwTopicDm($this->tid); $timestamp = Pw::getTime(); if ($this->info['lastpost_time'] > $timestamp || Pw::getstatus($this->info['tpcstatus'], PwThread::STATUS_DOWNED)) { $timestamp = null; } $dm->addReplies(1)->addHits(1)->setLastpost($this->user->uid, $this->user->username, $timestamp); $this->_getThreadsService()->updateThread($dm, PwThread::FETCH_MAIN); if ($rpid) { $dm = new PwReplyDm($rpid); $dm->addReplies(1); $this->_getThreadsService()->updatePost($dm); } } } /** * @see PwPostAction.afterRun */ public function afterRun() { $this->runDo('addPost', $this->pid, $this->tid); } public function getCreditOperate() { return 'post_reply'; } public function isForumContentCheck() { return intval($this->forum->forumset['contentcheck']) & 2; } public function updateUser() { $userDm = parent::updateUser(); $userDm->addPostnum(1)->addTodaypost(1)->setPostcheck($this->getHash($this->postDm->getContent())); return $userDm; } public function getNewId() { return $this->pid; } /** * Enter description here ... * * @return PwNoticeService */ protected function _getNoticeService() { return Wekit::load('message.srv.PwNoticeService'); } protected function _getThreadsService() { return Wekit::load('forum.PwThread'); } }
apache-2.0
dtk/dtk-server
application/model/module/module_utils/list_method.rb
6380
# # Copyright (C) 2010-2016 dtk contributors # # This file is part of the dtk project. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module DTK module ModuleUtils class ListMethod DEFAULT_VERSION = 'CURRENT' MASTER_VERSION = 'master' def self.aggregate_detail(branch_module_rows, project_idh, model_type, opts) project = project_idh.create_object() module_mh = project_idh.createMH(model_type) diff = opts[:diff] remote_repo_base = opts[:remote_repo_base] if opts[:include_remotes] augment_with_remotes_info!(branch_module_rows, module_mh) end # if there is an external_ref source, use that otherwise look for remote dtkn # there can be duplictes for a module when multiple repos; in which case will agree on all fields # except :repo, :module_branch, and :repo_remotes # index by module ndx_ret = {} # aggregate branch_module_rows.each do |r| module_branch = r[:module_branch] module_name = r.module_name() ndx_repo_remotes = r[:ndx_repo_remotes] repo = r[:repo] ndx = r[:id] is_equal = nil not_published = nil unless mdl = ndx_ret[ndx] r.delete(:repo) r.delete(:module_branch) mdl = ndx_ret[ndx] = r end # if finding differences with the dtkn catalog if diff && module_branch[:version].eql?('master') if default_remote_repo = RepoRemote.default_repo_remote?((ndx_repo_remotes || {}).values) remote = default_remote_repo.remote_dtkn_location(project, model_type, module_name) is_equal = repo.ret_local_remote_diff(module_branch, remote) elsif default_remote_repo = RepoRemote.default_from_module_branch?(module_branch) remote = default_remote_repo.remote_dtkn_location(project, model_type, module_name) is_equal = repo.ret_local_remote_diff(module_branch, remote) else not_published = true end mdl.merge!(remote_relationship: is_equal) mdl.merge!(not_published: not_published) end if opts[:include_versions] version = module_branch.version_print_form(Opts.new(default_version_string: MASTER_VERSION)) unless version.eql?('CURRENT') version_print = r[:dsl_parsed] ? version : "*#{version}" (mdl[:version_array] ||= []) << version_print end end if external_ref_source = module_branch.external_ref_source() mdl[:external_ref_source] = external_ref_source end if ndx_repo_remotes ndx_repo_remotes.each do |remote_repo_id, remote_repo| (mdl[:ndx_repo_remotes] ||= {})[remote_repo_id] ||= remote_repo end end end # put in display name form ndx_ret.each_value do |mdl| if raw_va = mdl.delete(:version_array) if raw_va.size == 1 mdl.merge!(versions: raw_va[0]) else version_array = [] master_print = raw_va.find { |v| v.delete('*') == MASTER_VERSION } raw_va.delete(master_print) version_array << master_print if master_print version_array << raw_va.sort{ |a, b| a.delete('*') <=> b.delete('*') }.reverse mdl.merge!(versions: version_array.join(', ')) end end external_ref_source = mdl.delete(:external_ref_source) ndx_repo_remotes = mdl.delete(:ndx_repo_remotes) if linked_remote = linked_remotes_print_form((ndx_repo_remotes || {}).values, external_ref_source, not_published: mdl[:not_published]) mdl.merge!(linked_remotes: linked_remote) end end ndx_ret.values end # each branch_module_row has a nested :repo column def self.augment_with_remotes_info!(branch_module_rows, module_mh) # index by repo_id ndx_branch_module_rows = branch_module_rows.inject({}) { |h, r| r[:repo] ? h.merge(r[:repo][:id] => r) : h } unless ndx_branch_module_rows.empty? sp_hash = { cols: [:id, :group_id, :display_name, :repo_id, :repo_name, :repo_namespace, :created_at, :is_default], filter: [:oneof, :repo_id, ndx_branch_module_rows.keys] } remotes = Model.get_objs(module_mh.createMH(:repo_remote), sp_hash) remotes.each do |r| ndx = r[:repo_id] (ndx_branch_module_rows[ndx][:ndx_repo_remotes] ||= {}).merge!(r[:id] => r) end end end def self.linked_remotes_print_form(repo_remotes, external_ref_source, opts = {}) opts_pp = Opts.new(provider_prefix: true) array = if repo_remotes.empty? [] elsif repo_remotes.size == 1 if repo_remotes.first.nil? # TODO: this is for obscure error; see what this is happening [] else [repo_remotes.first.print_form(opts_pp)] end else if default = RepoRemote.default_repo_remote?(repo_remotes) # remove all non default dtkn_providers repo_remotes.reject! { |r| r[:id] == default[:id] and r.is_dtkn_provider? } [default.print_form(opts_pp)] + repo_remotes.map { |r| r.print_form(opts_pp) } else repo_remotes.map { |r| r.print_form(opts_pp) } end end array << external_ref_source if external_ref_source array << '*** NOT PUBLISHED in DTKN ***' if opts[:not_published] array.uniq.join(JoinDelimiter) end JoinDelimiter = ', ' end end end
apache-2.0
apo-soft/wechat
aposoft-wechat-company-parent/aposoft-wechat-company-managemnt/src/main/java/org/aposoft/wechat/company/managemnt/tag/impl/BasicTag.java
553
package org.aposoft.wechat.company.managemnt.tag.impl; import org.aposoft.wechat.company.managemnt.tag.Tag; /** * 标签简单实现 * * @author Jann Liu * */ public class BasicTag implements Tag { private String tagname; private Integer tagid; public void setTagname(String tagname) { this.tagname = tagname; } public void setTagid(Integer tagid) { this.tagid = tagid; } @Override public String getTagname() { return tagname; } @Override public Integer getTagid() { return tagid; } }
apache-2.0
mapway/mapway-ui-frame
src/main/java/com/ksyzt/gwt/client/event/HasMessageHandlers.java
457
package com.ksyzt.gwt.client.event; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.event.shared.HasHandlers; // TODO: Auto-generated Javadoc /** * The Interface HasMessageHandlers. */ public interface HasMessageHandlers extends HasHandlers { /** * Adds the message handler. * * @param handler the handler * @return the handler registration */ HandlerRegistration addMessageHandler(MessageHandler handler); }
apache-2.0
digital-antiquity/repo-metadata
src/main/java/gov/loc/mods/v3/BaseTitleInfoType.java
12216
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-661 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2009.02.02 at 03:34:01 PM MST // package gov.loc.mods.v3; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for baseTitleInfoType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="baseTitleInfoType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice maxOccurs="unbounded" minOccurs="0"> * &lt;element name="title" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="subTitle" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="partNumber" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="partName" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="nonSort" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/choice> * &lt;attGroup ref="{http://www.loc.gov/mods/v3}idAuthorityXlinkLanguage"/> * &lt;attribute name="displayLabel" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "baseTitleInfoType", propOrder = { "titleOrSubTitleOrPartNumber" }) public class BaseTitleInfoType { @XmlElementRefs({ @XmlElementRef(name = "nonSort", namespace = "http://www.loc.gov/mods/v3", type = JAXBElement.class), @XmlElementRef(name = "subTitle", namespace = "http://www.loc.gov/mods/v3", type = JAXBElement.class), @XmlElementRef(name = "partNumber", namespace = "http://www.loc.gov/mods/v3", type = JAXBElement.class), @XmlElementRef(name = "partName", namespace = "http://www.loc.gov/mods/v3", type = JAXBElement.class), @XmlElementRef(name = "title", namespace = "http://www.loc.gov/mods/v3", type = JAXBElement.class) }) protected List<JAXBElement<String>> titleOrSubTitleOrPartNumber; @XmlAttribute protected String displayLabel; @XmlAttribute(name = "ID") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; @XmlAttribute protected String authority; @XmlAttribute(name = "lang") protected String mLang; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") protected String lang; @XmlAttribute protected String script; @XmlAttribute protected String transliteration; @XmlAttribute(namespace = "http://www.w3.org/1999/xlink") protected String type; @XmlAttribute(namespace = "http://www.w3.org/1999/xlink") @XmlSchemaType(name = "anyURI") protected String href; @XmlAttribute(namespace = "http://www.w3.org/1999/xlink") protected String role; @XmlAttribute(namespace = "http://www.w3.org/1999/xlink") protected String arcrole; @XmlAttribute(namespace = "http://www.w3.org/1999/xlink") protected String title; @XmlAttribute(namespace = "http://www.w3.org/1999/xlink") protected String show; @XmlAttribute(namespace = "http://www.w3.org/1999/xlink") protected String actuate; /** * Gets the value of the titleOrSubTitleOrPartNumber property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the titleOrSubTitleOrPartNumber property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTitleOrSubTitleOrPartNumber().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link JAXBElement }{@code <}{@link String }{@code >} * {@link JAXBElement }{@code <}{@link String }{@code >} * {@link JAXBElement }{@code <}{@link String }{@code >} * {@link JAXBElement }{@code <}{@link String }{@code >} * {@link JAXBElement }{@code <}{@link String }{@code >} * * */ public List<JAXBElement<String>> getTitleOrSubTitleOrPartNumber() { if (titleOrSubTitleOrPartNumber == null) { titleOrSubTitleOrPartNumber = new ArrayList<JAXBElement<String>>(); } return this.titleOrSubTitleOrPartNumber; } /** * Gets the value of the displayLabel property. * * @return * possible object is * {@link String } * */ public String getDisplayLabel() { return displayLabel; } /** * Sets the value of the displayLabel property. * * @param value * allowed object is * {@link String } * */ public void setDisplayLabel(String value) { this.displayLabel = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getID() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setID(String value) { this.id = value; } /** * Gets the value of the authority property. * * @return * possible object is * {@link String } * */ public String getAuthority() { return authority; } /** * Sets the value of the authority property. * * @param value * allowed object is * {@link String } * */ public void setAuthority(String value) { this.authority = value; } /** * Gets the value of the mLang property. * * @return * possible object is * {@link String } * */ public String getMLang() { return mLang; } /** * Sets the value of the mLang property. * * @param value * allowed object is * {@link String } * */ public void setMLang(String value) { this.mLang = value; } /** * Gets the value of the lang property. * * @return * possible object is * {@link String } * */ public String getLang() { return lang; } /** * Sets the value of the lang property. * * @param value * allowed object is * {@link String } * */ public void setLang(String value) { this.lang = value; } /** * Gets the value of the script property. * * @return * possible object is * {@link String } * */ public String getScript() { return script; } /** * Sets the value of the script property. * * @param value * allowed object is * {@link String } * */ public void setScript(String value) { this.script = value; } /** * Gets the value of the transliteration property. * * @return * possible object is * {@link String } * */ public String getTransliteration() { return transliteration; } /** * Sets the value of the transliteration property. * * @param value * allowed object is * {@link String } * */ public void setTransliteration(String value) { this.transliteration = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { if (type == null) { return "simple"; } else { return type; } } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } /** * Gets the value of the href property. * * @return * possible object is * {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is * {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the role property. * * @return * possible object is * {@link String } * */ public String getRole() { return role; } /** * Sets the value of the role property. * * @param value * allowed object is * {@link String } * */ public void setRole(String value) { this.role = value; } /** * Gets the value of the arcrole property. * * @return * possible object is * {@link String } * */ public String getArcrole() { return arcrole; } /** * Sets the value of the arcrole property. * * @param value * allowed object is * {@link String } * */ public void setArcrole(String value) { this.arcrole = value; } /** * Gets the value of the title property. * * @return * possible object is * {@link String } * */ public String getTitle() { return title; } /** * Sets the value of the title property. * * @param value * allowed object is * {@link String } * */ public void setTitle(String value) { this.title = value; } /** * Gets the value of the show property. * * @return * possible object is * {@link String } * */ public String getShow() { return show; } /** * Sets the value of the show property. * * @param value * allowed object is * {@link String } * */ public void setShow(String value) { this.show = value; } /** * Gets the value of the actuate property. * * @return * possible object is * {@link String } * */ public String getActuate() { return actuate; } /** * Sets the value of the actuate property. * * @param value * allowed object is * {@link String } * */ public void setActuate(String value) { this.actuate = value; } }
apache-2.0
griffon/griffon-pivot-plugin
src/main/griffon/pivot/support/adapters/ComponentStyleAdapter.java
1448
/* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package griffon.pivot.support.adapters; import groovy.lang.Closure; /** * @author Andres Almiray */ public class ComponentStyleAdapter implements GriffonPivotAdapter, org.apache.pivot.wtk.ComponentStyleListener { private Closure styleUpdated; public Closure getStyleUpdated() { return this.styleUpdated; } public void setStyleUpdated(Closure styleUpdated) { this.styleUpdated = styleUpdated; if (this.styleUpdated != null) { this.styleUpdated.setDelegate(this); this.styleUpdated.setResolveStrategy(Closure.DELEGATE_FIRST); } } public void styleUpdated(org.apache.pivot.wtk.Component arg0, java.lang.String arg1, java.lang.Object arg2) { if (styleUpdated != null) { styleUpdated.call(arg0, arg1, arg2); } } }
apache-2.0
kawasima/moshas
moshas/src/main/java/net/unit8/moshas/RenderFunction.java
268
package net.unit8.moshas; import net.unit8.moshas.context.IContext; import net.unit8.moshas.dom.Element; import java.io.Serializable; /** * * @author kawasima */ public interface RenderFunction extends Serializable { void render(Element el, IContext ctx); }
apache-2.0
Intacct/intacct-sdk-php
test/Intacct/Functions/PlatformServices/ApplicationInstallTest.php
1321
<?php /** * Copyright 2021 Sage Intacct, 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 * * 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. */ namespace Intacct\Functions\PlatformServices; use Intacct\Xml\XMLWriter; use InvalidArgumentException; /** * @coversDefaultClass \Intacct\Functions\PlatformServices\ApplicationInstall */ class ApplicationInstallTest extends \PHPUnit\Framework\TestCase { public function testRequiredXmlFilename(): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage("XML Filename is required for install"); $xml = new XMLWriter(); $xml->openMemory(); $xml->setIndent(true); $xml->setIndentString(' '); $xml->startDocument(); $app = new ApplicationInstall('unittest'); //$app->setXmlFilename('app.xml'); $app->writeXml($xml); } }
apache-2.0
kgiannakakis/MonoGameEffects
WindowsStore/GamePage.xaml.cs
586
using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using MonoGame.Framework; using Windows.ApplicationModel.Activation; namespace MonoGameEffects { /// <summary> /// The root page used to display the game. /// </summary> public sealed partial class GamePage : SwapChainBackgroundPanel { readonly Game1 _game; public GamePage(LaunchActivatedEventArgs args) { this.InitializeComponent(); // Create the game. _game = XamlGame<Game1>.Create(args, Window.Current.CoreWindow, this); } } }
apache-2.0
Sellegit/retrofit
retrofit/src/main/java/retrofit/sharehttp/Response.java
10237
package retrofit.sharehttp; import java.util.List; import static retrofit.sharehttp.StatusLine.HTTP_PERM_REDIRECT; import static retrofit.sharehttp.StatusLine.HTTP_TEMP_REDIRECT; import static java.net.HttpURLConnection.HTTP_MOVED_PERM; import static java.net.HttpURLConnection.HTTP_MOVED_TEMP; import static java.net.HttpURLConnection.HTTP_MULT_CHOICE; import static java.net.HttpURLConnection.HTTP_PROXY_AUTH; import static java.net.HttpURLConnection.HTTP_SEE_OTHER; import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; /** * An HTTP response. Instances of this class are not immutable: the response * body is a one-shot value that may be consumed only once. All other properties * are immutable. */ public final class Response { private final Request request; private final Protocol protocol; private final int code; private final String message; // private final Handshake handshake; private final Headers headers; private final ResponseBody body; private Response networkResponse; private Response cacheResponse; private final Response priorResponse; private volatile CacheControl cacheControl; // Lazily initialized. private Response(Builder builder) { this.request = builder.request; this.protocol = builder.protocol; this.code = builder.code; this.message = builder.message; // this.handshake = builder.handshake; this.headers = builder.headers.build(); this.body = builder.body; this.networkResponse = builder.networkResponse; this.cacheResponse = builder.cacheResponse; this.priorResponse = builder.priorResponse; } /** * The wire-level request that initiated this HTTP response. This is not * necessarily the same request issued by the application: * <ul> * <li>It may be transformed by the HTTP client. For example, the client * may copy headers like {@code Content-Length} from the request body. * <li>It may be the request generated in response to an HTTP redirect or * authentication challenge. In this case the request URL may be * different than the initial request URL. * </ul> */ public Request request() { return request; } /** * Returns the HTTP protocol, such as {@link Protocol#HTTP_1_1} or {@link * Protocol#HTTP_1_0}. */ public Protocol protocol() { return protocol; } /** Returns the HTTP status code. */ public int code() { return code; } /** * Returns true if the code is in [200..300), which means the request was * successfully received, understood, and accepted. */ public boolean isSuccessful() { return code >= 200 && code < 300; } /** Returns the HTTP status message or null if it is unknown. */ public String message() { return message; } /** * Returns the TLS handshake of the connection that carried this response, or * null if the response was received without TLS. */ // public Handshake handshake() { // return handshake; // } public List<String> headers(String name) { return headers.values(name); } public String header(String name) { return header(name, null); } public String header(String name, String defaultValue) { String result = headers.get(name); return result != null ? result : defaultValue; } public Headers headers() { return headers; } public ResponseBody body() { return body; } public Builder newBuilder() { return new Builder(this); } /** Returns true if this response redirects to another resource. */ public boolean isRedirect() { switch (code) { case HTTP_PERM_REDIRECT: case HTTP_TEMP_REDIRECT: case HTTP_MULT_CHOICE: case HTTP_MOVED_PERM: case HTTP_MOVED_TEMP: case HTTP_SEE_OTHER: return true; default: return false; } } /** * Returns the raw response received from the network. Will be null if this * response didn't use the network, such as when the response is fully cached. * The body of the returned response should not be read. */ public Response networkResponse() { return networkResponse; } /** * Returns the raw response received from the cache. Will be null if this * response didn't use the cache. For conditional get requests the cache * response and network response may both be non-null. The body of the * returned response should not be read. */ public Response cacheResponse() { return cacheResponse; } /** * Returns the response for the HTTP redirect or authorization challenge that * triggered this response, or null if this response wasn't triggered by an * automatic retry. The body of the returned response should not be read * because it has already been consumed by the redirecting client. */ public Response priorResponse() { return priorResponse; } /** * Returns the authorization challenges appropriate for this response's code. * If the response code is 401 unauthorized, this returns the * "WWW-Authenticate" challenges. If the response code is 407 proxy * unauthorized, this returns the "Proxy-Authenticate" challenges. Otherwise * this returns an empty list of challenges. */ // public List<Challenge> challenges() { // String responseField; // if (code == HTTP_UNAUTHORIZED) { // responseField = "WWW-Authenticate"; // } else if (code == HTTP_PROXY_AUTH) { // responseField = "Proxy-Authenticate"; // } else { // return Collections.emptyList(); // } // return OkHeaders.parseChallenges(headers(), responseField); // } /** * Returns the cache control directives for this response. This is never null, * even if this response contains no {@code Cache-Control} header. */ public CacheControl cacheControl() { CacheControl result = cacheControl; return result != null ? result : (cacheControl = CacheControl.parse(headers)); } @Override public String toString() { return "Response{protocol=" + protocol + ", code=" + code + ", message=" + message + ", url=" + request.urlString() + '}'; } public static class Builder { private Request request; private Protocol protocol; private int code = -1; private String message; // private Handshake handshake; private Headers.Builder headers; private ResponseBody body; private Response networkResponse; private Response cacheResponse; private Response priorResponse; public Builder() { headers = new Headers.Builder(); } private Builder(Response response) { this.request = response.request; this.protocol = response.protocol; this.code = response.code; this.message = response.message; // this.handshake = response.handshake; this.headers = response.headers.newBuilder(); this.body = response.body; this.networkResponse = response.networkResponse; this.cacheResponse = response.cacheResponse; this.priorResponse = response.priorResponse; } public Builder request(Request request) { this.request = request; return this; } public Builder protocol(Protocol protocol) { this.protocol = protocol; return this; } public Builder code(int code) { this.code = code; return this; } public Builder message(String message) { this.message = message; return this; } // public Builder handshake(Handshake handshake) { // this.handshake = handshake; // return this; // } /** * Sets the header named {@code name} to {@code value}. If this request * already has any headers with that name, they are all replaced. */ public Builder header(String name, String value) { headers.set(name, value); return this; } /** * Adds a header with {@code name} and {@code value}. Prefer this method for * multiply-valued headers like "Set-Cookie". */ public Builder addHeader(String name, String value) { headers.add(name, value); return this; } public Builder removeHeader(String name) { headers.removeAll(name); return this; } /** Removes all headers on this builder and adds {@code headers}. */ public Builder headers(Headers headers) { this.headers = headers.newBuilder(); return this; } public Builder body(ResponseBody body) { this.body = body; return this; } public Builder networkResponse(Response networkResponse) { if (networkResponse != null) checkSupportResponse("networkResponse", networkResponse); this.networkResponse = networkResponse; return this; } public Builder cacheResponse(Response cacheResponse) { if (cacheResponse != null) checkSupportResponse("cacheResponse", cacheResponse); this.cacheResponse = cacheResponse; return this; } private void checkSupportResponse(String name, Response response) { if (response.body != null) { throw new IllegalArgumentException(name + ".body != null"); } else if (response.networkResponse != null) { throw new IllegalArgumentException(name + ".networkResponse != null"); } else if (response.cacheResponse != null) { throw new IllegalArgumentException(name + ".cacheResponse != null"); } else if (response.priorResponse != null) { throw new IllegalArgumentException(name + ".priorResponse != null"); } } public Builder priorResponse(Response priorResponse) { if (priorResponse != null) checkPriorResponse(priorResponse); this.priorResponse = priorResponse; return this; } private void checkPriorResponse(Response response) { if (response.body != null) { throw new IllegalArgumentException("priorResponse.body != null"); } } public Response build() { if (request == null) throw new IllegalStateException("request == null"); if (protocol == null) throw new IllegalStateException("protocol == null"); if (code < 0) throw new IllegalStateException("code < 0: " + code); return new Response(this); } } }
apache-2.0
googleads/google-ads-java
google-ads-stubs-v9/src/main/java/com/google/ads/googleads/v9/services/MutateCampaignBudgetsRequest.java
50021
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/services/campaign_budget_service.proto package com.google.ads.googleads.v9.services; /** * <pre> * Request message for [CampaignBudgetService.MutateCampaignBudgets][google.ads.googleads.v9.services.CampaignBudgetService.MutateCampaignBudgets]. * </pre> * * Protobuf type {@code google.ads.googleads.v9.services.MutateCampaignBudgetsRequest} */ public final class MutateCampaignBudgetsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v9.services.MutateCampaignBudgetsRequest) MutateCampaignBudgetsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use MutateCampaignBudgetsRequest.newBuilder() to construct. private MutateCampaignBudgetsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private MutateCampaignBudgetsRequest() { customerId_ = ""; operations_ = java.util.Collections.emptyList(); responseContentType_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MutateCampaignBudgetsRequest(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MutateCampaignBudgetsRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); customerId_ = s; break; } case 18: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { operations_ = new java.util.ArrayList<com.google.ads.googleads.v9.services.CampaignBudgetOperation>(); mutable_bitField0_ |= 0x00000001; } operations_.add( input.readMessage(com.google.ads.googleads.v9.services.CampaignBudgetOperation.parser(), extensionRegistry)); break; } case 24: { partialFailure_ = input.readBool(); break; } case 32: { validateOnly_ = input.readBool(); break; } case 40: { int rawValue = input.readEnum(); responseContentType_ = rawValue; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { operations_ = java.util.Collections.unmodifiableList(operations_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v9.services.CampaignBudgetServiceProto.internal_static_google_ads_googleads_v9_services_MutateCampaignBudgetsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v9.services.CampaignBudgetServiceProto.internal_static_google_ads_googleads_v9_services_MutateCampaignBudgetsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest.class, com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest.Builder.class); } public static final int CUSTOMER_ID_FIELD_NUMBER = 1; private volatile java.lang.Object customerId_; /** * <pre> * Required. The ID of the customer whose campaign budgets are being modified. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The customerId. */ @java.lang.Override public java.lang.String getCustomerId() { java.lang.Object ref = customerId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); customerId_ = s; return s; } } /** * <pre> * Required. The ID of the customer whose campaign budgets are being modified. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for customerId. */ @java.lang.Override public com.google.protobuf.ByteString getCustomerIdBytes() { java.lang.Object ref = customerId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customerId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int OPERATIONS_FIELD_NUMBER = 2; private java.util.List<com.google.ads.googleads.v9.services.CampaignBudgetOperation> operations_; /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ @java.lang.Override public java.util.List<com.google.ads.googleads.v9.services.CampaignBudgetOperation> getOperationsList() { return operations_; } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ @java.lang.Override public java.util.List<? extends com.google.ads.googleads.v9.services.CampaignBudgetOperationOrBuilder> getOperationsOrBuilderList() { return operations_; } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ @java.lang.Override public int getOperationsCount() { return operations_.size(); } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ @java.lang.Override public com.google.ads.googleads.v9.services.CampaignBudgetOperation getOperations(int index) { return operations_.get(index); } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ @java.lang.Override public com.google.ads.googleads.v9.services.CampaignBudgetOperationOrBuilder getOperationsOrBuilder( int index) { return operations_.get(index); } public static final int PARTIAL_FAILURE_FIELD_NUMBER = 3; private boolean partialFailure_; /** * <pre> * If true, successful operations will be carried out and invalid * operations will return errors. If false, all operations will be carried * out in one transaction if and only if they are all valid. * Default is false. * </pre> * * <code>bool partial_failure = 3;</code> * @return The partialFailure. */ @java.lang.Override public boolean getPartialFailure() { return partialFailure_; } public static final int VALIDATE_ONLY_FIELD_NUMBER = 4; private boolean validateOnly_; /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } public static final int RESPONSE_CONTENT_TYPE_FIELD_NUMBER = 5; private int responseContentType_; /** * <pre> * The response content type setting. Determines whether the mutable resource * or just the resource name should be returned post mutation. * </pre> * * <code>.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 5;</code> * @return The enum numeric value on the wire for responseContentType. */ @java.lang.Override public int getResponseContentTypeValue() { return responseContentType_; } /** * <pre> * The response content type setting. Determines whether the mutable resource * or just the resource name should be returned post mutation. * </pre> * * <code>.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 5;</code> * @return The responseContentType. */ @java.lang.Override public com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType getResponseContentType() { @SuppressWarnings("deprecation") com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType result = com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType.valueOf(responseContentType_); return result == null ? com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType.UNRECOGNIZED : result; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, customerId_); } for (int i = 0; i < operations_.size(); i++) { output.writeMessage(2, operations_.get(i)); } if (partialFailure_ != false) { output.writeBool(3, partialFailure_); } if (validateOnly_ != false) { output.writeBool(4, validateOnly_); } if (responseContentType_ != com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType.UNSPECIFIED.getNumber()) { output.writeEnum(5, responseContentType_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, customerId_); } for (int i = 0; i < operations_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, operations_.get(i)); } if (partialFailure_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(3, partialFailure_); } if (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(4, validateOnly_); } if (responseContentType_ != com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType.UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(5, responseContentType_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest)) { return super.equals(obj); } com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest other = (com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest) obj; if (!getCustomerId() .equals(other.getCustomerId())) return false; if (!getOperationsList() .equals(other.getOperationsList())) return false; if (getPartialFailure() != other.getPartialFailure()) return false; if (getValidateOnly() != other.getValidateOnly()) return false; if (responseContentType_ != other.responseContentType_) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + CUSTOMER_ID_FIELD_NUMBER; hash = (53 * hash) + getCustomerId().hashCode(); if (getOperationsCount() > 0) { hash = (37 * hash) + OPERATIONS_FIELD_NUMBER; hash = (53 * hash) + getOperationsList().hashCode(); } hash = (37 * hash) + PARTIAL_FAILURE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getPartialFailure()); hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getValidateOnly()); hash = (37 * hash) + RESPONSE_CONTENT_TYPE_FIELD_NUMBER; hash = (53 * hash) + responseContentType_; hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Request message for [CampaignBudgetService.MutateCampaignBudgets][google.ads.googleads.v9.services.CampaignBudgetService.MutateCampaignBudgets]. * </pre> * * Protobuf type {@code google.ads.googleads.v9.services.MutateCampaignBudgetsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v9.services.MutateCampaignBudgetsRequest) com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v9.services.CampaignBudgetServiceProto.internal_static_google_ads_googleads_v9_services_MutateCampaignBudgetsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v9.services.CampaignBudgetServiceProto.internal_static_google_ads_googleads_v9_services_MutateCampaignBudgetsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest.class, com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest.Builder.class); } // Construct using com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getOperationsFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); customerId_ = ""; if (operationsBuilder_ == null) { operations_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { operationsBuilder_.clear(); } partialFailure_ = false; validateOnly_ = false; responseContentType_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v9.services.CampaignBudgetServiceProto.internal_static_google_ads_googleads_v9_services_MutateCampaignBudgetsRequest_descriptor; } @java.lang.Override public com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest getDefaultInstanceForType() { return com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest build() { com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest buildPartial() { com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest result = new com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest(this); int from_bitField0_ = bitField0_; result.customerId_ = customerId_; if (operationsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { operations_ = java.util.Collections.unmodifiableList(operations_); bitField0_ = (bitField0_ & ~0x00000001); } result.operations_ = operations_; } else { result.operations_ = operationsBuilder_.build(); } result.partialFailure_ = partialFailure_; result.validateOnly_ = validateOnly_; result.responseContentType_ = responseContentType_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest) { return mergeFrom((com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest other) { if (other == com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest.getDefaultInstance()) return this; if (!other.getCustomerId().isEmpty()) { customerId_ = other.customerId_; onChanged(); } if (operationsBuilder_ == null) { if (!other.operations_.isEmpty()) { if (operations_.isEmpty()) { operations_ = other.operations_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureOperationsIsMutable(); operations_.addAll(other.operations_); } onChanged(); } } else { if (!other.operations_.isEmpty()) { if (operationsBuilder_.isEmpty()) { operationsBuilder_.dispose(); operationsBuilder_ = null; operations_ = other.operations_; bitField0_ = (bitField0_ & ~0x00000001); operationsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getOperationsFieldBuilder() : null; } else { operationsBuilder_.addAllMessages(other.operations_); } } } if (other.getPartialFailure() != false) { setPartialFailure(other.getPartialFailure()); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } if (other.responseContentType_ != 0) { setResponseContentTypeValue(other.getResponseContentTypeValue()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object customerId_ = ""; /** * <pre> * Required. The ID of the customer whose campaign budgets are being modified. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The customerId. */ public java.lang.String getCustomerId() { java.lang.Object ref = customerId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); customerId_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Required. The ID of the customer whose campaign budgets are being modified. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for customerId. */ public com.google.protobuf.ByteString getCustomerIdBytes() { java.lang.Object ref = customerId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customerId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Required. The ID of the customer whose campaign budgets are being modified. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The customerId to set. * @return This builder for chaining. */ public Builder setCustomerId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } customerId_ = value; onChanged(); return this; } /** * <pre> * Required. The ID of the customer whose campaign budgets are being modified. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return This builder for chaining. */ public Builder clearCustomerId() { customerId_ = getDefaultInstance().getCustomerId(); onChanged(); return this; } /** * <pre> * Required. The ID of the customer whose campaign budgets are being modified. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The bytes for customerId to set. * @return This builder for chaining. */ public Builder setCustomerIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); customerId_ = value; onChanged(); return this; } private java.util.List<com.google.ads.googleads.v9.services.CampaignBudgetOperation> operations_ = java.util.Collections.emptyList(); private void ensureOperationsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { operations_ = new java.util.ArrayList<com.google.ads.googleads.v9.services.CampaignBudgetOperation>(operations_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v9.services.CampaignBudgetOperation, com.google.ads.googleads.v9.services.CampaignBudgetOperation.Builder, com.google.ads.googleads.v9.services.CampaignBudgetOperationOrBuilder> operationsBuilder_; /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public java.util.List<com.google.ads.googleads.v9.services.CampaignBudgetOperation> getOperationsList() { if (operationsBuilder_ == null) { return java.util.Collections.unmodifiableList(operations_); } else { return operationsBuilder_.getMessageList(); } } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public int getOperationsCount() { if (operationsBuilder_ == null) { return operations_.size(); } else { return operationsBuilder_.getCount(); } } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.ads.googleads.v9.services.CampaignBudgetOperation getOperations(int index) { if (operationsBuilder_ == null) { return operations_.get(index); } else { return operationsBuilder_.getMessage(index); } } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder setOperations( int index, com.google.ads.googleads.v9.services.CampaignBudgetOperation value) { if (operationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureOperationsIsMutable(); operations_.set(index, value); onChanged(); } else { operationsBuilder_.setMessage(index, value); } return this; } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder setOperations( int index, com.google.ads.googleads.v9.services.CampaignBudgetOperation.Builder builderForValue) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); operations_.set(index, builderForValue.build()); onChanged(); } else { operationsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder addOperations(com.google.ads.googleads.v9.services.CampaignBudgetOperation value) { if (operationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureOperationsIsMutable(); operations_.add(value); onChanged(); } else { operationsBuilder_.addMessage(value); } return this; } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder addOperations( int index, com.google.ads.googleads.v9.services.CampaignBudgetOperation value) { if (operationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureOperationsIsMutable(); operations_.add(index, value); onChanged(); } else { operationsBuilder_.addMessage(index, value); } return this; } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder addOperations( com.google.ads.googleads.v9.services.CampaignBudgetOperation.Builder builderForValue) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); operations_.add(builderForValue.build()); onChanged(); } else { operationsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder addOperations( int index, com.google.ads.googleads.v9.services.CampaignBudgetOperation.Builder builderForValue) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); operations_.add(index, builderForValue.build()); onChanged(); } else { operationsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder addAllOperations( java.lang.Iterable<? extends com.google.ads.googleads.v9.services.CampaignBudgetOperation> values) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, operations_); onChanged(); } else { operationsBuilder_.addAllMessages(values); } return this; } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder clearOperations() { if (operationsBuilder_ == null) { operations_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { operationsBuilder_.clear(); } return this; } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder removeOperations(int index) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); operations_.remove(index); onChanged(); } else { operationsBuilder_.remove(index); } return this; } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.ads.googleads.v9.services.CampaignBudgetOperation.Builder getOperationsBuilder( int index) { return getOperationsFieldBuilder().getBuilder(index); } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.ads.googleads.v9.services.CampaignBudgetOperationOrBuilder getOperationsOrBuilder( int index) { if (operationsBuilder_ == null) { return operations_.get(index); } else { return operationsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public java.util.List<? extends com.google.ads.googleads.v9.services.CampaignBudgetOperationOrBuilder> getOperationsOrBuilderList() { if (operationsBuilder_ != null) { return operationsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(operations_); } } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.ads.googleads.v9.services.CampaignBudgetOperation.Builder addOperationsBuilder() { return getOperationsFieldBuilder().addBuilder( com.google.ads.googleads.v9.services.CampaignBudgetOperation.getDefaultInstance()); } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.ads.googleads.v9.services.CampaignBudgetOperation.Builder addOperationsBuilder( int index) { return getOperationsFieldBuilder().addBuilder( index, com.google.ads.googleads.v9.services.CampaignBudgetOperation.getDefaultInstance()); } /** * <pre> * Required. The list of operations to perform on individual campaign budgets. * </pre> * * <code>repeated .google.ads.googleads.v9.services.CampaignBudgetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public java.util.List<com.google.ads.googleads.v9.services.CampaignBudgetOperation.Builder> getOperationsBuilderList() { return getOperationsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v9.services.CampaignBudgetOperation, com.google.ads.googleads.v9.services.CampaignBudgetOperation.Builder, com.google.ads.googleads.v9.services.CampaignBudgetOperationOrBuilder> getOperationsFieldBuilder() { if (operationsBuilder_ == null) { operationsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v9.services.CampaignBudgetOperation, com.google.ads.googleads.v9.services.CampaignBudgetOperation.Builder, com.google.ads.googleads.v9.services.CampaignBudgetOperationOrBuilder>( operations_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); operations_ = null; } return operationsBuilder_; } private boolean partialFailure_ ; /** * <pre> * If true, successful operations will be carried out and invalid * operations will return errors. If false, all operations will be carried * out in one transaction if and only if they are all valid. * Default is false. * </pre> * * <code>bool partial_failure = 3;</code> * @return The partialFailure. */ @java.lang.Override public boolean getPartialFailure() { return partialFailure_; } /** * <pre> * If true, successful operations will be carried out and invalid * operations will return errors. If false, all operations will be carried * out in one transaction if and only if they are all valid. * Default is false. * </pre> * * <code>bool partial_failure = 3;</code> * @param value The partialFailure to set. * @return This builder for chaining. */ public Builder setPartialFailure(boolean value) { partialFailure_ = value; onChanged(); return this; } /** * <pre> * If true, successful operations will be carried out and invalid * operations will return errors. If false, all operations will be carried * out in one transaction if and only if they are all valid. * Default is false. * </pre> * * <code>bool partial_failure = 3;</code> * @return This builder for chaining. */ public Builder clearPartialFailure() { partialFailure_ = false; onChanged(); return this; } private boolean validateOnly_ ; /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> * @param value The validateOnly to set. * @return This builder for chaining. */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; onChanged(); return this; } /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> * @return This builder for chaining. */ public Builder clearValidateOnly() { validateOnly_ = false; onChanged(); return this; } private int responseContentType_ = 0; /** * <pre> * The response content type setting. Determines whether the mutable resource * or just the resource name should be returned post mutation. * </pre> * * <code>.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 5;</code> * @return The enum numeric value on the wire for responseContentType. */ @java.lang.Override public int getResponseContentTypeValue() { return responseContentType_; } /** * <pre> * The response content type setting. Determines whether the mutable resource * or just the resource name should be returned post mutation. * </pre> * * <code>.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 5;</code> * @param value The enum numeric value on the wire for responseContentType to set. * @return This builder for chaining. */ public Builder setResponseContentTypeValue(int value) { responseContentType_ = value; onChanged(); return this; } /** * <pre> * The response content type setting. Determines whether the mutable resource * or just the resource name should be returned post mutation. * </pre> * * <code>.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 5;</code> * @return The responseContentType. */ @java.lang.Override public com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType getResponseContentType() { @SuppressWarnings("deprecation") com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType result = com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType.valueOf(responseContentType_); return result == null ? com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType.UNRECOGNIZED : result; } /** * <pre> * The response content type setting. Determines whether the mutable resource * or just the resource name should be returned post mutation. * </pre> * * <code>.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 5;</code> * @param value The responseContentType to set. * @return This builder for chaining. */ public Builder setResponseContentType(com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType value) { if (value == null) { throw new NullPointerException(); } responseContentType_ = value.getNumber(); onChanged(); return this; } /** * <pre> * The response content type setting. Determines whether the mutable resource * or just the resource name should be returned post mutation. * </pre> * * <code>.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 5;</code> * @return This builder for chaining. */ public Builder clearResponseContentType() { responseContentType_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v9.services.MutateCampaignBudgetsRequest) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v9.services.MutateCampaignBudgetsRequest) private static final com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest(); } public static com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<MutateCampaignBudgetsRequest> PARSER = new com.google.protobuf.AbstractParser<MutateCampaignBudgetsRequest>() { @java.lang.Override public MutateCampaignBudgetsRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MutateCampaignBudgetsRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<MutateCampaignBudgetsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<MutateCampaignBudgetsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v9.services.MutateCampaignBudgetsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache-2.0
NSRFSN/chenWeather
app/src/main/java/com/example/chenweather/db/County.java
802
package com.example.chenweather.db; import org.litepal.crud.DataSupport; public class County extends DataSupport { private int id; private String countyName; private String weatherId; private int cityId; public int getCityId() { return cityId; } public void setCityId(int cityId) { this.cityId = cityId; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCountyName() { return countyName; } public void setCountyName(String countyName) { this.countyName = countyName; } public String getWeatherId() { return weatherId; } public void setWeatherId(String weatherId) { this.weatherId = weatherId; } }
apache-2.0
jpogran/puppetlabs-dsc
lib/puppet/type/dsc_sqldatabaserecoverymodel.rb
4477
require 'pathname' Puppet::Type.newtype(:dsc_sqldatabaserecoverymodel) do require Pathname.new(__FILE__).dirname + '../../' + 'puppet/type/base_dsc' require Pathname.new(__FILE__).dirname + '../../puppet_x/puppetlabs/dsc_type_helpers' @doc = %q{ The DSC SqlDatabaseRecoveryModel resource type. Automatically generated from 'SqlServerDsc/DSCResources/MSFT_SqlDatabaseRecoveryModel/MSFT_SqlDatabaseRecoveryModel.schema.mof' To learn more about PowerShell Desired State Configuration, please visit https://technet.microsoft.com/en-us/library/dn249912.aspx. For more information about built-in DSC Resources, please visit https://technet.microsoft.com/en-us/library/dn249921.aspx. For more information about xDsc Resources, please visit https://github.com/PowerShell/DscResources. } validate do fail('dsc_name is a required attribute') if self[:dsc_name].nil? fail('dsc_servername is a required attribute') if self[:dsc_servername].nil? fail('dsc_instancename is a required attribute') if self[:dsc_instancename].nil? end def dscmeta_resource_friendly_name; 'SqlDatabaseRecoveryModel' end def dscmeta_resource_name; 'MSFT_SqlDatabaseRecoveryModel' end def dscmeta_module_name; 'SqlServerDsc' end def dscmeta_module_version; '11.1.0.0' end newparam(:name, :namevar => true ) do end ensurable do newvalue(:exists?) { provider.exists? } newvalue(:present) { provider.create } defaultto { :present } end # Name: PsDscRunAsCredential # Type: MSFT_Credential # IsMandatory: False # Values: None newparam(:dsc_psdscrunascredential) do def mof_type; 'MSFT_Credential' end def mof_is_embedded?; true end desc "PsDscRunAsCredential" validate do |value| unless value.kind_of?(Hash) fail("Invalid value '#{value}'. Should be a hash") end PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("Credential", value) end munge do |value| PuppetX::Dsc::TypeHelpers.munge_sensitive_hash!(value) end end # Name: Name # Type: string # IsMandatory: True # Values: None newparam(:dsc_name) do def mof_type; 'string' end def mof_is_embedded?; false end desc "Name - The SQL database name" isrequired validate do |value| unless value.kind_of?(String) fail("Invalid value '#{value}'. Should be a string") end end end # Name: RecoveryModel # Type: string # IsMandatory: False # Values: ["Full", "Simple", "BulkLogged"] newparam(:dsc_recoverymodel) do def mof_type; 'string' end def mof_is_embedded?; false end desc "RecoveryModel - The recovery model to use for the database. Valid values are Full, Simple, BulkLogged." validate do |value| unless value.kind_of?(String) fail("Invalid value '#{value}'. Should be a string") end unless ['Full', 'full', 'Simple', 'simple', 'BulkLogged', 'bulklogged'].include?(value) fail("Invalid value '#{value}'. Valid values are Full, Simple, BulkLogged") end end end # Name: ServerName # Type: string # IsMandatory: True # Values: None newparam(:dsc_servername) do def mof_type; 'string' end def mof_is_embedded?; false end desc "ServerName - The host name of the SQL Server to be configured." isrequired validate do |value| unless value.kind_of?(String) fail("Invalid value '#{value}'. Should be a string") end end end # Name: InstanceName # Type: string # IsMandatory: True # Values: None newparam(:dsc_instancename) do def mof_type; 'string' end def mof_is_embedded?; false end desc "InstanceName - The name of the SQL instance to be configured." isrequired validate do |value| unless value.kind_of?(String) fail("Invalid value '#{value}'. Should be a string") end end end def builddepends pending_relations = super() PuppetX::Dsc::TypeHelpers.ensure_reboot_relationship(self, pending_relations) end end Puppet::Type.type(:dsc_sqldatabaserecoverymodel).provide :powershell, :parent => Puppet::Type.type(:base_dsc).provider(:powershell) do confine :true => (Gem::Version.new(Facter.value(:powershell_version)) >= Gem::Version.new('5.0.10586.117')) defaultfor :operatingsystem => :windows mk_resource_methods end
apache-2.0
betsythefc/custard
login_exec.php
2274
<?php //Start session session_start(); //Include database connection details require 'connection.php'; require 'mysql.php'; //Array to store validation errors $errmsg_arr = array(); //Validation error flag $errflag = false; //Function to sanitize values received from the form. Prevents SQL injection function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } //Sanitize the POST values $username = clean($_POST['username']); $password = clean($_POST['password']); //Input Validations if($username == '' || $password == '') { $errmsg_arr[] = 'Username or password is missing'; $errflag = true; } //If there are input validations, redirect back to the login form if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: index.php"); exit(); } // Get & Hash password // $mode = "verify"; // require 'passwordhash.php'; $sql = $DBH->prepare("SELECT salt FROM member WHERE username='$username'"); $sql->execute(); $result = $sql->fetch(); $salt = "{$result[salt]}"; $password = hash('sha256', "{$password}{$salt}"); //Create query // Not working yet // $sql = $DBH->prepare("SELECT * FROM member WHERE username='$username' AND password='$password'"); // $sql->execute; // $result = $sql->fetch(); $qry="SELECT * FROM member WHERE username='$username' AND password='$password'"; $result=mysql_query($qry); //Check whether the query was successful or not if($result) { if(mysql_num_rows($result) > 0) { //Login Successful session_regenerate_id(); $member = mysql_fetch_assoc($result); $_SESSION['SESS_MEMBER_ID'] = $member['mem_id']; $_SESSION['SESS_FIRST_NAME'] = $member['username']; $_SESSION['SESS_LAST_NAME'] = $member['password']; session_write_close(); header("location: index.php"); //Log file //http://php.net/manual/en/function.fwrite.php exit(); } else { //Login failed $errmsg_arr[] = "user name and password not found"; $errflag = true; if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: index.php"); exit(); } } } else { die("Query failed"); } ?>
apache-2.0
injitools/cms-Inji
system/modules/Users/appControllers/UsersController.php
10420
<?php /** * Users app controller * * @author Alexey Krupskiy <admin@inji.ru> * @link http://inji.ru/ * @copyright 2015 Alexey Krupskiy * @license https://github.com/injitools/cms-Inji/blob/master/LICENSE */ /** * @property Users $users */ class UsersController extends Controller { public function indexAction() { Tools::redirect('/users/cabinet/profile'); } public function cabinetAction($activeSection = '') { $bread = []; $sections = $this->module->getSnippets('cabinetSection'); if (!empty($sections[$activeSection]['name'])) { $this->view->setTitle($sections[$activeSection]['name'] . ' - ' . \I18n\Text::module('Users', 'Личный кабинет')); $bread[] = ['text' => 'Личный кабинет', 'href' => '/users/cabinet']; $bread[] = ['text' => $sections[$activeSection]['name']]; } else { $this->view->setTitle('Личный кабинет'); $bread[] = ['text' => 'Личный кабинет']; } $this->view->page(['data' => compact('widgets', 'sections', 'activeSection', 'bread')]); } public function loginAction() { $this->view->setTitle('Авторизация'); $bread = []; $bread[] = ['text' => 'Авторизация']; $this->view->page(['data' => compact('bread')]); } public function passreAction() { $this->view->setTitle('Восстановление пароля'); $bread = []; $bread[] = ['text' => 'Восстановление пароля']; $this->view->page(['data' => compact('bread')]); } public function registrationAction() { $this->view->setTitle('Регистрация'); if (Users\User::$cur->user_id) { Tools::redirect('/', 'Вы уже зарегистрированы'); } if (!empty($_POST)) { $error = false; if ($this->Recaptcha) { $response = $this->Recaptcha->check($_POST['g-recaptcha-response']); if ($response) { if (!$response->success) { Msg::add('Вы не прошли проверку на робота', 'danger'); $error = true; } } else { Msg::add('Произошла ошибка, попробуйте ещё раз'); $error = true; } } if (!$error) { if ($this->Users->registration($_POST)) { Tools::redirect('/'); } } } $this->view->setTitle('Регистрация'); $bread = []; $bread[] = ['text' => 'Регистрация']; $this->view->page(['data' => compact('bread')]); } public function fastRegistrationAction() { $result = new \Server\Result(); if (Users\User::$cur->user_id) { $result->success = false; $result->content = 'Вы уже зарегистрированы'; return $result->send(); } if (!empty($_POST)) { $error = false; if ($this->Recaptcha) { $response = $this->Recaptcha->check($_POST['g-recaptcha-response']); if ($response) { if (!$response->success) { $result->success = false; $result->content = 'Вы не прошли проверку на робота'; return $result->send(); } } else { $result->success = false; $result->content = 'Произошла ошибка, попробуйте ещё раз'; return $result->send(); } } if (!$error) { $resultReg = $this->Users->registration($_POST, true, false); if (is_numeric($resultReg)) { return $result->send(); } else { $result->success = false; $result->content = $resultReg['error']; return $result->send(); } } } } public function activationAction($userId = 0, $hash = '') { $user = \Users\User::get((int)$userId); if (!$user || !$hash || $user->activation !== (string)$hash) { Tools::redirect('/', 'Во время активации произошли ошибки', 'danger'); } $user->activation = ''; $user->save(); Inji::$inst->event('Users-completeActivation', $user); $session = $this->users->newSession($user, true); $this->users->setCookie('_token.local', $session->user_id . ':' . $session->hash); Tools::redirect('/', 'Вы успешно активировали ваш аккаунт', 'success'); } public function attachEmailAction() { if (Users\User::$cur->mail) { Tools::redirect('/', 'К вашему аккаунту уже привязан E-Mail'); } if (!empty($_POST['mail'])) { $user_mail = trim($_POST['mail']); if (!filter_var($user_mail, FILTER_VALIDATE_EMAIL)) { Msg::add('Вы ввели не корректный E-mail', 'danger'); } else { $user = Users\User::get($user_mail, 'mail'); if ($user && $user->id != Users\User::$cur->id) { Msg::add('Данный E-mail уже привязан к другому аккаунту', 'danger'); } else { Users\User::$cur->mail = $user_mail; if (!empty($this->module->config['needActivation'])) { Users\User::$cur->activation = Tools::randomString(); $from = 'noreply@' . INJI_DOMAIN_NAME; $to = $user_mail; $subject = 'Активация аккаунта на сайте ' . idn_to_utf8(INJI_DOMAIN_NAME); $text = 'Для активации вашего аккаунта перейдите по ссылке <a href = "http://' . INJI_DOMAIN_NAME . '/users/activation/' . Users\User::$cur->id . '/' . Users\User::$cur->activation . '">http://' . idn_to_utf8(INJI_DOMAIN_NAME) . '/users/activation/' . Users\User::$cur->id . '/' . Users\User::$cur->activation . '</a>'; Tools::sendMail($from, $to, $subject, $text); Msg::add('На указанный почтовый ящик была выслана ваша ссылка для подтверждения E-Mail', 'success'); } else { Msg::add('Вы успешно привязали E-Mail к своему аккаунту', 'success'); } Users\User::$cur->save(); Tools::redirect('/'); } } } $this->view->page(); } public function resendActivationAction($userId = 0) { $user = \Users\User::get((int)$userId); if (!$user) { Tools::redirect('/', 'Не указан пользователь', 'danger'); } if (!$user->activation) { Tools::redirect('/', 'Пользователь уже активирован'); } $from = 'noreply@' . INJI_DOMAIN_NAME; $to = $user->mail; $subject = 'Активация аккаунта на сайте ' . idn_to_utf8(INJI_DOMAIN_NAME); $text = 'Для активации вашего аккаунта перейдите по ссылке <a href = "http://' . INJI_DOMAIN_NAME . '/users/activation/' . $user->id . '/' . $user->activation . '">http://' . idn_to_utf8(INJI_DOMAIN_NAME) . '/users/activation/' . $user->id . '/' . $user->activation . '</a>'; Tools::sendMail($from, $to, $subject, $text); Tools::redirect('/', 'На указанный почтовый ящик была выслана ваша ссылка для подтверждения E-Mail', 'success'); } public function getPartnerInfoAction($userId = 0) { $userId = (int)$userId; $result = new \Server\Result(); if (!$userId) { $result->success = false; $result->content = 'Не указан пользователь'; $result->send(); } $partners = App::$cur->users->getUserPartners(Users\User::$cur, 8); if (empty($partners['users'][$userId])) { $result->success = false; $result->content = 'Этот пользователь не находится в вашей структуре'; $result->send(); } $user = $partners['users'][$userId]; ob_start(); echo "id:{$user->id}<br />"; echo "E-mail: <a href='mailto:{$user->mail}'>{$user->mail}</a>"; $rewards = Money\Reward::getList(['where' => ['active', 1]]); foreach ($rewards as $reward) { foreach ($reward->conditions as $condition) { $complete = $condition->checkComplete($userId); ?> <h5 class="<?= $complete ? 'text-success' : 'text-danger'; ?>"><?= $condition->name(); ?></h5> <ul> <?php foreach ($condition->items as $item) { $itemComplete = $item->checkComplete($userId); switch ($item->type) { case 'event': $name = \Events\Event::get($item->value, 'event')->name(); break; } ?> <li> <b class="<?= $itemComplete ? 'text-success' : 'text-danger'; ?>"><?= $name; ?> <?= $item->recivedCount($userId); ?></b>/<?= $item->count; ?> <br/> </li> <?php } ?> </ul> <?php } } $result->content = ob_get_contents(); ob_end_clean(); $result->send(); } }
apache-2.0
jdahlstrom/vaadin.react
uitest/src/test/java/com/vaadin/tests/components/listselect/ListSelectNoDomRebuildTest.java
2292
/* * Copyright 2000-2014 Vaadin 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.vaadin.tests.components.listselect; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import com.vaadin.testbench.elements.ListSelectElement; import com.vaadin.tests.tb3.SingleBrowserTest; public class ListSelectNoDomRebuildTest extends SingleBrowserTest { @Override protected Class<?> getUIClass() { return ListSelects.class; } @Test public void testNoDomRebuild() { openTestURL(); // Testbench doesn't seem to support sending key events to the right // location, so we will just verify that the DOM is not rebuilt selectMenuPath("Component", "Selection", "Multi select"); selectMenuPath("Component", "Listeners", "Value change listener"); ListSelectElement list = $(ListSelectElement.class).first(); List<WebElement> options = list.findElements(By.tagName("option")); assertNotStale(options); options.get(4).click(); assertNotStale(options); new Actions(driver).keyDown(Keys.SHIFT).perform(); options.get(2).click(); options.get(6).click(); new Actions(driver).keyUp(Keys.SHIFT).perform(); assertNotStale(options); } private void assertNotStale(List<WebElement> options) { for (WebElement element : options) { // We really don't expect the text to be null, mainly doing this // since getText() will throw if the element is detached. Assert.assertNotNull(element.getText()); } } }
apache-2.0
VHAINNOVATIONS/ASRCM
srcalc/src/main/java/gov/va/med/srcalc/web/view/admin/NumericalRangeBuilder.java
4441
package gov.va.med.srcalc.web.view.admin; import com.google.common.base.MoreObjects; import gov.va.med.srcalc.domain.model.NumericalRange; /** * <p>Builds a {@link NumericalRange} from incrementally-specified component * parts. This class is useful because NumericalRange is immutable: you must * specify all properties in its constructor and you can't use it as a Java * bean.</p> * * <p>Per Effective Java Item 17, this class is marked final because it was not * designed for inheritance.</p> */ public final class NumericalRangeBuilder { private float fLowerBound; private boolean fLowerInclusive; private float fUpperBound; private boolean fUpperInclusive; /** * Constructs an instance. The default bounds are [0,100.0]. */ public NumericalRangeBuilder() { fLowerBound = 0.0f; fLowerInclusive = true; fUpperBound = 100.0f; fUpperInclusive = true; } /** * Constructs an instance with the given initial values. These initial * values may, of course, be changed before calling {@link #build()}. */ public NumericalRangeBuilder( final float initialLowerBound, final boolean initialLowerInclusive, final float initialUpperBound, final boolean initialUpperInclusive) { fLowerBound = initialLowerBound; fLowerInclusive = initialLowerInclusive; fUpperBound = initialUpperBound; fUpperInclusive = initialUpperInclusive; } /** * Factory method to create an instance based on a prototype NumericalRange. * @return a new builder that will build ranges equivalent to the given * prototype */ public static NumericalRangeBuilder fromPrototype( final NumericalRange prototypeRange) { return new NumericalRangeBuilder( prototypeRange.getLowerBound(), prototypeRange.isLowerInclusive(), prototypeRange.getUpperBound(), prototypeRange.isUpperInclusive()); } /** * Returns the lower bound to use. */ public float getLowerBound() { return fLowerBound; } /** * Sets the lower bound to use. * @return this builder for convenience */ public NumericalRangeBuilder setLowerBound(final float lowerBound) { fLowerBound = lowerBound; return this; } /** * Returns the inclusive flag to use for the lower bound. */ public boolean getLowerInclusive() { return fLowerInclusive; } /** * Sets the inclusive flag to use for the lower bound. * @return this builder for convenience */ public NumericalRangeBuilder setLowerInclusive(final boolean lowerInclusive) { fLowerInclusive = lowerInclusive; return this; } /** * Returns the upper bound to use. */ public float getUpperBound() { return fUpperBound; } /** * Sets the upper bound to use. * @return this builder for convenience */ public NumericalRangeBuilder setUpperBound(final float upperBound) { fUpperBound = upperBound; return this; } /** * Returns the inclusive flag to use for the upper bound. */ public boolean getUpperInclusive() { return fUpperInclusive; } /** * Sets the inclusive flag to use for the upper bound. * @return this builder for convenience */ public NumericalRangeBuilder setUpperInclusive(final boolean upperInclusive) { fUpperInclusive = upperInclusive; return this; } /** * Builds the NumericalRange with the configured bounds. */ public NumericalRange build() { return new NumericalRange( fLowerBound, fLowerInclusive, fUpperBound, fUpperInclusive); } /** * Returns a string representing the object. The exact format is unspecified * but it will contain the currently-set bounds and inclusive flags. */ @Override public String toString() { return MoreObjects.toStringHelper(this) .add("fLowerBound", fLowerBound) .add("fUpperInclusive", fUpperInclusive) .add("fUpperBound", fUpperBound) .add("fUpperInclusive", fUpperInclusive) .toString(); } }
apache-2.0
NationalSecurityAgency/ghidra
Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/lang/LanguageProvider.java
1692
/* ### * IP: GHIDRA * * 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 ghidra.program.model.lang; import ghidra.util.classfinder.ExtensionPoint; /** * NOTE: ALL LanguageProvider CLASSES MUST END IN "LanguageProvider". If not, * the ClassSearcher will not find them. * * Service for providing languages. * */ public interface LanguageProvider extends ExtensionPoint { /** * Returns the language with the given name or null if no language has that name * * @param languageId the name of the language to be retrieved * @return the {@link Language} with the given name */ Language getLanguage(LanguageID languageId); /** * Returns a list of language descriptions provided by this provider */ LanguageDescription[] getLanguageDescriptions(); /** * @return true if one of more languages or language description failed to load * properly. */ boolean hadLoadFailure(); /** * Returns true if the given language has been successfully loaded * * @param languageId the name of the language to be retrieved * @return true if the given language has been successfully loaded */ boolean isLanguageLoaded(LanguageID languageId); }
apache-2.0
dpursehouse/elasticsearch
modules/transport-netty4/src/test/java/org/elasticsearch/transport/netty4/SimpleNetty4TransportTests.java
3548
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.transport.netty4; import org.elasticsearch.Version; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.network.NetworkService; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.indices.breaker.NoneCircuitBreakerService; import org.elasticsearch.test.transport.MockTransportService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.AbstractSimpleTransportTestCase; import org.elasticsearch.transport.ConnectTransportException; import org.elasticsearch.transport.Transport; import org.elasticsearch.transport.TransportSettings; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collections; import static java.util.Collections.emptyMap; import static java.util.Collections.emptySet; import static org.hamcrest.Matchers.containsString; public class SimpleNetty4TransportTests extends AbstractSimpleTransportTestCase { public static MockTransportService nettyFromThreadPool( Settings settings, ThreadPool threadPool, final Version version) { NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry(); Transport transport = new Netty4Transport(settings, threadPool, new NetworkService(settings, Collections.emptyList()), BigArrays.NON_RECYCLING_INSTANCE, namedWriteableRegistry, new NoneCircuitBreakerService()) { @Override protected Version getCurrentVersion() { return version; } }; return new MockTransportService(Settings.EMPTY, transport, threadPool); } @Override protected MockTransportService build(Settings settings, Version version) { settings = Settings.builder().put(settings).put(TransportSettings.PORT.getKey(), "0").build(); MockTransportService transportService = nettyFromThreadPool(settings, threadPool, version); transportService.start(); return transportService; } public void testConnectException() throws UnknownHostException { try { serviceA.connectToNode(new DiscoveryNode("C", new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9876), emptyMap(), emptySet(),Version.CURRENT)); fail("Expected ConnectTransportException"); } catch (ConnectTransportException e) { assertThat(e.getMessage(), containsString("connect_timeout")); assertThat(e.getMessage(), containsString("[127.0.0.1:9876]")); } } }
apache-2.0
r39132/airflow
airflow/executors/base_executor.py
6948
# -*- coding: utf-8 -*- # # 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. from builtins import range from collections import OrderedDict # To avoid circular imports import airflow.utils.dag_processing from airflow import configuration from airflow.utils.log.logging_mixin import LoggingMixin from airflow.utils.state import State PARALLELISM = configuration.conf.getint('core', 'PARALLELISM') class BaseExecutor(LoggingMixin): def __init__(self, parallelism=PARALLELISM): """ Class to derive in order to interface with executor-type systems like Celery, Mesos, Yarn and the likes. :param parallelism: how many jobs should run at one time. Set to ``0`` for infinity :type parallelism: int """ self.parallelism = parallelism self.queued_tasks = OrderedDict() self.running = {} self.event_buffer = {} def start(self): # pragma: no cover """ Executors may need to get things started. For example LocalExecutor starts N workers. """ pass def queue_command(self, simple_task_instance, command, priority=1, queue=None): key = simple_task_instance.key if key not in self.queued_tasks and key not in self.running: self.log.info("Adding to queue: %s", command) self.queued_tasks[key] = (command, priority, queue, simple_task_instance) else: self.log.info("could not queue task %s", key) def queue_task_instance( self, task_instance, mark_success=False, pickle_id=None, ignore_all_deps=False, ignore_depends_on_past=False, ignore_task_deps=False, ignore_ti_state=False, pool=None, cfg_path=None): pool = pool or task_instance.pool # TODO (edgarRd): AIRFLOW-1985: # cfg_path is needed to propagate the config values if using impersonation # (run_as_user), given that there are different code paths running tasks. # For a long term solution we need to address AIRFLOW-1986 command = task_instance.command_as_list( local=True, mark_success=mark_success, ignore_all_deps=ignore_all_deps, ignore_depends_on_past=ignore_depends_on_past, ignore_task_deps=ignore_task_deps, ignore_ti_state=ignore_ti_state, pool=pool, pickle_id=pickle_id, cfg_path=cfg_path) self.queue_command( airflow.utils.dag_processing.SimpleTaskInstance(task_instance), command, priority=task_instance.task.priority_weight_total, queue=task_instance.task.queue) def has_task(self, task_instance): """ Checks if a task is either queued or running in this executor :param task_instance: TaskInstance :return: True if the task is known to this executor """ if task_instance.key in self.queued_tasks or task_instance.key in self.running: return True def sync(self): """ Sync will get called periodically by the heartbeat method. Executors should override this to perform gather statuses. """ pass def heartbeat(self): # Triggering new jobs if not self.parallelism: open_slots = len(self.queued_tasks) else: open_slots = self.parallelism - len(self.running) self.log.debug("%s running task instances", len(self.running)) self.log.debug("%s in queue", len(self.queued_tasks)) self.log.debug("%s open slots", open_slots) sorted_queue = sorted( [(k, v) for k, v in self.queued_tasks.items()], key=lambda x: x[1][1], reverse=True) for i in range(min((open_slots, len(self.queued_tasks)))): key, (command, _, queue, simple_ti) = sorted_queue.pop(0) self.queued_tasks.pop(key) self.running[key] = command self.execute_async(key=key, command=command, queue=queue, executor_config=simple_ti.executor_config) # Calling child class sync method self.log.debug("Calling the %s sync method", self.__class__) self.sync() def change_state(self, key, state): self.log.debug("Changing state: %s", key) self.running.pop(key, None) self.event_buffer[key] = state def fail(self, key): self.change_state(key, State.FAILED) def success(self, key): self.change_state(key, State.SUCCESS) def get_event_buffer(self, dag_ids=None): """ Returns and flush the event buffer. In case dag_ids is specified it will only return and flush events for the given dag_ids. Otherwise it returns and flushes all :param dag_ids: to dag_ids to return events for, if None returns all :return: a dict of events """ cleared_events = dict() if dag_ids is None: cleared_events = self.event_buffer self.event_buffer = dict() else: for key in list(self.event_buffer.keys()): dag_id, _, _, _ = key if dag_id in dag_ids: cleared_events[key] = self.event_buffer.pop(key) return cleared_events def execute_async(self, key, command, queue=None, executor_config=None): # pragma: no cover """ This method will execute the command asynchronously. """ raise NotImplementedError() def end(self): # pragma: no cover """ This method is called when the caller is done submitting job and wants to wait synchronously for the job submitted previously to be all done. """ raise NotImplementedError() def terminate(self): """ This method is called when the daemon receives a SIGTERM """ raise NotImplementedError()
apache-2.0
eoasoft/evolve
application/modules/hra/controllers/AttendanceController.php
37562
<?php /** * 2013-8-17 上午5:49:43 * @author x.li * @abstract */ class Hra_AttendanceController extends Zend_Controller_Action { public function indexAction() { $user_session = new Zend_Session_Namespace('user'); $this->view->hraAdmin = 0; $this->view->user_id = 0; if(isset($user_session->user_info)){ $this->view->user_id = $user_session->user_info['user_id']; if ($user_session->user_info['isSuperAdmin']) { $this->view->hraAdmin = 1; } else { if(Application_Model_User::checkPermissionByRoleName('系统管理员') || Application_Model_User::checkPermissionByRoleName('人事主管')){ $this->view->hraAdmin = 1; } } } } public function refreshhoursAction() { $attendance = new Hra_Model_Attendance(); $data = $attendance->fetchAll("clock_in != '' and clock_out != ''")->toArray(); foreach ($data as $d){ $clock_hours = (strtotime($d['clock_out']) - strtotime($d['clock_in'])) / 3600; $attendance->update(array('clock_hours' => $clock_hours), 'id = '.$d['id']); } exit; } /** * 根据员工打卡时间,判断打卡类别(0:无,1:上班,2:下班) * @param unknown $number * @param unknown $time */ public function checkAttendanceType($number, $time, $attendance_id = null) { $type = 0; $attendance = new Hra_Model_Attendance(); // 打卡记录ID $idCond = ""; // 当打卡记录ID不为空时,当前操作属于更新数据,需要排除当前打卡记录ID if($attendance_id){ $idCond = " and id != ".$attendance_id; } $date = date('Y-m-d', strtotime($time)); // 检查员工当天是否有更早的打卡时间 if($attendance->fetchAll("number = '".$number."' and DATE(time) = '".$date."' and time < '".$time."'".$idCond)->count() > 0){ // 检查员工当天是否有更晚的打卡时间 if($attendance->fetchAll("number = '".$number."' and DATE(time) = '".$date."' and time > '".$time."'".$idCond)->count() > 0){ // 当前打卡类型为“0:无” $type = 0; }else{ // 当前打卡类型为“2:下班” $type = 2; } }else{ // 当前打卡类型为“1:上班” $type = 1; } return $type; } public function setAttendanceType($id) { $attendance = new Hra_Model_Attendance(); $data = $attendance->fetchRow("id = ".$id)->toArray(); $type = $this->checkAttendanceType($data['number'], $data['time'], $id); $date = date('Y-m-d', strtotime($data['time'])); // 当类别不为0时,更新原有数据中(当天、当前用户)打卡类别为当前类别的数据为0(更新打卡类别) if($type != 0){ try { $updateData = array( 'type' => 0, 'sec_late' => 0, 'sec_leave' => 0, 'sec_truancy_half' => 0, 'sec_truancy' => 0, 'clock_chk' => 0, 'clock_info' => null ); $attendance->update($updateData, "id != ".$id." and number = '".$data['number']."' and DATE(time) = '".$date."' and type = ".$type); } catch (Exception $e) { $result['success'] = false; $result['info'] = $e->getMessage(); echo Zend_Json::encode($result); exit; } } try { $attendance->update(array('type' => $type), "id = ".$id); } catch (Exception $e) { $result['success'] = false; $result['info'] = $e->getMessage(); echo Zend_Json::encode($result); exit; } } // 修改打卡记录 public function editattendanceAction() { $result = array( 'success' => true, 'info' => '保存成功' ); $request = $this->getRequest()->getParams(); $now = date('Y-m-d H:i:s'); $user_session = new Zend_Session_Namespace('user'); $user_id = $user_session->user_info['user_id']; $json = json_decode($request['json']); $updated = $json->updated; $inserted = $json->inserted; $deleted = $json->deleted; $attendance = new Hra_Model_Attendance(); if(count($updated) > 0){ foreach ($updated as $val){ $clock_in = str_replace('T', ' ', $val->clock_in); $clock_out = str_replace('T', ' ', $val->clock_out); if($attendance->fetchAll("id != ".$val->id." and number = '".$val->number."' and (clock_in = '".$clock_in."' or clock_out = '".$clock_out."')")->count() > 0){ $result['success'] = false; $result['info'] = $val->number." 打卡时间重叠,请确认打卡时间!"; echo Zend_Json::encode($result); exit; } } foreach ($updated as $val){ $clock_in = str_replace('T', ' ', $val->clock_in); $clock_out = str_replace('T', ' ', $val->clock_out); $clock_hours = 0; if($clock_in != '' && $clock_out != ''){ $clock_hours = (strtotime($clock_out) - strtotime($clock_in)) / 3600; } $data = array( 'number' => $val->number, 'clock_in' => $clock_in, 'clock_out' => $clock_out, 'clock_hours' => $clock_hours, 'clock_chk' => 0,// 更新数据后需要重新刷新打卡结果 'remark' => $val->remark, 'update_time' => $now, 'update_user' => $user_id ); $where = "id = ".$val->id; try { $attendance->update($data, $where); } catch (Exception $e) { $result['success'] = false; $result['info'] = $e->getMessage(); echo Zend_Json::encode($result); exit; } } } if(count($inserted) > 0){ foreach ($inserted as $val){ $clock_in = str_replace('T', ' ', $val->clock_in); $clock_out = str_replace('T', ' ', $val->clock_out); if($attendance->fetchAll("number = '".$val->number."' and (clock_in = '".$clock_in."' or clock_out = '".$clock_out."')")->count() > 0){ $result['success'] = false; $result['info'] = $val->number." 打卡时间重叠,请确认打卡时间!"; echo Zend_Json::encode($result); exit; } } foreach ($inserted as $val){ $clock_in = str_replace('T', ' ', $val->clock_in); $clock_out = str_replace('T', ' ', $val->clock_out); $clock_hours = 0; if($clock_in != '' && $clock_out != ''){ $clock_hours = (strtotime($clock_out) - strtotime($clock_in)) / 3600; } $data = array( 'number' => $val->number, 'clock_in' => $clock_in, 'clock_out' => $clock_out, 'clock_hours' => $clock_hours, 'remark' => $val->remark, 'create_time' => $now, 'create_user' => $user_id, 'update_time' => $now, 'update_user' => $user_id ); try { $attendance->insert($data); } catch (Exception $e) { $result['success'] = false; $result['info'] = $e->getMessage(); echo Zend_Json::encode($result); exit; } } } if(count($deleted) > 0){ foreach ($deleted as $val){ try { $attendance->delete("id = ".$val->id); } catch (Exception $e){ $result['success'] = false; $result['info'] = $e->getMessage(); echo Zend_Json::encode($result); exit; } } } echo Zend_Json::encode($result); exit; } // 导入测试数据 public function addtestdataAction() { $result = array( 'success' => true, 'info' => '导入成功' ); $now = date('Y-m-d H:i:s'); $user_session = new Zend_Session_Namespace('user'); $user_id = $user_session->user_info['user_id']; $employee = new Hra_Model_Employee(); $eArr = $employee->fetchAll()->toArray(); $dateStart = '2014-01-01'; $attendance = new Hra_Model_Attendance(); for($i = 0; $i < 59; $i++){ $date = date('Y-m-d', strtotime($dateStart."+".$i." day")); $w = date('w', strtotime($date)); if($w != 0 && $w != 6){ foreach ($eArr as $e){ $data = array( 'number' => $e['number'], 'time' => $date.' 08:55:12', 'type' => 1, 'remark' => '123', 'create_user' => $user_id, 'create_time' => $now, 'update_user' => $user_id, 'update_time' => $now ); $attendance->insert($data); $data = array( 'number' => $e['number'], 'time' => $date.' 18:01:33', 'type' => 2, 'remark' => '456', 'create_user' => $user_id, 'create_time' => $now, 'update_user' => $user_id, 'update_time' => $now ); $attendance->insert($data); } } } echo Zend_Json::encode($result); exit; } // 导入打卡记录 public function importAction() { $result = array( 'success' => true, 'info' => '导入成功' ); $request = $this->getRequest()->getParams(); $type = isset($request['type']) ? $request['type'] : null; if(isset($_FILES['csv'])){ $now = date('Y-m-d H:i:s'); $user_session = new Zend_Session_Namespace('user'); $user_id = $user_session->user_info['user_id']; $file = $_FILES['csv']; $file_extension = strrchr($file['name'], "."); $h = new Application_Model_Helpers(); $tmp_file_name = $h->getMicrotimeStr().$file_extension; $savepath = "../temp/"; $tmp_file_path = $savepath.$tmp_file_name; move_uploaded_file($file["tmp_name"], $tmp_file_path); if($type == 'attendance'){ $attendance = new Hra_Model_Attendance(); // 出勤 $file = fopen($tmp_file_path, "r"); $insertIds = array(); while(! feof($file)) { $csv_data = fgetcsv($file); $number = isset($csv_data[0]) && $csv_data[0] != '' ? $csv_data[0] : null; $clock_in = isset($csv_data[2]) && $csv_data[2] != '' ? $csv_data[1].' '.$csv_data[2] : null; $clock_out = isset($csv_data[3]) && $csv_data[3] != '' ? $csv_data[1].' '.$csv_data[3] : null; if($number && ($clock_in || $clock_out)){ // 获取打卡日期:上班或下班打卡日期 $clock_date = $clock_in ? date('Y-m-d', strtotime($clock_in)) : date('Y-m-d', strtotime($clock_out)); if($attendance->fetchAll("number = '".$number."' and clock_date = '".$clock_date."'")->count() == 0){ $clock_hours = 0; if($clock_in != '' && $clock_out != ''){ $clock_hours = (strtotime($clock_out) - strtotime($clock_in)) / 3600; } $data = array( 'number' => $number, 'clock_date' => $clock_date, 'clock_in' => $clock_in, 'clock_out' => $clock_out, 'clock_hours' => $clock_hours, 'create_user' => $user_id, 'create_time' => $now, 'update_user' => $user_id, 'update_time' => $now ); try { $insertId = $attendance->insert($data); array_push($insertIds, $insertId); } catch (Exception $e) { $result['success'] = false; $result['info'] = $e->getMessage(); echo Zend_Json::encode($result); exit; } } } } fclose($file); // 刷新打卡类别setAttendanceType($id) /* foreach ($insertIds as $id){ $this->setAttendanceType($id); } */ } } echo Zend_Json::encode($result); exit; } // 刷新员工年假库 public function refreshvacationstorageAction() { $result = array( 'success' => true, 'info' => '刷新成功' ); $request = $this->getRequest()->getParams(); $employee_id = isset($request['employee_id']) ? $request['employee_id'] : null; $cover = isset($request['cover']) ? $request['cover'] : 0; $storage = new Hra_Model_Vacationstorage(); $result = $storage->refreshStorage($employee_id, $cover); echo Zend_Json::encode($result); exit; } /** * 获取年假库 */ public function getvacationstorageAction() { $request = $this->getRequest()->getParams(); $option = isset($request['option']) ? $request['option'] : 'list'; $condition = array( 'key' => isset($request['key']) ? $request['key'] : '', 'type' => $option ); $storage = new Hra_Model_Vacationstorage(); $data = $storage->getList($condition); if($option == 'csv'){ $this->view->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $h = new Application_Model_Helpers(); $h->exportCsv($data, '假期库'); }else{ echo Zend_Json::encode($data); } exit; } /** * 获取出勤信息 */ public function getattendanceAction() { $request = $this->getRequest()->getParams(); $option = isset($request['option']) ? $request['option'] : 'list'; $condition = array( 'key' => isset($request['key']) ? $request['key'] : '', 'only_on_and_off' => isset($request['only_on_and_off']) ? ($request['only_on_and_off'] == 'true' ? 1: 0) : 0, 'date_from' => isset($request['date_from']) ? $request['date_from'] : date('Y-m-01'), 'date_to' => isset($request['date_to']) ? $request['date_to'] : date('Y-m-t'), 'dept' => isset($request['dept']) ? $request['dept'] : 0, 'page' => isset($request['page']) ? $request['page'] : 1, 'limit' => isset($request['limit']) ? $request['limit'] : 0, 'type' => $option ); $attendance = new Hra_Model_Attendance(); $data = $attendance->getAttendanceList($condition); if($option == 'csv'){ $this->view->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $h = new Application_Model_Helpers(); $h->exportCsv($data, '打卡记录'); }else{ echo Zend_Json::encode($data); } exit; } /** * 获取考勤统计信息 */ public function getstatisticsAction() { $request = $this->getRequest()->getParams(); $option = isset($request['option']) ? $request['option'] : 'list'; $condition = array( 'key' => isset($request['key']) ? $request['key'] : null, 'employment_type' => isset($request['employment_type']) ? $request['employment_type'] : 1, 'date_from' => isset($request['date_from']) ? $request['date_from'] : date('Y-m-01'), 'date_to' => isset($request['date_to']) ? $request['date_to'] : date('Y-m-t'), 'page' => isset($request['page']) ? $request['page'] : 1, 'limit' => isset($request['limit']) ? $request['limit'] : 0, 'type' => $option ); $attendance = new Hra_Model_Attendance(); $data = $attendance->getStatisticsList($condition); if($option == 'csv'){ $this->view->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $h = new Application_Model_Helpers(); $h->exportCsv($data, '考勤统计'); }else{ echo Zend_Json::encode($data); } exit; } /** * 初始化年份工作日设置 */ public function iniworkdayAction() { // 返回值数组 $result = array( 'success' => true, 'info' => '编辑成功' ); $request = $this->getRequest()->getParams(); if(isset($request['year'])){ $workday = new Hra_Model_Workday(); $r = $workday->fetchAll("day like '".$request['year']."%'")->toArray(); if(count($r) > 0){ $result['success'] = false; $result['info'] = '年份设置错误,'.$request['year'].'年已有数据!'; }else{ $day = $request['year'].'-01-01'; $end = $request['year'].'-12-31'; $now = date('Y-m-d H:i:s'); $user_session = new Zend_Session_Namespace('user'); $user_id = $user_session->user_info['user_id']; while($day <= $end){ $weekIdx = date('w', strtotime($day)); $type = 1; if($weekIdx == 0 || $weekIdx == 6){ $type = 2; } $data = array( 'day' => $day, 'type' => $type, 'create_time' => $now, 'create_user' => $user_id, 'update_time' => $now, 'update_user' => $user_id ); $workday->insert($data); $day = date('Y-m-d', strtotime($day."+1 day")); } } }else{ $result['success'] = false; $result['info'] = '未设置年份'; } echo Zend_Json::encode($result); exit; } /** * 获取参数设置 */ public function getparamAction() { $param = new Hra_Model_Attendanceparams(); echo Zend_Json::encode($param->getData()); exit; } public function editparamAction() { // 返回值数组 $result = array( 'success' => true, 'info' => '编辑成功' ); $request = $this->getRequest()->getParams(); $now = date('Y-m-d H:i:s'); $user_session = new Zend_Session_Namespace('user'); $user_id = $user_session->user_info['user_id']; $json = json_decode($request['json']); $updated = $json->updated; $inserted = $json->inserted; $deleted = $json->deleted; $param = new Hra_Model_Attendanceparams(); if(count($updated) > 0){ foreach ($updated as $val){ if ($param->fetchAll("id != ".$val->id." and employment_type = ".$val->employment_type)->count() == 0) { foreach ($updated as $val){ $data = array( 'employment_type' => $val->employment_type, 'private' => $val->private, 'vacation' => $val->vacation, 'sick' => $val->sick, 'marriage' => $val->marriage, 'funeral' => $val->funeral, 'maternity' => $val->maternity, 'paternity' => $val->paternity, 'other' => $val->other, 'remark' => $val->remark, 'update_time' => $now, 'update_user' => $user_id ); $where = "id = ".$val->id; try { $param->update($data, $where); } catch (Exception $e) { $result['success'] = false; $result['info'] = $e->getMessage(); echo Zend_Json::encode($result); exit; } } }else{ $result['success'] = false; $result['info'] = '用工形式数据已存在,请勿重复添加!'; echo Zend_Json::encode($result); exit; } } } if(count($inserted) > 0){ foreach ($inserted as $val){ if ($param->fetchAll("employment_type = ".$val->employment_type)->count() == 0) { $data = array( 'employment_type' => $val->employment_type, 'private' => $val->private, 'vacation' => $val->vacation, 'sick' => $val->sick, 'marriage' => $val->marriage, 'funeral' => $val->funeral, 'maternity' => $val->maternity, 'paternity' => $val->paternity, 'other' => $val->other, 'remark' => $val->remark, 'create_time' => $now, 'create_user' => $user_id, 'update_time' => $now, 'update_user' => $user_id ); try { $param->insert($data); } catch (Exception $e) { $result['success'] = false; $result['info'] = $e->getMessage(); echo Zend_Json::encode($result); exit; } }else{ $result['success'] = false; $result['info'] = '用工形式数据已存在,请勿重复添加!'; echo Zend_Json::encode($result); exit; } } } if(count($deleted) > 0){ foreach ($deleted as $val){ try { $param->delete("id = ".$val->id); } catch (Exception $e){ $result['success'] = false; $result['info'] = $e->getMessage(); echo Zend_Json::encode($result); exit; } } } echo Zend_Json::encode($result); exit; } /** * 获取工作日设置 */ public function getworkdayAction() { $request = $this->getRequest()->getParams(); $option = isset($request['option']) ? $request['option'] : 'list'; $condition = array( 'type' => isset($request['type']) ? $request['type'] : 0, 'date_from' => isset($request['date_from']) ? $request['date_from'] : date('Y-m-01'), 'date_to' => isset($request['date_to']) ? $request['date_to'] : date('Y-m-t') ); /* echo '<pre>'; print_r($condition); */ $workday = new Hra_Model_Workday(); if($option == 'list'){ echo Zend_Json::encode($workday->getWorkdayList($condition)); } exit; } /** * 编辑工作日设置 */ public function editworkdayAction() { // 返回值数组 $result = array( 'success' => true, 'info' => '编辑成功' ); $request = $this->getRequest()->getParams(); $now = date('Y-m-d H:i:s'); $user_session = new Zend_Session_Namespace('user'); $user_id = $user_session->user_info['user_id']; $json = json_decode($request['json']); $updated = $json->updated; $workday = new Hra_Model_Workday(); if(count($updated) > 0){ foreach ($updated as $val){ $data = array( 'type' => $val->type, 'remark' => $val->remark, 'update_time' => $now, 'update_user' => $user_id ); $where = "id = ".$val->id; try { $workday->update($data, $where); } catch (Exception $e) { $result['success'] = false; $result['info'] = $e->getMessage(); echo Zend_Json::encode($result); exit; } } } echo Zend_Json::encode($result); exit; } /** * 编辑假期库 */ public function editvacationstorageAction() { // 返回值数组 $result = array( 'success' => true, 'info' => '编辑成功' ); $request = $this->getRequest()->getParams(); $now = date('Y-m-d H:i:s'); $user_session = new Zend_Session_Namespace('user'); $user_id = $user_session->user_info['user_id']; $json = json_decode($request['json']); $updated = $json->updated; $storage = new Hra_Model_Vacationstorage(); if(count($updated) > 0){ foreach ($updated as $val){ $data = array( 'qty' => $val->qty, 'qty_used' => $val->qty_used, 'remark' => $val->remark, 'update_time' => $now, 'update_user' => $user_id ); $where = "id = ".$val->id; try { $storage->update($data, $where); } catch (Exception $e) { $result['success'] = false; $result['info'] = $e->getMessage(); echo Zend_Json::encode($result); exit; } } } echo Zend_Json::encode($result); exit; } /** * 获取工作时间设置 */ public function getworktimeAction() { $request = $this->getRequest()->getParams(); $option = isset($request['option']) ? $request['option'] : 'list'; $condition = array( 'type' => isset($request['type']) ? $request['type'] : 0 ); $worktime = new Hra_Model_Worktime(); if($option == 'list'){ echo Zend_Json::encode($worktime->getWorktimeList($condition)); } exit; } public function testAction() { $workday = new Hra_Model_Workday(); $workdaySetting = $workday->getDayQtyBase(1, 0, '2014-07-01', '2014-07-31'); echo '<pre>';print_r($workdaySetting);exit; } /** * 编辑工作时间设置 */ public function editworktimeAction() { // 返回值数组 $result = array( 'success' => true, 'info' => '编辑成功' ); $request = $this->getRequest()->getParams(); $now = date('Y-m-d H:i:s'); $user_session = new Zend_Session_Namespace('user'); $user_id = $user_session->user_info['user_id']; $json = json_decode($request['json']); $updated = $json->updated; $inserted = $json->inserted; $deleted = $json->deleted; $worktime = new Hra_Model_Worktime(); if(count($updated) > 0){ foreach ($updated as $val){ if ($worktime->fetchAll("id != ".$val->id." and type = ".$val->type)->count() == 0) { $data = array( 'type' => $val->type, 'active_from' => $val->active_from, 'active_to' => $val->active_to, 'work_from' => str_replace('T', ' ', $val->work_from), 'work_to' => str_replace('T', ' ', $val->work_to), 'rest_from' => str_replace('T', ' ', $val->rest_from), 'rest_to' => str_replace('T', ' ', $val->rest_to), 'limit_late' => $val->limit_late, 'limit_leave' => $val->limit_leave, 'limit_truancy_half' => $val->limit_truancy_half, 'limit_truancy' => $val->limit_truancy, 'remark' => $val->remark, 'update_time' => $now, 'update_user' => $user_id ); $where = "id = ".$val->id; try { $worktime->update($data, $where); } catch (Exception $e) { $result['success'] = false; $result['info'] = $e->getMessage(); echo Zend_Json::encode($result); exit; } }else{ $result['success'] = false; $result['info'] = '用工形式数据已存在,请勿重复添加!'; echo Zend_Json::encode($result); exit; } } } if(count($inserted) > 0){ foreach ($inserted as $val){ if ($worktime->fetchAll("type = ".$val->type)->count() == 0) { $data = array( 'type' => $val->type, 'active_from' => $val->active_from, 'active_to' => $val->active_to, 'work_from' => $val->work_from, 'work_to' => $val->work_to, 'rest_from' => $val->rest_from, 'rest_to' => $val->rest_to, 'limit_late' => $val->limit_late, 'limit_leave' => $val->limit_leave, 'limit_truancy_half' => $val->limit_truancy_half, 'limit_truancy' => $val->limit_truancy, 'remark' => $val->remark, 'create_time' => $now, 'create_user' => $user_id, 'update_time' => $now, 'update_user' => $user_id ); try { $worktime->insert($data); } catch (Exception $e) { $result['success'] = false; $result['info'] = $e->getMessage(); echo Zend_Json::encode($result); exit; } }else{ $result['success'] = false; $result['info'] = '用工形式数据已存在,请勿重复添加!'; echo Zend_Json::encode($result); exit; } } } if(count($deleted) > 0){ foreach ($deleted as $val){ try { $worktime->delete("id = ".$val->id); } catch (Exception $e){ $result['success'] = false; $result['info'] = $e->getMessage(); echo Zend_Json::encode($result); exit; } } } echo Zend_Json::encode($result); exit; } }
apache-2.0
martin-g/wicket-osgi
wicket-core/src/test/java/org/apache/wicket/request/cycle/RequestCycleUrlForTest.java
6662
/* * 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.wicket.request.cycle; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.apache.wicket.mock.MockHomePage; import org.apache.wicket.request.IExceptionMapper; import org.apache.wicket.request.IRequestMapper; import org.apache.wicket.request.Request; import org.apache.wicket.request.Response; import org.apache.wicket.request.Url; import org.apache.wicket.core.request.handler.BookmarkablePageRequestHandler; import org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler; import org.apache.wicket.request.handler.resource.ResourceRequestHandler; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.request.resource.ByteArrayResource; import org.apache.wicket.request.resource.IResource; import org.apache.wicket.request.resource.ResourceReference; import org.apache.wicket.request.resource.caching.IStaticCacheableResource; import org.apache.wicket.response.StringResponse; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Tests that RequestCycle#urlFor() does not encode the jsessionid for static resources. * * https://issues.apache.org/jira/browse/WICKET-4334 */ public class RequestCycleUrlForTest extends Assert { private static final String JSESSIONID = ";jsessionid=1234567890"; private static final String BOOKMARKABLE_PAGE_URL = "/bookmarkablePage"; private static final String RES_REF_URL = "/resRef"; private static final String RESOURCE_URL = "/res"; RequestCycle requestCycle; @Before public void before() { Request request = mock(Request.class); Response response = new StringResponse() { @Override public String encodeURL(CharSequence url) { return url + JSESSIONID; } }; IRequestMapper mapper = mock(IRequestMapper.class); Url bookmarkablePageUrl = Url.parse(BOOKMARKABLE_PAGE_URL); when(mapper.mapHandler(argThat(new ExactClassMatcher<BookmarkablePageRequestHandler>(BookmarkablePageRequestHandler.class)))).thenReturn(bookmarkablePageUrl); Url resourceUrl = Url.parse(RESOURCE_URL); when(mapper.mapHandler(argThat(new ExactClassMatcher<ResourceRequestHandler>(ResourceRequestHandler.class)))).thenReturn(resourceUrl); Url resourceReferenceUrl = Url.parse(RES_REF_URL); when(mapper.mapHandler(argThat(new ExactClassMatcher<ResourceReferenceRequestHandler>(ResourceReferenceRequestHandler.class)))).thenReturn(resourceReferenceUrl); IExceptionMapper exceptionMapper = mock(IExceptionMapper.class); RequestCycleContext context = new RequestCycleContext(request, response, mapper, exceptionMapper); requestCycle = new RequestCycle(context); } /** * Pages should have the jsessionid encoded in the url * * @throws Exception */ @Test public void urlForClass() throws Exception { CharSequence url = requestCycle.urlFor(MockHomePage.class, new PageParameters()); assertEquals("/bookmarkablePage"+JSESSIONID, url); } /** * ResourceReference with IStaticCacheableResource should not have the jsessionid encoded in the url * * @throws Exception */ @Test public void urlForResourceReference() throws Exception { final IStaticCacheableResource resource = mock(IStaticCacheableResource.class); ResourceReference reference = new ResourceReference("dummy") { @Override public IResource getResource() { return resource; } }; ResourceReferenceRequestHandler handler = new ResourceReferenceRequestHandler(reference); CharSequence url = requestCycle.urlFor(handler); assertEquals(RES_REF_URL, url); } /** * ResourceReference with non-IStaticCacheableResource should not have the jsessionid encoded in the url * * @throws Exception */ @Test public void urlForResourceReferenceWithNonStaticResource() throws Exception { final IResource resource = mock(IResource.class); ResourceReference reference = new ResourceReference("dummy") { @Override public IResource getResource() { return resource; } }; ResourceReferenceRequestHandler handler = new ResourceReferenceRequestHandler(reference); CharSequence url = requestCycle.urlFor(handler); assertEquals(RES_REF_URL+JSESSIONID, url); } /** * IStaticCacheableResource should not have the jsessionid encoded in the url * * @throws Exception */ @Test public void urlForStaticResource() throws Exception { IStaticCacheableResource resource = mock(IStaticCacheableResource.class); ResourceRequestHandler handler = new ResourceRequestHandler(resource, new PageParameters()); CharSequence url = requestCycle.urlFor(handler); assertEquals(RESOURCE_URL, url); } /** * Non-IStaticCacheableResource should have the jsessionid encoded in the url * * @throws Exception */ @Test public void urlForDynamicResource() throws Exception { ByteArrayResource resource = new ByteArrayResource(null, new byte[] {1, 2}, "test.bin"); ResourceRequestHandler handler = new ResourceRequestHandler(resource, new PageParameters()); CharSequence url = requestCycle.urlFor(handler); assertEquals(RESOURCE_URL + JSESSIONID, url); } /** * A matcher that matches only when the object class is exactly the same as the expected one. * * @param <T> * the type of the expected class */ private static class ExactClassMatcher<T> extends BaseMatcher<T> { private final Class<T> targetClass; public ExactClassMatcher(Class<T> targetClass) { this.targetClass = targetClass; } @SuppressWarnings("unchecked") public boolean matches(Object obj) { if (obj != null) { return targetClass.equals(obj.getClass()); } return false; } public void describeTo(Description desc) { desc.appendText("Matches a class or subclass"); } } }
apache-2.0
dzhemriza/fsola
src/test/java/org/fsola/test/searching/FibonacciSearchTest.java
1305
/* * org.fsola * * File Name: FibonacciSearchTest.java * * Copyright 2014 Dzhem Riza * * 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.fsola.test.searching; import org.fsola.searching.FibonacciSearch; import org.fsola.sorting.QuickSort; import org.fsola.test.utils.Utils; import org.junit.Assert; import org.junit.Test; public class FibonacciSearchTest { @Test public void test1() { int[] a = Utils.randomIntArray(2048, 2048); QuickSort.quick1(a); for (int i = 0; i < a.length; ++i) { int result = FibonacciSearch.fibSearch(a, a[i]); Assert.assertEquals(a[i], a[result]); } for (int i = 2048; i < 4098; ++i) { Assert.assertEquals(-1, FibonacciSearch.fibSearch(a, i)); } } }
apache-2.0
KonstantinSviridov/raml-1-parser-test-utils
src/index.ts
2006
import impl = require("./impl"); import valuesCompare = require("./valuesCompare"); export const TRAVIS_COMMIT_MESSAGE = 'TRAVIS_COMMIT_MESSAGE'; export const TRAVIS_TRIGGER_FILE_NAME = "trigger.txt"; export function rootDir(currentDir:string) { return impl.rootDir(currentDir); } export function configureSecurity(homeDir:string) { return impl.configureSecurity(homeDir); } export function setSSHUrl(workingDir:string){ return impl.setSSHUrl(workingDir); } export function setGitUser(workingDir:string){ return impl.setGitUser(workingDir); } export function contributeTheStorage( workingDir:string, paths:string[], messageOrFileName:string, messageFromFile=false){ return impl.contributeTheStorage(workingDir,paths,messageOrFileName,messageFromFile); } export function extractValueFromTravisCommitMessage(tag:string):string{ return impl.extractValueFromTravisCommitMessage(tag); } export function cloneRepository(dir:string,uri:string,params?:any){ return impl.cloneRepository(dir,uri,params); } export function checkoutCommit(dir:string,commitId:string){ return impl.checkoutCommit(dir,commitId); } export function getLastCommitId(wrkDir:string){ return impl.getLastCommitId(wrkDir); } export function isWindows():boolean{ return impl.isWindows(); } export function deleteFolderRecursive(folder : string) { return impl.deleteFolderRecursive(folder); }; export interface Difference { message(label0?:string,label1?:string):string values():any[] path():string comment():string } export function compare(arg0:any,arg1:any):Difference[] { return valuesCompare.compare(arg0,arg1); } export function insertDummyChanges(rootDir:string,fileName:string=TRAVIS_TRIGGER_FILE_NAME){ return impl.insertDummyChanges(rootDir,fileName); } export function pluginBranch(pluginName:string,folderOrDescriptor:string, rootFolder?:string):string{ return impl.pluginBranch(pluginName,folderOrDescriptor,rootFolder); }
apache-2.0
webadvancedservicescom/magento
app/code/Magento/CatalogSearch/Model/Indexer/Fulltext/Plugin/Product/Action.php
1703
<?php /** * @copyright Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com) */ namespace Magento\CatalogSearch\Model\Indexer\Fulltext\Plugin\Product; use Magento\CatalogSearch\Model\Indexer\Fulltext\Plugin\AbstractPlugin; class Action extends AbstractPlugin { /** * Reindex on product attribute mass change * * @param \Magento\Catalog\Model\Product\Action $subject * @param \Closure $closure * @param array $productIds * @param array $attrData * @param int $storeId * @return \Magento\Catalog\Model\Product\Action * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundUpdateAttributes( \Magento\Catalog\Model\Product\Action $subject, \Closure $closure, array $productIds, array $attrData, $storeId ) { $result = $closure($productIds, $attrData, $storeId); $this->reindexList(array_unique($productIds)); return $result; } /** * Reindex on product websites mass change * * @param \Magento\Catalog\Model\Product\Action $subject * @param \Closure $closure * @param array $productIds * @param array $websiteIds * @param string $type * @return \Magento\Catalog\Model\Product\Action * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundUpdateWebsites( \Magento\Catalog\Model\Product\Action $subject, \Closure $closure, array $productIds, array $websiteIds, $type ) { $result = $closure($productIds, $websiteIds, $type); $this->reindexList(array_unique($productIds)); return $result; } }
apache-2.0
makeok/zhw-util
src/com/zhw/core/util/JsonUtil.java
1579
package com.zhw.core.util; import java.sql.Timestamp; import java.util.Date; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; public class JsonUtil { private static SerializeConfig mapping = new SerializeConfig(); private static String dateFormat; static { dateFormat = "yyyy-MM-dd HH:mm:ss"; mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat)); mapping.put(Timestamp.class, new SimpleDateFormatSerializer(dateFormat)); } /** * 默认的处理时间 * * @param jsonText * @return */ public static String toJSON(Object jsonText) { return JSON.toJSONString(jsonText, SerializerFeature.WriteDateUseDateFormat); } /** * 自定义时间格式 * * @param jsonText * @return */ public static String toJSONDef(Object jsonText) { return JSON.toJSONString(jsonText, mapping); } /** * 自定义时间格式 * * @param jsonText * @return */ public static String toJSON(Object jsonText,String format) { SerializeConfig map = new SerializeConfig(); map.put(Date.class, new SimpleDateFormatSerializer(format)); map.put(Timestamp.class, new SimpleDateFormatSerializer(format)); return JSON.toJSONString(jsonText, map); } }
apache-2.0
ManfredTremmel/gwt-bean-validators
gwt-bean-validators/src/main/java/de/knightsoftnet/validators/client/decorators/UniversalDecoratorWithIcons.java
2937
/* * 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 de.knightsoftnet.validators.client.decorators; import com.google.gwt.core.shared.GWT; import com.google.gwt.resources.client.DataResource; import com.google.gwt.uibinder.client.UiConstructor; /** * This is a Decorator which in changes style sheets and shows error messages when validation fails. * * <h3>Use in UiBinder Templates</h3> * <p> * The decorator may have exactly one Widget added though an <code>&lt;e:widget&gt;</code> child * tag. * </p> * <p> * For example: * </p> * * <pre> * &#064;UiField * UniversalDecoratorWithIcons&lt;String&gt; name; * </pre> * * <pre> * &lt;e:UniversalDecoratorWithIcons ui:field='name'&gt; * &lt;e:widget&gt; * &lt;g:TextBox /&gt; * &lt;/e:widget&gt; * &lt;/e:UniversalDecoratorWithIcons&gt; * </pre> * * @param <T> the type of data being edited */ public class UniversalDecoratorWithIcons<T> extends AbstractDecorator<T> { /** * A ClientBundle that provides images and style sheets for the decorator. */ public interface ExtendedResources extends Resources { @DataResource.MimeType("image/svg+xml") @Source("valid.svg") DataResource resValidImage(); @DataResource.MimeType("image/svg+xml") @Source("error.svg") DataResource resErrorImage(); /** * The styles used in this widget. * * @return decorator style */ @Override @Source("EditorDecoratorWithIcons.gss") DecoratorStyle decoratorStyle(); } /** * the default resources. */ private static ExtendedResources extendedResource; /** * Constructs a ValueBoxEditorDecorator. * * @param errorLocation location of the error text */ @UiConstructor public UniversalDecoratorWithIcons(final PanelLocationEnum errorLocation) { super(errorLocation, getExtendedResources()); } /** * get default resource, if not set, create one. * * @return default resource. */ protected static Resources getExtendedResources() { if (extendedResource == null) { // NOPMD needn't be thread save on client side extendedResource = GWT.create(ExtendedResources.class); } return extendedResource; } }
apache-2.0
MouslihAbdelhakim/Quick
src/main/scala/com/scalableQuality/quick/mantle/reportInterptations/textReport/ColumnComparisonTableRow.scala
2921
package com.scalableQuality.quick.mantle.reportInterptations.textReport case class ColumnComparisonTableRow( label: String, position: String, leftValue: String, rightValue: String ) object ColumnComparisonTableRow { def apply( sizes: ColumnComparisonTableColumnSizes, label: String, position: String, leftValue: Option[String], rightValue: Option[String] ): List[ColumnComparisonTableRow] = { val labelColumns = ColumnComparisonTableColumn(label, sizes.labelColumnSize) val positionColumn = ColumnComparisonTableColumn(position, sizes.positionColumnSize) val leftValueColumn = ColumnComparisonTableColumn(leftValue, sizes.valueColumnSize) val rightValueColumn = ColumnComparisonTableColumn(rightValue, sizes.valueColumnSize) fitRows( labelColumns, positionColumn, leftValueColumn, rightValueColumn, Nil ) } type Column = String type FittedColumns = (List[Column], List[Column], List[Column], List[Column]) type Row = ColumnComparisonTableRow def destruct(listOfColumns: List[Column]): (Column, List[Column]) = listOfColumns match { case Nil => (ColumnComparisonTableColumn.emptyColumn, Nil) case column :: restOFColumns => (column, restOFColumns) } private def fitRows( fittedLabelColumn: List[Column], fittedPositionColumn: List[Column], fittedLeftValueColumn: List[Column], fittedRightValueColumn: List[Column], listOfRows: List[Row] ): List[Row] = (fittedLabelColumn, fittedPositionColumn, fittedLeftValueColumn, fittedRightValueColumn) match { case (Nil, Nil, Nil, Nil) => listOfRows.reverse case (labelColumn :: Nil, positionColumn :: Nil, leftValueColumn :: Nil, rightValueColum :: Nil) => val row = ColumnComparisonTableRow(labelColumn, positionColumn, leftValueColumn, rightValueColum) (row :: listOfRows).reverse case _ => val (labelColumn, restOfLabelColumn) = destruct(fittedLabelColumn) val (positionColumn, restOfPositionColumn) = destruct( fittedPositionColumn) val (leftValueColumn, restOfLeftValueColumn) = destruct( fittedLeftValueColumn) val (rightValueColumn, restOfRightValueColumn) = destruct( fittedRightValueColumn) fitRows( restOfLabelColumn, restOfPositionColumn, restOfLeftValueColumn, restOfRightValueColumn, ColumnComparisonTableRow(labelColumn, positionColumn, leftValueColumn, rightValueColumn) :: listOfRows ) } }
apache-2.0