hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
1c177f88234d41668b4b18c7334e66e72ab743d8
505
package org.test.chartjs.configuration; public class ChartTitle { private Boolean display = null; private String text = null; public ChartTitle() { initDefaultValues(); } public void initDefaultValues() { display = true; text = "Chart.js Line Chart"; } public Boolean getDisplay() { return display; } public void setDisplay(Boolean display) { this.display = display; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
14.852941
42
0.689109
ca57621aac929e4a6c20179d4b0e2b37a748b1dd
637
/* * This file is part of the DITA Open Toolkit project. * * Copyright 2015 Jarno Elovirta * * See the accompanying LICENSE file for applicable license. */ // Dummy class to allow compiling against RenderX package com.renderx.xep.lib; import org.xml.sax.SAXException; public class FormatterException extends SAXException { public FormatterException() { super(""); } public FormatterException(String var1) { super(var1); } public FormatterException(Exception var1) { super(var1); } public FormatterException(String var1, Exception var2) { super(var1, var2); } }
20.548387
60
0.678179
e74ef9a430d3f8062a8f183480b058110422f23c
855
package bglib.display.shapes; import java.awt.*; import bglib.util.RectType; import bglib.util.Vector2i; public class FillRect extends Rect { public FillRect(RectType rect, int border, Color color, boolean useConversion) { super(rect, border, color, useConversion); } public FillRect(RectType rect, int border, Color color) { super(rect, border, color); } @Override public void draw(Conversion conversion, Graphics2D g) { Vector2i pos; Vector2i size; if (useConversion) pos = conversion.convert(rect.getPos()); else pos = rect.getPos().floor(); size = rect.getSize().floor(); g.setColor(color); if (border > 0) g.setStroke(new BasicStroke(border)); g.fillRect(pos.x, pos.y, size.x, size.y); } }
24.428571
84
0.608187
f2c6d848554c54942be548001b24e5b096b3f8a1
6,660
package com.project.convertedCode.includes.vendor.nesbot.carbon.src.Carbon.Lang; import com.runtimeconverter.runtime.RuntimeStack; import com.runtimeconverter.runtime.interfaces.ContextConstants; import com.runtimeconverter.runtime.includes.RuntimeIncludable; import com.runtimeconverter.runtime.includes.IncludeEventException; import com.runtimeconverter.runtime.classes.RuntimeClassBase; import com.runtimeconverter.runtime.RuntimeEnv; import com.runtimeconverter.runtime.interfaces.UpdateRuntimeScopeInterface; import com.runtimeconverter.runtime.ZVal; import com.runtimeconverter.runtime.arrays.ZPair; /* Converted with The Runtime Converter (runtimeconverter.com) vendor/nesbot/carbon/src/Carbon/Lang/ar.php */ public class file_ar_php implements RuntimeIncludable { public static final file_ar_php instance = new file_ar_php(); public final void include(RuntimeEnv env, RuntimeStack stack) throws IncludeEventException { Scope1953 scope = new Scope1953(); stack.pushScope(scope); this.include(env, stack, scope); stack.popScope(); } public final void include(RuntimeEnv env, RuntimeStack stack, Scope1953 scope) throws IncludeEventException { throw new IncludeEventException( ZVal.assign( ZVal.newArray( new ZPair( "year", "{0}\u0633\u0646\u0629|{1}\u0633\u0646\u0629|{2}\u0633\u0646\u062A\u064A\u0646|[3,10]:count \u0633\u0646\u0648\u0627\u062A|[11,Inf]:count \u0633\u0646\u0629"), new ZPair( "y", "{0}\u0633\u0646\u0629|{1}\u0633\u0646\u0629|{2}\u0633\u0646\u062A\u064A\u0646|[3,10]:count \u0633\u0646\u0648\u0627\u062A|[11,Inf]:count \u0633\u0646\u0629"), new ZPair( "month", "{0}\u0634\u0647\u0631|{1} \u0634\u0647\u0631|{2}\u0634\u0647\u0631\u064A\u0646|[3,10]:count \u0623\u0634\u0647\u0631|[11,Inf]:count \u0634\u0647\u0631"), new ZPair( "m", "{0}\u0634\u0647\u0631|{1} \u0634\u0647\u0631|{2}\u0634\u0647\u0631\u064A\u0646|[3,10]:count \u0623\u0634\u0647\u0631|[11,Inf]:count \u0634\u0647\u0631"), new ZPair( "week", "{0}\u0623\u0633\u0628\u0648\u0639|{1}\u0623\u0633\u0628\u0648\u0639|{2}\u0623\u0633\u0628\u0648\u0639\u064A\u0646|[3,10]:count \u0623\u0633\u0627\u0628\u064A\u0639|[11,Inf]:count \u0623\u0633\u0628\u0648\u0639"), new ZPair( "w", "{0}\u0623\u0633\u0628\u0648\u0639|{1}\u0623\u0633\u0628\u0648\u0639|{2}\u0623\u0633\u0628\u0648\u0639\u064A\u0646|[3,10]:count \u0623\u0633\u0627\u0628\u064A\u0639|[11,Inf]:count \u0623\u0633\u0628\u0648\u0639"), new ZPair( "day", "{0}\u064A\u0648\u0645|{1}\u064A\u0648\u0645|{2}\u064A\u0648\u0645\u064A\u0646|[3,10]:count \u0623\u064A\u0627\u0645|[11,Inf] \u064A\u0648\u0645"), new ZPair( "d", "{0}\u064A\u0648\u0645|{1}\u064A\u0648\u0645|{2}\u064A\u0648\u0645\u064A\u0646|[3,10]:count \u0623\u064A\u0627\u0645|[11,Inf] \u064A\u0648\u0645"), new ZPair( "hour", "{0}\u0633\u0627\u0639\u0629|{1}\u0633\u0627\u0639\u0629|{2}\u0633\u0627\u0639\u062A\u064A\u0646|[3,10]:count \u0633\u0627\u0639\u0627\u062A|[11,Inf]:count \u0633\u0627\u0639\u0629"), new ZPair( "h", "{0}\u0633\u0627\u0639\u0629|{1}\u0633\u0627\u0639\u0629|{2}\u0633\u0627\u0639\u062A\u064A\u0646|[3,10]:count \u0633\u0627\u0639\u0627\u062A|[11,Inf]:count \u0633\u0627\u0639\u0629"), new ZPair( "minute", "{0}\u062F\u0642\u064A\u0642\u0629|{1}\u062F\u0642\u064A\u0642\u0629|{2}\u062F\u0642\u064A\u0642\u062A\u064A\u0646|[3,10]:count \u062F\u0642\u0627\u0626\u0642|[11,Inf]:count \u062F\u0642\u064A\u0642\u0629"), new ZPair( "min", "{0}\u062F\u0642\u064A\u0642\u0629|{1}\u062F\u0642\u064A\u0642\u0629|{2}\u062F\u0642\u064A\u0642\u062A\u064A\u0646|[3,10]:count \u062F\u0642\u0627\u0626\u0642|[11,Inf]:count \u062F\u0642\u064A\u0642\u0629"), new ZPair( "second", "{0}\u062B\u0627\u0646\u064A\u0629|{1}\u062B\u0627\u0646\u064A\u0629|{2}\u062B\u0627\u0646\u064A\u062A\u064A\u0646|[3,10]:count \u062B\u0648\u0627\u0646|[11,Inf]:count \u062B\u0627\u0646\u064A\u0629"), new ZPair( "s", "{0}\u062B\u0627\u0646\u064A\u0629|{1}\u062B\u0627\u0646\u064A\u0629|{2}\u062B\u0627\u0646\u064A\u062A\u064A\u0646|[3,10]:count \u062B\u0648\u0627\u0646|[11,Inf]:count \u062B\u0627\u0646\u064A\u0629"), new ZPair("ago", "\u0645\u0646\u0630 :time"), new ZPair( "from_now", ":time \u0645\u0646 \u0627\u0644\u0622\u0646"), new ZPair("after", "\u0628\u0639\u062F :time"), new ZPair("before", "\u0642\u0628\u0644 :time")))); } private static final ContextConstants runtimeConverterContextContantsInstance = new ContextConstants() .setDir("/vendor/nesbot/carbon/src/Carbon/Lang") .setFile("/vendor/nesbot/carbon/src/Carbon/Lang/ar.php"); public ContextConstants getContextConstants() { return runtimeConverterContextContantsInstance; } private static class Scope1953 implements UpdateRuntimeScopeInterface { public void updateStack(RuntimeStack stack) {} public void updateScope(RuntimeStack stack) {} } }
65.294118
253
0.53979
5f29fa761ea6de42eab27081da582199794568a0
148
package com.siondream.ld29.room; public class MessagePostAction extends PostAction { String message; @Override public void run() { } }
10.571429
51
0.716216
f829e53c783943d4dca81bf74919deb95a46cc04
1,477
/* * Copyright 1999-2020 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.naming.pojo.instance; import com.alibaba.nacos.api.naming.spi.generator.IdGenerator; /** * Default instance id generator. * * @author xiweng.yy */ public class DefaultInstanceIdGenerator implements IdGenerator { public static final String ID_DELIMITER = "#"; private final String serviceName; private final String clusterName; private final String ip; private final int port; public DefaultInstanceIdGenerator(String serviceName, String clusterName, String ip, int port) { this.serviceName = serviceName; this.clusterName = clusterName; this.ip = ip; this.port = port; } @Override public String generateInstanceId() { return ip + ID_DELIMITER + port + ID_DELIMITER + clusterName + ID_DELIMITER + serviceName; } }
29.54
100
0.703453
bdd686f95b6e59e34652a90c12e0f2b650a64182
1,115
package com.mamasnicolaou.javadatastructures; public class Main { public static void main(String[] args) { testStack(); System.out.println(); testSimpleStack(); System.out.println(); testQueue(); } public static void testStack(){ System.out.println("Testing Stack"); Stack stack = new Stack<String>(); stack.push("World!"); stack.push("Hello "); while(!stack.isEmpty()) { System.out.print(stack.pop()); } } public static void testSimpleStack(){ System.out.println("Testing SimpleStack"); SimpleStack stack = new SimpleStack<String>(); stack.push("World!"); stack.push("Hello "); while(!stack.isEmpty()) { System.out.print(stack.pop()); } } public static void testQueue(){ System.out.println("Testing Queue"); Queue queue = new Queue<String>(); queue.push("Hello "); queue.push("World! "); while(!queue.isEmpty()) { System.out.print(queue.remove()); } } }
24.777778
54
0.547085
1b88b6cc4275c2e7ab202f512c5a144768add28e
1,489
package cdeler.highlight.highlighters; import java.awt.*; import javax.swing.*; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultHighlighter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cdeler.highlight.settings.TokenStyle; import cdeler.highlight.settings.UISettingsManager; import cdeler.highlight.token.TokenType; import cdeler.highlight.token.Tokenizer; public class LineTextHighlighter extends BaseTextHighlighter { private static final Logger LOGGER = LoggerFactory.getLogger(LineTextHighlighter.class); public LineTextHighlighter(Tokenizer tokenizer, UISettingsManager settingManager) { super(tokenizer, settingManager); LOGGER.warn("LineTextHighlighter doesn't fully support text highlighting"); } @Override protected void highlight(JTextPane textArea, TokenType tokenType, int startOffset, int endOffset) { try { TokenStyle style = settingsManager.getActiveStyleForTokenType(tokenType); textArea.getHighlighter().addHighlight(startOffset, endOffset, new DefaultHighlighter.DefaultHighlightPainter(style.getColor())); } catch (BadLocationException e) { LOGGER.error("Unable to highlight location from " + startOffset + " to " + endOffset, e); } } @Override protected void clearHighlight(JTextPane textArea, Rectangle clearArea) { textArea.getHighlighter().removeAllHighlights(); } }
34.627907
103
0.745467
c8c416f2a6f6ff1c39d78ef213cff0847330ab5d
6,512
package org.apache.helix.rest.server; /* * 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.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.helix.TestHelper; import org.apache.helix.msdcommon.constant.MetadataStoreRoutingConstants; import org.apache.helix.msdcommon.exception.InvalidRoutingDataException; import org.apache.helix.rest.metadatastore.accessor.MetadataStoreRoutingDataReader; import org.apache.helix.rest.metadatastore.accessor.ZkRoutingDataReader; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer; import org.apache.helix.zookeeper.zkclient.ZkClient; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; public class MetadataStoreDirectoryAccessorTestBase extends AbstractTestClass { /* * The following are constants to be used for testing. */ protected static final String TEST_NAMESPACE_URI_PREFIX = "/namespaces/" + TEST_NAMESPACE; protected static final String NON_EXISTING_NAMESPACE_URI_PREFIX = "/namespaces/not-existed-namespace/metadata-store-realms/"; protected static final String TEST_REALM_1 = "testRealm1"; protected static final List<String> TEST_SHARDING_KEYS_1 = Arrays.asList("/sharding/key/1/a", "/sharding/key/1/b", "/sharding/key/1/c"); protected static final String TEST_REALM_2 = "testRealm2"; protected static final List<String> TEST_SHARDING_KEYS_2 = Arrays.asList("/sharding/key/1/d", "/sharding/key/1/e", "/sharding/key/1/f"); protected static final String TEST_REALM_3 = "testRealm3"; protected static final String TEST_SHARDING_KEY = "/sharding/key/1/x"; protected static final String INVALID_TEST_SHARDING_KEY = "sharding/key/1/x"; // List of all ZK addresses, each of which corresponds to a namespace/routing ZK protected List<String> _zkList; protected MetadataStoreRoutingDataReader _routingDataReader; @BeforeClass public void beforeClass() throws Exception { _zkList = new ArrayList<>(ZK_SERVER_MAP.keySet()); clearRoutingData(); // Write dummy mappings in ZK // Create a node that represents a realm address and add 3 sharding keys to it ZNRecord znRecord = new ZNRecord("RoutingInfo"); _zkList.forEach(zk -> { ZK_SERVER_MAP.get(zk).getZkClient().setZkSerializer(new ZNRecordSerializer()); // Write first realm and sharding keys pair znRecord.setListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY, TEST_SHARDING_KEYS_1); ZK_SERVER_MAP.get(zk).getZkClient() .createPersistent(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + TEST_REALM_1, true); ZK_SERVER_MAP.get(zk).getZkClient() .writeData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + TEST_REALM_1, znRecord); // Create another realm and sharding keys pair znRecord.setListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY, TEST_SHARDING_KEYS_2); ZK_SERVER_MAP.get(zk).getZkClient() .createPersistent(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + TEST_REALM_2, true); ZK_SERVER_MAP.get(zk).getZkClient() .writeData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + TEST_REALM_2, znRecord); }); _routingDataReader = new ZkRoutingDataReader(TEST_NAMESPACE, _zkAddrTestNS, null); System.setProperty(MetadataStoreRoutingConstants.MSDS_SERVER_HOSTNAME_KEY, getBaseUri().getHost()); System.setProperty(MetadataStoreRoutingConstants.MSDS_SERVER_PORT_KEY, Integer.toString(getBaseUri().getPort())); } @AfterClass public void afterClass() throws Exception { System.clearProperty(MetadataStoreRoutingConstants.MSDS_SERVER_HOSTNAME_KEY); System.clearProperty(MetadataStoreRoutingConstants.MSDS_SERVER_PORT_KEY); _routingDataReader.close(); clearRoutingData(); } protected void clearRoutingData() throws Exception { Assert.assertTrue(TestHelper.verify(() -> { for (String zk : _zkList) { ZkClient zkClient = ZK_SERVER_MAP.get(zk).getZkClient(); if (zkClient.exists(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { for (String zkRealm : zkClient .getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { zkClient.delete(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + zkRealm); } } } for (String zk : _zkList) { ZkClient zkClient = ZK_SERVER_MAP.get(zk).getZkClient(); if (zkClient.exists(MetadataStoreRoutingConstants.ROUTING_DATA_PATH) && !zkClient .getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH).isEmpty()) { return false; } } return true; }, TestHelper.WAIT_DURATION), "Routing data path should be deleted after the tests."); } // Uses routingDataReader to get the latest realms in test-namespace; returns a modifiable copy // because it'll be modified in test cases protected Set<String> getAllRealms() throws InvalidRoutingDataException { return new HashSet<>(_routingDataReader.getRoutingData().keySet()); } // Uses routingDataReader to get the latest sharding keys in test-namespace, testRealm1 protected Set<String> getAllShardingKeysInTestRealm1() throws InvalidRoutingDataException { return new HashSet<>(_routingDataReader.getRoutingData().get(TEST_REALM_1)); } protected Map<String, List<String>> getRawRoutingData() throws InvalidRoutingDataException { return _routingDataReader.getRoutingData(); } }
43.413333
97
0.747236
f773c8ab846d11d7598f4fa5d5e757486e8741a2
1,893
/* * 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.intellij.dvcs.cherrypick; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.vcs.VcsKey; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.vcs.log.VcsFullCommitDetails; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.List; public abstract class VcsCherryPicker { @NonNls public static final ExtensionPointName<VcsCherryPicker> EXTENSION_POINT_NAME = ExtensionPointName.create("com.intellij.cherryPicker"); /** * @return - return vcs for current cherryPicker */ @NotNull public abstract VcsKey getSupportedVcs(); /** * @return CherryPick Action name for supported vcs */ @NotNull @Nls(capitalization = Nls.Capitalization.Title) public abstract String getActionTitle(); /** * Cherry-pick selected commits to current branch of appropriate repository * * @param commits to cherry-pick */ public abstract void cherryPick(@NotNull final List<? extends VcsFullCommitDetails> commits); /** * Return true if cherry picker can manage all commits from roots */ public abstract boolean canHandleForRoots(@NotNull Collection<? extends VirtualFile> roots); }
32.637931
95
0.760697
7d8b927be1b83db28cbf01f514e288f7e02d8072
1,065
package com.cloudwarriors.containercrush.cloudwarriors.models; import lombok.Data; @Data public class ProductDetailResponse { private String segment; private String segmentName; private String family; private String familyName; private String classType; private String className; private String commodity; private String commodityName; private String priceID; private String itemNumber; private String listPrice; private String discount; private String inStock; private String priceEffectiveDate; private String description; private String LongDescription; private String catalogueCatergory; private String skuUnitOfMeaure; private String styleItem; private String sKUAttribute1; private String sKUAttribute2; private String sKUAttribute3; private String sKUAttribute4; private String sKUAttribute5; private String sKUAttribute6; private String sKUAttValue1; private String sKUAttValue2; private String sKUAttValue3; private String sKUAttValue4; private String SKUAttValue5; private String SKUAttValue6; private String brand; }
25.357143
62
0.826291
dafef9ce87e4a6a53310720149e53661c1a0ce1d
12,056
/** * <copyright> * </copyright> * * $Id$ */ package org.eclipse.bpel4chor.model.pbd.impl; import java.util.Collection; import org.eclipse.bpel4chor.model.pbd.Activity; import org.eclipse.bpel4chor.model.pbd.DanglingFlowActivityLink; import org.eclipse.bpel4chor.model.pbd.PbdPackage; import org.eclipse.bpel4chor.model.pbd.Sources; import org.eclipse.bpel4chor.model.pbd.Targets; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Activity</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.eclipse.bpel4chor.model.pbd.impl.ActivityImpl#getTargets <em>Targets</em>}</li> * <li>{@link org.eclipse.bpel4chor.model.pbd.impl.ActivityImpl#getSources <em>Sources</em>}</li> * <li>{@link org.eclipse.bpel4chor.model.pbd.impl.ActivityImpl#getName <em>Name</em>}</li> * <li>{@link org.eclipse.bpel4chor.model.pbd.impl.ActivityImpl#getSuppressJoinFailure <em>Suppress Join Failure</em>}</li> * <li>{@link org.eclipse.bpel4chor.model.pbd.impl.ActivityImpl#getDanglingFlowActivityLink <em>Dangling Flow Activity Link</em>}</li> * </ul> * </p> * * @generated */ public class ActivityImpl extends ExtensibleElementsImpl implements Activity { /** * The cached value of the '{@link #getTargets() <em>Targets</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTargets() * @generated * @ordered */ protected Targets targets; /** * The cached value of the '{@link #getSources() <em>Sources</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSources() * @generated * @ordered */ protected Sources sources; /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The default value of the '{@link #getSuppressJoinFailure() <em>Suppress Join Failure</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSuppressJoinFailure() * @generated * @ordered */ protected static final org.eclipse.bpel4chor.model.pbd.Boolean SUPPRESS_JOIN_FAILURE_EDEFAULT = org.eclipse.bpel4chor.model.pbd.Boolean.NO; /** * The cached value of the '{@link #getSuppressJoinFailure() <em>Suppress Join Failure</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSuppressJoinFailure() * @generated * @ordered */ protected org.eclipse.bpel4chor.model.pbd.Boolean suppressJoinFailure = SUPPRESS_JOIN_FAILURE_EDEFAULT; /** * The cached value of the '{@link #getDanglingFlowActivityLink() <em>Dangling Flow Activity Link</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDanglingFlowActivityLink() * @generated * @ordered */ protected EList<DanglingFlowActivityLink> danglingFlowActivityLink; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ActivityImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return PbdPackage.Literals.ACTIVITY; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Targets getTargets() { return targets; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetTargets(Targets newTargets, NotificationChain msgs) { Targets oldTargets = targets; targets = newTargets; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, PbdPackage.ACTIVITY__TARGETS, oldTargets, newTargets); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTargets(Targets newTargets) { if (newTargets != targets) { NotificationChain msgs = null; if (targets != null) msgs = ((InternalEObject)targets).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - PbdPackage.ACTIVITY__TARGETS, null, msgs); if (newTargets != null) msgs = ((InternalEObject)newTargets).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - PbdPackage.ACTIVITY__TARGETS, null, msgs); msgs = basicSetTargets(newTargets, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, PbdPackage.ACTIVITY__TARGETS, newTargets, newTargets)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Sources getSources() { return sources; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetSources(Sources newSources, NotificationChain msgs) { Sources oldSources = sources; sources = newSources; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, PbdPackage.ACTIVITY__SOURCES, oldSources, newSources); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSources(Sources newSources) { if (newSources != sources) { NotificationChain msgs = null; if (sources != null) msgs = ((InternalEObject)sources).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - PbdPackage.ACTIVITY__SOURCES, null, msgs); if (newSources != null) msgs = ((InternalEObject)newSources).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - PbdPackage.ACTIVITY__SOURCES, null, msgs); msgs = basicSetSources(newSources, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, PbdPackage.ACTIVITY__SOURCES, newSources, newSources)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, PbdPackage.ACTIVITY__NAME, oldName, name)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public org.eclipse.bpel4chor.model.pbd.Boolean getSuppressJoinFailure() { return suppressJoinFailure; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSuppressJoinFailure(org.eclipse.bpel4chor.model.pbd.Boolean newSuppressJoinFailure) { org.eclipse.bpel4chor.model.pbd.Boolean oldSuppressJoinFailure = suppressJoinFailure; suppressJoinFailure = newSuppressJoinFailure == null ? SUPPRESS_JOIN_FAILURE_EDEFAULT : newSuppressJoinFailure; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, PbdPackage.ACTIVITY__SUPPRESS_JOIN_FAILURE, oldSuppressJoinFailure, suppressJoinFailure)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<DanglingFlowActivityLink> getDanglingFlowActivityLink() { if (danglingFlowActivityLink == null) { danglingFlowActivityLink = new EObjectContainmentEList<DanglingFlowActivityLink>(DanglingFlowActivityLink.class, this, PbdPackage.ACTIVITY__DANGLING_FLOW_ACTIVITY_LINK); } return danglingFlowActivityLink; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case PbdPackage.ACTIVITY__TARGETS: return basicSetTargets(null, msgs); case PbdPackage.ACTIVITY__SOURCES: return basicSetSources(null, msgs); case PbdPackage.ACTIVITY__DANGLING_FLOW_ACTIVITY_LINK: return ((InternalEList<?>)getDanglingFlowActivityLink()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case PbdPackage.ACTIVITY__TARGETS: return getTargets(); case PbdPackage.ACTIVITY__SOURCES: return getSources(); case PbdPackage.ACTIVITY__NAME: return getName(); case PbdPackage.ACTIVITY__SUPPRESS_JOIN_FAILURE: return getSuppressJoinFailure(); case PbdPackage.ACTIVITY__DANGLING_FLOW_ACTIVITY_LINK: return getDanglingFlowActivityLink(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case PbdPackage.ACTIVITY__TARGETS: setTargets((Targets)newValue); return; case PbdPackage.ACTIVITY__SOURCES: setSources((Sources)newValue); return; case PbdPackage.ACTIVITY__NAME: setName((String)newValue); return; case PbdPackage.ACTIVITY__SUPPRESS_JOIN_FAILURE: setSuppressJoinFailure((org.eclipse.bpel4chor.model.pbd.Boolean)newValue); return; case PbdPackage.ACTIVITY__DANGLING_FLOW_ACTIVITY_LINK: getDanglingFlowActivityLink().clear(); getDanglingFlowActivityLink().addAll((Collection<? extends DanglingFlowActivityLink>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case PbdPackage.ACTIVITY__TARGETS: setTargets((Targets)null); return; case PbdPackage.ACTIVITY__SOURCES: setSources((Sources)null); return; case PbdPackage.ACTIVITY__NAME: setName(NAME_EDEFAULT); return; case PbdPackage.ACTIVITY__SUPPRESS_JOIN_FAILURE: setSuppressJoinFailure(SUPPRESS_JOIN_FAILURE_EDEFAULT); return; case PbdPackage.ACTIVITY__DANGLING_FLOW_ACTIVITY_LINK: getDanglingFlowActivityLink().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case PbdPackage.ACTIVITY__TARGETS: return targets != null; case PbdPackage.ACTIVITY__SOURCES: return sources != null; case PbdPackage.ACTIVITY__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case PbdPackage.ACTIVITY__SUPPRESS_JOIN_FAILURE: return suppressJoinFailure != SUPPRESS_JOIN_FAILURE_EDEFAULT; case PbdPackage.ACTIVITY__DANGLING_FLOW_ACTIVITY_LINK: return danglingFlowActivityLink != null && !danglingFlowActivityLink.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (name: "); result.append(name); result.append(", suppressJoinFailure: "); result.append(suppressJoinFailure); result.append(')'); return result.toString(); } } //ActivityImpl
29.120773
172
0.693514
d097a6c3c46395198c47c8368a72b121a86d8fb1
4,696
package ru.vyarus.guice.validator.group; import com.google.common.collect.Sets; import org.junit.Assert; import org.junit.Test; import ru.vyarus.guice.validator.group.annotation.MethodGroupsFactory; import ru.vyarus.guice.validator.group.support.groups.FooGroup; import ru.vyarus.guice.validator.group.support.groups.FooGroup2; import ru.vyarus.guice.validator.group.support.groups.RootFooGroup; import ru.vyarus.guice.validator.group.support.groups.ann.Group1; import ru.vyarus.guice.validator.group.support.groups.ann.Group2; import ru.vyarus.guice.validator.group.support.groups.ann.RootGroup; import ru.vyarus.guice.validator.group.support.simple.*; /** * @author Vyacheslav Rusakov * @since 11.03.2016 */ @SuppressWarnings("unchecked") public class GroupRecognitionTest { MethodGroupsFactory factory = new MethodGroupsFactory(false); @Test public void checkSimpleCases() throws Throwable { Assert.assertArrayEquals(new Class[0], factory.create(SimpleAnnService.class.getMethod("nothing"))); Assert.assertArrayEquals(new Class[]{FooGroup.class}, factory.create(SimpleAnnService.class.getMethod("single"))); Assert.assertEquals(Sets.newHashSet(FooGroup.class, FooGroup2.class), Sets.newHashSet(factory.create(SimpleAnnService.class.getMethod("multiple")))); Assert.assertArrayEquals(new Class[]{Group1.class}, factory.create(SimpleAnnService.class.getMethod("custom"))); Assert.assertEquals(Sets.newHashSet(Group1.class, Group2.class), Sets.newHashSet(factory.create(SimpleAnnService.class.getMethod("custom2")))); } @Test public void checkCompositeCases() throws Throwable { Assert.assertArrayEquals(new Class[]{RootGroup.class}, factory.create(CompositeAnnService.class.getMethod("nothing"))); Assert.assertEquals(Sets.newHashSet(RootGroup.class, FooGroup.class), Sets.newHashSet(factory.create(CompositeAnnService.class.getMethod("single")))); Assert.assertEquals(Sets.newHashSet(RootGroup.class, FooGroup.class, FooGroup2.class), Sets.newHashSet(factory.create(CompositeAnnService.class.getMethod("multiple")))); Assert.assertEquals(Sets.newHashSet(RootGroup.class, Group1.class), Sets.newHashSet(factory.create(CompositeAnnService.class.getMethod("custom")))); Assert.assertEquals(Sets.newHashSet(RootGroup.class, Group1.class, Group2.class), Sets.newHashSet(factory.create(CompositeAnnService.class.getMethod("custom2")))); } @Test public void checkCompositeCases2() throws Throwable { Assert.assertArrayEquals(new Class[]{RootFooGroup.class}, factory.create(CompositeAnnService2.class.getMethod("nothing"))); Assert.assertEquals(Sets.newHashSet(RootFooGroup.class, FooGroup.class), Sets.newHashSet(factory.create(CompositeAnnService2.class.getMethod("single")))); Assert.assertEquals(Sets.newHashSet(RootFooGroup.class, Group1.class), Sets.newHashSet(factory.create(CompositeAnnService2.class.getMethod("custom")))); } @Test public void checkCompositeCases3() throws Throwable { Assert.assertEquals(Sets.newHashSet(RootGroup.class, RootFooGroup.class), Sets.newHashSet(factory.create(CompositeAnnService3.class.getMethod("nothing")))); Assert.assertEquals(Sets.newHashSet(RootGroup.class, RootFooGroup.class, FooGroup.class), Sets.newHashSet(factory.create(CompositeAnnService3.class.getMethod("single")))); Assert.assertEquals(Sets.newHashSet(RootGroup.class, RootFooGroup.class, Group1.class), Sets.newHashSet(factory.create(CompositeAnnService3.class.getMethod("custom")))); } @Test public void checkInheritance() throws Throwable { // @validationGroups is inheritable and propagate Assert.assertEquals(Sets.newHashSet(RootFooGroup.class), Sets.newHashSet(factory.create(InheritedService.class.getMethod("groupInherit")))); // custom annotation was not inheritable Assert.assertEquals(Sets.newHashSet(), Sets.newHashSet(factory.create(NotInheritedService.class.getMethod("noGroups")))); // annotations on methods are not inherit Assert.assertEquals(Sets.newHashSet(RootFooGroup.class), Sets.newHashSet(factory.create(InheritedService.class.getMethod("single")))); Assert.assertEquals(Sets.newHashSet(), Sets.newHashSet(factory.create(NotInheritedService.class.getMethod("custom")))); } }
45.592233
99
0.71678
34d9d04cefb2617315aa620c82256e8001c65068
326
package AppSettingsHandler; import com.google.inject.AbstractModule; import com.google.inject.Singleton; /** The type App settings bindings. */ public class AppSettingsBindings extends AbstractModule { @Override protected void configure() { bind(IAppSettings.class).to(AppSettings.class).in(Singleton.class); } }
23.285714
71
0.773006
9336477053314cbc6d58ce0507607328100159cd
3,681
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2008 Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-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.sakaiproject.time.api; /** * <p> * TimeRange ... * </p> */ public interface TimeRange extends Cloneable { /** * Check if this Time in my range. * * @param time * The time to check for inclusion. * @return true if the time is in the range, false if not. */ boolean contains(Time time); /** * Check if this TimeRange overlap this other TimeRange at all. * * @param range * The time range to check for overlap. * @return true if any time in the other range is in this range, false if not. */ boolean overlaps(TimeRange range); /** * Check if this TimeRange completely contains the other range. * * @param range * The time range to check for containment. * @return true if the other TimeRange is within this TimeRange, false if not. */ boolean contains(TimeRange range); /** * Access the first Time of the range. * * @return the first Time actually in the range. */ Time firstTime(); /** * Access the last Time in the range. * * @return the last Time actually in the range. */ Time lastTime(); /** * Access the first Time of the range (fudged). * * @param fudge * How many ms to increase if the first is not included. * @return the first Time actually in the range (fudged). */ Time firstTime(long fudge); /** * Access the last Time of the range (fudged). * * @param fudge * How many ms to decrease if the last is not included. * @return the first Time actually in the range (fudged). */ Time lastTime(long fudge); /** * Format the TimeRange - human readable. * * @return The TimeRange in string format. */ String toStringHR(); /** * Access the duration of the TimeRange, in milliseconds. * * @return The duration. */ long duration(); /** * Shift the time range back an interval * * @param i * time intervel in ms */ void shiftBackward(long i); /** * Shift the time range forward an interval * * @param i * time intervel in ms */ void shiftForward(long i); /** * Enlarge or shrink the time range by multiplying a zooming factor. * * @param f * zooming factor */ void zoom(double f); /** * Adjust this time range based on the difference between the origRange and the modRange, if any. * * @param original * the original time range. * @param modified * the modified time range. */ void adjust(TimeRange original, TimeRange modified); /** * Clone the TimeRange * * @return A cloned TimeRange. */ Object clone(); /** * Check if the TimeRange is really just a single Time. * * @return true if the tiTimeRange is a single Time, false if it is not. */ boolean isSingleTime(); }
24.217105
98
0.606629
fcdceec2402dfa9f9cf9a8f73c89d4f7b2c08de3
1,418
import java.io.File; import java.util.HashMap; import java.util.LinkedList; import java.util.Scanner; public class PartA { public static void main(String[] args) { Scanner sc = new Scanner(System.in); HashMap<Character, Character> closeMap = new HashMap<>(); closeMap.put('(', ')'); closeMap.put('[', ']'); closeMap.put('{', '}'); closeMap.put('<', '>'); HashMap<Character, Integer> scoreMap = new HashMap<>(); scoreMap.put(')', 3); scoreMap.put(']', 57); scoreMap.put('}', 1197); scoreMap.put('>', 25137); try { sc = new Scanner(new File("bin/i.txt")); } catch(Exception e) { e.printStackTrace(); return; } int points = 0; LinkedList<Character> chunks = new LinkedList<>(); while(sc.hasNextLine()) { String line = sc.nextLine(); boolean lineCorrupted = false; for(int i = 0; i < line.length() && !lineCorrupted; i++) { char ch = line.charAt(i); if (ch == '(' || ch == '[' || ch == '{' || ch == '<') { chunks.add(ch); } else { if (ch == closeMap.get(chunks.peekLast())) chunks.removeLast(); else { lineCorrupted = true; points += scoreMap.get(ch); } } } } System.out.println("accumulated score: " + points); } }
27.803922
74
0.503526
c2d2268f05c045b67dcef903e87049ec21cffd76
4,140
/* * 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.commons.math.optimization.linear; import java.util.Collection; import org.apache.commons.math.exception.MathIllegalStateException; import org.apache.commons.math.optimization.GoalType; import org.apache.commons.math.optimization.RealPointValuePair; /** * This interface represents an optimization algorithm for linear problems. * <p>Optimization algorithms find the input point set that either {@link GoalType * maximize or minimize} an objective function. In the linear case the form of * the function is restricted to * <pre> * c<sub>1</sub>x<sub>1</sub> + ... c<sub>n</sub>x<sub>n</sub> = v * </pre> * and there may be linear constraints too, of one of the forms: * <ul> * <li>c<sub>1</sub>x<sub>1</sub> + ... c<sub>n</sub>x<sub>n</sub> = v</li> * <li>c<sub>1</sub>x<sub>1</sub> + ... c<sub>n</sub>x<sub>n</sub> &lt;= v</li> * <li>c<sub>1</sub>x<sub>1</sub> + ... c<sub>n</sub>x<sub>n</sub> >= v</li> * <li>l<sub>1</sub>x<sub>1</sub> + ... l<sub>n</sub>x<sub>n</sub> + l<sub>cst</sub> = * r<sub>1</sub>x<sub>1</sub> + ... r<sub>n</sub>x<sub>n</sub> + r<sub>cst</sub></li> * <li>l<sub>1</sub>x<sub>1</sub> + ... l<sub>n</sub>x<sub>n</sub> + l<sub>cst</sub> &lt;= * r<sub>1</sub>x<sub>1</sub> + ... r<sub>n</sub>x<sub>n</sub> + r<sub>cst</sub></li> * <li>l<sub>1</sub>x<sub>1</sub> + ... l<sub>n</sub>x<sub>n</sub> + l<sub>cst</sub> >= * r<sub>1</sub>x<sub>1</sub> + ... r<sub>n</sub>x<sub>n</sub> + r<sub>cst</sub></li> * </ul> * where the c<sub>i</sub>, l<sub>i</sub> or r<sub>i</sub> are the coefficients of * the constraints, the x<sub>i</sub> are the coordinates of the current point and * v is the value of the constraint. * </p> * @version $Id: LinearOptimizer.java 1178006 2011-10-01 14:52:21Z luc $ * @since 2.0 */ public interface LinearOptimizer { /** Set the maximal number of iterations of the algorithm. * @param maxIterations maximal number of function calls */ void setMaxIterations(int maxIterations); /** Get the maximal number of iterations of the algorithm. * @return maximal number of iterations */ int getMaxIterations(); /** Get the number of iterations realized by the algorithm. * <p> * The number of evaluations corresponds to the last call to the * {@link #optimize(LinearObjectiveFunction, Collection, GoalType, boolean) optimize} * method. It is 0 if the method has not been called yet. * </p> * @return number of iterations */ int getIterations(); /** Optimizes an objective function. * @param f linear objective function * @param constraints linear constraints * @param goalType type of optimization goal: either {@link GoalType#MAXIMIZE} * or {@link GoalType#MINIMIZE} * @param restrictToNonNegative whether to restrict the variables to non-negative values * @return point/value pair giving the optimal value for objective function * @exception MathIllegalStateException if no solution fulfilling the constraints * can be found in the allowed number of iterations */ RealPointValuePair optimize(LinearObjectiveFunction f, Collection<LinearConstraint> constraints, GoalType goalType, boolean restrictToNonNegative) throws MathIllegalStateException; }
46
99
0.677536
1c5c6313fa9f74eb25afe29b68a8a22985d7b4ea
1,182
package com.highcom.admin.controller; import com.highcom.admin.pojo.*; import com.highcom.admin.service.MflowService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @Api(tags = "前台国际物流") @RestController @RequestMapping("/home") public class HomeMflowController extends BaseController { @Autowired private MflowService mflowService; @ApiOperation(value = "前台: 根据模块id显示国际物流信息") @RequestMapping(value = "mflowById", method = RequestMethod.GET) public Result<Mflow> mflowById(int moduleid){ Mflow mflow = mflowService.mflowbyid(moduleid); Result<Mflow> result = new Result<>(200, "提交成功", mflow); return result; } @ApiOperation(value = "前台: 显示所有国际物流模块") @RequestMapping(value = "moduleShow", method = RequestMethod.GET) public Result<List<Mtype>> moduleShow(){ List<Mtype> mtypes = mflowService.moduleShow(); Result<List<Mtype>> result = new Result<>(200, "提交成功", mtypes); return result; } }
33.771429
72
0.698816
95534fdc9d8cdaa50649f234979081de7c1170c7
2,908
package org.netlight.messaging; import org.netlight.channel.ChannelContext; import org.netlight.util.TimeProperty; import org.netlight.util.concurrent.AtomicBooleanField; import org.netlight.util.concurrent.CacheManager; import java.util.Objects; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; /** * @author ahmad */ public final class MessageQueueLoopGroup { private final ExecutorService executorService; private final MessageQueueLoopHandler handler; private final MessageQueueStrategy queueStrategy; private final MessageQueueLoopStrategy loopStrategy; private final CacheManager<ChannelContext, MessageQueueLoop> loops; private final AtomicBooleanField looping = new AtomicBooleanField(true); public MessageQueueLoopGroup(ExecutorService executorService, MessageQueueLoopHandler handler, MessageQueueStrategy queueStrategy, MessageQueueLoopStrategy loopStrategy) { Objects.requireNonNull(executorService); Objects.requireNonNull(handler); Objects.requireNonNull(queueStrategy); Objects.requireNonNull(loopStrategy); this.executorService = executorService; this.handler = handler; this.queueStrategy = queueStrategy; this.loopStrategy = loopStrategy; loops = CacheManager.<ChannelContext, MessageQueueLoop>newBuilder() .expireAfterAccess(TimeProperty.minutes(5)) .removalListener(notification -> { MessageQueueLoop loop = notification.getValue(); if (loop != null) { loop.stop(); } }).build(); } public void queueMessage(ChannelContext ctx, Message message) { final MessageQueueLoop loop = getLoop(ctx); loop.getMessageQueue().add(message); loop.getLoopStrategy().poke(); if (!loop.isLooping()) { executorService.execute(loop); } } private MessageQueueLoop getLoop(ChannelContext ctx) { MessageQueueLoop loop = loops.retrieve(ctx); if (loop == null) { final MessageQueueLoop l = loops.cacheIfAbsent(ctx, loop = new MessageQueueLoop(ctx, queueStrategy.next(), handler, loopStrategy)); if (l != null) { loop = l; } } return loop; } public boolean isLooping() { return looping.get(); } public boolean shutdownGracefully() { if (looping.compareAndSet(true, false)) { executorService.shutdown(); loops.forEachValue(MessageQueueLoop::stop); executorService.shutdownNow(); try { return executorService.awaitTermination(15L, TimeUnit.SECONDS); } catch (InterruptedException ignored) { } } return false; } }
35.463415
143
0.652338
94bf5da533538afd103c80628d4ad162d780f38c
1,534
package io.neow3j.devpack.constants; /** * Contains the possible respond codes that are used by Oracles. */ public class OracleResponseCode { /** * Indicates that the request has been successfully completed. */ public static final byte Success = 0; /** * Indicates that the protocol of the request is not supported. */ public static final byte ProtocolNotSupported = 0x10; /** * Indicates that the oracle nodes cannot reach a consensus on the result of the request. */ public static final byte ConsensusUnreachable = 0x12; /** * Indicates that the requested Uri does not exist. */ public static final byte NotFound = 0x14; /** * Indicates that the request was not completed within the specified time. */ public static final byte Timeout = 0x16; /** * Indicates that there is no permission to request the resource. */ public static final byte Forbidden = 0x18; /** * Indicates that the data for the response is too large. */ public static final byte ResponseTooLarge = 0x1a; /** * Indicates that the request failed due to insufficient balance. */ public static final byte InsufficientFunds = 0x1c; /** * Indicates that the content-type of the request is not supported. */ public static final byte ContentTypeNotSupported = 0x1f; /** * Indicates that the request failed due to other errors. */ public static final byte Error = (byte) 0xff; }
26
93
0.660365
b7701b8bc6cbb5d446287531071ee092eac939b9
1,396
/* * Copyright 2021 ROCKSEA. All rights Reserved. * ROCKSEA PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package kr.co.sample.gateway.exception; import java.util.Map; import org.springframework.boot.web.error.ErrorAttributeOptions; import org.springframework.boot.web.reactive.error.DefaultErrorAttributes; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.server.ResponseStatusException; @Component public class GlobalErrorAttributes extends DefaultErrorAttributes { @Override public Map<String, Object> getErrorAttributes( ServerRequest request, ErrorAttributeOptions options) { Map<String, Object> map = super.getErrorAttributes(request, options); Throwable throwable = getError(request); if (throwable instanceof ResponseStatusException) { ResponseStatusException ex = (ResponseStatusException) getError(request); map.put("exception", ex.getClass().getSimpleName()); map.put("message", ex.getMessage()); map.put("status", ex.getStatus().value()); map.put("error", ex.getStatus().getReasonPhrase()); return map; } map.put("exception", "SystemException"); map.put("message", throwable.getMessage()); return map; } }
37.72973
85
0.712751
effaa6d46ce6ce8f59c2b262c9e8bbb94728a8bc
964
package edu.gmu.csiss.earthcube.cyberconnector.tools; import java.util.List; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import edu.gmu.csiss.earthcube.cyberconnector.database.DataBaseBroker; /** *Class QueryOrderStatusTool.java *@author Ziheng Sun *@time Aug 10, 2015 12:11:27 PM *Original aim is to support iGFDS. */ public class QueryOrderStatusTool { /** * Query status by order id * @param orderid * @return * Status */ public String queryStatusByOrderId(String orderid){ String status = DataBaseBroker.queryAnOrderStatus(orderid); return status; } /** * Query the list of product * @return * A json string of the product list */ public String queryVirtualProductList(){ List productlist = DataBaseBroker.getListofVirtualProducts(); //encode the information into a json object String jsonstr = JSONValue.toJSONString(productlist); System.out.println(jsonstr); return jsonstr; } }
22.418605
70
0.742739
fddc39815feed7b04c442b416be7169c3dc6aa1f
4,046
package poe.level.data; import javafx.embed.swing.SwingFXUtils; import javafx.scene.control.Spinner; import javafx.scene.control.SpinnerValueFactory; import javafx.scene.image.Image; import javafx.util.StringConverter; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.logging.Logger; public class Util { private static final Logger m_logger = Logger.getLogger(Util.class.getName()); public static class HttpResponse { public int responseCode = -1; public String responseString = "Undefined"; } public static Image charToImage(String className, String asc) { Image result = null; try { BufferedImage img = ImageIO.read(Util.class.getResource("/classes/" + className + "/" + asc + ".png")); result = SwingFXUtils.toFXImage(img, null); } catch (Exception ex) { m_logger.severe("Failed to load ascendancy image for class: " + className + " asc: " + asc); } return result; } public static HttpResponse httpToString(String url) { m_logger.info("Retrieving URL: " + url); HttpURLConnection connection = null; HttpResponse httpResponse = new HttpResponse(); try { URL urlObj = new URL(url); connection = (HttpURLConnection) urlObj.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Path-Of-Leveling"); connection.connect(); httpResponse.responseCode = connection.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } connection.disconnect(); in.close(); httpResponse.responseString = response.toString(); connection.disconnect(); } catch (IOException ex) { m_logger.severe(ex.getMessage()); ex.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return httpResponse; } public static void downloadFile(URL url, File outputFile) throws IOException { try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile); ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream())) { fileOutputStream.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE); } } public static void addIntegerLimiterToIntegerSpinner(Spinner<Integer> theSpinner, SpinnerValueFactory<Integer> valueFactory) { theSpinner.setValueFactory(valueFactory); StringConverter<Integer> sci = valueFactory.getConverter(); StringConverter<Integer> sci2 = new StringConverter<Integer>() { @Override public Integer fromString(String value) { // Don't try to get fromString if the value is null or an empty String, just reset the field. if (value != null && !value.trim().isEmpty()) { try { return sci.fromString(value); } catch (NumberFormatException nfe) { // Ignore } } // if we get here, the input was invalid, reset it. theSpinner.getEditor().setText(toString(theSpinner.getValue())); return theSpinner.getValue(); } @Override public String toString(Integer value) { return sci.toString(value); } }; valueFactory.setConverter(sci2); } }
37.813084
130
0.615917
069923fe011099442822f84080ee83b59bfabb3c
7,037
package no.nav.fo.veilarbdialog.service; import lombok.RequiredArgsConstructor; import no.nav.fo.veilarbdialog.db.dao.DataVarehusDAO; import no.nav.fo.veilarbdialog.db.dao.DialogDAO; import no.nav.fo.veilarbdialog.db.dao.StatusDAO; import no.nav.fo.veilarbdialog.db.dao.VarselDAO; import no.nav.fo.veilarbdialog.domain.DatavarehusEvent; import no.nav.fo.veilarbdialog.domain.DialogData; import no.nav.fo.veilarbdialog.domain.DialogStatus; import no.nav.fo.veilarbdialog.domain.HenvendelseData; import no.nav.fo.veilarbdialog.metrics.FunksjonelleMetrikker; import org.springframework.stereotype.Service; import java.util.Date; @Service @RequiredArgsConstructor public class DialogStatusService { private final StatusDAO statusDAO; private final DialogDAO dialogDAO; private final DataVarehusDAO dataVarehusDAO; private final VarselDAO varselDAO; private final FunksjonelleMetrikker funksjonelleMetrikker; public DialogData nyHenvendelse(DialogData dialogData, HenvendelseData henvendelseData) { if (henvendelseData.getSendt() == null) { throw new UnsupportedOperationException("sendt tidspunkt kan ikke være null"); } if (henvendelseData.fraBruker()) { nyMeldingFraBruker(dialogData, henvendelseData); } else { nyMeldingFraVeileder(dialogData, henvendelseData); } return dialogDAO.hentDialog(dialogData.getId()); } public DialogData markerSomLestAvVeileder(DialogData dialogData) { if (dialogData.erNyesteHenvendelseLestAvVeileder()) { return dialogData; } statusDAO.markerSomLestAvVeileder(dialogData.getId(), new Date()); dataVarehusDAO.insertEvent(dialogData, DatavarehusEvent.LEST_AV_VEILEDER); funksjonelleMetrikker.markerDialogSomLestAvVeileder(dialogData); return dialogDAO.hentDialog(dialogData.getId()); } public DialogData markerSomLestAvBruker(DialogData dialogData) { if (dialogData.erLestAvBruker()) { return dialogData; } if (harAktivtparagraf8Varsel(dialogData)) { int antall = varselDAO.hentAntallAktiveDialogerForVarsel(dialogData.getParagraf8VarselUUID()); if (antall == 1) { varselDAO.revarslingSkalAvsluttes(dialogData.getParagraf8VarselUUID()); } } statusDAO.markerSomLestAvBruker(dialogData.getId()); dataVarehusDAO.insertEvent(dialogData, DatavarehusEvent.LEST_AV_BRUKER); funksjonelleMetrikker.markerDialogSomLestAvBruker(dialogData); return dialogDAO.hentDialog(dialogData.getId()); } private boolean harAktivtparagraf8Varsel(DialogData dialogData) { return dialogData.isHarUlestParagraf8Henvendelse() && dialogData.getParagraf8VarselUUID() != null; } public DialogData oppdaterVenterPaNavSiden(DialogData dialogData, boolean ferdigBehandlet) { if (dialogData.erFerdigbehandlet() == ferdigBehandlet) { return dialogData; } if (ferdigBehandlet) { statusDAO.setVenterPaNavTilNull(dialogData.getId()); dataVarehusDAO.insertEvent(dialogData, DatavarehusEvent.BESVART_AV_NAV); } else { statusDAO.setVenterPaNavTilNaa(dialogData.getId()); dataVarehusDAO.insertEvent(dialogData, DatavarehusEvent.VENTER_PAA_NAV); } funksjonelleMetrikker.oppdaterFerdigbehandletTidspunkt(dialogData, ferdigBehandlet); return dialogDAO.hentDialog(dialogData.getId()); } public DialogData oppdaterVenterPaSvarFraBrukerSiden(DialogData dialogData, DialogStatus dialogStatus) { if (dialogData.venterPaSvarFraBruker() == dialogStatus.venterPaSvar) { return dialogData; } if (dialogStatus.venterPaSvar) { statusDAO.setVenterPaSvarFraBrukerTilNaa(dialogStatus.getDialogId()); dataVarehusDAO.insertEvent(dialogData, DatavarehusEvent.VENTER_PAA_BRUKER); } else { statusDAO.setVenterPaSvarFraBrukerTilNull(dialogStatus.getDialogId()); dataVarehusDAO.insertEvent(dialogData, DatavarehusEvent.BESVART_AV_BRUKER); } funksjonelleMetrikker.oppdaterVenterSvar(dialogStatus); return dialogDAO.hentDialog(dialogStatus.getDialogId()); } public void settDialogTilHistorisk(DialogData dialogData) { statusDAO.setHistorisk(dialogData.getId()); if (!dialogData.erFerdigbehandlet()) { dataVarehusDAO.insertEvent(dialogData, DatavarehusEvent.BESVART_AV_NAV); } if (dialogData.venterPaSvarFraBruker()) { dataVarehusDAO.insertEvent(dialogData, DatavarehusEvent.BESVART_AV_BRUKER); } dataVarehusDAO.insertEvent(dialogData, DatavarehusEvent.SATT_TIL_HISTORISK); dialogDAO.hentDialog(dialogData.getId()); } public void oppdaterDatavarehus(DialogData oprettet) { dataVarehusDAO.insertEvent(oprettet, DatavarehusEvent.DIALOG_OPPRETTET); } private void nyMeldingFraVeileder(DialogData dialogData, HenvendelseData henvendelseData) { dataVarehusDAO.insertEvent(dialogData, DatavarehusEvent.NY_HENVENDELSE_FRA_VEILEDER); Date eldsteUlesteForBruker = getEldsteUlesteForBruker(dialogData, henvendelseData); oppdaterVenterPaNavSiden(dialogData, true); statusDAO.setEldsteUlesteForBruker(dialogData.getId(), eldsteUlesteForBruker); funksjonelleMetrikker.nyHenvendelseVeileder(dialogData); } private Date getEldsteUlesteForBruker(DialogData dialogData, HenvendelseData henvendelseData) { return dialogData.erLestAvBruker() ? henvendelseData.getSendt() : dialogData.getEldsteUlesteTidspunktForBruker(); } private void nyMeldingFraBruker(DialogData dialogData, HenvendelseData henvendelseData) { dataVarehusDAO.insertEvent(dialogData, DatavarehusEvent.NY_HENVENDELSE_FRA_BRUKER); Date nyesteUlestAvVeileder = hentTidspunktForNyesteUlestAvVeileder(dialogData, henvendelseData); Date venterPaNavSiden = dialogData.getVenterPaNavSiden(); if (dialogData.erFerdigbehandlet()) { venterPaNavSiden = henvendelseData.getSendt(); dataVarehusDAO.insertEvent(dialogData, DatavarehusEvent.VENTER_PAA_NAV); } if (dialogData.venterPaSvarFraBruker()) { dataVarehusDAO.insertEvent(dialogData, DatavarehusEvent.BESVART_AV_BRUKER); } statusDAO.setNyMeldingFraBruker( dialogData.getId(), nyesteUlestAvVeileder, venterPaNavSiden ); funksjonelleMetrikker.nyHenvendelseBruker(dialogData); } private Date hentTidspunktForNyesteUlestAvVeileder(DialogData dialogData, HenvendelseData henvendelseData) { return dialogData.erNyesteHenvendelseLestAvVeileder() ? henvendelseData.getSendt() : dialogData.getSisteUlestAvVeilederTidspunkt(); } public void markerSomParagraf8(long dialogId) { statusDAO.markerSomParagraf8(dialogId); } }
43.171779
139
0.732699
21c780c8b734d04bad90b38136181a33d01604bb
1,027
package com.yourtion.leetcode.daily.m10.d15; import com.yourtion.leetcode.utils.binary.Node; /** * 116. 填充每个节点的下一个右侧节点指针 * * @author Yourtion * @link https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/ */ public class Solution { public Node connect(Node root) { if (root == null) { return root; } // 从根节点开始 Node leftmost = root; while (leftmost.left != null) { // 遍历这一层节点组织成的链表,为下一层的节点更新 next 指针 Node head = leftmost; while (head != null) { // CONNECTION 1 if (head.left != null) { head.left.next = head.right; } // CONNECTION 2 if (head.next != null) { head.right.next = head.next.left; } // 指针向后移动 head = head.next; } // 去下一层的最左的节点 leftmost = leftmost.left; } return root; } }
27.026316
86
0.481986
d3e28c48ba413a24b5adf4153cdad4ccdda0a1c1
2,909
/* * Copyright (c) 2007 - 2010 Citrix Systems, Inc. All Rights Reserved. */ package com.citrix.wi.controls; import com.citrix.wi.mvc.WIContext; import com.citrix.wi.pageutils.Include; import com.citrix.wi.types.UserInterfaceBranding; import com.citrix.wi.util.ClientInfoUtilities; /** * Maintains presentation state for the footer control. */ public class FooterControl { private String footerText = ""; private static final String FOOTER_LINK_APPS = "http://www.citrix.com"; private static final String FOOTER_LINK_DESKTOPS = "http://www.citrix.com/xendesktop"; private static final String HDX_LINK = "http://hdx.citrix.com"; /** * Gets the footer text */ public String getFooterText() { return footerText; } /** * Sets the footer text * @param value the footer text */ public void setFooterText(String value) { footerText = value; } /** * Gets the relative path to the footer logo image. * * @return the footer image path */ public String getFooterImg(WIContext wiContext, LayoutControl layoutControl) { String img = (layoutControl.isLoggedOutPage) ? "CitrixLogoDarkLoggedOff.png" : "CitrixWatermark.png"; return ClientInfoUtilities.getImageName(wiContext.getClientInfo(), "../media/" + img); } /** * Gets the relative path to the footer HDX image. * * @return the footer HDX image path */ public String getHdxImg(WIContext wiContext, LayoutControl layoutControl) { String img = (layoutControl.isLoggedOutPage) ? "HDXLoggedOff.png" : "HDX.png"; return ClientInfoUtilities.getImageName(wiContext.getClientInfo(), "../media/" + img); } /** * Gets the alt text to use for the footer logo image. * * @return the footer logo image alt text */ public String getFooterImgAltText(WIContext wiContext) { return wiContext.getString((Include.getSiteBranding(wiContext) == UserInterfaceBranding.DESKTOPS) ? "FooterImgAltTextDesktops" : "FooterImgAltTextApps"); } /** * Gets the alt text to use for the footer HDX image. * * @return the footer HDX image alt text */ public String getHdxImgAltText(WIContext wiContext) { return wiContext.getString("HdxImgAltText"); } /** * Gets the URL for the footer logo link. * * @return the footer logo link */ public String getFooterImgLink(WIContext wiContext) { return (Include.getSiteBranding(wiContext) == UserInterfaceBranding.DESKTOPS) ? FOOTER_LINK_DESKTOPS : FOOTER_LINK_APPS; } /** * Gets the URL for the footer HDX link. * * @return the footer HDX link */ public String getHdxImgLink(WIContext wiContext) { return HDX_LINK; } }
31.619565
162
0.645583
ceaa707f5fbec46a567a5bd464115c2a4ed8ea4e
7,612
/** * 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.oozie.command.coord; import org.apache.oozie.CoordinatorActionBean; import org.apache.oozie.CoordinatorJobBean; import org.apache.oozie.WorkflowActionBean; import org.apache.oozie.WorkflowJobBean; import org.apache.oozie.client.CoordinatorAction; import org.apache.oozie.client.CoordinatorJob; import org.apache.oozie.client.WorkflowAction; import org.apache.oozie.client.WorkflowJob; import org.apache.oozie.command.CommandException; import org.apache.oozie.executor.jpa.JPAExecutorException; import org.apache.oozie.executor.jpa.WorkflowJobQueryExecutor; import org.apache.oozie.local.LocalOozie; import org.apache.oozie.service.JPAService; import org.apache.oozie.service.Services; import org.apache.oozie.test.XDataTestCase; import org.apache.oozie.workflow.WorkflowInstance; import org.apache.oozie.CoordinatorWfActionBean; import org.apache.oozie.client.CoordinatorWfAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; public class TestCoordWfActionInfoXCommand extends XDataTestCase { Services services; private CoordinatorJobBean coordJob; private List<WorkflowJobBean> wfJobs; private List<CoordinatorActionBean> coordActions; @Override protected void setUp() throws Exception { super.setUp(); services = new Services(); services.init(); createTestData(); } @Override protected void tearDown() throws Exception { services.destroy(); super.tearDown(); } /** * init the test case. * 1 coordJob * 5 coordAction created by the coordJob, while the 5th coordAction's workflow instance is null * 4 wfJob match the 1st ~ 4th coordAction * the 1st - 3rd wfAction has a wfAction named 'aa' each, but the 4th desn't. */ private void createTestData() throws Exception { JPAService jpaService = Services.get().get(JPAService.class); assertNotNull("Missing jpa service", jpaService); coordJob = addRecordToCoordJobTable(CoordinatorJob.Status.SUCCEEDED, false, false); wfJobs = new ArrayList<WorkflowJobBean>(); coordActions = new ArrayList<CoordinatorActionBean>(); for(int i = 0; i < 4; i++) { WorkflowJobBean wfJob = addRecordToWfJobTable(WorkflowJob.Status.SUCCEEDED, WorkflowInstance.Status.SUCCEEDED); wfJobs.add(wfJob); } for(int i = 0; i < 4; i++) { CoordinatorActionBean coordAction = addRecordToCoordActionTable(coordJob.getId(), (i+1), CoordinatorAction.Status.SUCCEEDED,"coord-action-get.xml", wfJobs.get(i).getId(), "SUCCEEDED", 0); coordActions.add(coordAction); } //add a coordAction that doesnt create workflow instance yet CoordinatorActionBean coordAction = addRecordToCoordActionTable(coordJob.getId(), 5, CoordinatorAction.Status.SUCCEEDED,"coord-action-get.xml", null, null, 0); coordActions.add(coordAction); //set the NominalTime,in order to keep the order of the coordAction. for(int i = 0; i < 5; i++) { setCoordActionNominalTime(coordActions.get(i).getId(), (i+1) * 1000); } //create the case that the 4th wfJob doesnt have a action named "aa" for(int i = 0; i < 4; i++) { String name = (i == 3) ? "bb" : "aa"; addRecordToWfActionTable(wfJobs.get(i).getId(), name, WorkflowAction.Status.DONE); } } public void testNormalCase() throws Exception { int offset = 2, len = 2; List<CoordinatorWfActionBean> coordWfActions = new CoordWfActionInfoXCommand(coordJob.getId(), "aa", offset, len).call(); assertEquals(2, coordWfActions.size()); List<String> wfIds = Arrays.asList(wfJobs.get(1).getId(), wfJobs.get(2).getId()); for(int i = 0; i < coordWfActions.size(); i++) { CoordinatorWfActionBean coordWfAction = coordWfActions.get(i); WorkflowActionBean wfAction = coordWfAction.getAction(); assertEquals(i + offset, coordWfActions.get(i).getActionNumber()); assertEquals(wfIds.get(i), wfAction.getWfId()); assertEquals(null, coordWfAction.getNullReason()); } } public void testActionMissing() throws CommandException{ List<CoordinatorWfActionBean> coordWfActions = new CoordWfActionInfoXCommand(coordJob.getId(), "aa", 2, 3).call(); assertEquals(3, coordWfActions.size()); assertEquals(wfJobs.get(1).getId(), coordWfActions.get(0).getAction().getWfId()); assertEquals(wfJobs.get(2).getId(), coordWfActions.get(1).getAction().getWfId()); CoordinatorWfActionBean coordWfAction = coordWfActions.get(2); assertEquals(4, coordWfAction.getActionNumber()); assertEquals(null, coordWfAction.getAction()); String expectNullReason = CoordinatorWfAction.NullReason.ACTION_NULL.getNullReason("aa", wfJobs.get(3).getId()); assertEquals(expectNullReason, coordWfAction.getNullReason()); } public void testWorkflowInstanceMissing() throws CommandException { List<CoordinatorWfActionBean> coordWfActions = new CoordWfActionInfoXCommand(coordJob.getId(), "aa", 2, 4).call(); assertEquals(4, coordWfActions.size()); CoordinatorWfActionBean coordWfAction = coordWfActions.get(3); assertEquals(5, coordWfAction.getActionNumber()); assertEquals(null, coordWfAction.getAction()); String expectNullReason = CoordinatorWfAction.NullReason.PARENT_NULL.getNullReason(); assertEquals(expectNullReason, coordWfAction.getNullReason()); } //test offset out of Range public void testOffsetOutOfRange() throws CommandException { List<CoordinatorWfActionBean> coordWfActions = new CoordWfActionInfoXCommand(coordJob.getId(), "aa", 6, 4).call(); assertEquals(0, coordWfActions.size()); } //test len out of Range public void testLenOutOfRange() throws CommandException { int offset = 2; List<CoordinatorWfActionBean> coordWfActions = new CoordWfActionInfoXCommand(coordJob.getId(), "aa", 2, 19).call(); assertEquals(4, coordWfActions.size()); for(int i = 0; i < coordWfActions.size(); i++) { assertEquals(i + offset, coordWfActions.get(i).getActionNumber()); } } //test default offset and len private void _testDefaultOffsetAndLen() throws CommandException { List<CoordinatorWfActionBean> coordWfActions = new CoordWfActionInfoXCommand(coordJob.getId(), "aa").call(); assertEquals(5, coordWfActions.size()); for(int i = 0; i < coordWfActions.size(); i++) { assertEquals(i + 1, coordWfActions.get(i).getActionNumber()); } } }
43.497143
129
0.697189
906311591ba22e2dfc938981043341f649245ad5
2,265
package com.google.template.autoesc.file; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.google.template.autoesc.inp.Source; /** * Relates character indices in the parsed input to source/line. */ final class LineMap { /** * For each SourceLineMap in sources, the index in the combined output of * its start. */ private final List<Integer> sourceBreakIndices = new ArrayList<>(); private final List<SourceLineMap> sourceLineMaps = new ArrayList<>(); void addInput(String rawChars, Source src) { int n = sourceBreakIndices.size(); int start = n != 0 ? sourceBreakIndices.get(n - 1) : 0; int end = start + rawChars.length(); sourceBreakIndices.add(end); sourceLineMaps.add(new SourceLineMap(rawChars, src)); } Source atCharIndex(int pos) { int sourceIndex = Collections.binarySearch(sourceBreakIndices, pos); if (sourceIndex < 0) { sourceIndex = ~sourceIndex; } if (sourceIndex == sourceLineMaps.size()) { return Source.UNKNOWN; } SourceLineMap sourceLineMap = sourceLineMaps.get(sourceIndex); int sourceStart = sourceIndex == 0 ? 0 : sourceBreakIndices.get(sourceIndex - 1); int relPos = pos - sourceStart; int lineIndex = Arrays.binarySearch(sourceLineMap.lineBreaks, relPos); if (lineIndex < 0) { lineIndex = ~lineIndex; } if (lineIndex == 0) { return sourceLineMap.src; } return new Source( sourceLineMap.src.source, sourceLineMap.src.lineNum + lineIndex); } } final class SourceLineMap { final Source src; final int[] lineBreaks; SourceLineMap(String rawChars, Source src) { this.src = src; int nLineBreaks = 0; int n = rawChars.length(); for (int i = 0; i < n; ++i) { if (isLineBreak(rawChars, i)) { ++nLineBreaks; } } this.lineBreaks = new int[nLineBreaks]; int k = 0; for (int i = 0; i < n; ++i) { if (isLineBreak(rawChars, i)) { lineBreaks[k++] = i; } } } private static boolean isLineBreak(String s, int i) { char ch = s.charAt(i); return ( ch == '\n' || ch == '\r' && (i + 1 == s.length() || s.charAt(i + 1) != '\n')); } }
26.647059
75
0.63223
65f966966447ec7714c31ed7d7867d8c195f9373
4,018
/* The MIT License (MIT) Copyright (c) 2016 Giacomo Marciani and Michele Porretta Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.acmutv.socstream.core.query3.tuple; import com.acmutv.socstream.common.tuple.Coordinate; import com.acmutv.socstream.common.tuple.GridCoordinate; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * JUnit test suite for {@link GridCoordinate}. * @author Giacomo Marciani {@literal <[email protected]>} * @author Michele Porretta {@literal <[email protected]>} * @since 1.0 * @see GridCoordinate */ public class GridCoordinateTest { private static final Logger LOGGER = LoggerFactory.getLogger(GridCoordinateTest.class); /** * Tests serialization of {@link GridCoordinate}. */ /*@Test public void test_serialize_grid_coordinate() throws Exception { List<GridCoordinate> coordinates = new ArrayList<>(); coordinates.add(new GridCoordinate(1,2,new Coordinate(0,0))); coordinates.add(new GridCoordinate(0,0,new Coordinate(0,0))); coordinates.add(new GridCoordinate(0,1,new Coordinate(0,0))); coordinates.add(new GridCoordinate(2,0,new Coordinate(0,0))); coordinates.add(new GridCoordinate(3,0,new Coordinate(0,0))); coordinates.add(new GridCoordinate(3,6,new Coordinate(0,0))); for (GridCoordinate expected : coordinates) { LOGGER.debug("GridCoordinate serialized: " + expected); String str = expected.toString(); GridCoordinate actual = GridCoordinate.valueOf(str); System.out.println("actual = "+ actual.toString()); Assert.assertEquals(expected.toString(), actual.toString()); } }*/ /** * Tests deserialization of {@link GridCoordinate} from a string representing an gridID */ @Test public void test_valueOfAsSensorEvent() throws Exception { List<GridCoordinate> coordinates = new ArrayList<>(); coordinates.add(new GridCoordinate(1,2,new Coordinate(1,2))); coordinates.add(new GridCoordinate(0,0,new Coordinate(1,2))); coordinates.add(new GridCoordinate(0,1,new Coordinate(1,2))); coordinates.add(new GridCoordinate(2,0,new Coordinate(1,2))); coordinates.add(new GridCoordinate(3,0,new Coordinate(1,2))); coordinates.add(new GridCoordinate(3,6,new Coordinate(1,2))); Map<String,String> IDs = new HashMap<>(); IDs.put(coordinates.get(0).getKey(),"1;2"); IDs.put(coordinates.get(1).getKey(),"0;0"); IDs.put(coordinates.get(2).getKey(),"0;1"); IDs.put(coordinates.get(3).getKey(),"2;0"); IDs.put(coordinates.get(4).getKey(),"3;0"); IDs.put(coordinates.get(5).getKey(),"3;6"); for (GridCoordinate actual : coordinates) { LOGGER.debug("GridCoordinate deserialized: " + actual); String expected = IDs.get(actual.getKey()); String actualID = actual.getKey(); Assert.assertEquals(expected,actualID); } } }
37.90566
89
0.726481
57a9cefeaf50f4c2c314351ad02fe62b58cef1b8
5,540
/* Copyright 2010, Object Management Group, Inc. * Copyright 2010, PrismTech, Inc. * Copyright 2010, Real-Time Innovations, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.omg.dds.sub; import java.io.Closeable; import java.util.Set; import org.omg.dds.core.Condition; /** * ReadCondition objects are conditions specifically dedicated to read * operations and attached to one {@link org.omg.dds.sub.DataReader}. * * ReadCondition objects allow an application to specify the data samples it * is interested in by specifying the desired sample states, view states, * and instance states. (See {@link Subscriber.DataState}.) * This allows the middleware to enable the condition only when suitable * information is available. They are to be used in conjunction with a * {@link org.omg.dds.core.WaitSet} as normal conditions. More than one ReadCondition may be * attached to the same DataReader. * * Similar to the {@link org.omg.dds.core.StatusCondition}, a ReadCondition also has a * triggerValue that determines whether the attached {@link org.omg.dds.core.WaitSet} is * BLOCKED or UNBLOCKED. However, unlike the StatusCondition, the * triggerValue of the ReadCondition is tied to the presence of at least a * sample managed by the Service with {@link org.omg.dds.sub.SampleState}, {@link org.omg.dds.sub.ViewState}, * and {@link org.omg.dds.sub.InstanceState} matching those of the ReadCondition. * * The fact that the triggerValue of a ReadCondition is dependent on the * presence of samples on the associated DataReader implies that a single * {@link org.omg.dds.sub.DataReader#take()} operation can potentially change the * triggerValue of several ReadCondition or {@link org.omg.dds.sub.QueryCondition} * conditions. For example, if all samples are taken, any ReadCondition and * QueryCondition conditions associated with the DataReader that had their * triggerValue == true before will see the triggerValue change to false. * Note that this does not guarantee that WaitSet objects that were * separately attached to those conditions will not be woken up. Once we have * triggerValue == true on a condition it may wake up the attached WaitSet, * the condition transitioning to triggerValue == false does not necessarily * 'unwakeup' the WaitSet as 'unwakening' may not be possible in general. The * consequence is that an application blocked on a WaitSet may return from * the wait with a list of conditions. some of which are no longer "active." * This is unavoidable if multiple threads are concurrently waiting on * separate WaitSet objects and taking data associated with the same * DataReader entity. * * To elaborate further, consider the following example: A ReadCondition that * has a sample state collection of {NOT_READ} will have triggerValue of true * whenever a new sample arrives and will transition to false as soon as all * the newly-arrived samples are either read (so their status changes to * {@link org.omg.dds.sub.SampleState#READ}) or taken (so they are no longer managed by the * Service). However if the same ReadCondition had a sample_statesample state * collection of {READ, NOT_READ}, then the triggerValue would only become * false once all the newly-arrived samples are taken (it is not sufficient * to read them as that would only change the SampleState to READ, which * overlaps the collection on the ReadCondition. * * @param <TYPE> The concrete type of the data that can be read using the * the {@link org.omg.dds.sub.DataReader} that created this ReadCondition. */ public interface ReadCondition<TYPE> extends Closeable, Condition { /** * This operation returns the set of sample states that are taken into * account to determine the triggerValue of the ReadCondition. These are * the sample states specified when the ReadCondition was created. * * @return an unmodifiable set. */ public Set<SampleState> getSampleStates(); /** * This operation returns the set of view states that are taken into * account to determine the triggerValue of the ReadCondition. These are * the view states specified when the ReadCondition was created. * * @return an unmodifiable set. */ public Set<ViewState> getViewStates(); /** * This operation returns the set of instance states that are taken into * account to determine the triggerValue of the ReadCondition. These are * the instance states specified when the ReadCondition was created. * * @return an unmodifiable set. */ public Set<InstanceState> getInstanceStates(); /** * @return the DataReader associated with the ReadCondition. Note that * there is exactly one DataReader associated with each * ReadCondition. */ public DataReader<TYPE> getParent(); /** * Reclaim any resources associated with this condition. */ public void close(); }
46.554622
109
0.738989
c087086d0d10ce26df39185581726fc10fbbf578
2,571
/* * #%L * ImgLib: a general-purpose, multidimensional image processing library. * %% * Copyright (C) 2009 - 2013 Stephan Preibisch, Tobias Pietzsch, Barry DeZonia, * Stephan Saalfeld, Albert Cardona, Curtis Rueden, Christian Dietz, Jean-Yves * Tinevez, Johannes Schindelin, Lee Kamentsky, Larry Lindsey, Grant Harris, * Mark Hiner, Aivar Grislis, Martin Horn, Nick Perry, Michael Zinsmaier, * Steffen Jaensch, Jan Funke, Mark Longair, and Dimiter Prodanov. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package script.imglib.algorithm; import mpicbg.imglib.outofbounds.OutOfBoundsStrategyMirrorFactory; import mpicbg.imglib.type.numeric.NumericType; /** Scale a 2D or 3D image, resizing only the 2D planes as necessary. The Z axis is left untouched. * * The constructors accept either an {@link Image} or an {@link IFunction} from which an {@link Image} is generated. */ /** * TODO * */ public class Scale2D<N extends NumericType<N>> extends Affine3D<N> { /** Scale the given image in 2D using the best interpolation available. */ public Scale2D(final Object fn, final Number scale) throws Exception { this(fn, scale.floatValue(), scale.floatValue(), Affine3D.BEST); } public Scale2D(final Object fn, final Number scale, final Mode mode) throws Exception { this(fn, scale.floatValue(), scale.floatValue(), mode); } public Scale2D(final Object fn, final Number scaleX, Number scaleY) throws Exception { this(fn, scaleX.floatValue(), scaleY.floatValue(), Affine3D.BEST); } public Scale2D(final Object fn, final Number scaleX, Number scaleY, final Mode mode) throws Exception { this(fn, scaleX.floatValue(), scaleY.floatValue(), mode); } public Scale2D(final Object fn, final float scaleX, final float scaleY, final Mode mode) throws Exception { super(fn, new float[]{scaleX, 0, 0, 0, 0, scaleY, 0, 0, 0, 0, 1, 0}, mode, new OutOfBoundsStrategyMirrorFactory<N>()); } }
39.553846
120
0.727732
f5a8eb592884e6785cb77c2d17f4be98586d344c
124
package org.anyboot.mvc.plugin.springmvc; public class TemplateView extends org.anyline.plugin.springmvc.TemplateView{ }
31
77
0.822581
ea57830b998a66c072592634474e4770dfc11ca5
446
package edu.fdiazaguirre.hackerrank; public class Solution { static final char[] VOCABULARY = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; static final int OFFSET = 10; public static void main(String[] args) { // TODO Auto-generated method stub for (int i = 0; i < VOCABULARY.length; i++) { System.out.println(Character.getNumericValue(VOCABULARY[i]) - OFFSET); } } }
29.733333
140
0.591928
ba820a2119c4ce7ca6f75a6c151ccd924108014e
12,245
/* * Copyright (c) 2011-2019, 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.core.image; import boofcv.concurrency.*; import boofcv.struct.image.*; /** * <p> * Operations that return information about the specific image. Useful when writing highly abstracted code * which is independent of the input image. * </p> * * @author Peter Abeles */ // TODO rename to GImageOps ? public class GeneralizedImageOps { public static boolean isFloatingPoint(Class<?> imgType) { if( GrayF.class.isAssignableFrom(imgType) ) { return true; } else { return false; } } public static double get(ImageGray img, int x, int y) { if (img instanceof GrayI8) { return ((GrayI8) img).get(x, y); } else if (img instanceof GrayI16) { return ((GrayI16) img).get(x, y); } else if (img instanceof GrayS32) { return ((GrayS32) img).get(x, y); } else if (img instanceof GrayF32) { return ((GrayF32) img).get(x, y); } else if (img instanceof GrayF64) { return ((GrayF64) img).get(x, y); } else if (img instanceof GrayS64) { return ((GrayS64) img).get(x, y); } else { throw new IllegalArgumentException("Unknown or incompatible image type: " + img.getClass().getSimpleName()); } } public static double get(ImageBase img, int x, int y , int band ) { if (img instanceof ImageGray) { return get((ImageGray) img, x, y); } else if (img instanceof ImageInterleaved) { return get((ImageInterleaved) img, x, y, band); } else if (img instanceof Planar) { return get(((Planar) img).getBand(band), x, y); } else { throw new IllegalArgumentException("Unknown or incompatible image type: " + img.getClass().getSimpleName()); } } public static double get(ImageInterleaved img, int x, int y , int band ) { if (img instanceof InterleavedU8) { return ((InterleavedU8) img).getBand(x, y, band); } else if (img instanceof InterleavedS8) { return ((InterleavedS8) img).getBand(x, y, band); } else if (img instanceof InterleavedS16) { return ((InterleavedS16) img).getBand(x, y, band); } else if (img instanceof InterleavedU16) { return ((InterleavedU16) img).getBand(x, y, band); } else if (img instanceof InterleavedS32) { return ((InterleavedS32) img).getBand(x, y, band); } else if (img instanceof InterleavedS64) { return ((InterleavedS64) img).getBand(x, y, band); } else if (img instanceof InterleavedF32) { return ((InterleavedF32) img).getBand(x, y, band); } else if (img instanceof InterleavedF64) { return ((InterleavedF64) img).getBand(x, y, band); } else { throw new IllegalArgumentException("Unknown or incompatible image type: " + img.getClass().getSimpleName()); } } public static <T extends ImageGray> T createSingleBand(ImageDataType type, int width, int height) { Class<T> typeClass = ImageType.getImageClass(ImageType.Family.GRAY, type); return (T)createSingleBand(typeClass, width, height); } public static <T extends ImageBase> T createImage(Class<T> type, int width, int height, int numBands ) { if( (Class)type == Planar.class ) throw new IllegalArgumentException("Can't use this function with planar because the data type needs to be specified too"); if( ImageGray.class.isAssignableFrom(type)) return (T)createSingleBand((Class)type,width,height); else if( ImageInterleaved.class.isAssignableFrom(type)) return (T)createInterleaved((Class)type,width,height,numBands); else throw new RuntimeException("Unknown"); } public static <T extends ImageGray<T>> T createSingleBand(Class<T> type, int width, int height) { type = convertGenericToSpecificType(type); if (type == GrayU8.class) { return (T)new GrayU8(width, height); } else if (type == GrayS8.class) { return (T)new GrayS8(width, height); } else if (type == GrayS16.class) { return (T)new GrayS16(width, height); } else if (type == GrayU16.class) { return (T)new GrayU16(width, height); } else if (type == GrayS32.class) { return (T)new GrayS32(width, height); } else if (type == GrayS64.class) { return (T)new GrayS64(width, height); } else if (type == GrayF32.class) { return (T)new GrayF32(width, height); } else if (type == GrayF64.class) { return (T)new GrayF64(width, height); } else if( (Class)type == GrayI.class ) { // ImageInteger is a generic type, so just create something return (T)new GrayS32(width,height); } throw new RuntimeException("Unknown type: "+type.getSimpleName()); } public static <T extends ImageInterleaved> T createInterleaved(ImageDataType type, int width, int height , int numBands) { Class<T> typeClass = ImageType.getImageClass(ImageType.Family.INTERLEAVED, type); return (T)createInterleaved(typeClass,width,height,numBands); } public static <T extends ImageInterleaved<T>> T createInterleaved(Class<T> type, int width, int height , int numBands) { type = convertGenericToSpecificType(type); if (type == InterleavedU8.class) { return (T)new InterleavedU8(width, height,numBands); } else if (type == InterleavedS8.class) { return (T)new InterleavedS8(width, height,numBands); } else if (type == InterleavedU16.class) { return (T)new InterleavedU16(width, height,numBands); } else if (type == InterleavedS16.class) { return (T)new InterleavedS16(width, height,numBands); } else if (type == InterleavedS32.class) { return (T)new InterleavedS32(width, height,numBands); } else if (type == InterleavedS64.class) { return (T)new InterleavedS64(width, height,numBands); } else if (type == InterleavedF32.class) { return (T)new InterleavedF32(width, height,numBands); } else if (type == InterleavedF64.class) { return (T)new InterleavedF64(width, height,numBands); } else if( (Class)type == ImageInterleaved.class ) { // ImageInteger is a generic type, so just create something return (T)new InterleavedS32(width,height,numBands); } throw new RuntimeException("Unknown type: "+type.getSimpleName()); } public static void set(ImageGray img, int x, int y, double value) { if (GrayI.class.isAssignableFrom(img.getClass())) { ((GrayI)img).set(x,y,(int)value); } else if (img instanceof GrayF32) { ((GrayF32) img).set(x, y,(float)value); } else if (img instanceof GrayF64) { ((GrayF64) img).set(x, y, value); } else if (img instanceof GrayS64) { ((GrayS64) img).set(x, y, (long)value); } else { throw new IllegalArgumentException("Unknown or incompatible image type: " + img.getClass().getSimpleName()); } } public static void setM(ImageBase img, int x, int y, double... value) { if( img instanceof Planar) { Planar ms = (Planar) img; for (int i = 0; i < value.length; i++) { set(ms.getBand(i), x, y, value[i]); } } else if( img instanceof ImageInterleaved ) { for (int band = 0; band < value.length; band++) { if (img instanceof InterleavedU8) { ((InterleavedU8) img).setBand(x, y, band, (byte) value[band]); } else if (img instanceof InterleavedS8) { ((InterleavedS8) img).setBand(x, y, band, (byte) value[band]); } else if (img instanceof InterleavedS16) { ((InterleavedS16) img).setBand(x, y, band, (short) value[band]); } else if (img instanceof InterleavedU16) { ((InterleavedU16) img).setBand(x, y, band, (short) value[band]); } else if (img instanceof InterleavedS32) { ((InterleavedS32) img).setBand(x, y, band, (int) value[band]); } else if (img instanceof InterleavedS64) { ((InterleavedS64) img).setBand(x, y, band, (long) value[band]); } else if (img instanceof InterleavedF32) { ((InterleavedF32) img).setBand(x, y, band, (float) value[band]); } else if (img instanceof InterleavedF64) { ((InterleavedF64) img).setBand(x, y, band, value[band]); } else { throw new IllegalArgumentException("Unknown or incompatible image type: " + img.getClass().getSimpleName()); } } } else if( img instanceof ImageGray) { if( value.length != 1 ) throw new IllegalArgumentException("For a single band image the input pixel must have 1 band"); set((ImageGray)img,x,y,value[0]); } else { throw new IllegalArgumentException("Add support for this image type!"); } } public static void setB(ImageBase img, int x, int y, int band , double value ) { if( img instanceof Planar) { Planar ms = (Planar) img; GeneralizedImageOps.set(ms.getBand(band),x,y,value); } else if( img instanceof ImageInterleaved ) { if (img instanceof InterleavedU8) { ((InterleavedU8) img).setBand(x, y, band, (byte) value); } else if (img instanceof InterleavedS8) { ((InterleavedS8) img).setBand(x, y, band, (byte) value); } else if (img instanceof InterleavedS16) { ((InterleavedS16) img).setBand(x, y, band, (short) value); } else if (img instanceof InterleavedU16) { ((InterleavedU16) img).setBand(x, y, band, (short) value); } else if (img instanceof InterleavedS32) { ((InterleavedS32) img).setBand(x, y, band, (int) value); } else if (img instanceof InterleavedS64) { ((InterleavedS64) img).setBand(x, y, band, (long) value); } else if (img instanceof InterleavedF32) { ((InterleavedF32) img).setBand(x, y, band, (float) value); } else if (img instanceof InterleavedF64) { ((InterleavedF64) img).setBand(x, y, band, value); } else { throw new IllegalArgumentException("Unknown or incompatible image type: " + img.getClass().getSimpleName()); } } else if( img instanceof ImageGray) { if( band != 0 ) throw new IllegalArgumentException("For a single band image the input pixel must have 1 band"); set((ImageGray)img,x,y,value); } else { throw new IllegalArgumentException("Add support for this image type!"); } } public static <T extends ImageGray<T>> int getNumBits(Class<T> type) { if (type == GrayU8.class) { return 8; } else if (type == GrayS8.class) { return 8; } else if (type == GrayS16.class) { return 16; } else if (type == GrayU16.class) { return 16; } else if (type == GrayS32.class) { return 32; } else if (type == GrayS64.class) { return 64; } else if (type == GrayF32.class) { return 32; } else if (type == GrayF64.class) { return 64; } throw new RuntimeException("Unknown type: "+type.getSimpleName()); } public static WorkArrays createWorkArray(ImageType<?> type) { if( type.getDataType().isInteger() ) { if( type.getDataType().getNumBits() < 64 ) { return new IWorkArrays(); } else { return new LWorkArrays(); } } else if( type.getDataType().getNumBits() < 64 ) { return new FWorkArrays(); } else { return new DWorkArrays(); } } /** * If an image is to be created then the generic type can't be used a specific one needs to be. An arbitrary * specific image type is returned here. */ public static <T> T convertGenericToSpecificType(Class<?> type) { if (type == GrayI8.class) return (T) GrayU8.class; if (type == GrayI16.class) return (T) GrayS16.class; if (type == InterleavedI8.class) return (T) InterleavedU8.class; if (type == InterleavedI16.class) return (T) InterleavedS16.class; return (T) type; } public static Object getArray(ImageGray input) { if( input instanceof GrayI8) return ((GrayI8)input).data; else if( input instanceof GrayI16 ) return ((GrayI16)input).data; else if( input instanceof GrayS32 ) return ((GrayS32)input).data; else if( input instanceof GrayS64 ) return ((GrayS64)input).data; else if( input instanceof GrayF32 ) return ((GrayF32)input).data; else if( input instanceof GrayF64 ) return ((GrayF64)input).data; else throw new RuntimeException("Unknown"); } }
38.02795
125
0.682074
8b48783f8213ccc3e20c585da80d31c2a2c5a3ef
5,722
/** * Licensed to the Austrian Association for Software Tool Integration (AASTI) * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. The AASTI 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.openengsb.ui.common.taskbox.web; import java.util.ArrayList; import javax.inject.Inject; import javax.inject.Named; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.extensions.markup.html.repeater.data.table.DefaultDataTable; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.FilterForm; import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.FilterToolbar; import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.FilteredAbstractColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.GoAndClearFilter; import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.TextFilteredPropertyColumn; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.EmptyPanel; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.openengsb.core.workflow.api.TaskboxException; import org.openengsb.core.workflow.api.model.Task; import org.openengsb.ui.common.taskbox.WebTaskboxService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TaskOverviewPanel extends Panel { private static final long serialVersionUID = -8724223987824602812L; public static final Logger LOGGER = LoggerFactory.getLogger(TaskOverviewPanel.class); private final TaskDataProvider dataProvider = new TaskDataProvider(); private Panel panel = (Panel) new EmptyPanel("taskPanel").setOutputMarkupId(true); @Inject @Named("webtaskboxService") private WebTaskboxService webtaskboxService; @SuppressWarnings("serial") public TaskOverviewPanel(String id) { super(id); setOutputMarkupId(true); ArrayList<IColumn<Task, String>> columns = new ArrayList<IColumn<Task, String>>(); IColumn<Task, String> actionsColumn = new FilteredAbstractColumn<Task, String>(Model.of("Actions")) { @Override public Component getFilter(String componentId, FilterForm<?> form) { return new GoAndClearFilter(componentId, form); } @Override @SuppressWarnings("rawtypes") public void populateItem(Item cellItem, String componentId, IModel rowModel) { final Task task = (Task) rowModel.getObject(); cellItem.add(new UserActionsPanel(componentId, task)); } }; columns.add(actionsColumn); columns.add(new TextFilteredPropertyColumn<Task, String, String>(Model.of("TaskId"), "taskId", "taskId")); columns.add(new TextFilteredPropertyColumn<Task, String, String>(Model.of("TaskType"), "taskType", "taskType")); columns.add(new TextFilteredPropertyColumn<Task, String, String>(Model.of("Description"), "description", "description")); columns.add(new PropertyColumn<Task, String>(Model.of("TaskCreationTimestamp"), "taskCreationTimestamp", "taskCreationTimestamp")); FilterForm<Task> form = new FilterForm<Task>("form", dataProvider); DefaultDataTable<Task, String> dataTable = new DefaultDataTable<Task, String>("dataTable", columns, dataProvider, 15); dataTable.addTopToolbar(new FilterToolbar(dataTable, form, dataProvider)); form.add(dataTable); add(form); add(panel); } private class UserActionsPanel extends Panel { private static final long serialVersionUID = -8163071854733837122L; private final Task task; @SuppressWarnings("serial") public UserActionsPanel(String id, Task t) { super(id); task = t; AjaxLink<Task> link = new AjaxLink<Task>("taskLink") { @Override public void onClick(AjaxRequestTarget target) { try { Panel newPanel = webtaskboxService.getTaskPanel(task, "taskPanel"); newPanel.setOutputMarkupId(true); panel.replaceWith(newPanel); panel = newPanel; target.add(panel); } catch (TaskboxException e) { LOGGER.error("Taskbox panel could not be started", e); } } }; link.add(new Label("linkLabel", String.format("%s (%s)", task == null ? "null" : task.getName(), task == null ? "null" : task.getTaskType()))); add(link); } } }
45.055118
120
0.690842
bc527a8f6007918a9b0528254d42dab4abdbdfe2
3,009
package io.github.phantamanta44.libnine.block.state; import com.google.common.collect.Lists; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import javax.annotation.Nullable; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; @SuppressWarnings("rawtypes") public class VirtualState { private final Map<IProperty<?>, Comparable<?>> props; @Nullable private Integer hashCode = null; private VirtualState() { this.props = new HashMap<>(); } @SuppressWarnings("unchecked") public Map<String, String> getSerializedProperties() { Map<String, String> result = new HashMap<>(); props.forEach((p, v) -> result.put(p.getName(), ((IProperty)p).getName(v))); return result; } @SuppressWarnings("unchecked") public <T extends Comparable<T>> T get(IProperty<T> prop) { return (T)props.get(prop); } @SuppressWarnings("EqualsBetweenInconvertibleTypes") public boolean matches(IBlockState state) { for (Map.Entry<IProperty<?>, Comparable<?>> prop : props.entrySet()) { if (!state.getValue(prop.getKey()).equals(prop.getValue())) return false; } return true; } @Override public int hashCode() { return hashCode == null ? (hashCode = props.hashCode()) : hashCode; } @Override public boolean equals(Object obj) { return obj instanceof VirtualState && props.equals(((VirtualState)obj).props); } @SuppressWarnings({ "unchecked", "RedundantCast" }) public IBlockState synthesize(BlockStateContainer container) { IBlockState state = container.getBaseState(); for (Map.Entry<IProperty<?>, Comparable<?>> prop : props.entrySet()) { state = state.withProperty((IProperty)prop.getKey(), (Comparable)prop.getValue()); } return state; } private Stream<VirtualState> cartesian(IProperty<?> prop) { return prop.getAllowedValues().stream().map(v -> compose(prop, v)); } private VirtualState compose(IProperty<?> prop, Comparable value) { VirtualState result = new VirtualState(); result.props.putAll(props); result.props.put(prop, value); return result; } private VirtualState compose(VirtualState other) { VirtualState result = new VirtualState(); result.props.putAll(props); result.props.putAll(other.props); return result; } public static List<VirtualState> cartesian(List<IProperty<?>> props) { return props.stream().<List<VirtualState>>reduce(Lists.newArrayList(new VirtualState()), (l, p) -> l.stream().flatMap(s -> s.cartesian(p)).collect(Collectors.toList()), (a, b) -> a.stream().flatMap(s -> b.stream().map(s::compose)).collect(Collectors.toList())); } }
33.433333
108
0.657694
f30607aa27c1baddffb184ddb786f6d6b6743a81
1,810
/* * Copyright 2018-2019 Ki11er_wolf * * 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.ki11erwolf.resynth.features; /** * Object holder class that holds references to every * created Resynth {@link net.minecraft.world.gen.feature.Feature}. * Also provides a base class for registering the created features. */ @SuppressWarnings("unused") public class ResynthFeatures { /** * Reference to the {@link SeedPodFeature}. */ private static final SeedPodFeature SEED_POD_FEATURE = new SeedPodFeature(); /** * Reference to the {@link MineralStoneFeature}. */ private static final MineralStoneFeature MINERAL_ROCK_FEATURE = new MineralStoneFeature(); /** * Reference to the {@link CalviniteFeature} */ private static final CalviniteFeature CALVINITE_FEATURE = new CalviniteFeature(); /** * Reference to the {@link SylvaniteFeature} */ private static final SylvaniteFeature SYLVANITE_FEATURE = new SylvaniteFeature(); /**Private Constructor.*/ private ResynthFeatures(){} /** * Static initialization method. Ensures * all Resynth Features are registered * to the game. */ public static void init(){ /*NO-OP - just serves to initialize the static references.*/ } }
31.206897
94
0.70442
831513ec26dc3f01014e229f33e9aef63862d45a
791
package com.aoeai.spin.accelerator.themes.customize.xy.finance.bean; import com.aoeai.spin.accelerator.generate.common.BaseClassProperty; import lombok.Data; import java.util.List; /** * 门面控制器测试类 * @author aoe * @date 2020/6/23 */ @Data public class XyFinFacadeTest extends BaseClassProperty { /** * 测试主机地址 */ private String hostTest; /** * url 前缀 */ private String urlPrefix; /** * url公共路径 */ private String urlCommonPath; private XyFinForm form; private XyFinPageListQo pageListQO; /** * 新增方法参数 */ private List<String> createParamList; /** * 新增/更新方法参数 */ private List<String> createOrUpdateParamList; /** * 更新方法参数 */ private List<String> updateParamList; }
15.509804
68
0.628319
8d894964da59eb8c03fc6d81154b6d9caa19cf78
63
package jports.data; public enum FilterOperation { AND, OR }
10.5
29
0.746032
a0a6c24860142787654004cb2f0e91dd2255501c
185
package com.arrow.dashboard.widget; public interface IScheduledWidget extends IWidget { public void start(); public void run(); public void stop(); public void destroy(); }
15.416667
51
0.724324
1c4f0cb55ae4f02c8f9a95e6a7fb9932bfcc7531
3,210
package com.pomelo.devnews.model; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; public class MobileNews { public static final String URL_ANDROID_NEWS = "http://gank.avosapps.com/api/data/Android/10/"; public static final String URL_IOS_NEWS = "http://gank.avosapps.com/api/data/iOS/10/"; public enum MobileType { ANDORID, ISO; } // 作者 private String who; // 时间 private String publishedAt; // 文章标题 private String desc; // 文章地址 private String url; public MobileNews() { } public MobileNews(String who, String publishedAt, String desc, String url) { this.who = who; this.publishedAt = publishedAt; this.desc = desc; this.url = url; } public static String getRequestUrl(MobileType type, int page) { switch (type) { case ANDORID: return URL_ANDROID_NEWS + page; case ISO: return URL_IOS_NEWS + page; default: return ""; } } public static ArrayList<MobileNews> parse(JSONArray resultsArray) { ArrayList<MobileNews> mobileNewses = new ArrayList<>(); for (int i = 0; i < resultsArray.length(); i++) { MobileNews mobileNews = new MobileNews(); JSONObject jsonObject = resultsArray.optJSONObject(i); mobileNews.setWho(jsonObject.optString("who")); mobileNews.setPublishedAt("publishedAt"); mobileNews.setDesc(jsonObject.optString("desc")); mobileNews.setUrl(jsonObject.optString("url")); mobileNewses.add(mobileNews); } return mobileNewses; } public static ArrayList<MobileNews> parseCache(JSONArray resultsArray) { ArrayList<MobileNews> mobileNewses = new ArrayList<>(); for (int i = 0; i < resultsArray.length(); i++) { MobileNews mobileNews = new MobileNews(); JSONObject jsonObject = resultsArray.optJSONObject(i); mobileNews.setWho(jsonObject.optString("who")); mobileNews.setPublishedAt("publishedAt"); mobileNews.setDesc(jsonObject.optString("desc")); mobileNews.setUrl(jsonObject.optString("url")); mobileNewses.add(mobileNews); } return mobileNewses; } @Override public String toString() { return "MobileNews{" + "who='" + who + '\'' + ", publishedAt='" + publishedAt + '\'' + ", desc='" + desc + '\'' + ", url='" + url + '\'' + '}'; } public String getWho() { return who; } public void setWho(String who) { this.who = who; } public String getPublishedAt() { return publishedAt; } public void setPublishedAt(String publishedAt) { this.publishedAt = publishedAt; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
24.503817
98
0.574143
713dccd68a7f8240ec41280fd13d7f4d59432453
751
package com.liziczh.designpattern.chain.service; import com.liziczh.designpattern.chain.Handler; import com.liziczh.designpattern.chain.handler.AHandler; import com.liziczh.designpattern.chain.handler.BHandler; import com.liziczh.designpattern.chain.handler.CHandler; /** * A * * @author chenzhehao * @version 1.0 * @description * @date 2022/6/15 12:34 下午 */ public class AbcService { public void execute() { Handler<String> handler = Handler.<String>builder() .add(new AHandler()) .add(new BHandler()) .add(new CHandler()) .build(); handler.execute("go"); } public static void main(String[] args) { new AbcService().execute(); } }
21.457143
59
0.63249
6e43e21ef0ec4888053e316d0fcf0ef890691750
1,605
/* * Copyright 2021 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. */ package com.google.events.cloud.cloudbuild.v1; import java.util.Map; /** * Pairs a set of secret environment variables containing encrypted * values with the Cloud KMS key to use to decrypt the value. */ public class Secret { private String kmsKeyName; private Map<String, String> secretEnv; /** * Cloud KMS key name to use to decrypt these envs. */ public String getKmsKeyName() { return kmsKeyName; } public void setKmsKeyName(String value) { this.kmsKeyName = value; } /** * Map of environment variable name to its encrypted value. * * Secret environment variables must be unique across all of a build's * secrets, and must be used by at least one build step. Values can be at most * 64 KB in size. There can be at most 100 secret values across all of a * build's secrets. */ public Map<String, String> getSecretEnv() { return secretEnv; } public void setSecretEnv(Map<String, String> value) { this.secretEnv = value; } }
34.891304
83
0.707165
d74dfddf7b3668de92c5215b89a0c56f104b431a
810
package lykrast.defiledlands.common.item; import java.util.List; import javax.annotation.Nullable; import lykrast.defiledlands.common.util.LocUtils; import net.minecraft.block.Block; import net.minecraft.client.resources.I18n; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; public class ItemBlockTooltip extends ItemBlock { public ItemBlockTooltip(Block block) { super(block); } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) { tooltip.addAll(LocUtils.getTooltips(TextFormatting.GRAY.toString() + I18n.format(super.getUnlocalizedName(stack) + ".tooltip"))); } }
27.931034
131
0.802469
7936a7e067aea32f0fbd47fba341cad154502c26
1,798
package com.projects.melih.wonderandwander; import android.os.StrictMode; import com.crashlytics.android.Crashlytics; import com.projects.melih.wonderandwander.di.DaggerSingletonComponent; import com.projects.melih.wonderandwander.di.SingletonComponent; import com.squareup.leakcanary.LeakCanary; import javax.inject.Inject; import dagger.android.AndroidInjector; import dagger.android.support.DaggerApplication; import io.fabric.sdk.android.Fabric; import timber.log.Timber; /** * Created by Melih Gültekin on 18.06.2018 */ public class WonderAndWanderApplication extends DaggerApplication { @Inject SingletonComponent singletonComponent; @Override public void onCreate() { if (BuildConfig.DEBUG) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectAll() .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .build()); } super.onCreate(); if (!BuildConfig.DEBUG) { Fabric.with(this, new Crashlytics()); } if (LeakCanary.isInAnalyzerProcess(this)) { return; } LeakCanary.install(this); Timber.plant(new Timber.DebugTree()); } @Override protected AndroidInjector<? extends WonderAndWanderApplication> applicationInjector() { return DaggerSingletonComponent.builder().create(this); } public SingletonComponent getSingletonComponent() { return singletonComponent; } }
29.47541
91
0.649055
da1135cbaf891ddd06aad177bdb68510f7ad87fb
1,673
package app.discoveritech.hoom.Activities; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.LinearLayout; import app.discoveritech.hoom.APIConfig.PostWebDataAPI; import app.discoveritech.hoom.LocalDatabase.PreferencesHandler; import app.discoveritech.hoom.R; public class SplashActivity extends AppCompatActivity { LinearLayout splash_layout; PreferencesHandler preferencesHandler; PostWebDataAPI postWebDataAPI; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); init(); } private void init() { postWebDataAPI = new PostWebDataAPI(SplashActivity.this); preferencesHandler = new PreferencesHandler(SplashActivity.this); splash_layout = findViewById(R.id.layout); Animation animZoomIn = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.zoom_in); splash_layout.startAnimation(animZoomIn); postWebDataAPI.GetAllTowns(); startActivity(); } private void startActivity() { new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(SplashActivity.this, LoginActivity.class); startActivity(intent); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); finish(); } }, 2500); } }
33.46
101
0.708906
d0b0ed9c18d47a9783f4fa9d2b7c7ef1191bd879
1,063
package com.inet.testapplication; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.UIManager; /** * Test Program */ public class TestLauncher { /** * Startpunkt vom Installer * * @param args ignored * @throws Exception if any error occur on connection the server */ public static void main( String[] args ) throws Exception { try { // Set OS L&F if some error message will be displayed UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); } catch( Throwable e ) { // ignore } final JFrame frame = new JFrame( "Test Application" ); frame.setUndecorated( true ); frame.setAlwaysOnTop( true ); frame.setVisible( true ); frame.setLocationRelativeTo( null ); JOptionPane.showMessageDialog( frame, "The Application seems to work, right?", "Test Application", JOptionPane.OK_OPTION ); frame.dispose(); System.exit(0); } }
29.527778
132
0.613358
35180cef75e611a93212c2fbfbb52c221d4d27ce
397
package com.eorionsolution.demo.bpms.creditcardapplicationdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class CreditCardApplicationDemoApplication { public static void main(String[] args) { SpringApplication.run(CreditCardApplicationDemoApplication.class, args); } }
28.357143
80
0.823678
24514ddf59429d01cfdd603b0a59bc471cc2aab4
640
package com.linkedin.common.client; import com.linkedin.common.urn.CorpuserUrn; import com.linkedin.identity.CorpUserKey; import com.linkedin.restli.client.Client; import javax.annotation.Nonnull; public class CorpUsersClient extends BaseClient { protected CorpUsersClient(@Nonnull Client restliClient) { super(restliClient); } @Nonnull protected CorpUserKey toCorpUserKey(@Nonnull CorpuserUrn urn) { return new CorpUserKey().setName(urn.getUsernameEntity()); } @Nonnull protected CorpuserUrn toCorpUserUrn(@Nonnull CorpUserKey key) { return new CorpuserUrn(key.getName()); } }
25.6
67
0.740625
8096b2ceefaed4893572c216fdb99e2d83aa2daa
367
package com.Attributs; public class Ressource { /* class contenant les attributs de la ressource demandee */ private String name; Ressource(String name) { this.name=name; } public void setName(String name) { this.name = name; } public String getName() { return name; } }
15.956522
59
0.550409
655a58775626822bd86297ec5a6f598065f31e48
13,581
/******************************************************************************* * Copyright (C) 2005-2013 Alfresco Software Limited. * * This file is part of the Alfresco Mobile SDK. * * 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.alfresco.mobile.android.api.services.impl; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.alfresco.mobile.android.api.model.Folder; import org.alfresco.mobile.android.api.model.KeywordSearchOptions; import org.alfresco.mobile.android.api.model.ListingContext; import org.alfresco.mobile.android.api.model.Node; import org.alfresco.mobile.android.api.model.PagingResult; import org.alfresco.mobile.android.api.model.SearchLanguage; import org.alfresco.mobile.android.api.model.impl.PagingResultImpl; import org.alfresco.mobile.android.api.services.SearchService; import org.alfresco.mobile.android.api.session.AlfrescoSession; import org.alfresco.mobile.android.api.session.impl.AbstractAlfrescoSessionImpl; import org.alfresco.mobile.android.api.utils.messages.Messagesl18n; import org.apache.chemistry.opencmis.client.api.ObjectFactory; import org.apache.chemistry.opencmis.client.api.OperationContext; import org.apache.chemistry.opencmis.client.api.Session; import org.apache.chemistry.opencmis.commons.data.ObjectData; import org.apache.chemistry.opencmis.commons.data.ObjectList; import org.apache.chemistry.opencmis.commons.spi.DiscoveryService; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; /** * Implementation of SearchService. * * @author Jean Marie Pascal */ public class SearchServiceImpl extends AlfrescoService implements SearchService { private Session cmisSession; /** * Default constructor for service. </br> Used by the * {@link ServiceRegistry}. * * @param repositorySession */ public SearchServiceImpl(AlfrescoSession repositorySession) { super(repositorySession); this.cmisSession = ((AbstractAlfrescoSessionImpl) repositorySession).getCmisSession(); } /** {@inheritDoc} */ public List<Node> search(String statement, SearchLanguage language) { return search(statement, language, null).getList(); } /** {@inheritDoc} */ public List<Node> keywordSearch(String keywords, KeywordSearchOptions options) { if (isStringNull(keywords)) { throw new IllegalArgumentException(String.format( Messagesl18n.getString("ErrorCodeRegistry.GENERAL_INVALID_ARG_NULL"), "keywords")); } KeywordSearchOptions tmpOptions = options; if (tmpOptions == null) { tmpOptions = new KeywordSearchOptions(); } return keywordSearch(keywords, tmpOptions, null).getList(); } /** {@inheritDoc} */ public PagingResult<Node> keywordSearch(String keywords, KeywordSearchOptions options, ListingContext listingContext) { String statement = createQuery(keywords, options.getTypeName(), options.doesIncludeContent(), options.isExactMatch(), options.getFolder(), options.doesIncludeDescendants(), listingContext); return search(statement, SearchLanguage.CMIS, listingContext); } /** {@inheritDoc} */ public PagingResult<Node> search(String statement, SearchLanguage language, ListingContext listingContext) { if (isStringNull(statement)) { throw new IllegalArgumentException(String.format( Messagesl18n.getString("ErrorCodeRegistry.GENERAL_INVALID_ARG_NULL"), "statement")); } if (isObjectNull(language)) { throw new IllegalArgumentException(String.format( Messagesl18n.getString("ErrorCodeRegistry.GENERAL_INVALID_ARG_NULL"), "language")); } try { DiscoveryService discoveryService = cmisSession.getBinding().getDiscoveryService(); OperationContext ctxt = cmisSession.getDefaultContext(); ObjectFactory objectFactory = cmisSession.getObjectFactory(); BigInteger maxItems = BigInteger.valueOf(ListingContext.DEFAULT_MAX_ITEMS); BigInteger skipCount = BigInteger.valueOf(0); String tmpStatement = statement; if (listingContext != null) { skipCount = BigInteger.valueOf((long) listingContext.getSkipCount()); maxItems = BigInteger.valueOf((long) listingContext.getMaxItems()); tmpStatement += getSorting(listingContext.getSortProperty(), listingContext.isSortAscending()); } // Log.d(TAG, maxItems + " " + skipCount + " " + tmpStatement); // fetch the data ObjectList resultList = discoveryService.query(session.getRepositoryInfo().getIdentifier(), tmpStatement, false, ctxt.isIncludeAllowableActions(), ctxt.getIncludeRelationships(), ctxt.getRenditionFilterString(), maxItems, skipCount, null); // convert query results List<Node> page = new ArrayList<Node>(); if (resultList.getObjects() != null) { for (ObjectData objectData : resultList.getObjects()) { if (objectData == null) { continue; } page.add(convertNode(objectFactory.convertObject(objectData, ctxt), false)); } // Log.d(TAG, "Query Result :" + page.size()); return new PagingResultImpl<Node>(page, resultList.hasMoreItems(), (resultList.getNumItems() == null) ? -1 : resultList.getNumItems().intValue()); } else { return new PagingResultImpl<Node>(page, false, -1); } } catch (Exception e) { convertException(e); } return null; } // ///////////////////////////////////////////////////////////////////////////////// // Internal // ///////////////////////////////////////////////////////////////////////////////// private static final String QUERY_DOCUMENT_TITLED = "SELECT d.* FROM cmis:document as d JOIN cm:titled as t ON d.cmis:objectId = t.cmis:objectId WHERE "; private static final String QUERY_DOCUMENT = "SELECT * FROM cmis:document WHERE "; private static final String QUERY_FOLDER_TITLED = "SELECT d.* FROM cmis:folder as d JOIN cm:titled as t ON d.cmis:objectId = t.cmis:objectId WHERE "; private static final String QUERY_FOLDER = "SELECT * FROM cmis:folder WHERE "; private static final String QUERY_DEFAULT = "SELECT * FROM %s WHERE "; private static final String PARAM_NODEREF = "{noderef}"; private static final String QUERY_INFOLDER = " IN_FOLDER('" + PARAM_NODEREF + "')"; private static final String QUERY_DESCENDANTS = " IN_TREE('" + PARAM_NODEREF + "')"; private static final String PARAM_NAME = "cmis:name"; private static final String PARAM_CREATED_AT = " cmis:creationDate "; private static final String PARAM_MODIFIED_AT = " cmis:lastModificationDate "; private static final String PARAM_TITLE = " t.cm:title "; private static final String PARAM_DESCRIPTION = " t.cm:description "; private static final String OPERTATOR_OR = " OR "; private static final String OPERTATOR_AND = " AND "; /** * Internal utility method to create a cmis query based on keywords. * * @param typeName * @param keywords : List of keywords to search * @param fulltext : Define if the search must include content inside * document. (fulltext search) * @param isExact : Define if the keyword must match exactly with keywords. * @return Cmis query based on parameters * @since 1.1 the query has been simplified. it doesn't cover anymore * cm:titled */ private static String createQuery(String query, String typeName, boolean fulltext, boolean isExact, Folder f, boolean descendants, ListingContext listingContext) { List<String> keywords = Arrays.asList(TextUtils.split(query.trim(), "\\s+")); // Check if we use aspect. In this case we need a JOIN boolean hasAspect = false; if (listingContext != null && listingContext.getSortProperty() != null && (SORT_PROPERTY_TITLE.equals(listingContext.getSortProperty()) || SORT_PROPERTY_DESCRIPTION .equals(listingContext.getSortProperty()))) { hasAspect = true; } // Prepare the query String startStatement = QUERY_DOCUMENT; if (KeywordSearchOptions.TYPENAME_DOCUMENT.equals(typeName)) { startStatement = QUERY_DOCUMENT; if (hasAspect) { startStatement = QUERY_DOCUMENT_TITLED; } } else if (KeywordSearchOptions.TYPENAME_FOLDER.equals(typeName)) { startStatement = QUERY_FOLDER; if (hasAspect) { startStatement = QUERY_FOLDER_TITLED; } } else { startStatement = String.format(QUERY_DEFAULT, typeName); } StringBuilder sb = new StringBuilder(startStatement); // First IN_FOLDER or IN_DESCENDANTS if (f != null) { if (descendants) { sb.append(QUERY_DESCENDANTS.replace(PARAM_NODEREF, f.getIdentifier())); } else { sb.append(QUERY_INFOLDER.replace(PARAM_NODEREF, f.getIdentifier())); } sb.append(OPERTATOR_AND); sb.append("("); } // Create keywords String keywordsValue = ""; for (String word : keywords) { if (word != null && !word.isEmpty()) { keywordsValue += " " + word; } } keywordsValue = keywordsValue.trim(); // Request name with each keyword. if (keywordsValue != null && keywordsValue.length() > 0) { if (isExact) { sb.append(PARAM_NAME + "= '" + keywordsValue + "'" + OPERTATOR_OR + " UPPER(" + PARAM_NAME + ") = '" + keywordsValue.toUpperCase() + "'" + OPERTATOR_OR + " CONTAINS('" + PARAM_NAME + ":\\\'" + keywordsValue + "\\\'')"); } else { sb.append("CONTAINS('~" + PARAM_NAME + ":\\\'" + keywordsValue + "\\\'')"); } if (fulltext) { sb.append(OPERTATOR_OR); sb.append("contains ('" + keywordsValue + "')"); } } if (f != null) { sb.append(")"); } // Log.d(TAG, "Query :" + sb.toString()); return sb.toString(); } @SuppressWarnings({ "serial" }) private static Map<String, String> sortingMap = new HashMap<String, String>() { { put(SORT_PROPERTY_NAME, PARAM_NAME); put(SORT_PROPERTY_TITLE, PARAM_TITLE); put(SORT_PROPERTY_DESCRIPTION, PARAM_DESCRIPTION); put(SORT_PROPERTY_CREATED_AT, PARAM_CREATED_AT); put(SORT_PROPERTY_MODIFIED_AT, PARAM_MODIFIED_AT); } }; private String getSorting(String sortingKey, boolean modifier) { String s; if (sortingMap.containsKey(sortingKey)) { s = sortingMap.get(sortingKey); } else { return ""; } if (modifier) { s += " ASC"; } else { s += " DESC"; } return " ORDER BY " + s; } // //////////////////////////////////////////////////// // Save State - serialization / deserialization // //////////////////////////////////////////////////// public static final Parcelable.Creator<SearchServiceImpl> CREATOR = new Parcelable.Creator<SearchServiceImpl>() { public SearchServiceImpl createFromParcel(Parcel in) { return new SearchServiceImpl(in); } public SearchServiceImpl[] newArray(int size) { return new SearchServiceImpl[size]; } }; public SearchServiceImpl(Parcel o) { super((AlfrescoSession) o.readParcelable(AlfrescoSession.class.getClassLoader())); } }
37.620499
158
0.584935
0e66c9dc8ee2fbb5b4cacb3e08fc23d39ca8defe
687
package se.kth.iv1350.integration; /** * Thrown when trying to fetch an item * from a database with a none existing ID */ public class NoMatchingIDException extends Exception { /** * Creates an instance with a message specifying * what item ID wasn't able to be found in the * database * @param itemID Item ID with no match */ String itemID; public NoMatchingIDException(String itemID){ super(itemID + " could not be found in the database."); this.itemID = itemID; } /** * * @return Returns the item ID causing the * exception */ public String getNotFoundItemID() { return itemID; } }
23.689655
63
0.631732
92c6d92ed7b0fe2828b1ff1dc4736ba3d85fc4a1
657
package com.moment.logconverge.img; import android.content.Context; import android.widget.ImageView; /** * Created by moment on 2018/1/30. */ public class ImageCache { private static Context mContext; private static String imageUrl; private static final ImageCache INSTANCE = new ImageCache(); public static ImageCache with(Context context) { mContext = context; return INSTANCE; } public static ImageCache load(String url) { imageUrl = url; return INSTANCE; } public static void into(ImageView imageView) { if (imageUrl != null && !"".equals(imageUrl)) { } } }
19.909091
64
0.652968
d5011290292e21b3f9f241ca98160cd610d33459
1,386
/* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. */ package com.amazonaws.services.lambda.runtime.tests.annotations; import com.amazonaws.services.lambda.runtime.tests.EventArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; import java.lang.annotation.*; /** * This annotation must be used in conjunction with {@link org.junit.jupiter.params.ParameterizedTest}.<br/> * It enables to inject an event (loaded from a json file) of the desired type into the current test.<br/> * Example:<br/> * <pre> * &#64;ParameterizedTest * &#64;Event(value = "sqs_event.json", type = SQSEvent.class) * public void testInjectEvent(SQSEvent event) { * assertThat(event).isNotNull(); * assertThat(event.getRecords()).hasSize(1); * } * </pre> */ @Documented @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @ArgumentsSource(EventArgumentsProvider.class) public @interface Event { /** * Path and file name of the json event * @return the file name (including the path) */ String value(); /** * Type of the event (for example, one of the <a href="https://github.com/aws/aws-lambda-java-libs/tree/master/aws-lambda-java-events">aws-lambda-java-events</a>), or your own type * @return the type of the event */ Class<?> type() default Void.class; }
34.65
184
0.698413
e0dec749c26529c47bb438b20bb4f4df0874b291
2,676
/***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * * ------------------------------------------------------------------------- * * This software is published under the terms of the Apache Software License * * version 1.1, a copy of which has been included with this distribution in * * the LICENSE file. * *****************************************************************************/ package org.apache.cocoon.components.xpath; import org.apache.avalon.framework.thread.ThreadSafe; import org.apache.avalon.framework.logger.AbstractLoggable; import org.apache.xpath.XPathAPI; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * This class defines the implementation of the {@link XPathProcessor} * component. * * To configure it, add the following lines in the * <file>cocoon.xconf</file> file: * * <pre> * &lt;xslt-processor class="org.apache.cocoon.components.xpath.XPathProcessorImpl"&gt; * &lt;/xslt-processor&gt; * </pre> * * @author <a href="mailto:[email protected]">Davanum Srinivas</a> * @version CVS $Revision: 1.3 $ $Date: 2002/01/08 08:00:27 $ $Author: cziegeler $ */ public class XPathProcessorImpl extends AbstractLoggable implements XPathProcessor, ThreadSafe { /** * Use an XPath string to select a single node. XPath namespace * prefixes are resolved from the context node, which may not * be what you want (see the next method). * * @param contextNode The node to start searching from. * @param str A valid XPath string. * @return The first node found that matches the XPath, or null. */ public Node selectSingleNode(Node contextNode, String str) { try { return XPathAPI.selectSingleNode(contextNode, str); } catch (javax.xml.transform.TransformerException e){ return null; } } /** * Use an XPath string to select a nodelist. * XPath namespace prefixes are resolved from the contextNode. * * @param contextNode The node to start searching from. * @param str A valid XPath string. * @return A NodeList, should never be null. */ public NodeList selectNodeList(Node contextNode, String str) { try { return XPathAPI.selectNodeList(contextNode, str); } catch (javax.xml.transform.TransformerException e){ return new NodeList(){ public Node item(int index) { return null;} public int getLength(){return 0;} }; } } }
36.657534
87
0.592676
2a67507209af22aa2d97e1f6bc99c6e54f05fd39
10,227
/******************************************************************************* * Copyright 2016 Jalian Systems Pvt. 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 net.sourceforge.marathon.javaagent.components; import java.awt.BorderLayout; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.lang.reflect.InvocationTargetException; import java.net.URL; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.html.HTMLDocument; import net.sourceforge.marathon.javaagent.IJavaAgent; import net.sourceforge.marathon.javaagent.IJavaElement; import net.sourceforge.marathon.javaagent.JavaAgent; import net.sourceforge.marathon.javaagent.JavaElementFactory; import net.sourceforge.marathon.javaagent.Wait; import net.sourceforge.marathon.javaagent.components.JavaElementTest; import net.sourceforge.marathon.testhelpers.ComponentUtils; import org.testng.AssertJUnit; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.sun.swingset3.demos.editorpane.EditorPaneDemo; @Test public class JEditorPaneJavaElementTest extends JavaElementTest { protected JFrame frame; private IJavaAgent driver; private IJavaElement editor; @BeforeMethod public void showDialog() throws Throwable { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { frame = new JFrame(JEditorPaneJavaElementTest.class.getSimpleName()); frame.setName("frame-" + JEditorPaneJavaElementTest.class.getSimpleName()); EditorPaneDemo editorPane = new EditorPaneDemo(); editorPane.setName("EditorPane"); frame.getContentPane().add(editorPane, BorderLayout.CENTER); frame.setSize(640, 600); frame.setAlwaysOnTop(true); frame.setVisible(true); } }); driver = new JavaAgent(); JavaElementFactory.add(JEditorPane.class, JEditorPaneJavaElement.class); editor = driver.findElementByTagName("editor-pane"); new Wait("Waiting for document to load") { @Override public boolean until() { try { return getFileName() != null; } catch (Throwable t) { } return false; } }; Thread.sleep(500); } @AfterMethod public void disposeDriver() throws Throwable { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { frame.setVisible(false); frame.dispose(); } }); JavaElementFactory.reset(); } @Test(enabled = false) public void clickOnText() throws Throwable { AssertJUnit.assertEquals("index.html", getFileName()); new Wait("Waiting for element to be available") { @Override public boolean until() { try { marathon_select_by_properties(editor, "text=Of a Louse", false); return true; } catch (Throwable t) { } return false; } }; IJavaElement prop = marathon_select_by_properties(editor, "text=Of a Louse", false); prop.click(); new Wait("Waiting for document to load") { @Override public boolean until() { try { return getFileName().equals("bug.html"); } catch (Throwable t) { } return false; } }; AssertJUnit.assertEquals("bug.html", getFileName()); } public void clickOnLink() throws Throwable { AssertJUnit.assertEquals("index.html", getFileName()); new Wait("Waiting for element to be available") { @Override public boolean until() { try { marathon_select_by_properties(editor, "link=bug.html", false); return true; } catch (Throwable t) { } return false; } }; IJavaElement prop = marathon_select_by_properties(editor, "link=bug.html", false); prop.click(); new Wait("Waiting for document to load") { @Override public boolean until() { try { return getFileName().equals("bug.html"); } catch (Throwable t) { } return false; } }; AssertJUnit.assertEquals("bug.html", getFileName()); } public void clickOnLinkWithIndex() throws Throwable { final String htmlText = "<a href='http://localhost' id='#first'><img src='none.gif'></a>" + "Some stuff here" + "<a href='http://localhost' id='#second'><img src='none.gif'></a>"; SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { JEditorPane editor = (JEditorPane) ComponentUtils.findComponent(JEditorPane.class, frame); Document d = editor.getEditorKit().createDefaultDocument(); editor.setDocument(d); editor.setText(htmlText); } }); new Wait("Waiting for element to be available") { @Override public boolean until() { try { marathon_select_by_properties(editor, "link=http://localhost(1)", false); return true; } catch (Throwable t) { } return false; } }; IJavaElement prop = marathon_select_by_properties(editor, "link=http://localhost(1)", false); AssertJUnit.assertEquals("#second", prop.getAttribute("id")); } public void clickOnTextWithIndex() throws Throwable { final String htmlText = "<a href='http://localhost' id='#first'>Goto Google</a>" + "Some stuff here" + "<a href='http://localhost' id='#second'>Goto Google</a>"; SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { JEditorPane editor = (JEditorPane) ComponentUtils.findComponent(JEditorPane.class, frame); Document d = editor.getEditorKit().createDefaultDocument(); editor.setDocument(d); editor.setText(htmlText); } }); new Wait("Waiting for element to be available") { @Override public boolean until() { try { marathon_select_by_properties(editor, "text=Goto Google(1)", false); return true; } catch (Throwable t) { } return false; } }; IJavaElement prop = marathon_select_by_properties(editor, "text=Goto Google(1)", false); AssertJUnit.assertEquals("#second", prop.getAttribute("id")); } protected String getFileName() throws InterruptedException, InvocationTargetException { final String[] values = new String[] { null }; SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { JEditorPane editor = (JEditorPane) ComponentUtils.findComponent(JEditorPane.class, frame); HTMLDocument document = (HTMLDocument) editor.getDocument(); URL base = document.getBase(); if (base != null) { String path = base.toString(); path = path.substring(path.lastIndexOf('/') + 1); values[0] = path; } } }); String path = values[0]; return path; } public void clickByPos() throws Throwable { AssertJUnit.assertEquals("index.html", getFileName()); final Point expected = new Point(); final Point actual = new Point(); final JEditorPane editorPane = (JEditorPane) ComponentUtils.findComponent(JEditorPane.class, frame); editorPane.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { actual.x = e.getPoint().x; actual.y = e.getPoint().y; } }); new Wait("Waiting for element to be available") { @Override public boolean until() { try { marathon_select_by_properties(editor, "353", false); return true; } catch (Throwable t) { } return false; } }; SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { try { Rectangle bounds = editorPane.modelToView(353); Point location = new Point(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2); expected.x = location.x; expected.y = location.y; } catch (BadLocationException e) { throw new RuntimeException("Failed to locate", e); } } }); IJavaElement prop = marathon_select_by_properties(editor, "353", false); prop.click(); AssertJUnit.assertEquals(expected.x, actual.x); AssertJUnit.assertEquals(expected.y, actual.y); } }
40.422925
117
0.576122
8d5ded2d380e45d0cdffc33b5abd22a4d059fc24
1,199
package com.codekeyz.nalosms; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Toast; import com.nalo.nalosms.NaloSMS; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); NaloSMS nalosms = new NaloSMS.SMSBuilder() .withAuthCred("your-username", "!@msweet") .setType(NaloSMS.Type.FLASH_MESSAGE_ISO_88559_1) .setMessage("Hey Geek, am Precious Keyz") .setSource("Tampico") .setDestination("+23324XX61XXX", "023XXXAAA", "0554XXX83X") .withDeliveryReport(true) .build(); nalosms.send(new NaloSMS.Callback() { @Override public void onResult(String result) { Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show(); } @Override public void onError(Throwable error) { Log.d("Error", "", error); } }); } }
29.975
84
0.604671
6b65d74ed2a12880d272f55d95537b2a943d16aa
421
package com.onesait.edge.engine.zigbee.util; public class PermitJoin { private int data = 0; public PermitJoin( int data){ this.data=data; } public int getData() { return data; } public String getPermitJoining(){ int result = this.data & 0x3; switch (result) { case 0: return "NOT ACCEPT"; case 1: return "ACCEPT"; default: return "UNKNOWN"; } } }
15.035714
45
0.5962
8d4c0fb76cfe3c3696d6adb3c7ab17dd0507d92b
1,986
package ar.com.javacuriosities.sessions; import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { processRequest(request, response); } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { // Recuperamos el nombre de usuario String user = request.getParameter("txtUser"); String jwt = createSignedJWT(user, "manager"); Cookie cookie = new Cookie("JWT-SESSION-ID", jwt); response.addCookie(cookie); out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Login</title>"); out.println("</head>"); out.println("<body>"); out.println("Bienvenido " + user); out.println("<form action='WelcomeServlet'>"); out.println("<input type='submit' value='JWT'>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } } private String createSignedJWT(String user, String role) { return JWT.create().withClaim("user", user).withClaim("role", role).sign(Algorithm.HMAC256("secret")); } }
35.464286
113
0.632427
94bfcaf0b807ff1bda5629e522f6db2aa846217c
457
package optional.util; import java.util.Optional; /** * @author zhangyupeng * @date 2018/8/25 */ public class Person { private Car car; private int age; public Optional<Car> getCar() { return Optional.ofNullable(car); } public int getAge() { return age; } public Person(Car car) { this.car = car; } public Person(Car car, int age) { this.car = car; this.age = age; } }
15.758621
40
0.564551
e4b4e249dfe01b14730e4d4c83210e6ddd3953b9
1,813
package org.opendaylight.controller.md.sal.dom.xsql.jdbc; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.Properties; import java.util.logging.Logger; public class JDBCDriver implements Driver { public static JDBCDriver drv = new JDBCDriver(); public JDBCDriver() { try { DriverManager.registerDriver(this); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public boolean acceptsURL(String arg0) throws SQLException { return true; } @Override public Connection connect(String url, Properties arg1) throws SQLException { System.err.println("JDBC Connection"); try { if (url.equals("svr")) { return new JDBCConnection(true); } else { return new JDBCConnection(url); } } catch (Exception err) { err.printStackTrace(); } return null; } @Override public int getMajorVersion() { return 1; } @Override public int getMinorVersion() { return 0; } @Override public DriverPropertyInfo[] getPropertyInfo(String arg0, Properties arg1) throws SQLException { DriverPropertyInfo i = new DriverPropertyInfo("NQL", "NQL"); return new DriverPropertyInfo[] {i}; } @Override public boolean jdbcCompliant() { return false; } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { // TODO Auto-generated method stub return null; } }
24.5
80
0.627689
1503976b2ccc98df53146734ff02904f74b52138
735
package com.google.cloud.storage; import com.google.common.base.*; import com.google.api.services.storage.model.*; static final class StorageImpl$7 implements Function<Bucket, com.google.cloud.storage.Bucket> { final /* synthetic */ StorageOptions val$serviceOptions; StorageImpl$7(final StorageOptions val$serviceOptions) { this.val$serviceOptions = val$serviceOptions; super(); } @Override public com.google.cloud.storage.Bucket apply(final Bucket a1) { return com.google.cloud.storage.Bucket.fromPb((Storage)this.val$serviceOptions.getService(), a1); } @Override public /* bridge */ Object apply(final Object o) { return this.apply((Bucket)o); } }
31.956522
105
0.692517
2a27a6061da2049e576a857e6fd222b032967984
7,523
package sbt_inc; import com.typesafe.zinc.Compiler; import com.typesafe.zinc.*; import org.apache.maven.plugin.logging.Log; import org.apache.maven.toolchain.Toolchain; import scala.Option; import scala_maven_executions.MainHelper; import util.JavaLocator; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; public class SbtIncrementalCompiler { public static final String SBT_GROUP_ID = "com.typesafe.sbt"; public static final String COMPILER_INTEGRATION_ARTIFACT_ID = "incremental-compiler"; public static final String COMPILER_INTERFACE_ARTIFACT_ID = "compiler-interface"; public static final String COMPILER_INTERFACE_CLASSIFIER = "sources"; public static final String XSBTI_ARTIFACT_ID = "sbt-interface"; private static final String ANALYSIS_MAP_ARG_SEPARATOR = ","; private static final String ANALYSIS_MAP_PAIR_SEPARATOR = File.pathSeparator; private Log log; private ZincClient zinc; private boolean useServer = false; private File compilerJar; private File libraryJar; private List<File> extraJars; private List<String> extraArgs; private xsbti.Logger logger; private Compiler compiler; public SbtIncrementalCompiler(boolean useZincServer, int zincPort, File libraryJar, File compilerJar, List<File> extraJars, File xsbtiJar, File interfaceJar, Log l, List<String> args) throws Exception { this.log = l; if (useZincServer) { this.zinc = new ZincClient(zincPort); if (zinc.serverAvailable()) { l.info("Using zinc server for incremental compilation"); this.useServer = true; this.compilerJar = compilerJar; this.libraryJar = libraryJar; this.extraJars = extraJars; this.extraArgs = args; } else { l.warn("Zinc server is not available at port " + zincPort + " - reverting to normal incremental compile"); this.useServer = false; } } if (!useServer) { l.info("Using incremental compilation"); if (args.size() > 0) l.warn("extra args for zinc are ignored in non-server mode"); this.logger = new SbtLogger(l); Setup setup = Setup.create(compilerJar, libraryJar, extraJars, xsbtiJar, interfaceJar, null, false); if (l.isDebugEnabled()) Setup.debug(setup, logger); this.compiler = Compiler.create(setup, logger); } } private IncOptions defaultOptions() { sbt.inc.IncOptions defaultSbtOptions = sbt.inc.IncOptions.Default(); return new IncOptions( defaultSbtOptions.transitiveStep(), defaultSbtOptions.recompileAllFraction(), defaultSbtOptions.relationsDebug(), defaultSbtOptions.apiDebug(), defaultSbtOptions.apiDiffContextSize(), defaultSbtOptions.apiDumpDirectory(), false, Option.<File>empty(), defaultSbtOptions.recompileOnMacroDef(), defaultSbtOptions.nameHashing()); } public void compile(File baseDir, List<String> classpathElements, List<File> sources, File classesDirectory, List<String> scalacOptions, List<String> javacOptions, File cacheFile, Map<File, File> cacheMap, String compileOrder, Toolchain toolchain) throws Exception { if (useServer) { zincCompile(baseDir, classpathElements, sources, classesDirectory, scalacOptions, javacOptions, cacheFile, cacheMap, compileOrder, toolchain); } else { if (log.isDebugEnabled()) log.debug("Incremental compiler = " + compiler + " [" + Integer.toHexString(compiler.hashCode()) + "]"); List<File> classpath = pathsToFiles(classpathElements); Inputs inputs = Inputs.create(classpath, sources, classesDirectory, scalacOptions, javacOptions, cacheFile, cacheMap, compileOrder, defaultOptions(), true); if (log.isDebugEnabled()) Inputs.debug(inputs, logger); compiler.compile(inputs, logger); } } private void zincCompile(File baseDir, List<String> classpathElements, List<File> sources, File classesDirectory, List<String> scalacOptions, List<String> javacOptions, File cacheFile, Map<File, File> cacheMap, String compileOrder, Toolchain toolchain) throws Exception { List<String> arguments = new ArrayList<String>(extraArgs); arguments.add("-log-level"); arguments.add(logLevelToString(log)); arguments.add("-scala-compiler"); arguments.add(compilerJar.getAbsolutePath()); arguments.add("-scala-library"); arguments.add(libraryJar.getAbsolutePath()); arguments.add("-scala-extra"); List<String> extraPaths = new ArrayList<String>(); for (File extraJar : extraJars) { extraPaths.add(extraJar.getAbsolutePath()); } arguments.add(MainHelper.toMultiPath(extraPaths)); if (!classpathElements.isEmpty()) { arguments.add("-classpath"); arguments.add(MainHelper.toMultiPath(classpathElements)); } arguments.add("-d"); arguments.add(classesDirectory.getAbsolutePath()); for (String scalacOption : scalacOptions) { arguments.add("-S" + scalacOption); } String javaHome = JavaLocator.findHomeFromToolchain(toolchain); if (javaHome != null) { log.info("Toolchain in scala-maven-plugin: " + javaHome); arguments.add("-java-home"); arguments.add(javaHome); } for (String javacOption : javacOptions) { arguments.add("-C" + javacOption); } arguments.add("-compile-order"); arguments.add(compileOrder); arguments.add("-analysis-cache"); arguments.add(cacheFile.getAbsolutePath()); arguments.add("-analysis-map"); arguments.add(cacheMapToString(cacheMap)); for (File source : sources) { arguments.add(source.getAbsolutePath()); } int exitCode = zinc.run(arguments, baseDir, System.out, System.err); if (exitCode != 0) { xsbti.Problem[] problems = null; throw new sbt.compiler.CompileFailed(arguments.toArray(new String[arguments.size()]), "Compile failed via zinc server", problems); } } private List<File> pathsToFiles(List<String> paths) { List<File> files = new ArrayList<File>(paths.size()); for (String path : paths) { files.add(new File(path)); } return files; } private String logLevelToString(Log l) { if (l.isDebugEnabled()) return "debug"; else if (l.isInfoEnabled()) return "info"; else if (l.isWarnEnabled()) return "warn"; else if (l.isErrorEnabled()) return "error"; else return "info"; } private String cacheMapToString(Map<File, File> cacheMap) throws Exception { String analysisMap = ""; boolean addArgSeparator = false; for (Map.Entry<File, File> entry : cacheMap.entrySet()) { if (addArgSeparator) analysisMap += ANALYSIS_MAP_ARG_SEPARATOR; analysisMap += entry.getKey().getAbsolutePath(); analysisMap += ANALYSIS_MAP_PAIR_SEPARATOR; analysisMap += entry.getValue().getAbsolutePath(); addArgSeparator = true; } return analysisMap; } }
42.027933
275
0.646551
a1e4cb21380a8e6c8121661b7be5cfb7e8954f64
288
package AsposeCellsExamples.SmartMarkers; public class Person { private String m_Name; private int m_Age; public Person(String name, int age) { this.m_Name = name; this.m_Age = age; } public String getName() { return m_Name; } public int getAge() { return m_Age; } }
13.714286
41
0.694444
8a09b27de6ca5116dfe71f0027e468f638c02b74
653
package com.tome.main.security.validation; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import com.baeldung.web.dto.UserDto; import com.tome.main.security.PlayerDTO; public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> { @Override public void initialize(final PasswordMatches constraintAnnotation) { // } @Override public boolean isValid(final Object obj, final ConstraintValidatorContext context) { final PlayerDTO user = (PlayerDTO) obj; return user.getPassword().equals(user.getMatchingPassword()); } }
28.391304
95
0.765697
99ac04c0e7e7d8189a1b1b29cc82f594b7f09349
5,966
package joshie.harvest.cooking.recipe; import joshie.harvest.api.cooking.Ingredient; import joshie.harvest.api.cooking.IngredientStack; import joshie.harvest.api.cooking.Recipe; import joshie.harvest.api.cooking.Utensil; import joshie.harvest.cooking.CookingAPI; import joshie.harvest.cooking.HFCooking; import joshie.harvest.cooking.item.ItemMeal.Meal; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import static joshie.harvest.core.lib.HFModInfo.MODID; public class RecipeHelper { private static Recipe addRecipe(String mealname, Utensil utensil, float hungerModifier, float modifier, int eatTimer, Ingredient... ingredients) { //Time to calculate hunger and saturation from the base ingredients int hunger = 0; float saturation = 0F; for (Ingredient ingredient: ingredients) { int internalHunger = ingredient.getHunger(); if (internalHunger == 0) { float internalSaturation = 0F; for (Ingredient test : ingredient.getEquivalents()) { if (internalHunger == 0 || (test.getSellValue() != 0) && test.getHunger() < internalHunger) { internalHunger = test.getHunger(); internalSaturation = test.getSaturation(); } } hunger += internalHunger; saturation += internalSaturation; } else { hunger += ingredient.getHunger(); saturation += ingredient.getSaturation(); } } hunger = (int)Math.min(20, Math.max(1, hunger * hungerModifier)); saturation = Math.min(1F, Math.max(0.2F, saturation * modifier)); //Add the recipe ResourceLocation resource = new ResourceLocation(MODID, mealname); Recipe recipe = new RecipeHF(resource, utensil, hunger, saturation, toIngredientStacks(ingredients)).setEatTimer(eatTimer); //TODO: Remove in 0.7+ recipe.setRegistryName(resource); //TODO: Remove in 0.7+ CookingAPI.REGISTRY.register(recipe); return recipe; } private static Recipe addRecipe(String name, ItemStack result, Utensil utensil, Ingredient... ingredients) { ResourceLocation resource = new ResourceLocation(MODID, name); Recipe recipe = new RecipeVanilla(resource, result, utensil, toIngredientStacks(ingredients)); //TODO: Remove in 0.7+ recipe.setRegistryName(resource); //TODO: Remove in 0.7+ CookingAPI.REGISTRY.register(recipe); return recipe; } public static IngredientStack[] toIngredientStacks(Ingredient[] ingredients) { IngredientStack[] stacks = new IngredientStack[ingredients.length]; for (int i = 0; i < ingredients.length; i++) { stacks[i] = new IngredientStack(ingredients[i], 1); } return stacks; } private static Recipe addRecipe(String mealname, Utensil utensil, float hungerModifier, float modifier, boolean drink, Ingredient... ingredients) { int timer = drink ? 24: (int) Math.max(24, Math.ceil(24 * modifier)); Recipe ret = addRecipe(mealname, utensil, hungerModifier, modifier, timer, ingredients); if(drink) ret.setIsDrink(); return ret; } public static Recipe addFryingPanRecipe(Meal meal, float hungerModifier, float modifier, Ingredient... ingredients) { return addRecipe(meal.getName(), HFCooking.FRYING_PAN, hungerModifier, modifier, false, ingredients); } @SuppressWarnings("unused") public static void addFryingPanRecipe(String mealname, ItemStack result, Ingredient... ingredients) { addRecipe(mealname, result, HFCooking.FRYING_PAN, ingredients); } public static Recipe addMixerRecipe(Meal meal, boolean isDrink, float hungerModifier, float modifier, Ingredient... ingredients) { return addRecipe(meal.getName(), HFCooking.MIXER, hungerModifier, modifier, isDrink, ingredients); } public static Recipe addMixerRecipe(Meal meal, float hungerModifier, float modifier, Ingredient... ingredients) { return addRecipe(meal.getName(), HFCooking.MIXER, hungerModifier, modifier, true, ingredients); } public static Recipe addMixerRecipe(String mealname, ItemStack result, Ingredient... ingredients) { return addRecipe(mealname, result, HFCooking.MIXER, ingredients); } public static Recipe addNoUtensilRecipe(Meal meal, float hungerModifier, float modifier, Ingredient... ingredients) { return addRecipe(meal.getName(), HFCooking.COUNTER, hungerModifier, modifier, false, ingredients); } public static Recipe addNoUtensilRecipe(String mealname, ItemStack result, Ingredient... ingredients) { return addRecipe(mealname, result, HFCooking.COUNTER, ingredients); } public static Recipe addPotRecipe(Meal meal, boolean isDrink, float hungerModifier, float modifier, Ingredient... ingredients) { return addRecipe(meal.getName(), HFCooking.POT, hungerModifier, modifier, isDrink, ingredients); } public static Recipe addPotRecipe(Meal meal, float hungerModifier, float modifier, Ingredient... ingredients) { return addRecipe(meal.getName(), HFCooking.POT, hungerModifier, modifier, false, ingredients); } public static Recipe addPotRecipe(String mealname, ItemStack result, Ingredient... ingredients) { return addRecipe(mealname, result, HFCooking.POT, ingredients); } public static Recipe addOvenRecipe(Meal meal, float hungerModifier, float modifier, Ingredient... ingredients) { return addRecipe(meal.getName(), HFCooking.OVEN, hungerModifier, modifier, false, ingredients); } public static Recipe addOvenRecipe(String mealname, ItemStack result, Ingredient... ingredients) { return addRecipe(mealname, result, HFCooking.OVEN, ingredients); } }
46.976378
151
0.689071
ea8f2d66707cf8edc5ce8a9eb03449370d885c03
3,155
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package view; import view.componets.Dashboard; import view.componets.Theme; import java.awt.Dimension; import javax.swing.JPanel; /** * * @author johnrojas */ public class GUIStructure extends javax.swing.JFrame { PageAbstract current; /** * Creates new form GUIStructure */ public GUIStructure() { initComponents(); } public void start(){ setBackground(Theme.Color.DARK); setVisible(true); setLocationRelativeTo(null); } public Dashboard getNav() { return nav; } public JPanel getView() { return view; } public PageAbstract getCurrent() { return current; } public void setCurrent(PageAbstract current) { this.current = current; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { nav = new view.componets.Dashboard(); view = new javax.swing.JPanel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(Theme.Color.OLIVE); setBounds(new java.awt.Rectangle(0, 0, 0, 0)); nav.setBackground(Theme.Color.DARK); view.setBackground(Theme.Color.BG); view.setPreferredSize(new Dimension(PageAbstract.PAGE_WIDTH,PageAbstract.PAGE_HEIGTH)); view.setLayout(new java.awt.CardLayout()); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(nav, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE) .addComponent(view, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(view, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(nav, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private view.componets.Dashboard nav; private javax.swing.JPanel view; // End of variables declaration//GEN-END:variables }
34.293478
152
0.683043
30d6a41c110feed837a1369f6cbdeb275563cae5
3,364
package org.jtwig.spring; import com.google.common.base.Function; import org.jtwig.addons.Addon; import org.jtwig.addons.tag.TagAddon; import org.jtwig.functions.repository.api.FunctionRepository; import org.jtwig.parser.config.ParserConfiguration; import org.jtwig.parser.config.TagSymbols; import org.jtwig.resource.JtwigResource; import org.junit.Before; import org.junit.Test; import javax.annotation.Nullable; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class XmlConfigurationTest { private XmlConfiguration underTest; private FunctionRepository functionRepository; @Before public void setUp() throws Exception { functionRepository = mock(FunctionRepository.class); underTest = new XmlConfiguration(functionRepository); } @Test public void setStrictModeShouldSetTheRenderStrictMode() throws Exception { underTest.setRenderStrictMode(true); assertThat(underTest.render().strictMode(), equalTo(true)); } @Test public void setJsonMapperShouldSetTheRenderJsonMapper() throws Exception { Function<Object, String> jsonMapper = new Function<Object, String>() { @Nullable @Override public String apply(@Nullable Object input) { return null; } }; underTest.setJsonMapper(jsonMapper); assertThat(underTest.render().jsonConfiguration().jsonMapper(), equalTo(jsonMapper)); } @Test public void setCharsetShouldSetTheRenderCharset() throws Exception { underTest.setCharset("UTF-8"); assertThat(underTest.render().charset().name(), equalTo("UTF-8")); } @Test public void logNonStrictModeShouldSetTheRenderLogNonStrictMode() throws Exception { underTest.setLogNonStrictMode(true); assertThat(underTest.render().logNonStrictMode(), equalTo(true)); } @Test public void setExtraFunctionContainersShouldAddToTheFunctionRepository() throws Exception { Object container = new Object(); underTest.setExtraFunctionContainers(new Object[] {container}); verify(functionRepository).include(eq(container)); } @Test public void setTagSymbols() throws Exception { underTest.setTagSymbols("JAVASCRIPT_COLLISION_FREE"); assertEquals(TagSymbols.JAVASCRIPT_COLLISION_FREE, underTest.parse().symbols()); } @Test public void setExtraSyntaticAddons() throws Exception { Class<? extends Addon> testAddonClass = TestAddon.class; underTest.setExtraSyntaticAddons(new Class[]{ testAddonClass }); assertTrue(underTest.parse().addons().list().contains(testAddonClass)); } public static class TestAddon extends TagAddon { public TestAddon(JtwigResource resource, ParserConfiguration configuration) { super(resource, configuration); } @Override protected Function<String, String> transformation() { return null; } @Override protected String keyword() { return null; } } }
31.439252
95
0.706302
a2d4f442d25f32de152198c2c2c7ba2f259a671d
1,343
package com.badugi.game.logic.model.domain.vo.flash.user; public class TrackRooms { private String rid;// 房间id private String rn;// 房间名称 private double bb;// 大盲 private double sb;// 小盲 private String sp;// 速度 private int cc;// 房间人数 private int st;// 状态(1:坐下,0:旁观,2留座) public TrackRooms() { super(); } public TrackRooms(String rid, String rn, double bb, double sb) { super(); this.rid = rid; this.rn = rn; this.bb = bb; this.sb = sb; } public TrackRooms(String rid, String rn, double bb, double sb, String sp, int cc, int st) { super(); this.rid = rid; this.rn = rn; this.bb = bb; this.sb = sb; this.sp = sp; this.cc = cc; this.st = st; } public String getRid() { return rid; } public void setRid(String rid) { this.rid = rid; } public String getRn() { return rn; } public void setRn(String rn) { this.rn = rn; } public double getBb() { return bb; } public void setBb(double bb) { this.bb = bb; } public double getSb() { return sb; } public void setSb(double sb) { this.sb = sb; } public String getSp() { return sp; } public void setSp(String sp) { this.sp = sp; } public int getCc() { return cc; } public void setCc(int cc) { this.cc = cc; } public int getSt() { return st; } public void setSt(int st) { this.st = st; } }
14.287234
74
0.612063
e4711306de46787dd675b15224779617663256d4
5,020
/** * The MIT License (MIT) * * Copyright (c) 2014 Seamus Minogue * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.theblackchamber.crypto.util; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.UnrecoverableEntryException; import java.security.cert.CertificateException; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import net.theblackchamber.crypto.model.KeyConfig2; import net.theblackchamber.crypto.providers.digest.SHA256DigestProvider; import net.theblackchamber.crypto.providers.digest.SHA256DigestProvider.TYPE; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.bouncycastle.jce.provider.BouncyCastleProvider; import com.google.crypto.tink.CleartextKeysetHandle; import com.google.crypto.tink.JsonKeysetReader; import com.google.crypto.tink.JsonKeysetWriter; import com.google.crypto.tink.KeysetHandle; import com.google.crypto.tink.aead.AeadKeyTemplates; import com.google.crypto.tink.aead.AesGcmKeyManager; import com.google.crypto.tink.config.TinkConfig; import com.google.crypto.tink.subtle.AesGcmJce; /** * Utility used for managing a keystore. Generate keys etc. * * @author sminogue * */ public class KeystoreUtils2 { private static SHA256DigestProvider digest = new SHA256DigestProvider(TYPE.SHA1); /** * Method which will generate a random Secret key and store it securely on disk. * * @param config * Configuration for generation of key. * @throws IOException * @throws GeneralSecurityException */ public static void generateSecretKey(KeyConfig2 config) throws IOException, GeneralSecurityException { if (config == null || config.getKeyStoreFile() == null || StringUtils.isBlank(config.getKeyPass())) { throw new KeyStoreException( "Missing parameters, unable to create keystore."); } TinkConfig.register(); //Create rando key KeysetHandle keysetHandle = KeysetHandle.generateNew( AesGcmKeyManager.aes256GcmTemplate()); //using key-pass from config encrypt the encryption key String dKey = digest.digest(config.getKeyPass()); AesGcmJce aesKey = new AesGcmJce(dKey.substring(0, 32).getBytes()); ByteArrayOutputStream privateOutputStream = new ByteArrayOutputStream(); keysetHandle.write(JsonKeysetWriter.withOutputStream(privateOutputStream), aesKey); //Store the key to disk. byte[] privateBytes = privateOutputStream.toByteArray(); FileUtils.writeByteArrayToFile(config.getKeyStoreFile(), privateBytes); } /** * Method which will load a secret key from disk with the specified entry * name. * * @param keystore * {@link KeyStore} file to read. * @param keyStorePassword * Password used to open the {@link KeyStore} * @return * @throws FileNotFoundException * @throws IOException * @throws GeneralSecurityException */ public static KeysetHandle getSecretKey(KeyConfig2 config) throws IOException, GeneralSecurityException { if (config == null || config.getKeyStoreFile() == null || StringUtils.isBlank(config.getKeyPass())) { throw new KeyStoreException( "Missing parameters, unable to create keystore."); } TinkConfig.register(); //Read and decrypt encrypted key from disk String dKey = digest.digest(config.getKeyPass()); AesGcmJce aesKey = new AesGcmJce(dKey.substring(0, 32).getBytes()); byte[] encryptedBytes = FileUtils.readFileToByteArray(config.getKeyStoreFile()); return KeysetHandle.read(JsonKeysetReader.withBytes(encryptedBytes), aesKey); } }
36.642336
106
0.767131
577918d5a4e3ded8473b93d496bf8e162e15f8f7
808
/* * */ package com.synectiks.process.common.plugins.pipelineprocessor.ast.statements; import com.synectiks.process.common.plugins.pipelineprocessor.EvaluationContext; import com.synectiks.process.common.plugins.pipelineprocessor.ast.expressions.Expression; public class FunctionStatement implements Statement { private final Expression functionExpression; public FunctionStatement(Expression functionExpression) { this.functionExpression = functionExpression; } @Override public Object evaluate(EvaluationContext context) { return functionExpression.evaluate(context); } public Expression getFunctionExpression() { return functionExpression; } @Override public String toString() { return functionExpression.toString(); } }
26.933333
89
0.75495
6e8f5998f0fb1d3e8bae6cd0070777937fa7d79a
1,324
package com.example.qt.dl; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.TextView; import com.example.qt.MainActivity; import com.example.qt.R; public class welcome extends AppCompatActivity { Handler handler=new Handler(); private TextView textview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); textview = findViewById(R.id.textView); try { PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0); textview.setText("V."+packageInfo.versionName); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); textview.setText("V"); } handler.postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(welcome.this, MainActivity.class); startActivity(intent); finish(); } },2000); } }
28.782609
94
0.667674
28d85c623184e8639809c3788bd93ca03ab3119f
32,255
/* * eGov SmartCity eGovernance suite aims to improve the internal efficiency,transparency, * accountability and the service delivery of the government organizations. * * Copyright (C) <2019> eGovernments Foundation * * The updated version of eGov suite of products as by eGovernments Foundation * is available at http://www.egovernments.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/ or * http://www.gnu.org/licenses/gpl.html . * * In addition to the terms of the GPL license to be adhered to in using this * program, the following additional terms are to be complied with: * * 1) All versions of this program, verbatim or modified must carry this * Legal Notice. * Further, all user interfaces, including but not limited to citizen facing interfaces, * Urban Local Bodies interfaces, dashboards, mobile applications, of the program and any * derived works should carry eGovernments Foundation logo on the top right corner. * * For the logo, please refer http://egovernments.org/html/logo/egov_logo.png. * For any further queries on attribution, including queries on brand guidelines, * please contact [email protected] * * 2) Any misrepresentation of the origin of the material is prohibited. It * is required that all modified versions of this material be marked in * reasonable ways as different from the original version. * * 3) This license does not grant any rights to any user of the program * with regards to rights under trademark law for use of the trade names * or trademarks of eGovernments Foundation. * * In case of any queries, you can reach eGovernments Foundation at [email protected]. */ package org.egov.common.entity.edcr; import java.io.Serializable; import java.math.BigDecimal; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; //These are the declarations of the applicant in the plan using PLAN_INFO layer. public class PlanInformation implements Serializable { private static final String NA = "NA"; public static final String SEQ_EDCR_PLANINFO = "SEQ_EDCR_PLANINFO"; private static final long serialVersionUID = 4L; @Id @GeneratedValue(generator = SEQ_EDCR_PLANINFO, strategy = GenerationType.SEQUENCE) private Long id; // Plot area defined in PLAN_INFO layer. Using the same to measure coverage and small plot condition.This is the declared plot area in the plan. private BigDecimal plotArea = BigDecimal.ZERO; // Temporary field used to capture Owner Name private String ownerName; //Temporary field used to auto populate occupancy detail. private String occupancy; //Temporary field used for service type. private String serviceType; //Temporary field used to show amenities used in application. private String amenities; //Save architect who submitted application mentioned in plan info. private String architectInformation; // Applicant Name private String applicantName; // Extracted from Plan info. Whether plot present in CRZ zone. Expecting default value as NO. private Boolean crzZoneArea = true; //Extracted from Plan info. Demolition area to be mentioned in the plan info. private BigDecimal demolitionArea = BigDecimal.ZERO; //Extracted from Plan info. Depth cutting more than 1.5 Meter flag. private transient Boolean depthCutting; //YES/NO/NA.Extracted from Plan info. Is building of type government or aided school. private transient Boolean governmentOrAidedSchool; //YES/NO/NA.Extracted from Plan info. Is plot comes under security zone flag. private transient Boolean securityZone = true; //YES/NO/NA.Extracted from Plan info. Access width to the plot. private transient BigDecimal accessWidth; //Extracted from Plan info. In case of medical occupancy, capture number of beds present in the building. Sanitation details are decided based on number of beds present. private transient BigDecimal noOfBeds; //YES/NO/NA.Extracted from Plan info. NOC received from the side owner. private transient String nocToAbutSideDesc = NA; //YES/NO/NA.Extracted from Plan info. NOC received from the rear owner. private transient String nocToAbutRearDesc = NA; //YES/NO/NA.Extracted from Plan info. Any opening on sides of building. private transient Boolean openingOnSide = false; //YES/NO/NA.Extracted from Plan info. Any opening on rear side of building. private transient Boolean openingOnRear = false; //Extracted from Plan info. Number of seats present in special occupancy private transient Integer noOfSeats = 0; //Extracted from Plan info. Number of mechanical parking declared in the plan private transient Integer noOfMechanicalParking = 0; //YES/NO/NA.Extracted from Plan info.Is plan belongs to single family building. There are few rules relaxed for single family building private transient Boolean singleFamilyBuilding; //Extracted from Plan info. Revenue survey number declared in the plan private String reSurveyNo; //Extracted from Plan info. Revenue ward name declared in the plan private String revenueWard; //Extracted from Plan info. Desam name declared in the plan private String desam; //Extracted from Plan info. Village name declared in the plan private String village; //Extracted from Plan info. Land Use zone. The value should be standard like RESIDENTIAL,COMMERCIAL,INDUSTRIAL,PUBLICANDSEMIPUBLIC etc. private transient String landUseZone; //YES/NO/NA. Extracted from Plan info. Is lease hold land private transient String leaseHoldLand; //Extracted from Plan info. Road width declared in the plan. private BigDecimal roadWidth = BigDecimal.ZERO; //Extracted from Plan info. Road length declared in the plan. private BigDecimal roadLength = BigDecimal.ZERO; //Extracted from Plan info. Type of area. Whether old or new area. private String typeOfArea; //Extracted from Plan info. Average plot depth. private BigDecimal depthOfPlot = BigDecimal.ZERO; //Extracted from Plan info. Average plot width. private BigDecimal widthOfPlot = BigDecimal.ZERO; //YES/NO/NA. Extracted from Plan info. Is building near to monument. private transient String buildingNearMonument = NA; //YES/NO/NA.Extracted from Plan info. Is building near to government building private transient String buildingNearGovtBuilding = NA; //YES/NO/NA.Extracted from Plan info. Building near monument and permitted with NOC private transient String nocNearMonument = NA; //YES/NO/NA.Extracted from Plan info. Building near airport and permitted with airport authority private transient String nocNearAirport = NA; //YES/NO/NA.Extracted from Plan info. Building near defence aerodrome and permitted with NOC private transient String nocNearDefenceAerodomes = NA; //YES/NO/NA.Extracted from Plan info. Permitted with state Environmental impact assessment study report private transient String nocStateEnvImpact = NA; //YES/NO/NA.Extracted from Plan info. Permitted with railway NOC private transient String nocRailways = NA; //YES/NO/NA.Extracted from Plan info. Permitted with noc issued by collector on govt. land private transient String nocCollectorGvtLand = NA; //YES/NO/NA.Extracted from Plan info. Permitted with irrigation report NOC private transient String nocIrrigationDept = NA; //YES/NO/NA.Extracted from Plan info. Permitted with fire department NOC private transient String nocFireDept = NA; //YES/NO/NA.Extracted from Plan info. Building near the river flag private transient String buildingNearToRiver = NA; //YES/NO/NA.Extracted from Plan info. Barrier free access for physically handicapped person provided. private transient String barrierFreeAccessForPhyChlngdPpl = NA; //YES/NO/NA.Extracted from Plan info. Provision for green building and sustainability provided in plan.Rainwater harvesting,solar,segregation of waste etc. private transient String provisionsForGreenBuildingsAndSustainability = NA; //YES/NO/NA.Extracted from Plan info. Fire Protection And Fire Safety Requirements declared in the plan. private transient String fireProtectionAndFireSafetyRequirements = NA; //Extracted from Plan info.Plot number. private String plotNo; //Extracted from Plan info.Khata number. private String khataNo; //Extracted from Plan info.Mauza number. private String mauza; //Extracted from Plan info.District name. private String district; //YES/NO/NA.Extracted from Plan info. Rain water declared in plan. private transient String rwhDeclared = NA; //YES/NO/NA.Extracted from Plan info. Permitted with Public health 7 department NOC private transient String nocPH7Dept = NA; //YES/NO/NA.Extracted from Plan info. Permitted with Tehsildar department NOC private transient String nocTehsildarDept = NA; //YES/NO/NA.Extracted from Plan info. Permitted with Public health department NOC private transient String nocPHDept = NA; //YES/NO/NA.Extracted from Plan info. Permitted with Sub-Office Manimajara department NOC private transient String nocManimajaraDept = NA; //YES/NO/NA.Extracted from Plan info. Permitted with Road 2 department NOC private transient String nocRoad2Dept = NA; //YES/NO/NA.Extracted from Plan info. Permitted with Urban Planning Department (PAC) department NOC private transient String nocPACDept = NA; //YES/NO/NA.Extracted from Plan info. Permitted with Structure department NOC private transient String nocStructureDept = NA; //YES/NO/NA.Extracted from Plan info. Permitted with Electrical department NOC private transient String nocElectricalDept = NA; //YES/NO/NA.Extracted from Plan info. Permitted with Pollution control department NOC private transient String nocPollutionDept = NA; //ROOT_BOUNDARY_TYPE private transient String rootBoundaryType =NA; //ZONE private transient String zone=NA; //Sector Number private transient String sectorNumber =NA; //FLUSHING_UNITS_VOLUME_ABOVE_SEVEN_LITRES private transient String flushingUnitVolume=NA; //PLOT_TYPE private transient String plotType =NA; //TOTAL_USERS private transient String totalNumberOfBuildingUsers=NA; //SOLAR_PHOTOVOLTAIC_KWP private transient String solarPhotovoltaicPanelscapacity =NA; //EXISTING_BUILDING_CONSTRUCTED_WITHOUT_BASEMENT private transient String whetherExistingBuildingConstructedWithoutBasement=NA; //EXISTING_BUILDING_CONSTRUCTED_WITHOUT_BASEMENT private transient String whetherArtificialAndMechanicalVentilatorsProvided=NA; //SOIL_OR_VENTILATING_PIPE_EXTERNAL_WALL private transient String soilOrVentilatingPipe=NA; //WHETHER_STAIRCASE_TOUCHING_LIFT_SHAFT private transient String WhetherAnyStaircaseTouchingLiftShaft =NA; //SOLAR_PHOTOVOLTAIC_KWP private transient String solarPhotovoltaicKWP=NA; //BASEMENT_SERVICES_PRINTING PRESS_A.C. PLANTS_ELECTRICAL PANELS_FILTRATIONPLANTS_LAUNDRYPLANTS_OR_MACHINES_ AUTOMATED/STACK PARKING private transient String basementServicePrintingPressACPlantsElectricalPanelFiltrationplantsLaundryplantsOrMachinesAutomated; //SERVICE_FLOOR_HEIGHT_M= private transient String serviceFloorHeight=NA; //FIRE_SAFETY_PROVISIONS_AS_PER_NBC_DFPF_FSA private transient String fireSafetyProvisionsAsPerNbcDFPF=NA; //EXIT_REQUIREMENT_FIRE_&_LIFE_SAFETY_AS_PER_NBC= private transient String exitRequirmentFireAndLifeSafetyAsPerNBC=NA; //COMBUSTIBLE_MATERIAL _IN_FIRE_TOWER private transient String combustibleMaterialInFireTower=NA; //DAMP_PROOFING_AT_BASEMENT private transient String dampProofingAtBasement=NA; // Hospital _Bedded private transient String hospitalBedded=NA; //Hospital_type private transient String hospitalType=NA; //SOLOR_WATER_HEATING_IN_LTR private transient String solorWaterHeatingInLtr=NA; //RESIDENTIAL_NO_OWNER private transient String residentialNoOwner=NA; public String getRootBoundaryType() { return rootBoundaryType; } public void setRootBoundaryType(String rootBoundaryType) { this.rootBoundaryType = rootBoundaryType; } public String getZone() { return zone; } public void setZone(String zoon) { this.zone = zoon; } public String getSectorNumber() { return sectorNumber; } public void setSectorNumber(String sectorNumber) { this.sectorNumber = sectorNumber; } public String getFlushingUnitVolume() { return flushingUnitVolume; } public void setFlushingUnitVolume(String flushingUnitVolume) { this.flushingUnitVolume = flushingUnitVolume; } public String getPlotType() { return plotType; } public void setPlotType(String plotType) { this.plotType = plotType; } public String getTotalNumberOfBuildingUsers() { return totalNumberOfBuildingUsers; } public void setTotalNumberOfBuildingUsers(String totalNumberOfBuildingUsers) { this.totalNumberOfBuildingUsers = totalNumberOfBuildingUsers; } public String getSolarPhotovoltaicPanelscapacity() { return solarPhotovoltaicPanelscapacity; } public void setSolarPhotovoltaicPanelscapacity(String solarPhotovoltaicPanelscapacity) { this.solarPhotovoltaicPanelscapacity = solarPhotovoltaicPanelscapacity; } public String getWhetherExistingBuildingConstructedWithoutBasement() { return whetherExistingBuildingConstructedWithoutBasement; } public void setWhetherExistingBuildingConstructedWithoutBasement( String whetherExistingBuildingConstructedWithoutBasement) { this.whetherExistingBuildingConstructedWithoutBasement = whetherExistingBuildingConstructedWithoutBasement; } public String getWhetherArtificialAndMechanicalVentilatorsProvided() { return whetherArtificialAndMechanicalVentilatorsProvided; } public void setWhetherArtificialAndMechanicalVentilatorsProvided( String whetherArtificialAndMechanicalVentilatorsProvided) { this.whetherArtificialAndMechanicalVentilatorsProvided = whetherArtificialAndMechanicalVentilatorsProvided; } public String getSoilOrVentilatingPipe() { return soilOrVentilatingPipe; } public void setSoilOrVentilatingPipe(String soilOrVentilatingPipe) { this.soilOrVentilatingPipe = soilOrVentilatingPipe; } public String getWhetherAnyStaircaseTouchingLiftShaft() { return WhetherAnyStaircaseTouchingLiftShaft; } public void setWhetherAnyStaircaseTouchingLiftShaft(String whetherAnyStaircaseTouchingLiftShaft) { WhetherAnyStaircaseTouchingLiftShaft = whetherAnyStaircaseTouchingLiftShaft; } public String getSolarPhotovoltaicKWP() { return solarPhotovoltaicKWP; } public void setSolarPhotovoltaicKWP(String solarPhotovoltaicKWP) { this.solarPhotovoltaicKWP = solarPhotovoltaicKWP; } public String getBasementServicePrintingPressACPlantsElectricalPanelFiltrationplantsLaundryplantsOrMachinesAutomated() { return basementServicePrintingPressACPlantsElectricalPanelFiltrationplantsLaundryplantsOrMachinesAutomated; } public void setBasementServicePrintingPressACPlantsElectricalPanelFiltrationplantsLaundryplantsOrMachinesAutomated( String basementServicePrintingPressACPlantsElectricalPanelFiltrationplantsLaundryplantsOrMachinesAutomated) { this.basementServicePrintingPressACPlantsElectricalPanelFiltrationplantsLaundryplantsOrMachinesAutomated = basementServicePrintingPressACPlantsElectricalPanelFiltrationplantsLaundryplantsOrMachinesAutomated; } public String getServiceFloorHeight() { return serviceFloorHeight; } public void setServiceFloorHeight(String serviceFloorHeight) { this.serviceFloorHeight = serviceFloorHeight; } public String getFireSafetyProvisionsAsPerNbcDFPF() { return fireSafetyProvisionsAsPerNbcDFPF; } public void setFireSafetyProvisionsAsPerNbcDFPF(String fireSafetyProvisionsAsPerNbcDFPF) { this.fireSafetyProvisionsAsPerNbcDFPF = fireSafetyProvisionsAsPerNbcDFPF; } public String getExitRequirmentFireAndLifeSafetyAsPerNBC() { return exitRequirmentFireAndLifeSafetyAsPerNBC; } public void setExitRequirmentFireAndLifeSafetyAsPerNBC(String exitRequirmentFireAndLifeSafetyAsPerNBC) { this.exitRequirmentFireAndLifeSafetyAsPerNBC = exitRequirmentFireAndLifeSafetyAsPerNBC; } public String getCombustibleMaterialInFireTower() { return combustibleMaterialInFireTower; } public void setCombustibleMaterialInFireTower(String combustibleMaterialInFireTower) { this.combustibleMaterialInFireTower = combustibleMaterialInFireTower; } public String getDampProofingAtBasement() { return dampProofingAtBasement; } public void setDampProofingAtBasement(String dampProofingAtBasement) { this.dampProofingAtBasement = dampProofingAtBasement; } public String getHospitalBedded() { return hospitalBedded; } public void setHospitalBedded(String hospitalBedded) { this.hospitalBedded = hospitalBedded; } public String getHospitalType() { return hospitalType; } public void setHospitalType(String hospitalType) { this.hospitalType = hospitalType; } public String getSolorWaterHeatingInLtr() { return solorWaterHeatingInLtr; } public void setSolorWaterHeatingInLtr(String solorWaterHeatingInLtr) { this.solorWaterHeatingInLtr = solorWaterHeatingInLtr; } public String getResidentialNoOwner() { return residentialNoOwner; } public void setResidentialNoOwner(String residentialNoOwner) { this.residentialNoOwner = residentialNoOwner; } public Boolean getGovernmentOrAidedSchool() { return governmentOrAidedSchool; } public void setGovernmentOrAidedSchool(Boolean governmentOrAidedSchool) { this.governmentOrAidedSchool = governmentOrAidedSchool; } public Boolean getCrzZoneArea() { return crzZoneArea; } public void setCrzZoneArea(Boolean crzZoneArea) { this.crzZoneArea = crzZoneArea; } public BigDecimal getPlotArea() { return plotArea; } public void setPlotArea(BigDecimal plotArea) { this.plotArea = plotArea; } public String getOwnerName() { return ownerName; } public void setOwnerName(String ownerName) { this.ownerName = ownerName; } public String getServiceType() { return serviceType; } public void setServiceType(String serviceType) { this.serviceType = serviceType; } public String getAmenities() { return amenities; } public void setAmenities(String amenities) { this.amenities = amenities; } public String getArchitectInformation() { return architectInformation; } public void setArchitectInformation(String architectInformation) { this.architectInformation = architectInformation; } public String getOccupancy() { return occupancy; } public void setOccupancy(String occupancy) { this.occupancy = occupancy; } public Boolean getSecurityZone() { return securityZone; } public void setSecurityZone(Boolean securityZone) { this.securityZone = securityZone; } public BigDecimal getAccessWidth() { return accessWidth; } public Boolean getDepthCutting() { return depthCutting; } public void setDepthCutting(Boolean depthCutting) { this.depthCutting = depthCutting; } public void setAccessWidth(BigDecimal accessWidth) { this.accessWidth = accessWidth; } /* * public Boolean getNocToAbutSide() { return nocToAbutSide; } public void setNocToAbutSide(Boolean nocToAbutSide) { * this.nocToAbutSide = nocToAbutSide; } */ /* * public Boolean getNocToAbutRear() { return nocToAbutRear; } public void setNocToAbutRear(Boolean nocToAbutRear) { * this.nocToAbutRear = nocToAbutRear; } */ public Boolean getOpeningOnSide() { return openingOnSide; } public void setOpeningOnSide(Boolean openingOnSide) { this.openingOnSide = openingOnSide; } /* * public Boolean getOpeningOnSideBelow2mts() { return openingOnSideBelow2mts; } */ /* * public void setOpeningOnSideBelow2mts(Boolean openingOnSideBelow2mts) { this.openingOnSideBelow2mts = * openingOnSideBelow2mts; } */ /* * public Boolean getOpeningOnSideAbove2mts() { return openingOnSideAbove2mts; } */ /* * public void setOpeningOnSideAbove2mts(Boolean openingOnSideAbove2mts) { this.openingOnSideAbove2mts = * openingOnSideAbove2mts; } */ /* * public Boolean getOpeningOnRearBelow2mts() { return openingOnRearBelow2mts; } */ /* * public void setOpeningOnRearBelow2mts(Boolean openingOnRearBelow2mts) { this.openingOnRearBelow2mts = * openingOnRearBelow2mts; } */ /* * public Boolean getOpeningOnRearAbove2mts() { return openingOnRearAbove2mts; } */ /* * public void setOpeningOnRearAbove2mts(Boolean openingOnRearAbove2mts) { this.openingOnRearAbove2mts = * openingOnRearAbove2mts; } */ /* * public Boolean getNocToAbutAdjascentSide() { return nocToAbutAdjascentSide; } public void setNocToAbutAdjascentSide(Boolean * nocToAbutAdjascentSide) { this.nocToAbutAdjascentSide = nocToAbutAdjascentSide; } */ public Boolean getOpeningOnRear() { return openingOnRear; } public void setOpeningOnRear(Boolean openingOnRear) { this.openingOnRear = openingOnRear; } public String getApplicantName() { return applicantName; } public void setApplicantName(String applicantName) { this.applicantName = applicantName; } public BigDecimal getNoOfBeds() { return noOfBeds; } public void setNoOfBeds(BigDecimal noOfBeds) { this.noOfBeds = noOfBeds; } public Integer getNoOfSeats() { return noOfSeats; } public void setNoOfSeats(Integer noOfSeats) { this.noOfSeats = noOfSeats; } public Integer getNoOfMechanicalParking() { return noOfMechanicalParking; } public void setNoOfMechanicalParking(Integer noOfMechanicalParking) { this.noOfMechanicalParking = noOfMechanicalParking; } public Boolean getSingleFamilyBuilding() { return singleFamilyBuilding; } public void setSingleFamilyBuilding(Boolean singleFamilyBuilding) { this.singleFamilyBuilding = singleFamilyBuilding; } public BigDecimal getDemolitionArea() { return demolitionArea; } public void setDemolitionArea(BigDecimal demolitionArea) { this.demolitionArea = demolitionArea; } public String getReSurveyNo() { return reSurveyNo; } public void setReSurveyNo(String reSurveyNo) { this.reSurveyNo = reSurveyNo; } public String getRevenueWard() { return revenueWard; } public void setRevenueWard(String revenueWard) { this.revenueWard = revenueWard; } public String getDesam() { return desam; } public void setDesam(String desam) { this.desam = desam; } public String getVillage() { return village; } public void setVillage(String village) { this.village = village; } public String getNocToAbutSideDesc() { return nocToAbutSideDesc; } public void setNocToAbutSideDesc(String nocToAbutSideDesc) { this.nocToAbutSideDesc = nocToAbutSideDesc; } public String getNocToAbutRearDesc() { return nocToAbutRearDesc; } public void setNocToAbutRearDesc(String nocToAbutRearDesc) { this.nocToAbutRearDesc = nocToAbutRearDesc; } public String getLandUseZone() { return landUseZone; } public void setLandUseZone(String landUseZone) { this.landUseZone = landUseZone; } public String getLeaseHoldLand() { return leaseHoldLand; } public void setLeaseHoldLand(String leaseHoldLand) { this.leaseHoldLand = leaseHoldLand; } public BigDecimal getRoadWidth() { return roadWidth; } public void setRoadWidth(BigDecimal roadWidth) { this.roadWidth = roadWidth; } public String getTypeOfArea() { return typeOfArea; } public void setTypeOfArea(String typeOfArea) { this.typeOfArea = typeOfArea; } public BigDecimal getDepthOfPlot() { return depthOfPlot; } public void setDepthOfPlot(BigDecimal depthOfPlot) { this.depthOfPlot = depthOfPlot; } public BigDecimal getWidthOfPlot() { return widthOfPlot; } public void setWidthOfPlot(BigDecimal widthOfPlot) { this.widthOfPlot = widthOfPlot; } public String getBuildingNearMonument() { return buildingNearMonument; } public void setBuildingNearMonument(String buildingNearMonument) { this.buildingNearMonument = buildingNearMonument; } public String getBuildingNearGovtBuilding() { return buildingNearGovtBuilding; } public void setBuildingNearGovtBuilding(String buildingNearGovtBuilding) { this.buildingNearGovtBuilding = buildingNearGovtBuilding; } public String getNocNearMonument() { return nocNearMonument; } public void setNocNearMonument(String nocNearMonument) { this.nocNearMonument = nocNearMonument; } public String getNocNearAirport() { return nocNearAirport; } public void setNocNearAirport(String nocNearAirport) { this.nocNearAirport = nocNearAirport; } public String getNocNearDefenceAerodomes() { return nocNearDefenceAerodomes; } public void setNocNearDefenceAerodomes(String nocNearDefenceAerodomes) { this.nocNearDefenceAerodomes = nocNearDefenceAerodomes; } public String getNocStateEnvImpact() { return nocStateEnvImpact; } public void setNocStateEnvImpact(String nocStateEnvImpact) { this.nocStateEnvImpact = nocStateEnvImpact; } public String getNocRailways() { return nocRailways; } public void setNocRailways(String nocRailways) { this.nocRailways = nocRailways; } public String getNocCollectorGvtLand() { return nocCollectorGvtLand; } public void setNocCollectorGvtLand(String nocCollectorGvtLand) { this.nocCollectorGvtLand = nocCollectorGvtLand; } public String getNocIrrigationDept() { return nocIrrigationDept; } public void setNocIrrigationDept(String nocIrrigationDept) { this.nocIrrigationDept = nocIrrigationDept; } public String getNocFireDept() { return nocFireDept; } public void setNocFireDept(String nocFireDept) { this.nocFireDept = nocFireDept; } public BigDecimal getRoadLength() { return roadLength; } public void setRoadLength(BigDecimal roadLength) { this.roadLength = roadLength; } public String getBuildingNearToRiver() { return buildingNearToRiver; } public void setBuildingNearToRiver(String buildingNearToRiver) { this.buildingNearToRiver = buildingNearToRiver; } public String getBarrierFreeAccessForPhyChlngdPpl() { return barrierFreeAccessForPhyChlngdPpl; } public void setBarrierFreeAccessForPhyChlngdPpl(String barrierFreeAccessForPhyChlngdPpl) { this.barrierFreeAccessForPhyChlngdPpl = barrierFreeAccessForPhyChlngdPpl; } public String getPlotNo() { return plotNo; } public void setPlotNo(String plotNo) { this.plotNo = plotNo; } public String getKhataNo() { return khataNo; } public void setKhataNo(String khataNo) { this.khataNo = khataNo; } public String getMauza() { return mauza; } public void setMauza(String mauza) { this.mauza = mauza; } public String getDistrict() { return district; } public void setDistrict(String district) { this.district = district; } public String getProvisionsForGreenBuildingsAndSustainability() { return provisionsForGreenBuildingsAndSustainability; } public void setProvisionsForGreenBuildingsAndSustainability(String provisionsForGreenBuildingsAndSustainability) { this.provisionsForGreenBuildingsAndSustainability = provisionsForGreenBuildingsAndSustainability; } public String getFireProtectionAndFireSafetyRequirements() { return fireProtectionAndFireSafetyRequirements; } public void setFireProtectionAndFireSafetyRequirements(String fireProtectionAndFireSafetyRequirements) { this.fireProtectionAndFireSafetyRequirements = fireProtectionAndFireSafetyRequirements; } public String getRwhDeclared() { return rwhDeclared; } public void setRwhDeclared(String rwhDeclared) { this.rwhDeclared = rwhDeclared; } public String getNocPH7Dept() { return nocPH7Dept; } public void setNocPH7Dept(String nocPH7Dept) { this.nocPH7Dept = nocPH7Dept; } public String getNocTehsildarDept() { return nocTehsildarDept; } public void setNocTehsildarDept(String nocTehsildarDept) { this.nocTehsildarDept = nocTehsildarDept; } public String getNocPHDept() { return nocPHDept; } public void setNocPHDept(String nocPHDept) { this.nocPHDept = nocPHDept; } public String getNocManimajaraDept() { return nocManimajaraDept; } public void setNocManimajaraDept(String nocManimajaraDept) { this.nocManimajaraDept = nocManimajaraDept; } public String getNocRoad2Dept() { return nocRoad2Dept; } public void setNocRoad2Dept(String nocRoad2Dept) { this.nocRoad2Dept = nocRoad2Dept; } public String getNocPACDept() { return nocPACDept; } public void setNocPACDept(String nocPACDept) { this.nocPACDept = nocPACDept; } public String getNocStructureDept() { return nocStructureDept; } public void setNocStructureDept(String nocStructureDept) { this.nocStructureDept = nocStructureDept; } public String getNocElectricalDept() { return nocElectricalDept; } public void setNocElectricalDept(String nocElectricalDept) { this.nocElectricalDept = nocElectricalDept; } public String getNocPollutionDept() { return nocPollutionDept; } public void setNocPollutionDept(String nocPollutionDept) { this.nocPollutionDept = nocPollutionDept; } }
33.494289
210
0.724384
1dac4fb34532c57705fcb1cfb0e5254dbf1a1799
457
package com.example; import java.util.List; import javax.sql.DataSource; import java.sql.Connection; public interface PagoDAO { public void setDataSource(Connection connection); public void create(String descripcionPago); public Pago getPago(Integer ID_Pago); public List<Pago> listPago(); public void delete(Integer ID_Pago); public void update(Integer ID_Pago, String descripcionPago); }
35.153846
65
0.695842
d1b5576ab0a80efd7b3fdbf867eed35e740202cb
5,420
package mods.clayium.gui.client; import codechicken.nei.recipe.GuiCraftingRecipe; import java.util.ArrayList; import java.util.List; import mods.clayium.block.tile.TileClayContainer; import mods.clayium.block.tile.TileClayMachines; import mods.clayium.core.ClayiumCore; import mods.clayium.gui.GuiPictureButton; import mods.clayium.gui.container.ContainerClayMachines; import mods.clayium.gui.container.ContainerTemp; import mods.clayium.util.UtilTier; import net.minecraft.block.Block; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.util.ResourceLocation; public class GuiClayMachines extends GuiClayEnergyTemp { protected static ResourceLocation TEXTURE = new ResourceLocation("clayium", "textures/gui/clayworktable.png"); protected int progressBarPosX; protected int progressBarPosY; protected int progressBarSizeX; protected int progressBarSizeY; public GuiClayMachines(InventoryPlayer invPlayer, TileClayMachines tile, Block block) { super((ContainerTemp) new ContainerClayMachines(invPlayer, tile, block), (TileClayContainer) tile, block); } public GuiClayMachines(ContainerTemp container, TileClayContainer tile, Block block) { super(container, tile, block); } public void drawScreen(int mousex, int mousey, float p_73863_3_) { super.drawScreen(mousex, mousey, p_73863_3_); calculateProgressBarOffsets(); if (ClayiumCore.IntegrationID.NEI.loaded() && !getOutputId().equals("")) { int offsetX = (this.width - this.xSize) / 2; int offsetY = (this.height - this.ySize) / 2; if (offsetX + this.progressBarPosX <= mousex && offsetY + this.progressBarPosY <= mousey && offsetX + this.progressBarPosX + this.progressBarSizeX > mousex && offsetY + this.progressBarPosY + this.progressBarSizeY > mousey) { List<String> list = new ArrayList(); list.add("Recipes"); func_146283_a(list, mousex, mousey); } } } protected void drawGuiContainerBackgroundLayer(float partialTick, int mouseX, int mouseZ) { super.drawGuiContainerBackgroundLayer(partialTick, mouseX, mouseZ); calculateProgressBarOffsets(); TileClayMachines tileClayMachines = (TileClayMachines) this.tile; int offsetX = (this.width - this.xSize) / 2; int offsetY = (this.height - this.ySize) / 2; ResourceLocation ProgressBarTexture = new ResourceLocation("clayium", "textures/gui/progressbarfurnace.png"); calculateProgressBarOffsets(); this.mc.getTextureManager().bindTexture(ProgressBarTexture); drawTexturedModalRect(offsetX + this.progressBarPosX, offsetY + this.progressBarPosY, 0, 0, this.progressBarSizeX, this.progressBarSizeY); drawTexturedModalRect(offsetX + this.progressBarPosX, offsetY + this.progressBarPosY, 0, this.progressBarSizeY, tileClayMachines.getCraftProgressScaled(this.progressBarSizeX), this.progressBarSizeY); drawButton(); } public void addButton() { int offsetX = (this.width - this.xSize) / 2; int offsetY = (this.height - this.ySize) / 2; TileClayMachines tileClayMachines = (TileClayMachines) this.tile; ContainerClayMachines container = (ContainerClayMachines) this.inventorySlots; if (UtilTier.canManufactualCraft(tileClayMachines.getTier())) { this.buttonList.add(new GuiPictureButton(1, offsetX + (container.machineGuiSizeX - 16) / 2, offsetY + 56, 16, 16, GuiTemp.ButtonTexture, 0, 0)); } } public void drawButton() { TileClayMachines tileClayMachines = (TileClayMachines) this.tile; if (UtilTier.canManufactualCraft(tileClayMachines.getTier())) ((GuiPictureButton) this.buttonList.get(0)).enabled = (tileClayMachines.canPushButton() != 0); } protected boolean contains(Block[] blocks, Block block) { for (Block b : blocks) { if (b == block) return true; } return false; } public void mouseClicked(int mousex, int mousey, int button) { calculateProgressBarOffsets(); String outputId = getOutputId(); if (ClayiumCore.IntegrationID.NEI.loaded() && !outputId.equals("")) { int offsetX = (this.width - this.xSize) / 2; int offsetY = (this.height - this.ySize) / 2; if (offsetX + this.progressBarPosX <= mousex && offsetY + this.progressBarPosY <= mousey && offsetX + this.progressBarPosX + this.progressBarSizeX > mousex && offsetY + this.progressBarPosY + this.progressBarSizeY > mousey) { GuiCraftingRecipe.openRecipeGui(outputId, new Object[0]); return; } } super.mouseClicked(mousex, mousey, button); } protected void calculateProgressBarOffsets() { ContainerClayMachines container = (ContainerClayMachines) this.inventorySlots; this.progressBarSizeX = 24; this.progressBarSizeY = 17; this.progressBarPosX = (container.machineGuiSizeX - this.progressBarSizeX) / 2; this.progressBarPosY = 35; } protected String getOutputId() { TileClayMachines tileClayMachines = (TileClayMachines) this.tile; String recipeid = tileClayMachines.getNEIOutputId(); return (recipeid == null) ? "" : recipeid; } }
37.638889
237
0.687454
b01fea924f59a3f903a3bad3f9f987f6edb252fe
246
package com.stormmq.java.parsing.ast.details.valueDetails; public final class DoubleSingleValueDetail implements SingleValueDetail { private final double value; public DoubleSingleValueDetail(final double value) { this.value = value; } }
20.5
71
0.804878
79795f496840a0e74ffb763e1424b21edba0af5b
2,893
package org.loader.router; import android.content.Context; import org.loader.router.exception.NotRouteException; import org.loader.router.rule.ActivityRule; import org.loader.router.rule.ReceiverRule; import org.loader.router.rule.Rule; import org.loader.router.rule.ServiceRule; import java.util.HashMap; import java.util.Set; /** * Created by qibin on 2016/10/8. */ public class RouterInternal { private static RouterInternal sInstance; /** scheme->路由规则 */ private HashMap<String, Rule> mRules; private RouterInternal() { mRules = new HashMap<>(); initDefaultRouter(); } /** * 添加默认的Activity,Service,Receiver路由 */ private void initDefaultRouter() { addRule(ActivityRule.ACTIVITY_SCHEME, new ActivityRule()); addRule(ServiceRule.SERVICE_SCHEME, new ServiceRule()); addRule(ReceiverRule.RECEIVER_SCHEME, new ReceiverRule()); } /*package */ static RouterInternal get() { if (sInstance == null) { synchronized (RouterInternal.class) { if (sInstance == null) { sInstance = new RouterInternal(); } } } return sInstance; } /** * 添加自定义路由规则 * @param scheme 路由scheme * @param rule 路由规则 * @return {@code RouterInternal} Router真实调用类 */ public final RouterInternal addRule(String scheme, Rule rule) { mRules.put(scheme, rule); return this; } private <T, V> Rule<T, V> getRule(String pattern) { HashMap<String, Rule> rules = mRules; Set<String> keySet = rules.keySet(); Rule<T, V> rule = null; for (String scheme : keySet) { if (pattern.startsWith(scheme)) { rule = rules.get(scheme); break; } } return rule; } /** * 添加路由 * @param pattern 路由uri * @param klass 路由class * @return {@code RouterInternal} Router真实调用类 */ public final <T> RouterInternal router(String pattern, Class<T> klass) { Rule<T, ?> rule = getRule(pattern); if (rule == null) { throw new NotRouteException("unknown", pattern); } rule.router(pattern, klass); return this; } /** * 路由调用 * @param ctx Context * @param pattern 路由uri * @return {@code V} 返回对应的返回值 */ /*package*/ final <V> V invoke(Context ctx, String pattern) { Rule<?, V> rule = getRule(pattern); if (rule == null) { throw new NotRouteException("unknown", pattern); } return rule.invoke(ctx, pattern); } /** * 是否存在该路由 * @param pattern * @return */ final boolean resolveRouter(String pattern) { Rule<?, ?> rule = getRule(pattern); return rule != null && rule.resolveRule(pattern); } }
24.726496
76
0.578638
ee356c6ab8da236fa62c9b8a9b974853794f53e2
2,109
/** * generated by Xtext 2.25.0 */ package org.sodalite.dsl.optimization.optimization; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>EKeras</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link org.sodalite.dsl.optimization.optimization.EKeras#getVersion <em>Version</em>}</li> * <li>{@link org.sodalite.dsl.optimization.optimization.EKeras#getBackend <em>Backend</em>}</li> * </ul> * * @see org.sodalite.dsl.optimization.optimization.OptimizationPackage#getEKeras() * @model * @generated */ public interface EKeras extends EObject { /** * Returns the value of the '<em><b>Version</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Version</em>' attribute. * @see #setVersion(String) * @see org.sodalite.dsl.optimization.optimization.OptimizationPackage#getEKeras_Version() * @model * @generated */ String getVersion(); /** * Sets the value of the '{@link org.sodalite.dsl.optimization.optimization.EKeras#getVersion <em>Version</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Version</em>' attribute. * @see #getVersion() * @generated */ void setVersion(String value); /** * Returns the value of the '<em><b>Backend</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Backend</em>' attribute. * @see #setBackend(String) * @see org.sodalite.dsl.optimization.optimization.OptimizationPackage#getEKeras_Backend() * @model * @generated */ String getBackend(); /** * Sets the value of the '{@link org.sodalite.dsl.optimization.optimization.EKeras#getBackend <em>Backend</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Backend</em>' attribute. * @see #getBackend() * @generated */ void setBackend(String value); } // EKeras
29.291667
125
0.638691
58562fd006ebd1c6d6ae382564a794c7e7c56020
1,098
package softuni.softunigamestore.domeins.entities; import lombok.Getter; import lombok.Setter; import softuni.softunigamestore.domeins.enums.Role; import javax.persistence.*; import javax.validation.constraints.Email; import javax.validation.constraints.Pattern; import java.util.Set; @Entity @Table(name = "users") @Getter @Setter public class User extends BaseEntity { @Column(nullable = false, unique = true) @Pattern(regexp = "^\\b[A-Za-z0-9+]+[a-zA-Z0-9]@[\\w]+\\.[A-Za-z]{2,4}\\b$", message = "Incorrect email.") private String email; @Column(nullable = false) @Pattern(regexp = "(?=^.{6,}$)(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\\s)[0-9a-zA-Z!@#$%^&*()]*$", message = "Password doesn't mach the validations!") private String password; private String fullName; @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "users_games", joinColumns = @JoinColumn(name = "users"), inverseJoinColumns = @JoinColumn(name = "games")) private Set<Game> games; @Enumerated(value = EnumType.STRING) private Role role; }
29.675676
99
0.652095
0e73a809379361cd7fc62e37f18c6efd34f75c30
517
package com.example.diploma.persistence.dto.admin; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.FieldDefaults; import java.util.List; @Data @NoArgsConstructor @AllArgsConstructor @FieldDefaults(level = AccessLevel.PRIVATE) public class ProductDto { Long id; String name; String brand; Double price; List<SizeDto> sizes; List<ColorDto> colors; String imageName; CategoryDto category; }
19.884615
50
0.769826
82a1010ea7b2bec2313f246e9c8a405b3675c84e
2,535
package com.inepex.ineom.shared; import java.util.Map; public abstract class PropHandler { public abstract void setProp(HasProp hasProp, String group, String key, Boolean value); public abstract void setProp(HasProp hasProp, String group, String key, Double value); public abstract void setProp(HasProp hasProp, String group, String key, String value, boolean strictMatch); public abstract void setProp(HasProp hasProp, String group, String key, String value); public abstract Boolean getBooleanProp(HasProp hasProp, String group, String key); public abstract Double getNumberProp(HasProp hasProp, String group, String key); public abstract String getStringProp(HasProp hasProp, String group, String key); public abstract String getStringPropFromGroupJson(String key, String json); public abstract Boolean getBooleanPropFromGroupJson(String key, String json); public abstract Double getNumberPropFromGroupJson(String key, String json); public abstract Map<String, Object> getPropMap(HasProp hasProp, String id); public abstract void setProp(HasProp o, String group, String key, Object value); public static String getStrictMatchKey(String key) { return "#" + key; } public void mergeProps(HasProp from, HasProp to) { for (String id : from.getAllPropsJson().keySet()) { String toPropsJson = to.getPropsJson(id); if (toPropsJson == null) { to.getAllPropsJson().put(id, from.getPropsJson(id)); } else { Map<String, Object> propMap = getPropMap(from, id); for (String key : propMap.keySet()) { setProp(to, id, key, propMap.get(key)); } } } } public String getStringPropOverride( String group, String key, HasProp tracker, HasProp user, String defaultValue) { String value = defaultValue; String trackerValue = null; if (tracker != null) { trackerValue = getStringProp(tracker, group, key); } if (trackerValue != null && !trackerValue.equals("")) { value = trackerValue; } else { String userValue = getStringProp(user, group, key); if (userValue != null && !userValue.equals("")) { value = userValue; } } return value; } }
33.8
95
0.614201
5723c3634b3374e0588e7ff80e5673ba5254b510
4,472
/* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. * * Copyright (C) 2016-2021 Philip Helger (www.helger.com) * philip[at]helger[dot]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.helger.quartz; import static com.helger.quartz.JobBuilder.newJob; import static com.helger.quartz.TriggerBuilder.newTrigger; import static org.junit.Assert.assertTrue; import java.util.List; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.helger.commons.concurrent.ThreadHelper; import com.helger.commons.lang.NonBlockingProperties; import com.helger.quartz.impl.StdSchedulerFactory; import com.helger.quartz.simpl.SimpleThreadPool; /** * Test job interruption */ public class InterruptableJobTest { private static final Logger LOGGER = LoggerFactory.getLogger (InterruptableJobTest.class); static final CyclicBarrier sync = new CyclicBarrier (2); public static class TestInterruptableJob implements IInterruptableJob { public static final AtomicBoolean interrupted = new AtomicBoolean (false); public void execute (final IJobExecutionContext context) throws JobExecutionException { LOGGER.info ("TestInterruptableJob is executing."); try { sync.await (); // wait for test thread to notice the job is now running } catch (final InterruptedException | BrokenBarrierException e1) {} for (int i = 0; i < 200; i++) { // simulate being busy for a while, then // checking interrupted flag... ThreadHelper.sleep (50); if (TestInterruptableJob.interrupted.get ()) { LOGGER.info ("TestInterruptableJob main loop detected interrupt signal."); break; } } try { LOGGER.info ("TestInterruptableJob exiting with interrupted = " + interrupted); sync.await (); } catch (final InterruptedException | BrokenBarrierException e) {} } public void interrupt () throws UnableToInterruptJobException { TestInterruptableJob.interrupted.set (true); LOGGER.info ("TestInterruptableJob.interrupt() called."); } } @Test public void testJobInterruption () throws Exception { // create a simple scheduler final NonBlockingProperties config = new NonBlockingProperties (); config.setProperty (StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, "InterruptableJobTest_Scheduler"); config.setProperty (StdSchedulerFactory.PROP_SCHED_INSTANCE_ID, "AUTO"); config.setProperty ("org.quartz.threadPool.threadCount", "2"); config.setProperty ("org.quartz.threadPool.class", SimpleThreadPool.class.getName ()); final IScheduler sched = new StdSchedulerFactory ().initialize (config).getScheduler (); sched.start (); // add a job with a trigger that will fire immediately final IJobDetail job = newJob ().ofType (TestInterruptableJob.class).withIdentity ("j1").build (); final ITrigger trigger = newTrigger ().withIdentity ("t1").forJob (job).startNow ().build (); sched.scheduleJob (job, trigger); sync.await (); // make sure the job starts running... final List <IJobExecutionContext> executingJobs = sched.getCurrentlyExecutingJobs (); assertTrue ("Number of executing jobs should be 1 ", executingJobs.size () == 1); final IJobExecutionContext jec = executingJobs.get (0); final boolean interruptResult = sched.interrupt (jec.getFireInstanceId ()); sync.await (); // wait for the job to terminate assertTrue ("Expected successful result from interruption of job ", interruptResult); assertTrue ("Expected interrupted flag to be set on job class ", TestInterruptableJob.interrupted.get ()); sched.clear (); sched.shutdown (); } }
38.222222
110
0.722272
b680100e0c81f7df009dc6c53ccf80178c4e814d
823
package experimentobackup.dominio; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Copiador extends AbstractCopiador { public Copiador() { } @Override public long copiar (String entrada, String saida) throws FileNotFoundException, IOException { // Instanciar streams sem buffer InputStream fis = new FileInputStream(entrada); OutputStream fos = new FileOutputStream(saida); // Chamar método de cópia adquirido por herança long tempoDeCopia = this.copiar(fis, fos); // Fechar streams fis.close(); fos.close(); return tempoDeCopia; } }
25.71875
95
0.670717
adf2f3d3b34f66f9b6b8fafcf892670939986de1
1,632
package game; import java.util.concurrent.ThreadLocalRandom; import static game.Color.*; public class Player { private final String name; private final Color color; public Player(String name, Color color) { this.name = name; if (color == NONE) { throw new IllegalArgumentException("Player cannot have color 'None'"); } this.color = color; } public Player(String name) { this.name = name; this.color = Color.values()[ThreadLocalRandom.current().nextInt(0, 2)]; } public Player(Player other) { this.name = other.name; this.color = other.color; } public Player opponent(String name) { return new Player(name, this.oppositeColor()); } public Color getColor() { return color; } public String getName() { return name; } public Color oppositeColor() { if (color.equals(RED)) { return WHITE; } else { return RED; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Player player = (Player) o; return name != null ? name.equals(player.name) : player.name == null && color == player.color; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (color != null ? color.hashCode() : 0); return result; } public Boolean nobody() { return this.name == null || this.name.equals(""); } }
22.985915
102
0.563113
52169adf9fbe60b8caa8b4809d8bbd71975b4f55
4,634
/** * Copyright 2016-2017 Seznam.cz, a.s. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cz.seznam.euphoria.hadoop.input; import cz.seznam.euphoria.core.client.io.DataSource; import cz.seznam.euphoria.core.client.io.DataSourceFactory; import cz.seznam.euphoria.core.client.io.Partition; import cz.seznam.euphoria.core.client.io.Reader; import cz.seznam.euphoria.core.client.util.Pair; import cz.seznam.euphoria.core.util.Settings; import cz.seznam.euphoria.hadoop.HadoopUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Objects; import java.util.Set; import static java.util.stream.Collectors.toList; /** * A convenience, easy-to-use data source reading hadoop based inputs * as lines of UTF-8 encoded text and delivering them as strings. */ public class SimpleHadoopTextFileSource implements DataSource<String> { /** * Wraps a {@code Reader<Pair<LongWritable, Text>>} to provide an API as * {@code Reader<String>} where the {@code Text} from the original reader * is transparently converted to a string. */ static final class WrapReader implements Reader<String> { private final Reader<Pair<LongWritable, Text>> wrap; WrapReader(Reader<Pair<LongWritable, Text>> wrap) { this.wrap = Objects.requireNonNull(wrap); } @Override public void close() throws IOException { this.wrap.close(); } @Override public boolean hasNext() { return this.wrap.hasNext(); } @Override public String next() { Pair<LongWritable, Text> p = this.wrap.next(); return p.getSecond().toString(); } } /** * Wraps a {@code Partition<Pair<LongWritable, Text>>} to provide an API as * {@code Partition<String>} where the {@code Text} is from the original partition * is transparently convered to a string. */ static final class WrapPartition implements Partition<String> { private final Partition<Pair<LongWritable, Text>> wrap; WrapPartition(Partition<Pair<LongWritable, Text>> wrap) { this.wrap = Objects.requireNonNull(wrap); } @Override public Set<String> getLocations() { return wrap.getLocations(); } @Override public Reader<String> openReader() throws IOException { return new WrapReader(this.wrap.openReader()); } } /** * A standard URI based factory for instances of {@link SimpleHadoopTextFileSource}. */ public static final class Factory implements DataSourceFactory { @Override @SuppressWarnings("unchecked") public <T> DataSource<T> get(URI uri, Settings settings) { return (DataSource<T>) new SimpleHadoopTextFileSource( uri.toString(), HadoopUtils.createConfiguration(settings)); } } private final HadoopTextFileSource wrap; @Override public List<Partition<String>> getPartitions() { return this.wrap.getPartitions().stream().map(WrapPartition::new).collect(toList()); } @Override public boolean isBounded() { return this.wrap.isBounded(); } /** * Convenience constructor invoking * {@link #SimpleHadoopTextFileSource(String, Configuration)} * with a newly created hadoop configuration. * * @param path the path where to place the output to * * @throws NullPointerException if any of the given parameters is {@code null} */ public SimpleHadoopTextFileSource(String path) { this(path, new Configuration()); } /** * Constructs a data sink based on hadoop's {@link HadoopTextFileSource}. * The specified path is automatically set/overridden in the given hadoop * configuration. * * @param path the path to read data from * @param hadoopConfig the hadoop configuration to build on top of * * @throws NullPointerException if any of the parameters is {@code null} */ @SuppressWarnings("unchecked") public SimpleHadoopTextFileSource(String path, Configuration hadoopConfig) { this.wrap = new HadoopTextFileSource(path, hadoopConfig); } }
31.310811
88
0.716012
1e0646741cd21bc4e2730becf8be9928e7f432be
2,348
package com.song.deviceinfo.model.beans; /** * Created by chensongsong on 2020/8/3. */ public class XposedHookBean { private boolean xposedApp = false; private boolean xposedImei = false; private boolean xposedSerial = false; private boolean xposedSsid = false; private boolean xposedMac = false; private boolean xposedAddress = false; private boolean xposedAndroidId = false; private boolean xposedImsi = false; private boolean xposedLatitude = false; private boolean xposedLongitude = false; public XposedHookBean() { } public boolean isXposedApp() { return xposedApp; } public void setXposedApp(boolean xposedApp) { this.xposedApp = xposedApp; } public boolean isXposedImei() { return xposedImei; } public void setXposedImei(boolean xposedImei) { this.xposedImei = xposedImei; } public boolean isXposedSerial() { return xposedSerial; } public void setXposedSerial(boolean xposedSerial) { this.xposedSerial = xposedSerial; } public boolean isXposedSsid() { return xposedSsid; } public void setXposedSsid(boolean xposedSsid) { this.xposedSsid = xposedSsid; } public boolean isXposedMac() { return xposedMac; } public void setXposedMac(boolean xposedMac) { this.xposedMac = xposedMac; } public boolean isXposedAddress() { return xposedAddress; } public void setXposedAddress(boolean xposedAddress) { this.xposedAddress = xposedAddress; } public boolean isXposedAndroidId() { return xposedAndroidId; } public void setXposedAndroidId(boolean xposedAndroidId) { this.xposedAndroidId = xposedAndroidId; } public boolean isXposedImsi() { return xposedImsi; } public void setXposedImsi(boolean xposedImsi) { this.xposedImsi = xposedImsi; } public boolean isXposedLatitude() { return xposedLatitude; } public void setXposedLatitude(boolean xposedLatitude) { this.xposedLatitude = xposedLatitude; } public boolean isXposedLongitude() { return xposedLongitude; } public void setXposedLongitude(boolean xposedLongitude) { this.xposedLongitude = xposedLongitude; } }
23.247525
61
0.667376
6e33b8e5aae79e12144be8720913425a03d88f32
1,886
package com.wix.reactnativenotifications.core; import android.app.IntentService; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import com.wix.reactnativenotifications.core.notifications.ILocalNotification; import com.wix.reactnativenotifications.core.notifications.LocalNotification; import com.wix.reactnativenotifications.core.notifications.NotificationProps; import com.wix.reactnativenotifications.core.notifications.actions.Action; public class LocalNotificationService extends IntentService { public static final String EXTRA_NOTIFICATION = "com.wix.reactnativenotifications.core.NOTIFICATION"; public static final String EXTRA_NOTIFICATION_ID = "com.wix.reactnativenotifications.core.NOTIFICATION_ID"; public static final String EXTRA_ACTION = "com.wix.reactnativenotifications.core.ACTION"; private static final String TAG = LocalNotificationService.class.getSimpleName(); public LocalNotificationService() { super(LocalNotificationService.class.getSimpleName()); } @Override protected void onHandleIntent(@Nullable Intent intent) { Log.d(TAG, "New intent: " + intent); final Bundle notificationBundle = intent != null ? intent.getBundleExtra(EXTRA_NOTIFICATION) : null; final Bundle actionBundle = intent != null ? intent.getBundleExtra(EXTRA_ACTION) : null; if (actionBundle != null) { final Action action = new Action(actionBundle); action.onFired(this, intent); } else if (notificationBundle != null) { final NotificationProps notificationProps = NotificationProps.fromBundle(this, notificationBundle); final ILocalNotification localNotification = LocalNotification.get(this, notificationProps); localNotification.onOpened(); } } }
42.863636
111
0.7614
73ad5510a01c4ebfbeb4654ae0d3400da7138122
735
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.packt.section6; import java.util.ArrayList; import java.util.List; /** * * @author Erik Costlow */ public class JZoo { private String name; private List<JAnimal> animals = new ArrayList<>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public List<JAnimal> getAnimals() { return animals; } public void setAnimals(List<JAnimal> animals) { this.animals = animals; } }
20.416667
80
0.613605
1235198e84d5be80dd0585624e4f0c23ad00066a
7,634
/* * * Copyright (c) 2021 Marco Marini, [email protected] * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * END OF TERMS AND CONDITIONS * */ package org.mmarini.genesis.model3; import java.util.Random; import static org.mmarini.genesis.model3.Matrix.of; /** * */ public class CloneGene implements PIPGene { private static final int MASS_THRESHOLD_IDX = 0; private static final int ENERGY_THRESHOLD_IDX = 1; private static final int MASS_PROB_RATE_IDX = 2; private static final int ENERGY_PROB_RATE_IDX = 3; /** * @param minMassThreshold minimum mass threshold * @param maxMassThreshold maximum mass threshold * @param minEnergyThreshold minimum energy threshold * @param maxEnergyThreshold maximum energy threshold * @param minMassProbability minimum mass probability speed * @param maxMassProbability maximum mass probability speed * @param minEnergyProbability minimum energy probability speed * @param maxEnergyProbability maximum energy probability speed * @param energyRef energy resource index * @param inPlacePreference clone in-place location preference * @param adjacentPreference clone adjacent location preference * @param mutationProb mutation probability * @param mutationSigma mutation sigma */ public static CloneGene create(final double minMassThreshold, final double maxMassThreshold, final double minEnergyThreshold, final double maxEnergyThreshold, final double minMassProbability, final double maxMassProbability, final double minEnergyProbability, final double maxEnergyProbability, final int energyRef, final double inPlacePreference, final double adjacentPreference, final double mutationProb, final double mutationSigma) { final Matrix minLevels = of( minMassThreshold, minEnergyThreshold, minMassProbability, minEnergyProbability ); final Matrix maxLevels = of( maxMassThreshold, maxEnergyThreshold, maxMassProbability, maxEnergyProbability ); final Matrix locationProb = of( inPlacePreference, adjacentPreference, adjacentPreference, adjacentPreference ).softmaxi().cdfiRows(); return create(minLevels, maxLevels, energyRef, locationProb, mutationProb, mutationSigma); } /** * @param minLevels minimum level of signals (4 x 1) * @param maxLevels maximum level of signals (4 x 1) * @param energyRef energy resource index * @param locationProb location probabilities (in-place, 3 x adjacent) (4 x 1) * @param mutationProb mutation probability * @param mutationSigma mutation sigma */ public static CloneGene create(final Matrix minLevels, final Matrix maxLevels, final int energyRef, final Matrix locationProb, final double mutationProb, final double mutationSigma) { return new CloneGene(minLevels, maxLevels.copy().divi(minLevels).logi(), energyRef, locationProb, mutationProb, mutationSigma); } private final Matrix minLevels; private final Matrix levelRates; private final int energyRef; private final Matrix locationProb; private final double mutationProb; private final double mutationSigma; /** * @param minLevels minimum level of signals (4 x 1) * @param levelRates rates of signals (4 x 1) * @param energyRef energy resource index * @param locationProb location probabilities (4 x 1) * @param mutationProb mutation probability * @param mutationSigma mutation sigma */ public CloneGene(final Matrix minLevels, final Matrix levelRates, final int energyRef, Matrix locationProb, double mutationProb, double mutationSigma) { this.minLevels = minLevels; this.levelRates = levelRates; this.energyRef = energyRef; this.locationProb = locationProb; this.mutationProb = mutationProb; this.mutationSigma = mutationSigma; } @Override public Population execute(final Population population, final Matrix signals, final double dt, final Matrix molecularMasses, final Topology topology, final Random random) { // Computes the actual signal levels final Matrix values = signals.copy().muli(levelRates).expi().muli(minLevels); // Extracts the mass thresholds final Matrix massThs = values.extractRow(MASS_THRESHOLD_IDX); // Extracts the energy thresholds final Matrix energyThs = values.extractRows(ENERGY_THRESHOLD_IDX); // Extracts the mass thresholds final Matrix massCloneProbRate = values.extractRow(MASS_PROB_RATE_IDX); // Extracts the energy thresholds final Matrix energyCloneProbRate = values.extractRows(ENERGY_PROB_RATE_IDX); return population.performClone(dt, molecularMasses, topology, random, massThs, energyThs, massCloneProbRate, energyCloneProbRate, this); } /** * */ public int getEnergyRef() { return energyRef; } /** * */ public Matrix getLevelRates() { return levelRates; } /** * */ public Matrix getLocationProb() { return locationProb; } /** * */ public Matrix getMinLevels() { return minLevels; } /** * */ public double getMutationProb() { return mutationProb; } /** * */ public double getMutationSigma() { return mutationSigma; } @Override public int getNumSignals() { return 4; } }
36.352381
156
0.611868
5c6a98533decff636ee8c9c4a42d5f9fceed4b0b
1,762
/******************************************************************************* * Caleydo - Visualization for Molecular Biology - http://caleydo.org * Copyright (c) The Caleydo Team. All rights reserved. * Licensed under the new BSD license, available at http://caleydo.org/license ******************************************************************************/ package org.caleydo.vis.lineup.model.mapping; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.caleydo.vis.lineup.data.ADoubleFunction; /** * @author Samuel Gratzl * */ public class BaseCategoricalMappingFunction<T> extends ADoubleFunction<T> implements ICategoricalMappingFunction<T>, Cloneable { private final Map<T, Double> mapping = new LinkedHashMap<>(); private double missingValue = Double.NaN; public BaseCategoricalMappingFunction(Set<T> items) { int i = 1; double f = 1.f / items.size(); for (T key : items) mapping.put(key, (i++) * f); } public BaseCategoricalMappingFunction(BaseCategoricalMappingFunction<T> copy) { this.mapping.putAll(copy.mapping); } @Override public BaseCategoricalMappingFunction<T> clone() { return new BaseCategoricalMappingFunction<T>(this); } @Override public boolean isComplexMapping() { return false; } @Override public double applyPrimitive(T in) { if (in == null) return missingValue; Double r = mapping.get(in); return r == null ? missingValue : r.doubleValue(); } public void put(T in, double value) { mapping.put(in, value); } public void remove(T in) { mapping.remove(in); } @Override public void reset() { int i = 1; double f = 1.f / mapping.size(); for (Map.Entry<T, Double> entry : mapping.entrySet()) entry.setValue((i++) * f); } }
25.911765
116
0.646425
2db8b7b43b5e9b2db436112aebdd2192cc42926d
353
package com.yikekong.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; @Configuration @ConfigurationProperties("webhook") @Data public class WebHookConfig { private String online; //断连web钩子地址 private String gps; //gps钩子地址 }
22.0625
75
0.804533
ec8d7fe345cf0c9981f65a2187ead51c37c25ce4
1,944
package Shameimaru.powers; import Shameimaru.cards.sp.photograph.Photograph; import com.megacrit.cardcrawl.actions.common.ReducePowerAction; import com.megacrit.cardcrawl.actions.common.RemoveSpecificPowerAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.cards.DamageInfo; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.localization.PowerStrings; import com.megacrit.cardcrawl.powers.AbstractPower; import static Shameimaru.Shameimaru.makeID; import static Shameimaru.util.actionShortcuts.atb; import static Shameimaru.util.actionShortcuts.p; public class OverclockedCameraPower extends AbstractPower { public static final String POWER_ID = makeID(OverclockedCameraPower.class.getSimpleName()); private static final PowerStrings powerStrings = CardCrawlGame.languagePack.getPowerStrings(POWER_ID); public static final String NAME = powerStrings.NAME; public static final String[] DESCRIPTIONS = powerStrings.DESCRIPTIONS; private int INITIAL_AMOUNT = 1; public OverclockedCameraPower() { name = NAME; ID = POWER_ID; this.owner = p(); this.amount = INITIAL_AMOUNT; type = PowerType.BUFF; isTurnBased = false; loadRegion("flameBarrier"); updateDescription(); } public void atEndOfRound() { flash(); if (this.amount == 0) { atb(new RemoveSpecificPowerAction(this.owner, this.owner, this)); } else { atb(new ReducePowerAction(this.owner, this.owner, this, 1)); } } @Override public float atDamageGive(float damage, DamageInfo.DamageType type, AbstractCard c) { if (c instanceof Photograph) { damage = damage * 2f; } return damage; } @Override public void updateDescription() { this.description = this.amount == 1 ? String.format(DESCRIPTIONS[0], this.amount) : String.format(DESCRIPTIONS[1], this.amount); } }
39.673469
168
0.73714
4b20fe72624900b7caa8a307e3b5b2bf4149dcfe
8,097
package za.ac.unisa.lms.tools.cronjobs.jobs; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Calendar; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import org.apache.struts.util.LabelValueBean; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.StatefulJob; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.AuthzGroupService; import org.sakaiproject.authz.api.AuthzPermissionException; import org.sakaiproject.authz.api.GroupNotDefinedException; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.email.api.EmailService; import org.sakaiproject.tool.api.Session; import org.sakaiproject.tool.api.SessionManager; import org.sakaiproject.user.api.User; import org.sakaiproject.user.api.UserDirectoryService; import org.sakaiproject.component.cover.ComponentManager; //import org.sakaiproject.authz.*; import za.ac.unisa.lms.tools.cronjobs.dao.UserCleanupSakaiDAO; import za.ac.unisa.lms.tools.cronjobs.dao.UserCleanupStudDAO; import za.ac.unisa.lms.tools.cronjobs.locks.SingleClusterInstanceJob; public class UserCleanup extends SingleClusterInstanceJob implements StatefulJob, OutputGeneratingJob { public static long runcount = 1L; private ByteArrayOutputStream outputStream; private PrintWriter output; private EmailService emailService; private SessionManager sessionManager; private UserDirectoryService userDirectoryService; /* * Crontab file ___________ Crontab syntax :- A crontab file has five fields for specifying day , date and time followed by the command to be run at that interval. * * * * * command to be executed - - - - - | | | | | | | | | +----- day of week (0 - 6) (Sunday=0) | | | +------- month (1 - 12) | | +--------- day of month (1 - 31) | +----------- hour (0 - 23) +------------- min (0 - 59) (non-Javadoc) */ private AuthzGroupService authzGroupService; /* public void setAuthzGroupService(AuthzGroupService authzGroupService) { this.authzGroupService = authzGroupService; } */ public void executeLocked(JobExecutionContext context) throws JobExecutionException { sessionManager = (SessionManager) ComponentManager.get(SessionManager.class); userDirectoryService = (UserDirectoryService) ComponentManager.get(UserDirectoryService.class); System.out.println("Cronjob: SonetteTest"); UserCleanupStudDAO db1 = new UserCleanupStudDAO(); UserCleanupSakaiDAO db2 = new UserCleanupSakaiDAO(); String feedbackMsg = "<b> The following users was removed from myUnisa: </b>"; String notRemoved = ""; Calendar now = Calendar.getInstance(); now.add(Calendar.MONTH, -15); now.add(Calendar.DATE, 13); int year1 = now.get(Calendar.YEAR); int month1 = (now.get(Calendar.MONTH)+1); int date1 = now.get(Calendar.DATE); String month = ""; if(month1<10){ month = "0"+month1; }else{ month = Integer.toString(month1); } String date =""; if(date1<10){ date="0"+date1; }else{ date=Integer.toString(date1); } String startyear = year1+"-"+month+"-"+date; Calendar now1 = Calendar.getInstance(); now1.add(Calendar.MONTH, -3); now1.add(Calendar.DATE,-18 ); int year2 = now1.get(Calendar.YEAR); int month2 = (now1.get(Calendar.MONTH)+1); int date2 = now1.get(Calendar.DATE); String endmonth = ""; if(month2<10){ endmonth = "0"+month2; }else{ endmonth=Integer.toString(month2); } String enddate = ""; if(date2<10){ enddate = "0"+date2; }else{ enddate = Integer.toString(date2); } String endyear = year2+"-"+endmonth+"-"+enddate; System.out.println("start date:"+startyear); System.out.println("end date:"+endyear); ArrayList resignedUsers= new ArrayList(); try { resignedUsers = db1.selectResignedPers(startyear,endyear); } catch (Exception e2) { // TODO Auto-generated catch block e2.printStackTrace(); } for (int i=0; i < resignedUsers.size(); i++) { LabelValueBean rUser = (LabelValueBean) resignedUsers.get(i); String userEid = rUser.getValue(); // get userId String userId = ""; try { userId = db2.getUserId(userEid); } catch (Exception e2) { // TODO Auto-generated catch block e2.printStackTrace(); } //if ((null!=userId)||(userId.length() != 0)||(!userId.equalsIgnoreCase(""))) { if (userId.equals("")) { notRemoved = notRemoved+"<br> "+userEid; } else { //authzGroupService = org.sakaiproject.authz.cover.AuthzGroupService.getInstance(); authzGroupService = (AuthzGroupService) ComponentManager.get(AuthzGroupService.class); //authzGroupService.getAuthzGroupsIsAllowed: the Set (String) of AuthzGroup ids in which this user is allowed to perform this function java.util.Set authzGroups = authzGroupService.getAuthzGroupsIsAllowed(userId , "site.visit", null); // (1) java.util.Iterator it = authzGroups.iterator(); // (2) User user = userDirectoryService.authenticate( ServerConfigurationService.getString("admin.user"), ServerConfigurationService.getString("admin.password")); if (user != null) { Session session = sessionManager.startSession(); if (session == null) throw new JobExecutionException("No session"); session.setUserEid(user.getId()); session.setUserId(user.getId()); sessionManager.setCurrentSession(session); while (it.hasNext()) { AuthzGroup group; try { group = authzGroupService.getAuthzGroup((String) it.next()); group.removeMember(userId); authzGroupService.save(group); } catch (GroupNotDefinedException e1) { // TODO Auto-generated catch block System.out.println("error occured: "+e1); feedbackMsg = feedbackMsg + " error: "+e1; //e1.printStackTrace(); } //AuthzGroup group = authzGroups.get(i); catch (AuthzPermissionException e) { // TODO Auto-generated catch block System.out.println("error occured: "+e); feedbackMsg = feedbackMsg + " error: "+e; e.printStackTrace(); } } } // if user!=null feedbackMsg = feedbackMsg +"<br> "+userEid+" = "+userId; } // end if userId is null } // end for each resigned user // Send feedback email String feedbackEmail = "<html><body>"+feedbackMsg + " <b> Users not removed: </b> "+notRemoved+" "+ " </body></html>"; String emailSubject = "myUnisa User Cleanup"; try { sendEmail(emailSubject,feedbackEmail,"[email protected]"); } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void sendEmail(String subject, String body, String emailAddress) throws AddressException { String tmpEmailFrom = ServerConfigurationService.getString("noReplyEmailFrom"); InternetAddress toEmail = new InternetAddress(emailAddress); InternetAddress iaTo[] = new InternetAddress[1]; iaTo[0] = toEmail; InternetAddress iaHeaderTo[] = new InternetAddress[1]; iaHeaderTo[0] = toEmail; InternetAddress iaReplyTo[] = new InternetAddress[1]; iaReplyTo[0] = new InternetAddress(tmpEmailFrom); List<String> contentList = new ArrayList<String>(); contentList.add("Content-Type: text/html"); //contentList.add("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); emailService = (EmailService) ComponentManager.get(EmailService.class); emailService.sendMail(iaReplyTo[0],iaTo,subject,body,iaHeaderTo,iaReplyTo,contentList); //log.info("sending mail from "+iaReplyTo[0]+" to "+toEmail.toString()); } // end of sendEmail public String getOutput() { if (output != null) { output.flush(); return outputStream.toString(); } return null; } }
34.164557
138
0.682845
491fa2687aecfc8a4b8d4925c5815dd5937e25e9
64,979
package org.onosproject.provider.framework.abnormal.feature.impl; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Modified; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.onlab.packet.Ethernet; import org.onlab.packet.ICMP; import org.onlab.packet.IPv4; import org.onlab.packet.IPv6; import org.onlab.packet.Ip4Prefix; import org.onlab.packet.Ip6Prefix; import org.onlab.packet.TCP; import org.onlab.packet.UDP; import org.onlab.packet.VlanId; import org.onosproject.athena.database.AthenaFeatureField; import org.onosproject.athena.feature.AggregateStatisticsFeature; import org.onosproject.athena.feature.ErrorMessageFeature; import org.onosproject.athena.feature.FeatureCollectorProviderRegistry; import org.onosproject.athena.feature.FeatureCollectorProviderService; import org.onosproject.athena.feature.FeatureIndex; import org.onosproject.athena.feature.FlowRemovedFeature; import org.onosproject.athena.feature.FlowStatisticsFeature; import org.onosproject.athena.feature.PacketInFeature; import org.onosproject.athena.feature.PortStatisticsFeature; import org.onosproject.athena.feature.PortStatusFeature; import org.onosproject.athena.feature.QueueStatisticsFeature; import org.onosproject.athena.feature.TableStatisticsFeature; import org.onosproject.athena.feature.UnitAggregateStatistics; import org.onosproject.athena.feature.UnitErrorMessageInformation; import org.onosproject.athena.feature.UnitFeature; import org.onosproject.athena.feature.UnitFlowRemovedInformation; import org.onosproject.athena.feature.UnitFlowStatistics; import org.onosproject.athena.feature.UnitPacketInInformation; import org.onosproject.athena.feature.UnitPortStatistics; import org.onosproject.athena.feature.UnitPortStatusInformation; import org.onosproject.athena.feature.UnitQueueStatistics; import org.onosproject.athena.feature.UnitTableStatistics; import org.onosproject.cfg.ComponentConfigService; import org.onosproject.core.CoreService; import org.onosproject.net.ConnectPoint; import org.onosproject.net.DeviceId; import org.onosproject.net.PortNumber; import org.onosproject.net.driver.DriverService; import org.onosproject.net.flow.FlowEntry; import org.onosproject.net.flow.FlowRuleService; import org.onosproject.net.flow.TrafficSelector; import org.onosproject.net.flow.instructions.Instruction; import org.onosproject.net.flow.instructions.Instructions; import org.onosproject.net.packet.DefaultInboundPacket; import org.onosproject.net.packet.InboundPacket; import org.onosproject.net.provider.AbstractProvider; import org.onosproject.net.provider.ProviderId; import org.onosproject.openflow.controller.Dpid; import org.onosproject.openflow.controller.OpenFlowAsynchronousEventListener; import org.onosproject.openflow.controller.OpenFlowController; import org.onosproject.openflow.controller.OpenFlowPacketContext; import org.onosproject.openflow.controller.OpenFlowStatisticsListener; import org.osgi.service.component.ComponentContext; import org.projectfloodlight.openflow.protocol.OFAggregateStatsReply; import org.projectfloodlight.openflow.protocol.OFErrorMsg; import org.projectfloodlight.openflow.protocol.OFFlowRemoved; import org.projectfloodlight.openflow.protocol.OFFlowStatsEntry; import org.projectfloodlight.openflow.protocol.OFFlowStatsReply; import org.projectfloodlight.openflow.protocol.OFPacketIn; import org.projectfloodlight.openflow.protocol.OFPortStatsEntry; import org.projectfloodlight.openflow.protocol.OFPortStatsReply; import org.projectfloodlight.openflow.protocol.OFPortStatus; import org.projectfloodlight.openflow.protocol.OFQueueStatsEntry; import org.projectfloodlight.openflow.protocol.OFQueueStatsReply; import org.projectfloodlight.openflow.protocol.OFTableStatsEntry; import org.projectfloodlight.openflow.protocol.OFTableStatsReply; import org.projectfloodlight.openflow.protocol.OFVersion; import org.projectfloodlight.openflow.protocol.match.Match; import org.projectfloodlight.openflow.protocol.match.MatchField; import org.projectfloodlight.openflow.types.IPv4Address; import org.projectfloodlight.openflow.types.IPv6Address; import org.projectfloodlight.openflow.types.Masked; import org.projectfloodlight.openflow.types.OFVlanVidMatch; import org.slf4j.Logger; import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import static java.lang.Math.toIntExact; import static org.slf4j.LoggerFactory.getLogger; /** * Created by seunghyeon on 8/26/15. */ @Component(immediate = true) public class FeatureCollectorProvider extends AbstractProvider implements org.onosproject.athena.feature.FeatureCollectorProvider { private final Logger log = getLogger(getClass()); @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected FeatureCollectorProviderRegistry providerRegistry; //register componentConfigService @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected ComponentConfigService cfgService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected DriverService driverService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected FlowRuleService flowRuleService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected OpenFlowController controller; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected CoreService coreService; protected InternalStatisticsCollector listener = new InternalStatisticsCollector(); private FeatureCollectorProviderService providerService; protected FeatureCollectorProviderUtil featureCollectorProviderUtil = new FeatureCollectorProviderUtil(); // Local feature tables - By Jinwoo ConcurrentHashMap<BigInteger, UnitFlowStatistics> fStatisticsLF = new ConcurrentHashMap<BigInteger, UnitFlowStatistics>(); ConcurrentHashMap<BigInteger, UnitPortStatistics> pStatisticsLF = new ConcurrentHashMap<BigInteger, UnitPortStatistics>(); // for print out // ConcurrentHashMap<String, UnitTableStatistics> tStatisticsLFT = new ConcurrentHashMap<String, // UnitTableStatistics>(); // ConcurrentHashMap<String, UnitFlowRemovedInformation> frStatisticsLFT = new ConcurrentHashMap<String, // UnitFlowRemovedInformation>(); // threshold value for polling rate - By Jinwoo static final long THRESHOLD = 3; static final long FLOW_POLL_INTERVAL = 5; static final long PORT_POLL_INTERVAL = 5; static final long TIME_THRESHOLD_SECONDS = 10; public long packetIn; public FeatureCollectorProvider() { super(new ProviderId("framework", "org.onosproject.provider.framework")); } @Activate public void activate(ComponentContext context) { log.info("Starts!"); providerService = providerRegistry.register(this); controller.addAsynchronousListener(0, listener); controller.addStatisticsListener(0, listener); //add expiration collector Timer timer = new Timer(false); timer.schedule(new ExpirationCollector(), TIME_THRESHOLD_SECONDS * 1000, TIME_THRESHOLD_SECONDS * 1000); } @Deactivate public void deactivate(ComponentContext context) { controller.removeAsynchronousListener(listener); controller.removeStatisticsListener(listener); log.info("End"); providerRegistry.unregister(this); } @Modified public void modified(ComponentContext context) { } private class InternalStatisticsCollector implements OpenFlowStatisticsListener, OpenFlowAsynchronousEventListener { @Override public void packetInProcess(Dpid dpid, OFPacketIn packetIn, OpenFlowPacketContext pktCtx) { //exclude abnormal packet -- Jinwoo Kim //only store ipv4 packet to DB try { short etherType = convertPacketContextToInboundPacket(pktCtx).parsed().getEtherType(); if (etherType != 2048) { return; } } catch (Exception e) { log.error(e.toString()); } InboundPacket ip = convertPacketContextToInboundPacket(pktCtx); PacketInFeature pif = new PacketInFeature(); UnitPacketInInformation ufii; Date date = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()); if (packetIn.getVersion() == OFVersion.OF_13) { FeatureIndex pfi = matchToFeatureIndex(packetIn.getMatch()); pfi = extractElementsFromInboundPkt(pfi, ip); ufii = new UnitPacketInInformation(packetIn.getTotalLen(), packetIn.getReason().ordinal(), pfi); // in case of OF_10, just store dummy match value // Jinwoo kim } else { ufii = new UnitPacketInInformation(); // return; } ufii.setDate(date); FeatureIndex fi = new FeatureIndex(); fi.setSwitchDatapathId(dpid.value()); fi.setSwitchPortId(toIntExact(ip.receivedFrom().port().toLong())); pif.addFeatureData(fi, ufii); providerService.packetInFeatureHandler(pif); } @Override public void flowRemovedProcess(Dpid dpid, OFFlowRemoved flowRemoved) { FlowRemovedFeature frf = new FlowRemovedFeature(); UnitFlowRemovedInformation ufri = new UnitFlowRemovedInformation(flowRemoved.getReason(), flowRemoved.getDurationSec(), flowRemoved.getDurationNsec(), flowRemoved.getIdleTimeout(), flowRemoved.getHardTimeout(), flowRemoved.getPacketCount().getValue(), flowRemoved.getByteCount().getValue()); Date date = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()); ufri.setDate(date); FeatureIndex fi = matchToFeatureIndex(flowRemoved.getMatch()); fi.setSwitchDatapathId(dpid.value()); // extract rich feature -> store to UnitFlowstatistics ufri = (UnitFlowRemovedInformation) extractRichFeature(fi, ufri, AthenaFeatureField.FLOW_REMOVED); frf.addFeatureData(fi, ufri); // printFlowRemovedLFT(frStatisticsLFT); providerService.flowRemovedHandler(frf); } @Override public void portStatusProcess(Dpid dpid, OFPortStatus portStatus) { PortStatusFeature psf = new PortStatusFeature(); UnitPortStatusInformation upsi = new UnitPortStatusInformation(portStatus.getReason().ordinal()); Date date = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()); upsi.setDate(date); FeatureIndex fi = new FeatureIndex(); fi.setSwitchDatapathId(dpid.value()); psf.addFeatureData(fi, upsi); providerService.portStatusHandler(psf); } @Override public void errorMsgProcess(Dpid dpid, OFErrorMsg errorMsg) { ErrorMessageFeature emf = new ErrorMessageFeature(); UnitErrorMessageInformation uemi = new UnitErrorMessageInformation(errorMsg.getErrType().ordinal()); Date date = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()); uemi.setDate(date); FeatureIndex fi = new FeatureIndex(); fi.setSwitchDatapathId(dpid.value()); emf.addFeatureData(fi, uemi); providerService.errorMsgHandler(emf); } @Override public void aggregateStatsProcess(Dpid dpid, OFAggregateStatsReply reply) { //magic number if (reply.getXid() != 1126) { return; } AggregateStatisticsFeature asf = new AggregateStatisticsFeature(); UnitAggregateStatistics uas = new UnitAggregateStatistics(reply.getPacketCount().getValue(), reply.getByteCount().getValue(), reply.getFlowCount()); Date date = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()); uas.setDate(date); FeatureIndex fi = new FeatureIndex(); fi.setSwitchDatapathId(dpid.value()); asf.addFeatureData(fi, uas); providerService.aggregateStatsHandler(asf); } public Map<OFFlowStatsEntry, FlowEntry> getApplicationInfoFromInternalFlowTable( Dpid dpid, List<OFFlowStatsEntry> statsEntries) { //private DeviceId deviceId = DeviceId.deviceId("of:0000000000000001"); DeviceId deviceId = DeviceId.deviceId(dpid.uri(dpid)); /** *TODO optimize mechanism for comparing between incoming and internal one. */ Map<OFFlowStatsEntry, FlowEntry> flowEntiresWithFlowInformation = new HashMap<>(); Iterable<FlowEntry> internalFlowEntries = flowRuleService.getFlowEntries(deviceId); for (int i = 0; i < statsEntries.size(); i++) { OFFlowStatsEntry entry = statsEntries.get(i); TrafficSelector inSelector = featureCollectorProviderUtil.buildSelector(entry.getMatch()); for (FlowEntry flowEntry : internalFlowEntries) { if (flowEntry.selector().equals(inSelector)) { flowEntiresWithFlowInformation.put(entry, flowEntry); break; } } } return flowEntiresWithFlowInformation; } public double[] getPairFlowInformation(Map<OFFlowStatsEntry, FlowEntry> table, Map<OFFlowStatsEntry, Boolean> pairFlowSet) { double[] vals = new double[4]; //total flow vals[0] = table.size(); //pair flow vals[1] = pairFlowSet.size(); //single flow vals[2] = vals[0] - vals[1]; //pairflowratio flow if (vals[1] == 0) { vals[3] = 0; } else { vals[3] = vals[1] / vals[0]; } return vals; } public Map<OFFlowStatsEntry, Boolean> getPairFlowSet(Map<OFFlowStatsEntry, FlowEntry> table) { Map<OFFlowStatsEntry, Boolean> pairFlowSet = new HashMap<>(); Map<OFFlowStatsEntry, int[]> pairFlowInfo = new HashMap<>(); for (Map.Entry<OFFlowStatsEntry, FlowEntry> entry : table.entrySet()) { OFFlowStatsEntry e = entry.getKey(); Match match = e.getMatch(); //0 - src, 1 - dst, 2 - proto int[] vals = new int[3]; vals[0] = 0; vals[1] = 0; vals[2] = 0; for (MatchField<?> field : match.getMatchFields()) { switch (field.id) { case IPV4_SRC: vals[0] = match.get(MatchField.IPV4_SRC).getInt(); break; case IPV4_DST: vals[1] = match.get(MatchField.IPV4_DST).getInt(); break; case IP_PROTO: vals[2] = match.get(MatchField.IP_PROTO).getIpProtocolNumber(); break; default: break; } } if (vals[0] == 0 || vals[1] == 0) { continue; } pairFlowInfo.put(e, vals); } //extract pairflow for (Map.Entry<OFFlowStatsEntry, int[]> entryCur : pairFlowInfo.entrySet()) { boolean pairflow = false; int[] valsCur = entryCur.getValue(); for (Map.Entry<OFFlowStatsEntry, int[]> entryTar : pairFlowInfo.entrySet()) { int[] valsTar = entryTar.getValue(); //src(cur) == dst(tar), src(cur) == dst(tar), proto == if ((valsCur[0] == valsTar[1]) && (valsCur[1] == valsTar[0]) && (valsCur[2] == valsTar[2]) ) { pairflow = true; break; } } if (pairflow) { pairFlowSet.put(entryCur.getKey(), true); } } return pairFlowSet; } @Override public void flowStatsProcess(Dpid dpid, OFFlowStatsReply reply) { //magic number if (reply.getXid() != 1127) { return; } FlowStatisticsFeature fsf = new FlowStatisticsFeature(); Map<OFFlowStatsEntry, FlowEntry> flowEntiresWithApps = getApplicationInfoFromInternalFlowTable(dpid, reply.getEntries()); //make a consistent among each entries Date date = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()); //pair flow related Map<OFFlowStatsEntry, Boolean> pairFlowSet = getPairFlowSet(flowEntiresWithApps); //common pair flow information double[] pairFlowInformation = getPairFlowInformation(flowEntiresWithApps, pairFlowSet); for (Map.Entry<OFFlowStatsEntry, FlowEntry> entry : flowEntiresWithApps.entrySet()) { OFFlowStatsEntry e = entry.getKey(); FlowEntry fe = entry.getValue(); UnitFlowStatistics ufs = new UnitFlowStatistics(e.getDurationSec(), e.getDurationNsec(), e.getPriority(), e.getIdleTimeout(), e.getHardTimeout(), e.getPacketCount().getValue(), e.getByteCount().getValue()); //set pairFlowInformation ufs.setTotalFlows(pairFlowInformation[0]); ufs.setTotalPairFlow(pairFlowInformation[1]); ufs.setTotalSingleFlow(pairFlowInformation[2]); ufs.setPairFlowRatio(pairFlowInformation[3]); //set Pairflow itself if (pairFlowSet.containsKey(e)) { ufs.setPairFlow(true); } else { ufs.setPairFlow(false); } List<Instruction> instructionList = fe.treatment().allInstructions(); for (int i = 0; i < fe.treatment().allInstructions().size(); i++) { Instruction instruction = instructionList.get(i); //get all actions switch (instruction.type()) { case OUTPUT: PortNumber pn = ((Instructions.OutputInstruction) instruction).port(); ufs.setActionOutput(true); ufs.setActionOutputPort(pn.toLong()); break; default: log.warn("not supported Instruction Type"); } } //No action in here ! if (fe.treatment().allInstructions().size() == 0) { ufs.setActionDrop(true); } ufs.setDate(date); ufs.setApplicationId(coreService.getAppId(fe.appId())); FeatureIndex fi = matchToFeatureIndex(e.getMatch()); fi.setSwitchDatapathId(dpid.value()); fi.setSwitchTableId(e.getTableId().getValue()); // extract rich feature -> store to UnitFlowstatistics ufs = (UnitFlowStatistics) extractRichFeature(fi, ufs, AthenaFeatureField.FLOW_STATS); // add Unitstatistics data with a feature index. fsf.addFeatureData(fi, ufs); } // printFlowStatsLFT(fStatisticsLF); providerService.flowStatsHandler(fsf); } @Override public void portStatsProcess(Dpid dpid, OFPortStatsReply reply) { //magic number if (reply.getXid() != 1128) { return; } PortStatisticsFeature psf = new PortStatisticsFeature(); List<OFPortStatsEntry> opse = reply.getEntries(); Date date = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()); for (OFPortStatsEntry p : opse) { UnitPortStatistics ups = new UnitPortStatistics(p.getRxPackets().getValue(), p.getTxPackets().getValue(), p.getRxBytes().getValue(), p.getTxBytes().getValue(), p.getRxDropped().getValue(), p.getTxDropped().getValue(), p.getRxErrors().getValue(), p.getTxErrors().getValue(), p.getRxFrameErr().getValue(), p.getRxOverErr().getValue(), p.getRxCrcErr().getValue(), p.getCollisions().getValue()); ups.setDate(date); FeatureIndex fi = new FeatureIndex(); fi.setSwitchDatapathId((dpid.value())); fi.setSwitchPortId(p.getPortNo().getPortNumber()); // extract rich feature -> store to UnitFlowstatistics ups = (UnitPortStatistics) extractRichFeature(fi, ups, AthenaFeatureField.PORT_STATS); psf.addFeatureData(fi, ups); } // to print LFT // printPortStatsLFT(pStatisticsLF); providerService.portStatsHandler(psf); } @Override public void queueStatsProcess(Dpid dpid, OFQueueStatsReply reply) { //magic number if (reply.getXid() != 1129) { return; } QueueStatisticsFeature qsf = new QueueStatisticsFeature(); List<OFQueueStatsEntry> oqsr = reply.getEntries(); Date date = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()); for (OFQueueStatsEntry q : oqsr) { UnitQueueStatistics uqs = new UnitQueueStatistics(q.getTxBytes().getValue(), q.getTxPackets().getValue(), q.getTxErrors().getValue()); uqs.setDate(date); FeatureIndex fi = new FeatureIndex(); fi.setSwitchDatapathId(dpid.value()); fi.setSwitchPortId(q.getPortNo().getPortNumber()); fi.setSwitchQeueueId(q.getQueueId()); qsf.addFeatureData(fi, uqs); } providerService.queueStatsHandler(qsf); } @Override public void tableStatsProcess(Dpid dpid, OFTableStatsReply reply) { //magic number if (reply.getXid() != 1130) { return; } TableStatisticsFeature tsf = new TableStatisticsFeature(); List<OFTableStatsEntry> otse = reply.getEntries(); Date date = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()); for (OFTableStatsEntry t : otse) { if (t.getActiveCount() == 0) { break; } UnitTableStatistics uts = new UnitTableStatistics(t.getMaxEntries(), t.getActiveCount(), t.getLookupCount().getValue(), t.getMatchedCount().getValue()); uts.setDate(date); FeatureIndex fi = new FeatureIndex(); fi.setSwitchDatapathId(dpid.value()); fi.setSwitchTableId(t.getTableId().getValue()); // extract rich feature -> store to UnitTablestatistics uts = (UnitTableStatistics) extractRichFeature(fi, uts, AthenaFeatureField.TABLE_STATS); tsf.addFeatureData(fi, uts); } // printTableStatsLFT(tStatisticsLFT); providerService.tableStatsHandler(tsf); } } //Utils. public InboundPacket convertPacketContextToInboundPacket(OpenFlowPacketContext pktCtx) { //convert OpenFlowPacketContext to PacketContext DeviceId id = DeviceId.deviceId(Dpid.uri(pktCtx.dpid().value())); DefaultInboundPacket inPkt = new DefaultInboundPacket( new ConnectPoint(id, PortNumber.portNumber(pktCtx.inPort())), pktCtx.parsed(), ByteBuffer.wrap(pktCtx.unparsed())); /* DefaultOutboundPacket outPkt = null; if (!pktCtx.isBuffered()) { outPkt = new DefaultOutboundPacket(id, null, ByteBuffer.wrap(pktCtx.unparsed())); } OpenFlowCorePacketContext context = new OpenFlowCorePacketContext(System.currTimeMillis(), inPkt, outPkt, pktCtx.isHandled(), pktCtx); */ return inPkt; } public FeatureIndex extractElementsFromInboundPkt(FeatureIndex fi, InboundPacket pkt) { Ethernet ethPkt = pkt.parsed(); //EthType.EtherType.ARP.ethType().toShort() //EthType ethType = new EthType(); if (ethPkt == null) { return fi; } if (ethPkt.getDestinationMAC().toLong() != 0) { fi.setMatchEthDst(ethPkt.getDestinationMAC().toLong()); } if (ethPkt.getSourceMAC().toLong() != 0) { fi.setMatchEthSrc(ethPkt.getSourceMAC().toLong()); } if (ethPkt.getEtherType() == ethPkt.TYPE_ARP) { fi.setMatchEthType(ethPkt.getEtherType()); } else if (ethPkt.getEtherType() == ethPkt.VLAN_UNTAGGED) { fi.setMatchEthType(ethPkt.getEtherType()); fi.setMatchVlanVid(ethPkt.getVlanID()); } else if (ethPkt.getEtherType() == ethPkt.TYPE_IPV4) { fi.setMatchEthType(ethPkt.getEtherType()); IPv4 ipv4Packet = (IPv4) ethPkt.getPayload(); byte ipv4Protocol = ipv4Packet.getProtocol(); fi.setMatchIpv4Src(ipv4Packet.getSourceAddress()); fi.setMatchIpv4Dst(ipv4Packet.getDestinationAddress()); fi.setMatchIpDscp(ipv4Packet.getDscp()); fi.setMatchIpEcn(ipv4Packet.getEcn()); if (ipv4Protocol == IPv4.PROTOCOL_TCP) { TCP tcpPacket = (TCP) ipv4Packet.getPayload(); fi.setMatchIpProto((short) ipv4Protocol); fi.setMatchTcpSrc(tcpPacket.getSourcePort()); fi.setMatchTcpDst(tcpPacket.getDestinationPort()); } if (ipv4Protocol == IPv4.PROTOCOL_UDP) { UDP udpPacket = (UDP) ipv4Packet.getPayload(); fi.setMatchIpProto((short) ipv4Protocol); fi.setMatchUdpSrc(udpPacket.getSourcePort()); fi.setMatchUdpDst(udpPacket.getDestinationPort()); } if (ipv4Protocol == IPv4.PROTOCOL_ICMP) { ICMP icmpPacket = (ICMP) ipv4Packet.getPayload(); fi.setMatchIpProto((short) ipv4Protocol); fi.setMatchIcmpv4Code(icmpPacket.getIcmpCode()); fi.setMatchIcmpv4Type(icmpPacket.getIcmpType()); } // log.warn("[DEbug] IPv4 !!!!!!!!!!!!!!!!!!!"); } else if (ethPkt.getEtherType() == ethPkt.TYPE_IPV6) { fi.setMatchEthType(ethPkt.getEtherType()); IPv6 ipv6Packet = (IPv6) ethPkt.getPayload(); byte ipv6NextHeader = ipv6Packet.getNextHeader(); fi.setMatchIpv6Src(ipv6Packet.getSourceAddress()); fi.setMatchIpv6Dst(ipv6Packet.getDestinationAddress()); fi.setMatchIpv6Flabel(ipv6Packet.getFlowLabel()); if (ipv6NextHeader == IPv6.PROTOCOL_TCP) { TCP tcpPacket = (TCP) ipv6Packet.getPayload(); fi.setMatchIpProto((short) ipv6NextHeader); fi.setMatchTcpSrc(tcpPacket.getSourcePort()); fi.setMatchTcpDst(tcpPacket.getDestinationPort()); } if (ipv6NextHeader == IPv6.PROTOCOL_UDP) { UDP udpPacket = (UDP) ipv6Packet.getPayload(); fi.setMatchIpProto((short) ipv6NextHeader); fi.setMatchUdpSrc(udpPacket.getSourcePort()); fi.setMatchUdpDst(udpPacket.getDestinationPort()); } if (ipv6NextHeader == IPv6.PROTOCOL_ICMP6) { ICMP icmpPacket = (ICMP) ipv6Packet.getPayload(); fi.setMatchIpProto((short) ipv6NextHeader); fi.setMatchIcmpv6Code(icmpPacket.getIcmpCode()); fi.setMatchIcmpv6Type(icmpPacket.getIcmpType()); } } else { //log.info("Not supported Ethernet Type(Packet_In payload)"); return null; } return fi; } //See the FlowEntryBuilder public FeatureIndex matchToFeatureIndex(Match match) { FeatureIndex fi = new FeatureIndex(); for (MatchField<?> field : match.getMatchFields()) { switch (field.id) { case IN_PORT: fi.setMatchInPort(match.get(MatchField.IN_PORT).getPortNumber()); break; case IN_PHY_PORT: fi.setMatchInPhyPort(match.get(MatchField.IN_PHY_PORT).getPortNumber()); break; case METADATA: log.info("Skip MEDATADATA"); break; case ETH_DST: fi.setMatchEthDst(match.get(MatchField.ETH_DST).getLong()); break; case ETH_SRC: fi.setMatchEthSrc(match.get(MatchField.ETH_SRC).getLong()); break; case ETH_TYPE: fi.setMatchEthType(match.get(MatchField.ETH_TYPE).getValue()); break; case VLAN_VID: VlanId vlanId = null; if (match.isPartiallyMasked(MatchField.VLAN_VID)) { Masked<OFVlanVidMatch> masked = match.getMasked(MatchField.VLAN_VID); if (masked.getValue().equals(OFVlanVidMatch.PRESENT) && masked.getMask().equals(OFVlanVidMatch.PRESENT)) { vlanId = VlanId.ANY; } } else { vlanId = VlanId.vlanId(match.get(MatchField.VLAN_VID).getVlan()); } fi.setMatchVlanVid(vlanId.toShort()); break; case VLAN_PCP: fi.setMatchVlanPcp(match.get(MatchField.VLAN_PCP).getValue()); break; case IP_DSCP: fi.setMatchIpDscp(match.get(MatchField.IP_DSCP).getDscpValue()); break; case IP_ECN: fi.setMatchIpEcn(match.get(MatchField.IP_ECN).getEcnValue()); break; case IP_PROTO: fi.setMatchIpProto(match.get(MatchField.IP_PROTO).getIpProtocolNumber()); break; case IPV4_SRC: if (match.isPartiallyMasked(MatchField.IPV4_SRC)) { Masked<IPv4Address> maskedIp = match.getMasked(MatchField.IPV4_SRC); fi.setMatchIpv4Src(maskedIp.getValue().getInt()); fi.setMatchIpv4SrcMask(maskedIp.getMask().asCidrMaskLength()); } else { fi.setMatchIpv4Src(match.get(MatchField.IPV4_SRC).getInt()); fi.setMatchIpv4SrcMask(Ip4Prefix.MAX_MASK_LENGTH); } break; case IPV4_DST: if (match.isPartiallyMasked(MatchField.IPV4_DST)) { Masked<IPv4Address> maskedIp = match.getMasked(MatchField.IPV4_DST); fi.setMatchIpv4Dst(maskedIp.getValue().getInt()); fi.setMatchIpv4DstMask(maskedIp.getMask().asCidrMaskLength()); } else { fi.setMatchIpv4Dst(match.get(MatchField.IPV4_DST).getInt()); fi.setMatchIpv4DstMask(Ip4Prefix.MAX_MASK_LENGTH); } break; case TCP_SRC: fi.setMatchTcpSrc(match.get(MatchField.TCP_SRC).getPort()); break; case TCP_DST: fi.setMatchTcpDst(match.get(MatchField.TCP_DST).getPort()); break; case UDP_SRC: fi.setMatchUdpSrc(match.get(MatchField.UDP_SRC).getPort()); break; case UDP_DST: fi.setMatchUdpDst(match.get(MatchField.UDP_DST).getPort()); break; case MPLS_LABEL: fi.setMatchMplsLabel((int) match.get(MatchField.MPLS_LABEL).getValue()); break; case SCTP_SRC: fi.setMatchSctpSrc(match.get(MatchField.SCTP_SRC).getPort()); break; case SCTP_DST: fi.setMatchSctpDst(match.get(MatchField.SCTP_DST).getPort()); break; case ICMPV4_TYPE: fi.setMatchIcmpv4Type((byte) match.get(MatchField.ICMPV4_TYPE).getType()); break; case ICMPV4_CODE: fi.setMatchIcmpv4Code((byte) match.get(MatchField.ICMPV4_CODE).getCode()); break; case IPV6_SRC: if (match.isPartiallyMasked(MatchField.IPV6_SRC)) { Masked<IPv6Address> maskedIp = match.getMasked(MatchField.IPV6_SRC); fi.setMatchIpv6Src(maskedIp.getValue().getBytes()); fi.setMatchIpv6SrcMask(maskedIp.getMask().asCidrMaskLength()); } else { fi.setMatchIpv6Src(match.get(MatchField.IPV6_SRC).getBytes()); fi.setMatchIpv6SrcMask(Ip6Prefix.MAX_MASK_LENGTH); } break; case IPV6_DST: if (match.isPartiallyMasked(MatchField.IPV6_DST)) { Masked<IPv6Address> maskedIp = match.getMasked(MatchField.IPV6_DST); fi.setMatchIpv6Dst(maskedIp.getValue().getBytes()); fi.setMatchIpv6DstMask(maskedIp.getMask().asCidrMaskLength()); } else { fi.setMatchIpv6Dst(match.get(MatchField.IPV6_DST).getBytes()); fi.setMatchIpv6DstMask(Ip6Prefix.MAX_MASK_LENGTH); } break; case IPV6_FLABEL: fi.setMatchIpv6Flabel(match.get(MatchField.IPV6_FLABEL).getIPv6FlowLabelValue()); break; case ICMPV6_TYPE: fi.setMatchIcmpv6Type((byte) match.get(MatchField.ICMPV6_TYPE).getValue()); break; case ICMPV6_CODE: fi.setMatchIcmpv6Code((byte) match.get(MatchField.ICMPV6_CODE).getValue()); break; case IPV6_ND_TARGET: fi.setMatchIpv6NdTarget(match.get(MatchField.IPV6_ND_TARGET).getBytes()); break; case IPV6_ND_SLL: fi.setMatchIpv6NdSll(match.get(MatchField.IPV6_ND_SLL).getLong()); break; case IPV6_ND_TLL: fi.setMatchIpv6NdTll(match.get(MatchField.IPV6_ND_TLL).getLong()); break; case IPV6_EXTHDR: fi.setMatchIpv6Exthdr(match.get(MatchField.IPV6_EXTHDR).getValue()); break; case OCH_SIGID: case OCH_SIGTYPE: case ARP_OP: case ARP_SHA: case ARP_SPA: case ARP_THA: case ARP_TPA: case MPLS_TC: case TUNNEL_ID: default: log.warn("Match type {} not yet implemented.", field.id); } } return fi; } // extract rich feature from statistic OF packet - By Jinwoo public UnitFeature extractRichFeature(FeatureIndex fi, UnitFeature uf, String fname) { BigInteger hashIndex = generateHashIndex(fi); try { switch (fname) { case AthenaFeatureField.FLOW_STATS: UnitFlowStatistics ufs = (UnitFlowStatistics) uf; ufs = calculateFlowStatsRichFeatures(hashIndex, ufs); uf = ufs; break; case AthenaFeatureField.PORT_STATS: UnitPortStatistics ups = (UnitPortStatistics) uf; ups = calculatePortStatsRichFeatures(hashIndex, ups); uf = ups; break; case AthenaFeatureField.FLOW_REMOVED: UnitFlowRemovedInformation ufri = (UnitFlowRemovedInformation) uf; ufri = calculateFlowRemovedRichFeatures(hashIndex, ufri); uf = ufri; break; case AthenaFeatureField.TABLE_STATS: UnitTableStatistics uts = (UnitTableStatistics) uf; uts = calculateTableStatsRichFeatures(hashIndex, uts); break; default: break; } } catch (Exception e) { log.warn(e.toString()); } return uf; } //TODO: Could be serious problem... // generate HashIndex of LFT - By Jinwoo public BigInteger generateHashIndex(FeatureIndex fi) { BigInteger result = null; MessageDigest md; try { md = MessageDigest.getInstance("MD5"); // allocate byte buffer for all feature index // TODO : should be more intelligent way ByteBuffer bb = ByteBuffer.allocate(4 * Long.BYTES + 18 * Integer.BYTES + 2 * Short.BYTES + 3 * Byte.BYTES); bb.putLong(fi.getSwitchDatapathId()); bb.putInt(fi.getSwitchPortId()); bb.putLong(fi.getSwitchQeueueId()); bb.putInt(fi.getSwitchTableId()); bb.putInt(fi.getMatchInPort()); bb.putInt(fi.getMatchInPhyPort()); bb.putLong(fi.getMatchEthDst()); bb.putLong(fi.getMatchEthSrc()); bb.putInt(fi.getMatchEthType()); bb.putShort(fi.getMatchVlanVid()); bb.put(fi.getMatchVlanPcp()); bb.put(fi.getMatchIpDscp()); bb.put(fi.getMatchIpEcn()); bb.putShort(fi.getMatchIpProto()); bb.putInt(fi.getMatchIpv4Src()); bb.putInt(fi.getMatchIpv4SrcMask()); bb.putInt(fi.getMatchIpv4Dst()); bb.putInt(fi.getMatchIpv4DstMask()); bb.putInt(fi.getMatchTcpSrc()); bb.putInt(fi.getMatchTcpDst()); bb.putInt(fi.getMatchUdpDst()); bb.putInt(fi.getMatchUdpDst()); bb.putInt(fi.getMatchMplsLabel()); bb.putInt(fi.getMatchSctpSrc()); bb.putInt(fi.getMatchSctpDst()); bb.putInt(fi.getMatchIcmpv4Code()); bb.putInt(fi.getMatchIcmpv4Type()); // generate hash index using MD5 byte[] hashIndex = md.digest(bb.array()); bb.clear(); md.reset(); // generate string of hashIndex // StringBuilder key = new StringBuilder(); // for (int i = 0; i < hashIndex.length; i++) { // key.append(String.format("%02x", hashIndex[i])); // } result = new BigInteger(hashIndex); } catch (Exception e) { log.warn(e.toString()); } return result; } public synchronized UnitFlowStatistics calculateFlowStatsRichFeatures(BigInteger hashIndex, UnitFlowStatistics ufs) { try { double timeDiff; double prevTotalDuration; double currTotalDuration = ((ufs.getDurationSec() * (long) Math.pow(10, 9)) + ufs.getDurationNsec()); // look up LFT using hash index UnitFlowStatistics prevUfs = fStatisticsLF.get(hashIndex); if (prevUfs == null) { timeDiff = -1; } else { prevTotalDuration = (prevUfs.getDurationSec() * (long) Math.pow(10, 9)) + prevUfs.getDurationNsec(); timeDiff = (currTotalDuration - prevTotalDuration) / (double) Math.pow(10, 9); } if (timeDiff == 0) { return ufs; } // extract current packet, byte count and time long currPacketCount = ufs.getPacketCount(); long currByteCount = ufs.getByteCount(); double currTotalFlow = ufs.getTotalFlows(); double currTotalPairFlow = ufs.getTotalPairFlow(); double currTotalSingleFlow = ufs.getTotalSingleFlow(); double currPairFlowRatio = ufs.getPairFlowRatio(); // rich feature variables double currPacketCountVar = 0; double currByteCountVar = 0; double currBytePerPacket = 0; double currBytePerPacketVar = 0; double currPacketPerDuration = 0; double currPacketPerDurationVar = 0; double currBytePerDuration = 0; double currBytePerDurationVar = 0; //add (Existing values) double currTotalFlowVar = 0; double currTotalPairFlowVar = 0; double currTotalSingleFlowVar = 0; double currPairFlowRatioVar = 0; // if current packet count is zero, set bytePerPacket as zero if (currPacketCount != 0) { currBytePerPacket = currByteCount / (double) currPacketCount; } // 2. Calculate variation if (timeDiff > 0 && timeDiff < FLOW_POLL_INTERVAL * THRESHOLD) { // extract previous features long prevPacketCount = prevUfs.getPacketCount(); long prevByteCount = prevUfs.getByteCount(); double prevTotalFlow = prevUfs.getTotalFlows(); double prevTotalPairFlow = prevUfs.getTotalPairFlow(); double prevTotalSingleFlow = prevUfs.getTotalSingleFlow(); double prevPairFlowRatio = prevUfs.getPairFlowRatio(); double prevBytePerPacket = prevUfs.getBytePerPacket(); double prevPacketPerDuration = prevUfs.getPacketPerDuration(); double prevBytePerDuration = prevUfs.getPacketPerDuration(); currPacketCountVar = (currPacketCount - prevPacketCount) / timeDiff; currByteCountVar = (currByteCount - prevByteCount) / timeDiff; currTotalFlowVar = (currTotalFlow - prevTotalFlow) / timeDiff; if ((currTotalPairFlow - prevTotalPairFlow) != 0) { currTotalPairFlowVar = (currTotalPairFlow - prevTotalPairFlow) / timeDiff; } if ((currTotalSingleFlow - prevTotalSingleFlow) != 0) { currTotalSingleFlowVar = (currTotalSingleFlow - prevTotalSingleFlow) / timeDiff; } if ((currPairFlowRatio - prevPairFlowRatio) != 0) { currPairFlowRatioVar = (currPairFlowRatio - prevPairFlowRatio) / timeDiff; } currBytePerPacketVar = (currBytePerPacket - prevBytePerPacket) / timeDiff; currTotalDuration /= (double) Math.pow(10, 9); currPacketPerDuration = currPacketCount / (double) currTotalDuration; currPacketPerDurationVar = (currPacketPerDuration - prevPacketPerDuration) / timeDiff; currBytePerDuration = currByteCount / (double) currTotalDuration; currBytePerDurationVar = (currBytePerDuration - prevBytePerDuration) / timeDiff; // prefix + attribute (var) => refer to the prefix // currBytePerDuration - prevBytePerDuration / TD // 1. new or 3. Expire entries (EC) } else if (timeDiff < 0 || timeDiff > FLOW_POLL_INTERVAL * THRESHOLD) { currPacketCountVar = currPacketCount / (double) FLOW_POLL_INTERVAL; currByteCountVar = currByteCount / (double) FLOW_POLL_INTERVAL; currTotalFlowVar = currTotalFlow / (double) FLOW_POLL_INTERVAL; if (currTotalPairFlow != 0) { currTotalPairFlowVar = currTotalPairFlow / (double) FLOW_POLL_INTERVAL; } if (currTotalSingleFlow != 0) { currTotalSingleFlowVar = currTotalSingleFlow / (double) FLOW_POLL_INTERVAL; } if (currPairFlowRatio != 0) { currPairFlowRatioVar = currPairFlowRatio / (double) FLOW_POLL_INTERVAL; } // currByteCountVar - prevBytCountVar / TD currBytePerPacketVar = currBytePerPacket / (double) FLOW_POLL_INTERVAL; currTotalDuration /= (double) Math.pow(10, 9); currPacketPerDuration = currPacketCount / (double) currTotalDuration; currPacketPerDurationVar = currPacketPerDuration / (double) FLOW_POLL_INTERVAL; currBytePerDuration = currByteCount / (double) currTotalDuration; currBytePerDurationVar = currBytePerDuration / (double) FLOW_POLL_INTERVAL; } // update or add new entry to LFT ufs.setPacketCountVar(currPacketCountVar); ufs.setByteCountVar(currByteCountVar); ufs.setTotalFlowsVar(currTotalFlowVar); ufs.setTotalPairFlowVar(currTotalPairFlowVar); ufs.setTotalSingleFlowVar(currTotalSingleFlowVar); ufs.setPairFlowRatioVar(currPairFlowRatioVar); ufs.setBytePerPacket(currBytePerPacket); ufs.setBytePerPacketVar(currBytePerPacketVar); ufs.setBytePerDuration(currBytePerDuration); ufs.setBytePerDurationVar(currBytePerDurationVar); ufs.setPacketPerDuration(currPacketPerDuration); ufs.setPacketPerDurationVar(currPacketPerDurationVar); fStatisticsLF.remove(hashIndex); fStatisticsLF.put(hashIndex, ufs); } catch (Exception e) { log.error(e.toString()); } return ufs; } public synchronized UnitPortStatistics calculatePortStatsRichFeatures(BigInteger hashIndex, UnitPortStatistics ups) { try { double timeDiff; long currTimeStamp = ups.getTimestamp().getTime(); // get feature // look up LFT using hash index UnitPortStatistics prevUps = pStatisticsLF.get(hashIndex); // if previous entry is empty, regard it as a new entry if (prevUps == null) { timeDiff = -1; } else { long prevTimeStamp = prevUps.getTimestamp().getTime(); timeDiff = currTimeStamp - prevTimeStamp; timeDiff /= Math.pow(10, 3); } if (timeDiff == 0) { return ups; } // extract current features long currRxPackets = ups.getRxPackets(); long currTxPackets = ups.getTxPackets(); long currRxBytes = ups.getRxBytes(); long currTxBytes = ups.getTxBytes(); long currRxDropped = ups.getRxDropped(); long currTxDropped = ups.getTxDropped(); long currRxErrors = ups.getRxErrors(); long currTxErrors = ups.getTxErrors(); long currRxFrameErr = ups.getRxFrameErr(); long currRxOverErr = ups.getRxOverErr(); long currRxCrcErr = ups.getRxCrcErr(); long currCollisions = ups.getCollisions(); // current rich feature variables double currRxPacketsVar = 0; double currTxPacketsVar = 0; double currRxBytesVar = 0; double currTxBytesVar = 0; double currRxDroppedVar = 0; double currTxDroppedVar = 0; double currRxErrorsVar = 0; double currTxErrorsVar = 0; double currRxFrameErrVar = 0; double currRxOverErrVar = 0; double currRxCrcErrVar = 0; double currCollisionsVar = 0; double currRxBytePerPacket = 0; double currRxBytePerPacketVar = 0; double currTxBytePerPacket = 0; double currTxBytePerPacketVar = 0; double currRxDroppedPerPacket = 0; double currRxDroppedPerPacketVar = 0; double currTxDroppedPerPacket = 0; double currTxDroppedPerPacketVar = 0; double currRxErrorPerPacket = 0; double currRxErrorPerPacketVar = 0; double currTxErrorPerPacket = 0; double currTxErrorPerPacketVar = 0; double currRxFrameErrPerPacket = 0; double currRxFrameErrPerPacketVar = 0; double currRxOverErrPerPacket = 0; double currRxOverErrPerPacketVar = 0; double currRxCrcErrPerPacket = 0; double currRxCrcErrPerPacketVar = 0; // calculate single rich features if (currRxPackets != 0) { currRxBytePerPacket = currRxBytes / (double) currRxPackets; currRxDroppedPerPacket = currRxDropped / (double) currRxPackets; currRxErrorPerPacket = currRxErrors / (double) currRxPackets; currRxFrameErrPerPacket = currRxFrameErr / (double) currRxPackets; currRxOverErrPerPacket = currRxOverErr / (double) currRxPackets; currRxCrcErrPerPacket = currRxCrcErr / (double) currRxPackets; } if (currTxPackets != 0) { currTxBytePerPacket = currTxBytes / (double) currTxPackets; currTxDroppedPerPacket = currTxDropped / (double) currTxPackets; currTxErrorPerPacket = currTxErrors / (double) currTxPackets; } // 2. Calculate variation if (timeDiff > 0 && timeDiff < FLOW_POLL_INTERVAL * THRESHOLD) { // extract previous features long prevRxPackets = prevUps.getRxPackets(); long prevTxPackets = prevUps.getTxPackets(); long prevRxBytes = prevUps.getRxBytes(); long prevTxBytes = prevUps.getTxBytes(); long prevRxDropped = prevUps.getRxDropped(); long prevTxDropped = prevUps.getTxDropped(); long prevRxErrors = prevUps.getRxErrors(); long prevTxErrors = prevUps.getTxErrors(); long prevRxFrameErr = prevUps.getRxFrameErr(); long prevRxOverErr = prevUps.getRxOverErr(); long prevRxCrcErr = prevUps.getRxCrcErr(); long prevCollisions = prevUps.getCollisions(); double prevRxBytePerPacket = prevUps.getRxBytePerPacket(); double prevTxBytePerPacket = prevUps.getTxBytePerPacket(); double prevRxDroppedPerPacket = prevUps.getRxDroppedPerPacket(); double prevTxDroppedPerPacket = prevUps.getTxDroppedPerPacket(); double prevRxErrorPerPacket = prevUps.getRxErrorPerPacket(); double prevTxErrorPerPacket = prevUps.getTxErrorPerPacket(); double prevRxFrameErrPerPacket = prevUps.getRxFrameErrPerPacket(); double prevRxOverErrPerPacket = prevUps.getRxOverErrPerPacket(); double prevRxCrcErrPerPacket = prevUps.getRxCrcErrPerPacket(); // calculate variation rich features // timeDiff /= Math.pow(10, 3); currRxPacketsVar = (currRxPackets - prevRxPackets) / timeDiff; currTxPacketsVar = (currTxPackets - prevTxPackets) / timeDiff; currRxBytesVar = (currRxBytes - prevRxBytes) / timeDiff; currTxBytesVar = (currTxBytes - prevTxBytes) / timeDiff; currRxDroppedVar = (currRxDropped - prevRxDropped) / timeDiff; currTxDroppedVar = (currTxDropped - prevTxDropped) / timeDiff; currRxErrorsVar = (currRxErrors - prevRxErrors) / timeDiff; currTxErrorsVar = (currTxErrors - prevTxErrors) / timeDiff; currRxFrameErrVar = (currRxFrameErr - prevRxFrameErr) / timeDiff; currRxOverErrVar = (currRxOverErr - prevRxOverErr) / timeDiff; currRxCrcErrVar = (currRxCrcErr - prevRxCrcErr) / timeDiff; currCollisionsVar = (currCollisions - prevCollisions) / timeDiff; currRxBytePerPacketVar = (currRxBytePerPacket - prevRxBytePerPacket) / timeDiff; currTxBytePerPacketVar = (currTxBytePerPacket - prevTxBytePerPacket) / timeDiff; currRxDroppedPerPacketVar = (currRxDroppedPerPacket - prevRxDroppedPerPacket) / timeDiff; currTxDroppedPerPacketVar = (currTxDroppedPerPacket - prevTxDroppedPerPacket) / timeDiff; currRxErrorPerPacketVar = (currRxErrorPerPacket - prevRxErrorPerPacket) / timeDiff; currTxErrorPerPacketVar = (currTxErrorPerPacket - prevTxErrorPerPacket) / timeDiff; currRxFrameErrPerPacketVar = (currRxFrameErrPerPacket - prevRxFrameErrPerPacket) / timeDiff; currRxOverErrPerPacketVar = (currRxOverErrPerPacket - prevRxOverErrPerPacket) / timeDiff; currRxCrcErrPerPacketVar = (currRxCrcErrPerPacket - prevRxCrcErrPerPacket) / timeDiff; // 1. new or 3. Expire entries (EC) } else if (timeDiff < 0 || timeDiff > FLOW_POLL_INTERVAL * THRESHOLD) { // calculate variation rich features currRxPacketsVar = currRxPackets / (double) PORT_POLL_INTERVAL; currTxPacketsVar = currTxPackets / (double) PORT_POLL_INTERVAL; currRxBytesVar = currRxBytes / (double) PORT_POLL_INTERVAL; currTxBytesVar = currTxBytes / (double) PORT_POLL_INTERVAL; currRxDroppedVar = currRxDropped / (double) PORT_POLL_INTERVAL; currTxDroppedVar = currTxDropped / (double) PORT_POLL_INTERVAL; currRxErrorsVar = currRxErrors / (double) PORT_POLL_INTERVAL; currTxErrorsVar = currTxErrors / (double) PORT_POLL_INTERVAL; currRxFrameErrVar = currRxFrameErr / (double) PORT_POLL_INTERVAL; currRxOverErrVar = currRxOverErr / (double) PORT_POLL_INTERVAL; currRxCrcErrVar = currRxCrcErr / (double) PORT_POLL_INTERVAL; currCollisionsVar = currCollisions / (double) PORT_POLL_INTERVAL; currRxBytePerPacketVar = currRxBytePerPacket / (double) PORT_POLL_INTERVAL; currTxBytePerPacketVar = currTxBytePerPacket / (double) PORT_POLL_INTERVAL; currRxDroppedPerPacketVar = currRxDroppedPerPacket / (double) PORT_POLL_INTERVAL; currTxDroppedPerPacketVar = currTxDroppedPerPacket / (double) PORT_POLL_INTERVAL; currRxErrorPerPacketVar = currRxErrorPerPacket / (double) PORT_POLL_INTERVAL; currTxErrorPerPacketVar = currTxErrorPerPacket / (double) PORT_POLL_INTERVAL; currRxFrameErrPerPacketVar = currRxFrameErrPerPacket / (double) PORT_POLL_INTERVAL; currRxOverErrPerPacketVar = currRxOverErrPerPacket / (double) PORT_POLL_INTERVAL; currRxCrcErrPerPacketVar = currRxCrcErrPerPacket / (double) PORT_POLL_INTERVAL; } // update or add new entry to LFT ups.setRxPacketsVar(currRxPacketsVar); ups.setTxPacketsVar(currTxPacketsVar); ups.setRxBytesVar(currRxBytesVar); ups.setTxBytesVar(currTxBytesVar); ups.setRxDroppedVar(currRxDroppedVar); ups.setTxDroppedVar(currTxDroppedVar); ups.setRxErrorsVar(currRxErrorsVar); ups.setTxErrorsVar(currTxErrorsVar); ups.setRxFrameErrVar(currRxFrameErrVar); ups.setRxOverErrVar(currRxOverErrVar); ups.setRxCrcErrVar(currRxCrcErrVar); ups.setCollisionsVar(currCollisionsVar); ups.setRxBytePerPacket(currRxBytePerPacket); ups.setRxBytePerPacketVar(currRxBytePerPacketVar); ups.setTxBytePerPacket(currTxBytePerPacket); ups.setTxBytePerPacketVar(currTxBytePerPacketVar); ups.setRxDroppedPerPacket(currRxDroppedPerPacket); ups.setRxDroppedPerPacketVar(currRxDroppedPerPacketVar); ups.setTxDroppedPerPacket(currTxDroppedPerPacket); ups.setTxDroppedPerPacketVar(currTxDroppedPerPacketVar); ups.setRxErrorPerPacket(currRxErrorPerPacket); ups.setRxErrorPerPacketVar(currRxErrorPerPacketVar); ups.setTxErrorPerPacket(currTxErrorPerPacket); ups.setTxErrorPerPacketVar(currTxErrorPerPacketVar); ups.setRxFrameErrPerPacket(currRxFrameErrPerPacket); ups.setRxFrameErrPerPacketVar(currRxFrameErrPerPacketVar); ups.setRxOverErrPerPacket(currRxOverErrPerPacket); ups.setRxOverErrPerPacket(currRxOverErrPerPacketVar); ups.setRxCrcErrPerPacket(currRxCrcErrPerPacket); ups.setRxCrcErrPerPacketVar(currRxCrcErrPerPacketVar); pStatisticsLF.remove(hashIndex); pStatisticsLF.put(hashIndex, ups); } catch (Exception e) { log.error(e.toString()); } return ups; } public UnitTableStatistics calculateTableStatsRichFeatures(BigInteger hashIndex, UnitTableStatistics uts) { try { // extract current features long currMaxEntries = uts.getMaxEntries(); long currActiveCount = uts.getActiveCount(); long currLookupCount = uts.getLookupCount(); long currMatchedCount = uts.getMatchedCount(); // calculate rich features double matchedPerLookup = 0; double activePerMax = 0; double lookupPerActive = 0; double matchedPerActive = 0; if (currLookupCount != 0) { matchedPerLookup = currMatchedCount / (double) currLookupCount; } if (currMaxEntries != 0) { activePerMax = currActiveCount / (double) currMaxEntries; } if (currActiveCount != 0) { lookupPerActive = currLookupCount / (double) currActiveCount; matchedPerActive = currMatchedCount / (double) currActiveCount; } uts.setMatchedPerLookup(matchedPerLookup); uts.setActivePerMax(activePerMax); uts.setLookupPerActive(lookupPerActive); uts.setMatchedPerActive(matchedPerActive); // tStatisticsLFT.remove(hashIndex); // tStatisticsLFT.put(hashIndex, uts); } catch (Exception e) { log.error(e.toString()); } return uts; } public UnitFlowRemovedInformation calculateFlowRemovedRichFeatures(BigInteger hashIndex, UnitFlowRemovedInformation ufri) { try { // extract current features long currPacketCount = ufri.getPacketCount(); long currByteCount = ufri.getByteCount(); double currTotalDuration = ((ufri.getDurationSec() * (long) Math.pow(10, 9)) + ufri.getDurationNsec()); // calculate rich features double packetPerDuration = 0; double bytePerDuration = 0; if (currTotalDuration != 0) { currTotalDuration /= (double) Math.pow(10, 9); packetPerDuration = currPacketCount / (double) currTotalDuration; bytePerDuration = currByteCount / (double) currTotalDuration; } ufri.setPacketPerDuration(packetPerDuration); ufri.setBytePerDuration(bytePerDuration); // frStatisticsLFT.remove(hashIndex); // frStatisticsLFT.put(hashIndex, ufri); } catch (Exception e) { log.error(e.toString()); } return ufri; } //Expiration Collector for LFT - By Jinwoo public class ExpirationCollector extends TimerTask { @Override public synchronized void run() { long lastTimeStamp; long currTimeStamp = System.currentTimeMillis(); double diffTimeStamp; try { // log.error("call ExpirationCollector!"); // for flow statistics LFT for (Entry<BigInteger, UnitFlowStatistics> obj : fStatisticsLF.entrySet()) { lastTimeStamp = obj.getValue().getTimestamp().getTime(); diffTimeStamp = (currTimeStamp - lastTimeStamp) / Math.pow(10, 3); // log.error("[FLOWLFT] diffTimeStamp: " + diffTimeStamp); if (diffTimeStamp > TIME_THRESHOLD_SECONDS) { // log.error("diffTimeStamp: " + diffTimeStamp + ", remove hashIndex: " + obj.getKey()); fStatisticsLF.remove(obj.getKey()); } } // for port statistics LFT for (Entry<BigInteger, UnitPortStatistics> obj : pStatisticsLF.entrySet()) { lastTimeStamp = obj.getValue().getTimestamp().getTime(); diffTimeStamp = (currTimeStamp - lastTimeStamp) / Math.pow(10, 3); // log.error("[PORTLFT] diffTimeStamp: " + diffTimeStamp); if (diffTimeStamp > TIME_THRESHOLD_SECONDS) { // log.error("diffTimeStamp: " + diffTimeStamp + ", remove hashIndex: " + obj.getKey()); pStatisticsLF.remove(obj.getKey()); } } } catch (Exception e) { log.error(e.toString()); } } } } // public void printFlowStatsLFT(ConcurrentHashMap<BigInteger, UnitFlowStatistics> targetLFT) { // for (Entry<BigInteger, UnitFlowStatistics> obj : targetLFT.entrySet()) { // System.out.println("[hashIndex]: " + obj.getKey() + " [value]: " // + obj.getValue().toString()); // } // System.out.println("=================================="); // } // to print out LFT for test // public void printPortStatsLFT(ConcurrentHashMap<String, UnitPortStatistics> targetLFT) { // for (Entry<String, UnitPortStatistics> obj : targetLFT.entrySet()) { // System.out.println("[hashIndex]: " + obj.getKey() + " [value]: " // + obj.getValue().toString()); // } // System.out.println("=================================="); // } // public void printTableStatsLFT(ConcurrentHashMap<String, UnitTableStatistics> targetLFT) { // for (Entry<String, UnitTableStatistics> obj : targetLFT.entrySet()) { // System.out.println("[hashIndex]: " + obj.getKey() + " [value]: " // + obj.getValue().toString()); // } // System.out.println("=================================="); // } // // public void printFlowRemovedLFT(ConcurrentHashMap<String, UnitFlowRemovedInformation> targetLFT) { // for (Entry<String, UnitFlowRemovedInformation> obj : targetLFT.entrySet()) { // System.out.println("[hashIndex]: " + obj.getKey() + " [value]: " // + obj.getValue().toString()); // } // System.out.println("=================================="); // }
45.030492
116
0.5953
c85fa199d44fd81ef2c85387c1254e4d5ba89c53
760
package io.hashimati.security; import jakarta.inject.Singleton; import org.jasypt.util.password.StrongPasswordEncryptor; @Singleton public class PasswordEncoderService implements PasswordEncoder{ private StrongPasswordEncryptor strongPasswordEncryptor = new StrongPasswordEncryptor(); @Override public String encode(String rawPassword) { return strongPasswordEncryptor.encryptPassword(rawPassword); } @Override public boolean matches(String rawPassword, String encodedPassword) { return strongPasswordEncryptor.checkPassword(rawPassword, encodedPassword); } @Override public boolean upgradeEncoding(String encodedPassword) { throw new RuntimeException("This function is not supported"); } }
30.4
92
0.775
c615fd8ba26a3ea8c86361b8be0fb4f9f84d65b5
3,003
package com.github.onlyofficehelper.ds.config; import com.github.onlyofficehelper.annotation.OnlyOfficeConfig; /** * <p> * The document section allows to change all the parameters pertaining to the document (title, url, file type, etc.). * </p> * * @author EricChen 2020/02/25 00:13 * @see <a href='https://api.onlyoffice.com/editors/config/document'>official API</a> */ @OnlyOfficeConfig(prefix = Document.PREFIX) public class Document { public static final String PREFIX = "onlyoffice.documentserver.document"; public static final String FILE_TYPE = PREFIX + ".fileType"; public static final String KEY = PREFIX + ".key"; public static final String TITLE = PREFIX + ".title"; public static final String URL = PREFIX + ".url"; /** * Defines the type of the file for the source viewed or edited document. * eg: "docx" */ private String fileType; /** * Defines the unique document identifier used for document recognition by the service. * In case the known key is sent the document will be taken from the cache. * Every time the document is edited and saved, the key must be generated anew. * The document url can be used as the key but without the special characters and the length is limited to 20 symbols. * eg:"Khirz6zTPdfd7" */ private String key; /** * Defines the desired file name for the viewed or edited document which will also be used as file name when the document is downloaded. * eg: "Example Document Title.docx" */ private String title; /** * Defines the absolute URL where the source viewed or edited document is stored. * eg: "https://example.com/url-to-example-document.docx" */ private String url; /** * The document info section allows to change additional parameters for the document (document owner, folder where the document is stored, uploading date, sharing settings). */ private Info info; /** * The document permission section allows to change the permission for the document to be edited and downloaded or not. */ private Permissions permissions; public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Info getInfo() { return info; } public void setInfo(Info info) { this.info = info; } public Permissions getPermissions() { return permissions; } public void setPermissions(Permissions permissions) { this.permissions = permissions; } }
28.330189
177
0.658342
e037c68bfebb44d2cfceae37571e6d8fa719c458
3,112
/******************************************************************************* * Copyright 2012 EMBL-EBI, Hinxton outstation * * 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 uk.ac.ebi.embl.api.entry.location; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import uk.ac.ebi.embl.api.entry.location.LocalRange; import uk.ac.ebi.embl.api.entry.location.Range; import uk.ac.ebi.embl.api.entry.location.RemoteRange; public class LocalRangeTest { @Before public void setUp() throws Exception { } @Test public void testRange() { Range range = new LocalRange(2L, 3L); assertEquals(new Long(2), range.getBeginPosition()); assertEquals(new Long(3), range.getEndPosition()); assertEquals(2, range.getLength()); assertFalse(range.isComplement()); } @Test public void testRange_Null() { Range range = new LocalRange(null, null); assertNull(range.getBeginPosition()); assertNull(range.getEndPosition()); assertEquals(0, range.getLength()); } @Test public void testSetPosition() { Range range = new LocalRange(null, null); assertNull(range.getBeginPosition()); assertNull(range.getEndPosition()); range.setBeginPosition(2L); range.setEndPosition(3L); assertEquals(new Long(2), range.getBeginPosition()); assertEquals(new Long(3), range.getEndPosition()); assertEquals(2, range.getLength()); } @Test public void testToString() { assertNotNull(new LocalRange(null, null).toString()); assertNotNull(new LocalRange(2L, 3L).toString()); } @Test public void testRangeHashCode() { new LocalRange(1L, 2L).hashCode(); } @Test public void testEquals() { Range location1 = new LocalRange(2L, 3L); assertTrue(location1.equals(location1)); Range location2 = new LocalRange(2L, 3L); assertTrue(location1.equals(location2)); assertTrue(location2.equals(location1)); assertFalse(location1.equals(new RemoteRange("y", 1, 2L, 3L))); assertFalse(location1.equals(new RemoteRange("x", 2, 2L, 3L))); assertFalse(location1.equals(new RemoteRange("x", 1, 3L, 3L))); assertFalse(location1.equals(new RemoteRange("x", 1, 2L, 4L))); assertFalse(location1.equals(new RemoteRange("x", 1, 2L, 3L, true))); } @Test public void testEquals_WrongObject() { assertFalse(new LocalRange(2L, 3L).equals(new String())); } }
32.082474
80
0.69473
e396ea5fbbedd80b99b0bf218bc68cdab0678aae
8,745
package org.jboss.resteasy.test.validation; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.resteasy.api.validation.ResteasyConstraintViolation; import org.jboss.resteasy.api.validation.ResteasyViolationException; import org.jboss.resteasy.api.validation.Validation; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.test.validation.resource.ValidationCoreClassConstraint; import org.jboss.resteasy.test.validation.resource.ValidationCoreClassValidator; import org.jboss.resteasy.test.validation.resource.ValidationCoreFoo; import org.jboss.resteasy.test.validation.resource.ValidationCoreFooConstraint; import org.jboss.resteasy.test.validation.resource.ValidationCoreFooReaderWriter; import org.jboss.resteasy.test.validation.resource.ValidationCoreFooValidator; import org.jboss.resteasy.test.validation.resource.ValidationCoreResourceWithAllViolationTypes; import org.jboss.resteasy.test.validation.resource.ValidationCoreResourceWithReturnValues; import org.jboss.resteasy.util.HttpResponseCodes; import org.jboss.resteasy.utils.PortProviderUtil; import org.jboss.resteasy.utils.TestUtil; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Response; /** * @tpSubChapter Response * @tpChapter Integration tests * @tpTestCaseDetails Test basic validation with disable executable-validation in validation.xml file. Validation should not be active. * @tpSince RESTEasy 3.0.16 */ @RunWith(Arquillian.class) @RunAsClient public class ExecutableValidationDisabledTest { static final String RESPONSE_ERROR_MSG = "Response has wrong content"; static final String WRONG_ERROR_MSG = "Expected validation error is not in response"; ResteasyClient client; @Deployment public static Archive<?> createTestArchive() { WebArchive war = TestUtil.prepareArchive(ExecutableValidationDisabledTest.class.getSimpleName()) .addClasses(ValidationCoreFoo.class, ValidationCoreFooConstraint.class, ValidationCoreFooReaderWriter.class, ValidationCoreFooValidator.class) .addClasses(ValidationCoreClassConstraint.class, ValidationCoreClassValidator.class) .addClasses(ValidationCoreResourceWithAllViolationTypes.class, ValidationCoreResourceWithReturnValues.class) .addAsResource("META-INF/services/javax.ws.rs.ext.Providers") .addAsResource(ExecutableValidationDisabledTest.class.getPackage(), "ExecutableValidationDisabledValidationDisabled.xml", "META-INF/validation.xml"); return TestUtil.finishContainerPrepare(war, null, (Class<?>[]) null); } @Before public void init() { client = new ResteasyClientBuilder().build().register(ValidationCoreFooReaderWriter.class); } @After public void after() throws Exception { client.close(); } private static String generateURL(String path) { return PortProviderUtil.generateURL(path, ExecutableValidationDisabledTest.class.getSimpleName()); } /** * @tpTestDetails Test disabled validation of returned value. * @tpSince RESTEasy 3.0.16 */ @Test public void testReturnValues() throws Exception { // Valid native constraint ValidationCoreFoo foo = new ValidationCoreFoo("a"); Response response = client.target(generateURL("/return/native")).request().post(Entity.entity(foo, "application/foo")); Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus()); Assert.assertEquals(RESPONSE_ERROR_MSG, foo, response.readEntity(ValidationCoreFoo.class)); response.close(); // Valid imposed constraint foo = new ValidationCoreFoo("abcde"); response = client.target(generateURL("/return/imposed")).request().post(Entity.entity(foo, "application/foo")); Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus()); Assert.assertEquals(RESPONSE_ERROR_MSG, foo, response.readEntity(ValidationCoreFoo.class)); response.close(); // Valid native and imposed constraints. foo = new ValidationCoreFoo("abc"); response = client.target(generateURL("/return/nativeAndImposed")).request().post(Entity.entity(foo, "application/foo")); Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus()); Assert.assertEquals(RESPONSE_ERROR_MSG, foo, response.readEntity(ValidationCoreFoo.class)); response.close(); { // Invalid native constraint // BUT EXECUTABLE VALIDATION IS DISABLE. foo = new ValidationCoreFoo("abcdef"); response = client.target(generateURL("/return/native")).request().post(Entity.entity(foo, "application/foo")); Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus()); Assert.assertEquals(RESPONSE_ERROR_MSG, foo, response.readEntity(ValidationCoreFoo.class)); response.close(); } { // Invalid imposed constraint // BUT EXECUTABLE VALIDATION IS DISABLE. foo = new ValidationCoreFoo("abcdef"); response = client.target(generateURL("/return/imposed")).request().post(Entity.entity(foo, "application/foo")); Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus()); Assert.assertEquals(RESPONSE_ERROR_MSG, foo, response.readEntity(ValidationCoreFoo.class)); response.close(); } { // Invalid native and imposed constraints // BUT EXECUTABLE VALIDATION IS DISABLE. foo = new ValidationCoreFoo("abcdef"); response = client.target(generateURL("/return/nativeAndImposed")).request().post(Entity.entity(foo, "application/foo")); Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus()); Assert.assertEquals(RESPONSE_ERROR_MSG, foo, response.readEntity(ValidationCoreFoo.class)); response.close(); } } /** * @tpTestDetails Test disabled validation before return value evaluation. * @tpSince RESTEasy 3.0.16 */ @Test public void testViolationsBeforeReturnValue() throws Exception { // Valid ValidationCoreFoo foo = new ValidationCoreFoo("pqrs"); Response response = client.target(generateURL("/all/abc/wxyz")).request().post(Entity.entity(foo, "application/foo")); Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus()); Assert.assertEquals(RESPONSE_ERROR_MSG, foo, response.readEntity(ValidationCoreFoo.class)); response.close(); // Invalid: Should have 1 each of field, property, class, and parameter violations, // and no return value violations. // BUT EXECUTABLE VALIDATION IS DISABLE. There will be no parameter violation. response = client.target(generateURL("/all/a/z")).request().post(Entity.entity(foo, "application/foo")); Assert.assertEquals(HttpResponseCodes.SC_BAD_REQUEST, response.getStatus()); String header = response.getHeaderString(Validation.VALIDATION_HEADER); Assert.assertNotNull("Missing validation header", header); Assert.assertTrue("Wrong value of validation header", Boolean.valueOf(header)); String entity = response.readEntity(String.class); ResteasyViolationException e = new ResteasyViolationException(entity); TestUtil.countViolations(e, 3, 1, 1, 1, 0, 0); ResteasyConstraintViolation violation = e.getFieldViolations().iterator().next(); Assert.assertEquals(WRONG_ERROR_MSG, "size must be between 2 and 4", violation.getMessage()); Assert.assertEquals(WRONG_ERROR_MSG, "a", violation.getValue()); violation = e.getPropertyViolations().iterator().next(); Assert.assertEquals(WRONG_ERROR_MSG, "size must be between 3 and 5", violation.getMessage()); Assert.assertEquals(WRONG_ERROR_MSG, "z", violation.getValue()); violation = e.getClassViolations().iterator().next(); Assert.assertEquals(WRONG_ERROR_MSG, "Concatenation of s and t must have length > 5", violation.getMessage()); Assert.assertTrue(WRONG_ERROR_MSG, violation.getValue().startsWith("org.jboss.resteasy.test.validation.resource.ValidationCoreResourceWithAllViolationTypes@")); response.close(); } }
53
167
0.728073
244740d44a4c609492d33a34ce5c1cfa8927f4ab
4,647
/** * The MIT License * * Copyright (c) 2020 Ilwoong Jeong (https://github.com/ilwoong) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package mockup.crypto; import java.util.Arrays; import mockup.crypto.util.ByteArray; public abstract class BufferedBlockCipher implements NamedAlgorithm { public enum CipherMode { ENCRYPT, DECRYPT } protected CipherMode cipherMode; protected BlockCipher cipher; protected byte[] buffer; protected int offset; protected int blocksize; protected int shift; private Padding padding; public void init(CipherMode mode, BlockCipher cipher, byte[] mk, byte[] iv) { this.cipherMode = mode; this.cipher = cipher; cipher.init(mk); blocksize = cipher.getBlocksize(); shift = blocksize; buffer = new byte[shift]; init(iv); } public void setPadding(Padding padding) { this.padding = padding; } protected void reset() { offset = 0; Arrays.fill(buffer, (byte) 0); restoreToInitialState(); } protected abstract void restoreToInitialState(); protected abstract void init(byte[] iv); public void setShift(int shift) { if (shift > blocksize) { throw new IllegalArgumentException("shift should be less or equal to " + blocksize); } this.shift = shift; } public byte[] update(final byte[] msg) { if (msg == null || msg.length == 0) { return null; } var msgpos = 0; var dstpos = 0; var length = msg.length; var dst = getUpdateBuffer(msg.length); if (offset > 0) { var gap = Math.min(length, shift - offset); System.arraycopy(msg, 0, buffer, offset, gap); msgpos += gap; offset += gap; length -= gap; if (offset == shift) { updateBlock(buffer, 0, dst, 0); dstpos += shift; offset = 0; } } while (length >= shift) { if ((padding != null) && (cipherMode == CipherMode.DECRYPT) && (length == shift)) { break; } updateBlock(msg, msgpos, dst, dstpos); msgpos += shift; dstpos += shift; length -= shift; } if (length > 0) { System.arraycopy(msg, msgpos, buffer, offset, length); offset += length; } return dst; } public byte[] getUpdateBuffer(int length) { var count = length + offset; if (count < shift) { return null; } if (padding != null && cipherMode == CipherMode.DECRYPT) { return new byte[count - shift]; } return new byte[count - (count % shift)]; } public abstract void updateBlock(final byte[] src, int srcpos, byte[] dst, int dstpos); public byte[] doFinal(final byte[] msg) { var head = update(msg); var tail = doFinal(); return ByteArray.merge(head, tail); } public byte[] doFinal() { return padding == null ? doFinalWithoutPadding() : doFinalWithPadding(); } private byte[] doFinalWithPadding() { byte[] dst = null; if (cipherMode == CipherMode.ENCRYPT) { var padded = padding.pad(buffer, offset); dst = new byte[padded.length]; updateBlock(padded, 0, dst, 0); // cipher.decryptBlock(padded, 0, dst, 0); } else { var padded = new byte[blocksize]; updateBlock(buffer, 0, padded, 0); // cipher.decryptBlock(buffer, 0, padded, 0); dst = padding.unpad(padded); } reset(); return dst; } private byte[] doFinalWithoutPadding() { byte[] tail = null; if (offset > 0) { var tmp = new byte[blocksize]; updateBlock(buffer, 0, tmp, 0); tail = Arrays.copyOfRange(tmp, 0, offset); offset = 0; } reset(); return tail; } }
23.953608
89
0.647084
c7f32f0704236d748da2be8997ded84e5e5e9dd6
2,563
/* * Copyright 2015 Szabolcs Balazs Beres. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.eszabre.osgi.config.scr.impl; import com.github.eszabre.osgi.config.scr.MyService; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.ConfigurationPolicy; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Modified; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.PropertyOption; import org.apache.felix.scr.annotations.Service; import java.util.Map; @Component(immediate = true, policy = ConfigurationPolicy.OPTIONAL) @Service @Properties({ @Property(name = "BoolProperty", boolValue = true, label = "myLabel"), @Property(name = "StringProperty", value = "myStringValue", options = { @PropertyOption(name = "option1", value = "optionValue1") }), @Property(name = "StringListProperty", value = "myStringValue,mystringvalue2", cardinality = Integer.MAX_VALUE), @Property(name = "PasswordProperty", passwordValue = "1234") } ) public class MyServiceImpl implements MyService { @Property(description = "Field annotated property without default value") private static final String PROPERTY_NAME = "FieldAnnotatedProperty"; @Activate public void activate(final Map<String, Object> properties) { System.out.println(this.getClass().getName() + " activated"); System.out.println("Properties: "); printMap(properties); } private void printMap(Map<String, Object> properties) { System.out.println(properties.toString()); } @Modified public void update(final Map<String, Object> properties) { System.out.println(this.getClass().getName() + " updated"); System.out.println("Properties: "); printMap(properties); } @Deactivate public void deactivate() { System.out.println(this.getClass().getName() + " deactivated"); } }
32.0375
80
0.739758