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
d8d3def95316ab280175264755ebd93a31cb1574
17,677
package io.antmedia.statistic; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.LongSerializer; import org.apache.kafka.common.serialization.StringSerializer; import org.bytedeco.javacpp.Pointer; import org.red5.server.Launcher; import org.red5.server.api.IServer; import org.red5.server.api.listeners.IScopeListener; import org.red5.server.api.scope.IScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContextAware; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import io.antmedia.IResourceMonitor; import io.antmedia.SystemUtils; import io.antmedia.rest.WebRTCClientStats; import io.antmedia.statistic.GPUUtils.MemoryStatus; import io.antmedia.webrtc.api.IWebRTCAdaptor; import io.vertx.core.Vertx; public class ResourceMonitor implements IResourceMonitor, ApplicationContextAware { public static final String IN_USE_SWAP_SPACE = "inUseSwapSpace"; public static final String FREE_SWAP_SPACE = "freeSwapSpace"; public static final String TOTAL_SWAP_SPACE = "totalSwapSpace"; public static final String VIRTUAL_MEMORY = "virtualMemory"; public static final String PROCESSOR_COUNT = "processorCount"; public static final String JAVA_VERSION = "javaVersion"; public static final String OS_ARCH = "osArch"; public static final String OS_NAME = "osName"; public static final String IN_USE_SPACE = "inUseSpace"; public static final String FREE_SPACE = "freeSpace"; public static final String TOTAL_SPACE = "totalSpace"; public static final String USABLE_SPACE = "usableSpace"; public static final String IN_USE_MEMORY = "inUseMemory"; public static final String FREE_MEMORY = "freeMemory"; public static final String TOTAL_MEMORY = "totalMemory"; public static final String MAX_MEMORY = "maxMemory"; public static final String PROCESS_CPU_LOAD = "processCPULoad"; public static final String SYSTEM_CPU_LOAD = "systemCPULoad"; public static final String PROCESS_CPU_TIME = "processCPUTime"; public static final String CPU_USAGE = "cpuUsage"; public static final String INSTANCE_ID = "instanceId"; public static final String JVM_MEMORY_USAGE = "jvmMemoryUsage"; public static final String SYSTEM_INFO = "systemInfo"; public static final String SYSTEM_MEMORY_INFO = "systemMemoryInfo"; public static final String FILE_SYSTEM_INFO = "fileSystemInfo"; public static final String GPU_UTILIZATION = "gpuUtilization"; public static final String GPU_DEVICE_INDEX = "index"; public static final String GPU_MEMORY_UTILIZATION = "memoryUtilization"; public static final String GPU_MEMORY_TOTAL = "memoryTotal"; public static final String GPU_MEMORY_FREE = "memoryFree"; public static final String GPU_MEMORY_USED = "memoryUsed"; public static final String GPU_DEVICE_NAME = "deviceName"; public static final String GPU_USAGE_INFO = "gpuUsageInfo"; public static final String TOTAL_LIVE_STREAMS = "totalLiveStreamSize"; public static final String LOCAL_WEBRTC_LIVE_STREAMS = "localWebRTCLiveStreams"; public static final String LOCAL_WEBRTC_VIEWERS = "localWebRTCViewers"; public static final String LOCAL_HLS_VIEWERS = "localHLSViewers"; private static final String TIME = "time"; protected static final Logger logger = LoggerFactory.getLogger(ResourceMonitor.class); private static final String MEASURED_BITRATE = "measured_bitrate"; private static final String SEND_BITRATE = "send_bitrate"; private static final String AUDIO_FRAME_SEND_PERIOD = "audio_frame_send_period"; private static final String VIDEO_FRAME_SEND_PERIOD = "video_frame_send_period"; private static final String STREAM_ID = "streamId"; private static final String WEBRTC_CLIENT_ID = "webrtcClientId"; private ConcurrentLinkedQueue<IScope> scopes = new ConcurrentLinkedQueue<>(); @Autowired private Vertx vertx; private Queue<Integer> cpuMeasurements = new ConcurrentLinkedQueue<>(); Gson gson = new Gson(); private int windowSize = 5; private int measurementPeriod = 5000; private int staticSendPeriod = 15000; private int cpuLoad; private int cpuLimit = 70; /** * Min Free Ram Size that free memory should be always more than min */ private int minFreeRamSize = 20; private String kafkaBrokers = null; public static final String INSTANCE_STATS_TOPIC_NAME = "ams-instance-stats"; public static final String WEBRTC_STATS_TOPIC_NAME = "ams-webrtc-stats"; private Producer<Long,String> kafkaProducer = null; private long cpuMeasurementTimerId = -1; private long kafkaTimerId = -1; public void start() { cpuMeasurementTimerId = getVertx().setPeriodic(measurementPeriod, l -> addCpuMeasurement(SystemUtils.getSystemCpuLoad())); startKafkaProducer(); } private void startKafkaProducer() { if (kafkaBrokers != null && !kafkaBrokers.isEmpty()) { kafkaProducer = createKafkaProducer(); kafkaTimerId = getVertx().setPeriodic(staticSendPeriod, l -> { sendInstanceStats(scopes); sendWebRTCClientStats(); }); } } private void sendWebRTCClientStats() { getVertx().executeBlocking( b -> { collectAndSendWebRTCClientsStats(); b.complete(); }, r -> { }); } public void collectAndSendWebRTCClientsStats() { for (Iterator<IScope> iterator = scopes.iterator(); iterator.hasNext();) { IScope scope = iterator.next(); if( scope.getContext().getApplicationContext().containsBean(IWebRTCAdaptor.BEAN_NAME)) { IWebRTCAdaptor webrtcAdaptor = (IWebRTCAdaptor)scope.getContext().getApplicationContext().getBean(IWebRTCAdaptor.BEAN_NAME); Set<String> streams = webrtcAdaptor.getStreams(); List<WebRTCClientStats> webRTCClientStats; for (String streamId : streams) { webRTCClientStats = webrtcAdaptor.getWebRTCClientStats(streamId); sendWebRTCClientStats2Kafka(webRTCClientStats, streamId); } } } } public void sendWebRTCClientStats2Kafka(List<WebRTCClientStats> webRTCClientStatList, String streamId) { JsonObject jsonObject; String dateTime = DateTimeFormatter.ISO_INSTANT.format(Instant.now()); for (WebRTCClientStats webRTCClientStat : webRTCClientStatList) { jsonObject = new JsonObject(); jsonObject.addProperty(STREAM_ID, streamId); jsonObject.addProperty(WEBRTC_CLIENT_ID, webRTCClientStat.getClientId()); jsonObject.addProperty(AUDIO_FRAME_SEND_PERIOD, (int)webRTCClientStat.getAudioFrameSendPeriod()); jsonObject.addProperty(VIDEO_FRAME_SEND_PERIOD, (int)webRTCClientStat.getVideoFrameSendPeriod()); jsonObject.addProperty(MEASURED_BITRATE, webRTCClientStat.getMeasuredBitrate()); jsonObject.addProperty(SEND_BITRATE, webRTCClientStat.getSendBitrate()); jsonObject.addProperty(TIME, dateTime); //logstash cannot parse json array so that we send each info separately send2Kafka(jsonObject, WEBRTC_STATS_TOPIC_NAME); } } public Producer<Long, String> createKafkaProducer() { Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaBrokers); props.put(ProducerConfig.CLIENT_ID_CONFIG, Launcher.getInstanceId()); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); return new KafkaProducer<>(props); } public static JsonObject getFileSystemInfoJSObject() { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty(USABLE_SPACE, SystemUtils.osHDUsableSpace(null,"B", false)); jsonObject.addProperty(TOTAL_SPACE, SystemUtils.osHDTotalSpace(null, "B", false)); jsonObject.addProperty(FREE_SPACE, SystemUtils.osHDFreeSpace(null, "B", false)); jsonObject.addProperty(IN_USE_SPACE, SystemUtils.osHDInUseSpace(null, "B", false)); return jsonObject; } public static JsonObject getGPUInfoJSObject(int deviceIndex, GPUUtils gpuUtils) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty(GPU_DEVICE_INDEX, deviceIndex); jsonObject.addProperty(GPU_UTILIZATION, gpuUtils.getGPUUtilization(deviceIndex)); jsonObject.addProperty(GPU_MEMORY_UTILIZATION, gpuUtils.getMemoryUtilization(deviceIndex)); MemoryStatus memoryStatus = gpuUtils.getMemoryStatus(deviceIndex); jsonObject.addProperty(GPU_MEMORY_TOTAL, memoryStatus.getMemoryTotal()); jsonObject.addProperty(GPU_MEMORY_FREE, memoryStatus.getMemoryFree()); jsonObject.addProperty(GPU_MEMORY_USED, memoryStatus.getMemoryUsed()); jsonObject.addProperty(GPU_DEVICE_NAME, GPUUtils.getInstance().getDeviceName(deviceIndex)); return jsonObject; } public static JsonArray getGPUInfoJSObject() { int deviceCount = GPUUtils.getInstance().getDeviceCount(); JsonArray jsonArray = new JsonArray(); if (deviceCount > 0) { for (int i=0; i < deviceCount; i++) { jsonArray.add(getGPUInfoJSObject(i, GPUUtils.getInstance())); } } return jsonArray; } public static JsonObject getCPUInfoJSObject() { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty(PROCESS_CPU_TIME, SystemUtils.getProcessCpuTime()); jsonObject.addProperty(SYSTEM_CPU_LOAD, SystemUtils.getSystemCpuLoad()); jsonObject.addProperty(PROCESS_CPU_LOAD, SystemUtils.getProcessCpuLoad()); return jsonObject; } public static JsonObject getJVMMemoryInfoJSObject() { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty(MAX_MEMORY, SystemUtils.jvmMaxMemory("B", false)); jsonObject.addProperty(TOTAL_MEMORY, SystemUtils.jvmTotalMemory("B", false)); jsonObject.addProperty(FREE_MEMORY, SystemUtils.jvmFreeMemory("B", false)); jsonObject.addProperty(IN_USE_MEMORY, SystemUtils.jvmInUseMemory("B", false)); return jsonObject; } public static JsonObject getSystemInfoJSObject() { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty(OS_NAME, SystemUtils.osName); jsonObject.addProperty(OS_ARCH, SystemUtils.osArch); jsonObject.addProperty(JAVA_VERSION, SystemUtils.jvmVersion); jsonObject.addProperty(PROCESSOR_COUNT, SystemUtils.osProcessorX); return jsonObject; } public static JsonObject getSysteMemoryInfoJSObject() { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty(VIRTUAL_MEMORY, SystemUtils.osCommittedVirtualMemory("B", false)); jsonObject.addProperty(TOTAL_MEMORY, SystemUtils.osTotalPhysicalMemory("B", false)); jsonObject.addProperty(FREE_MEMORY, SystemUtils.osFreePhysicalMemory("B", false)); jsonObject.addProperty(IN_USE_MEMORY, SystemUtils.osInUsePhysicalMemory("B", false)); jsonObject.addProperty(TOTAL_SWAP_SPACE, SystemUtils.osTotalSwapSpace("B", false)); jsonObject.addProperty(FREE_SWAP_SPACE, SystemUtils.osFreeSwapSpace("B", false)); jsonObject.addProperty(IN_USE_SWAP_SPACE, SystemUtils.osInUseSwapSpace("B", false)); return jsonObject; } public static JsonObject getSystemResourcesInfo(Queue<IScope> scopes) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty(INSTANCE_ID, Launcher.getInstanceId()); jsonObject.add(CPU_USAGE, getCPUInfoJSObject()); jsonObject.add(JVM_MEMORY_USAGE, getJVMMemoryInfoJSObject()); jsonObject.add(SYSTEM_INFO, getSystemInfoJSObject()); jsonObject.add(SYSTEM_MEMORY_INFO, getSysteMemoryInfoJSObject()); jsonObject.add(FILE_SYSTEM_INFO, getFileSystemInfoJSObject()); //add gpu info jsonObject.add(ResourceMonitor.GPU_USAGE_INFO, ResourceMonitor.getGPUInfoJSObject()); int localHlsViewers = 0; int localWebRTCViewers = 0; int localWebRTCStreams = 0; if (scopes != null) { for (Iterator<IScope> iterator = scopes.iterator(); iterator.hasNext();) { IScope scope = iterator.next(); localHlsViewers += getHLSViewers(scope); if( scope.getContext().getApplicationContext().containsBean(IWebRTCAdaptor.BEAN_NAME)) { IWebRTCAdaptor webrtcAdaptor = (IWebRTCAdaptor)scope.getContext().getApplicationContext().getBean(IWebRTCAdaptor.BEAN_NAME); localWebRTCViewers += webrtcAdaptor.getNumberOfTotalViewers(); localWebRTCStreams += webrtcAdaptor.getNumberOfLiveStreams(); } } } //add local webrtc viewer size jsonObject.addProperty(ResourceMonitor.LOCAL_WEBRTC_LIVE_STREAMS, localWebRTCStreams); jsonObject.addProperty(ResourceMonitor.LOCAL_WEBRTC_VIEWERS, localWebRTCViewers); jsonObject.addProperty(ResourceMonitor.LOCAL_HLS_VIEWERS, localHlsViewers); return jsonObject; } private static int getHLSViewers(IScope scope) { if (scope.getContext().getApplicationContext().containsBean(HlsViewerStats.BEAN_NAME)) { HlsViewerStats hlsViewerStats = (HlsViewerStats) scope.getContext().getApplicationContext().getBean(HlsViewerStats.BEAN_NAME); if (hlsViewerStats != null) { return hlsViewerStats.getTotalViewerCount(); } } return 0; } public void sendInstanceStats(Queue<IScope> scopes) { JsonObject jsonObject = getSystemResourcesInfo(scopes); jsonObject.addProperty(TIME, DateTimeFormatter.ISO_INSTANT.format(Instant.now())); send2Kafka(jsonObject, INSTANCE_STATS_TOPIC_NAME); } public void send2Kafka(JsonElement jsonElement, String topicName) { ProducerRecord<Long, String> record = new ProducerRecord<>(topicName, gson.toJson(jsonElement)); try { kafkaProducer.send(record).get(); } catch (ExecutionException e) { logger.error(ExceptionUtils.getStackTrace(e)); } catch (InterruptedException e) { logger.error(ExceptionUtils.getStackTrace(e)); Thread.currentThread().interrupt(); } } public void addCpuMeasurement(int measurment) { cpuMeasurements.add(measurment); if(cpuMeasurements.size() > windowSize) { cpuMeasurements.poll(); } int total = 0; for (int msrmnt : cpuMeasurements) { total += msrmnt; } cpuLoad = total/cpuMeasurements.size(); } @Override public boolean enoughResource(){ boolean enoughResource = false; if(cpuLoad < cpuLimit) { long freeJvmRamValue = getFreeRam(); if (freeJvmRamValue > minFreeRamSize) { long maxPhysicalBytes = Pointer.maxPhysicalBytes(); long physicalBytes = Pointer.physicalBytes(); if (maxPhysicalBytes > 0) { long freeNativeMemory = SystemUtils.convertByteSize(maxPhysicalBytes - physicalBytes, "MB"); if (freeNativeMemory > minFreeRamSize ) { enoughResource = true; } else { logger.error("Not enough resource. Due to no enough native memory. Current free memory:{} min free memory:{}", freeNativeMemory, minFreeRamSize); } } else { //if maxPhysicalBytes is not reported, just proceed enoughResource = true; } } else { logger.error("Not enough resource. Due to not free RAM. Free RAM should be more than {} but it is: {}", minFreeRamSize, freeJvmRamValue); } } else { logger.error("Not enough resource. Due to high cpu load: {} cpu limit: {}", cpuLoad, cpuLimit); } return enoughResource; } @Override public int getFreeRam() { //return the allocatable free ram which means max memory - inuse memory //inuse memory means total memory - free memory long inuseMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); return (int)SystemUtils.convertByteSize(Runtime.getRuntime().maxMemory() - inuseMemory, "MB"); } @Override public int getMinFreeRamSize() { return minFreeRamSize; } public void setMinFreeRamSize(int ramLimit) { this.minFreeRamSize = ramLimit; } public void setCpuLoad(int cpuLoad) { this.cpuLoad = cpuLoad; } @Override public int getCpuLoad() { return cpuLoad; } public int getWindowSize() { return windowSize; } public void setWindowSize(int windowSize) { this.windowSize = windowSize; } public Vertx getVertx() { return vertx; } public void setVertx(Vertx vertx) { this.vertx = vertx; } public void setCpuLimit(int cpuLimit) { if (cpuLimit > 100) { this.cpuLimit = 100; } else if (cpuLimit < 10) { this.cpuLimit = 10; } else { this.cpuLimit = cpuLimit; } } @Override public int getCpuLimit() { return cpuLimit; } @Override public void setApplicationContext(org.springframework.context.ApplicationContext applicationContext) throws BeansException { IServer server = (IServer) applicationContext.getBean(IServer.ID); server.addListener(new IScopeListener() { @Override public void notifyScopeRemoved(IScope scope) { scopes.remove(scope); } @Override public void notifyScopeCreated(IScope scope) { scopes.add(scope); } }); } public int getStaticSendPeriod() { return staticSendPeriod; } public void setStaticSendPeriod(int staticSendPeriod) { this.staticSendPeriod = staticSendPeriod; } public void setKafkaProducer(Producer<Long, String> kafkaProducer) { this.kafkaProducer = kafkaProducer; } public String getKafkaBrokers() { return kafkaBrokers; } public void setKafkaBrokers(String kafkaBrokers) { this.kafkaBrokers = kafkaBrokers; } public void setScopes(ConcurrentLinkedQueue<IScope> scopes) { this.scopes = scopes; } }
31.907942
151
0.768796
d1a4ab59275adcd7d14e7aa2b4a5f630b2030d2d
311
package com.knits.kncare.repository; import com.knits.kncare.model.PracticeAttachment; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface PracticeAttachmentRepository extends JpaRepository<PracticeAttachment, Long> { }
31.1
95
0.858521
a8938308815c101bf1997c313a790fd3b675b4fb
1,652
package com.lzq.echarts.series; import com.lzq.echarts.code.Orient; import com.lzq.echarts.code.SeriesType; import com.lzq.echarts.style.ItemStyle; import lombok.Getter; import lombok.Setter; /** * 『箱形图』、『盒须图』、『盒式图』、『盒状图』、『箱线图』 * * @author lizhiqiang */ @Getter @Setter public class Boxplot extends Series<Boxplot> { /** * 布局方式 */ private Orient layout; /** * box 的宽度的上下限。数组的意思是:[min, max] */ private Object[] boxWidth; /** * boxplot 图形样式,有 normal 和 emphasis 两个状态,normal 是图形正常的样式,emphasis 是图形高亮的样式,比如鼠标悬浮或者图例联动高亮的时候会使用 emphasis 作为图形的样式 */ private ItemStyle itemStyle; /** * 构造函数 */ public Boxplot() { this.type(SeriesType.boxplot); } /** * 构造函数,参数:name * * @param name */ public Boxplot(String name) { super(name); this.type(SeriesType.boxplot); } public Orient layout() { return this.layout; } public Boxplot layout(Orient layout) { this.layout = layout; return this; } public Object[] boxWidth() { return this.boxWidth; } public Boxplot boxWidth(Object[] boxWidth) { this.boxWidth = boxWidth; return this; } public Boxplot boxWidth(Object min, Object max) { this.boxWidth = new Object[]{min, max}; return this; } public ItemStyle itemStyle() { if (this.itemStyle == null) { this.itemStyle = new ItemStyle(); } return this.itemStyle; } public Boxplot itemStyle(ItemStyle itemStyle) { this.itemStyle = itemStyle; return this; } }
19.435294
116
0.588378
14d6098eba006d19ff3a6bb2bb3875304e5e16ba
2,303
/******************************************************************************* * 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.core.internal.startup; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.caleydo.core.startup.IStartupAddon; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.RegistryFactory; import com.google.common.base.Strings; import com.google.common.collect.Maps; /** * @author Samuel Gratzl * */ public class StartupAddons { private static final String EXTENSION_POINT = "org.caleydo.core.StartupAddon"; public static Map<String, IStartupAddon> findAll() { List<StartupAddonDesc> tmp = new ArrayList<>(); try { for (IConfigurationElement elem : RegistryFactory.getRegistry().getConfigurationElementsFor(EXTENSION_POINT)) { final Object o = elem.createExecutableExtension("class"); if (o instanceof IStartupAddon) { String orderS = elem.getAttribute("order"); int order = Strings.isNullOrEmpty(orderS) ? 10 : Integer.parseInt(orderS); tmp.add(new StartupAddonDesc(elem.getAttribute("name"), (IStartupAddon) o, order)); } } } catch (CoreException e) { System.err.println("can't find implementations of " + EXTENSION_POINT + " : " + "name"); e.printStackTrace(); } // sort by order Collections.sort(tmp); Map<String, IStartupAddon> factories = Maps.newLinkedHashMap(); for(StartupAddonDesc desc : tmp) factories.put(desc.label, desc.addon); return Collections.unmodifiableMap(factories); } private static class StartupAddonDesc implements Comparable<StartupAddonDesc> { private final String label; private final IStartupAddon addon; private final int order; public StartupAddonDesc(String label, IStartupAddon addon, int order) { this.label = label; this.addon = addon; this.order = order; } @Override public int compareTo(StartupAddonDesc o) { return order - o.order; } } }
33.376812
114
0.691272
98fb26850f53d4f60602e5072bc12c69dd7ea593
3,877
/* Copyright 2017 Petr Michalík 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.alej.michalik.totp.client; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Properties; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.Timer; import org.apache.commons.codec.binary.Base32; import cz.alej.michalik.totp.util.TOTP; /** * Panel pro záznam s TOTP kódem * * @author Petr Michalík * */ @SuppressWarnings("serial") public class OtpPanel extends JPanel { Clip clip = new Clip(); /** * Přidá jeden panel se záznamem * * @param raw_data * Data z Properties * @param p * Properties * @param index * Index záznamu - pro vymazání */ public OtpPanel(String raw_data, final Properties p, final int index) { // Data jsou oddělena středníkem final String[] data = raw_data.split(";"); // this.setBackground(App.COLOR); this.setLayout(new GridBagLayout()); // Mřížkové rozložení prvků GridBagConstraints c = new GridBagConstraints(); this.setMaximumSize(new Dimension(Integer.MAX_VALUE, 100)); // Tlačítko pro zkopírování hesla final JButton passPanel = new JButton(""); passPanel.setFont(passPanel.getFont().deriveFont(App.FONT_SIZE)); passPanel.setBackground(App.COLOR); // Zabere celou šířku c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 100; this.add(passPanel, c); passPanel.setText(data[0]); // Tlačítko pro smazání JButton delete = new JButton("X"); try { String path = "/material-design-icons/action/drawable-xhdpi/ic_delete_black_24dp.png"; Image img = ImageIO.read(App.class.getResource(path)); delete.setIcon(new ImageIcon(img)); delete.setText(""); } catch (Exception e) { System.out.println("Icon not found"); } delete.setFont(delete.getFont().deriveFont(App.FONT_SIZE)); delete.setBackground(App.COLOR); // Zabere kousek vpravo c.fill = GridBagConstraints.NONE; c.weightx = 0.5; c.anchor = GridBagConstraints.EAST; this.add(delete, c); // Akce pro vytvoření a zkopírování hesla do schránky passPanel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Generuji kod pro " + data[1]); System.out.println(new Base32().decode(data[1].getBytes()).length); clip.set(new TOTP(new Base32().decode(data[1].getBytes())).toString()); System.out.printf("Kód pro %s je ve schránce\n", data[0]); passPanel.setText("Zkopírováno"); // Zobrazí zprávu na 1 vteřinu int time = 1000; // Animace zobrazení zprávy po zkopírování final Timer t = new Timer(time, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { passPanel.setText(data[0]); } }); t.start(); t.setRepeats(false); } }); // Akce pro smazání panelu a uložení změn delete.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.printf("Odstraněn %s s indexem %d\n", data[0], index); p.remove(String.valueOf(index)); App.saveProperties(); App.loadProperties(); } }); } }
29.371212
89
0.7057
aca64b8396f9146b36afaadcd446aabeca469e2f
7,997
/* * * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.engine.set; import static com.netflix.hollow.core.HollowConstants.ORDINAL_NONE; import com.netflix.hollow.core.index.key.HollowPrimaryKeyValueDeriver; import com.netflix.hollow.core.memory.encoding.HashCodes; import com.netflix.hollow.core.read.engine.SetMapKeyHasher; import com.netflix.hollow.tools.checksum.HollowChecksum; import java.util.BitSet; class HollowSetTypeReadStateShard { private HollowSetTypeDataElements currentData; private volatile HollowSetTypeDataElements currentDataVolatile; private HollowPrimaryKeyValueDeriver keyDeriver; public int size(int ordinal) { HollowSetTypeDataElements currentData; int size; do { currentData = this.currentData; size = (int)currentData.setPointerAndSizeArray.getElementValue((long)(ordinal * currentData.bitsPerFixedLengthSetPortion) + currentData.bitsPerSetPointer, currentData.bitsPerSetSizeValue); } while(readWasUnsafe(currentData)); return size; } public boolean contains(int ordinal, int value, int hashCode) { HollowSetTypeDataElements currentData; boolean foundData; threadsafe: do { long startBucket; long endBucket; do { currentData = this.currentData; startBucket = getAbsoluteBucketStart(currentData, ordinal); endBucket = currentData.setPointerAndSizeArray.getElementValue((long)ordinal * currentData.bitsPerFixedLengthSetPortion, currentData.bitsPerSetPointer); } while(readWasUnsafe(currentData)); hashCode = HashCodes.hashInt(hashCode); long bucket = startBucket + (hashCode & (endBucket - startBucket - 1)); int bucketOrdinal = absoluteBucketValue(currentData, bucket); while(bucketOrdinal != currentData.emptyBucketValue) { if(bucketOrdinal == value) { foundData = true; continue threadsafe; } bucket++; if(bucket == endBucket) bucket = startBucket; bucketOrdinal = absoluteBucketValue(currentData, bucket); } foundData = false; } while(readWasUnsafe(currentData)); return foundData; } public int findElement(int ordinal, Object... hashKey) { int hashCode = SetMapKeyHasher.hash(hashKey, keyDeriver.getFieldTypes()); HollowSetTypeDataElements currentData; threadsafe: do { long startBucket; long endBucket; do { currentData = this.currentData; startBucket = getAbsoluteBucketStart(currentData, ordinal); endBucket = currentData.setPointerAndSizeArray.getElementValue((long)ordinal * currentData.bitsPerFixedLengthSetPortion, currentData.bitsPerSetPointer); } while(readWasUnsafe(currentData)); long bucket = startBucket + (hashCode & (endBucket - startBucket - 1)); int bucketOrdinal = absoluteBucketValue(currentData, bucket); while(bucketOrdinal != currentData.emptyBucketValue) { if(readWasUnsafe(currentData)) continue threadsafe; if(keyDeriver.keyMatches(bucketOrdinal, hashKey)) return bucketOrdinal; bucket++; if(bucket == endBucket) bucket = startBucket; bucketOrdinal = absoluteBucketValue(currentData, bucket); } } while(readWasUnsafe(currentData)); return ORDINAL_NONE; } public int relativeBucketValue(int setOrdinal, int bucketIndex) { HollowSetTypeDataElements currentData; int value; do { long startBucket; do { currentData = this.currentData; startBucket = getAbsoluteBucketStart(currentData, setOrdinal); } while(readWasUnsafe(currentData)); value = absoluteBucketValue(currentData, startBucket + bucketIndex); if(value == currentData.emptyBucketValue) value = ORDINAL_NONE; } while(readWasUnsafe(currentData)); return value; } private long getAbsoluteBucketStart(HollowSetTypeDataElements currentData, int ordinal) { return ordinal == 0 ? 0 : currentData.setPointerAndSizeArray.getElementValue((long)(ordinal - 1) * currentData.bitsPerFixedLengthSetPortion, currentData.bitsPerSetPointer); } private int absoluteBucketValue(HollowSetTypeDataElements currentData, long absoluteBucketIndex) { return (int)currentData.elementArray.getElementValue(absoluteBucketIndex * currentData.bitsPerElement, currentData.bitsPerElement); } void invalidate() { setCurrentData(null); } HollowSetTypeDataElements currentDataElements() { return currentData; } private boolean readWasUnsafe(HollowSetTypeDataElements data) { return data != currentDataVolatile; } void setCurrentData(HollowSetTypeDataElements data) { this.currentData = data; this.currentDataVolatile = data; } protected void applyToChecksum(HollowChecksum checksum, BitSet populatedOrdinals, int shardNumber, int numShards) { int ordinal = populatedOrdinals.nextSetBit(0); while(ordinal != ORDINAL_NONE) { if((ordinal & (numShards - 1)) == shardNumber) { int shardOrdinal = ordinal / numShards; int numBuckets = HashCodes.hashTableSize(size(shardOrdinal)); long offset = getAbsoluteBucketStart(currentData, shardOrdinal); checksum.applyInt(ordinal); for(int i=0;i<numBuckets;i++) { int bucketValue = absoluteBucketValue(currentData, offset + i); if(bucketValue != currentData.emptyBucketValue) { checksum.applyInt(i); checksum.applyInt(bucketValue); } } } ordinal = populatedOrdinals.nextSetBit(ordinal + 1); } } public long getApproximateHeapFootprintInBytes() { long requiredBitsForSetPointers = (long)currentData.bitsPerFixedLengthSetPortion * (currentData.maxOrdinal + 1); long requiredBitsForBuckets = (long)currentData.bitsPerElement * currentData.totalNumberOfBuckets; long requiredBits = requiredBitsForSetPointers + requiredBitsForBuckets; return requiredBits / 8; } public long getApproximateHoleCostInBytes(BitSet populatedOrdinals, int shardNumber, int numShards) { long holeBits = 0; int holeOrdinal = populatedOrdinals.nextClearBit(0); while(holeOrdinal <= currentData.maxOrdinal) { if((holeOrdinal & (numShards - 1)) == shardNumber) holeBits += currentData.bitsPerFixedLengthSetPortion; holeOrdinal = populatedOrdinals.nextClearBit(holeOrdinal + 1); } return holeBits / 8; } public void setKeyDeriver(HollowPrimaryKeyValueDeriver keyDeriver) { this.keyDeriver = keyDeriver; } }
37.195349
200
0.644992
2573466a1acb1b53fbd713b33e3f5e524e0513c8
1,986
/** * Copyright to the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. */ package moxy.impl; import moxy.MoxyListener; import java.net.Socket; public class RelayInfo { private Socket listener; private Socket routeTo; private ReadAndSendDataThread listenerToRouteTo; private ReadAndSendDataThread routeToToListener; public RelayInfo(Socket listener, Socket routeTo) { this.listener = listener; this.routeTo = routeTo; } public void startRelaying(final MoxyListener dispatchListener) { listenerToRouteTo = new ReadAndSendDataThread(listener, routeTo) { protected void sentData(byte[] data) { dispatchListener.sentData(listener.getLocalPort(), routeTo.getRemoteSocketAddress(), data); } protected void threadDied() { stopRelaying(); } }; routeToToListener = new ReadAndSendDataThread(routeTo, listener) { protected void sentData(byte[] data) { dispatchListener.receivedData(listener.getLocalPort(), routeTo.getRemoteSocketAddress(), data); } protected void threadDied() { stopRelaying(); } }; listenerToRouteTo.start(); routeToToListener.start(); } public void stopRelaying() { ThreadKiller.killAndWait(listenerToRouteTo); ThreadKiller.killAndWait(routeToToListener); } }
33.661017
111
0.674723
bcd3e0fd63c7a10769469793d7d67380f05e2397
1,941
/* * Copyright (C) 2015 Mesosphere, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package contains defines a client used to interact with a Mesos HTTP API such as the * <a href="https://github.com/apache/mesos/blob/master/docs/scheduler-http-api.md" target="_blank">Scheduler HTTP API</a>. * * <h2>Design</h2> * This library is designed to allow a user to interact with Mesos by defining a function that receives a stream * ({@link rx.Observable Observable}) of * <a href="https://github.com/apache/mesos/blob/master/docs/scheduler-http-api.md#events" target="_blank">Events</a> * from Mesos potentially emitting events of it's own that will be sent to Mesos. * <p> * However this function is implemented doesn't matter to the library, as long as the function contract is upheld. * <p> * This module is ignorant of the actual messages being sent and received from Mesos and the serialization mechanism * used. Instead, the user provides a {@link com.mesosphere.mesos.rx.java.util.MessageCodec MessageCodec} for each * of the corresponding messages. The advantage of this is that the client can stay buffered from message changes * made my Mesos as well as serialization used (the package * <a href="protobuf/package-summary.html">com.mesosphere.mesos.rx.java.protobuf</a> provides the codecs necessary to use * protobuf when connecting to mesos). */ package com.mesosphere.mesos.rx.java;
53.916667
123
0.750644
6b896720c5881a245365d6d5e081a2f778ca44bf
5,991
package beenalongday.lenslauncher.util; import android.app.Application; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.graphics.Rect; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.content.ContextCompat; import android.view.View; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import beenalongday.lenslauncher.R; import beenalongday.lenslauncher.background.BroadcastReceivers; import beenalongday.lenslauncher.model.App; import beenalongday.lenslauncher.model.AppPersistent; /** * Created by beenalongday on 2016/04/02. */ public class AppUtil { private static final String TAG = AppUtil.class.getSimpleName(); // Get all available apps for launcher public static ArrayList<App> getApps( PackageManager packageManager, Context context, Application application, String iconPackLabelName, AppSorter.SortType sortType) { ArrayList<App> apps = new ArrayList<>(); Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.addCategory(Intent.CATEGORY_LAUNCHER); List<ResolveInfo> availableActivities = null; try { availableActivities = packageManager.queryIntentActivities(intent, 0); } catch (RuntimeException e) { e.printStackTrace(); Toast.makeText(context, R.string.error_too_many_apps, Toast.LENGTH_SHORT).show(); } if (availableActivities != null) { IconPackManager.IconPack selectedIconPack = null; ArrayList<IconPackManager.IconPack> iconPacks = new IconPackManager().getAvailableIconPacksWithIcons(true, application); for (IconPackManager.IconPack iconPack : iconPacks) { if (iconPack.mName.equals(iconPackLabelName)) selectedIconPack = iconPack; } for (int i = 0; i < availableActivities.size(); i++) { ResolveInfo resolveInfo = availableActivities.get(i); App app = new App(); app.setId(i); try { app.setInstallDate(packageManager.getPackageInfo(resolveInfo.activityInfo.packageName, 0).firstInstallTime); } catch (PackageManager.NameNotFoundException e) { app.setInstallDate(0); } app.setLabel(resolveInfo.loadLabel(packageManager)); app.setPackageName(resolveInfo.activityInfo.packageName); app.setName(resolveInfo.activityInfo.name); app.setIconResId(resolveInfo.activityInfo.getIconResource()); Bitmap defaultBitmap = BitmapUtil.packageNameToBitmap( context, packageManager, resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.getIconResource()); if (selectedIconPack != null) app.setIcon(selectedIconPack.getIconForPackage(app.getPackageName().toString(), defaultBitmap)); else app.setIcon(defaultBitmap); app.setPaletteColor(ColorUtil.getPaletteColorFromApp(app)); apps.add(app); } } AppSorter.sort(apps, sortType); return apps; } // Launch apps, for launcher :-P public static void launchComponent(Context context, String packageName, String name, View view, Rect bounds) { if (packageName != null && name != null) { Intent componentIntent = new Intent(); componentIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); componentIntent.setComponent(new ComponentName(packageName, name)); if (!packageName.equals("beenalongday.lenslauncher")) { componentIntent.setAction(Intent.ACTION_MAIN); } componentIntent.addCategory(Intent.CATEGORY_LAUNCHER); try { // Launch Component ContextCompat.startActivity(context, componentIntent, getLauncherOptionsBundle(context, view, bounds)); // Increment app open count AppPersistent.incrementAppCount(packageName, name); // Resort apps (if open count selected) Settings settings = new Settings(context); if (settings.getSortType() == AppSorter.SortType.OPEN_COUNT_ASCENDING || settings.getSortType() == AppSorter.SortType.OPEN_COUNT_DESCENDING) { Intent editAppsIntent = new Intent(context, BroadcastReceivers.AppsEditedReceiver.class); context.sendBroadcast(editAppsIntent); } } catch (ActivityNotFoundException e) { Toast.makeText(context, R.string.error_app_not_found, Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(context, R.string.error_app_not_found, Toast.LENGTH_SHORT).show(); } } private static Bundle getLauncherOptionsBundle(Context context, View source, Rect bounds) { Bundle optionsBundle = null; if (source != null) { ActivityOptionsCompat options; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && bounds != null) { // Clip reveal animation for Marshmallow and above options = ActivityOptionsCompat.makeClipRevealAnimation(source, bounds.left, bounds.top, bounds.width(), bounds.height()); } else { // Fade animation otherwise options = ActivityOptionsCompat.makeCustomAnimation(context, R.anim.fade_in, R.anim.fade_out); } optionsBundle = options.toBundle(); } return optionsBundle; } }
46.084615
138
0.651811
8ae6c267fc9f7c8a39870ea12141a72e0c82313e
274
package com.sap.cloud.lm.sl.cf.core.dto.serialization; import javax.xml.bind.annotation.XmlTransient; import com.sap.cloud.lm.sl.mta.model.v1_0.Target; @XmlTransient @Deprecated public abstract class TargetPlatformDto { public abstract Target toTargetPlatform(); }
19.571429
54
0.791971
a9046755ca22081a77f7d8dc53d83bcf1a17dacc
3,720
/******************************************************************************* * ENdoSnipe 5.0 - (https://github.com/endosnipe) * * The MIT License (MIT) * * Copyright (c) 2012 Acroquest Technology Co.,Ltd. * * 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 jp.co.acroquest.endosnipe.javelin.converter.leak.monitor; import java.io.BufferedReader; import java.io.IOException; import jp.co.acroquest.endosnipe.javelin.common.AttachUtil; /** * Attach APIを用いてクラスヒストグラムを取得する。 * 取得したヒストグラムは以下の形式で取得できるため、パース処理を行い、 * * <pre> * num #instances #bytes class name * -------------------------------------- * 1: 68319 4985448 [C * 2: 39246 4661584 <constMethodKlass> * 3: 19963 3308768 [B * 4: 39246 3144680 <methodKlass> * 5: 55071 2329384 <symbolKlass> * 6: 3798 1927880 <constantPoolKlass> * 7: 70549 1693176 java.lang.String * 8: 3787 1658056 <instanceKlassKlass> * 9: 53196 1276704 java.util.HashMap$Entry * 10: 3277 1129696 <constantPoolCacheKlass> * </pre> * * @author eriguchi */ public class SunClassHistogramMonitor extends ClassHistogramMonitor { /** クラスヒストグラム中の、インスタンス数のインデックス。 */ private static final int INDEX_INSTANCES = 1; /** クラスヒストグラム中の、サイズ(byte)のインデックス。 */ private static final int INDEX_BYTES = 2; /** クラスヒストグラム中の、クラス名のインデックス。 */ private static final int INDEX_CLASSNAME = 3; /** クラスヒストグラムのカラム数。 */ private static final int CLASS_HISTOGRAM_COLUMNS = 4; /** * ヒストグラムの文字列を読み込むReaderを生成する。 * * @param classHistoGC ヒストグラム取得時にGCするかどうか * @return ヒストグラムの文字列を読み込むReader。 * @throws IOException ヒストグラム取得時にIOエラーが発生 */ public BufferedReader newReader(boolean classHistoGC) throws IOException { return AttachUtil.getHeapHistoReader(classHistoGC); } /** * 1行をパースして、ClassHistogramEntryを生成する。 * @param splitLine 1行 * @return ClassHistogramEntry、パースに失敗した場合はnull */ public ClassHistogramEntry parseEntry(final String[] splitLine) { if (splitLine.length != CLASS_HISTOGRAM_COLUMNS) { return null; } ClassHistogramEntry entry = new ClassHistogramEntry(); entry.setInstances(Integer.parseInt(splitLine[INDEX_INSTANCES])); entry.setBytes(Integer.parseInt(splitLine[INDEX_BYTES])); entry.setClassName(splitLine[INDEX_CLASSNAME]); return entry; } }
37.2
81
0.635484
b06d0f874b3f0a295916832015299967bb24feb4
5,665
package se.fortnox.reactivewizard.mocks; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.cookie.Cookie; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.netty.Connection; import reactor.netty.NettyOutbound; import reactor.netty.http.server.HttpServerResponse; import reactor.netty.http.server.WebsocketServerSpec; import reactor.netty.http.websocket.WebsocketInbound; import reactor.netty.http.websocket.WebsocketOutbound; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Predicate; public class MockHttpServerResponse implements HttpServerResponse { private Publisher<? extends byte[]> output; private HttpHeaders headers = new DefaultHttpHeaders(); private HttpResponseStatus status; public String getOutp() { if (output == null) { return ""; } return Flux.from(output) .collect(ByteArrayOutputStream::new, this::collectChunks) .map(ByteArrayOutputStream::toString) .block(); } private void collectChunks(ByteArrayOutputStream outputStream, byte[] bytes) { try { outputStream.write(bytes); } catch (IOException e) { throw new RuntimeException(e); } } @Override public HttpServerResponse addCookie(Cookie cookie) { return null; } @Override public HttpServerResponse addHeader(CharSequence name, CharSequence value) { headers.add(name, value); return this; } @Override public HttpServerResponse chunkedTransfer(boolean chunked) { return null; } @Override public ByteBufAllocator alloc() { return null; } @Override public NettyOutbound sendByteArray(Publisher<? extends byte[]> dataStream) { if (output == null) { output = dataStream; } return this; } @Override public NettyOutbound sendString(Publisher<? extends String> dataStream) { return sendByteArray(Flux.from(dataStream).map(String::getBytes)); } @Override public NettyOutbound send(Publisher<? extends ByteBuf> dataStream, Predicate<ByteBuf> predicate) { return null; } @Override public NettyOutbound sendObject(Publisher<?> dataStream, Predicate<Object> predicate) { return null; } @Override public NettyOutbound sendObject(Object message) { return null; } @Override public <S> NettyOutbound sendUsing(Callable<? extends S> sourceInput, BiFunction<? super Connection, ? super S, ?> mappedInput, Consumer<? super S> sourceCleanup) { return null; } @Override public HttpServerResponse withConnection(Consumer<? super Connection> withConnection) { return null; } @Override public HttpServerResponse compression(boolean compress) { return null; } @Override public boolean hasSentHeaders() { return false; } @Override public HttpServerResponse header(CharSequence name, CharSequence value) { return null; } @Override public HttpServerResponse headers(HttpHeaders headers) { return null; } @Override public HttpServerResponse keepAlive(boolean keepAlive) { return null; } @Override public HttpHeaders responseHeaders() { return headers; } @Override public Mono<Void> send() { return null; } @Override public NettyOutbound sendHeaders() { return null; } @Override public Mono<Void> sendNotFound() { return null; } @Override public Mono<Void> sendRedirect(String location) { return null; } @Override public Mono<Void> sendWebsocket(BiFunction<? super WebsocketInbound, ? super WebsocketOutbound, ? extends Publisher<Void>> websocketHandler, WebsocketServerSpec websocketServerSpec) { return null; } @Override public HttpServerResponse sse() { return null; } @Override public HttpResponseStatus status() { return status; } @Override public HttpServerResponse status(HttpResponseStatus status) { this.status = status; return this; } @Override public HttpServerResponse trailerHeaders(Consumer<? super HttpHeaders> consumer) { return this; } @Override public Map<CharSequence, Set<Cookie>> cookies() { return null; } @Override public boolean isKeepAlive() { return false; } @Override public boolean isWebsocket() { return false; } @Override public HttpMethod method() { return null; } @Override public String fullPath() { return null; } @Override public String requestId() { return null; } @Override public String uri() { return null; } @Override public HttpVersion version() { return null; } @Override public Map<CharSequence, List<Cookie>> allCookies() { return null; } }
24.209402
187
0.66549
c068c8600f9604e0fbf2672a1e02f12d9dc843a3
1,295
package org.zxp.ConcurrentLatch; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.Map; /** * 代理对象生成类 */ class ConcurrentLatchBeanFactory implements InvocationHandler{ private Object target; private String key = ""; private Object in = null; /** * 绑定委托对象并返回一个代理类 * @param target 目标类型 * @param pKey 任务代号 * @return */ public LatchThread getBean(Object target,String pKey,Object in) throws Exception { this.key = pKey; this.target = target; this.in = in; LatchThread proxyInstance = (LatchThread)Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this); //取得代理对象 return proxyInstance; } /** * 代理层将返回结果封装在map中以标识任务名称 * @param proxy * @param method * @param args * @return * @throws Throwable */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; result = method.invoke(target, in); Map<String,Object> map = new HashMap<String,Object>(); map.put(this.key,result); return map; } }
25.9
107
0.637066
bef15fd10891b5c480c9680f30a1d360a1edf73c
1,081
/* * Copyright (C) 2015 theta4j project */ package org.theta4j; import org.theta4j.ptp.type.UINT32; import java.util.EventListener; /** * An interface for receiving THETA events. * * @see Theta#addListener(ThetaEventListener) * @see Theta#removeListener(ThetaEventListener) */ public interface ThetaEventListener extends EventListener { /** * Invoked when a new object is added. * * @param objectHandle The ObjectHandle of the added object. */ void onObjectAdded(UINT32 objectHandle); /** * Invoked when the capture status of THETA is changed. */ void onCaptureStatusChanged(); /** * Invoked when video recording time is updated. */ void onRecordingTimeChanged(); /** * Invoked when remaining video recording time is updated. */ void onRemainingRecordingTimeChanged(); /** * Invoked when the storage of THETA faced into the limit. */ void onStoreFull(); /** * Invoked when capturing is complete. */ void onCaptureComplete(UINT32 transactionID); }
21.62
64
0.666975
d0ce8a0d8238cf6200d1ce8ed2d6a79727406b1d
3,519
/* * Copyright (C) 2020 Matthew Rosato * * 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.t07m.synolvm.command; import java.util.Arrays; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; import com.t07m.console.Command; import com.t07m.console.Console; import com.t07m.synolvm.SynoLVM; import com.t07m.synolvm.config.LVMConfig; import com.t07m.synolvm.config.LVMConfig.ViewConfig; import joptsimple.OptionParser; import joptsimple.OptionSet; public class ViewListCommand extends Command { private static final Logger logger = LoggerFactory.getLogger(ViewListCommand.class); private final SynoLVM lvm; public ViewListCommand(SynoLVM lvm) { super("View List"); this.lvm = lvm; OptionParser op = new OptionParser(); String[] viewOptions = { "v", "view" }; op.acceptsAll(Arrays.asList(viewOptions), "View Name").withRequiredArg().ofType(String.class); setOptionParser(op); } public void process(OptionSet optionSet, Console console) { LVMConfig config = lvm.getConfig(); synchronized(config) { ViewConfig[] views = config.getViewConfigurations(); if(optionSet.has("view")) { printSingleView(optionSet, views); return; } printAllViews(views); } } private void printAllViews(ViewConfig[] views) { if(views.length > 0) { for(ViewConfig vc : views) { logger.info(vc.getName() + " - " + (vc.isEnabled() ? "Enabled" : "Disabled") + " P:" +vc.getPriority()); } return; } logger.info("No views loaded."); } private void printSingleView(OptionSet optionSet, ViewConfig[] views) { String name = (String)optionSet.valueOf("view"); for(ViewConfig vc : views) { if(name.equalsIgnoreCase(vc.getName())) { printViewConfig(vc); return; } } logger.warn("Unable to find view: " + name); } private void printViewConfig(ViewConfig vc) { logger.info("Name: " + vc.getName() + System.lineSeparator() + "Enabled: " + vc.isEnabled() + System.lineSeparator() + "Priority: " + vc.getPriority() + System.lineSeparator() + "Monitor: " + vc.getMonitor()); if(vc.getRegistry().getLoginHistory() != null) { try { printLoginHistory(vc); }catch(JsonSyntaxException e) { e.printStackTrace(); } } } private void printLoginHistory(ViewConfig vc) { Gson gson = new Gson(); JsonArray jsonArray = gson.fromJson(vc.getRegistry().getLoginHistory().replace("\\\"", "\""), JsonArray.class); JsonObject json = jsonArray.get(0).getAsJsonObject(); for(Entry<String, JsonElement> entry : json.entrySet()) { if(entry.getValue() != null && entry.getValue().getAsString().length() > 0) { logger.info(entry.getKey() + ": " + entry.getValue().getAsString()); } } } }
31.419643
114
0.683717
db9b2ec2045c9d203e7478a869e1c7a3f2ff3c2c
1,619
package org.apache.dubbo.admin.config; import org.apache.commons.lang3.StringUtils; import org.apache.dubbo.admin.common.util.UrlUtils; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author libing * @version 1.0 * @date 2020/10/6 11:01 上午 */ @Configuration public class RegistryBeanConfig { @Bean public Registry getRegistry(RegistryProperties properties) { Registry registry = null; // if (!(dynamicConfig instanceof NoOpConfiguration)) { // String globalConfig = dynamicConfig.getConfig(, DynamicConfiguration.DEFAULT_GROUP); // if (StringUtils.isNotEmpty(globalConfig)) { // String registryConfigStr = Arrays.stream(globalConfig.split("\n")) // .filter(s -> s.startsWith("dubbo.registry")) // .collect(Collectors.joining("\n")); // if (StringUtils.isNotEmpty(registryConfigStr)) { // //read config-center config // throw new UnsupportedOperationException(); // } // } // } else if (StringUtils.isNotEmpty(properties.getAddress())) { RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension(); registry = registryFactory.getRegistry(UrlUtils.create(properties)); } return registry; } }
39.487805
127
0.665843
8596b663e9fa7974aed8fe1bdd8bf62cc814685a
6,369
package com.liaoyb.saber.modules.job.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.persistence.*; import java.io.Serializable; import java.time.Instant; import java.util.Objects; /** * A ScheduleJobHistory. */ @Entity @Table(name = "schedule_job_history") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class ScheduleJobHistory implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "title") private String title; @Column(name = "description") private String description; @Column(name = "bean_name") private String beanName; @Column(name = "method_name") private String methodName; @Column(name = "params") private String params; @Column(name = "cron_expression") private String cronExpression; @Column(name = "status") private Integer status; @Column(name = "error") private String error; @Column(name = "elapsed_time") private Long elapsedTime; @Column(name = "create_time") private Instant createTime; @Column(name = "end_time") private Instant endTime; @ManyToOne @JsonIgnoreProperties("") private ScheduleJob scheduleJob; // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public ScheduleJobHistory title(String title) { this.title = title; return this; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public ScheduleJobHistory description(String description) { this.description = description; return this; } public void setDescription(String description) { this.description = description; } public String getBeanName() { return beanName; } public ScheduleJobHistory beanName(String beanName) { this.beanName = beanName; return this; } public void setBeanName(String beanName) { this.beanName = beanName; } public String getMethodName() { return methodName; } public ScheduleJobHistory methodName(String methodName) { this.methodName = methodName; return this; } public void setMethodName(String methodName) { this.methodName = methodName; } public String getParams() { return params; } public ScheduleJobHistory params(String params) { this.params = params; return this; } public void setParams(String params) { this.params = params; } public String getCronExpression() { return cronExpression; } public ScheduleJobHistory cronExpression(String cronExpression) { this.cronExpression = cronExpression; return this; } public void setCronExpression(String cronExpression) { this.cronExpression = cronExpression; } public Integer getStatus() { return status; } public ScheduleJobHistory status(Integer status) { this.status = status; return this; } public void setStatus(Integer status) { this.status = status; } public String getError() { return error; } public ScheduleJobHistory error(String error) { this.error = error; return this; } public void setError(String error) { this.error = error; } public Long getElapsedTime() { return elapsedTime; } public ScheduleJobHistory elapsedTime(Long elapsedTime) { this.elapsedTime = elapsedTime; return this; } public void setElapsedTime(Long elapsedTime) { this.elapsedTime = elapsedTime; } public Instant getCreateTime() { return createTime; } public ScheduleJobHistory createTime(Instant createTime) { this.createTime = createTime; return this; } public void setCreateTime(Instant createTime) { this.createTime = createTime; } public Instant getEndTime() { return endTime; } public ScheduleJobHistory endTime(Instant endTime) { this.endTime = endTime; return this; } public void setEndTime(Instant endTime) { this.endTime = endTime; } public ScheduleJob getScheduleJob() { return scheduleJob; } public ScheduleJobHistory scheduleJob(ScheduleJob scheduleJob) { this.scheduleJob = scheduleJob; return this; } public void setScheduleJob(ScheduleJob scheduleJob) { this.scheduleJob = scheduleJob; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ScheduleJobHistory scheduleJobHistory = (ScheduleJobHistory) o; if (scheduleJobHistory.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), scheduleJobHistory.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "ScheduleJobHistory{" + "id=" + getId() + ", title='" + getTitle() + "'" + ", description='" + getDescription() + "'" + ", beanName='" + getBeanName() + "'" + ", methodName='" + getMethodName() + "'" + ", params='" + getParams() + "'" + ", cronExpression='" + getCronExpression() + "'" + ", status=" + getStatus() + ", error='" + getError() + "'" + ", elapsedTime=" + getElapsedTime() + ", createTime='" + getCreateTime() + "'" + ", endTime='" + getEndTime() + "'" + "}"; } }
23.764925
109
0.613754
9a6758b10fe70c70309ca546cd517580022f2a41
237
package saci; public class Tuple3<F1, F2, F3> { public final F1 f1; public final F2 f2; public F3 f3; public Tuple3(F1 x, F2 f2, F3 f3) { this.f1 = x; this.f2 = f2; this.f3 = f3; } }
15.8
40
0.506329
a86dab94a67110f4957becef016e97aa74904a51
476
package leetcode.lc283_move_zeroes; import java.util.Arrays; /** * https://leetcode.com/problems/move-zeroes/ #easy */ public final class LC283MoveZeroes { public void moveZeroes(final int[] nums) { int target = 0; for (int index = 0; index < nums.length; index++) { nums[target] = nums[index]; if (nums[index] != 0) { target++; } } Arrays.fill(nums, target, nums.length, 0); } }
23.8
59
0.552521
75131926876cedd7e378d4a99cd32bcbbcf4db01
6,640
package de.unisiegen.gtitool.ui.netbeans; import javax.swing.JDialog; import javax.swing.JFrame; import de.unisiegen.gtitool.core.entities.Transition; import de.unisiegen.gtitool.ui.logic.ChooseTransitionDialog; import de.unisiegen.gtitool.ui.netbeans.interfaces.GUIClass; /** * The choose {@link Transition} dialog. * * @author Christian Fehler * @version $Id$ */ @SuppressWarnings({ "all" }) public class ChooseTransitionDialogForm extends JDialog implements GUIClass <ChooseTransitionDialog> { /** * The serial version uid. */ private static final long serialVersionUID = -7313308327163039456L; /** * The {@link ChooseTransitionDialog}. */ private ChooseTransitionDialog logic; /** * Allocates a new {@link ChooseTransitionDialogForm}. * * @param logic The {@link ChooseTransitionDialog}. * @param parent The parent {@link JFrame}. */ public ChooseTransitionDialogForm(ChooseTransitionDialog logic, JFrame parent) { super(parent, true); this.logic = logic; initComponents(); } /** * {@inheritDoc} * * @see GUIClass#getLogic() */ public final ChooseTransitionDialog getLogic () { return this.logic; } /** 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. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jGTILabelHeader = new de.unisiegen.gtitool.ui.swing.JGTILabel(); jGTIPanelTransitions = new de.unisiegen.gtitool.ui.swing.JGTIPanel(); jGTIButtonOk = new de.unisiegen.gtitool.ui.swing.JGTIButton(); jGTIButtonCancel = new de.unisiegen.gtitool.ui.swing.JGTIButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("de/unisiegen/gtitool/ui/i18n/messages"); // NOI18N setTitle(bundle.getString("ChooseTransitionDialog.Title")); // NOI18N setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); getContentPane().setLayout(new java.awt.GridBagLayout()); jGTILabelHeader.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jGTILabelHeader.setText(bundle.getString("ChooseTransitionDialog.Header")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(16, 16, 5, 16); getContentPane().add(jGTILabelHeader, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 16, 5, 16); getContentPane().add(jGTIPanelTransitions, gridBagConstraints); jGTIButtonOk.setMnemonic(java.util.ResourceBundle.getBundle("de/unisiegen/gtitool/ui/i18n/messages").getString("ChooseTransitionDialog.OkMnemonic").charAt(0)); jGTIButtonOk.setText(bundle.getString("ChooseTransitionDialog.Ok")); // NOI18N jGTIButtonOk.setToolTipText(bundle.getString("ChooseTransitionDialog.OkToolTip")); // NOI18N jGTIButtonOk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jGTIButtonOkActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 16, 16, 5); getContentPane().add(jGTIButtonOk, gridBagConstraints); jGTIButtonCancel.setText(bundle.getString("ChooseTransitionDialog.Cancel")); // NOI18N jGTIButtonCancel.setToolTipText(bundle.getString("ChooseTransitionDialog.CancelToolTip")); // NOI18N jGTIButtonCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jGTIButtonCancelActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 16, 16); getContentPane().add(jGTIButtonCancel, gridBagConstraints); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-400)/2, (screenSize.height-300)/2, 400, 300); }// </editor-fold>//GEN-END:initComponents private void jGTIButtonOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jGTIButtonOkActionPerformed this.logic.handleOk(); }//GEN-LAST:event_jGTIButtonOkActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing this.logic.handleCancel(); }//GEN-LAST:event_formWindowClosing private void jGTIButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jGTIButtonCancelActionPerformed this.logic.handleCancel(); }//GEN-LAST:event_jGTIButtonCancelActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables public de.unisiegen.gtitool.ui.swing.JGTIButton jGTIButtonCancel; public de.unisiegen.gtitool.ui.swing.JGTIButton jGTIButtonOk; public de.unisiegen.gtitool.ui.swing.JGTILabel jGTILabelHeader; public de.unisiegen.gtitool.ui.swing.JGTIPanel jGTIPanelTransitions; // End of variables declaration//GEN-END:variables }
43.398693
167
0.705723
ebd9557c8be40e5ef9b7db8d03a2ae307a52a7f2
1,730
package com.cesurazure.crm.controller; import com.cesurazure.crm.controller.impl.IPackSMSController; import com.cesurazure.crm.model.PackSMS; import com.cesurazure.crm.service.impl.IPackSMSService; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; @RestController public class PackSMSController implements IPackSMSController{ @Autowired IPackSMSService packSMSService; @Override @RequestMapping(value = "/smsSave") public ModelAndView save(HttpServletRequest request) { System.out.println("*********** Hitted ***********"); packSMSService.save(request); return new ModelAndView("redirect:/smspackcreate"); } @Override public ModelAndView edit(int id) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public ModelAndView update(HttpServletRequest request) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public ModelAndView delete(int id) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public List<PackSMS> getAll() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
35.306122
135
0.742197
2cdffe1e0d91f306a7b2d39382cfaca1dcf7ab90
1,068
package eu.wauz.wauzunit; import static org.junit.Assert.assertEquals; import org.bukkit.ChatColor; import org.junit.Test; import eu.wauz.wauzcore.system.util.Formatters; import eu.wauz.wauzunit.abstracts.AbstractCoreTest; /** * Tests the currency mechanics from WauzCore. * * @author Wauzmons */ public class CurrencyTest extends AbstractCoreTest { /** * Tests the silver, gold and crystal coin formatting. */ @Test public void testCoinFormatting() { String format03Digits = ChatColor.GRAY + "100"; String format06Digits = ChatColor.GOLD + "200" + ChatColor.WHITE + "," + format03Digits; String format09Digits = ChatColor.AQUA + "300" + ChatColor.WHITE + "," + format06Digits; String format12Digits = ChatColor.AQUA + "400" + ChatColor.WHITE + "," + format09Digits; assertEquals(format03Digits, Formatters.formatCoins(100L)); assertEquals(format06Digits, Formatters.formatCoins(200100L)); assertEquals(format09Digits, Formatters.formatCoins(300200100L)); assertEquals(format12Digits, Formatters.formatCoins(400300200100L)); } }
30.514286
90
0.755618
4b9eeeee6a2f24c6bfbc88bec58cae32cc4a3358
2,875
package com.ilcarro.qa.tests; import com.ilcarro.qa.model.Car; import com.ilcarro.qa.model.User; import org.testng.annotations.DataProvider; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class DataProviders { @DataProvider public Iterator<Object[]> validUser(){ List<Object[]> list = new ArrayList<>(); list.add(new Object[]{"fName","lName","flName@gmail.com","nk123456"}); list.add(new Object[]{"sima","lima","sima@gmail.com","sima12345"}); list.add(new Object[]{"11","22","11@ww.com","tima12345"}); list.add(new Object[]{"Kr","Kn","kr@gmail.com","kr1234567"}); return list.iterator(); } @DataProvider public Iterator<Object[]>validUserFromCSV() throws IOException { List<Object[]>list = new ArrayList<>(); BufferedReader reader = new BufferedReader(new FileReader( new File("src/test/java/resources/test_newUser.csv"))); String line = reader.readLine(); while(line != null) { String[] split = line.split(","); list.add(new Object[]{new User().setFirstName(split[0]).setSecondName(split[1]) .setEmail(split[2]).setPassword(split[3])}); line = reader.readLine(); } return list.iterator(); } // @DataProvider // public Iterator<Object[]> validCarFromCSV() throws IOException { // List<Object[]> list = new ArrayList<>(); // BufferedReader reader = new BufferedReader(new FileReader( // new File("src/test/resources/addCar.csv"))); // String line = reader.readLine(); // // while (line != null){ // String[] split = line.split(","); // list.add(new Object[]{new Car() // .setCountry(split[0]) // .setAddress(split[1]) // .setDistance(split[2]) // .setSerialNumber(split[3]) // .setBrand(split[4]) // .setModel(split[5]) // .setYear(split[6]) // .setEngine(split[7]) // .setFuelConsumption(split[8]) // .setFuel(split[9]) // .setTransmission(split[10]) // .setWd(split[11]) // .setHorsepower(split[12]) // .setTorque(split[13]) // .setDoors(split[14]) // .setSeats(split[15]) // .setClasss(split[16]) // .setAbout(split[17]) // .setFeature(split[18]) // .setPrice(split[19])}); // // line = reader.readLine(); // } // // return list.iterator(); // } }
35.060976
91
0.529391
25cd81f31774c62ca24cd51fcb74f88b14ab2dcd
6,844
/** * Copyright 2019 Huawei Technologies Co.,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.obs.services.internal.utils; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.obs.log.ILogger; import com.obs.log.LoggerBuilder; import com.obs.services.ObsClient; import com.obs.services.exception.ObsException; import com.obs.services.internal.ServiceException; public class ReflectUtils { private static final ILogger ILOG = LoggerBuilder.getLogger(ReflectUtils.class); private static Class<?> androidBase64Class; private static Class<?> jdkBase64EncoderClass; private static Class<?> jdkBase64DecoderClass; private static Object jdkNewEncoder; private static Object jdkNewDecoder; private static Map<String, Field> fields = new ConcurrentHashMap<String, Field>(); static { try { androidBase64Class = Class.forName("android.util.Base64"); } catch (ClassNotFoundException e) { } try { Class<?> base64 = Class.forName("java.util.Base64"); jdkNewEncoder = base64.getMethod("getEncoder").invoke(null); jdkNewDecoder = base64.getMethod("getDecoder").invoke(null); } catch (ClassNotFoundException e) { ILOG.warn("class not found exception.", e); } catch (IllegalAccessException e) { ILOG.warn("illegal access exception.", e); } catch (IllegalArgumentException e) { ILOG.warn("illegal argument exception.", e); } catch (InvocationTargetException e) { ILOG.warn("invocation target exception.", e); } catch (NoSuchMethodException e) { ILOG.warn("nosuch method exception.", e); } catch (SecurityException e) { ILOG.warn("security exception.", e); } try { jdkBase64EncoderClass = Class.forName("sun.misc.BASE64Encoder"); } catch (ClassNotFoundException e) { ILOG.warn("class not found exception.", e); } try { jdkBase64DecoderClass = Class.forName("sun.misc.BASE64Decoder"); } catch (ClassNotFoundException e) { ILOG.warn("class not found exception.", e); } } public static String toBase64(byte[] data) { if (androidBase64Class != null) { try { Method m = androidBase64Class.getMethod("encode", byte[].class, int.class); return new String((byte[]) m.invoke(null, data, 2), Charset.defaultCharset()); } catch (Exception e) { throw new ServiceException(e); } } if (jdkNewEncoder != null) { try { Method m = jdkNewEncoder.getClass().getMethod("encode", byte[].class); return new String((byte[]) m.invoke(jdkNewEncoder, data), "UTF-8").replaceAll("\\s", ""); } catch (Exception e) { throw new ServiceException(e); } } if (jdkBase64EncoderClass != null) { try { Method m = jdkBase64EncoderClass.getMethod("encode", byte[].class); return ((String) m.invoke(jdkBase64EncoderClass.getConstructor().newInstance(), data)).replaceAll("\\s", ""); } catch (Exception e) { throw new ServiceException(e); } } throw new ServiceException("Failed to find a base64 encoder"); } public static byte[] fromBase64(String b64Data) throws UnsupportedEncodingException { if (androidBase64Class != null) { try { Method m = androidBase64Class.getMethod("decode", byte[].class, int.class); return (byte[]) m.invoke(null, b64Data.getBytes("UTF-8"), 2); } catch (Exception e) { throw new ServiceException(e); } } if (jdkNewDecoder != null) { try { Method m = jdkNewDecoder.getClass().getMethod("decode", byte[].class); return (byte[]) m.invoke(jdkNewDecoder, b64Data.getBytes("UTF-8")); } catch (Exception e) { throw new ServiceException(e); } } if (jdkBase64DecoderClass != null) { try { Method m = jdkBase64DecoderClass.getMethod("decodeBuffer", String.class); return (byte[]) m.invoke(jdkBase64DecoderClass.getConstructor().newInstance(), b64Data); } catch (Exception e) { throw new ServiceException(e); } } throw new ServiceException("Failed to find a base64 decoder"); } public static void setInnerClient(final Object obj, final ObsClient obsClient) { if (obj != null && obsClient != null) { final Class<?> clazz = obj.getClass(); final String name = clazz.getName(); // fix findbugs: DP_DO_INSIDE_DO_PRIVILEGED AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { Field f = fields.get(name); try { if (f == null) { f = getFieldFromClass(clazz, "innerClient"); f.setAccessible(true); fields.put(name, f); } f.set(obj, obsClient); } catch (Exception e) { throw new ObsException(e.getMessage(), e); } return null; } }); } } private static Field getFieldFromClass(Class<?> clazz, String key) { do { try { return clazz.getDeclaredField(key); } catch (NoSuchFieldException e) { clazz = clazz.getSuperclass(); } } while (clazz != null); return null; } }
36.795699
120
0.577294
ffa5f3bad0256dff9c2f79304dd55079aaa068c6
2,360
/* * Copyright (c) 2020 TurnOnline.biz 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 biz.turnonline.ecosystem.widget.purchase.ui; import biz.turnonline.ecosystem.widget.purchase.event.EditCategoryEvent; import biz.turnonline.ecosystem.widget.shared.AppMessages; import biz.turnonline.ecosystem.widget.shared.rest.payment.Category; import com.google.web.bindery.event.shared.EventBus; import gwt.material.design.client.constants.ButtonSize; import gwt.material.design.client.constants.ButtonType; import gwt.material.design.client.constants.Color; import gwt.material.design.client.constants.IconType; import gwt.material.design.client.constants.WavesType; import gwt.material.design.client.ui.MaterialButton; import gwt.material.design.client.ui.table.cell.WidgetColumn; /** * @author <a href="mailto:pohorelec@turnonline.biz">Jozef Pohorelec</a> */ public class ColumnCategoriesActions extends WidgetColumn<Category, MaterialButton> { private final EventBus eventBus; protected AppMessages messages = AppMessages.INSTANCE; public ColumnCategoriesActions( EventBus eventBus ) { this.eventBus = eventBus; } @Override public MaterialButton getValue( Category value ) { MaterialButton btnEdit = new MaterialButton(); btnEdit.addClickHandler( event -> { event.stopPropagation(); eventBus.fireEvent( new EditCategoryEvent( value.getId() ) ); } ); btnEdit.setType( ButtonType.FLOATING ); btnEdit.setBackgroundColor( Color.BLUE ); btnEdit.setIconType( IconType.EDIT ); btnEdit.setIconColor( Color.WHITE ); btnEdit.setWaves( WavesType.DEFAULT ); btnEdit.setSize( ButtonSize.MEDIUM ); btnEdit.setTooltip( messages.tooltipEditCategory() ); return btnEdit; } }
34.202899
75
0.733475
117cb0aec7dca6c9a019c943a1b82868b772252b
2,369
/* * Copyright 2016 Crown Copyright * * 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 stroom.cache.client.presenter; import com.google.inject.Inject; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.mvp.client.View; import stroom.cache.shared.CacheRow; import stroom.content.client.presenter.ContentTabPresenter; import stroom.dispatch.client.ClientDispatchAsync; import stroom.svg.client.Icon; import stroom.svg.client.SvgPresets; public class CachePresenter extends ContentTabPresenter<CachePresenter.CacheView> { public static final String LIST = "LIST"; public static final String NODE_LIST = "NODE_LIST"; private final CacheListPresenter cacheListPresenter; private final CacheNodeListPresenter cacheNodeListPresenter; @Inject public CachePresenter(final EventBus eventBus, final CacheView view, final CacheListPresenter cacheListPresenter, final CacheNodeListPresenter cacheNodeListPresenter, final ClientDispatchAsync dispatcher) { super(eventBus, view); this.cacheListPresenter = cacheListPresenter; this.cacheNodeListPresenter = cacheNodeListPresenter; setInSlot(LIST, cacheListPresenter); setInSlot(NODE_LIST, cacheNodeListPresenter); } @Override protected void onBind() { super.onBind(); registerHandler( cacheListPresenter.getSelectionModel().addSelectionHandler(event -> { final CacheRow row = cacheListPresenter.getSelectionModel().getSelected(); cacheNodeListPresenter.read(row); })); } @Override public Icon getIcon() { return SvgPresets.MONITORING; } @Override public String getLabel() { return "Caches"; } public interface CacheView extends View { } }
34.838235
118
0.721401
30d9cf158f4ad913e53df58b5ce75d25302d2b08
2,262
/* * Copyright 2016-2018 Cisco Systems Inc * * 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.ciscospark.androidsdk.utils; import android.os.Build; import android.support.annotation.Nullable; import com.cisco.spark.android.util.Strings; import com.ciscospark.androidsdk.Spark; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; /** * An utility class. * * @since 0.1 */ public class Utils { public static <T> T checkNotNull(@Nullable T object, String message) { if (object == null) { throw new NullPointerException(message); } return object; } public static String timestampUTC() { return DateTime.now(DateTimeZone.UTC).toString(); } public static String versionInfo() { String tempUserAgent = String.format("%s/%s (Android %s; %s %s / %s %s;)", Spark.APP_NAME, Spark.APP_VERSION, Build.VERSION.RELEASE, Strings.capitalize(Build.MANUFACTURER), Strings.capitalize(Build.DEVICE), Strings.capitalize(Build.BRAND), Strings.capitalize(Build.MODEL) ); return Strings.stripInvalidHeaderChars(tempUserAgent); } }
34.8
82
0.699823
5f433c74220f5e4bb3564afd2902c745317f2949
3,676
package etri.sdn.controller.protocol.rest.serializer; import java.io.IOException; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.Version; import org.codehaus.jackson.map.JsonSerializer; import org.codehaus.jackson.map.SerializerProvider; import org.codehaus.jackson.map.module.SimpleModule; import org.projectfloodlight.openflow.protocol.OFFeaturesReply; import org.projectfloodlight.openflow.protocol.OFPortDesc; import etri.sdn.controller.protocol.OFProtocol; /** * A Custom Serializer for OFFeaturesReply (FEATURES_REPLY) message. * * @author bjlee * */ final class OFFeaturesReplySerializer extends JsonSerializer<OFFeaturesReply> { OFProtocol protocol; public OFFeaturesReplySerializer(OFProtocol protocol) { this.protocol = protocol; } @Override public void serialize(OFFeaturesReply reply, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("datapathId", reply.getDatapathId().toString()); try { jgen.writeStringField("actions", reply.getActions().toString()); } catch ( UnsupportedOperationException u ) { jgen.writeStringField("actions", "[]"); } jgen.writeNumberField("buffers", reply.getNBuffers()); jgen.writeStringField("capabilities", reply.getCapabilities().toString()); jgen.writeNumberField("tables", reply.getNTables()); jgen.writeStringField("type", reply.getType().toString()); jgen.writeNumberField("version", reply.getVersion().ordinal()); jgen.writeNumberField("xid", reply.getXid()); try { provider.defaultSerializeField("ports", reply.getPorts(), jgen); } catch (UnsupportedOperationException u) { provider.defaultSerializeField("ports", this.protocol.getPortInformations(reply.getDatapathId().getLong()), jgen); } jgen.writeEndObject(); } } /** * A Custom Serializer for OFPhysicalPort object. * @author bjlee * */ //final class OFPhysicalPortSerializer extends JsonSerializer<OFPhysicalPort> { final class OFPhysicalPortSerializer extends JsonSerializer<OFPortDesc> { @Override // public void serialize(OFPhysicalPort port, JsonGenerator jgen, SerializerProvider provider) public void serialize(OFPortDesc port, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeNumberField("portNumber", port.getPortNo().getPortNumber()); jgen.writeStringField("hardwareAddress", port.getHwAddr().toString()); jgen.writeStringField("name", new String(port.getName())); jgen.writeStringField("config", port.getConfig().toString()); jgen.writeStringField("state", port.getState().toString()); jgen.writeStringField("currentFeatures", port.getCurr().toString()); jgen.writeStringField("advertisedFeatures", port.getAdvertised().toString()); jgen.writeStringField("supportedFeatures", port.getSupported().toString()); jgen.writeStringField("peerFeatures", port.getPeer().toString()); jgen.writeEndObject(); } } /** * A Custom Serializer Module which consists of * {@link OFFeaturesReplySerializer} and {@link OFPhysicalPortSerializer} * * @author bjlee * */ public final class OFFeaturesReplySerializerModule extends SimpleModule { public OFFeaturesReplySerializerModule(OFProtocol protocol) { super("OFFeaturesReplyModule", new Version(1, 0, 0, "OFFeaturesReplyModule")); addSerializer(OFFeaturesReply.class, new OFFeaturesReplySerializer(protocol)); // addSerializer(OFPhysicalPort.class, new OFPhysicalPortSerializer()); addSerializer(OFPortDesc.class, new OFPhysicalPortSerializer()); } }
36.76
117
0.77802
3a9d1ca92b688db5a31a242a36db3be3f3d80415
4,188
/** * */ package com.force.formula.commands; import java.lang.reflect.Type; import java.math.BigDecimal; import java.util.*; import com.force.formula.*; import com.force.formula.FormulaCommandType.AllowedContext; import com.force.formula.FormulaCommandType.SelectorSection; import com.force.formula.impl.*; import com.force.formula.sql.SQLPair; import com.force.formula.util.FormulaI18nUtils; import com.force.i18n.BaseLocalizer; /** * @author stamm * @since 0.1.0 */ @AllowedContext(section=SelectorSection.DATE_TIME) public class FunctionAddMonths extends FormulaCommandInfoImpl implements FormulaCommandValidator { public FunctionAddMonths() { super("ADDMONTHS", BigDecimal.class, new Class[] { Date.class }); } @Override public FormulaCommand getCommand(FormulaAST node, FormulaContext context) { return new FunctionAddMonthsCommand(this); } @Override public SQLPair getSQL(FormulaAST node, FormulaContext context, String[] args, String[] guards, TableAliasRegistry registry) { String sql = String.format(getSqlHooks(context).sqlAddMonths(), args[0], args[1]); String guard = SQLPair.generateGuard(guards, null); return new SQLPair(sql, guard); } @Override public Type validate(FormulaAST node, FormulaContext context, FormulaProperties properties) throws FormulaException { if (node.getNumberOfChildren() != 2) { throw new WrongNumberOfArgumentsException(node.getText(), 2, node); } FormulaAST firstNode = (FormulaAST)node.getFirstChild(); Type inputDataType = firstNode.getDataType(); Type rhsType = ((FormulaAST)firstNode.getNextSibling()).getDataType(); if (inputDataType != FormulaDateTime.class && inputDataType != Date.class && inputDataType != RuntimeType.class) { throw new IllegalArgumentTypeException(node.getText()); } if (rhsType != RuntimeType.class && rhsType != BigDecimal.class) { throw new IllegalArgumentTypeException(node.getText()); } return inputDataType; } @Override public JsValue getJavascript(FormulaAST node, FormulaContext context, JsValue[] args) throws FormulaException { String js = "$F.addmonths(" + args[0] + "," + jsToNum(context, args[1].js) + ")"; return JsValue.generate(js, args, true, args[0]); } static class FunctionAddMonthsCommand extends AbstractFormulaCommand { private static final long serialVersionUID = 1L; public FunctionAddMonthsCommand(FormulaCommandInfo formulaCommandInfo) { super(formulaCommandInfo); } // Uncomment this out if you want to support fractions in addmonths //private static BigDecimal MONTH_FRACTION = new BigDecimal("365.24").divide(new BigDecimal("12.00"), RoundingMode.HALF_DOWN); @Override public void execute(FormulaRuntimeContext context, Deque<Object> stack) { BigDecimal months = (BigDecimal) stack.pop(); Object input = stack.pop(); Date d = checkDateType(input); Object result; if (d == null) { result = null; // No NPEs if null } else if (months == null) { result = input; // Assume null = 0 months? } else { Calendar c = FormulaI18nUtils.getLocalizer().getCalendar(BaseLocalizer.GMT); c.setTime(d); c.add(Calendar.DAY_OF_YEAR, 1); // c.add(Calendar.MONTH, months.intValue()); /* // Uncomment this out if you want to support fractions in addmonths BigDecimal fractionalPart = months.remainder(BigDecimal.ONE).multiply(MONTH_FRACTION); int fractionalDays = fractionalPart.intValue(); if (fractionalDays != 0) { c.add(Calendar.DAY_OF_YEAR, fractionalDays); } */ c.add(Calendar.DAY_OF_YEAR, -1); result = input instanceof FormulaDateTime ? new FormulaDateTime(c.getTime()) : c.getTime(); } stack.push(result); } } }
38.777778
131
0.647803
ac1aafceab661f228da83986f353a15b9bbd0e9f
2,469
package org.support.project.knowledge.logic; import java.lang.invoke.MethodHandles; import java.util.List; import org.support.project.aop.Aspect; import org.support.project.common.log.Log; import org.support.project.common.log.LogFactory; import org.support.project.common.util.DateUtils; import org.support.project.di.Container; import org.support.project.di.DI; import org.support.project.di.Instance; import org.support.project.knowledge.dao.KnowledgesDao; import org.support.project.knowledge.dao.StockKnowledgesDao; import org.support.project.knowledge.entity.StockKnowledgesEntity; import org.support.project.knowledge.logic.activity.Activity; import org.support.project.knowledge.logic.activity.ActivityLogic; import org.support.project.knowledge.vo.Stock; import org.support.project.knowledge.vo.api.StockSelect; import org.support.project.web.bean.AccessUser; @DI(instance = Instance.Singleton) public class KnowledgeStockLogic { /** LOG */ private static final Log LOG = LogFactory.getLog(MethodHandles.lookup()); /** Get instance */ public static KnowledgeStockLogic get() { return Container.getComp(KnowledgeStockLogic.class); } private StockSelect getSelected(Long stockId, List<StockSelect> list) { for (StockSelect stockSelect : list) { if (stockId.longValue() == stockSelect.getStockId()) { return stockSelect; } } return null; } /** * 記事をストックに入れたり、ストックから外したりする * @param knowledgeId * @param stocks * @param accessUser */ @Aspect(advice = org.support.project.ormapping.transaction.Transaction.class) public void setStocks(long knowledgeId, List<Stock> stocks, AccessUser accessUser) { LOG.trace("setStocks"); StockKnowledgesDao dao = StockKnowledgesDao.get(); for (Stock stock : stocks) { StockKnowledgesEntity entity = new StockKnowledgesEntity(); entity.setStockId(stock.getStockId()); entity.setKnowledgeId(knowledgeId); if (stock.getStocked()) { entity.setComment(stock.getComment()); dao.save(entity); } else { // 存在チェックはしていない dao.physicalDelete(entity); } } ActivityLogic.get().processActivity(Activity.KNOWLEDGE_STOCK, accessUser, DateUtils.now(), KnowledgesDao.get().selectOnKey(knowledgeId)); } }
36.850746
98
0.688943
70eb22ec73a2b2040d7ba6e267befc16dbc43ad9
537
package co.caio.casserole.service; import co.caio.cerberus.db.RecipeMetadata; import co.caio.cerberus.db.RecipeMetadataDatabase; import java.util.Optional; import org.springframework.stereotype.Service; @Service public class MetadataService { private final RecipeMetadataDatabase metadataDatabase; public MetadataService(RecipeMetadataDatabase metadataDatabase) { this.metadataDatabase = metadataDatabase; } public Optional<RecipeMetadata> findById(long recipeId) { return metadataDatabase.findById(recipeId); } }
25.571429
67
0.811918
b46f8bc4129dc927076833b048b45744c012a977
1,712
/* * Copyright (C) 2017-2019 Dremio Corporation * * 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.dremio.service.flight; import org.apache.arrow.flight.FlightRuntimeException; import org.junit.BeforeClass; import org.junit.Test; import com.dremio.service.flight.impl.FlightWorkManager; /** * Tests for encryption options with the Flight endpoint service. */ public class TestEncryptedFlightServer extends BaseFlightQueryTest { @BeforeClass public static void setup() throws Exception { setupBaseFlightQueryTest( true, true, "encrypted.flight.reserved.port", FlightWorkManager.RunQueryResponseHandlerFactory.DEFAULT); } @Test(expected = FlightRuntimeException.class) public void testFlightEncryptedClientNoCerts() throws Exception { openFlightClient(DUMMY_USER, DUMMY_PASSWORD); } @Test public void testFlightEncryptedClientWithServerCerts() throws Exception { openEncryptedFlightClient(DUMMY_USER, DUMMY_PASSWORD, getCertificateStream()); } @Test(expected = FlightRuntimeException.class) public void testFlightClientUnencryptedServerEncrypted() throws Exception { openFlightClient(DUMMY_USER, DUMMY_PASSWORD); } }
32.301887
82
0.768107
d75bd8be1fd72d27471f68d75b8693e9912ae431
2,289
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.bootstrap.context.embedded.jetty; import java.util.Arrays; import org.eclipse.jetty.webapp.Configuration; import org.eclipse.jetty.webapp.WebAppContext; import org.junit.Test; import org.mockito.InOrder; import org.springframework.bootstrap.context.embedded.AbstractEmbeddedServletContainerFactoryTests; import org.springframework.bootstrap.context.embedded.jetty.JettyEmbeddedServletContainer; import org.springframework.bootstrap.context.embedded.jetty.JettyEmbeddedServletContainerFactory; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; /** * Tests for {@link JettyEmbeddedServletContainerFactory} and * {@link JettyEmbeddedServletContainer}. * * @author Phillip Webb */ public class JettyEmbeddedServletContainerFactoryTests extends AbstractEmbeddedServletContainerFactoryTests { @Test public void jettyConfigurations() throws Exception { JettyEmbeddedServletContainerFactory factory = getFactory(); Configuration[] configurations = new Configuration[4]; for (int i = 0; i < configurations.length; i++) { configurations[i] = mock(Configuration.class); } factory.setConfigurations(Arrays.asList(configurations[0], configurations[1])); factory.addConfigurations(configurations[2], configurations[3]); this.container = factory.getEmbdeddedServletContainer(); InOrder ordered = inOrder((Object[]) configurations); for (Configuration configuration : configurations) { ordered.verify(configuration).configure((WebAppContext) anyObject()); } } @Override protected JettyEmbeddedServletContainerFactory getFactory() { return new JettyEmbeddedServletContainerFactory(); } }
36.919355
99
0.790301
0d30a686c4ccf19bf5d21f5ff6a3f5f973d48308
366
package maquina.hibernate.repository; import maquina.hibernate.dominio.one2one.Mago; public class MagoRepositoryTest extends JpaRepositoryImplTest<Long, Mago> { @Override public Mago getInstanceDeE() { Mago mago = new Mago(); mago.setNombre("Natsu"); return mago; } @Override public Long getClavePrimariaNoExistente() { return Long.MAX_VALUE; } }
18.3
75
0.756831
00fa0891cabb9d79b6b0192a11bcfc579093fca8
1,335
// Autogenerated from vk-api-schema. Please don't edit it manually. package com.vk.api.sdk.objects.video; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import com.vk.api.sdk.objects.Validable; import com.vk.api.sdk.objects.base.Image; import com.vk.api.sdk.objects.base.PropertyExists; import java.util.Objects; /** * VideoImage object */ public class VideoImage extends Image implements Validable { @SerializedName("with_padding") private PropertyExists withPadding; public boolean isWithPadding() { return withPadding == PropertyExists.PROPERTY_EXISTS; } @Override public int hashCode() { return Objects.hash(withPadding); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; VideoImage videoImage = (VideoImage) o; return Objects.equals(withPadding, videoImage.withPadding); } @Override public String toString() { final Gson gson = new Gson(); return gson.toJson(this); } public String toPrettyString() { final StringBuilder sb = new StringBuilder("VideoImage{"); sb.append("withPadding=").append(withPadding); sb.append('}'); return sb.toString(); } }
27.8125
67
0.67191
a14a2ad86ca6d93925eeb43d4f6d24704292f344
1,313
/* * Class: MathFunctionWithFirstDerivative * Description: * Environment: Java * Software: SSJ * Copyright (C) 2001 Pierre L'Ecuyer and Universite de Montreal * Organization: DIRO, Universite de Montreal * @author Éric Buist * @since * * * 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 umontreal.ssj.functions; /** * Represents a mathematical function whose derivative can be computed using * #derivative(double). * * <div class="SSJ-bigskip"></div> */ public interface MathFunctionWithFirstDerivative extends MathFunction { /** * Computes (or estimates) the first derivative of the function at point `x`. * @param x the point to evaluate the derivative to. * @return the value of the derivative. */ public double derivative (double x); }
32.02439
77
0.718964
dd7392e88f4f4beb06b5cd631268f313a25fa565
1,097
package com.pull_more_refresh.ui; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Message; import android.widget.ImageView; import com.pull_more_refresh.R; import com.pull_more_refresh.model.ImageBean; import com.pull_more_refresh.net.URLConstants; /** * Created by wangliang on 2017/6/27. */ public class TestAt extends BaseActivity { private ImageView mImageView; @Override int getLayout() { return R.layout.test_at; } @Override void initView() { mImageView = findView(R.id.img_); mUIHandler = new AHandler() { @Override void refreshUI(Message msg) { Bundle bundle = msg.getData(); if (bundle != null) { Bitmap bitmap = bundle.getParcelable("bitmap"); mImageView.setImageBitmap(bitmap); } } }; loadData(); } @Override void loadData() { ImageBean imageBean = new ImageBean(URLConstants.url3); // new LIFOTask(imageBean, null).start(); } }
23.340426
67
0.606199
c1ce1e3d07ce62e038ae39551aba83bb5c76cfa9
6,111
/** * Copyright 2015 DuraSpace, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fcrepo.kernel.modeshape.rdf.impl; import static com.google.common.collect.ImmutableSet.builder; import static com.hp.hpl.jena.graph.NodeFactory.createLiteral; import static com.hp.hpl.jena.graph.NodeFactory.createURI; import static com.hp.hpl.jena.graph.Triple.create; import static com.hp.hpl.jena.rdf.model.ResourceFactory.createTypedLiteral; import static java.util.Arrays.stream; import static java.util.stream.Collectors.joining; import static org.fcrepo.kernel.api.FedoraJcrTypes.ROOT; import static org.fcrepo.kernel.api.RdfLexicon.HAS_FIXITY_CHECK_COUNT; import static org.fcrepo.kernel.api.RdfLexicon.HAS_FIXITY_ERROR_COUNT; import static org.fcrepo.kernel.api.RdfLexicon.HAS_FIXITY_REPAIRED_COUNT; import static org.fcrepo.kernel.api.RdfLexicon.REPOSITORY_NAMESPACE; import static org.slf4j.LoggerFactory.getLogger; import com.hp.hpl.jena.rdf.model.Resource; import org.apache.commons.lang3.StringUtils; import org.fcrepo.kernel.api.identifiers.IdentifierConverter; import org.fcrepo.kernel.api.models.FedoraResource; import org.fcrepo.metrics.RegistryService; import java.util.Map; import javax.jcr.Repository; import org.fcrepo.kernel.modeshape.services.functions.GetClusterConfiguration; import org.modeshape.jcr.JcrRepository; import org.slf4j.Logger; import com.codahale.metrics.Counter; import com.google.common.collect.ImmutableSet; import com.hp.hpl.jena.graph.Triple; /** * Assemble {@link Triple}s derived from the root of a repository. * * @author ajs6f * @since Oct 18, 2013 */ public class RootRdfContext extends NodeRdfContext { private static final String PREFIX = "org.fcrepo.services."; private static final String FIXITY_REPAIRED_COUNTER = "LowLevelStorageService.fixity-repaired-counter"; private static final String FIXITY_ERROR_COUNTER = "LowLevelStorageService.fixity-error-counter"; private static final String FIXITY_CHECK_COUNTER = "LowLevelStorageService.fixity-check-counter"; private static final Logger LOGGER = getLogger(RootRdfContext.class); static final RegistryService registryService = RegistryService.getInstance(); /** * Ordinary constructor. * * @param resource the resource * @param idTranslator the id translator */ public RootRdfContext(final FedoraResource resource, final IdentifierConverter<Resource, FedoraResource> idTranslator) { super(resource, idTranslator); if (resource().hasType(ROOT)) { concatRepositoryTriples(); } } private void concatRepositoryTriples() { LOGGER.trace("Creating RDF triples for repository description"); final Repository repository = session().getRepository(); final ImmutableSet.Builder<Triple> b = builder(); stream(repository.getDescriptorKeys()).forEach(key -> { final String descriptor = repository.getDescriptor(key); if (descriptor != null) { // Create a URI from the jcr.Repository constant values, // converting them from dot notation (identifier.stability) // to the camel case that is more common in RDF properties. final String uri = stream(key.split("\\.")) .map(StringUtils::capitalize).collect(joining("", REPOSITORY_NAMESPACE + "repository", "")); b.add(create(subject(), createURI(uri), createLiteral(descriptor))); } }); /* FIXME: removing due to performance problems, esp. w/ many files on federated filesystem see: https://www.pivotaltracker.com/story/show/78647248 b.add(create(subject(), HAS_OBJECT_COUNT.asNode(), createLiteral(String .valueOf(getRepositoryCount(repository))))); b.add(create(subject(), HAS_OBJECT_SIZE.asNode(), createLiteral(String .valueOf(getRepositorySize(repository))))); */ // Get the cluster configuration, if available // this ugly test checks to see whether this is an ordinary JCR // repository or a ModeShape repo, which will possess the extra info if (JcrRepository.class.isAssignableFrom(repository.getClass())) { final Map<String, String> config = new GetClusterConfiguration().apply(repository); assert (config != null); config.forEach((k, v) -> b.add(create(subject(), createURI(REPOSITORY_NAMESPACE + k), createLiteral(v)))); } // retrieve the metrics from the service final Map<String, Counter> counters = registryService.getMetrics().getCounters(); // and add the repository metrics to the RDF model if (counters.containsKey(FIXITY_CHECK_COUNTER)) { b.add(create(subject(), HAS_FIXITY_CHECK_COUNT.asNode(), createTypedLiteral(counters.get(PREFIX + FIXITY_CHECK_COUNTER).getCount()).asNode())); } if (counters.containsKey(FIXITY_ERROR_COUNTER)) { b.add(create(subject(), HAS_FIXITY_ERROR_COUNT.asNode(), createTypedLiteral(counters.get(PREFIX + FIXITY_ERROR_COUNTER).getCount()).asNode())); } if (counters.containsKey(FIXITY_REPAIRED_COUNTER)) { b.add(create(subject(), HAS_FIXITY_REPAIRED_COUNT.asNode(), createTypedLiteral(counters.get(PREFIX + FIXITY_REPAIRED_COUNTER).getCount()).asNode())); } // offer all these accumulated triples concat(b.build()); } }
44.933824
118
0.702504
b9c4d4e8cd6dd7332afc3e596a67279841f55482
2,866
package farmsim.crops; import farmsim.tiles.TileProperty; import farmsim.world.terrain.Biomes; import org.junit.*; import org.junit.runner.RunWith; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.HashMap; import java.util.Map; import farmsim.entities.tileentities.crops.*; import farmsim.tiles.Tile; @PrepareForTest({DatabaseHandler.class}) @RunWith(PowerMockRunner.class) public class LemonTest { private Lemon lemon; private DatabaseHandler dbHandler; private Map<String, Object> properties; private Tile tile; /** * Mocks the relevant classes and static calls so the Lemon class can be * tested in isolation. */ @Before public void setup() { properties = new HashMap<>(); properties.put("Clevel", 1); properties.put("Gtime1", 0); properties.put("Gtime2", 560000); properties.put("Gtime3", 1200000); properties.put("Gtime4", 1680000); properties.put("Gtime5", 2520000); properties.put("Hquantity", 14); properties.put("StNames1", "seed"); properties.put("StNames2", "Lemon1"); properties.put("StNames3", "Lemon2"); properties.put("StNames4", "Lemon3"); properties.put("DeadStage1", "Lemon1dead"); properties.put("DeadStage2", "Lemon2dead"); properties.put("DeadStage3", "Lemon3dead"); properties.put("Penvironment", "FOREST"); properties.put("Nenvironment", "ROCKY"); tile = mock(Tile.class); dbHandler = mock(DatabaseHandler.class); PowerMockito.mockStatic(DatabaseHandler.class); PowerMockito.when(DatabaseHandler.getInstance()).thenReturn(dbHandler); when(dbHandler.getPlantData("Lemon")).thenReturn(properties); when(tile.getProperty(TileProperty.BIOME)).thenReturn(Biomes.GRASSLAND); } /** * Checks the initialised state of the lemon. */ @Test public void initialisationTest() { lemon = new Lemon(tile); assertEquals("Lemon", lemon.getName()); assertFalse(lemon.isDead()); assertTrue(lemon.isOrchard(lemon.getName())); } /** * Check that the tick method behaves correctly depending on the water * state of the tile. */ @Test public void tickTest() { lemon = new Lemon(tile); when(tile.getWaterLevel()).thenReturn((float) 0.1); lemon.tick(); assertFalse("Not dead yet", lemon.isDead()); when(tile.getWaterLevel()).thenReturn((float) 0.0); lemon.tick(); assertTrue("Is dead", lemon.isDead()); assertEquals("Incorrect stage", lemon.getTileType(), "seed"); } }
32.202247
80
0.65806
b9be00c2bc13c0bc3322d006c72aca85210df995
531
package cic.cs.unb.ca.flow.ui; import cic.cs.unb.ca.weka.WekaXMeans; import java.io.File; public class FlowFileInfo { private File filepath; private WekaXMeans xMeans; public FlowFileInfo(File filepath, WekaXMeans xMeans) { this.filepath = filepath; this.xMeans = xMeans; } @Override public String toString() { return filepath.getName(); } public File getFilepath() { return filepath; } public WekaXMeans getxMeans() { return xMeans; } }
17.129032
59
0.634652
16521a48523ab68332bbe31ce05bc63030709c8e
1,406
/* * Copyright 2015 Adaptris 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.adaptris.core.services.findreplace; import com.adaptris.annotation.DisplayOrder; import com.adaptris.core.AdaptrisMessage; import com.thoughtworks.xstream.annotations.XStreamAlias; /** * {@link ReplacementSource} implementation which returns the passed in value. * <p> * Used with {@link FindAndReplaceService} to replace text in the message. * </p> * * @config configured-replacement-source */ @XStreamAlias("configured-replacement-source") @DisplayOrder(order = {"value"}) public class ConfiguredReplacementSource extends AbstractReplacementSource { public ConfiguredReplacementSource() { super(); } public ConfiguredReplacementSource(String val) { this(); setValue(val); } public String obtainValue(AdaptrisMessage msg) { return this.getValue(); } }
29.291667
78
0.745377
47fb02497f55cc5e864305ba8c4c984aee03a3ea
982
package it.polimi.ingsw.server.model; /** * Choose action phase. */ public class ChooseActionPhase extends TurnPhase { public ChooseActionPhase(Game game) { super(game, "Choose the next action", false); } @Override public void start() { getGame().getViewAdapter().announceTurnPhase(getGame().getCurrentPlayer(), getName(), getPhaseInfo()); } @Override public String getPhaseInfo() { return "In this turn phase you have to choose an action between:\n" + "-Use the Market: choose a row or a column from the Market and earn resources;\n" + "-Buy a Development Card: use your resources to buy a new Development Card to insert in your board;\n" + "-Activate productions: use your resources to produce other resources."; } //In this case, the next turn phase is managed by ControllerAdapter. @Override public TurnPhase nextTurnPhase() { return null; } }
32.733333
120
0.652749
9b5dd03347cf5f224f10cef7c2fb0ab8dcecb2bc
3,247
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference // Implementation, v2.3.0 // See <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2021.08.06 at 04:43:12 PM BST // package org.treblereel.gwt.xml.mapper.client.tests.pmml.model.api; /** * Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element ref="{http://www.dmg.org/PMML-4_4}REAL-ARRAY" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;attribute name="trend" default="additive"&gt; * &lt;simpleType&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN"&gt; * &lt;enumeration value="additive"/&gt; * &lt;enumeration value="damped_additive"/&gt; * &lt;enumeration value="multiplicative"/&gt; * &lt;enumeration value="damped_multiplicative"/&gt; * &lt;enumeration value="polynomial_exponential"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * &lt;/attribute&gt; * &lt;attribute name="gamma" type="{http://www.dmg.org/PMML-4_4}REAL-NUMBER" /&gt; * &lt;attribute name="phi" type="{http://www.dmg.org/PMML-4_4}REAL-NUMBER" default="1" /&gt; * &lt;attribute name="smoothedValue" type="{http://www.dmg.org/PMML-4_4}REAL-NUMBER" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> */ public interface TrendExpoSmooth { /** * Gets the value of the realarray property. * * @return possible object is {@link REALARRAY } */ REALARRAY getREALARRAY(); /** * Sets the value of the realarray property. * * @param value allowed object is {@link REALARRAY } */ void setREALARRAY(REALARRAY value); /** * Gets the value of the trend property. * * @return possible object is {@link String } */ String getTrend(); /** * Sets the value of the trend property. * * @param value allowed object is {@link String } */ void setTrend(String value); /** * Gets the value of the gamma property. * * @return possible object is {@link Double } */ Double getGamma(); /** * Sets the value of the gamma property. * * @param value allowed object is {@link Double } */ void setGamma(Double value); /** * Gets the value of the phi property. * * @return possible object is {@link Double } */ double getPhi(); /** * Sets the value of the phi property. * * @param value allowed object is {@link Double } */ void setPhi(Double value); /** * Gets the value of the smoothedValue property. * * @return possible object is {@link Double } */ Double getSmoothedValue(); /** * Sets the value of the smoothedValue property. * * @param value allowed object is {@link Double } */ void setSmoothedValue(Double value); }
28.482456
99
0.62704
93d32b0809ee5da3963552305610bc8191b4a8e5
2,008
package ignis.warren.gsontime; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAccessor; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class GsonJava8TimeAdapter { private final Map<Class<? extends TemporalAccessor>, TemporalAccessorSerializer<?>> instanceMap = new HashMap<>(); private GsonJava8TimeAdapter() { instanceMap.putAll(Java8TimeSerializers.SERIALIZERS_MAP); } public static Gson create() { return register(new GsonBuilder()).create(); } public static GsonBuilder register(GsonBuilder gsonBuilder) { return new GsonJava8TimeAdapter().registerAllSerializers(gsonBuilder, Collections.emptyMap()); } public static Gson create(Map<Class<? extends TemporalAccessor>, DateTimeFormatter> formatMap) { Objects.requireNonNull(formatMap); return createBuilder(formatMap).create(); } public static GsonBuilder createBuilder() { return createBuilder(Collections.emptyMap()); } public static GsonBuilder createBuilder(Map<Class<? extends TemporalAccessor>, DateTimeFormatter> formatMap) { return new GsonJava8TimeAdapter().registerAllSerializers(new GsonBuilder(), formatMap); } private GsonBuilder registerAllSerializers(GsonBuilder gsonBuilder, Map<Class<? extends TemporalAccessor>, DateTimeFormatter> formatMap) { formatMap.forEach(this::overrideFormatter); instanceMap.forEach(gsonBuilder::registerTypeAdapter); return gsonBuilder; } private void overrideFormatter(Class<? extends TemporalAccessor> accessor, DateTimeFormatter formatter) { final TemporalAccessorSerializer<?> overrideFormatter = instanceMap.get(accessor) .overrideFormatter(formatter); instanceMap.put(accessor, overrideFormatter); } }
34.033898
118
0.726096
77dc1c3e3ddc8ad99a2495e923abc85e464e4b00
281
package com.shunyi.autoparts.exception; /** * @description VFS类目找不到异常 * @author Shunyi Chen * @date 2020/3/23 */ public class VFSCategoryNotFoundException extends RuntimeException { public VFSCategoryNotFoundException(String exception) { super(exception); } }
21.615385
68
0.736655
0864a5d11aaa3c830ab346949d6bc6e5394a60e1
444
package cn.gyyx.bts.core.ctrl; import com.google.inject.Inject; public class ZooPathCtrl { @Inject public ZooPathCtrl() { } public String getGlobalLockPath() { return "/global/lock"; } public String getServerParent() { return "/onlineserver"; } public String getOnlinePath(long processIndex) { return String.format("%s/%s", getServerParent(),processIndex+""); } public String getGuidPath() { return "/guid"; } }
15.857143
67
0.691441
6d696d8d1bfa9dbfa5346340989f8465d9ab0b52
5,732
/* * This file is part of Cubic Chunks Mod, licensed under the MIT License (MIT). * * Copyright (c) 2015-2019 OpenCubicChunks * Copyright (c) 2015-2019 contributors * * 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 io.github.opencubicchunks.cubicchunks.core.worldgen; import io.github.opencubicchunks.cubicchunks.core.CubicChunks; import io.github.opencubicchunks.cubicchunks.core.util.CompatHandler; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.TimeUnit; public class WorldgenHangWatchdog { public static final boolean ENABLED = "true".equalsIgnoreCase(System.getProperty("cubicchunks.wgen_hang_watchdog", "true")); private static final WorldgenHangWatchdog INSTANCE = new WorldgenHangWatchdog(); private static final Thread thread = init(); private final WeakHashMap<Thread, Entry> entries = new WeakHashMap<>(); private static volatile String crashInfo = null; private WorldgenHangWatchdog() { if (INSTANCE != null) { throw new IllegalStateException("Already initialized"); } } public static String getCrashInfo() { return crashInfo; } public static void startWorldGen() { synchronized (INSTANCE.entries) { INSTANCE.entries.compute(Thread.currentThread(), (t, old) -> { if (old == null) { return new Entry(); } old.count++; return old; }); } } public static void endWorldGen() { synchronized (INSTANCE.entries) { Entry e = INSTANCE.entries.get(Thread.currentThread()); if (e != null) { if (e.count <= 0) { INSTANCE.entries.remove(Thread.currentThread()); } else { e.count--; } } } } private static Thread init() { Thread t = new Thread(INSTANCE::run); t.setName("WorldGen hang watchdog thread"); t.setDaemon(true); t.start(); return t; } @SuppressWarnings("deprecation") private void run() { if (!ENABLED) { return; } while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (entries) { for (Iterator<Map.Entry<Thread, Entry>> iterator = entries.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<Thread, Entry> entry = iterator.next(); Thread t = entry.getKey(); Entry e = entry.getValue(); e.samples.add(t.getStackTrace()); long currentTime = System.nanoTime(); long dt = currentTime - e.startTime; if (dt > TimeUnit.SECONDS.toNanos(10)) { StringBuilder sb = new StringBuilder(); sb.append("World generation taking ").append(dt / (double) TimeUnit.SECONDS.toNanos(1)) .append(" seconds, should be less than 50ms. Stopping the server.\n"); sb.append("Samples collected during world generation:\n"); int i = 1; for (StackTraceElement[] stacktrace : e.samples) { sb.append("--------------------------------------------\n"); Set<String> likelyModsInvolved = CompatHandler.getModsForStacktrace(stacktrace); sb.append("SAMPLE #").append(i).append(", likely mods involved: ").append(String.join(", ", likelyModsInvolved)) .append('\n'); for (StackTraceElement traceElement : stacktrace) { sb.append("\tat ").append(traceElement).append('\n'); } i++; } String msg = sb.toString(); crashInfo = msg; CubicChunks.LOGGER.fatal(msg); t.stop(); iterator.remove(); } } } } } private static class Entry { long startTime; int count; List<StackTraceElement[]> samples = new ArrayList<>(); Entry() { startTime = System.nanoTime(); } } }
36.74359
140
0.56141
6afe5bab6018cae2b23839115410cae9e9024c17
273
package BQN.tokenizer.types; import BQN.tokenizer.Token; public class SemiTok extends Token { public SemiTok(String line, int spos, int epos) { super(line, spos, epos); type = ';'; flags = 0; } @Override public String toRepr() { return ";"; } }
18.2
51
0.6337
08d86021b25f84e1cde8584b9bb5e037916d5b46
5,119
/** * 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.geronimo.gbean; import java.util.Map; import java.util.LinkedHashMap; import java.util.Collections; import java.net.URI; import javax.management.ObjectName; import junit.framework.TestCase; import org.apache.geronimo.kernel.repository.Artifact; import org.apache.geronimo.kernel.repository.Version; /** * @version $Rev$ $Date$ */ public class AbstractNameTest extends TestCase { public void testSimple() throws Exception { Artifact artifact = new Artifact("groupId", "artifactId", "version", "type"); Map nameMap = new LinkedHashMap(); nameMap.put("a", "aaa"); nameMap.put("b", "bbb"); nameMap.put("c", "ccc"); AbstractName abstractName = new AbstractName(artifact, nameMap, new ObjectName("test:nothing=true")); URI uri = abstractName.toURI(); assertEquals(abstractName, new AbstractName(uri)); } public void testMinimalArtifact() throws Exception { Artifact artifact = new Artifact(null, "artifactId", (Version)null, null); Map nameMap = new LinkedHashMap(); nameMap.put("a", "aaa"); nameMap.put("b", "bbb"); nameMap.put("c", "ccc"); AbstractName abstractName = new AbstractName(artifact, nameMap, new ObjectName("test:nothing=true")); URI uri = abstractName.toURI(); assertEquals(abstractName, new AbstractName(uri)); } public void testCreateURI() throws Exception { Artifact artifact = new Artifact("groupId", "artifactId", "version", "type"); URI uri = new URI(null, null, artifact.toString(), "a=aaa", null); AbstractName abstractName = new AbstractName(artifact, Collections.singletonMap("a", "aaa"), new ObjectName("test:nothing=true")); assertEquals(abstractName, new AbstractName(uri)); } public void testEmptyName() throws Exception { Artifact artifact = new Artifact("groupId", "artifactId", "version", "type"); URI uri = new URI(null, null, artifact.toString(), "", null); try { new AbstractName(uri); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } } public void testNoName() throws Exception { Artifact artifact = new Artifact("groupId", "artifactId", "version", "type"); URI uri = new URI(null, null, artifact.toString(), null, null); try { new AbstractName(uri); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } } public void testEmptyArtifact() throws Exception { URI uri = new URI(null, null, "", "a=aaa", null); try { new AbstractName(uri); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } } public void testInvalidArtifact() throws Exception { URI uri = new URI(null, null, "foo", "a=aaa", null); try { new AbstractName(uri); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } uri = new URI(null, null, "foo/", "a=aaa", null); try { new AbstractName(uri); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } uri = new URI(null, null, "/foo/", "a=aaa", null); try { new AbstractName(uri); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } uri = new URI(null, null, "foo////", "a=aaa", null); try { new AbstractName(uri); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } } public void testNoArtifact() throws Exception { URI uri = new URI(null, null, null, "a=aaa", null); try { new AbstractName(uri); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } } }
34.126667
109
0.616722
7f74086c6fab53e1b0367ba4d181187d38359b36
4,661
/* * 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 server; import java.io.IOException; import java.io.OutputStream; import java.net.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Resource; import javax.jms.*; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.json.simple.JSONObject; import operator.entity.DocumentRequest; /** * * @author Bogdan */ public class Main { @Resource(lookup = "jms/__defaultConnectionFactory") public static ConnectionFactory connectionFactory; @Resource(lookup = "jmsQueue") public static javax.jms.Queue jmsQueue; public static final String PERSO_SUBMIT_URL = "http://collabnet.netset.rs:8081/is/persoCentar/submit"; /** * @param args the command line arguments */ public static void main(String[] args) { JMSContext context = connectionFactory.createContext(); JMSConsumer consumer = context.createConsumer(jmsQueue); EntityManagerFactory emf = Persistence.createEntityManagerFactory("ServerPU"); EntityManager em = emf.createEntityManager(); System.out.println("Server started"); while (true) { try { Message msg = consumer.receive(); if (msg == null) continue; if (msg instanceof ObjectMessage) { ObjectMessage objMsg = (ObjectMessage) msg; DocumentRequest docReq = (DocumentRequest) objMsg.getObject(); System.out.println(docReq.getJmbg()); int id = ((DocumentRequest)em.createNamedQuery("DocumentRequest.findByJmbg") .setParameter("jmbg", docReq.getJmbg()).getResultList().get(0)).getId(); JSONObject obj = new JSONObject(); obj.put("id", "17011" + String.format("%07d", id)); obj.put("ime", docReq.getIme()); obj.put("prezime", docReq.getPrezime()); obj.put("imeMajke", docReq.getImeMajke()); obj.put("imeOca", docReq.getImeOca()); obj.put("prezimeMajke", docReq.getPrezimeMajke()); obj.put("prezimeOca", docReq.getPrezimeOca()); obj.put("pol", docReq.getPol()); obj.put("datumRodjenja", docReq.getDatumRodjenja()); obj.put("nacionalnost", docReq.getNacionalnost()); obj.put("profesija", docReq.getProfesija()); obj.put("bracnoStanje", docReq.getBracnoStanje()); obj.put("opstinaPrebivalista", docReq.getOpstinaPrebivalista()); obj.put("ulicaPrebivalista", docReq.getUlicaPrebivalista()); obj.put("brojPrebivalista", docReq.getBrojPrebivalista()); obj.put("JMBG", docReq.getJmbg()); System.out.println("Json: " + obj.toString()); URL url = new URL(PERSO_SUBMIT_URL); HttpURLConnection submitConnection = (HttpURLConnection) url.openConnection(); submitConnection.setRequestMethod("POST"); submitConnection.setRequestProperty("Content-Type", "application/json"); submitConnection.setDoOutput(true); try (OutputStream os = submitConnection.getOutputStream()) { os.write(obj.toString().getBytes()); os.flush(); } if (submitConnection.getResponseCode() == 200){ docReq.setStatus("U produkciji"); em.getTransaction().begin(); // em.persist(docReq); em.merge(docReq); em.flush(); em.getTransaction().commit(); System.out.println("RESPONSE PERSO"); } else { System.out.println("SUBMIT PERSO FAILED"); } } } catch (JMSException | IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } } }
41.247788
106
0.544947
5d68e23ed62307f132ab1c2dd1330676f5f85195
2,003
/* * $Id$ * * 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.tiles.request.collection; import java.util.Enumeration; /** * Utilities for requests. * * @version $Rev: 1064782 $ $Date: 2011-01-28 18:08:52 +0100 (Fri, 28 Jan 2011) $ */ public final class CollectionUtil { /** * Constructor. */ private CollectionUtil() { } /** * Returns the string representation of the key. * * @param key The key. * @return The string representation of the key. * @throws IllegalArgumentException If the key is <code>null</code>. */ public static String key(Object key) { if (key == null) { throw new IllegalArgumentException(); } else if (key instanceof String) { return ((String) key); } else { return (key.toString()); } } /** * Returns the number of elements in an enumeration, by iterating it. * * @param keys The enumeration. * @return The number of elements. */ public static int enumerationSize(Enumeration<?> keys) { int n = 0; while (keys.hasMoreElements()) { keys.nextElement(); n++; } return n; } }
28.211268
81
0.637544
082d813ac4eef5b1c2e05f288e5081aeedf5454e
2,797
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package DECL|package|org.apache.camel.component.wordpress package|package name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|wordpress package|; end_package begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|wordpress operator|. name|api operator|. name|test operator|. name|WordpressMockServerTestSupport import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|test operator|. name|junit4 operator|. name|CamelTestSupport import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|AfterClass import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|BeforeClass import|; end_import begin_class DECL|class|WordpressComponentTestSupport specifier|public class|class name|WordpressComponentTestSupport extends|extends name|CamelTestSupport block|{ annotation|@ name|BeforeClass DECL|method|beforeClass () specifier|public specifier|static name|void name|beforeClass parameter_list|() throws|throws name|IOException block|{ name|WordpressMockServerTestSupport operator|. name|setUpMockServer argument_list|() expr_stmt|; block|} annotation|@ name|AfterClass DECL|method|afterClass () specifier|public specifier|static name|void name|afterClass parameter_list|() block|{ name|WordpressMockServerTestSupport operator|. name|tearDownMockServer argument_list|() expr_stmt|; block|} DECL|method|getServerBaseUrl () specifier|protected name|String name|getServerBaseUrl parameter_list|() block|{ return|return name|WordpressMockServerTestSupport operator|. name|getServerBaseUrl argument_list|() return|; block|} block|} end_class end_unit
19.289655
810
0.806578
bcfd95adecf7ca1837ec8984f21360b2445f3587
4,213
// Autor y desarrollador parcial o total: Santiago Hernández Plazas (santiago.h.plazas@gmail.com). /** * Paquete para conectarse a R */ package co.gov.ideamredd.R; import java.util.LinkedList; import java.util.Queue; import org.rosuda.JRI.RMainLoopCallbacks; import org.rosuda.JRI.Rengine; /** * Clase de entidad de comunicación con R * * @author Santiago Hernández Plazas (santiago.h.plazas@gmail.com) * */ class ComunicacionR implements RMainLoopCallbacks { /** * metodos propios implementados de la api JRI para hacer conexion desde Java al software estadistico R. */ public void rWriteConsole(Rengine re, String text, int oType) { System.out.print(text); } /** * Método vacío para determinar si r está ocupado */ public void rBusy(Rengine re, int which) { } /** * Leer la consola de R */ public String rReadConsole(Rengine re, String prompt, int addToHistory) { return null; } /** * Mostrar mensaje de r */ public void rShowMessage(Rengine re, String message) { System.out.println("rShowMessage \"" + message + "\""); } /** * Elegir archivo */ public String rChooseFile(Rengine re, int newFile) { return ""; } /** * Descargar la consulta */ public void rFlushConsole(Rengine re) { } /** * Cargar historial */ public void rLoadHistory(Rengine re, String filename) { } /** * Guardar historial */ public void rSaveHistory(Rengine re, String filename) { } } /** * Métodos de conexión y comunicación con R * * @author Santiago Hernández Plazas (santiago.h.plazas@gmail.com) * */ public class ConexionR { static ConexionR conexionR; static Rengine re; static private Queue<String> procesos; static private String serialActual = null; /** * Método que establece coneccion con R desde Java */ private ConexionR() { // String path = "/usr/java/jdk1.6.0_45/jre/lib/amd64/server:/usr/java/jdk1.6.0_45/jre/lib/amd64:/usr/java/jdk1.6.0_45/jre/../lib/amd64:/usr/lib64/R/lib:/usr/lib64/R/bin::/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib:"; // path+=System.getProperty("java.library.path"); // System.setProperty( "java.library.path",path); System.out.println(System.getProperty("java.library.path")); System.setProperty("java.library.path", System.getProperty("java.library.path") + ":/usr/lib64/R/lib:/usr/lib64/R/bin"); System.out.println(System.getProperty("java.library.path")); procesos = new LinkedList<String>(); String[] parametro = { "--no-save" }; re = new Rengine(parametro, false, new ComunicacionR()); System.out.println("Rengine creado, esperando respuesta de R"); if (!re.waitForR()) { System.out.println("No se pudo cargar R"); return; } } /** * Singleton del motor Rengine de JRI que establece comunicacion con R desde Java, manteniendo una unica instancia ejecutada del Rengine * * @return re instancia del Rengine */ public static Rengine getConexionR() { if (re == null) { conexionR = new ConexionR(); } return re; } /** * Retorna token * * @param serial */ public static void retornarToken(String serial) { try { conexionR.seguir(serial); } catch (InterruptedException e) { } } /** * Espera ejecución de R * * @param serial * @throws InterruptedException */ @SuppressWarnings("unused") private synchronized void esperar(String serial) throws InterruptedException { while (!serial.equals(serialActual)) { wait(); } } /** * Continua ejecución de R * * @param serial * @throws InterruptedException */ private synchronized void seguir(String serial) throws InterruptedException { if (serial.equals(serialActual)) { serialActual = procesos.poll(); re.eval("rm(list=ls())"); notify(); } } /** * Método main * * @param a */ public static void main(String[] a) { System.out.println(System.getProperty("java.library.path")); // procesos=new LinkedList<String>(); String[] parametro = { "--no-save" }; Rengine re1 = new Rengine(parametro, false, new ComunicacionR()); System.out.println("Rengine creado, esperando respuesta de R"); if (!re1.waitForR()) { System.out.println("No se pudo cargar R"); return; } } }
22.650538
236
0.678376
cd21f2eae25602e192b6f08c2b9975233d4f86ec
323
package com.bblog.test.support.hooks; import io.cucumber.java.After; import io.cucumber.java.Before; import io.restassured.RestAssured; public class Hooks { @After public void after() { } @Before public void before() { RestAssured.baseURI = "https://qa-task.backbasecloud.com/api/"; } }
17.944444
71
0.674923
d6598831ca41deca2ef643c2d8396cd28ff57aa5
1,710
package com; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; public class SocketProducer { public static void main(String[] args) throws InterruptedException { try { //1.建立客户端socket连接,指定服务器位置及端口 ServerSocket server = new ServerSocket(2222); Socket socket =server.accept(); //2.得到socket读写流 OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os); //输入流 InputStream is = socket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("D:\\admin\\Desktop\\log")); int tempchar; while ((tempchar = inputStreamReader.read()) != -1) { //屏蔽掉换行符 if (((char) tempchar) != '\r') { pw.write((char) tempchar); pw.flush(); } Thread.sleep(1); } //3.利用流按照一定的操作,对socket进行读写操作 //socket.shutdownOutput(); //接收服务器的相应 String reply = null; while (!((reply = br.readLine()) == null)) { System.out.println("接收服务器的信息:" + reply); } //4.关闭资源 inputStreamReader.close(); br.close(); is.close(); pw.close(); os.close(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
33.529412
120
0.519883
59fbde54777b8b3bf7ded76fe670b21828ea133f
1,139
package com.liueq.keyper.data.repository; import android.support.annotation.Nullable; import com.liueq.keyper.data.model.Account; import com.liueq.keyper.data.model.Tag; import java.util.List; /** * Created by liueq on 24/2/2016. * Tag Repository */ public interface TagRepo { /** * Get all tags in db * @return */ List<Tag> getAllTags(); /** * Insert a new tag or update the tag name */ String insertOrUpdateTag(@Nullable Tag tag); /** * Delete a tag * @param tag * @return */ boolean deleteTag(Tag tag); /** * Search tag by name * @param tag_name * @return */ List<Tag> searchTag(String tag_name); /** * Search db, is there tag exist with same name. * @param tag_name * @return */ boolean hasTag(String tag_name); List<Account> getAccountFromTag(Tag tag); List<Tag> getTagFromAccount(Account account); boolean addAccountTag(Account account, List<Tag> tags); boolean deleteAccountTag(Account account, Tag tag); /** * Replace an account`s all tags * @param account * @param tag_list * @return */ boolean replaceAccountTag(Account account, List<Tag> tag_list); }
17.796875
64
0.685689
8b5065c57b33136fc13c3d60a7e329ddcd94662d
4,546
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.fhwa.c2cri.centermodel; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.net.URL; import org.fhwa.c2cri.centermodel.emulation.exceptions.EntityEmulationException; /** * * @author TransCore ITS, LLC Created: Feb 9, 2016 */ public class EmulationDataFileProcessor { public static byte[] getByteArray(URL fileURL) throws EntityEmulationException { try { InputStream stream = fileURL.openStream(); // throws IOException byte results[] = getBytes(stream); // throws IOException stream.close(); return results; } catch (Exception ex) { throw new EntityEmulationException(ex); } } public static byte[] getByteArray(String fileName) throws EntityEmulationException { byte fileContent[] = null; try { //create file object File file = new File(fileName); //create FileInputStream object FileInputStream fis = new FileInputStream(file); fileContent = getBytes(fis); // fis.close(); // /* // * Create byte array large enough to hold the content of the file. // * Use File.length to determine size of the file in bytes. // */ // fileContent = new byte[(int) file.length()]; // // /* // * To read content of the file in byte array, use // * int read(byte[] byteArray) method of java FileInputStream class. // * // */ // fis.read(fileContent); // fis.close(); } catch (FileNotFoundException ex) { throw new EntityEmulationException(ex); } catch (IOException ex) { throw new EntityEmulationException(ex); } return fileContent; } private static byte[] getBytes(InputStream is) throws IOException { int len; int size = 1024; byte[] buf; if (is instanceof ByteArrayInputStream) { size = is.available(); buf = new byte[size]; len = is.read(buf, 0, size); } else { ByteArrayOutputStream bos = new ByteArrayOutputStream(); buf = new byte[size]; while ((len = is.read(buf, 0, size)) != -1) { bos.write(buf, 0, len); } buf = bos.toByteArray(); } return buf; } public static StringBuffer getContent(URL fileURL) throws EntityEmulationException { try { String filePath = fileURL.toURI().getPath(); return getContent(filePath); } catch (URISyntaxException ex) { throw new EntityEmulationException(ex); } } public static StringBuffer getContent(String fileName) throws EntityEmulationException { byte[] entityData = getByteArray(fileName); StringBuffer returnBuffer = getContent(entityData); return returnBuffer; } public static StringBuffer getContent(byte[] entityData) throws EntityEmulationException { StringBuffer returnBuffer = new StringBuffer(); if (entityData != null) { try { ByteArrayInputStream bInput = new ByteArrayInputStream(entityData); BufferedReader bfReader = null; bfReader = new BufferedReader(new InputStreamReader(bInput,"UTF-8")); String temp = null; while ((temp = bfReader.readLine()) != null) { // Each line should have be in an 'elementName = elementValue' format. // For each element, lookup it's SchemaId and determine it's entityId returnBuffer.append(temp).append("\n"); } bInput.close(); } catch (FileNotFoundException ex) { throw new EntityEmulationException(ex); } catch (IOException ex) { throw new EntityEmulationException(ex); } } return returnBuffer; } }
33.182482
94
0.592609
3826b6ed0f39f204832dbb9523a49fa0461a6af9
2,036
/* * Copyright (C) 2015 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package test; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.SettableFuture; import dagger.producers.Producer; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static com.google.common.truth.Truth.assertThat; @RunWith(JUnit4.class) public class ProducerFactoryTest { @Test public void noArgMethod() throws Exception { SimpleProducerModule module = new SimpleProducerModule(); Producer<String> producer = new SimpleProducerModule_StrFactory(module, MoreExecutors.directExecutor()); assertThat(producer.get().get()).isEqualTo("Hello, World!"); } @Test public void singleArgMethod() throws Exception { SimpleProducerModule module = new SimpleProducerModule(); SettableFuture<String> strFuture = SettableFuture.create(); Producer<String> strProducer = producerOfFuture(strFuture); Producer<Integer> producer = new SimpleProducerModule_LenFactory(module, MoreExecutors.directExecutor(), strProducer); assertThat(producer.get().isDone()).isFalse(); strFuture.set("abcdef"); assertThat(producer.get().get()).isEqualTo(6); } private static <T> Producer<T> producerOfFuture(final ListenableFuture<T> future) { return new Producer<T>() { @Override public ListenableFuture<T> get() { return future; } }; } }
36.357143
97
0.749018
efe73aa3b7dc3eded26c4f690f03efa9555c670a
925
package com.davidmarian_buzatu.benchme.tester; import com.davidmarian_buzatu.benchme.benchmark.IBenchmark; import com.davidmarian_buzatu.benchme.logging.ConsoleLogger; import com.davidmarian_buzatu.benchme.logging.ILogger; import com.davidmarian_buzatu.benchme.timing.ITimer; import com.davidmarian_buzatu.benchme.timing.TimeUnit; import com.davidmarian_buzatu.benchme.timing.Timer; public class TestRAM { public void test() { ITimer timer = new Timer(); ILogger log = new ConsoleLogger(); // IBenchmark benchmark = new CPUDigitsOfPi(); TimeUnit timeUnit = TimeUnit.SEC; final int limit = 123456; // for (int i = 0; i < 1; i++) { // timer.start(); // benchmark.run(2); // // log.writeTime("PI3 -> Finished in ", timer.stop(), timeUnit); // log.write(benchmark.getResult(3)); // benchmark.clean(); // } } }
33.035714
75
0.659459
8519e936b65cbad20988ad598a43286fe537150e
4,737
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project 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.killbill.commons.embeddeddb.postgresql; import org.killbill.commons.embeddeddb.EmbeddedDB; import org.postgresql.ds.PGSimpleDataSource; import javax.sql.DataSource; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; public class PostgreSQLEmbeddedDB extends EmbeddedDB { protected final AtomicBoolean started = new AtomicBoolean(false); protected final int port; private KillBillTestingPostgreSqlServer testingPostgreSqlServer; public PostgreSQLEmbeddedDB() { // Avoid dashes - PostgreSQL doesn't like them this("database" + UUID.randomUUID().toString().substring(0, 8), "user" + UUID.randomUUID().toString().substring(0, 8)); } public PostgreSQLEmbeddedDB(final String databaseName, final String username) { super(databaseName, username, null, null); this.port = getPort(); this.jdbcConnectionString = String.format("jdbc:postgresql://localhost:%s/%s?user=%s", port, databaseName, username); } @Override public DBEngine getDBEngine() { return DBEngine.POSTGRESQL; } @Override public void initialize() throws IOException { } @Override public void start() throws IOException { if (started.get()) { throw new IOException("PostgreSQL is already running: " + jdbcConnectionString); } startPostgreSql(); createDataSource(); refreshTableNames(); } @Override public void refreshTableNames() throws IOException { final String query = "select table_name from information_schema.tables where table_schema = current_schema() and table_type = 'BASE TABLE';"; try { executeQuery(query, new ResultSetJob() { @Override public void work(final ResultSet resultSet) throws SQLException { allTables.clear(); while (resultSet.next()) { allTables.add(resultSet.getString(1)); } } }); } catch (final SQLException e) { throw new IOException(e); } } @Override public DataSource getDataSource() throws IOException { if (!started.get()) { throw new IOException("PostgreSQL is not running"); } return super.getDataSource(); } @Override public void stop() throws IOException { if (!started.get()) { throw new IOException("PostgreSQL is not running"); } super.stop(); stopPostgreSql(); } @Override public String getCmdLineConnectionString() { return String.format("psql -U%s -p%s %s", username, port, databaseName); } protected void createDataSource() throws IOException { if (useConnectionPooling()) { dataSource = createHikariDataSource(); } else { final PGSimpleDataSource pgSimpleDataSource = new PGSimpleDataSource(); pgSimpleDataSource.setDatabaseName(databaseName); pgSimpleDataSource.setUser(username); pgSimpleDataSource.setUrl(jdbcConnectionString); dataSource = pgSimpleDataSource; } } private void startPostgreSql() throws IOException { try { this.testingPostgreSqlServer = new KillBillTestingPostgreSqlServer(username, port, databaseName); } catch (final Exception e) { throw new IOException(e); } started.set(true); logger.info("PostgreSQL started: " + getCmdLineConnectionString()); } private void stopPostgreSql() throws IOException { if (testingPostgreSqlServer != null) { testingPostgreSqlServer.close(); started.set(false); logger.info("PostgreSQL stopped: " + getCmdLineConnectionString()); } } }
32.668966
149
0.649778
ce36ff6e0c396f2253263553ab654a040e995895
377
package kelvin.mite.blocks; import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap; import net.minecraft.client.render.RenderLayer; public class MiteTallPlantBlock extends net.minecraft.block.TallPlantBlock { public MiteTallPlantBlock(Settings properties) { super(properties); BlockRenderLayerMap.INSTANCE.putBlock(this, RenderLayer.getCutout()); } }
26.928571
76
0.822281
08a8389c1366b2bd71e0dba3cc3509035cfbaef1
947
package frc.robot.oi.movements; import frc.robot.oi.controllers.XboxPositionAccessible; import frc.robot.oi.positions.ThumbstickPosition; // The values needed to drive using arcade mode. public class ArcadeMovement { public double straightSpeed = 0; // x Forward & Backward public double rotationSpeed = 0; // z Rotate public ArcadeMovement() { } public ArcadeMovement(double xStraightSpeed, double zRotationSpeed) { straightSpeed = xStraightSpeed; rotationSpeed = zRotationSpeed; } // Determines the arcade movement from the given xbox thumbstick position(s) public static ArcadeMovement getMovement(XboxPositionAccessible controller, boolean isYleftFlipped) { ThumbstickPosition pos = ThumbstickPosition.getPositions(controller, isYleftFlipped); ArcadeMovement move = new ArcadeMovement(pos.leftForwardBackPosition, pos.leftSideToSidePosition); return move; } }
33.821429
106
0.751848
6d2bcbe667e7a6be324563d6be5ee094cb7fc39b
7,858
package com.github.idegtiarenko.json.ui; import com.github.idegtiarenko.json.Json; import com.github.idegtiarenko.json.Node; import com.github.idegtiarenko.json.ui.components.BackgroundTaskExecutor; import com.github.idegtiarenko.json.ui.components.LabeledProgressBarTreeTableCell; import com.github.idegtiarenko.json.ui.components.MutableObservableValue; import com.github.idegtiarenko.json.ui.components.ProgressAndLabel; import javafx.application.Application; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.SplitPane; import javafx.scene.control.TextArea; import javafx.scene.control.TreeTableColumn; import javafx.scene.control.TreeTableView; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.FileChooser; import javafx.stage.Stage; import java.io.File; import java.util.Optional; import java.util.function.Function; import java.util.function.IntConsumer; import static com.github.idegtiarenko.json.FileSystem.sizeToString; import static com.github.idegtiarenko.json.ui.components.NodeUtils.fillHeight; import static com.github.idegtiarenko.json.ui.components.NodeUtils.fillWidth; import static javafx.scene.control.TreeTableView.CONSTRAINED_RESIZE_POLICY; public class JsonViewer extends Application { private static final String APP_NAME = "Json viewer"; public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) { var state = new MutableObservableValue<JsonViewerState>(); var fileChooser = new FileChooser(); var executor = new BackgroundTaskExecutor(); var root = new VBox( createMenu(stage, state, fileChooser, executor), createJsonViewer(state), executor.getLabeledProgressBar() ); stage.setTitle(APP_NAME); stage.setScene(new Scene(root)); stage.show(); getInitialFile().ifPresent(file -> openFile(state, executor, file)); } private MenuBar createMenu( Stage stage, MutableObservableValue<JsonViewerState> state, FileChooser fileChooser, BackgroundTaskExecutor executor ) { var open = new MenuItem("Open"); open.setOnAction(event -> { var file = fileChooser.showOpenDialog(stage); if (file != null) { fileChooser.setInitialDirectory(file.getParentFile()); } openFile(state, executor, file); }); var close = new MenuItem("Close"); close.setOnAction(event -> state.reset()); var exit = new MenuItem("Exit"); exit.setOnAction(event -> stage.close()); var about = new MenuItem("About"); about.setOnAction(event -> showAboutDialog()); return new MenuBar( new Menu("File", null, open, close, new SeparatorMenuItem(), exit), new Menu("Help", null, about) ); } private void openFile(MutableObservableValue<JsonViewerState> state, BackgroundTaskExecutor backgroundTaskExecutor, File file) { backgroundTaskExecutor.submit(new BackgroundTaskExecutor.Task<JsonViewerState>() { @Override public String getName() { return "Loading json file"; } @Override public int getTotalSize() { return file != null ? (int) file.length() : 0; } @Override public JsonViewerState execute(IntConsumer onProgress) { return JsonViewerState.from(file, onProgress); } @Override public void onSuccess(JsonViewerState result) { state.setValue(result); } @Override public void onFailure(Exception e) { state.setValue(null); showErrorDialogFor(e); } }); } private void showErrorDialogFor(Exception e) { var alert = new Alert(Alert.AlertType.ERROR); alert.setTitle(APP_NAME); alert.setHeaderText("An error has been encountered"); alert.setContentText(e.getMessage()); alert.showAndWait(); } private void showAboutDialog() { var about = new Alert(Alert.AlertType.INFORMATION); about.setTitle(APP_NAME); about.setHeaderText(APP_NAME); about.setContentText("https://github.com/idegtiarenko/json-viewer"); about.showAndWait(); } private VBox createJsonViewer(ObservableValue<JsonViewerState> state) { var path = new Text(); var preview = fillWidth(new TextArea()); preview.setEditable(false); var tree = fillWidth(new TreeTableView<Node>()); tree.setColumnResizePolicy(CONSTRAINED_RESIZE_POLICY); tree.getColumns().addAll( createColumn("name", 0.45, Node::getName), createColumn("direct" + System.lineSeparator() + "children", 0.15, Node::getChildrenCount), createLabeledProgressBarColumn("recursive" + System.lineSeparator() + "children", 0.2, node -> { var totalSize = state.getValue().node().getRecursiveChildrenCount(); var currentSize = node.getRecursiveChildrenCount(); return new ProgressAndLabel(currentSize, totalSize, Integer.toString(currentSize)); }), createLabeledProgressBarColumn("size", 0.2, node -> { var totalSize = state.getValue().node().getSize(); var currentSize = node.getSize(); return new ProgressAndLabel(currentSize, totalSize, sizeToString(currentSize)); }) ); tree.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { if (newValue != null) { path.setText(Json.toAbbreviatedJsonPath(newValue, 256)); preview.setText(Json.toAbbreviatedFormattedString(newValue.getValue(), 1024)); } else { path.setText(""); preview.setText(""); } }); state.addListener((observable, oldValue, newValue) -> tree.setRoot(newValue != null ? new JsonNodeTreeItem(newValue.node()) : null)); return fillHeight(new VBox( path, fillHeight(new SplitPane(tree, preview)) )); } private <T> TreeTableColumn<Node, T> createColumn(String name, double widthRatio, Function<Node, T> extractor) { TreeTableColumn<Node, T> column = new TreeTableColumn<>(name); column.setCellValueFactory(param -> new SimpleObjectProperty<>(extractor.apply(param.getValue().getValue()))); column.setMaxWidth(widthRatio * Double.MAX_VALUE); return column; } private TreeTableColumn<Node, ProgressAndLabel> createLabeledProgressBarColumn(String name, double widthRatio, Function<Node, ProgressAndLabel> extractor) { var column = new TreeTableColumn<Node, ProgressAndLabel>(name); column.setCellValueFactory(param -> { var node = param.getValue().getValue(); return new SimpleObjectProperty<>(extractor.apply(node)); }); column.setCellFactory(param -> new LabeledProgressBarTreeTableCell<>()); column.setMaxWidth(widthRatio * Double.MAX_VALUE); return column; } private Optional<File> getInitialFile() { return getParameters().getRaw().stream().map(File::new).filter(File::exists).findFirst(); } }
38.331707
160
0.64902
722bdb1066bcd840acd997b8427abfa37e9660e6
993
package com.custom.rest; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * Serializable class containing LCSProduct, LCSSKU, LCSProductSeasonLink, LCSSKUSeasonLink, LCSSeason * Including the List<FlexBOMPart>(s), FlexBOMLinks & LCSMaterials * Classes are ordered in a hierarchical structure and annotated using fasterxml.jackson.annotation */ @JsonPropertyOrder({ "LCSProduct", "FlexBOMPart" }) public class FlexBOMResponse { private List<FlexBOMPartProxy> flexBOMParts; private ProductProxy product; public FlexBOMResponse(ProductProxy product, List<FlexBOMPartProxy> flexBOMPart) { this.product = product; this.flexBOMParts = flexBOMPart; } @JsonProperty("LCSProduct") public ProductProxy getLCSProduct() { return product; } @JsonProperty("FlexBOMPart") public List<FlexBOMPartProxy> getFlexBOMPart() { return flexBOMParts; } }
27.583333
103
0.758308
12fbe3c78c35a0e130c1248a58e1806be0845c19
16,957
package com.jeecms.cms.action.admin.assist; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.jeecms.cms.Constants; import com.jeecms.cms.entity.back.CmsField; import com.jeecms.cms.manager.assist.CmsResourceMng; import com.jeecms.cms.manager.assist.CmsSqlserverDataBackMng; import com.jeecms.common.util.DateUtils; import com.jeecms.common.util.StrUtils; import com.jeecms.common.util.Zipper; import com.jeecms.common.util.Zipper.FileEntry; import com.jeecms.common.web.RequestUtils; import com.jeecms.common.web.ResponseUtils; import com.jeecms.common.web.springmvc.RealPathResolver; import com.jeecms.core.manager.CmsLogMng; import com.jeecms.core.web.WebErrors; @Controller public class SqlserverDataAct { private static String SUFFIX = "sql"; private static String BR = "\r\n"; private static String SLASH = "/"; private static String dbXmlFileName = "/WEB-INF/config/jdbc.properties"; private static String SPACE = " "; private static String BRANCH = ";"; private static String INSERT_INTO = " INSERT INTO "; private static String VALUES = "VALUES"; private static String LEFTBRACE = "("; private static String RIGHTBRACE = ")"; private static String QUOTES = "'"; private static String COMMA = ","; private static final String INVALID_PARAM = "template.invalidParams"; private static String backup_table; private static final Logger log = LoggerFactory.getLogger(ResourceAct.class); @RequiresPermissions("data:v_list") @RequestMapping("/sqlserver/data/v_list.do") public String list(ModelMap model, HttpServletRequest request, HttpServletResponse response) { List<String> tables = dataBackMng.listTabels(); model.addAttribute("tables", tables); return "data/list"; } @RequiresPermissions("data:v_listfields") @RequestMapping("/sqlserver/data/v_listfields.do") public String listfiled(String tablename, ModelMap model, HttpServletRequest request, HttpServletResponse response) { List<CmsField> list = dataBackMng.listFields(tablename); model.addAttribute("list", list); return "data/fields"; } @RequiresPermissions("data:v_revert") @RequestMapping("/sqlserver/data/v_revert.do") public String listDataBases(ModelMap model, HttpServletRequest request, HttpServletResponse response) { try { String defaultCatalog = dataBackMng.getDefaultCatalog(); model.addAttribute("defaultCatalog", defaultCatalog); } catch (SQLException e) { model.addAttribute("msg", e.toString()); return "common/error_message"; } List<String> databases = dataBackMng.listDataBases(); model.addAttribute("databases", databases); model.addAttribute("backuppath", Constants.BACKUP_PATH); return "data/databases"; } @RequiresPermissions("data:o_revert") @RequestMapping("/sqlserver/data/o_revert.do") public String revert(String filename, String db, ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException { String backpath = realPathResolver.get(Constants.BACKUP_PATH); String backFilePath = backpath + SLASH + filename; String sql = readFile(backFilePath); dataBackMng.executeSQL("use [" + db + "]" + BR); dataBackMng.executeSQL(sql); // 若db发生变化,需要处理jdbc try { String defaultCatalog = dataBackMng.getDefaultCatalog(); if (!defaultCatalog.equals(db)) { String dbXmlPath = realPathResolver.get(dbXmlFileName); dbXml(dbXmlPath, defaultCatalog, db); } } catch (Exception e) { model.addAttribute("msg", e.toString()); return "common/error_message"; } model.addAttribute("msg", "success"); return listDataBases(model, request, response); } @RequiresPermissions("data:o_backup") @RequestMapping("/sqlserver/data/o_backup.do") public String backup(String tableNames[], ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException { String backpath = realPathResolver.get(Constants.BACKUP_PATH); File backDirectory = new File(backpath); if (!backDirectory.exists()) { backDirectory.mkdir(); } DateUtils dateUtils = DateUtils.getDateInstance(); String backFilePath = backpath + SLASH + dateUtils.getNowString() + "." + SUFFIX; File file = new File(backFilePath); List<String> tables = dataBackMng.listTabels(); model.addAttribute("tables", tables); Thread thread = new DateBackupTableThread(file, tableNames); thread.start(); return "data/backupProgress"; } @RequiresPermissions("data:o_backup_progress") @RequestMapping({ "/sqlserver/data/o_backup_progress.do" }) public void getBackupProgress(HttpServletRequest request, HttpServletResponse response) throws JSONException { JSONObject json = new JSONObject(); json.put("tablename", backup_table); ResponseUtils.renderJson(response, json.toString()); } @RequiresPermissions("data:v_listfiles") @RequestMapping("/sqlserver/data/v_listfiles.do") public String listBackUpFiles(ModelMap model, HttpServletRequest request, HttpServletResponse response) { model.addAttribute("list", resourceMng.listFile(Constants.BACKUP_PATH, false)); return "data/files"; } @RequiresPermissions("data:v_selectfile") @RequestMapping("/sqlserver/data/v_selectfile.do") public String selectBackUpFiles(ModelMap model, HttpServletRequest request, HttpServletResponse response) { model.addAttribute("list", resourceMng.listFile(Constants.BACKUP_PATH, false)); return "data/selectfile"; } @RequiresPermissions("data:o_delete") @RequestMapping("/sqlserver/data/o_delete.do") public String delete(String root, String[] names, HttpServletRequest request, ModelMap model, HttpServletResponse response) { WebErrors errors = validateDelete(names, request); if (errors.hasErrors()) { return errors.showErrorPage(model); } int count = resourceMng.delete(names); log.info("delete Resource count: {}", count); for (String name : names) { log.info("delete Resource name={}", name); cmsLogMng.operating(request, "resource.log.delete", "filename=" + name); } model.addAttribute("root", root); return listBackUpFiles(model, request, response); } @RequiresPermissions("data:o_delete_single") @RequestMapping("/sqlserver/data/o_delete_single.do") public String deleteSingle(HttpServletRequest request, ModelMap model, HttpServletResponse response) { // TODO 输入验证 String name = RequestUtils.getQueryParam(request, "name"); WebErrors errors = validateDelete(new String[] { name }, request); if (errors.hasErrors()) { return errors.showErrorPage(model); } int count = resourceMng.delete(new String[] { name }); log.info("delete Resource {}, count {}", name, count); cmsLogMng.operating(request, "resource.log.delete", "filename=" + name); return listBackUpFiles(model, request, response); } @RequiresPermissions("data:v_rename") @RequestMapping(value = "/sqlserver/data/v_rename.do") public String renameInput(HttpServletRequest request, ModelMap model) { String name = RequestUtils.getQueryParam(request, "name"); String origName = name.substring(Constants.BACKUP_PATH.length()); model.addAttribute("origName", origName); return "data/rename"; } @RequiresPermissions("data:o_rename") @RequestMapping(value = "/sqlserver/data/o_rename.do", method = RequestMethod.POST) public String renameSubmit(String root, String origName, String distName, HttpServletRequest request, ModelMap model, HttpServletResponse response) { String orig = Constants.BACKUP_PATH + origName; String dist = Constants.BACKUP_PATH + distName; resourceMng.rename(orig, dist); log.info("name Resource from {} to {}", orig, dist); model.addAttribute("root", root); return listBackUpFiles(model, request, response); } @RequiresPermissions("data:o_export") @RequestMapping(value = "/sqlserver/data/o_export.do") public String exportSubmit(String[] names, ModelMap model, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException { if (validate(names, request)) { WebErrors errors = WebErrors.create(request); errors.addErrorCode(INVALID_PARAM); return errors.showErrorPage(model); } String backName = "back"; if (names != null && names.length > 0 && names[0] != null) { backName = names[0].substring(names[0].indexOf(Constants.BACKUP_PATH) + Constants.BACKUP_PATH.length() + 1); } List<FileEntry> fileEntrys = new ArrayList<FileEntry>(); response.setContentType("application/x-download;charset=UTF-8"); response.addHeader("Content-disposition", "filename=" + backName + ".zip"); for (String filename : names) { File file = new File(realPathResolver.get(filename)); fileEntrys.add(new FileEntry("", "", file)); } try { // 模板一般都在windows下编辑,所以默认编码为GBK Zipper.zip(response.getOutputStream(), fileEntrys, "GBK"); } catch (IOException e) { log.error("export db error!", e); } return null; } public void dbXml(String fileName, String oldDbHost, String dbHost) throws Exception { String s = FileUtils.readFileToString(new File(fileName)); s = StringUtils.replace(s, oldDbHost, dbHost); FileUtils.writeStringToFile(new File(fileName), s); } private String readFile(String filename) throws IOException { File file = new File(filename); if (filename == null || filename.equals("")) { throw new NullPointerException("<@s.m 'db.fileerror'/>"); } long len = file.length(); byte[] bytes = new byte[(int) len]; BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file)); int r = bufferedInputStream.read(bytes); if (r != len) // throw new IOException("<@s.m 'db.filereaderror'/>"); bufferedInputStream.close(); return new String(bytes, "utf-8"); } private WebErrors validateDelete(String[] names, HttpServletRequest request) { WebErrors errors = WebErrors.create(request); errors.ifEmpty(names, "names"); if (names != null && names.length > 0) { for (String name : names) { // 导出阻止非法获取其他目录文件 if (!name.contains("/WEB-INF/backup/") || name.contains("../") || name.contains("..\\")) { errors.addErrorCode(INVALID_PARAM); } } } else { errors.addErrorCode(INVALID_PARAM); } for (String id : names) { vldExist(id, errors); } return errors; } private boolean vldExist(String name, WebErrors errors) { if (errors.ifNull(name, "name")) { return true; } return false; } private boolean validate(String[] names, HttpServletRequest request) { if (names != null && names.length > 0) { for (String name : names) { // 导出阻止非法获取其他目录文件 if (!name.contains(Constants.BACKUP_PATH) || name.contains("../") || name.contains("..\\")) { return true; } } } else { return true; } return false; } private class DateBackupTableThread extends Thread { private File file; private String[] tablenames; public DateBackupTableThread(File file, String[] tablenames) { this.file = file; this.tablenames = tablenames; } public void run() { OutputStreamWriter writer = null; try { FileOutputStream out = new FileOutputStream(file); writer = new OutputStreamWriter(out, "utf8"); for (int i = 0; i < this.tablenames.length; i++) { backup_table = tablenames[i]; nocheckConstraint(writer, this.tablenames[i]); } for (int i = 0; i < this.tablenames.length; i++) { backup_table = tablenames[i]; backupTable(writer, this.tablenames[i]); } for (int i = 0; i < this.tablenames.length; i++) { backup_table = tablenames[i]; checkConstraint(writer, this.tablenames[i]); } backup_table = ""; writer.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } private String nocheckConstraint(OutputStreamWriter writer, String tablename) throws IOException { StringBuffer buffer = new StringBuffer(); buffer.append("ALTER TABLE " + tablename + " NOCHECK CONSTRAINT ALL; " + SqlserverDataAct.BR); writer.write(buffer.toString()); writer.flush(); return tablename; } private String checkConstraint(OutputStreamWriter writer, String tablename) throws IOException { StringBuffer buffer = new StringBuffer(); buffer.append("ALTER TABLE " + tablename + " CHECK CONSTRAINT ALL; " + SqlserverDataAct.BR); writer.write(buffer.toString()); writer.flush(); return tablename; } private String backupTable(OutputStreamWriter writer, String tablename) throws IOException { String sql = createOneTableSql(tablename); writer.write(sql); sql = createOneTableConstraintSql(sql, tablename); writer.write(sql); writer.flush(); return tablename; } private String createOneTableSql(String tablename) { StringBuffer buffer = new StringBuffer(); buffer.append(getNoCheckReference(tablename)); buffer.append(dataBackMng.createTableDDL(tablename)); List<Object[]> results = dataBackMng.createTableData(tablename); List<String> columns = dataBackMng.getColumns(tablename); if ((buffer.toString().contains(" IDENTITY")) && (results.size() > 0)) { buffer.append("SET IDENTITY_INSERT " + tablename + " ON" + SqlserverDataAct.BR); } for (int i = 0; i < results.size(); i++) { Object[] oneResult = (Object[]) results.get(i); buffer.append(createOneInsertSql(tablename, columns, oneResult)); } if ((buffer.toString().contains(" IDENTITY")) && (results.size() > 0)) { buffer.append("SET IDENTITY_INSERT " + tablename + " OFF" + SqlserverDataAct.BR); } return buffer.toString(); } private String createOneTableConstraintSql(String sql, String tablename) { StringBuffer buffer = new StringBuffer(); buffer.append(dataBackMng.createConstraintDDL(sql, tablename)); return buffer.toString(); } private String createOneInsertSql(String tablename, List<String> columns, Object[] oneResult) { StringBuffer buffer = new StringBuffer(); buffer.append(Constants.ONESQL_PREFIX + SqlserverDataAct.INSERT_INTO + tablename); buffer.append(SqlserverDataAct.LEFTBRACE); for (int colIndex = 0; colIndex < columns.size() - 1; colIndex++) { buffer.append("[" + (String) columns.get(colIndex) + "]" + SqlserverDataAct.COMMA); } buffer.append("[" + (String) columns.get(columns.size() - 1) + "]" + SqlserverDataAct.RIGHTBRACE); buffer.append(SqlserverDataAct.SPACE + SqlserverDataAct.VALUES + SqlserverDataAct.LEFTBRACE); for (int j = 0; j < oneResult.length; j++) { if (oneResult[j] != null) { if ((oneResult[j] instanceof Date)) buffer.append(SqlserverDataAct.QUOTES + oneResult[j] + SqlserverDataAct.QUOTES); else if ((oneResult[j] instanceof String)) buffer.append(SqlserverDataAct.QUOTES + // 整合版 StrUtils.replaceKeyString(oneResult[j].toString().replace("'", "")) + SqlserverDataAct.QUOTES); else if ((oneResult[j] instanceof Boolean)) { if (((Boolean) oneResult[j]).booleanValue()) buffer.append(1); else buffer.append(0); } else buffer.append(oneResult[j]); } else { buffer.append(oneResult[j]); } buffer.append(SqlserverDataAct.COMMA); } if (buffer.lastIndexOf(SqlserverDataAct.COMMA) != -1) buffer = buffer.deleteCharAt(buffer.lastIndexOf(SqlserverDataAct.COMMA)); buffer.append(RIGHTBRACE + BRANCH + BR); return buffer.toString(); } private String getNoCheckReference(String tablename) { Map<String, String> refers = dataBackMng.getBeReferForeignKeyFromTable(tablename); StringBuffer sqlBuffer = new StringBuffer(); Iterator<String> keyIt = refers.keySet().iterator(); if ((refers != null) && (!refers.isEmpty())) { while (keyIt.hasNext()) { String key = (String) keyIt.next(); sqlBuffer.append( "ALTER TABLE [" + (String) refers.get(key) + "]" + " DROP CONSTRAINT " + key + BR); } } return sqlBuffer.toString(); } } @Autowired private RealPathResolver realPathResolver; @Autowired private CmsSqlserverDataBackMng dataBackMng; @Autowired private CmsResourceMng resourceMng; @Autowired private CmsLogMng cmsLogMng; }
36.62419
117
0.727487
3f6695f39b3f12a483d3560dfd720a996dfbb2c7
1,093
class Unite { private boolean enVie; private int pointsDeVie; } class Hache {} class Arc {} interface Nain { public void frappeAvecHache(); } interface Elfe { public void tireFleche(); } interface Magicien { public void lanceSort(); } interface Cavalier { public void chevauche(); } class NainMagicien extends Unite implements Nain, Magicien { private int taille; private Hache hache; public void frappeAvecHache() {}; public void lanceSort() {}; } class NainCavalier extends Unite implements Nain, Cavalier { private int taille; private Hache hache; public void frappeAvecHache() {}; public void chevauche() {}; } class ElfeMagicien extends Unite implements Elfe, Magicien { private int poids; private Arc arc; public void tireFleche() {}; public void lanceSort() {}; } class ElfeCavalier extends Unite implements Elfe, Cavalier { private int poids; private Arc arc; public void tireFleche() {}; public void chevauche() {}; }
21.019231
69
0.643184
886466f08a6ce12b56bc50e1514e90fee171763e
288
package com.joker17.rdt_jpa_test.service; import com.joker17.rdt_jpa_test.base.BaseService; import com.joker17.rdt_jpa_test.domain.Goods; import org.springframework.stereotype.Service; @Service public class GoodsService extends BaseService<Goods, String> implements IGoodsService { }
24
87
0.836806
017416e7f854bd16188c2b5972e70c5aaddbef74
294
package com.elgendy.photoservice.service; import com.elgendy.photoservice.model.Photo; import java.util.List; public interface PhotoService { List<Photo> getAll(); Photo getOne(Integer id); void add(Photo photo); void update(Photo photo); void delete(Integer id); }
15.473684
44
0.714286
d6731630bc7cb8b4d0b108cfdc3b97e0d3e91481
1,587
package com.example.demo2.controller; import java.net.URI; import java.net.URISyntaxException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.example.demo2.domain.Medico; import com.example.demo2.repository.MedicoRepository; @RestController public class MedicoController { @Autowired private MedicoRepository repository; @GetMapping("/medicos") public ResponseEntity<Iterable<Medico>> getAll() { Iterable<Medico> medicos = repository.findAll(); return new ResponseEntity<>(medicos, HttpStatus.OK); } @PostMapping("/medicos") ResponseEntity<Medico> create( @RequestBody Medico record) throws URISyntaxException { Medico result = repository.save(record); return ResponseEntity.created(new URI("/medicos/" + result.getId())).body(result); } @DeleteMapping("/medicos/{id}") public ResponseEntity<?> delete(@PathVariable Long id) { repository.deleteById(id); return ResponseEntity.ok().build(); } }
26.45
90
0.712035
8102f886702901ccdb1402da8d190ab666682645
3,801
package com.the8team.dragonboatrace; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.World; /** * An obstacle, extended from MovingObject. * * @author Josh Stafford */ public class Obstacle extends MovingObject { // Characteristics public int damageDealt; public int horizontalVelocity; public int verticalVelocity; /** * Construct an obstacle. * * @param horizontalVelocity The horizontal velocity of the obstacle * @param verticalVelocity The vertical velocity of the obstacle * @param damageDealt How much damage it can deal * @param x The starting x coordinate * @param y The starting y coordinate * @param width The width * @param height The height * @param world The world in which to create the obstacle * @param textureFile The texture path for the obstacle */ public Obstacle(int horizontalVelocity, int verticalVelocity, int damageDealt, int x, int y, int width, int height, World world, String textureFile) { super(x, y, width, height, world, textureFile); this.damageDealt = damageDealt; this.horizontalVelocity = horizontalVelocity; this.verticalVelocity = verticalVelocity; } /** * Updates horizontal velocity. * * @param vel The velocity value to set */ public void setHorizontalVel(int vel) { // Sets class variable to passed value and then runs updateMovement() method this.horizontalVelocity = vel; this.updateMovement(); } /** * Updates vertical veolcity. * * @param vel The velocity value to set */ public void setVerticalVel(int vel) { // Sets class variable to passed value and then runs updateMovement() method this.verticalVelocity = vel; this.updateMovement(); } /** * Update the movement of the obstacle with the velocities. */ public void updateMovement() { // Sets obstacle velocity using class variables if (this.bBody != null) { this.bBody.setLinearVelocity(this.horizontalVelocity, this.verticalVelocity); } } /** * Function to check if obstacle has left the boundaries of the screen behind * the player and returns a boolean result. * * @param playerX The player's x coordinate * @return true if offscreen, false otherwise */ public boolean isOffScreen(int playerX) { float x = this.getPosition().x * Utils.scale; float screenWidth = Gdx.graphics.getWidth(); if (x < playerX - screenWidth / 2) { System.out.println("Obstacle has left the screen"); return true; } else { return false; } } /** * Reinstantiate function that takes parameters for position of moved obstacle. * * @param x The x coordinate to move to * @param y The y coordinate to move to */ public void reinstantiate(int x, int y) { this.bBody.getTransform().setPosition(new Vector2((float) x, (float) y)); } /** * Reinstantiate function that sets position of obstacle based on position of * player. * * @param playerX The player's x coordinate */ public void reinstantiate(int playerX) { float screenWidth = Gdx.graphics.getWidth(); float newX = (float) playerX + screenWidth / 2 + 4f; this.bBody.getTransform().setPosition(new Vector2(newX, this.getPosition().y)); } }
29.695313
120
0.604578
d7a0cc8703485da4b8a42efb689f8b0dcfdce5d6
1,910
/** * The MIT License * Copyright (c) 2014 Ilkka Seppälä * * 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.iluwatar.hexagonal.notifications; import com.iluwatar.hexagonal.domain.PlayerDetails; /** * * Provides notifications for lottery events. * */ public interface LotteryNotifications { /** * Notify lottery ticket was submitted */ void notifyTicketSubmitted(PlayerDetails details); /** * Notify there was an error submitting lottery ticket */ void notifyTicketSubmitError(PlayerDetails details); /** * Notify lottery ticket did not win */ void notifyNoWin(PlayerDetails details); /** * Notify that prize has been paid */ void notifyPrize(PlayerDetails details, int prizeAmount); /** * Notify that there was an error paying the prize */ void notifyPrizeError(PlayerDetails details, int prizeAmount); }
31.833333
80
0.743455
51190422f2ce894e5f2c667fe21d7ee571d6317e
2,623
/* * 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 tr.gov.turkiye.esign.support; import java.security.cert.X509Certificate; import java.util.ResourceBundle; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; /** * This extension lists certificate policies, recognized by the issuing CA, * that apply to the certificate, together with optional qualifier * information pertaining to these certificate policies * @author sercan */ public class CertificatePolicySupport { private static ResourceBundle bundle = null; /** * * @param key the oid for certificate policy * @return name of certificate policy name */ public static String getValue(final String key) { if (bundle == null) { bundle = ResourceBundle.getBundle("certificate/certificatePolicyIds"); } return bundle.getString(key); } /** * Checks whether given certificate has one of the predefined certificate policies. * @param cert certificate * @return true or false */ public static boolean checkCertificatePolicyIdentifier(final X509Certificate cert) { try { //Logger logger = Logger.getLogger(CertificatePolicySupport.class.toString()); //logger.info("CHECKING CERTIFICATE POLICY IDENTIFIER"); byte[] extensionValue = cert.getExtensionValue("2.5.29.32"); ASN1OctetString octs = (ASN1OctetString) ASN1Primitive.fromByteArray(extensionValue); ASN1Sequence sequence = (ASN1Sequence) ASN1Primitive.fromByteArray(octs.getOctets()); for (int i = 0; i < sequence.size(); i++) { ASN1Sequence subSequence = (ASN1Sequence) sequence.getObjectAt(i); ASN1ObjectIdentifier identifier = (ASN1ObjectIdentifier) subSequence.getObjectAt(0); String oidValue = getValue(identifier.getId()); if (oidValue != null) { //logger.info("CHECKING CERTIFICATE POLICY IDENTIFIER IS VALID : " + identifier.getId() + " - " + oidValue); return true; } else { //logger.info("CHECKING CERTIFICATE POLICY IDENTIFIER IS NOT VALID : " + identifier.getId()); } } return false; } catch (final Throwable e) { } return false; } }
39.149254
128
0.658406
8f282e78c4b305b07eb5b04f266ad5505ed06a8f
3,695
/* * Licensed to Gisaïa under one or more contributor * license agreements. See the NOTICE.txt file distributed with * this work for additional information regarding copyright * ownership. Gisaïa 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 io.arlas.server.rest.plugins.eo; import cyclops.control.Try; import io.arlas.server.core.exceptions.ArlasException; import io.arlas.server.core.exceptions.InternalServerErrorException; import io.arlas.server.core.model.RasterTileURL; import io.arlas.server.core.utils.Tile; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import java.util.Optional; public class URLBasedRasterTileProvider implements TileProvider <RasterTile>{ static { ImageIO.scanForPlugins(); } private RasterTileURL template; private int width =-1; private int height =-1; public static final String PATTERN_X="{x}"; public static final String PATTERN_Y="{y}"; public static final String PATTERN_Z="{z}"; private String pattern_x = PATTERN_X; private String pattern_y = PATTERN_Y; private String pattern_z = PATTERN_Z; public URLBasedRasterTileProvider(RasterTileURL template){ this.template=template; } public URLBasedRasterTileProvider(RasterTileURL template, int width, int height){ this.template=template; this.height=height; this.width=width; } @Override public Try<Optional<RasterTile>,ArlasException> getTile(Tile request) { return Try.withCatch(()->{ RasterTile tile = (request.getzTile() > template.maxZ || request.getzTile() < template.minZ)?null: new RasterTile(request.getxTile(), request.getyTile(), request.getzTile(), getImage(resolveURL(request))); return Optional.ofNullable(tile); },Error.class).mapFailure(e -> {e.printStackTrace();return new InternalServerErrorException("Can not fetch the tile "+request.getxTile()+"/"+request.getyTile()+"/"+request.getzTile(),e);}); } protected BufferedImage getImage(URL url) throws IOException { BufferedImage img = ImageIO.read(url); if(width>-1 && height>-1 && (img.getWidth()>width || img.getHeight()>height)){ return img.getSubimage(0,0,width, height); }else{ return img; } } protected URL resolveURL(Tile request) throws IOException { return new URL(template.url .replace(getPattern_x(), ""+request.getxTile()) .replace(getPattern_y(), ""+request.getyTile()) .replace(getPattern_z(), ""+request.getzTile())); } public String getPattern_x() { return pattern_x; } public void setPattern_x(String pattern_x) { this.pattern_x = pattern_x; } public String getPattern_y() { return pattern_y; } public void setPattern_y(String pattern_y) { this.pattern_y = pattern_y; } public String getPattern_z() { return pattern_z; } public void setPattern_z(String pattern_z) { this.pattern_z = pattern_z; } }
34.212963
197
0.686062
7c4ffd2c90e4f55cb538eb15f6398c51813a388f
621
package de.id.tigergraph.sdk.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import java.util.Map; @Data @JsonIgnoreProperties(ignoreUnknown = true) public class Edge { @JsonProperty("IsDirected") private boolean directed; @JsonProperty("ToVertexTypeName") private String toVertex; @JsonProperty("Config") private Map<String, String> config; @JsonProperty("Attributes") private String attributes; @JsonProperty("FromVertexTypeName") private String fromVertex; @JsonProperty("Name") private String name; }
20.032258
61
0.78905
8b7950de05071eab0577d54034646caadb2d2448
1,229
package com.wch.gulimall.member.web; import com.alibaba.fastjson.JSON; import com.wch.common.utils.R; import com.wch.gulimall.member.feign.OrderFeignService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; /** * @author wch * @version 1.0 * @date 2022/4/8 20:49 */ @Controller public class MemberWebController { @Autowired private OrderFeignService orderFeignService; /** * 支付成功以后的跳转页面 * @return */ @GetMapping("/member-order.html") public String memberOrderPage(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, Model model, HttpServletRequest request){ //获取支付宝给我们的数据, HashMap<String, Object> params = new HashMap<>(); params.put("page", pageNum.toString()); R r = orderFeignService.getOrderList(params); model.addAttribute("orders",r); return "orderList"; } }
28.581395
103
0.707079
c343acf5bb1ff0c8e938ab693bb5e1e70cdd7790
2,950
/* * Copyright (c) 2014 Red Hat, Inc. and others * * Red Hat 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 io.vertx.config.impl.spi; import io.vertx.config.ConfigRetriever; import io.vertx.config.spi.ConfigStore; import io.vertx.config.spi.ConfigStoreFactory; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.config.spi.ConfigProcessor; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.After; import org.junit.Before; import org.junit.runner.RunWith; import java.util.concurrent.atomic.AtomicBoolean; import static org.awaitility.Awaitility.await; import static org.hamcrest.CoreMatchers.is; /** * @author <a href="http://escoffier.me">Clement Escoffier</a> */ @RunWith(VertxUnitRunner.class) public abstract class ConfigStoreTestBase { public static final ConfigProcessor JSON = new JsonProcessor(); public static final ConfigProcessor PROPERTIES = new PropertiesConfigProcessor(); protected Vertx vertx; protected ConfigStoreFactory factory; protected ConfigStore store; protected ConfigRetriever retriever; @Before public void setUp(TestContext context) { vertx = Vertx.vertx(); vertx.exceptionHandler(context.exceptionHandler()); } @After public void tearDown() { AtomicBoolean done = new AtomicBoolean(); if (store != null) { store.close(v -> done.set(true)); await().untilAtomic(done, is(true)); done.set(false); } if (retriever != null) { retriever.close(); } vertx.close(v -> done.set(true)); await().untilAtomic(done, is(true)); } protected void getJsonConfiguration(Vertx vertx, ConfigStore store, Handler<AsyncResult<JsonObject>> handler) { store.get(buffer -> { if (buffer.failed()) { handler.handle(Future.failedFuture(buffer.cause())); } else { JSON.process(vertx, new JsonObject(), buffer.result(), handler); } }); } protected void getPropertiesConfiguration(Vertx vertx, ConfigStore store, Handler<AsyncResult<JsonObject>> handler) { store.get(buffer -> { if (buffer.failed()) { handler.handle(Future.failedFuture(buffer.cause())); } else { PROPERTIES.process(vertx, new JsonObject(), buffer.result(), handler); } }); } }
30.102041
119
0.715254
31dd35b10db13cf133b1315630030be22c0a476d
8,107
package moeam.db.queryTest; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Date; import moeam.db.query.driver.DatabaseDriver; import org.junit.AfterClass; import org.junit.BeforeClass; public abstract class AbstractQueryTest { private static final String USERS_TABLE = "users"; private static final String GAMES_TABLE = "games"; private static final String TOPICS_TABLE = "topics"; private static final String POSTS_TABLE = "posts"; /** Create a new DB connection */ private static Connection m_connection = new DatabaseDriver().openConnection(); private static PreparedStatement m_statement; /** Create all the tables and populate them with default data */ @BeforeClass public static void createTables() { // Drop tables before recreating them deleteTables(); // Create tables createUsersTable(); createGamesTable(); createTopicsTable(); createPostsTable(); // Create table data createUser(); createGame(); createTopic(); createPost(); } private static void createUsersTable() { try { // Create table String createUsersTable = "CREATE TABLE " + USERS_TABLE + " ("; createUsersTable += "P_userId int PRIMARY KEY NOT NULL AUTO_INCREMENT UNIQUE,"; createUsersTable += "userName VARCHAR(30),"; createUsersTable += "password VARCHAR(30))"; m_statement = m_connection.prepareStatement(createUsersTable); m_statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } private static void createGamesTable() { try { // Create table String createGamesTable = "CREATE TABLE " + GAMES_TABLE + " ("; createGamesTable += "P_gameId int PRIMARY KEY NOT NULL AUTO_INCREMENT UNIQUE,"; createGamesTable += "gameName VARCHAR(15),"; createGamesTable += "companyName VARCHAR(15),"; createGamesTable += "downloadLink VARCHAR(50),"; createGamesTable += "description VARCHAR(300))"; m_statement = m_connection.prepareStatement(createGamesTable); m_statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } private static void createTopicsTable() { try { // Create table String createTopicsTable = "CREATE TABLE " + TOPICS_TABLE + " ("; createTopicsTable += "P_topicId int PRIMARY KEY NOT NULL AUTO_INCREMENT UNIQUE,"; createTopicsTable += "F_gameId int, FOREIGN KEY (F_gameId) REFERENCES games(P_gameId),"; createTopicsTable += "topicName VARCHAR(20),"; createTopicsTable += "dateCreated DATE)"; m_statement = m_connection.prepareStatement(createTopicsTable); m_statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } private static void createPostsTable() { try { // Create table String createPostsTable = "CREATE TABLE " + POSTS_TABLE + " ("; createPostsTable += "P_postId int PRIMARY KEY NOT NULL AUTO_INCREMENT UNIQUE,"; createPostsTable += "F_topicId int, FOREIGN KEY (F_topicId) REFERENCES topics(P_topicId),"; createPostsTable += "F_userId int, FOREIGN KEY (F_userId) REFERENCES users(P_userId),"; createPostsTable += "contents VARCHAR(500),"; createPostsTable += "dateCreated DATE)"; m_statement = m_connection.prepareStatement(createPostsTable); m_statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } private static void createUser() { final String userName = "User1"; final String password = "User1Password"; try { String insertUserData = "INSERT INTO users (userName, password) VALUES (?, ?)"; m_statement = m_connection.prepareStatement(insertUserData); m_statement.setString(1, userName); m_statement.setString(2, password); m_statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } private static void createGame() { final String gameName = "Game1"; final String companyName = "Company1"; final String downloadLink = "http://Game1.Company1.com/"; final String description = "Description1"; try { String insertGameData = "INSERT INTO games (gameName, companyName, downloadLink, description) VALUES (?, ?, ?, ?)"; m_statement = m_connection.prepareStatement(insertGameData); m_statement.setString(1, gameName); m_statement.setString(2, companyName); m_statement.setString(3, downloadLink); m_statement.setString(4, description); m_statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } private static void createTopic() { final int gameId = 1; final String topicName = "Topic1"; final Date date = new Date(); final java.sql.Date sqlDate = new java.sql.Date(date.getTime()); try { String insertGameData = "INSERT INTO topics (F_gameId, topicName, dateCreated) VALUES (?, ?, ?)"; m_statement = m_connection.prepareStatement(insertGameData); m_statement.setInt(1, gameId); m_statement.setString(2, topicName); m_statement.setDate(3, sqlDate); m_statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } private static void createPost() { final int topicId = 1; final int userId = 1; final String contents = "Post1Content"; final Date date = new Date(); final java.sql.Date sqlDate = new java.sql.Date(date.getTime()); try { String insertPostData = "INSERT INTO posts (F_topicId, F_userId, contents, dateCreated) VALUES (?, ?, ?, ?)"; m_statement = m_connection.prepareStatement(insertPostData); m_statement.setInt(1, topicId); m_statement.setInt(2, userId); m_statement.setString(3, contents); m_statement.setDate(4, sqlDate); m_statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } @AfterClass public static void deleteTables() { try { String dropPostsTable = "DROP TABLE IF EXISTS " + POSTS_TABLE; m_statement = m_connection.prepareStatement(dropPostsTable); m_statement.executeUpdate(); String dropTopicsTable = "DROP TABLE IF EXISTS " + TOPICS_TABLE; m_statement = m_connection.prepareStatement(dropTopicsTable); m_statement.executeUpdate(); String dropGamesTable = "DROP TABLE IF EXISTS " + GAMES_TABLE; m_statement = m_connection.prepareStatement(dropGamesTable); m_statement.executeUpdate(); String dropUsersTable = "DROP TABLE IF EXISTS " + USERS_TABLE; m_statement = m_connection.prepareStatement(dropUsersTable); m_statement.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
33.639004
128
0.576539
905c6be5aa067d00c7ff7b50834d8dee166fb966
3,988
/* * Cardinal-Components-API * Copyright (C) 2019-2020 OnyxStudios * * 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 dev.onyxstudios.componenttest; import dev.onyxstudios.componenttest.vita.AmbientVita; import dev.onyxstudios.componenttest.vita.Vita; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.block.BlockState; import net.minecraft.client.MinecraftClient; import net.minecraft.client.item.TooltipContext; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.server.world.ServerWorld; import net.minecraft.text.Text; import net.minecraft.text.TranslatableText; import net.minecraft.util.Hand; import net.minecraft.util.TypedActionResult; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import javax.annotation.Nullable; import java.util.List; public class VitalityStickItem extends Item { public VitalityStickItem(Settings settings) { super(settings); } @Override public TypedActionResult<ItemStack> use(World world, PlayerEntity player, Hand hand) { ItemStack stack = player.getStackInHand(hand); Vita vita = Vita.get(stack); if (vita.getVitality() > 0 && !world.isClient) { if (player.isSneaking()) { AmbientVita worldVita = (AmbientVita) Vita.get( world.random.nextInt(10) == 0 ? world.getLevelProperties() : world ); vita.transferTo(worldVita, 1); worldVita.syncWithAll(((ServerWorld)world).getServer()); } else { vita.transferTo(Vita.get(player), vita.getVitality()); } } return TypedActionResult.pass(stack); } @Override public boolean postHit(ItemStack stack, LivingEntity target, LivingEntity holder) { // The entity may not have the component, but the stack always does. TestComponents.VITA.maybeGet(target) .ifPresent(v -> v.transferTo(Vita.get(stack), 1)); return true; } @Environment(EnvType.CLIENT) @Override public void appendTooltip(ItemStack stack, @Nullable World world, List<Text> lines, TooltipContext ctx) { super.appendTooltip(stack, world, lines, ctx); lines.add(new TranslatableText("componenttest:tooltip.vitality", TestComponents.VITA.get(stack).getVitality())); PlayerEntity holder = MinecraftClient.getInstance().player; if (holder != null) { lines.add(new TranslatableText("componenttest:tooltip.self_vitality", TestComponents.VITA.get(holder).getVitality())); } } @Override public boolean canMine(BlockState block, World world, BlockPos pos, PlayerEntity player) { return !player.isCreative(); } }
41.541667
130
0.704614
b4cdbae8c9db40d95d89e30e1a893e8dbe1259b9
1,520
package com.wanandroid.module_home.mvp.di.module; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.LinearLayout; import com.alibaba.android.arouter.launcher.ARouter; import com.jess.arms.base.DefaultAdapter; import com.jess.arms.di.component.AppComponent; import com.jess.arms.di.scope.ActivityScope; import com.jess.arms.http.imageloader.ImageLoader; import com.jess.arms.utils.ArmsUtils; import com.wanandroid.module_home.mvp.contract.HomeContract; import com.wanandroid.module_home.mvp.model.HomeModel; import com.wanandroid.module_home.mvp.model.entity.HomeBean; import com.wanandroid.module_home.mvp.ui.fragment.adapter.HomeListAdapter; import java.util.ArrayList; import java.util.List; import dagger.Binds; import dagger.Module; import dagger.Provides; @Module public abstract class HomeModule { @Binds abstract HomeContract.Model bindGoldModel(HomeModel model); @ActivityScope @Provides static LinearLayoutManager provideLayoutManager(HomeContract.View view) { return new LinearLayoutManager(view.getActivity(), LinearLayout.VERTICAL, false); } @ActivityScope @Provides static List<HomeBean.DatasBean> provideGoldHomeData() { return new ArrayList(); } @ActivityScope @Provides static HomeListAdapter provideGoldHomeAdapter(HomeContract.View view,List<HomeBean.DatasBean> data) { return new HomeListAdapter(view,data); } }
29.803922
105
0.7875
fbcdb0bd6e1c2a3f8c712bc93021bba733a35139
8,437
package com.forkexec.rst.ws; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.jws.WebService; import com.forkexec.rst.domain.Restaurant; import com.forkexec.rst.domain.RestaurantMenu; import com.forkexec.rst.domain.RestaurantMenuId; import com.forkexec.rst.domain.RestaurantMenuOrder; import com.forkexec.rst.domain.RestaurantMenuOrderId; import com.forkexec.rst.domain.exceptions.*; /** * This class implements the Web Service port type (interface). The annotations * below "map" the Java class to the WSDL definitions. */ @WebService(endpointInterface = "com.forkexec.rst.ws.RestaurantPortType", wsdlLocation = "RestaurantService.wsdl", name ="RestaurantWebService", portName = "RestaurantPort", targetNamespace="http://ws.rst.forkexec.com/", serviceName = "RestaurantService" ) public class RestaurantPortImpl implements RestaurantPortType { /** * The Endpoint manager controls the Web Service instance during its whole * lifecycle. */ private RestaurantEndpointManager endpointManager; /** Constructor receives a reference to the endpoint manager. */ public RestaurantPortImpl(RestaurantEndpointManager endpointManager) { this.endpointManager = endpointManager; } // Main operations ------------------------------------------------------- @Override public Menu getMenu(MenuId menuId) throws BadMenuIdFault_Exception { if (menuId == null) { throwBadMenuId("MenuId cannot be null"); } String id = menuId.getId().trim(); if (id.length() == 0) throwBadMenuId("MenuId cannot be empty or whitespace"); // Access restaurantServer Restaurant restaurantServer = Restaurant.getInstance(); RestaurantMenu menu = null; // Accesses all menus and shows the wanted menu synchronized(restaurantServer) { try { menu = restaurantServer.getMenu(id); } catch (BadMenuIdFaultException e) { throwBadMenuId("MenuId not found"); } } return this.buildMenuInfo(menu); } @Override public List<Menu> searchMenus(String descriptionText) throws BadTextFault_Exception { if (descriptionText== null) { throwBadText("Description cannot be null"); } String descriptionTrimmed = descriptionText.trim(); if (descriptionTrimmed.length() == 0) throwBadText("Description cannot be empty or whitespace"); // Access restaurantServer Restaurant restaurantServer = Restaurant.getInstance(); List<RestaurantMenu> list = null; List<Menu> menu_list = new ArrayList<Menu>(); // Accesses all menus and looks for menus with wanted food synchronized(restaurantServer) { list = restaurantServer.searchMenus(descriptionTrimmed); } Iterator<RestaurantMenu> restaurantMenuIterator = list.iterator(); while (restaurantMenuIterator.hasNext()) { menu_list.add(this.buildMenuInfo(restaurantMenuIterator.next())); } return menu_list; } @Override public MenuOrder orderMenu(MenuId arg0, int arg1) throws BadMenuIdFault_Exception, BadQuantityFault_Exception, InsufficientQuantityFault_Exception { if (arg0 == null) { throwBadMenuId("Description cannot be null"); } // Access restaurantServer Restaurant restaurantServer = Restaurant.getInstance(); RestaurantMenuOrder menuOrder = null; synchronized(restaurantServer) { try { menuOrder = restaurantServer.orderMenu(arg0.getId(), arg1); } catch (BadMenuIdFaultException e) { this.throwBadMenuId("Invalid menu id"); } catch (BadQuantityFaultException e) { this.throwBadQuantity("Invalid quantity"); } catch (InsufficientQuantityFaultException e) { this.throwInsufficientQuantity("Insufficient Quantity"); } } return this.buildMenuOrderInfo(menuOrder); } // Control operations ---------------------------------------------------- /** Diagnostic operation to check if service is running. */ @Override public String ctrlPing(String inputMessage) { // If no input is received, return a default name. if (inputMessage == null || inputMessage.trim().length() == 0) inputMessage = "friend"; // If the park does not have a name, return a default. String wsName = this.endpointManager.getWsName(); if (wsName == null || wsName.trim().length() == 0) wsName = "Restaurant"; // Build a string with a message to return. StringBuilder builder = new StringBuilder(); builder.append("Hello ").append(inputMessage); builder.append(" from ").append(wsName); return builder.toString(); } /** Return all variables to default values. */ @Override public void ctrlClear() { Restaurant.getInstance().resetRestaurantServer(); } /** Set variables with specific values. */ @Override public void ctrlInit(List<MenuInit> initialMenus) throws BadInitFault_Exception { if (initialMenus == null) { throwBadInit("Initial Menus cannot be null"); } // Access restaurantServer Restaurant restaurantServer = Restaurant.getInstance(); synchronized(restaurantServer) { Iterator<MenuInit> menuInitIterator = initialMenus.iterator(); while (menuInitIterator.hasNext()) { MenuInit menuInitAux = menuInitIterator.next(); Menu menuAux = menuInitAux.getMenu(); RestaurantMenu menu = new RestaurantMenu(new RestaurantMenuId(menuAux.getId().getId()) ,menuAux.getEntree(), menuAux.getPlate(), menuAux.getDessert(), menuAux.getPrice(), menuAux.getPreparationTime(), menuInitAux.getQuantity()); try { restaurantServer.addMenu(menu); } catch(BadInitFaultException exception) { throwBadInit("Cannot add menu with invalid properties"); } } } } // View helpers ---------------------------------------------------------- /** Helper to convert a Menu object to a view. */ private Menu buildMenuInfo(RestaurantMenu menu) { Menu info = new Menu(); info.setId(this.buildMenuIdInfo(menu.getId())); info.setEntree(menu.getEntree()); info.setPlate(menu.getMainCourse()); info.setDessert(menu.getDessert()); info.setPrice(menu.getPrice()); info.setPreparationTime(menu.getPreparationTime()); return info; } /** Helper to convert a MenuId object to a view. */ private MenuId buildMenuIdInfo(RestaurantMenuId id) { MenuId info = new MenuId(); info.setId(id.getId()); return info; } /** Helper to convert a RestaurantMenuOrder object to a view. */ private MenuOrder buildMenuOrderInfo(RestaurantMenuOrder menu) { MenuOrder info = new MenuOrder(); info.setId(this.buildMenuOrderIdInfo(menu.getId())); info.setMenuId(this.buildMenuIdInfo(menu.getMenuId())); info.setMenuQuantity(menu.getMenuQuantity()); return info; } /** Helper to convert a RestaurantMenuOrderId object to a view. */ private MenuOrderId buildMenuOrderIdInfo(RestaurantMenuOrderId id) { MenuOrderId info = new MenuOrderId(); info.setId(id.getId()); return info; } // Exception helpers ----------------------------------------------------- /** Helper to throw a new BadInit exception. */ private void throwBadInit(final String message) throws BadInitFault_Exception { BadInitFault faultInfo = new BadInitFault(); faultInfo.message = message; throw new BadInitFault_Exception(message, faultInfo); } /** Helper to throw a new BadMenuId exception. */ private void throwBadMenuId(final String message) throws BadMenuIdFault_Exception { BadMenuIdFault faultInfo = new BadMenuIdFault(); faultInfo.message = message; throw new BadMenuIdFault_Exception(message, faultInfo); } /** Helper to throw a new BadQuantity exception. */ private void throwBadQuantity(final String message) throws BadQuantityFault_Exception { BadQuantityFault faultInfo = new BadQuantityFault(); faultInfo.message = message; throw new BadQuantityFault_Exception(message, faultInfo); } /** Helper to throw a new BadText exception. */ private void throwBadText(final String message) throws BadTextFault_Exception { BadTextFault faultInfo = new BadTextFault(); faultInfo.message = message; throw new BadTextFault_Exception(message, faultInfo); } /** Helper to throw a new InsufficientQuantity exception. */ private void throwInsufficientQuantity(final String message) throws InsufficientQuantityFault_Exception { InsufficientQuantityFault faultInfo = new InsufficientQuantityFault(); faultInfo.message = message; throw new InsufficientQuantityFault_Exception(message, faultInfo); } }
33.086275
155
0.716724
fd9873ca60f62503aec7cfc53fd6610c1cfed188
1,717
package com.frestoinc.maildemo.data.local.room; import com.frestoinc.maildemo.data.model.AccountUser; import com.frestoinc.maildemo.data.model.EasFolder; import com.frestoinc.maildemo.data.model.EasMessage; import com.frestoinc.maildemo.data.model.GalContact; import java.util.List; import io.reactivex.Completable; import io.reactivex.Maybe; import io.reactivex.Single; /** * Created by frestoinc on 11,December,2019 for MailDemo. */ public interface RoomHelper { /** * ACCOUNT USERS. */ Single<List<AccountUser>> getAllAccounts(); Single<AccountUser> getAccount(String email); Maybe<AccountUser> getSessionAccount(); Completable insertAccount(AccountUser user); Completable deleteAllAccounts(); Completable updateSession(String email, int i); /** * EAS FOLDERS. */ Single<List<EasFolder>> getAllFolders(); Single<EasFolder> getFolder(int id); Completable insertFolder(EasFolder folder); Completable insertFolders(List<EasFolder> folders); Completable deleteFolder(int id); Completable deleteAllFolder(); /** * EAS MESSAGES. */ Single<List<EasMessage>> getFolderMessages(String id); Single<List<EasMessage>> getAllMessages(); Single<EasMessage> getEasMessage(int key); Completable insertMessages(List<EasMessage> messages); Completable updateMessage(EasMessage message); Completable deleteMessage(String id); Completable deleteAllMessage(); /** * Contacts. */ Completable insertContact(GalContact contact); Completable deleteContact(String email); Single<GalContact> getContact(String email); Single<List<GalContact>> getAllContacts(); }
22.012821
58
0.721607
6652feb4dd72c998735baed64fa488b0788b9e14
12,320
/* * Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. * * Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. * * BK-BASE 蓝鲸基础平台 is licensed under the MIT License. * * License for BK-BASE 蓝鲸基础平台: * -------------------------------------------------------------------- * 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.tencent.bk.base.dataflow.ml.node; import com.tencent.bk.base.dataflow.core.conf.ConstantVar; import com.tencent.bk.base.dataflow.core.conf.ConstantVar.DataNodeType; import com.tencent.bk.base.dataflow.core.conf.ConstantVar.HdfsTableFormat; import com.tencent.bk.base.dataflow.core.conf.ConstantVar.PeriodUnit; import com.tencent.bk.base.dataflow.core.conf.ConstantVar.TableType; import com.tencent.bk.base.dataflow.core.topo.Node.AbstractBuilder; import com.tencent.bk.base.dataflow.spark.sql.topology.builder.periodic.PeriodicSQLHDFSSinkNodeBuilder; import com.tencent.bk.base.dataflow.spark.sql.topology.builder.periodic.PeriodicSQLIcebergSinkBuilder; import com.tencent.bk.base.dataflow.spark.sql.topology.helper.TopoBuilderScalaHelper$; import com.tencent.bk.base.dataflow.spark.utils.CommonUtil$; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import scala.Tuple2; public class ModelSinkBuilderFactory extends AbstractModelBuilderFactory { private Map<String, Object> sourceNodes; public ModelSinkBuilderFactory(String jobType, long scheduleTime, Map<String, Object> sourceNodes) { super(jobType, scheduleTime); this.sourceNodes = sourceNodes; } @Override public AbstractBuilder getBuilder(Map<String, Object> sinkNodeInfo) { this.nodeInfo = sinkNodeInfo; //获取基本信息 ConstantVar.DataNodeType sinkNodeType = ConstantVar.DataNodeType .valueOf(this.nodeInfo.get("type").toString()); Map<String, Object> outputInfo = (Map<String, Object>) this.nodeInfo.get("output"); ConstantVar.TableType tableType = ConstantVar.TableType.valueOf(outputInfo .getOrDefault("table_type", TableType.other.toString()).toString()); ConstantVar.HdfsTableFormat hdfsTableFormat = getHdfsTableFormat(outputInfo.get("format").toString()); Map<String, Object> sinkConfMap = this.getConfigMap(tableType, hdfsTableFormat, sinkNodeType); switch (sinkNodeType) { case model: return new ModelDefaultSinkNode.ModelDefaultSinkNodeBuilder(sinkConfMap); case data: switch (tableType) { case query_set: switch (hdfsTableFormat) { case iceberg: return new ModelIceBergQuerySetSinkNode.ModelIceBergQuerySetSinkNodeBuilder( sinkConfMap); case parquet: return new ModelDefaultSinkNode.ModelDefaultSinkNodeBuilder(sinkConfMap); default: throw new RuntimeException("Not supported table format:" + hdfsTableFormat); } case result_table: switch (hdfsTableFormat) { case parquet: return new PeriodicSQLHDFSSinkNodeBuilder(sinkConfMap); case iceberg: return new PeriodicSQLIcebergSinkBuilder(sinkConfMap); default: throw new RuntimeException("Not supported table type:" + tableType); } default: throw new RuntimeException("Not supported table type:" + hdfsTableFormat); } default: throw new RuntimeException("Not supported sink node type:" + sinkNodeType); } } /** * 根据sink节点类型(model或data)得到节点的配置信息,以供后续生成具体的node节点 * * @param tableType 表类型:query_set或result_table * @param hdfsTableFormat hdfs上文件类型:parquet或iceberg * @param sinkNodeType 节点类型:model或data * @return 具体的配置信息,包括路径,存储等 */ @Override public Map<String, Object> getConfigMap(TableType tableType, HdfsTableFormat hdfsTableFormat, DataNodeType sinkNodeType) { Map<String, Object> sinkNodeConfMap = new HashMap<>(); // 加入基本信息 Map<String, Object> outputInfo = (Map<String, Object>) this.nodeInfo.get("output"); String sinkNodeId = this.nodeInfo.get("id").toString(); sinkNodeConfMap.put("id", sinkNodeId); sinkNodeConfMap.put("name", sinkNodeId); sinkNodeConfMap.put("job_type", jobType); sinkNodeConfMap.put("storages", (Map<String, Object>) this.nodeInfo.get("storages")); sinkNodeConfMap.put("schedule_time", scheduleTime); sinkNodeConfMap.put("output_mode", outputInfo.get("mode").toString()); sinkNodeConfMap.put("fields", this.nodeInfo.get("fields")); sinkNodeConfMap.put("output", outputInfo); if (sinkNodeType == DataNodeType.model) { sinkNodeConfMap.put("type", sinkNodeType.toString()); } //加入iceberg的信息 if (hdfsTableFormat == HdfsTableFormat.iceberg) { Map<String, Object> icebergConf = (Map<String, Object>) outputInfo.get("iceberg_config"); // todo:为规避出错,暂时只取hdfs_config中的hive.metastore.uris Map<String, Object> icebergHdfsConf = (Map<String, Object>) icebergConf.get("hdfs_config"); Map<String, Object> finalIcebergConf = new HashMap<>(); finalIcebergConf.put("hive.metastore.uris", icebergHdfsConf.get("hive.metastore.uris")); sinkNodeConfMap.put("iceberg_table_name", icebergConf.get("physical_table_name").toString()); sinkNodeConfMap.put("iceberg_conf", finalIcebergConf); } //加入时间属性 if (tableType == TableType.query_set) { sinkNodeConfMap.put("dt_event_time", 0L); sinkNodeConfMap.put("type", sinkNodeType.toString()); } else if (tableType == TableType.result_table) { // 加入窗口信息 Tuple2 minWindow = this.getWindowSize(); int minWindowSize = ((Integer) minWindow._1()).intValue(); ConstantVar.PeriodUnit minWindowUnit = (ConstantVar.PeriodUnit) minWindow._2(); sinkNodeConfMap.put("min_window_size", minWindowSize); sinkNodeConfMap.put("min_window_unit", minWindowUnit); sinkNodeConfMap.put("type", ConstantVar.Role.batch.toString()); long scheduleTimeInHour = CommonUtil$.MODULE$.roundScheduleTimeStampToHour(scheduleTime); long dtEventTimeStamp = TopoBuilderScalaHelper$.MODULE$.getDtEventTimeInMs( scheduleTimeInHour, minWindowSize, minWindowUnit); sinkNodeConfMap.put("dt_event_time", dtEventTimeStamp); } return sinkNodeConfMap; } /** * 计算得到非累加窗口(滚动窗口)的窗口大小 * * @param windowInfo 窗口信息 * @return 返回计算得到的窗口大小 */ public int getNonAccumulateWindowSize(Map<String, Object> windowInfo) { int windowSize; ConstantVar.PeriodUnit windowSizePeriod = ConstantVar.PeriodUnit .valueOf(windowInfo.get("window_size_period").toString().toLowerCase()); switch (windowSizePeriod) { case hour: windowSize = Double.valueOf(windowInfo.get("window_size").toString()).intValue(); break; case day: windowSize = 24 * Double.valueOf(windowInfo.get("window_size").toString()).intValue(); break; case week: windowSize = 7 * 24 * Double.valueOf(windowInfo.get("window_size").toString()).intValue(); break; case month: windowSize = Double.valueOf(windowInfo.get("window_size").toString()).intValue(); break; default: windowSize = 1; } return windowSize; } /** * 返回需要减小1时的窗口信息 * * @param scheduleUnit 调度周期 * @param countFreq 调度频率 * @param unit 调度单位 * @param windowSizeCollect 用于存储windowsize的列表 * @return 返回计算后的调度单位 */ public ConstantVar.PeriodUnit dealWithMinus1WindowSize(ConstantVar.PeriodUnit scheduleUnit, int countFreq, List<Integer> windowSizeCollect, ConstantVar.PeriodUnit unit) { int windowSize = 1; switch (scheduleUnit) { case hour: windowSize = countFreq; break; case day: windowSize = 24 * countFreq; break; case week: windowSize = 7 * 24 * countFreq; break; case month: unit = ConstantVar.PeriodUnit.month; windowSize = countFreq; break; default: windowSize = countFreq; break; } windowSizeCollect.add(windowSize); return unit; } /** * 根据source内所有输入表的窗口信息,获取最小窗口 */ public Tuple2 getWindowSize() { List<Integer> windowSizeCollect = new ArrayList<>(); boolean hasMinus1WindowSize = false; //父表调度单位 ConstantVar.PeriodUnit unit = ConstantVar.PeriodUnit.hour; // 当前表调度单位 ConstantVar.PeriodUnit scheduleUnit = ConstantVar.PeriodUnit.hour; int countFreq = 1; for (Map.Entry<String, Object> table : sourceNodes.entrySet()) { String sourceType = ((Map<String, Object>) table.getValue()).get("type").toString(); if (!"data".equalsIgnoreCase(sourceType)) { continue; } Map<String, Object> windowInfo = (Map<String, Object>) ((Map<String, Object>) table.getValue()) .get("window"); // 其实每个table内的schedule_period都是一样的 scheduleUnit = ConstantVar.PeriodUnit.valueOf(windowInfo.get("schedule_period").toString().toLowerCase()); countFreq = Integer.parseInt(windowInfo.get("count_freq").toString()); int windowSize; Boolean accumuate = Boolean.valueOf(windowInfo.get("accumulate").toString()); if (accumuate) { windowSize = 1; } else { windowSize = this.getNonAccumulateWindowSize(windowInfo); ConstantVar.PeriodUnit windowSizePeriod = ConstantVar.PeriodUnit .valueOf(windowInfo.get("window_size_period").toString().toLowerCase()); if (windowSizePeriod == PeriodUnit.month) { unit = ConstantVar.PeriodUnit.month; } } if (windowSize == -1) { hasMinus1WindowSize = true; } else { windowSizeCollect.add(windowSize); } } if (hasMinus1WindowSize && windowSizeCollect.isEmpty()) { unit = this.dealWithMinus1WindowSize(scheduleUnit, countFreq, windowSizeCollect, unit); } return new Tuple2(Collections.min(windowSizeCollect), unit); } }
47.022901
118
0.625731
23157b62dde607c19111002d8395fa3780f4df46
6,533
package io.opensphere.core.util.javafx.input.view; import java.util.regex.Pattern; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.value.ObservableIntegerValue; import javafx.beans.value.ObservableValue; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; /** * A stylized spinner, in which the up and down arrows are presented above and * below the content area, respectively. This spinner was developed for use in * the time picker, to allow for each component of a clock to be spun * independently. The component was developed generically to allow for any * numeric values to be represented. */ public class BoundNumericSpinner extends VBox { /** * The name of the style class used to skin the component. */ private static final String DEFAULT_STYLE_CLASS = "time-spinner"; /** * The pattern used for validation. */ private static final Pattern VALIDATION_PATTERN = Pattern.compile("\\d{1,2}"); /** * The button pressed to move the spinner's value up. */ private final Button myUpButton; /** * The button pressed to move the spinner's value down. */ private final Button myDownButton; /** * The component in which the content is rendered. */ private final TextField myContent; /** * The maximum value of the spinner, expressed exclusively. */ private final int myMaxValue; /** * The minimum value of the spinner expressed inclusively. */ private final int myMinValue; /** * The total distance between the maximum value and the minimum value. */ private final int myFieldSpan; /** * The property through which value changes are propagated. */ private final IntegerProperty myValue; /** * Creates a new numeric spinner, with the a minimum value of zero, and a * maximum value of the supplied value. * * @param pMaxValue the maximum value of the spinner. */ @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") public BoundNumericSpinner(int pMaxValue) { myMaxValue = pMaxValue; myMinValue = 0; myFieldSpan = myMaxValue - myMinValue; getStyleClass().add(DEFAULT_STYLE_CLASS); myUpButton = new Button(); myUpButton.getStyleClass().add("up-button"); StackPane upArrow = new StackPane(); upArrow.getStyleClass().add("up-arrow"); upArrow.setMaxSize(USE_PREF_SIZE, USE_PREF_SIZE); myUpButton.setGraphic(upArrow); myUpButton.setOnAction(pEvent -> increment()); myContent = new TextField("00"); myContent.getStyleClass().add("value"); myContent.textProperty().addListener((pObservable, pOldValue, pNewValue) -> validate(pObservable, pOldValue, pNewValue)); myDownButton = new Button(); myDownButton.getStyleClass().add("down-button"); myDownButton.setOnAction(pEvent -> decrement()); StackPane downArrow = new StackPane(); downArrow.getStyleClass().add("down-arrow"); downArrow.setMaxSize(USE_PREF_SIZE, USE_PREF_SIZE); myDownButton.setGraphic(downArrow); getChildren().add(myUpButton); getChildren().add(myContent); getChildren().add(myDownButton); setOnScroll(pEvent -> { if (pEvent.getDeltaY() > 0) { increment(); } else { decrement(); } }); myValue = new SimpleIntegerProperty(0); } /** * Validates the supplied value. This method is used as an event handler, * and is called when the {@link #myContent} field changes. This method has * a side-effect of resetting the value of the {@link #myContent} field to * the old value if the new value fails validation. * * @param pObservable the item that triggered the event. * @param pOldValue the original value of the field before it was changed. * @param pNewValue the new value of the field to validate. */ protected void validate(ObservableValue<? extends String> pObservable, String pOldValue, String pNewValue) { if (!pObservable.equals(myContent.textProperty())) { // validate that only numbers are entered: if (!VALIDATION_PATTERN.matcher(pNewValue).matches()) { myContent.textProperty().set(pOldValue); } else { // validate that only valid numbers are entered: int value = Integer.parseInt(pNewValue); if (value >= myMaxValue || value < myMinValue) { myContent.textProperty().set(pOldValue); } else { myContent.textProperty().set(String.format("%02d", Integer.valueOf(value))); } } } } /** * Gets the value of the {@link #myValue} field. * * @return the value stored in the {@link #myValue} field. */ public ObservableIntegerValue value() { return myValue; } /** * Sets the value of the spinner to the supplied value. * * @param pValue the value to which to set the spinner. */ public void set(int pValue) { myContent.textProperty().set(String.format("%02d", Integer.valueOf(pValue))); myValue.set(pValue); } /** * Adjusts the value of the spinner, and fires off notification through the * {@link #myValue} property. */ public void increment() { int value = Integer.parseInt(myContent.textProperty().get()) + 1; if (value >= myMaxValue) { value -= myFieldSpan; } myContent.textProperty().set(String.format("%02d", Integer.valueOf(value))); myValue.set(value); } /** * Adjusts the value of the spinner, and fires off notification through the * {@link #myValue} property. */ public void decrement() { int value = Integer.parseInt(myContent.textProperty().get()) - 1; if (value < myMinValue) { value += myFieldSpan; } myContent.textProperty().set(String.format("%02d", Integer.valueOf(value))); myValue.set(value); } }
31.258373
129
0.618399
fa87b5fc8b923ba4ec5ec4bae7cd44ad42f5e1dd
2,549
package com.santiagoapps.sleepadviser.activities.profile; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.santiagoapps.sleepadviser.R; public class ProfilingActivity_occupation extends AppCompatActivity { String occupation , name, gender; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profiling_occupation); //get intents Intent intent = getIntent(); Bundle bd = intent.getExtras(); gender = (String) bd.get("SESSION_GENDER"); name = (String) bd.get("SESSION_NAME"); Button btnChoice3 = findViewById(R.id.occ_choice3); btnChoice3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { occupation = "Etc."; Intent intent = new Intent(getBaseContext(), ProfilingActivity_age.class); intent.putExtra("SESSION_OCCUPATION", occupation); intent.putExtra("SESSION_GENDER", gender); intent.putExtra("SESSION_NAME", name); startActivity(intent); overridePendingTransition(R.anim.fade_in,R.anim.fade_out); } }); Button btnChoice2 = findViewById(R.id.occ_choice2); btnChoice2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { occupation = "Employee"; Intent intent = new Intent(getBaseContext(), ProfilingActivity_age.class); intent.putExtra("SESSION_OCCUPATION", occupation); intent.putExtra("SESSION_GENDER", gender); intent.putExtra("SESSION_NAME", name); startActivity(intent); } }); Button btnChoice1 = findViewById(R.id.occ_choice1); btnChoice1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { occupation = "Student"; Intent intent = new Intent(getBaseContext(), ProfilingActivity_age.class); intent.putExtra("SESSION_OCCUPATION", occupation); intent.putExtra("SESSION_GENDER", gender); intent.putExtra("SESSION_NAME", name); startActivity(intent); } }); } }
38.044776
90
0.622205
7cb8b3c317609901b0463ed48db738bdc2f0ed1b
2,407
package net.sourceforge.squirrel_sql.client.session.mainpanel; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import net.sourceforge.squirrel_sql.fw.util.StringManager; import net.sourceforge.squirrel_sql.fw.util.StringManagerFactory; public class SQLHistoryItemWrapper { /** Internationalized strings for this class. */ private static final StringManager s_stringMgr = StringManagerFactory.getStringManager(SQLHistoryItemWrapper.class); private static final String[] COLUMNS = new String[] { // i18n[SQLHistoryItemWrapper.index=Index] s_stringMgr.getString("SQLHistoryItemWrapper.index"), // i18n[SQLHistoryItemWrapper.lastUsed=Last used] s_stringMgr.getString("SQLHistoryItemWrapper.lastUsed"), // i18n[SQLHistoryItemWrapper.sql=SQL] s_stringMgr.getString("SQLHistoryItemWrapper.sql"), }; private static final SimpleDateFormat LAST_USAGE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); public static ArrayList<SQLHistoryItemWrapper> wrap(ArrayList<SQLHistoryItem> items) { ArrayList<SQLHistoryItemWrapper> ret = new ArrayList<SQLHistoryItemWrapper>(items.size()); int i=0; for (SQLHistoryItem item : items) { ret.add(new SQLHistoryItemWrapper(item, ++i)); } Collections.reverse(ret); return ret; } public static String[] getColumns() { return COLUMNS; } public static int getSQLColIx() { return 2; } private SQLHistoryItem _item; private int _index; private String _upperCaseSQL; private String _lastUsageTimeString; public SQLHistoryItemWrapper(SQLHistoryItem item, int index) { _item = item; _index = index; _upperCaseSQL = item.getSQL().toUpperCase(); if(null != _item.getLastUsageTime()) { _lastUsageTimeString = LAST_USAGE_DATE_FORMAT.format(_item.getLastUsageTime()); } } public Object getColum(int column) { // corresponding to COLUMNS switch(column) { case 0: return _index; case 1: return _lastUsageTimeString; case 2: return _item.getSQL(); default: throw new IllegalArgumentException("Unknown colum index " + column); } } public String getUpperCaseSQL() { return _upperCaseSQL; } }
25.606383
114
0.687993
fa32935518551ebac1447bbfe4efef947cd6a53b
999
package com.nukkitx.protocol.bedrock.v291.serializer; import com.nukkitx.protocol.bedrock.BedrockPacketHelper; import com.nukkitx.protocol.bedrock.BedrockPacketSerializer; import com.nukkitx.protocol.bedrock.packet.PlayStatusPacket; import io.netty.buffer.ByteBuf; import lombok.AccessLevel; import lombok.NoArgsConstructor; import static com.nukkitx.protocol.bedrock.packet.PlayStatusPacket.Status; @NoArgsConstructor(access = AccessLevel.PROTECTED) public class PlayStatusSerializer_v291 implements BedrockPacketSerializer<PlayStatusPacket> { public static final PlayStatusSerializer_v291 INSTANCE = new PlayStatusSerializer_v291(); @Override public void serialize(ByteBuf buffer, BedrockPacketHelper helper, PlayStatusPacket packet) { buffer.writeInt(packet.getStatus().ordinal()); } @Override public void deserialize(ByteBuf buffer, BedrockPacketHelper helper, PlayStatusPacket packet) { packet.setStatus(Status.values()[buffer.readInt()]); } }
37
98
0.804805
531169606d4c3cb88c0ef8271378d130230be0d6
5,301
/* * SoapUI, Copyright (C) 2004-2016 SmartBear Software * * Licensed under the EUPL, Version 1.1 or - as soon as they will be approved by the European Commission - subsequen * versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * http://ec.europa.eu/idabc/eupl * * Unless required by applicable law or agreed to in writing, software distributed under the Licence is * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the Licence for the specific language governing permissions and limitations * under the Licence. */ package com.eviware.soapui.impl.wsdl.support.wsrm; import com.eviware.soapui.config.WsrmConfigConfig; import com.eviware.soapui.config.WsrmVersionTypeConfig; import com.eviware.soapui.support.PropertyChangeNotifier; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.math.BigInteger; public class WsrmConfig implements PropertyChangeNotifier { private WsrmConfigConfig wsrmConfig; private String sequenceIdentifier; private Long lastMessageId; private String uuid; private PropertyChangeSupport propertyChangeSupport; private final WsrmContainer container; public WsrmConfig(WsrmConfigConfig wsrmConfig, WsrmContainer container) { this.setWsrmConfig(wsrmConfig); this.container = container; this.setPropertyChangeSupport(new PropertyChangeSupport(this)); lastMessageId = 1l; if (!wsrmConfig.isSetVersion()) { wsrmConfig.setVersion(WsrmVersionTypeConfig.X_1_2); } } public void addPropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.addPropertyChangeListener(listener); } public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { propertyChangeSupport.addPropertyChangeListener(propertyName, listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.removePropertyChangeListener(listener); } public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { propertyChangeSupport.removePropertyChangeListener(propertyName, listener); } public void setWsrmConfig(WsrmConfigConfig wsrmConfig) { this.wsrmConfig = wsrmConfig; } public WsrmConfigConfig getWsrmConfig() { return wsrmConfig; } public void setPropertyChangeSupport(PropertyChangeSupport propertyChangeSupport) { this.propertyChangeSupport = propertyChangeSupport; } public PropertyChangeSupport getPropertyChangeSupport() { return propertyChangeSupport; } public WsrmContainer getContainer() { return container; } public void setAckTo(String newAckTo) { String oldValue = wsrmConfig.getAckTo(); wsrmConfig.setAckTo(newAckTo); propertyChangeSupport.firePropertyChange("ackTo", oldValue, newAckTo); } public String getAckTo() { return wsrmConfig.getAckTo(); } public String getOfferEndpoint() { return wsrmConfig.getOfferEndpoint(); } public void setSequenceExpires(BigInteger newTimeout) { BigInteger oldValue = wsrmConfig.getSequenceExpires(); wsrmConfig.setSequenceExpires(newTimeout); propertyChangeSupport.firePropertyChange("sequenceExpires", oldValue, newTimeout); } public void setOfferEndpoint(String endpointUri) { String oldValue = wsrmConfig.getOfferEndpoint(); wsrmConfig.setOfferEndpoint(endpointUri); propertyChangeSupport.firePropertyChange("offerEndpoint", oldValue, endpointUri); } public BigInteger getSequenceExpires() { return wsrmConfig.getSequenceExpires(); } public void setWsrmEnabled(boolean enable) { boolean oldValue = isWsrmEnabled(); container.setWsrmEnabled(enable); propertyChangeSupport.firePropertyChange("wsrmEnabled", oldValue, enable); } public boolean isWsrmEnabled() { return container.isWsrmEnabled(); } public void setVersion(String arg0) { String oldValue = getVersion(); wsrmConfig.setVersion(WsrmVersionTypeConfig.Enum.forString(arg0)); propertyChangeSupport.firePropertyChange("version", oldValue, arg0); } public String getVersion() { return wsrmConfig.getVersion().toString(); } public void setSequenceIdentifier(String sequenceIdentifier) { this.sequenceIdentifier = sequenceIdentifier; } public String getSequenceIdentifier() { return sequenceIdentifier; } public Long nextMessageId() { this.lastMessageId++; return lastMessageId; } public Long getLastMessageId() { return lastMessageId; } public void setLastMessageId(long msgId) { lastMessageId = msgId; } public void setUuid(String uuid) { this.uuid = uuid; } public String getUuid() { return uuid; } public String getVersionNameSpace() { return WsrmUtils.getWsrmVersionNamespace(wsrmConfig.getVersion()); } }
31.553571
116
0.722882
2484868cca1af9ca78d8cc91dbc785b77e21bc45
2,340
package fr.pizzeria.doa.pizza; import java.io.IOException; import java.math.BigDecimal; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import fr.pizzeria.exception.DaoException; import fr.pizzeria.exception.NotImplementException; import fr.pizzeria.model.CategoriePizza; import fr.pizzeria.model.Pizza; public class PizzaDaoImplFile implements IPizzaDao { private static final String REPERTOIRE_DATA = "data"; @Override public Set<Pizza> findAllPizzas() { try (Stream<Path> stream = Files.list(Paths.get(REPERTOIRE_DATA));){ return stream.map(path -> { Pizza p = new Pizza(); p.setCode(path.getFileName().toString().replaceAll(".txt", "")); String line; try { line = Files.readAllLines(path).get(0); String[] ligneTab = line.split(";"); p.setNom(ligneTab[0]); p.setPrix(new BigDecimal(ligneTab[1])); p.setCategorie(CategoriePizza.valueOf(ligneTab[2])); } catch (IOException e) { e.printStackTrace(); } return p; }).collect(Collectors.toSet()); } catch (IOException e) { throw new DaoException(e); } } private String convertPizzaToString(Pizza p) { return p.getNom() + ";" + p.getPrix() + ";" + p.getCategorie().name(); } @Override public void saveNewPizza(Pizza newPizza){ try { Path nouveauFichier = Paths.get(REPERTOIRE_DATA + "/" + newPizza.getCode() + ".txt"); Files.write(nouveauFichier, Arrays.asList(convertPizzaToString(newPizza)), StandardOpenOption.CREATE_NEW); } catch (IOException e) { throw new DaoException(e); } } @Override public void updatePizza(String codePizza, Pizza updatePizza) throws DaoException { // TODO Auto-generated method stub } @Override public void deletePizza(String codePizza) throws DaoException { // TODO Auto-generated method stub } @Override /** * Fonstionnalité non accessible pour cette dao */ public boolean transactionInsertPizza(List<Pizza> p) { throw new NotImplementException("Veuillez configurer l'application avec une implémentation base de données"); } }
28.192771
112
0.694017
150ffd63d022c6c694242d5dfccdccf7f8bf8174
2,829
/* * 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.hyracks.storage.am.lsm.invertedindex.tokenizers; import java.io.IOException; import org.apache.hyracks.data.std.util.GrowableArray; import org.apache.hyracks.util.string.UTF8StringUtil; public class HashedUTF8WordToken extends UTF8WordToken { private int hash = 0; public HashedUTF8WordToken(byte tokenTypeTag, byte countTypeTag) { super(tokenTypeTag, countTypeTag); } @Override public boolean equals(Object o) { if (o == null) { return false; } if (!(o instanceof IToken)) { return false; } IToken t = (IToken) o; if (t.getTokenLength() != tokenLength) { return false; } int offset = 0; for (int i = 0; i < tokenLength; i++) { if (UTF8StringUtil.charAt(t.getData(), t.getStartOffset() + offset) != UTF8StringUtil.charAt(data, startOffset + offset)) { return false; } offset += UTF8StringUtil.charSize(data, startOffset + offset); } return true; } @Override public int hashCode() { return hash; } @Override public void reset(byte[] data, int startOffset, int endOffset, int tokenLength, int tokenCount) { super.reset(data, startOffset, endOffset, tokenLength, tokenCount); // pre-compute hash value using JAQL-like string hashing int pos = startOffset; hash = GOLDEN_RATIO_32; for (int i = 0; i < tokenLength; i++) { hash ^= Character.toLowerCase(UTF8StringUtil.charAt(data, pos)); hash *= GOLDEN_RATIO_32; pos += UTF8StringUtil.charSize(data, pos); } hash += tokenCount; } @Override public void serializeToken(GrowableArray out) throws IOException { if (tokenTypeTag > 0) { out.getDataOutput().write(tokenTypeTag); } // serialize hash value out.getDataOutput().writeInt(hash); } }
32.147727
110
0.639802
bae91404d05d7daad0b6cd6d06cc818210e54a94
851
package org.DataBase; import java.sql.ResultSet; import java.sql.SQLException; /** * データベースを扱うための共通インターフェース * @author max * */ public interface DataBaseAccess { // SQL実行 /** * DML文のSelectが主に使用されます * @param sql SQL文を受け取る変数 * @return ResultSetクラスのメタデータを返します * @throws SQLException SQLが受け付けなかった場合に発生する例外 * @throws NullPointerException アクセスができない場合に発生します */ // select文 public ResultSet SearchSQLExecute(String sql) throws SQLException; /** * DDL,DCL,トランザクション処理などのデータベース管理やチューニングなどに使用するためのSQLで使用します * @param sql SQL文を受け取る変数 * @return ResultSetクラスのメタデータを返します * @throws SQLException SQLが受け付けなかった場合に発生する例外 * @throws NullPointerException アクセスができない場合に発生します */ // insert, update, delete文 public int UpdateSQLExecute(String sql) throws SQLException; /** * データベースを閉じるためのメソッド */ public void close(); }
20.756098
67
0.741481
746033266026a06f5ce0d5e09fbbbc77b1d34522
2,545
package com.start.quick.entity; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import javax.persistence.*; import java.util.Calendar; import java.util.Date; @Entity public class Carousel { /** * 主键 */ @Id private String id; /** * 图片地址 */ private String imageUrl; /** * 背景色 */ private String backgroundColor; /** * 商品id */ private String itemId; /** * 商品分类id */ private String categoryId; /** * 轮播图类型 轮播图类型,用于判断,可以根据商品id或者分类进行页面跳转,1:商品 2:分类 */ private Integer type; /** * 轮播图展示顺序 */ private Integer sort; /** * 是否展示 */ private Integer isShow; /** * 创建时间 */ @CreatedDate @Column(columnDefinition = "DATETIME") private Calendar createTime; /** * 更新时间 */ @LastModifiedDate @Column(columnDefinition = "DATETIME") private Calendar updateTime; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getBackgroundColor() { return backgroundColor; } public void setBackgroundColor(String backgroundColor) { this.backgroundColor = backgroundColor; } public String getItemId() { return itemId; } public void setItemId(String itemId) { this.itemId = itemId; } public String getCategoryId() { return categoryId; } public void setCategoryId(String categoryId) { this.categoryId = categoryId; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public Integer getIsShow() { return isShow; } public void setIsShow(Integer isShow) { this.isShow = isShow; } public Calendar getCreateTime() { return createTime; } public void setCreateTime(Calendar createTime) { this.createTime = createTime; } public Calendar getUpdateTime() { return updateTime; } public void setUpdateTime(Calendar updateTime) { this.updateTime = updateTime; } }
17.312925
60
0.588212
a4926664f5c848859606ead6c3454439426f4be0
912
package se.cygni.paintbot.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; @Service public class AuthenticationService { TokenService tokenService; Map<String, String> users = new HashMap<String, String>() {{ put("emil", "lime"); put("chen", "nehc"); put("johannes", "sennahoj"); }}; @Autowired public AuthenticationService(TokenService tokenService) { this.tokenService = tokenService; } public String authenticate(String login, String password) throws Exception { if (users.containsKey(login)) { String pwd = users.get(login); if (pwd.equals(password)) { return tokenService.createToken(); } } throw new Exception("Invalid credentials"); } }
24.648649
80
0.64693
be913bd0a6b8153ea8a383249e09b078c0063e10
1,849
package net.FENGberd.Nukkit.FNPC.npc; import cn.nukkit.Player; import cn.nukkit.item.Item; import net.FENGberd.Nukkit.FNPC.Main; import net.FENGberd.Nukkit.FNPC.utils.Utils; import java.util.ArrayList; import java.util.HashMap; @SuppressWarnings("unused") public class CommandNPC extends NPC { public ArrayList<String> command=new ArrayList<>(); public CommandNPC(String nid,String nametag,double x,double y,double z,Item handItem) { super(nid,nametag,x,y,z,handItem); } public CommandNPC(String nid,String nametag,double x,double y,double z) { this(nid,nametag,x,y,z,null); } public CommandNPC(String nid) { this(nid,"",0,0,0); } @Override public void onTouch(Player player) { this.command.forEach(cmd->{ cmd=cmd.replace("%p",player.getName()).replace("%x",String.valueOf(player.getX())).replace("%y",String.valueOf(player.getY())).replace("%z",String.valueOf(player.getZ())); if(! player.isOp() && cmd.contains("%op")) { cmd=cmd.replace("%op",""); player.setOp(true); Main.getInstance().getServer().dispatchCommand(player,cmd); player.setOp(false); } else { cmd=cmd.replace("%op",""); Main.getInstance().getServer().dispatchCommand(player,cmd); } }); } @Override public HashMap<String,Object> reload() { HashMap<String,Object> cfg=super.reload(); if(cfg!=null) { this.command=Utils.cast(cfg.getOrDefault("command",new ArrayList<String>())); } return cfg; } public void addCommand(String data) { this.command.add(data); this.save(); } public boolean removeCommand(String data) { return this.command.remove(data); } @Override public void save() { this.save(new HashMap<>()); } @Override public void save(HashMap<String,Object> extra) { extra.put("type","command"); extra.put("command",this.command); super.save(extra); } }
21.252874
174
0.685776
ef963362768a7e9437a0dcdbd1e27be473132ae5
512
package php.runtime.ext.core.classes.stream; import php.runtime.env.Environment; import php.runtime.ext.java.JavaException; import php.runtime.reflection.ClassEntity; import static php.runtime.annotation.Reflection.Name; @Name("php\\io\\IOException") public class WrapIOException extends JavaException { public WrapIOException(Environment env, Throwable throwable) { super(env, throwable); } public WrapIOException(Environment env, ClassEntity clazz) { super(env, clazz); } }
26.947368
66
0.753906
aac50c77c39fa07847807df9c0dfc9da57a4685e
3,512
/* * This software is released under a licence similar to the Apache Software Licence. * See org.logicalcobwebs.proxool.package.html for details. * The latest version is available at http://proxool.sourceforge.net */ package org.logicalcobwebs.proxool; import org.logicalcobwebs.dbscript.ConnectionAdapterIF; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; /** * This is the simplest pool you can get. It isn\ufffdt thread safe. It isn't robust. * But it is fast. We use it as our bench mark on how could we should strive * to be. * * Provides Simpool connections to the {@link org.logicalcobwebs.dbscript.ScriptFacade ScriptFacade} * * @version $Revision: 1.12 $, $Date: 2006/01/18 14:40:06 $ * @author Bill Horsman (bill@logicalcobwebs.co.uk) * @author $Author: billhorsman $ (current maintainer) * @since Proxool 0.5 */ public class SimpoolAdapter implements ConnectionAdapterIF { private static final Log LOG = LogFactory.getLog(SimpoolAdapter.class); private Connection[] connections; private int index = 0; public String getName() { return "simpool"; } public void setup(String driver, String url, Properties info) throws SQLException { try { Class.forName(driver); } catch (ClassNotFoundException e) { throw new SQLException("Couldn't find " + driver); } int connectionCount = Integer.parseInt(info.getProperty(ProxoolConstants.MAXIMUM_CONNECTION_COUNT_PROPERTY)); connections = new Connection[connectionCount]; for (int i = 0; i < connectionCount; i++) { connections[i] = DriverManager.getConnection(url, info); } } public Connection getConnection() throws SQLException { Connection c = connections[index]; index++; if (index >= connections.length) { index = 0; } return c; } public void closeConnection(Connection connection) { // Do nothing ! } public void tearDown() { try { for (int i = 0; i < connections.length; i++) { connections[i].close(); } } catch (SQLException e) { LOG.error("Problem tearing down " + getName() + " adapter", e); } } } /* Revision history: $Log: SimpoolAdapter.java,v $ Revision 1.12 2006/01/18 14:40:06 billhorsman Unbundled Jakarta's Commons Logging. Revision 1.11 2003/03/04 10:24:40 billhorsman removed try blocks around each test Revision 1.10 2003/03/03 11:12:05 billhorsman fixed licence Revision 1.9 2003/03/01 15:27:24 billhorsman checkstyle Revision 1.8 2003/02/19 15:14:25 billhorsman fixed copyright (copy and paste error, not copyright change) Revision 1.7 2003/02/06 17:41:03 billhorsman now uses imported logging Revision 1.6 2003/01/27 23:32:10 billhorsman encoding fix (no idea how that happened) Revision 1.5 2002/11/13 20:23:38 billhorsman change method name, throw exceptions differently, trivial changes Revision 1.4 2002/11/09 16:02:20 billhorsman fix doc Revision 1.3 2002/11/02 14:22:16 billhorsman Documentation Revision 1.2 2002/11/02 12:46:42 billhorsman improved debug Revision 1.1 2002/11/02 11:37:48 billhorsman New tests Revision 1.1 2002/10/30 21:17:50 billhorsman new performance tests */
27.873016
117
0.681948
728ae624b70d8a4fb5f42e68cc281a6228cbe364
604
package br.com.ipet.Repository; import br.com.ipet.Models.Service; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.PagingAndSortingRepository; import java.util.Set; public interface ServiceRepository extends PagingAndSortingRepository<Service, Long> { Service findByName(String name); Service findById(long id); Page<Service> findProductsByIdIn(Set<Long> ids, Pageable pageable); Page<Service> findByIdIn(Set<Long> ids, Pageable pageable); Set<Service> findProductsByIdIn(Set<Long> ids); }
31.789474
86
0.793046
56d72d280462e39d5e172de19e9f4b30cb44237c
61,284
/** * This software was developed and / or modified by Raytheon Company, * pursuant to Contract DG133W-05-CQ-1067 with the US Government. * * U.S. EXPORT CONTROLLED TECHNICAL DATA * This software product contains export-restricted data whose * export/transfer/disclosure is restricted by U.S. law. Dissemination * to non-U.S. persons whether in the United States or abroad requires * an export license or other authorization. * * Contractor Name: Raytheon Company * Contractor Address: 6825 Pine Street, Suite 340 * Mail Stop B8 * Omaha, NE 68106 * 402.291.0100 * * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ package com.raytheon.viz.gfe.makehazard; import java.nio.ByteBuffer; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TimeZone; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Layout; import org.eclipse.swt.widgets.Scale; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.progress.UIJob; import org.opengis.referencing.FactoryException; import org.opengis.referencing.operation.TransformException; import com.google.common.collect.ImmutableMap; import com.raytheon.uf.common.dataplugin.gfe.db.objects.GridLocation; import com.raytheon.uf.common.dataplugin.gfe.discrete.DiscreteDefinition; import com.raytheon.uf.common.dataplugin.gfe.discrete.DiscreteKey; import com.raytheon.uf.common.dataplugin.gfe.grid.Grid2DBit; import com.raytheon.uf.common.dataplugin.gfe.grid.Grid2DByte; import com.raytheon.uf.common.dataplugin.gfe.reference.ReferenceData; import com.raytheon.uf.common.dataplugin.gfe.reference.ReferenceID; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; import com.raytheon.uf.common.time.SimulatedTime; import com.raytheon.uf.common.time.TimeRange; import com.raytheon.uf.viz.core.RGBColors; import com.raytheon.uf.viz.core.VizApp; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.zoneselector.AbstractZoneSelector.IZoneSelectionListener; import com.raytheon.viz.core.mode.CAVEMode; import com.raytheon.viz.gfe.GFEPreference; import com.raytheon.viz.gfe.constants.StatusConstants; import com.raytheon.viz.gfe.core.DataManager; import com.raytheon.viz.gfe.core.IParmManager; import com.raytheon.viz.gfe.core.IReferenceSetManager; import com.raytheon.viz.gfe.core.griddata.DiscreteGridData; import com.raytheon.viz.gfe.core.griddata.IGridData; import com.raytheon.viz.gfe.core.parm.Parm; import com.raytheon.viz.gfe.product.TextDBUtil; import com.raytheon.viz.gfe.ui.zoneselector.ZoneSelector; import com.raytheon.viz.ui.dialogs.CaveSWTDialog; import com.raytheon.viz.ui.statusline.StatusMessage.Importance; import com.raytheon.viz.ui.statusline.StatusStore; /** * Make Hazard Dialog * * <pre> * SOFTWARE HISTORY * * Date Ticket# Engineer Description * ------------- -------- ----------- ------------------------------------------ * Jun 05, 2008 Eric Babin Initial Creation * Sep 27, 2010 5813 gzhou get etn from param pattern hazXXXnnn * Feb 28, 2012 14436 mli Add RP.S - Rip Current * Apr 03, 2012 436 randerso Reworked dialog to be called by Python * MakeHazard procedure * Apr 09, 2012 436 randerso Merged RNK's MakeHazards_Elevation * procedure * May 30, 2012 2028 randerso Cleaned up dialog layout * Nov 13, 2014 646 lshi Fixed hard coded endTimeSlider's Max value * Jul 30, 2015 17770 lshi Add handling for AT, EP, CP and WP basins * Jan 14, 2016 5239 randerso Fixed Zones included/not included labels * not always visible * Feb 05, 2016 5316 randerso Moved AbstractZoneSelector to separate * project * Nov 01, 2016 5979 njensen Cast to Number where applicable * Jul 06, 2017 20085 lshi Undefined basin ID for Atlantic when * issuing tropical warning * Jan 03, 2018 7178 randerso Change to use IDataObject. Code cleanup. * Jan 24, 2018 7153 randerso Changes to allow new GFE config file to be * selected when perspective is re-opened. * * </pre> * * @author ebabin */ public class MakeHazardDialog extends CaveSWTDialog implements IZoneSelectionListener { private static final IUFStatusHandler statusHandler = UFStatus .getHandler(MakeHazardDialog.class); private static final String DEFAULT_MAP_COLOR = "red"; private static final double DEFAULT_AREA_THRESHOLD = 0.10; private static final String ZONES_MSG = "USING MAP SELECTIONS"; private static final String EDIT_AREA_MSG = "USING ACTIVE EDIT AREA"; private final List<String> tropicalHaz; private final int natlBaseETN; private final Map<String, List<String>> localEffectAreas; private final Map<String, List<Object>> localAreaData; /** * Zoom step size. */ private static final double ZOOM_STEP = 0.75; private final Map<String, List<String>> hazardDict; private Text etnSegNumberField; private Scale startTimeSlider, endTimeSlider; private Label startTimeLabel, endTimeLabel; private static final String gmtPattern = "HH:mm'Z' EEE dd-MMM-yy"; private final SimpleDateFormat dateFormatter; private ZoneSelector zoneSelector; /** * Used by hazard start and end Time. * */ private int toHours = 96; private String hazardStartTime; private org.eclipse.swt.widgets.List selectedHazardList; /** * The Python script to load and run methods from. */ private final String defaultHazardType; private final Map<String, List<String>> mapNames; private Group leGroup; private Combo leCombo; private Label usingLabel; private final int defaultMapWidth; private RGB mapColor; private final int timeScaleEndTime; private double areaThreshold = DEFAULT_AREA_THRESHOLD; private TimeRange selectedTimeRange; private List<String> defaultAreaList; private String defaultHazard; private String defaultSegment; private final DataManager dataManager; private final List<String> tcmList; private String tcmProduct = null; private Map<String, Integer> comboDict; private String currentHazardType; private String hazLocalEffect; private boolean running; private org.eclipse.swt.widgets.List hazardGroupList; private static final String[] WMO_TITLES = { "NATIONAL HURRICANE CENTER", // NHC "NATIONAL WEATHER SERVICE TIYAN", // GUM "CENTRAL PACIFIC HURRICANE CENTER" // CPHC }; private static final Map<String, String> BASINS = ImmutableMap.of("AL", "10", "EP", "20", "CP", "30", "WP", "40"); /** * Constructor * * @param parent * @param dataManager * @param colorName * @param defaultMapWidth * @param timeScaleEndTime * @param areaThreshold * @param defaultHazardType * @param mapNames * @param hazardDict * @param tcmList * @param tropicalHaz * @param natlBaseETN * @param localEffectAreas * @param localAreaData */ public MakeHazardDialog(Shell parent, DataManager dataManager, String colorName, int defaultMapWidth, int timeScaleEndTime, float areaThreshold, String defaultHazardType, Map<String, List<String>> mapNames, Map<String, List<String>> hazardDict, List<String> tcmList, List<String> tropicalHaz, int natlBaseETN, Map<String, List<String>> localEffectAreas, Map<String, List<Object>> localAreaData) { super(parent, SWT.DIALOG_TRIM | SWT.RESIZE, CAVE.DO_NOT_BLOCK | CAVE.NO_PACK); this.dataManager = dataManager; this.defaultMapWidth = defaultMapWidth; this.timeScaleEndTime = timeScaleEndTime; this.areaThreshold = areaThreshold; this.defaultHazardType = defaultHazardType; this.mapNames = mapNames; this.hazardDict = hazardDict; this.tcmList = tcmList; this.tropicalHaz = tropicalHaz; this.natlBaseETN = natlBaseETN; this.localEffectAreas = localEffectAreas; this.localAreaData = localAreaData; this.hazLocalEffect = "None"; try { this.mapColor = RGBColors.getRGBColor(colorName); } catch (Exception e) { statusHandler.handle(Priority.ERROR, "Invalid mapColor in MakeHazard.py. Using default", e); this.mapColor = RGBColors.getRGBColor(DEFAULT_MAP_COLOR); } this.setText("MakeHazard"); dateFormatter = new SimpleDateFormat(gmtPattern); dateFormatter.setTimeZone(TimeZone.getTimeZone("GMT")); } @Override protected Layout constructShellLayout() { // Create the main layout for the shell. GridLayout mainLayout = new GridLayout(1, false); mainLayout.marginHeight = 2; mainLayout.marginWidth = 2; mainLayout.verticalSpacing = 2; return mainLayout; } @Override protected void initializeComponents(Shell shell) { // Initialize all of the controls and layouts initializeComponents(); shell.pack(); this.comboDict = new HashMap<>(); setHazardType(this.defaultHazardType); loadInitialData(); getInitialSelections(); } private void getInitialSelections() { selectedTimeRange = getSelectedTimeRange(); defaultAreaList = getZoneList(); defaultHazard = getHazard(); defaultSegment = etnSegNumberField.getText(); } private TimeRange getSelectedTimeRange() { Date startTime = null; Date endTime = null; TimeRange uiValues; try { startTime = dateFormatter.parse(startTimeLabel.getText()); endTime = dateFormatter.parse(endTimeLabel.getText()); uiValues = new TimeRange(startTime, endTime); } catch (ParseException e) { // If we're here, something is seriously wrong. e.printStackTrace(); uiValues = new TimeRange(); } return uiValues; } private String getHazard() { // get the selected hazard from the hazard list String[] hazArray = selectedHazardList.getSelection(); // Make sure a hazard is selected if (hazArray.length != 1) { return null; } return hazArray[0]; } private int getSegment() { // get the ETN // get the segment # String segString = this.etnSegNumberField.getText(); int segNumber = Integer.MIN_VALUE; // Validate the segment number segString = segString.trim(); if (!"".equals(segString)) { try { segNumber = Integer.parseInt(segString); if (segNumber < 1) { throw new NumberFormatException(String .format("Bad segment number '%s'", segString)); } } catch (NumberFormatException e) { return Integer.MIN_VALUE; } } return segNumber; } /** * Try to pre-load the dialog with data from the grid manager. */ private void loadInitialData() { IParmManager parmManager = dataManager.getParmManager(); Parm[] parms = parmManager.getSelectedParms(); TimeRange timeRange = null; Parm parm = null; String parmName = null; if ((parms != null) && (parms.length == 1)) { parm = parms[0]; parmName = parm.getParmID().getParmName(); } // Check for an ETN or segment # if ((parmName != null) && parmName.startsWith("haz")) { // DR 5813 // parmName example: hazxxxnnn // where xxx = hazard type, nnn = etn (or segment number) int index = parmName.length() - 1; while (Character.isDigit(parmName.charAt(index))) { index--; } if (index < (parmName.length() - 1)) { String etn = parmName.substring(index + 1); if (Integer.parseInt(etn) > 0) { this.etnSegNumberField.setText(etn); } } } timeRange = determineTimeRange(parm); if ((parmName == null) || !parmName.startsWith("haz")) { setTRSliders(timeRange); return; } IGridData[] grids = null; if (timeRange != null) { grids = parm.getGridInventory(timeRange); if ((grids == null) || (grids.length != 1)) { timeRange = null; } else { timeRange = grids[0].getGridTime(); } } if (timeRange == null) { return; } setTRSliders(timeRange); String phen_sig = parmName.substring(3, 5) + "." + parmName.charAt(5); pickDefaultCategory(phen_sig); selectMapFromGrid(grids[0]); } /** * @param timeRange */ private void setTRSliders(TimeRange timeRange) { if (timeRange != null) { // set the start and end time sliders Date zeroDate = null; try { zeroDate = dateFormatter.parse(hazardStartTime); } catch (ParseException e) { statusHandler.handle(Priority.EVENTB, "Hazard start time cannot be parsed.", e); } if (zeroDate != null) { long zeroLong = zeroDate.getTime(); Date startDate = timeRange.getStart(); Date endDate = timeRange.getEnd(); long startLong = startDate.getTime(); long endLong = endDate.getTime(); int startHour = (int) (startLong - zeroLong) / (60 * 60 * 1000); if (startHour < 0) { startHour = 0; } if (startHour > toHours) { statusHandler.handle(Priority.VERBOSE, "Hazard start time is beyond date slider limit"); startHour = toHours; } startTimeSlider.setSelection(startHour); updateTime(startHour, startTimeLabel); int endHour = (int) (endLong - zeroLong) / (60 * 60 * 1000); if (endHour < (startHour + 1)) { endHour = startHour + 1; } if (endHour > (toHours + 1)) { statusHandler.handle(Priority.VERBOSE, "Hazard end time is beyond date slider limit"); endHour = toHours + 1; } endTimeSlider.setSelection(endHour); updateTime(endHour, endTimeLabel); } } } /** * In AWIPS I, MakeHazard was passed a time range parameter obtained from * EditActionProcessor's determineTimeRange(), which is part of the * preview() process. Currently, we don't implement preview(), but we * probably will at some point in the future. When we do, we can get rid of * this method and let preview() do this for us like AWIPS I did. * * @param parm * @return */ private TimeRange determineTimeRange(Parm parm) { Date seTime = dataManager.getSpatialDisplayManager() .getSpatialEditorTime(); TimeRange timeRange = dataManager.getParmOp().getSelectionTimeRange(); if ((timeRange != null) && timeRange.isValid()) { if (!timeRange.contains(seTime)) { statusHandler.handle(Priority.PROBLEM, "Time range does not intersect Spatial Editor time. " + "Please set Time so results will be visible."); } } else { timeRange = null; if (parm != null) { timeRange = parm.getParmState().getSelectedTimeRange(); if ((timeRange != null) && !timeRange.isValid()) { timeRange = null; } } if (timeRange == null) { if (seTime == null) { timeRange = new TimeRange(); } else { timeRange = new TimeRange(seTime, 10 * 1000); } } } if ((timeRange != null) && (parm != null)) { IGridData[] grids = parm.getGridInventory(timeRange); if ((grids != null) && (grids.length > 1)) { // There should be a yes/no dialog pop up... } } return timeRange; } /** * Figure out the hazard type (i.e., "Winter Weather") and db tables to use, * based on phen_sig. The same phensig sometimes appears in multiple hazard * types, so pick the one that draws from the most db tables. * * @param phen_sig */ protected void pickDefaultCategory(String phen_sig) { String hazardType = null; List<String> hazTables = null; Map<String, List<String>> hazDict = getHazardsDictionary(); for (Map.Entry<String, List<String>> entry : hazDict.entrySet()) { List<String> phenSigsForType = entry.getValue(); if ((phenSigsForType != null) && phenSigsForType.contains(phen_sig)) { String entryHazardType = entry.getKey(); List<String> entryHazTables = mapNames.get(entryHazardType); if ((hazTables == null) || (hazTables.size() < entryHazTables.size())) { hazardType = entryHazardType; hazTables = entryHazTables; } } } // Set the radio button and selection list entry if (hazardType != null) { setHazardType(hazardType); setHazard(phen_sig); } } /** * Initialize the controls on the display. */ private void initializeComponents() { Composite topComp = new Composite(shell, SWT.NONE); GridLayout gl = new GridLayout(3, false); gl.marginWidth = 0; gl.marginHeight = 0; topComp.setLayout(gl); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); topComp.setLayoutData(gd); Composite mapComp = new Composite(topComp, SWT.BORDER); createMapComponent(mapComp); Composite hazardComp = new Composite(topComp, SWT.NONE); createSelectHazardComponent(hazardComp); Composite timeComp = new Composite(topComp, SWT.NONE); createTimeSelectComponent(timeComp); createLocalEffectComponent(timeComp); createButtons(); } /** * Create the hazard in response to the run or run/dismiss button. Indicate * whether the run succeeded so run/dismiss knows whether it's OK to close * the dialog. * * @return true if the hazard was created, false otherwise. */ private boolean doRunInternal(boolean dismiss) { // Obtain information from the controls TimeRange timeRange = getSelectedTimeRange(); if (!timeRange.isValid()) { return false; } // get the zones selected List<String> zoneList = getZoneList(); // Validate the control inputs // get the selected hazard from the hazard list String hazard = getHazard(); // Make sure a hazard is selected if (hazard == null) { StatusStore.updateStatus(StatusConstants.CATEGORY_GFE, "You must select a hazard", Importance.SIGNIFICANT); return false; } String tropicalETN = null; // get the tropical ETN if (tcmProduct != null) { tropicalETN = tcmETNforTrop(tcmProduct); } // get the segment # String phenSig = hazard.substring(0, 4); int segNum = getSegment(); String segmentNumber = ""; // Validate the segment number if ((this.tropicalHaz.contains(phenSig))) { // if ETN is already correctly assigned, use it if (segNum >= this.natlBaseETN) { segmentNumber = Integer.toString(segNum); } else if ((etnSegNumberField.getText().length() > 0) && (segNum < this.natlBaseETN)) { // if there is a number in the box, but it is not correct, send // message String msg = "Must use national tropical hazard ETN. Remove number\n" + "from the ETN box and choose the appropriate TCM to get the ETN."; StatusStore.updateStatus(StatusConstants.CATEGORY_GFE, msg, Importance.SIGNIFICANT); return false; } else if ((etnSegNumberField.getText().length() == 0) && (tropicalETN != null)) { // If there is no number assigned and they have chosen a TCM, // use that segmentNumber = tropicalETN; // LogStream.logUse("ETN from TCM was:", tropicalETN) } else { // If we got here, then no TCM was chosen nor a national ETN // otherwise assigned. Send message. String msg = "Must use national tropical hazard ETN. \n" + "Choose the appropriate TCM to get the ETN when creating the grid."; StatusStore.updateStatus(StatusConstants.CATEGORY_GFE, msg, Importance.SIGNIFICANT); return false; } } else { if (segNum > 0) { segmentNumber = Integer.toString(segNum); } } // We need to validate that there are points selected. However, if there // are no zones selected, it may be because we are creating a hazard for // an edit area instead of zones. // The latter is much easier to check in Python, so the validation is // done in the script. // Use the validated inputs // Put arguments in a map to pass to the script. Map<String, Object> argmap = new HashMap<>(); argmap.put("selectedHazard", hazard); argmap.put("timeRange", timeRange); argmap.put("areaList", zoneList); argmap.put("segmentNumber", segmentNumber); argmap.put("selectedTimeRange", selectedTimeRange); argmap.put("defaultAreaList", defaultAreaList); argmap.put("defaultHazard", defaultHazard); argmap.put("defaultSegment", defaultSegment); argmap.put("hazLocalEffect", hazLocalEffect); argmap.put("dismiss", dismiss); setReturnValue(argmap); running = false; return true; } private String tcmETNforTrop(String tcmProductId) { statusHandler.debug("chosen TCM is " + tcmProductId); String[] tcmProduct = getTextProductFromDB(tcmProductId); String tropicalETN = null; if (tcmProduct.length < 3) { String msg = tcmProductId + " could not be retrieved from the text database."; statusHandler.handle(Priority.SIGNIFICANT, msg); // Just return if no TCM is found. Something's really wrong return null; } String altFileName = getAltInfoFilename(tcmProduct); if (altFileName != null) { String nationalBase = BASINS.get("AL"); String baseETN = altFileName.substring(0, 2); String baseEtnCode = BASINS.get(baseETN); if (baseEtnCode != null) { nationalBase = baseEtnCode; } else { statusHandler.warn("Undefined basin ID: " + baseETN + ", defaulting to AL"); } String stormNum = altFileName.substring(2, 4); tropicalETN = nationalBase + stormNum; } return tropicalETN; } private String getAltInfoFilename(String[] tcmProduct) { String altFilename = null; for (int i = 0; i < tcmProduct.length; i++) { for (String title : WMO_TITLES) { if (tcmProduct[i].contains(title)) { String[] parts = tcmProduct[i].split("\\s"); altFilename = parts[parts.length - 1]; return altFilename; } } } return altFilename; } private String[] getTextProductFromDB(String productID) { boolean testVtec = GFEPreference.getBoolean("TestVTECDecode", false); boolean gfeMode = (this.dataManager.getOpMode() .equals(CAVEMode.OPERATIONAL)); boolean opMode = testVtec || gfeMode; String fullText = TextDBUtil.retrieveProduct(productID, opMode); String[] textList = fullText.split("\n"); return textList; } private List<String> getZoneList() { List<List<String>> zoneGroupings = zoneSelector.getZoneGroupings(); List<String> zoneList = Collections.emptyList(); if (!zoneGroupings.isEmpty()) { zoneList = zoneGroupings.get(0); } return zoneList; } private void createButtons() { GridData gd = new GridData(SWT.CENTER, SWT.DEFAULT, true, false); Composite buttons = new Composite(shell, SWT.NONE); buttons.setLayoutData(gd); FillLayout fillLayout = new FillLayout(); fillLayout.spacing = 5; buttons.setLayout(fillLayout); Button runButton = new Button(buttons, SWT.PUSH); runButton.setText("Run"); runButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doRunInternal(false); } }); Button runDismissButton = new Button(buttons, SWT.PUSH); runDismissButton.setText("Run/Dismiss"); runDismissButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doRunInternal(true); } }); Button cancelButton = new Button(buttons, SWT.PUSH); cancelButton.setText("Cancel"); cancelButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { running = false; } }); } private void createMapComponent(Composite mapComp) { GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); GridLayout gl = new GridLayout(1, false); gl.marginHeight = 0; gl.marginWidth = 0; mapComp.setLayout(gl); mapComp.setLayoutData(gd); Composite theMapComposite = new Composite(mapComp, SWT.NONE); gl = new GridLayout(1, false); gl.marginHeight = 0; gl.marginWidth = 0; gl.horizontalSpacing = 0; gl.verticalSpacing = 0; theMapComposite.setLayout(gl); gd = new GridData(SWT.FILL, SWT.FILL, true, true); gd.minimumHeight = 100; gd.minimumWidth = 100; gd.widthHint = this.defaultMapWidth; theMapComposite.setLayoutData(gd); try { initializeShapeComponent(theMapComposite); } catch (Exception e) { statusHandler.handle(Priority.SIGNIFICANT, e.getLocalizedMessage(), e); } Composite buttonComp = new Composite(mapComp, SWT.NONE); GridLayout layout = new GridLayout(4, false); buttonComp.setLayout(layout); GridData layoutData = new GridData(SWT.FILL, SWT.DEFAULT, true, false); buttonComp.setLayoutData(layoutData); Composite comp = new Composite(buttonComp, SWT.NONE); layout = new GridLayout(1, true); layout.marginHeight = 0; layout.marginWidth = 0; comp.setLayout(layout); layoutData = new GridData(SWT.DEFAULT, SWT.FILL, false, true); comp.setLayoutData(layoutData); Button zoomInButton = new Button(comp, SWT.PUSH); zoomInButton.setText("Zoom In"); layoutData = new GridData(SWT.FILL, SWT.DEFAULT, true, false); zoomInButton.setLayoutData(layoutData); Button zoomOutButton = new Button(comp, SWT.PUSH); zoomOutButton.setText("Zoom Out"); layoutData = new GridData(SWT.FILL, SWT.DEFAULT, true, false); zoomOutButton.setLayoutData(layoutData); Button zoomOneToOneButton = new Button(comp, SWT.PUSH); zoomOneToOneButton.setText("Zoom 1:1"); layoutData = new GridData(SWT.FILL, SWT.DEFAULT, true, false); zoomOneToOneButton.setLayoutData(layoutData); comp = new Composite(buttonComp, SWT.NONE); layout = new GridLayout(1, true); layout.marginHeight = 0; layout.marginWidth = 0; comp.setLayout(layout); layoutData = new GridData(SWT.DEFAULT, SWT.FILL, false, true); comp.setLayoutData(layoutData); Button clearAllButton = new Button(comp, SWT.PUSH); clearAllButton.setText("Clear All"); layoutData = new GridData(SWT.FILL, SWT.DEFAULT, true, false); clearAllButton.setLayoutData(layoutData); Button selectAllButton = new Button(comp, SWT.PUSH); selectAllButton.setText("Select All"); layoutData = new GridData(SWT.FILL, SWT.DEFAULT, true, false); selectAllButton.setLayoutData(layoutData); comp = new Composite(buttonComp, SWT.NONE); layout = new GridLayout(1, false); layout.marginHeight = 0; layout.marginWidth = 0; comp.setLayout(layout); layoutData = new GridData(SWT.DEFAULT, SWT.FILL, false, true); comp.setLayoutData(layoutData); Button showMapLabelsButton = new Button(comp, SWT.CHECK); showMapLabelsButton.setText("Map Labels"); comp = new Composite(buttonComp, SWT.NONE); layout = new GridLayout(2, false); layout.marginHeight = 0; layout.marginWidth = 0; comp.setLayout(layout); layoutData = new GridData(SWT.RIGHT, SWT.FILL, true, true); comp.setLayoutData(layoutData); GC gc = new GC(getDisplay()); int height = gc.getFontMetrics().getHeight(); gc.dispose(); Label label = new Label(comp, SWT.NONE); label.setBackground( new Color(getDisplay(), zoneSelector.getNoZoneColor())); gd = new GridData(height, height); label.setLayoutData(gd); label = new Label(comp, SWT.NONE); label.setText("Zones not included"); label = new Label(comp, SWT.NONE); label.setBackground(new Color(getDisplay(), mapColor)); gd = new GridData(height, height); label.setLayoutData(gd); label = new Label(comp, SWT.NONE); label.setText("Zones included"); showMapLabelsButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { zoneSelector .setLabelZones(((Button) e.getSource()).getSelection()); } }); selectAllButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Map<String, Integer> comboDict = new HashMap<>(); for (String zoneName : zoneSelector.getZoneNames()) { comboDict.put(zoneName, 1); } zoneSelector.updateCombos(comboDict); zoneSelected(null); } }); clearAllButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { zoneSelector.updateCombos(new HashMap<String, Integer>()); zoneSelected(null); } }); zoomInButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { zoneSelector .setZoomLevel(zoneSelector.getZoomLevel() * ZOOM_STEP); } }); zoomOutButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { zoneSelector .setZoomLevel(zoneSelector.getZoomLevel() / ZOOM_STEP); } }); zoomOneToOneButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // reset the display to fully zoomed extent zoneSelector.setZoomLevel(1); } }); usingLabel = new Label(buttonComp, SWT.NORMAL); usingLabel.setAlignment(SWT.CENTER); layoutData = new GridData(SWT.CENTER, SWT.CENTER, true, false); layoutData.horizontalSpan = 4; usingLabel.setLayoutData(layoutData); usingLabel.setText(EDIT_AREA_MSG); } private void createSelectHazardComponent(Composite hazardComp) { GridLayout gl = new GridLayout(2, false); gl.marginHeight = 0; gl.marginWidth = 0; hazardComp.setLayout(gl); GridData gd = new GridData(SWT.DEFAULT, SWT.FILL, false, true); hazardComp.setLayoutData(gd); Group hazardGroup = new Group(hazardComp, SWT.BORDER); hazardGroup.setText("Select Hazard"); gl = new GridLayout(1, true); gl.verticalSpacing = 0; gl.marginHeight = 0; gl.marginWidth = 0; hazardGroup.setLayout(gl); gd = new GridData(SWT.FILL, SWT.FILL, true, true); gd.horizontalSpan = 2; hazardGroup.setLayoutData(gd); selectedHazardList = new org.eclipse.swt.widgets.List(hazardGroup, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.SINGLE); gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false); gd.heightHint = (selectedHazardList.getItemHeight() * 16) + selectedHazardList.getBorderWidth(); selectedHazardList.setLayoutData(gd); Group hazardTypeGroup = new Group(hazardComp, SWT.BORDER); hazardTypeGroup.setText("Hazard Type"); gl = new GridLayout(1, true); gl.verticalSpacing = 0; hazardTypeGroup.setLayout(gl); gd = new GridData(SWT.FILL, SWT.FILL, true, true); hazardTypeGroup.setLayoutData(gd); Group etnSegNumGroup = new Group(hazardComp, SWT.BORDER); etnSegNumGroup.setText("ETN/Segment Number"); etnSegNumGroup.setLayout(new GridLayout(1, true)); etnSegNumGroup .setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); List<String> groups = new ArrayList<>(getHazardsDictionary().keySet()); this.currentHazardType = ""; SelectionAdapter selAdapt = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { org.eclipse.swt.widgets.List list = (org.eclipse.swt.widgets.List) e .getSource(); String[] sel = list.getSelection(); if (sel.length > 0) { setHazardType(sel[0]); } } }; hazardGroupList = new org.eclipse.swt.widgets.List(hazardTypeGroup, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.SINGLE); gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false); gd.heightHint = (hazardGroupList.getItemHeight() * Math.min(12, groups.size())) + hazardGroupList.getBorderWidth(); hazardGroupList.setLayoutData(gd); hazardGroupList.addSelectionListener(selAdapt); for (String k : groups) { hazardGroupList.add(k); if (k.equals(this.defaultHazardType)) { hazardGroupList.select(hazardGroupList.getItemCount() - 1); } } etnSegNumberField = new Text(etnSegNumGroup, SWT.BORDER); gd = new GridData(SWT.CENTER, SWT.DEFAULT, true, false); etnSegNumberField.setTextLimit(4); GC gc = new GC(etnSegNumberField); gd.widthHint = 4 * gc.getCharWidth('0'); gc.dispose(); etnSegNumberField.setLayoutData(gd); etnSegNumberField.addVerifyListener(new VerifyListener() { @Override public void verifyText(VerifyEvent e) { for (char c : e.text.toCharArray()) { if ((!Character.isDigit(c)) && (!Character.isISOControl(c))) { e.doit = false; break; } } } }); if (!tcmList.isEmpty()) { Composite tcmFrameComp = new Composite(etnSegNumGroup, SWT.NONE); tcmFrameComp.setLayout(new GridLayout(1, true)); tcmFrameComp.setLayoutData( new GridData(GridData.FILL, SWT.BOTTOM, true, false)); for (String s : tcmList) { Button radioButton = new Button(tcmFrameComp, SWT.RADIO); radioButton.setText(s); radioButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { Button b = ((Button) (event.getSource())); if (b.getSelection()) { tcmProduct = ((Button) (event.getSource())) .getText(); } } }); } } } /** * Creates a pair of sliders in the sash form for user to choose the start * and end times of the hazard that is being created. The sliders are set up * to require hazards to start and end on an hour boundary, and have a * duration of at least an hour. */ private void createTimeSelectComponent(Composite timeComp) { GridLayout gl = new GridLayout(1, false); gl.marginHeight = 0; gl.marginWidth = 0; timeComp.setLayout(gl); GridData gd = new GridData(SWT.FILL, SWT.FILL, false, true); timeComp.setLayoutData(gd); Group startGroup = new Group(timeComp, SWT.BORDER); startGroup.setText("Hazard Start Time"); gl = new GridLayout(1, false); gl.marginHeight = 0; gl.marginWidth = 0; startGroup.setLayout(gl); gd = new GridData(SWT.FILL, SWT.FILL, true, false); startGroup.setLayoutData(gd); // create a label to show the start time startTimeLabel = new Label(startGroup, SWT.CENTER); gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false); startTimeLabel.setLayoutData(gd); // create the start time slider startTimeSlider = new Scale(startGroup, SWT.HORIZONTAL); gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false); gd.minimumWidth = 200; startTimeSlider.setLayoutData(gd); startTimeSlider.addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected(SelectionEvent e) { // Not called for sliders } /** * Event handler for when the user moves the slider. This updates * the slider label and changes the end time slider if the end time * is before the start time. * * @param e * The event that caused this handler to be called. */ @Override public void widgetSelected(SelectionEvent e) { updateTime(startTimeSlider.getSelection(), startTimeLabel); if (startTimeSlider.getSelection() >= endTimeSlider .getSelection()) { endTimeSlider .setSelection(startTimeSlider.getSelection() + 1); updateTime(endTimeSlider.getSelection(), endTimeLabel); } } }); startTimeSlider.setMinimum(0); startTimeSlider.setMaximum(this.timeScaleEndTime); startTimeSlider.setIncrement(1); startTimeSlider.setPageIncrement(1); // Force start time to an hourly boundary Calendar cal = Calendar.getInstance(); cal.setTime(SimulatedTime.getSystemTime().getTime()); cal.set(Calendar.MINUTE, 0); hazardStartTime = dateFormatter.format(cal.getTime()); updateTime(0, startTimeLabel); Group endGroup = new Group(timeComp, SWT.BORDER); endGroup.setText("Hazard End Time"); gl = new GridLayout(1, false); gl.marginHeight = 0; gl.marginWidth = 0; endGroup.setLayout(gl); gd = new GridData(SWT.FILL, SWT.FILL, true, false); endGroup.setLayoutData(gd); // Create a label to show the user the hazard end time endTimeLabel = new Label(endGroup, SWT.CENTER); gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false); endTimeLabel.setLayoutData(gd); updateTime(1, endTimeLabel); // Create the end time slider endTimeSlider = new Scale(endGroup, SWT.HORIZONTAL); gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false); gd.minimumWidth = 200; endTimeSlider.setLayoutData(gd); toHours = this.timeScaleEndTime; // #646 endTimeSlider.setMinimum(1); endTimeSlider.setMaximum(toHours + 1); endTimeSlider.setIncrement(1); endTimeSlider.setPageIncrement(1); endTimeSlider.setSelection(1); endTimeSlider.addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected(SelectionEvent e) { // Not called for sliders } /** * Event handler for when the user moves the slider. This updates * the slider label and changes the start time slider if the end * time is before the start time. * * @param e * The event that caused this handler to be called. */ @Override public void widgetSelected(SelectionEvent e) { updateTime(endTimeSlider.getSelection(), endTimeLabel); if (endTimeSlider.getSelection() <= startTimeSlider .getSelection()) { startTimeSlider .setSelection(endTimeSlider.getSelection() - 1); updateTime(startTimeSlider.getSelection(), startTimeLabel); } } }); } private void createLocalEffectComponent(Composite comp) { this.leGroup = new Group(comp, SWT.BORDER); GridLayout gl = new GridLayout(1, false); gl.verticalSpacing = 0; leGroup.setLayout(gl); GridData gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false); leGroup.setLayoutData(gd); leGroup.setText("Local Effect Area"); SelectionAdapter selAdapt = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Combo c = (Combo) e.getSource(); hazardLocalEffectSelected((String) c.getData(c.getText())); } }; leCombo = new Combo(leGroup, SWT.DROP_DOWN | SWT.READ_ONLY); gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false); leCombo.setLayoutData(gd); leCombo.addSelectionListener(selAdapt); GC gc = new GC(this.getDisplay()); String longest = ""; int widest = 0; for (List<String> list : localEffectAreas.values()) { for (String s : list) { int width = gc.stringExtent(s).x; if (width > widest) { widest = width; longest = s; } } } gc.dispose(); leCombo.add(longest); } private Map<String, List<String>> getHazardsDictionary() { return hazardDict; } private List<String> getHazardListForType(String key) { Map<String, List<String>> hazardDict = getHazardsDictionary(); if (hazardDict.containsKey(key)) { return hazardDict.get(key); } return null; } private void updateSelectedHazardList(String hazType) { String prevType = this.currentHazardType; this.currentHazardType = hazType; String siteId = dataManager.getSiteID(); DiscreteDefinition discreteDef = DiscreteKey.discreteDefinition(siteId); java.util.List<String> list = null; if ((list = getHazardListForType(hazType)) != null) { selectedHazardList.removeAll(); for (String s : list) { String sdesc = discreteDef.keyDesc("Hazards_SFC", s); if (sdesc.isEmpty()) { if ("CF.S".equals(s)) { sdesc = "COASTAL FLOOD STATEMENT"; } else if ("LS.S".equals(s)) { sdesc = "LAKESHORE FLOOD STATEMENT"; } else if ("MA.S".equals(s)) { sdesc = "MARINE WEATHER STATEMENT"; } else if ("HU.S".equals(s)) { sdesc = "TROPICAL CYCLONE LOCAL STATEMENT"; } else { sdesc = "UNKNOWN PHENOMENON.SIGNIFICANCE"; } } selectedHazardList.add(s + " -- " + sdesc); } selectedHazardList.select(0); selectedHazardList.deselect(0); } List<String> mapNames = this.mapNames.get(hazType); if (mapNames == null) { statusHandler.error("MakeHazardConfig.mapNames has no entry for \"" + hazType + "\""); return; } if (!prevType.equals(hazType) && !mapNames.equals(this.mapNames.get(prevType))) { this.zoneSelector.setMap(mapNames, this.comboDict, Arrays.asList(mapColor)); } } /** * Add <code>selection</code> hours to <code>hazardStartTime</code> (that * is, the default starting time), and set the text of <code>label</code> to * the result, formatted by <code>dateFormatter</code>. * * @param selection * The integer slider value selected by the user. * @param label * The label whose text should be changed. */ private void updateTime(int selection, Label label) { try { Date theDate = dateFormatter.parse(hazardStartTime); Calendar cal = Calendar.getInstance(); cal.setTime(theDate); cal.add(Calendar.HOUR_OF_DAY, selection); label.setText(dateFormatter.format(cal.getTime())); } catch (ParseException e) { // This shouldn't ever happen... statusHandler.handle(Priority.ERROR, "Invalid hazardStartTime", e); } } private void initializeShapeComponent(Composite controlComp) throws TransformException, FactoryException, VizException { GridLocation gloc = dataManager.getParmManager() .compositeGridLocation(); zoneSelector = new ZoneSelector(controlComp, gloc, null, this); zoneSelector.setLimitToOneGroup(true); } /** * Set the hazard type in the radio button control. If the hazard type is * changed, the radio button selection listener will fire, changing and * clearing selectedHazardList as a side effect. * * @param hazardType * the hazard type to select. */ public void setHazardType(String hazardType) { hazardGroupList.setSelection(hazardGroupList.indexOf(hazardType)); updateSelectedHazardList(hazardType); if (this.localEffectAreas.containsKey(hazardType)) { leGroup.setVisible(true); ((GridData) leGroup.getLayoutData()).exclude = false; leCombo.removeAll(); leCombo.add("None"); leCombo.setText("None"); for (String eaName : this.localEffectAreas.get(hazardType)) { List<Object> laData = this.localAreaData.get(eaName); if (laData != null) { String label = eaName; String display = (String) laData.get(1); if ((display != null) && !display.isEmpty()) { label = display; } leCombo.add(label); leCombo.setData(label, eaName); } else { statusHandler.error("No entry found for '" + eaName + "' in localAreaData"); } } } else { leGroup.setVisible(false); ((GridData) leGroup.getLayoutData()).exclude = true; this.hazLocalEffect = "None"; String s = etnSegNumberField.getText(); for (Entry<String, List<Object>> entry : localAreaData.entrySet()) { if (s.equals(entry.getValue().get(0))) { this.etnSegNumberField.setText(""); this.etnSegNumberField.setSelection(0); break; } } } } /** * Set the selection in selectedHazardList to the first item that starts * with phen_sig. If phen_sig is null or an empty string, clears all * selections. * * @param phen_sig * The phen_sig to select */ public void setHazard(String phen_sig) { if ((phen_sig == null) || (phen_sig.length() == 0)) { selectedHazardList.deselectAll(); return; } String[] items = selectedHazardList.getItems(); int index = 0; for (String item : items) { if (item.startsWith(phen_sig)) { selectedHazardList.select(index); break; } index++; } } private void hazardLocalEffectSelected(String le) { this.hazLocalEffect = le; List<Object> laData = this.localAreaData.get(le); if (laData != null) { // get the segment number Number segment = (Number) laData.get(0); if (segment != null) { String segText = segment.toString(); this.etnSegNumberField.setText(segText); this.etnSegNumberField.setSelection(segText.length()); } else { String s = etnSegNumberField.getText(); for (Entry<String, List<Object>> entry : localAreaData .entrySet()) { if (s.equals(entry.getValue().get(0))) { this.etnSegNumberField.setText(""); this.etnSegNumberField.setSelection(0); break; } } } @SuppressWarnings("unchecked") List<String> zoneList = (List<String>) laData.get(2); if ((zoneList != null) && !zoneList.isEmpty()) { Map<String, Integer> comboDict = new HashMap<>(zoneList.size()); for (String z : zoneList) { comboDict.put(z, 1); } this.zoneSelector.updateCombos(comboDict); } } } /** * @param grid * The parm grid to select from */ private void selectMapFromGrid(IGridData grid) { if (grid instanceof DiscreteGridData) { // Get the byte grid out of the grid Grid2DByte byteGrid = ((DiscreteGridData) grid).getDataObject() .getDiscreteGrid(); // Make a bit grid from the byte grid. // Try to avoid copying. // (ReferenceData ctor will copy, so copy here is redundant) Grid2DBit grid2DBit = null; if (byteGrid instanceof Grid2DBit) { grid2DBit = (Grid2DBit) byteGrid; } else { int xDim = byteGrid.getXdim(); int yDim = byteGrid.getYdim(); ByteBuffer byteBuf = byteGrid.getBuffer(); grid2DBit = new Grid2DBit(xDim, yDim, byteBuf); } List<String> zoneIdsToShow = getAreaList(grid2DBit); // Select the zones if ((zoneIdsToShow != null) && (!zoneIdsToShow.isEmpty())) { usingLabel.setText(ZONES_MSG); for (String z : zoneIdsToShow) { this.comboDict.put(z, 1); } zoneSelector.updateCombos(this.comboDict); } else { usingLabel.setText(EDIT_AREA_MSG); } } else { IllegalArgumentException iae = new IllegalArgumentException( "Grid parameter must be an instance of DiscreteGridSlice."); iae.fillInStackTrace(); throw iae; } } @Override public void zoneSelected(String zone) { Set<String> selectedZones = zoneSelector.getCombos().keySet(); if (!selectedZones.isEmpty()) { usingLabel.setText(ZONES_MSG); } else { usingLabel.setText(EDIT_AREA_MSG); } usingLabel.pack(true); } /** * Defend against bad values for areaThreshold in config file. */ protected void initAreaThreshold() { if (this.areaThreshold > 1.0) { // This wouldn't select any zones statusHandler.handle(Priority.WARN, "Area threshold is greater than 100%. Using default."); this.areaThreshold = DEFAULT_AREA_THRESHOLD; } else if (this.areaThreshold <= 0.0) { // This would always select all zones statusHandler.handle(Priority.WARN, "Area threshold is 0% or below. Using default."); this.areaThreshold = DEFAULT_AREA_THRESHOLD; } } /** * @param grid2dBit * @return */ private List<String> getAreaList(Grid2DBit mask) { IReferenceSetManager rm = this.dataManager.getRefManager(); List<String> areas = this.zoneSelector.getZoneNames(); List<String> areaList = new ArrayList<>(); for (String area : areas) { ReferenceID refId = new ReferenceID(area); ReferenceData refData = rm.loadRefSet(refId); Grid2DBit editAreaMask = refData.getGrid(); Grid2DBit intersect = editAreaMask.and(mask); float ratio = (float) intersect.numberOfBitsSet() / (float) editAreaMask.numberOfBitsSet(); if (ratio >= areaThreshold) { areaList.add(refData.getId().getName()); } } return areaList; } /** * Open dialog from Python */ public void openFromPython() { VizApp.runSync(new Runnable() { @Override public void run() { open(); } }); } /** * Run the dialog event loop from Python * * @return map of Python arguments for MakeHazard.py */ public Object runFromPython() { final Object[] retVal = new Object[1]; VizApp.runSync(new Runnable() { @Override public void run() { running = true; setReturnValue(null); while (running) { if (!getDisplay().readAndDispatch()) { getDisplay().sleep(); } } retVal[0] = getReturnValue(); } }); return retVal[0]; } /** * Close the dialog from Python */ public void closeFromPython() { VizApp.runSync(new Runnable() { @Override public void run() { close(); } }); } /** * Create a MakeHazardDialog instance from Python * * @param args * @return the dialog */ @SuppressWarnings("unchecked") public static MakeHazardDialog createFromPython(Map<String, Object> args) { final DataManager dataManager = (DataManager) args.get("dataManager"); final String colorName = (String) args.get("mapColor"); final int defaultMapWidth = ((Number) args.get("defaultMapWidth")) .intValue(); final int timeScaleEndTime = ((Number) args.get("timeScaleEndTime")) .intValue(); final float areaThreshold = ((Number) args.get("areaThreshold")) .floatValue(); final String defaultHazardType = (String) args.get("defaultHazardType"); final Map<String, List<String>> mapNames = (Map<String, List<String>>) args .get("mapNames"); final Map<String, List<String>> hazardDict = (Map<String, List<String>>) args .get("hazardDict"); final List<String> tcmList = (List<String>) args.get("tcmList"); final List<String> tropicalHaz = (List<String>) args.get("tropicalHaz"); final int natlBaseETN = ((Number) args.get("natlBaseETN")).intValue(); final Map<String, List<String>> localEffectAreas = (Map<String, List<String>>) args .get("localEffectAreas"); final Map<String, List<Object>> localAreaData = (Map<String, List<Object>>) args .get("localAreaData"); final MakeHazardDialog[] dlg = new MakeHazardDialog[1]; VizApp.runSync(new Runnable() { @Override public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); dlg[0] = new MakeHazardDialog(shell, dataManager, colorName, defaultMapWidth, timeScaleEndTime, areaThreshold, defaultHazardType, mapNames, hazardDict, tcmList, tropicalHaz, natlBaseETN, localEffectAreas, localAreaData); } }); return dlg[0]; } /** * Set the segment number field from non-UI thread * * @param segNum */ public void setSegmentNumber(final int segNum) { Job updateSegNumField = new UIJob("Updating ETN/segment number.") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { if ((!MakeHazardDialog.this.etnSegNumberField.isDisposed()) && (MakeHazardDialog.this.etnSegNumberField != null)) { MakeHazardDialog.this.etnSegNumberField .setText(Integer.toString(segNum)); return Status.OK_STATUS; } return Status.CANCEL_STATUS; } }; updateSegNumField.setSystem(true); updateSegNumField.schedule(); } @Override protected void disposed() { this.running = false; super.disposed(); } }
36.718993
94
0.581636
b37af6b69af8d6939cb212f827b9820a98357011
566
package com.kenez92.betwinner.domain.weather; import com.kenez92.betwinner.domain.matches.MatchDto; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; import java.util.List; @AllArgsConstructor @NoArgsConstructor @Builder @Data public class WeatherDto { private Long id; private String country; private Date date; private Double tempFelt; private Double tempMin; private Double tempMax; private Integer pressure; private List<MatchDto> matchList; }
21.769231
53
0.779152
1ee3b2a08c07b7ae6f16aa2831a1ee2dde1c4781
1,009
package servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.PageContext; import java.io.IOException; /** * @ClassName RequestTest * @Description TODO * @Author lxyqaq @Email A00279565@student.ait.ie * @Date 2021/3/6 02:20 * @Version 1.0 */ public class RequestTest extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); String password = req.getParameter("password"); System.out.println(username + ": " + password); //要注意重定向的路径问题 resp.sendRedirect(req.getContextPath() + "/success.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
25.871795
114
0.725471
9a7d5b9473a7e2cc2360ee3fb64ec0efadf0cc02
741
package malculator.shared; import malculator.shared.ast.*; public class Function { NodeTree tree; NodeTree dTree; String original_function; String simplified_function; String derivative; public Function(String func) { original_function = func; Lexer lex = new Lexer(original_function); Parser parser = new Parser(lex.getTokens()); tree = parser.getTree(); tree.solve(); simplified_function = tree.toFunction(); dTree = tree; dTree.dSolve(); derivative = dTree.toFunction(); } public String getSimplified_function() { return simplified_function; } public String getDerivative() { return derivative; } }
21.794118
52
0.635628