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
34eac5060c39e7bc3229ec649028fce06f610c58
4,632
package ObjectTracker; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; /** * This class represents a panel. The purpose of * the panel is to allow the user to enter class * names into a list. This list will be used to * filter out all classes that are not present in * in the list from the Graphical Java Displayer. * * @author Eoin O'Connor * @see UserOptionsPanel * @see ObjectTracker */ public class FilterPanel extends JPanel { /** * The width of the panel. */ private int width; /** * The height of the panel. */ private int height; /** * The button used to add a class name to * the list. */ private JButton addButton; /** * The button used to remove a class name * from the list. */ private JButton removeButton; /** * A JList used to manage the real list. */ private JList list; /** * A temporary list. */ private DefaultListModel listModel; /** * Used to enter class names. */ private JTextField textField; /** * The list of class names. */ private ArrayList classList; /** * Constuctor: initializes the panel and * the lists. Sets the button listeners. */ public FilterPanel() { width = 240; height = 200; ButtonListener listener = new ButtonListener(); classList = new ArrayList(); setLayout(new GridLayout(1,2)); JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); JPanel listLabelPanel = new JPanel(); listLabelPanel.setLayout(new FlowLayout()); JLabel listLabel = new JLabel("Filter List:"); listLabelPanel.add(listLabel); addButton = new JButton("Add"); addButton.addActionListener(listener); listLabelPanel.add(addButton); removeButton = new JButton("Remove"); removeButton.addActionListener(listener); listLabelPanel.add(removeButton); mainPanel.add(listLabelPanel,"North"); JPanel listPanel = new JPanel(); listPanel.setLayout(new FlowLayout()); list = new JList(); list.setVisibleRowCount(5); listModel = new DefaultListModel(); JScrollPane listScroller = new JScrollPane(list); list.setModel(listModel); listPanel.add(listScroller); mainPanel.add(listPanel,"Center"); JPanel fieldPanel = new JPanel(); fieldPanel.setLayout(new FlowLayout()); textField = new JTextField(20); textField.setText("Enter class name"); fieldPanel.add(textField); mainPanel.add(fieldPanel,"South"); add(mainPanel); } /** * Adds a class name from the text field * to the JList and to the ArrayList of class * names. Resets the contents of the text field. */ private void addClass() { String className = textField.getText(); if(className.length() > 0) { if(!classList.contains(className)) { listModel.addElement(className); list.setModel(listModel); classList.add(className); } textField.setText(""); } } /** * Removes the selected class name from * the JList and from the ArrayList of * class names. */ private void removeClass() { int index = list.getSelectedIndex(); if(index > -1) { String className = (String)list.getSelectedValue(); classList.remove(className); listModel.remove(index); list.setModel(listModel); } } /** * Returns the list of class names. * * @return The list of class names. */ public ArrayList getClassList() { return classList; } /** * This class listens for the add or remove * button to be pressed. */ private class ButtonListener implements ActionListener { /** * If the add button is pressed then the * addClass() method is called. If the remove * button is pressed then the removeClass() * method is called. * * @param event The ActionEvent that has occurred. */ public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if(source==addButton) addClass(); else if(source==removeButton) removeClass(); } } }
25.450549
64
0.58247
15513932017470cfc41fa181102d4f8b8ecc98c7
89
type reference in array typereferenceinarray type reference in array typereferenceinarray
89
89
0.898876
1872867373b169daea9b520095e14ef3965e014c
433
package com.java.creationalPattern.singletonPattern; /** * Created by Intellij IDEA Author: lizhiyong E-mail: lizhiyong@xiaomi.com Time: * 17-2-24 下午2:27 */ public class RegSingletonChild extends RegSingleton { public RegSingletonChild() { } public static RegSingletonChild getInstance() { return (RegSingletonChild) RegSingleton.getInstance("com.java.patterns.singletonPattern.RegSingletonChild"); } }
27.0625
116
0.748268
d974cca264329ea2c71fb8c42293a6df5b1d2a3f
1,015
/* * Copyright 2017 Alibaba.com All right reserved. This software is the * confidential and proprietary information of Alibaba.com ("Confidential * Information"). You shall not disclose such Confidential Information and shall * use it only in accordance with the terms of the license agreement you entered * into with Alibaba.com. */ package com.work.job.jmx; import com.work.job.GCTest; import com.work.job.MemUtils; import org.junit.Test; import java.lang.management.ManagementFactory; /** * @author lujun.xlj * @date 2017/10/10 */ public class JmxTest { @Test public void testManagerBean() throws Exception { System.out.println(ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() / MemUtils.Unit.MB.getVal()); GCTest.MemObject memObject = new GCTest.MemObject(MemUtils.Unit.MB.getVal() * 100); System.out.println(ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() / MemUtils.Unit.MB.getVal()); } }
31.71875
124
0.717241
1f44d0ad96b4fc98cab1a19c15074f2461899b1d
2,525
package com.geetest.stringguard; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // Test static final fields private static final String STATIC_FINAL_FIELD_1 = "test_private_static_final"; protected static final String STATIC_FINAL_FIELD_2 = "test_protected_static_final"; public static final String STATIC_FINAL_FIELD_3 = "test_public_static_final"; // Test static fields private static String static_field_1 = "test_private_static"; protected static String static_field_2 = "test_protected_static"; public static String static_field_3 = "test_public_static"; // Test final fields private final String final_field_1 = "test_private_final"; protected final String final_field_2 = "test_protected_final"; public final String final_field_3 = "test_public_final"; // Test normal fields private String normal_field_1 = "test_private_normal"; protected String normal_field_2 = "test_protected_normal"; public String normal_field_3 = "test_public_normal"; // Test null static final value public static final String null_static_final; // Test null static value public static String null_static; static { null_static_final = "test_null_static_final"; null_static = "test_null_static"; // Test static block Log.i("stringguard", "test static block"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 范例请参考: // https://github.com/MegatronKing/StringGuard-Sample1 // https://github.com/MegatronKing/StringGuard-Sample2 // Test local params String title = "MainActivity"; ((TextView)findViewById(R.id.text)).setText(title + "Test"); String tag = "stringfog"; Log.i(tag, STATIC_FINAL_FIELD_1); Log.i(tag, STATIC_FINAL_FIELD_2); Log.i(tag, STATIC_FINAL_FIELD_3); Log.i(tag, static_field_1); Log.i(tag, static_field_2); Log.i(tag, static_field_3); Log.i(tag, final_field_1); Log.i(tag, final_field_2); Log.i(tag, final_field_3); Log.i(tag, normal_field_1); Log.i(tag, normal_field_2); Log.i(tag, normal_field_3); Log.i(tag, null_static_final); Log.i(tag, null_static); } }
31.962025
87
0.696238
92bd45d3f4b2a3afc373208c75b5873ffa48ab9a
569
/* * Copyright (c) 2003, the JUNG Project and the Regents of the University * of California * All rights reserved. * * This software is open-source under the BSD license; see either * "license.txt" or * http://jung.sourceforge.net/license.txt for a description. */ package edu.uci.ics.jung.algorithms.util; /** * An interface for algorithms that proceed iteratively. * */ public interface IterativeContext { /** * Advances one step. */ void step(); /** * Returns true if this iterative process is finished, and false otherwise. */ boolean done(); }
19.62069
76
0.702988
cd63163f534fcf78d038779ab3c61816ad345239
994
package com.hiveelpay.dal.dao.mapper; import com.hiveelpay.dal.dao.model.TransOrder; import com.hiveelpay.dal.dao.model.TransOrderExample; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface TransOrderMapper { int countByExample(TransOrderExample example); int deleteByExample(TransOrderExample example); int deleteByPrimaryKey(String transOrderId); int insert(TransOrder record); int insertSelective(TransOrder record); List<TransOrder> selectByExample(TransOrderExample example); TransOrder selectByPrimaryKey(String transOrderId); int updateByExampleSelective(@Param("record") TransOrder record, @Param("example") TransOrderExample example); int updateByExample(@Param("record") TransOrder record, @Param("example") TransOrderExample example); int updateByPrimaryKeySelective(TransOrder record); int updateByPrimaryKey(TransOrder record); }
30.121212
114
0.794769
2c67c3f9f3c30fca1af7f6e282ddf97d22e1c654
92
package com.chipsetsv.multipaint.tools; public enum Tools { None, Eraser, Pen, Clear }
10.222222
39
0.728261
69c80955cf048864fddacc975e2c12b85e7440f2
645
package com.vdreamers.vmediaselector.core.impl.task; import android.content.ContentResolver; import com.vdreamers.vmediaselector.core.entity.MediaEntity; import com.vdreamers.vmediaselector.core.impl.callback.IMediaTaskCallback; /** * 多媒体任务 * <p> * date 2019-09-18 20:32:02 * * @author <a href="mailto:codepoetdream@gmail.com">Mr.D</a> */ public interface IMediaTask<T extends MediaEntity> { /** * 多媒体加载 * * @param cr 内容解析器 * @param page 页数 * @param id 多媒体Id * @param callback 多媒体加载回调 */ void load(ContentResolver cr, int page, String id, IMediaTaskCallback<T> callback); }
22.241379
87
0.675969
9d2bcb7f16745fd5bead9ac7f5e35928bd318436
1,615
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Set; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; public class stdinPetr { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); // test int k = in.nextInt(); out.println(k); out.println("123"); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
24.846154
78
0.601858
495360c65561cf91baf3f7baca8d71c3c3e7cedf
3,020
/* * SimpleSearchMetaQueryImpl.java */ package org.ngbw.sdk.data; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.ngbw.sdk.api.data.DataResource; import org.ngbw.sdk.api.data.DatasetService; import org.ngbw.sdk.api.data.QueryResult; import org.ngbw.sdk.api.data.SearchHitCollection; import org.ngbw.sdk.api.data.SimpleQuery; import org.ngbw.sdk.api.data.SimpleSearchMetaQuery; import org.ngbw.sdk.core.types.Dataset; import org.ngbw.sdk.core.types.FieldDataType; import org.ngbw.sdk.core.types.RecordType; /** * @author Roland H. Niedner <br /> * */ public class SimpleSearchMetaQueryImpl extends MetaQueryImpl implements SimpleSearchMetaQuery { private static final Log log = LogFactory.getLog(SimpleSearchMetaQueryImpl.class); public SimpleSearchMetaQueryImpl(final DatasetService datasetService, final RecordType recordType, Dataset dataset) { super(datasetService, recordType, dataset); } public SimpleSearchMetaQueryImpl(final DatasetService datasetService, final RecordType recordType, Set<Dataset> datasets) { super(datasetService, recordType, datasets); } public int execute(String searchPhrase) throws ParseException, InterruptedException, ExecutionException { return execute(searchPhrase, true); } public int execute(String searchPhrase, boolean parallel) throws ParseException, InterruptedException, ExecutionException { //reset the query if (executed) { resultMap = new HashMap<Dataset, SearchHitCollection>(); results = null; timer.reset(); } //harvest the query results HashMap<Dataset, Future<?>> queries = new HashMap<Dataset, Future<?>>(datasets.size()); timer.start(); for (Dataset dataset : datasets) { DataResource dr = datasetService.getDataResource(dataset); Map<String, FieldDataType> fields = datasetService.getFields(dataset); SimpleQuery query = dr.createSimpleQuery(dataset, fields, searchPhrase); query.setMaxResults(maxResults); if (parallel) { Future<?> foo = pool.submit(new SimpleQueryExecutor(dataset, query)); queries.put(dataset, foo); } else { QueryResult qr = query.execute(); resultMap.put(dataset, translateQueryResult(dataset, qr)); } } if (parallel) { for (Dataset dataset : datasets) { queries.get(dataset).get(); } } timer.takeTime(); executed = true; return getResultCount(); } class SimpleQueryExecutor implements Runnable { private final SimpleQuery query; private final Dataset dataset; SimpleQueryExecutor(Dataset dataset, SimpleQuery query) { this.dataset = dataset; this.query = query; } public void run() { try { QueryResult qr = query.execute(); resultMap.put(dataset, translateQueryResult(dataset, qr)); } catch (Exception err) { log.error("", err); } } } }
28.761905
124
0.746689
087fa59547cc5d978b7fae7778b276cc916e9065
2,548
package com.zs.controller; import com.zs.config.Code; import com.zs.comm.Respond; import com.zs.model.User; import com.zs.server.OrderServer; import com.zs.server.UserServer; import com.zs.vo.OrderQuery; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.UsernamePasswordToken; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Map; @Controller public class MainController { @Autowired private UserServer userService; @Autowired private OrderServer orderServer; @ResponseBody @PostMapping("/login") public Respond login(String faccount, String fpasswd) { Respond respond; AuthenticationToken token = new UsernamePasswordToken(faccount, fpasswd); try { SecurityUtils.getSubject().login(token); respond = Respond.success("登录成功"); } catch (AuthenticationException e) { respond = Respond.error(Code.AUTH_FAIL); } return respond; } @ResponseBody @GetMapping("/login") public Respond noLogin() { return Respond.error(Code.NO_LOGIN); } @ResponseBody @GetMapping("/logout") public Respond logout() { SecurityUtils.getSubject().logout(); return Respond.success("退出成功"); } @ResponseBody @PostMapping("/password") public Respond password(String oldpwd, String newpwd) { int result = userService.password(oldpwd, newpwd); if (result == 1) { return Respond.success("密码修改成功"); } else { return Respond.error(Code.AUTH_FAIL.getCode(), "旧密码错误"); } } @GetMapping("/index") @ResponseBody public Respond index() { User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user"); String toDay = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); OrderQuery query = new OrderQuery(); query.setFeid(user.getFeid()); query.setFbegin(toDay); query.setFend(toDay); Map<String, Object> data = orderServer.toDay(query); return Respond.success(data); } }
30.333333
89
0.689168
9286d9298e89542b0ad802341bf90feea57fbce2
600
package io.spring.user.service; import io.spring.user.action.User; import io.spring.user.dao.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; @Service("userService") public class UserServiceImpl implements UserService{ @Autowired private UserDao userDao; @Value("#{config['javaosc.password.value']}") private String password; @Override public User getUserList(User user) { user = userDao.getUser(user); user.setPassword(password); return user; } }
22.222222
62
0.78
75a4af835f5da19684de46be9d3230fd67ad772f
8,314
/* * Copyright 2021 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.titus.master.jobmanager.store; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import com.google.common.annotations.VisibleForTesting; import com.netflix.spectator.api.Gauge; import com.netflix.spectator.api.Registry; import com.netflix.titus.api.jobmanager.model.job.ExecutableStatus; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.JobFunctions; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.model.job.TaskState; import com.netflix.titus.api.jobmanager.service.V3JobOperations; import com.netflix.titus.api.jobmanager.store.JobStore; import com.netflix.titus.common.framework.scheduler.ScheduleReference; import com.netflix.titus.common.framework.scheduler.model.ScheduleDescriptor; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.Evaluators; import com.netflix.titus.common.util.ExecutorsExt; import com.netflix.titus.common.util.guice.annotation.Activator; import com.netflix.titus.common.util.guice.annotation.Deactivator; import com.netflix.titus.common.util.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Completable; import rx.Observable; import static com.netflix.titus.master.MetricConstants.METRIC_JOB_MANAGER; @Singleton public class ArchivedTasksGc { private static final Logger logger = LoggerFactory.getLogger(ArchivedTasksGc.class); private final V3JobOperations jobOperations; private final JobStore jobStore; private final TitusRuntime titusRuntime; private final ArchivedTasksGcConfiguration configuration; private final Gauge jobsEvaluatedGauge; private final Gauge jobsNeedingGcGauge; private final Gauge tasksNeedingGcGauge; private final Gauge tasksToGcGauge; private ScheduleReference schedulerRef; @Inject public ArchivedTasksGc(ArchivedTasksGcConfiguration configuration, V3JobOperations jobOperations, JobStore jobStore, TitusRuntime titusRuntime) { this.configuration = configuration; this.jobOperations = jobOperations; this.jobStore = jobStore; this.titusRuntime = titusRuntime; Registry registry = titusRuntime.getRegistry(); String metricNamePrefix = METRIC_JOB_MANAGER + "archivedTasksGc."; jobsEvaluatedGauge = registry.gauge(metricNamePrefix + "jobsEvaluated"); jobsNeedingGcGauge = registry.gauge(metricNamePrefix + "jobsNeedingGc"); tasksNeedingGcGauge = registry.gauge(metricNamePrefix + "tasksNeedingGc"); tasksToGcGauge = registry.gauge(metricNamePrefix + "tasksToGc"); } @Activator public void enterActiveMode() { ScheduleDescriptor scheduleDescriptor = ScheduleDescriptor.newBuilder() .withName("gcArchivedTasks") .withDescription("GC oldest archived pasts once the criteria is met") .withInitialDelay(Duration.ofMillis(configuration.getGcInitialDelayMs())) .withInterval(Duration.ofMillis(configuration.getGcIntervalMs())) .withTimeout(Duration.ofMillis(configuration.getGcTimeoutMs())) .build(); this.schedulerRef = titusRuntime.getLocalScheduler().schedule( scheduleDescriptor, e -> gc(), ExecutorsExt.namedSingleThreadExecutor(ArchivedTasksGc.class.getSimpleName()) ); } @Deactivator @PreDestroy public void shutdown() { Evaluators.acceptNotNull(schedulerRef, ScheduleReference::cancel); } @VisibleForTesting void gc() { if (!configuration.isGcEnabled()) { logger.info("GC is not enabled"); return; } long maxNumberOfArchivedTasksPerJob = configuration.getMaxNumberOfArchivedTasksPerJob(); List<String> jobIds = jobOperations.getJobs().stream().map(Job::getId).collect(Collectors.toList()); logger.info("Evaluating {} jobs for GC", jobIds.size()); jobsEvaluatedGauge.set(jobIds.size()); List<Observable<Pair<String, Long>>> archivedTaskCountObservables = jobIds.stream() .map(jobId -> jobStore.retrieveArchivedTaskCountForJob(jobId).map(count -> Pair.of(jobId, count))) .collect(Collectors.toList()); List<Pair<String, Long>> archivedTaskCountsPerJob = Observable.merge(archivedTaskCountObservables, configuration.getMaxRxConcurrency()) .toList().toBlocking().singleOrDefault(Collections.emptyList()); logger.debug("archivedTaskCountsPerJob: {}", archivedTaskCountsPerJob); List<String> jobsNeedingGc = new ArrayList<>(); for (Pair<String, Long> archivedTaskCountPair : archivedTaskCountsPerJob) { if (archivedTaskCountPair.getRight() > maxNumberOfArchivedTasksPerJob) { jobsNeedingGc.add(archivedTaskCountPair.getLeft()); } } logger.info("{} jobs need GC: {}", jobsNeedingGc.size(), jobsNeedingGc); jobsNeedingGcGauge.set(jobsNeedingGc.size()); List<Observable<Pair<String, List<Task>>>> archivedTaskObservables = jobsNeedingGc.stream() .map(jobId -> jobStore.retrieveArchivedTasksForJob(jobId).toList().map(l -> Pair.of(jobId, l))) .collect(Collectors.toList()); List<Pair<String, List<Task>>> archivedTasksPerJob = Observable.merge(archivedTaskObservables, configuration.getMaxRxConcurrency()) .toList().toBlocking().singleOrDefault(Collections.emptyList()); List<Task> archivedTasksNeedingGc = new ArrayList<>(); for (Pair<String, List<Task>> archivedTasksPair : archivedTasksPerJob) { List<Task> archivedTasksToGc = getArchivedTasksToGc(archivedTasksPair.getRight(), maxNumberOfArchivedTasksPerJob); archivedTasksNeedingGc.addAll(archivedTasksToGc); } logger.info("{} tasks need GC", archivedTasksNeedingGc.size()); tasksNeedingGcGauge.set(archivedTasksNeedingGc.size()); List<Task> archivedTasksToGc = archivedTasksNeedingGc.stream() .limit(configuration.getMaxNumberOfArchivedTasksToGcPerIteration()) .collect(Collectors.toList()); List<String> archivedTasksToGcIds = archivedTasksToGc.stream().map(Task::getId).collect(Collectors.toList()); logger.info("Starting to GC {} tasks: {}", archivedTasksToGc.size(), archivedTasksToGcIds); tasksToGcGauge.set(archivedTasksToGc.size()); List<Completable> deleteArchivedTaskCompletables = archivedTasksToGc.stream() .map(t -> jobStore.deleteArchivedTask(t.getJobId(), t.getId())).collect(Collectors.toList()); Completable.merge(Observable.from(deleteArchivedTaskCompletables), configuration.getMaxRxConcurrency()).await(); logger.info("Finished GC"); } static List<Task> getArchivedTasksToGc(List<Task> tasks, long maxNumberOfArchivedTasksPerJob) { int total = tasks.size(); if (total > maxNumberOfArchivedTasksPerJob) { tasks.sort(Comparator.comparing(t -> JobFunctions.findTaskStatus(t, TaskState.Accepted).map(ExecutableStatus::getTimestamp).orElse(0L))); int numberOfTasksToGc = (int) (total - maxNumberOfArchivedTasksPerJob); return tasks.subList(0, numberOfTasksToGc); } return Collections.emptyList(); } }
46.188889
149
0.716262
8db988e3a4db7871ed5e44edc99533ede7d2d3aa
859
package de.homelab.madgaksha.lotsofbs.entityengine.component; import com.badlogic.ashley.core.Component; import com.badlogic.gdx.utils.Pool.Poolable; public class TimeScaleComponent implements Component, Poolable { private final static float DEFAULT_TIME_SCALING_FACTOR = 1.0f; private final static boolean DEFAULT_SCALE_DISABLED = false; public float timeScalingFactor = DEFAULT_TIME_SCALING_FACTOR; public boolean scaleDisabled = DEFAULT_SCALE_DISABLED; public TimeScaleComponent() { } /** * Scales time by the given factor, slowing down or speeding up motion. * * @param tsf * Time scaling factor. 1.0 is no change. */ public TimeScaleComponent(float tsf) { timeScalingFactor = tsf; } @Override public void reset() { timeScalingFactor = DEFAULT_TIME_SCALING_FACTOR; scaleDisabled = DEFAULT_SCALE_DISABLED; } }
26.84375
72
0.769499
0f537f5de1f7c54c990b78ae555861d76a0d692f
762
package com.technicise; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for LaryngealRoute. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="LaryngealRoute"> * &lt;restriction base="{urn:hl7-org:v3}cs"> * &lt;enumeration value="LARYNGINSTIL"/> * &lt;enumeration value="LARYNGTA"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "LaryngealRoute") @XmlEnum public enum LaryngealRoute { LARYNGINSTIL, LARYNGTA; public String value() { return name(); } public static LaryngealRoute fromValue(String v) { return valueOf(v); } }
19.538462
95
0.658793
519b1374b3493e2d70cd4cbb4c67da9e94df6cae
5,492
/******************************************************************************* * Copyright 2013 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * 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 de.tudarmstadt.ukp.jwktl.parser.de.components; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import de.tudarmstadt.ukp.jwktl.api.entry.WiktionaryEntry; import de.tudarmstadt.ukp.jwktl.api.entry.WiktionarySense; import de.tudarmstadt.ukp.jwktl.parser.util.ParsingContext; import de.tudarmstadt.ukp.jwktl.parser.util.StringUtils; /** * Abstract parser component for extracting sense-disambiguated information * items from the German Wiktionary (e.g., example sentences, * semantic relations, translations). * @author Christian M. Meyer */ public abstract class DESenseIndexedBlockHandler<InformationType> extends DEBlockHandler { protected static final Pattern INDEX_PATTERN = Pattern.compile("^\\s*\\[([^\\[\\]]{0,20}?)\\](.*)$"); protected Map<Integer, List<String>> indexedInformation; protected Set<Integer> indexSet; /** Initializes the block handler for parsing all sections starting with * one of the specified labels. */ public DESenseIndexedBlockHandler(final String... labels) { super(labels); } @Override public boolean processHead(final String text, final ParsingContext context) { indexedInformation = new TreeMap<>(); return super.processHead(text, context); } @Override public boolean processBody(final String textLine, final ParsingContext context) { String text = textLine.trim(); if (text.startsWith("::")) { // Append to previous index set. text = text.substring(2).trim(); Matcher matcher = INDEX_PATTERN.matcher(text); if (matcher.find()) { String indexStr = matcher.group(1); text = matcher.group(2); Set<Integer> subIndexSet = StringUtils.compileIndexSet(indexStr); if (subIndexSet != null && subIndexSet.size() > 0) { indexSet = subIndexSet; for (Integer idx : indexSet) addIndexedLine(idx, text); } else for (Integer idx : indexSet) appendIndexedLine(idx, text); } else if (indexSet != null) for (Integer idx : indexSet) appendIndexedLine(idx, text); /*if (indexSet != null) for (Integer idx : indexSet) appendIndexedLine(idx, text);*/ } else if (text.startsWith(":")) { // Determine index set and add the information. text = text.substring(1).trim(); Matcher matcher = INDEX_PATTERN.matcher(text); if (matcher.find()) { String indexStr = matcher.group(1); text = matcher.group(2); indexSet = StringUtils.compileIndexSet(indexStr); for (Integer idx : indexSet) addIndexedLine(idx, text); } else { indexSet = new HashSet<>(); indexSet.add(0); addIndexedLine(0, text); } } else { // Append to previous index set. if (indexSet != null) for (Integer idx : indexSet) appendIndexedLine(idx, text); } return super.processBody(textLine, context); } protected void addIndexedLine(int index, final String text) { if (text.isEmpty()) return; if (index < 0) index = 0; List<String> lines = indexedInformation.get(index); if (lines == null) { lines = new ArrayList<>(); indexedInformation.put(index, lines); } lines.add(text); } protected void appendIndexedLine(int index, final String text) { if (text.isEmpty()) return; if (index < 0) index = 0; List<String> lines = indexedInformation.get(index); if (lines == null) { lines = new ArrayList<>(); indexedInformation.put(index, lines); } if (lines.size() > 0) { lines.set(lines.size() - 1, lines.get(lines.size() - 1) + "\n" + text); } else lines.add(text); } protected abstract List<InformationType> extract(int index, final String text); public void fillContent(final ParsingContext context) { WiktionaryEntry posEntry = context.findEntry(); for (Entry<Integer, List<String>> indexedLine : indexedInformation.entrySet()) { WiktionarySense sense = posEntry.findSenseByMarker(Integer.toString(indexedLine.getKey())); //TODO: index set as a list of strings? for (String line : indexedLine.getValue()) { List<InformationType> extractedInformation = extract(indexedLine.getKey(), line); if (extractedInformation != null) { for (InformationType info : extractedInformation) if (sense != null) updateSense(sense, info); else updatePosEntry(posEntry, info); } } } } protected abstract void updateSense(final WiktionarySense sense, final InformationType info); protected abstract void updatePosEntry(final WiktionaryEntry posEntry, final InformationType info); }
33.084337
134
0.683904
5021feed54942285b909cfb611b31be6f59cd7e3
528
package io.alauda.jenkins.devops.sync.util; import io.alauda.devops.java.client.models.V1alpha1Condition; import java.util.List; import javax.annotation.Nullable; public class ConditionUtils { @Nullable public static V1alpha1Condition getCondition( List<V1alpha1Condition> conditions, String conditionType) { if (conditions == null) { return null; } return conditions .stream() .filter(cond -> cond.getType().equals(conditionType)) .findAny() .orElse(null); } }
22.956522
65
0.691288
13bdd276f78605df4052b678aec9eb55002dd946
13,693
/* * 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.druid.query.groupby.orderby; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; import it.unimi.dsi.fastutil.objects.Object2IntMap; import org.apache.druid.common.config.NullHandling; import org.apache.druid.data.input.Rows; import org.apache.druid.java.util.common.ISE; import org.apache.druid.java.util.common.granularity.Granularities; import org.apache.druid.java.util.common.guava.Sequence; import org.apache.druid.java.util.common.guava.Sequences; import org.apache.druid.query.aggregation.AggregatorFactory; import org.apache.druid.query.aggregation.PostAggregator; import org.apache.druid.query.dimension.DimensionSpec; import org.apache.druid.query.groupby.GroupByQuery; import org.apache.druid.query.groupby.ResultRow; import org.apache.druid.query.ordering.StringComparator; import org.apache.druid.query.ordering.StringComparators; import org.apache.druid.segment.column.ValueType; import javax.annotation.Nullable; import java.nio.ByteBuffer; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * */ public class DefaultLimitSpec implements LimitSpec { private static final byte CACHE_KEY = 0x1; private final List<OrderByColumnSpec> columns; private final int limit; /** * Check if a limitSpec has columns in the sorting order that are not part of the grouping fields represented * by `dimensions`. * * @param limitSpec LimitSpec, assumed to be non-null * @param dimensions Grouping fields for a groupBy query * * @return True if limitSpec has sorting columns not contained in dimensions */ public static boolean sortingOrderHasNonGroupingFields(DefaultLimitSpec limitSpec, List<DimensionSpec> dimensions) { for (OrderByColumnSpec orderSpec : limitSpec.getColumns()) { int dimIndex = OrderByColumnSpec.getDimIndexForOrderBy(orderSpec, dimensions); if (dimIndex < 0) { return true; } } return false; } public static StringComparator getComparatorForDimName(DefaultLimitSpec limitSpec, String dimName) { final OrderByColumnSpec orderBy = OrderByColumnSpec.getOrderByForDimName(limitSpec.getColumns(), dimName); if (orderBy == null) { return null; } return orderBy.getDimensionComparator(); } @JsonCreator public DefaultLimitSpec( @JsonProperty("columns") List<OrderByColumnSpec> columns, @JsonProperty("limit") Integer limit ) { this.columns = (columns == null) ? ImmutableList.of() : columns; this.limit = (limit == null) ? Integer.MAX_VALUE : limit; Preconditions.checkArgument(this.limit > 0, "limit[%s] must be >0", limit); } @JsonProperty public List<OrderByColumnSpec> getColumns() { return columns; } @JsonProperty public int getLimit() { return limit; } public boolean isLimited() { return limit < Integer.MAX_VALUE; } @Override public Function<Sequence<ResultRow>, Sequence<ResultRow>> build(final GroupByQuery query) { final List<DimensionSpec> dimensions = query.getDimensions(); // Can avoid re-sorting if the natural ordering is good enough. boolean sortingNeeded = dimensions.size() < columns.size(); final Set<String> aggAndPostAggNames = new HashSet<>(); for (AggregatorFactory agg : query.getAggregatorSpecs()) { aggAndPostAggNames.add(agg.getName()); } for (PostAggregator postAgg : query.getPostAggregatorSpecs()) { aggAndPostAggNames.add(postAgg.getName()); } if (!sortingNeeded) { for (int i = 0; i < columns.size(); i++) { final OrderByColumnSpec columnSpec = columns.get(i); if (aggAndPostAggNames.contains(columnSpec.getDimension())) { sortingNeeded = true; break; } final ValueType columnType = getOrderByType(columnSpec, dimensions); final StringComparator naturalComparator; if (columnType == ValueType.STRING) { naturalComparator = StringComparators.LEXICOGRAPHIC; } else if (ValueType.isNumeric(columnType)) { naturalComparator = StringComparators.NUMERIC; } else { sortingNeeded = true; break; } if (columnSpec.getDirection() != OrderByColumnSpec.Direction.ASCENDING || !columnSpec.getDimensionComparator().equals(naturalComparator) || !columnSpec.getDimension().equals(dimensions.get(i).getOutputName())) { sortingNeeded = true; break; } } } if (!sortingNeeded) { // If granularity is ALL, sortByDimsFirst doesn't change the sorting order. sortingNeeded = !query.getGranularity().equals(Granularities.ALL) && query.getContextSortByDimsFirst(); } if (!sortingNeeded) { return isLimited() ? new LimitingFn(limit) : Functions.identity(); } // Materialize the Comparator first for fast-fail error checking. final Ordering<ResultRow> ordering = makeComparator( query.getResultRowPositionLookup(), query.getResultRowHasTimestamp(), query.getDimensions(), query.getAggregatorSpecs(), query.getPostAggregatorSpecs(), query.getContextSortByDimsFirst() ); if (isLimited()) { return new TopNFunction(ordering, limit); } else { return new SortingFn(ordering); } } @Override public LimitSpec merge(LimitSpec other) { return this; } private ValueType getOrderByType(final OrderByColumnSpec columnSpec, final List<DimensionSpec> dimensions) { for (DimensionSpec dimSpec : dimensions) { if (columnSpec.getDimension().equals(dimSpec.getOutputName())) { return dimSpec.getOutputType(); } } throw new ISE("Unknown column in order clause[%s]", columnSpec); } @Override public LimitSpec filterColumns(Set<String> names) { return new DefaultLimitSpec( columns.stream().filter(c -> names.contains(c.getDimension())).collect(Collectors.toList()), limit ); } private Ordering<ResultRow> makeComparator( Object2IntMap<String> rowOrderLookup, boolean hasTimestamp, List<DimensionSpec> dimensions, List<AggregatorFactory> aggs, List<PostAggregator> postAggs, boolean sortByDimsFirst ) { final Ordering<ResultRow> timeOrdering; if (hasTimestamp) { timeOrdering = new Ordering<ResultRow>() { @Override public int compare(ResultRow left, ResultRow right) { return Longs.compare(left.getLong(0), right.getLong(0)); } }; } else { timeOrdering = null; } Map<String, DimensionSpec> dimensionsMap = new HashMap<>(); for (DimensionSpec spec : dimensions) { dimensionsMap.put(spec.getOutputName(), spec); } Map<String, AggregatorFactory> aggregatorsMap = new HashMap<>(); for (final AggregatorFactory agg : aggs) { aggregatorsMap.put(agg.getName(), agg); } Map<String, PostAggregator> postAggregatorsMap = new HashMap<>(); for (PostAggregator postAgg : postAggs) { postAggregatorsMap.put(postAgg.getName(), postAgg); } Ordering<ResultRow> ordering = null; for (OrderByColumnSpec columnSpec : columns) { String columnName = columnSpec.getDimension(); Ordering<ResultRow> nextOrdering = null; final int columnIndex = rowOrderLookup.applyAsInt(columnName); if (columnIndex >= 0) { if (postAggregatorsMap.containsKey(columnName)) { //noinspection unchecked nextOrdering = metricOrdering(columnIndex, postAggregatorsMap.get(columnName).getComparator()); } else if (aggregatorsMap.containsKey(columnName)) { //noinspection unchecked nextOrdering = metricOrdering(columnIndex, aggregatorsMap.get(columnName).getComparator()); } else if (dimensionsMap.containsKey(columnName)) { nextOrdering = dimensionOrdering(columnIndex, columnSpec.getDimensionComparator()); } } if (nextOrdering == null) { throw new ISE("Unknown column in order clause[%s]", columnSpec); } if (columnSpec.getDirection() == OrderByColumnSpec.Direction.DESCENDING) { nextOrdering = nextOrdering.reverse(); } ordering = ordering == null ? nextOrdering : ordering.compound(nextOrdering); } if (ordering == null) { ordering = timeOrdering; } else if (timeOrdering != null) { ordering = sortByDimsFirst ? ordering.compound(timeOrdering) : timeOrdering.compound(ordering); } //noinspection unchecked return ordering != null ? ordering : (Ordering) Ordering.allEqual(); } private <T> Ordering<ResultRow> metricOrdering(final int column, final Comparator<T> comparator) { // As per SQL standard we need to have same ordering for metrics as dimensions i.e nulls first // If SQL compatibility is not enabled we use nullsLast ordering for null metrics for backwards compatibility. final Comparator<T> nullFriendlyComparator = NullHandling.sqlCompatible() ? Comparator.nullsFirst(comparator) : Comparator.nullsLast(comparator); //noinspection unchecked return Ordering.from(Comparator.comparing(row -> (T) row.get(column), nullFriendlyComparator)); } private Ordering<ResultRow> dimensionOrdering(final int column, final StringComparator comparator) { return Ordering.from( Comparator.comparing((ResultRow row) -> getDimensionValue(row, column), Comparator.nullsFirst(comparator)) ); } @Nullable private static String getDimensionValue(ResultRow row, int column) { final List<String> values = Rows.objectToStrings(row.get(column)); return values.isEmpty() ? null : Iterables.getOnlyElement(values); } @Override public String toString() { return "DefaultLimitSpec{" + "columns='" + columns + '\'' + ", limit=" + limit + '}'; } private static class LimitingFn implements Function<Sequence<ResultRow>, Sequence<ResultRow>> { private final int limit; public LimitingFn(int limit) { this.limit = limit; } @Override public Sequence<ResultRow> apply(Sequence<ResultRow> input) { return input.limit(limit); } } private static class SortingFn implements Function<Sequence<ResultRow>, Sequence<ResultRow>> { private final Ordering<ResultRow> ordering; public SortingFn(Ordering<ResultRow> ordering) { this.ordering = ordering; } @Override public Sequence<ResultRow> apply(@Nullable Sequence<ResultRow> input) { return Sequences.sort(input, ordering); } } private static class TopNFunction implements Function<Sequence<ResultRow>, Sequence<ResultRow>> { private final Ordering<ResultRow> ordering; private final int limit; public TopNFunction(Ordering<ResultRow> ordering, int limit) { this.ordering = ordering; this.limit = limit; } @Override public Sequence<ResultRow> apply(final Sequence<ResultRow> input) { return new TopNSequence<>(input, ordering, limit); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultLimitSpec that = (DefaultLimitSpec) o; if (limit != that.limit) { return false; } if (columns != null ? !columns.equals(that.columns) : that.columns != null) { return false; } return true; } @Override public int hashCode() { int result = columns != null ? columns.hashCode() : 0; result = 31 * result + limit; return result; } @Override public byte[] getCacheKey() { final byte[][] columnBytes = new byte[columns.size()][]; int columnsBytesSize = 0; int index = 0; for (OrderByColumnSpec column : columns) { columnBytes[index] = column.getCacheKey(); columnsBytesSize += columnBytes[index].length; ++index; } ByteBuffer buffer = ByteBuffer.allocate(1 + columnsBytesSize + 4) .put(CACHE_KEY); for (byte[] columnByte : columnBytes) { buffer.put(columnByte); } buffer.put(Ints.toByteArray(limit)); return buffer.array(); } }
31.191344
116
0.685533
d26928f8b65d6d50003801354d63a8a308bcb963
186
package scala.meta.pc; import java.util.List; import org.eclipse.lsp4j.TextEdit; public interface AutoImportsResult { public String packageName(); public List<TextEdit> edits(); }
18.6
36
0.768817
90a5e95342fd3144373e383c39742a1a42895545
1,438
package com.xxgc.model; public class MessageReplay { private int mrid; private int meid; private String mrcontent; private String mrtime; private int mruser; private int mrmanager; private String managername; private String username; public int getMrmanager() { return mrmanager; } public void setMrmanager(int mrmanager) { this.mrmanager = mrmanager; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getManagername() { return managername; } public void setManagername(String managername) { this.managername = managername; } public int getMruser() { return mruser; } public void setMruser(int mruser) { this.mruser = mruser; } public int getMrid() { return mrid; } public void setMrid(int mrid) { this.mrid = mrid; } public int getMeid() { return meid; } public void setMeid(int meid) { this.meid = meid; } public String getMrcontent() { return mrcontent; } public void setMrcontent(String mrcontent) { this.mrcontent = mrcontent; } public String getMrtime() { return mrtime; } public void setMrtime(String mrtime) { this.mrtime = mrtime; } @Override public String toString() { return "MessageReplay [managername=" + managername + ", meid=" + meid + ", mrcontent=" + mrcontent + ", mrid=" + mrid + ", mrtime=" + mrtime + ", mruser=" + mruser + "]"; } }
19.69863
71
0.687761
4b68da02ce0e0d0a14ce3fbc49bd80bbb77d2b1a
3,492
package seedu.address.logic.commands; import static java.util.Objects.requireNonNull; import static seedu.address.logic.parser.CliSyntax.PREFIX_RECORD_HOUR; import static seedu.address.logic.parser.CliSyntax.PREFIX_RECORD_REMARK; import java.util.List; import seedu.address.commons.core.EventsCenter; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.commons.events.ui.ContextChangeEvent; import seedu.address.commons.events.ui.RecordChangeEvent; import seedu.address.logic.CommandHistory; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.record.Record; import seedu.address.model.record.RecordContainsEventIdPredicate; import seedu.address.model.volunteer.Volunteer; /** * Adds a record to the application. */ public class AddRecordCommand extends Command { public static final String COMMAND_WORD = "add"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Adds a volunteer record to the event that " + "is currently managed." + "Parameters: VOLUNTEER_INDEX (must be a positive integer) " + "[" + PREFIX_RECORD_HOUR + "HOURS] " + "[" + PREFIX_RECORD_REMARK + "REMARKS]\n" + "Example: " + COMMAND_WORD + " " + "1 " + PREFIX_RECORD_HOUR + "5 " + PREFIX_RECORD_REMARK + "Emcee"; public static final String MESSAGE_SUCCESS = "Record added: %1$s"; public static final String MESSAGE_DUPLICATE_RECORD = "This volunteer is already registered."; public final Index index; private final Record toAdd; /** * Creates an AddCommand to add the specified {@code Person} */ public AddRecordCommand(Index index, Record record) { requireNonNull(index); requireNonNull(record); this.index = index; this.toAdd = record; } @Override public CommandResult execute(Model model, CommandHistory history) throws CommandException { requireNonNull(model); List<Volunteer> lastShownList = model.getFilteredVolunteerList(); if (index.getZeroBased() >= lastShownList.size()) { throw new CommandException(Messages.MESSAGE_INVALID_VOLUNTEER_DISPLAYED_INDEX); } Volunteer volunteerSelected = lastShownList.get(index.getZeroBased()); Record record = new Record(model.getSelectedEvent().getEventId(), volunteerSelected.getVolunteerId(), toAdd.getHour(), toAdd.getRemark()); record.setVolunteerName(volunteerSelected.getName().fullName); if (model.hasRecord(record)) { throw new CommandException(MESSAGE_DUPLICATE_RECORD); } model.addRecord(record); model.updateFilteredRecordList(new RecordContainsEventIdPredicate(model.getSelectedEvent().getEventId())); model.commitAddressBook(); // Posting event EventsCenter.getInstance().post(new RecordChangeEvent(model.getSelectedEvent())); EventsCenter.getInstance().post(new ContextChangeEvent(model.getContextId())); return new CommandResult(String.format(MESSAGE_SUCCESS, record)); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof AddRecordCommand // instanceof handles nulls && toAdd.equals(((AddRecordCommand) other).toAdd)); } }
38.8
114
0.703322
b87a8dd3256be6fa87b9ad5e2df4adb591d0a993
3,378
/** * The MIT License * * Copyright (C) 2015 Asterios Raptis * * 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.astrapi69.design.pattern.observer; import java.util.ArrayList; import java.util.Collection; import java.util.List; import lombok.Getter; import io.github.astrapi69.design.pattern.observer.api.Observer; import io.github.astrapi69.design.pattern.observer.api.Subject; /** * The Class AbstractSubject is an implementation from the interface Subject. This class * encapsulates the observable and fires an update if the observable changes. The update informs all * registered observers about the change of the observable. * * @param <T> * the generic type of the observable. * @param <O> * the generic type of the observer */ public abstract class AbstractSubject<T, O extends Observer<T>> implements Subject<T, O> { /** The observers. */ @Getter private final List<O> observers; /** The observable object. */ @Getter private T observable; /** * Initialize block. **/ { observers = new ArrayList<>(); } /** * Default constructor for a new subject. */ public AbstractSubject() { } /** * Constructor for a new subject with an observable. * * @param observable * the observable */ public AbstractSubject(final T observable) { this.observable = observable; } /** * {@inheritDoc} */ @Override public synchronized void add(final O observer) { getObservers().add(observer); } /** * {@inheritDoc} */ @Override public synchronized void addAll(final Collection<O> observers) { getObservers().addAll(observers); } /** * {@inheritDoc} */ @Override public synchronized void remove(final O observer) { final int index = getObservers().indexOf(observer); if (0 <= index) { getObservers().remove(observer); } } /** * {@inheritDoc} */ @Override public synchronized void removeAll(final Collection<O> observers) { getObservers().removeAll(observers); } /** * {@inheritDoc} */ @Override public synchronized void setObservable(final T observable) { this.observable = observable; updateObservers(); } /** * {@inheritDoc} */ @Override public synchronized void updateObservers() { for (final O observer : getObservers()) { observer.update(getObservable()); } } }
23.622378
100
0.706631
fb21c949cd9db61d1f0bc838c643dfa6b4faac01
458
package pt.ismai.hungryme.ui.UI; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.ButterKnife; public class BaseFragment extends Fragment { public View inflateAndBind(LayoutInflater inflater, ViewGroup container, int layout) { View view = inflater.inflate(layout, container, false); ButterKnife.bind(this, view); return view; } }
25.444444
90
0.748908
46d9393103b94a1c6e4bf9530080976a27e8ac5a
1,681
package lci.biz.springboot.resources; import lci.biz.springboot.model.Calculation; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; /** * Created by tlanders on 5/3/2017. */ @RestController @RequestMapping("/calculation") public class CalculationController { private static final String PATTERN = "^-?+\\d+\\.?+\\d*$"; @RequestMapping(value = "/power", method = RequestMethod.GET) public Calculation pow(@RequestParam(value = "base") String b, @RequestParam(value = "exponent") String exp) { List<String> input = new ArrayList<>(); input.add(b); input.add(exp); List<String> output = new ArrayList<>(); if(b != null && exp != null && b.matches(PATTERN) && exp.matches(PATTERN)) { output.add(String.valueOf(Math.pow(Double.valueOf(b), Double.valueOf(exp)))); } else { output.add("base and/or exponent are not numeric"); } return new Calculation("power", input, output); } @RequestMapping(value = "/sqrt/{num:.+}", method = RequestMethod.GET) public Calculation sqrt(@PathVariable(value = "num") String num) { List<String> input = new ArrayList<>(); input.add(num); List<String> output = new ArrayList<>(); if(num != null && num.matches(PATTERN)) { try { output.add(String.valueOf(Math.sqrt(Double.valueOf(num)))); } catch(Exception ex) { output.add("num is negative"); } } else { output.add("num is not numeric"); } return new Calculation("sqrt", input, output); } }
33.62
114
0.599643
327f3bc709060b3feb72e431b12dfd948a7c31be
1,940
package com.github.chic.admin.component.aspect; import cn.hutool.extra.servlet.ServletUtil; import com.github.chic.admin.util.SecurityUtils; import com.github.chic.common.util.ServletUtils; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; /** * 统一日志处理切面 */ @Slf4j @Aspect @Component public class WebLogAspect { /** * LOG TEMPLATE * {METHOD} - {URL} - ARGS : {} - UID : {} - IP : {} - SPEND TIME : {} */ private static final String LOG_TEMPLATE = "{} : {} - ARGS : {} - UID : {} - IP : {} - SPEND TIME : {}"; @Around("execution(public * com.github.chic.admin.controller..*.*(..))") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { // 记录开始时间 long startTime = System.currentTimeMillis(); // 请求 HttpServletRequest request = ServletUtils.getRequest(); // 记录请求内容 String method = request.getMethod(); String url = request.getRequestURL().toString(); String args = Arrays.toString(joinPoint.getArgs()); Long uid = getCurrentAdminId(); String ip = ServletUtil.getClientIP(request); try { // 执行请求方法 return joinPoint.proceed(joinPoint.getArgs()); } finally { // 记录结束时间 long endTime = System.currentTimeMillis(); // {METHOD} - {URL} - ARGS : {} - UID : {} - IP : {} - SPEND TIME : {} log.info(LOG_TEMPLATE, method, url, args, uid, ip, endTime - startTime); } } /** * 获取当前用户 ID */ private Long getCurrentAdminId() { try { return SecurityUtils.getCurrentAdminId(); } catch (Exception e) { return null; } } }
31.290323
108
0.613918
00ffb6cb178146c55d11f70627622794c1d91518
554
package org.firstinspires.ftc.teamcode6032.debug.comms.data.commands; import static org.firstinspires.ftc.teamcode6032.debug.comms.data.Command.create; public class CommandsInitializer { /** Load (or reload) all the commands */ public static void load() { // Control commands, no function, but used in command sender. create("WAIT", p->null); create("FAIL",p->null); // Functional commands, handling or requesting data from the robot. create(new LogsCommand()); //// TODO: add commands } }
30.777778
81
0.67148
b5cdfb3cb76c82d71814f93ed44dc42fce924df9
916
package com.home.client.control; import com.home.client.part.hPlayer.HPlayer; import com.home.client.scene.scene.GScene; import com.home.commonClient.control.ClientFactoryControl; import com.home.commonClient.control.SceneControl; import com.home.commonClient.part.player.Player; import com.home.commonClient.scene.base.GameScene; public class GClientFactoryControl extends ClientFactoryControl { @Override public GClientMainControl createMainControl() { return new GClientMainControl(); } @Override public GClientBehaviourControl createBehaviourControl() { return new GClientBehaviourControl(); } @Override public SceneControl createSceneControl() { return new GSceneControl(); } //--逻辑组--// /** 创建角色 */ public Player createPlayer() { return new HPlayer(); } /** 创建场景 */ public GameScene createScene() { return new GScene(); } }
20.818182
64
0.723799
02501eb514d0fa6020eaa5939222dcdca5dfdc00
1,131
package com.example.pocketknife; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import pocketknife.BindExtra; import pocketknife.NotRequired; import pocketknife.PocketKnife; import pocketknife.SaveState; public class SimpleFragmentActivity extends FragmentActivity { @BindExtra("INT") @NotRequired int intExtra = 2; @BindExtra("STRING") @NotRequired String stringExtra = "NOT_REQUIRED"; @SaveState int i = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.simple_activity); PocketKnife.bindExtras(this); PocketKnife.restoreInstanceState(this, savedInstanceState); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); PocketKnife.saveInstanceState(this, outState); } public void replaceFragment(Fragment fragment) { getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit(); } }
26.928571
98
0.733864
41909f8a4dce37aa25b73cfdd71ef345645367f8
776
package eu.kalodiodev.springjumpstart.repository; import java.util.Set; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import eu.kalodiodev.springjumpstart.domain.PasswordResetToken; /** * Repository for {@link PasswordResetToken} * * @author Athanasios Raptodimos */ @Repository public interface PasswordResetTokenRepository extends CrudRepository<PasswordResetToken, Long> { /** * Find Password reset token by token * * @param token * @return passwordResetToken */ PasswordResetToken findByToken(String token); /** * Find all password reset tokens of user * * @param userId User's id * @return Password reset tokens */ Set<PasswordResetToken> findAllByUserId(Long userId); }
22.823529
96
0.766753
dfa817296a89321fec4f237ff54791c6e60a74db
2,113
package leetcode.official; import java.util.ArrayList; import java.util.HashSet; import java.util.Random; /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */ public class Question380 { public static class RandomizedSet { // 值 Set private final HashSet<Integer> values = new HashSet<>(); // 随机数 private static final Random random = new Random(); public RandomizedSet() { } public boolean insert(int val) { if (values.contains(val)) { return false; } values.add(val); return true; } public boolean remove(int val) { if (!values.contains(val)) { return false; } values.remove(val); return true; } /** * 此方法是利用 values 的所有现有值作为 ArrayList 的构造函数参数 * 创建一个新 ArrayList,然后 get 其下标值 idx,idx 此处为 values 的 size 范围内随机生成 * @return */ public int getRandom() { return new ArrayList<>(values).get(random.nextInt(values.size())); } } /** * 以下为宫水的解法 * 时间上要高一点 */ // class RandomizedSet { // static int[] nums = new int[200010]; // Random random = new Random(); // Map<Integer, Integer> map = new HashMap<>(); // int idx = -1; // public boolean insert(int val) { // if (map.containsKey(val)) return false; // nums[++idx] = val; // map.put(val, idx); // return true; // } // public boolean remove(int val) { // if (!map.containsKey(val)) return false; // int loc = map.remove(val); // if (loc != idx) map.put(nums[idx], loc); // nums[loc] = nums[idx--]; // return true; // } // public int getRandom() { // return nums[random.nextInt(idx + 1)]; // } // } }
27.441558
78
0.517747
ea5f146127ab9832ad2c50da3c632e326afc8a24
6,718
/* * Copyright 2020 Global Biodiversity Information Facility (GBIF) * * 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.gbif.registry.ws.it; import org.gbif.api.model.common.paging.Pageable; import org.gbif.api.model.common.paging.PagingRequest; import org.gbif.api.model.common.paging.PagingResponse; import org.gbif.api.model.registry.Installation; import org.gbif.api.model.registry.Organization; import org.gbif.api.model.registry.metasync.MetasyncHistory; import org.gbif.api.model.registry.metasync.MetasyncResult; import org.gbif.api.service.registry.InstallationService; import org.gbif.api.service.registry.MetasyncHistoryService; import org.gbif.api.service.registry.NodeService; import org.gbif.api.service.registry.OrganizationService; import org.gbif.registry.search.test.EsManageServer; import org.gbif.registry.test.TestDataFactory; import org.gbif.registry.ws.client.InstallationClient; import org.gbif.registry.ws.client.NodeClient; import org.gbif.registry.ws.client.OrganizationClient; import org.gbif.ws.client.filter.SimplePrincipalProvider; import org.gbif.ws.security.KeyStore; import java.util.Date; import java.util.UUID; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.server.LocalServerPort; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Runs tests for the {@link MetasyncHistoryService} implementations. This is parameterized to run * the same test routines for the following: * * <ol> * <li>The WS service layer * <li>The WS service client layer * </ol> */ public class MetasyncHistoryIT extends BaseItTest { private final MetasyncHistoryService metasyncHistoryResource; private final MetasyncHistoryService metasyncHistoryClient; private final OrganizationService organizationResource; private final OrganizationService organizationClient; private final NodeService nodeResource; private final NodeService nodeClient; private final InstallationService installationResource; private final InstallationService installationClient; private final TestDataFactory testDataFactory; @Autowired public MetasyncHistoryIT( MetasyncHistoryService metasyncHistoryResource, OrganizationService organizationResource, NodeService nodeResource, InstallationService installationResource, SimplePrincipalProvider simplePrincipalProvider, TestDataFactory testDataFactory, EsManageServer esServer, @LocalServerPort int localServerPort, KeyStore keyStore) { super(simplePrincipalProvider, esServer); this.metasyncHistoryResource = metasyncHistoryResource; this.organizationResource = organizationResource; this.organizationClient = prepareClient(localServerPort, keyStore, OrganizationClient.class); this.nodeResource = nodeResource; this.nodeClient = prepareClient(localServerPort, keyStore, NodeClient.class); this.installationResource = installationResource; this.installationClient = prepareClient(localServerPort, keyStore, InstallationClient.class); this.testDataFactory = testDataFactory; this.metasyncHistoryClient = prepareClient(localServerPort, keyStore, InstallationClient.class); } /** Tests the operations create and list of {@link MetasyncHistoryService}. */ @ParameterizedTest @EnumSource(ServiceType.class) public void testCreateAndList(ServiceType serviceType) { MetasyncHistoryService service = getService(serviceType, metasyncHistoryResource, metasyncHistoryClient); MetasyncHistory metasyncHistory = getTestInstance(serviceType); service.createMetasync(metasyncHistory); PagingResponse<MetasyncHistory> response = service.listMetasync(new PagingRequest()); assertTrue( response.getResults().size() > 0, "The list operation should return at least 1 record"); } /** Tests the {@link MetasyncHistoryService#listMetasync(UUID, Pageable)} operation. */ @ParameterizedTest @EnumSource(ServiceType.class) public void testListAndListByInstallation(ServiceType serviceType) { MetasyncHistoryService service = getService(serviceType, metasyncHistoryResource, metasyncHistoryClient); MetasyncHistory metasyncHistory = getTestInstance(serviceType); service.createMetasync(metasyncHistory); PagingResponse<MetasyncHistory> response = service.listMetasync(metasyncHistory.getInstallationKey(), new PagingRequest()); assertTrue( response.getResults().size() > 0, "The list operation should return at least 1 record"); } /** * Creates a test installation. The installation is persisted in the data base. The organization * related to the installation are created too. */ private Installation createTestInstallation(ServiceType serviceType) { NodeService nodeService = getService(serviceType, nodeResource, nodeClient); OrganizationService organizationService = getService(serviceType, organizationResource, organizationClient); InstallationService installationService = getService(serviceType, installationResource, installationClient); // endorsing node for the organization UUID nodeKey = nodeService.create(testDataFactory.newNode()); // publishing organization (required field) Organization org = testDataFactory.newOrganization(nodeKey); UUID organizationKey = organizationService.create(org); Installation inst = testDataFactory.newInstallation(organizationKey); UUID installationKey = installationService.create(inst); inst.setKey(installationKey); return inst; } /** Creates {@link MetasyncHistory} object to be used in test cases. */ private MetasyncHistory getTestInstance(ServiceType serviceType) { MetasyncHistory metasyncHistory = new MetasyncHistory(); metasyncHistory.setDetails("testDetails"); metasyncHistory.setResult(MetasyncResult.OK); metasyncHistory.setSyncDate(new Date()); Installation installation = createTestInstallation(serviceType); metasyncHistory.setInstallationKey(installation.getKey()); return metasyncHistory; } }
43.341935
100
0.78967
1bec689d5e4c7603e86dedac07823e6935cf2f87
4,790
package pl.polidea.navigator.ui; import pl.polidea.navigator.R; import pl.polidea.navigator.menu.AbstractDataEntryMenu; import pl.polidea.navigator.transformers.TransformationException; import pl.polidea.navigator.transformers.TransformerInterface; import android.content.res.Resources; import android.os.Bundle; import android.text.InputFilter; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import android.widget.Toast; /** * Abstract navigable number fragment - works for all numeric types. */ public abstract class AbstractDataEntryFragment extends AbstractMenuNavigatorFragment { private int errorTooShortResourceId = R.string.error_too_short; protected TransformerInterface transformer; protected EditText text; public AbstractDataEntryFragment() { super(); } protected abstract ViewGroup inflateViewGroup(LayoutInflater inflater, ViewGroup container); protected abstract void setEditTextOptions(); @Override public ViewGroup onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { if (getNavigationMenu() == null) { return null; } final ViewGroup layout = inflateViewGroup(inflater, container); text = (EditText) layout.findViewById(R.id.provide_text); if (getNavigationMenu().hint != null) { text.setHint(getNavigationMenu().hint); } final Button nextButton = (Button) layout.findViewById(R.id.provide_button); setEditTextOptions(); final AbstractDataEntryMenu menu = getNavigationMenu(); text.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(final TextView v, final int actionId, final KeyEvent event) { return goNext(v.getText().toString()); } }); nextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { goNext(text.getText().toString()); } }); if (menu.maxLength != null) { final InputFilter[] filterArray = new InputFilter[1]; filterArray[0] = new InputFilter.LengthFilter(menu.maxLength); text.setFilters(filterArray); } return layout; } @Override public AbstractDataEntryMenu getNavigationMenu() { return (AbstractDataEntryMenu) super.getNavigationMenu(); } public boolean goNext(final String transaction) { final String transformedText = transformText(transaction); if (transformedText == null) { return false; } if (getNavigationMenu().minLength != null && getNavigationMenu().minLength > transformedText.length()) { final Resources resources = getActivity().getResources(); final String toastText = String.format(resources.getString(errorTooShortResourceId), getNavigationMenu().minLength); Toast.makeText(getActivity(), toastText, Toast.LENGTH_LONG).show(); return false; } final AbstractDataEntryMenu menu = getNavigationMenu(); if (menu.variable != null && menu.menuContext != null && menu.menuContext.variables != null) { menu.menuContext.variables.put(menu.variable, transformedText); } if (menu.link == null) { if (menu.transaction != null) { onTransactionListener.handleTransaction(menu.transaction); return true; } } else { menuDownListener.onMenuDown(menu.link); return true; } return false; } private String transformText(final String transaction) { String transformedText = null; if (transformer == null) { transformedText = transaction; } else { try { transformedText = transformer.transformEnteredText(transaction); } catch (final TransformationException e) { Toast.makeText(getActivity(), e.userMessage, Toast.LENGTH_LONG).show(); return null; } } return transformedText; } public void setTransformer(final TransformerInterface transformer) { this.transformer = transformer; } public void setErrorTooShortResourceId(final int errorTooShortResourceId) { this.errorTooShortResourceId = errorTooShortResourceId; } }
37.716535
112
0.664927
0ad513c7476d58dbac5d5cb527f9b14d37fa26af
1,453
package org.visallo.core.status; import org.visallo.core.exception.VisalloException; import java.io.*; public class StatusData { private final String url; private final String hostName; private final String hostAddress; public StatusData(String url, String hostName, String hostAddress) { this.url = url; this.hostName = hostName; this.hostAddress = hostAddress; } public StatusData(byte[] rawData) { try { DataInputStream in = new DataInputStream(new ByteArrayInputStream(rawData)); this.url = in.readUTF(); this.hostName = in.readUTF(); this.hostAddress = in.readUTF(); } catch (IOException ex) { throw new VisalloException("Could not parse data", ex); } } public byte[] toBytes() { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); out.writeUTF(this.url); out.writeUTF(this.hostName); out.writeUTF(this.hostAddress); return baos.toByteArray(); } catch (IOException ex) { throw new VisalloException("Could not write data", ex); } } public String getUrl() { return url; } public String getHostName() { return hostName; } public String getHostAddress() { return hostAddress; } }
26.907407
88
0.603579
a5629cf3337571930cac670a731557f2bb544231
3,037
package com.liang.leetcode.daily.history; import java.util.HashMap; import java.util.Map; /** * LRU 缓存机制 * * @author LiaNg * @date 2020/5/25 9:16 */ public class LRUCache { public static void main(String[] args) { LRUCache cache = new LRUCache(1); cache.put(2, 1); System.out.println(cache.get(2)); cache.put(3, 2); System.out.println(cache.get(2)); } Node head; Node tail; int capacity; int count = 0; Map<Integer, Node> cache = new HashMap<Integer, Node>(); /** * 运用你所掌握的数据结构,设计和实现一个  LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。 * 获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。 * 写入数据 put(key, value) - 如果密钥已经存在,则变更其数据值;如果密钥不存在,则插入该组「密钥/数据值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。 *   * 进阶: * 你是否可以在 O(1) 时间复杂度内完成这两种操作? *   * 示例: * LRUCache cache = new LRUCache(2);// 缓存容量 * cache.put(1,1); * cache.put(2,2); * cache.get(1); // 返回 1 * cache.put(3,3); // 该操作会使得密钥 2 作废 * cache.get(2); // 返回 -1 (未找到) * cache.put(4,4); // 该操作会使得密钥 1 作废 * cache.get(1); // 返回 -1 (未找到) * cache.get(3); // 返回 3 * cache.get(4); // 返回 4 * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/lru-cache * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public LRUCache(int capacity) { this.capacity = capacity; head = new Node(); tail = new Node(); head.next = tail; tail.pre = head; } public int get(int key) { if (cache.get(key) == null) { return -1; } Node node = cache.get(key); int val = node.val; node.pre.next = node.next; node.next.pre = node.pre; node.next = head.next; node.pre = head; head.next.pre = node; head.next = node; return val; } public void put(int key, int value) { Node node = cache.get(key); if (node != null) { node.val = value; node.pre.next = node.next; node.next.pre = node.pre; node.next = head.next; node.pre = head; head.next.pre = node; head.next = node; return; } Node newNode = new Node(key, value, null, null); if (capacity == count) { cache.remove(tail.pre.key); tail.pre.pre.next = tail; tail.pre = tail.pre.pre; count--; } newNode.next = head.next; newNode.pre = head; head.next.pre = newNode; head.next = newNode; count++; cache.put(key, newNode); } class Node { int val; int key; Node next; Node pre; Node() { } Node(int key, int val, Node next, Node pre) { this.val = val; this.key = key; this.next = next; this.pre = pre; } } }
23.183206
116
0.49786
f86c7603acb3fea6fba4c29ef8e7bd8985f860da
4,337
package org.jetbrains.anko.sdk27.coroutines; import android.widget.CalendarView; import android.widget.CalendarView.OnDateChangeListener; import kotlin.Result.Failure; import kotlin.Unit; import kotlin.coroutines.Continuation; import kotlin.coroutines.CoroutineContext; import kotlin.coroutines.jvm.internal.Boxing; import kotlin.coroutines.jvm.internal.DebugMetadata; import kotlin.coroutines.jvm.internal.SuspendLambda; import kotlin.jvm.functions.Function2; import kotlin.jvm.functions.Function6; import kotlin.jvm.internal.Intrinsics; import kotlinx.coroutines.BuildersKt; import kotlinx.coroutines.CoroutineScope; import kotlinx.coroutines.CoroutineStart; import kotlinx.coroutines.GlobalScope; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; final class Sdk27CoroutinesListenersWithCoroutinesKt$onDateChange$1 implements OnDateChangeListener { final /* synthetic */ CoroutineContext $context; final /* synthetic */ Function6 $handler; @DebugMetadata(c = "org/jetbrains/anko/sdk27/coroutines/Sdk27CoroutinesListenersWithCoroutinesKt$onDateChange$1$1", f = "ListenersWithCoroutines.kt", i = {}, l = {631, 633}, m = "invokeSuspend", n = {}, s = {}) /* renamed from: org.jetbrains.anko.sdk27.coroutines.Sdk27CoroutinesListenersWithCoroutinesKt$onDateChange$1$1 reason: invalid class name */ static final class AnonymousClass1 extends SuspendLambda implements Function2<CoroutineScope, Continuation<? super Unit>, Object> { int label; private CoroutineScope p$; final /* synthetic */ Sdk27CoroutinesListenersWithCoroutinesKt$onDateChange$1 this$0; { this.this$0 = r1; } @NotNull public final Continuation<Unit> create(@Nullable Object obj, @NotNull Continuation<?> continuation) { Intrinsics.checkParameterIsNotNull(continuation, "completion"); AnonymousClass1 r1 = new AnonymousClass1(this.this$0, calendarView2, i4, i5, i6, continuation); r1.p$ = (CoroutineScope) obj; return r1; } public final Object invoke(Object obj, Object obj2) { return ((AnonymousClass1) create(obj, (Continuation) obj2)).invokeSuspend(Unit.INSTANCE); } @Nullable public final Object invokeSuspend(@NotNull Object obj) { Object coroutine_suspended = IntrinsicsKt__IntrinsicsKt.getCOROUTINE_SUSPENDED(); int i = this.label; if (i != 0) { if (i != 1) { throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine"); } else if (obj instanceof Failure) { throw ((Failure) obj).exception; } } else if (!(obj instanceof Failure)) { CoroutineScope coroutineScope = this.p$; Function6 function6 = this.this$0.$handler; CalendarView calendarView = calendarView2; Integer boxInt = Boxing.boxInt(i4); Integer boxInt2 = Boxing.boxInt(i5); Integer boxInt3 = Boxing.boxInt(i6); this.label = 1; if (function6.invoke(coroutineScope, calendarView, boxInt, boxInt2, boxInt3, this) == coroutine_suspended) { return coroutine_suspended; } } else { throw ((Failure) obj).exception; } return Unit.INSTANCE; } } Sdk27CoroutinesListenersWithCoroutinesKt$onDateChange$1(CoroutineContext coroutineContext, Function6 function6) { this.$context = coroutineContext; this.$handler = function6; } public final void onSelectedDayChange(CalendarView calendarView, int i, int i2, int i3) { GlobalScope globalScope = GlobalScope.INSTANCE; CoroutineContext coroutineContext = this.$context; CoroutineStart coroutineStart = CoroutineStart.DEFAULT; final CalendarView calendarView2 = calendarView; final int i4 = i; final int i5 = i2; final int i6 = i3; AnonymousClass1 r3 = new AnonymousClass1(this, null); BuildersKt.launch(globalScope, coroutineContext, coroutineStart, r3); } }
46.138298
215
0.660595
0278ce04b9f2b0cff862058e6271dd182887ab9a
9,176
/* * Copyright 2014 by the Metanome project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.metanome.frontend.client.datasources; import com.google.gwt.junit.client.GWTTestCase; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.HTML; import de.metanome.algorithm_integration.configuration.DbSystem; import de.metanome.backend.results_db.DatabaseConnection; import de.metanome.backend.results_db.EntityStorageException; import de.metanome.backend.results_db.TableInput; import de.metanome.frontend.client.BasePage; import de.metanome.frontend.client.TabWrapper; import de.metanome.frontend.client.TestHelper; import de.metanome.frontend.client.helpers.InputValidationException; import org.fusesource.restygwt.client.MethodCallback; import java.util.ArrayList; public class GwtTestTableInputTab extends GWTTestCase { /** * Test method for {@link de.metanome.frontend.client.datasources.TableInputTab#addTableInputToTable(de.metanome.backend.results_db.TableInput)} */ public void testAddTableInputToTable() { //Setup DatabaseConnection databaseConnection = new DatabaseConnection(); databaseConnection.setUrl("url"); databaseConnection.setPassword("password"); databaseConnection.setUsername("user"); databaseConnection.setSystem(DbSystem.DB2); TableInput tableInput = new TableInput(); tableInput.setDatabaseConnection(databaseConnection); tableInput.setTableName("table"); TableInputTab input = new TableInputTab(new DataSourcePage(new BasePage())); int rowCount = input.tableInputList.getRowCount(); // Execute input.addTableInputToTable(tableInput); //Check assertEquals(rowCount + 1, input.tableInputList.getRowCount()); } /** * Test method for {@link de.metanome.frontend.client.datasources.DatabaseConnectionTab#listDatabaseConnections(java.util.List)} */ public void testListDatabaseConnections() { //Setup DatabaseConnection databaseConnection1 = new DatabaseConnection(); databaseConnection1.setUrl("url"); databaseConnection1.setPassword("password"); databaseConnection1.setUsername("user"); databaseConnection1.setSystem(DbSystem.DB2); TableInput tableInput1 = new TableInput(); tableInput1.setDatabaseConnection(databaseConnection1); tableInput1.setTableName("table"); DatabaseConnection databaseConnection2 = new DatabaseConnection(); databaseConnection2.setUrl("url"); databaseConnection2.setPassword("password"); databaseConnection2.setUsername("user"); databaseConnection2.setSystem(DbSystem.DB2); TableInput tableInput2 = new TableInput(); tableInput2.setDatabaseConnection(databaseConnection2); tableInput2.setTableName("table"); ArrayList<TableInput> inputs = new ArrayList<TableInput>(); inputs.add(tableInput1); inputs.add(tableInput2); TableInputTab input = new TableInputTab(new DataSourcePage(new BasePage())); int rowCount = input.tableInputList.getRowCount(); // Execute input.listTableInputs(inputs); //Check assertEquals(rowCount + 3, input.tableInputList.getRowCount()); } /** * Test method for {@link de.metanome.frontend.client.datasources.TableInputTab#getDeleteCallback(de.metanome.backend.results_db.TableInput)} * and test method for {@link de.metanome.frontend.client.datasources.TableInputEditForm#increaseDatabaseConnectionUsage(String identifier)} * and test method for {@link de.metanome.frontend.client.datasources.TableInputEditForm#decreaseDatabaseConnectionUsage(String identifier)} */ public void testDeleteCallback() throws EntityStorageException, InputValidationException { // Setup TestHelper.resetDatabaseSync(); DatabaseConnection databaseConnection1 = new DatabaseConnection(); databaseConnection1.setUrl("url1"); databaseConnection1.setUsername("user1"); databaseConnection1.setSystem(DbSystem.DB2); TableInput tableInput1 = new TableInput(); tableInput1.setTableName("table1"); tableInput1.setDatabaseConnection(databaseConnection1); DatabaseConnection databaseConnection2 = new DatabaseConnection(); databaseConnection2.setUrl("url2"); databaseConnection2.setUsername("user2"); databaseConnection2.setSystem(DbSystem.DB2); TableInput tableInput2 = new TableInput(); tableInput2.setTableName("table2"); tableInput2.setDatabaseConnection(databaseConnection2); TableInput tableInput3 = new TableInput(); tableInput3.setTableName("table3"); tableInput3.setDatabaseConnection(databaseConnection2); BasePage parent = new BasePage(); DataSourcePage page = new DataSourcePage(parent); TableInputTab tableInputTab = new TableInputTab(page); page.setMessageReceiver(new TabWrapper()); page.databaseConnectionTab.addDatabaseConnectionToTable(databaseConnection1); page.databaseConnectionTab.addDatabaseConnectionToTable(databaseConnection2); tableInputTab.addTableInputToTable(tableInput1); tableInputTab.addTableInputToTable(tableInput2); tableInputTab.addTableInputToTable(tableInput3); tableInputTab.editForm.dbMap.put(databaseConnection1.getIdentifier(), databaseConnection1); tableInputTab.editForm.dbMap.put(databaseConnection2.getIdentifier(), databaseConnection2); tableInputTab.editForm.increaseDatabaseConnectionUsage(databaseConnection1.getIdentifier()); tableInputTab.editForm.increaseDatabaseConnectionUsage(databaseConnection2.getIdentifier()); tableInputTab.editForm.increaseDatabaseConnectionUsage(databaseConnection2.getIdentifier()); int rowCount = tableInputTab.tableInputList.getRowCount(); // Execute (delete Table Input 2) MethodCallback<Void > callback = tableInputTab.getDeleteCallback(tableInput2); callback.onSuccess(null, null); // Check assertEquals(rowCount - 1, tableInputTab.tableInputList.getRowCount()); assertEquals("table3", ((HTML) tableInputTab.tableInputList.getWidget(1, 1)).getText()); assertFalse(((Button) page.databaseConnectionTab.connectionInputList.getWidget(1, 5)).isEnabled()); // Execute (delete Table Input 1) callback = tableInputTab.getDeleteCallback(tableInput1); callback.onSuccess(null, null); // Check assertEquals(rowCount - 2, tableInputTab.tableInputList.getRowCount()); assertEquals("table3", ((HTML) tableInputTab.tableInputList.getWidget(0, 1)).getText()); assertTrue(((Button) page.databaseConnectionTab.connectionInputList.getWidget(0, 5)).isEnabled()); // Cleanup TestHelper.resetDatabaseSync(); } /** * Test method for {@link de.metanome.frontend.client.datasources.TableInputTab#updateTableInputInTable(TableInput updatedInput, TableInput oldInput)} */ public void testUpdateTableInput() { // Setup TestHelper.resetDatabaseSync(); DatabaseConnection databaseConnection1 = new DatabaseConnection(); databaseConnection1.setUrl("url"); databaseConnection1.setPassword("password"); databaseConnection1.setUsername("user"); databaseConnection1.setSystem(DbSystem.DB2); TableInput oldTableInput = new TableInput(); oldTableInput.setDatabaseConnection(databaseConnection1); oldTableInput.setTableName("table"); ArrayList<TableInput> inputs = new ArrayList<TableInput>(); inputs.add(oldTableInput); TableInputTab tableInputTab = new TableInputTab(new DataSourcePage(new BasePage())); tableInputTab.listTableInputs(inputs); // Expected Values String expectedValue = "updated"; DatabaseConnection databaseConnection2 = new DatabaseConnection(); databaseConnection2.setUrl(expectedValue); databaseConnection2.setPassword(expectedValue); databaseConnection2.setUsername(expectedValue); databaseConnection2.setSystem(DbSystem.DB2); TableInput updatedTableInput = new TableInput(); updatedTableInput.setDatabaseConnection(databaseConnection2); updatedTableInput.setTableName(expectedValue); updatedTableInput.setComment(expectedValue); // Execute tableInputTab.updateTableInputInTable(updatedTableInput, oldTableInput); // Check assertEquals(2, tableInputTab.tableInputList.getRowCount()); assertTrue(((HTML) (tableInputTab.tableInputList.getWidget(1, 0))).getText().contains(expectedValue)); assertTrue(tableInputTab.tableInputList.getText(1, 1).contains(expectedValue)); assertTrue(tableInputTab.tableInputList.getText(1, 2).contains(expectedValue)); // Clean up TestHelper.resetDatabaseSync(); } @Override public String getModuleName() { return "de.metanome.frontend.client.MetanomeTest"; } }
39.551724
152
0.771469
d501284ee0c0b42f07c9bb72af2804980fefadd5
681
package webapp.tier.util; import java.io.IOException; import com.hazelcast.client.HazelcastClient; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.core.HazelcastInstance; public class HazelcastInstanceConfigurator { private HazelcastInstanceConfigurator() { } public static HazelcastInstance getInstance() throws IOException { ClientConfig clientConfig = new ClientConfig(); clientConfig.getNetworkConfig().addAddress("hazelcast:5701"); clientConfig.getConnectionStrategyConfig().getConnectionRetryConfig() .setClusterConnectTimeoutMillis(1000) .setMaxBackoffMillis(2000); return HazelcastClient.newHazelcastClient(clientConfig); } }
29.608696
71
0.819383
4b23f1ce473fbcbbab8fe64429020dafb573a344
5,189
package com.davidalmarinho.main; import com.davidalmarinho.graphics.Window; import com.davidalmarinho.input.KeyboardInput; import com.davidalmarinho.input.MouseInput; import com.davidalmarinho.scenes.LevelEditorScene; import com.davidalmarinho.scenes.LevelScene; import com.davidalmarinho.scenes.Scene; import com.davidalmarinho.scenes.Scenes; import com.davidalmarinho.utils.Constants; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; public class GameManager extends Engine { // Graphics private final BufferedImage background; // Instance private static GameManager gameManager; // Components Window window; KeyboardInput keyboardInput; public MouseInput mouseInput; public Debugger debugger; // Scenes private Scene currentScene; // Using Singleton private GameManager() { background = new BufferedImage(Constants.WINDOW_WIDTH, Constants.WINDOW_HEIGHT, BufferedImage.TYPE_INT_RGB); window = Window.getInstance(mouseInput); mouseInput = MouseInput.getInstance(); keyboardInput = KeyboardInput.getInstance(); addListeners(window); debugger = Debugger.getInstance(); } private void addListeners(Window window) { window.addKeyListener(keyboardInput); window.addMouseListener(mouseInput); window.addMouseMotionListener(mouseInput); } /* We need here an init method, because sometimes, we want to access to the instance of gameManager if init() * method in the Scene's classes. So we only initialize the scenes after initializing GameManager */ @Override public void init() { changeScene(Scenes.LEVEL_SCENE); window.requestFocus(); } public void changeScene(Scenes scene) { switch (scene) { case LEVEL_SCENE: currentScene = new LevelScene(); currentScene.init(); System.out.println("Inside Level Scene"); break; case LEVEL_EDITOR_SCENE: currentScene = new LevelEditorScene(); currentScene.init(); System.out.println("Inside Level Editor Scene"); break; } } @Override public void update(float dt) { // Update SCALES to, when we resize the window we need the exact position of the mouse in the game background Constants.WINDOW_SCALE_X = (float) (window.getWidth() / (double) background.getWidth()); Constants.WINDOW_SCALE_Y = (float) (window.getHeight() / (double) background.getHeight()); currentScene.update(dt); if (keyboardInput.isKeyDown(KeyEvent.VK_F3)) { debugger.debugging = !debugger.debugging; } debugger.update(dt); keyboardInput.update(); mouseInput.update(); } public void draw(Graphics g) { renderOffScreen(g); debugger.draw(g); } public void renderOffScreen(Graphics g) { Graphics2D g2 = (Graphics2D) g; currentScene.render(g2); } @Override public void render() { /* BufferStrategies are a specie of screen workers. * What they do so? * Very simple, depending in how many BufferStrategies we create, they will create surrogate's images * that will be waiting to be rendered. * For example, we have created 3 buffer strategies. * * Queue images' list Image that is been rendering * * ________________ ________________ ________________ * | | | | | | * | IMAGE 3 | | IMAGE 2 | | IMAGE 1 | * | waiting to be | ----> | waiting to be | ----> | image that is | * | rendered | | rendered | | been rendering | * |________________| |________________| |________________| * * So, we need at least 1 BufferStrategy to render our game. */ BufferStrategy bs = window.getBufferStrategy(); // Check if we have BufferStrategies and only keep moving when we have created them if (bs == null) { window.createBufferStrategy(2); return; } Graphics g = background.getGraphics(); draw(g); g = bs.getDrawGraphics(); g.drawImage(background, 0, 0, window.getWidth(), window.getHeight(), null); bs.show(); } public Scene getCurrentScene() { return currentScene; } public KeyboardInput getKeyboardInput() { return keyboardInput; } /* Just get an instance of GameManager, because we just want a GameManager not 2 or 3, * and because it's easier to have access to all stuff. */ public static GameManager getInstance() { if (GameManager.gameManager == null) { GameManager.gameManager = new GameManager(); } return GameManager.gameManager; } }
34.593333
117
0.617653
954ff8d0f228afca7e8a13bdc9e972e1dcf09ad5
675
package scratch.kevin.ucerf3; import java.io.File; import java.io.IOException; import org.dom4j.DocumentException; import scratch.UCERF3.FaultSystemSolution; import scratch.UCERF3.utils.FaultSystemIO; public class SAFRupCount { public static void main(String[] args) throws IOException, DocumentException { int parentID = 301; FaultSystemSolution fss = FaultSystemIO.loadSol(new File( "/home/kevin/workspace/OpenSHA/dev/scratch/UCERF3/data/scratch/InversionSolutions/" + "2013_05_10-ucerf3p3-production-10runs_COMPOUND_SOL_FM3_1_MEAN_BRANCH_AVG_SOL.zip")); System.out.println("Count: "+fss.getRupSet().getRupturesForParentSection(parentID).size()); } }
30.681818
93
0.795556
229d83051b044b9cbe79a9532f03d4d85dc0aa57
2,513
package de.domisum.pingoxd; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLEncoder; public class VoteSender { // constants private static final String PINGO_VOTE_URL = "http://pingo.upb.de/vote"; // SENDING public String send(Vote vote) { StringBuilder data = new StringBuilder(); try { data.append(encodeKeyValue("utf8", "✓")).append("&"); data.append(encodeKeyValue("authenticity_token", vote.authenticityToken)).append("&"); for(String encodedOption : vote.getEncodedOptions()) data.append(encodeKeyValue("option"+(vote.multipleChoice ? "[]" : ""), encodedOption)).append("&"); data.append(encodeKeyValue("id", vote.id)).append("&"); data.append(encodeKeyValue("commit", "Vote!")); } catch(UnsupportedEncodingException e) { e.printStackTrace(); } try { URL url = new URL(PINGO_VOTE_URL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setRequestMethod("POST"); con.setConnectTimeout(500); con.setReadTimeout(500); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("Content-Length", String.valueOf(data.length())); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0"); con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); con.setRequestProperty("Accept-Encoding", "gzip, deflate"); /*con.setRequestProperty("Referer", "http://pingo.upb.de/"+vote.surveyId); con.setRequestProperty("Connection", "keep-alive"); con.setRequestProperty("Upgrade-Insecure-Requests", "1");*/ OutputStream os = con.getOutputStream(); os.write(data.toString().getBytes()); os.close(); int responseCode = con.getResponseCode(); if(responseCode != 200) return responseCode+" "+con.getResponseMessage(); } catch(java.io.IOException e) { if(e instanceof SocketTimeoutException) return "Timeout"; e.printStackTrace(); } return null; } private String encodeKeyValue(String key, String value) throws UnsupportedEncodingException { String keyEncoded = URLEncoder.encode(key, "UTF-8"); String valueEncoded = URLEncoder.encode(value, "UTF-8"); return keyEncoded+"="+valueEncoded; } }
29.916667
116
0.71349
2c58494d66e0a7cd7a4fe1f731032958aa90ffd2
3,413
/* * Copyright (c) 2016, Apptentive, Inc. All Rights Reserved. * Please refer to the LICENSE file for the terms and conditions * under which redistribution and use of this file is permitted. */ package com.apptentive.android.sdk.tests.module.engagement.criteria; import androidx.test.runner.AndroidJUnit4; import com.apptentive.android.sdk.Apptentive; import com.apptentive.android.sdk.module.engagement.interaction.model.InteractionCriteria; import com.apptentive.android.sdk.module.engagement.logic.FieldManager; import com.apptentive.android.sdk.storage.AppRelease; import com.apptentive.android.sdk.storage.Device; import com.apptentive.android.sdk.storage.EventData; import com.apptentive.android.sdk.storage.Person; import com.apptentive.android.sdk.storage.VersionHistory; import com.apptentive.android.sdk.tests.ApptentiveTestCaseBase; import org.json.JSONException; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import static org.junit.Assert.assertTrue; @RunWith(AndroidJUnit4.class) public class OperatorTests extends ApptentiveTestCaseBase { private static final String TEST_DATA_DIR = "engagement" + File.separator + "criteria" + File.separator; @Test public void exists() throws JSONException { doTest("testOperatorExists.json"); } @Test public void not() throws JSONException { doTest("testOperatorNot.json"); } @Test public void lessThan() throws JSONException { doTest("testOperatorLessThan.json"); } @Test public void lessThanOrEqual() throws JSONException { doTest("testOperatorLessThanOrEqual.json"); } @Test public void greaterThanOrEqual() throws JSONException { doTest("testOperatorGreaterThanOrEqual.json"); } @Test public void greaterThan() throws JSONException { doTest("testOperatorGreaterThan.json"); } @Test public void stringEquals() throws JSONException { doTest("testOperatorStringEquals.json"); } @Test public void stringNotEquals() throws JSONException { doTest("testOperatorStringNotEquals.json"); } @Test public void contains() throws JSONException { doTest("testOperatorContains.json"); } @Test public void startsWith() throws JSONException { doTest("testOperatorStartsWith.json"); } @Test public void endsWith() throws JSONException { doTest("testOperatorEndsWith.json"); } @Test public void before() throws JSONException { doTest("testOperatorBefore.json"); } @Test public void after() throws JSONException { doTest("testOperatorAfter.json"); } private void doTest(String testFile) throws JSONException { String json = loadTextAssetAsString(TEST_DATA_DIR + testFile); InteractionCriteria criteria = new InteractionCriteria(json); Device device = new Device(); FieldManager fieldManager = new FieldManager(targetContext, new VersionHistory(), new EventData(), new Person(), device, new AppRelease()); Apptentive.DateTime dateTime = new Apptentive.DateTime(1000d); Apptentive.Version version = new Apptentive.Version(); version.setVersion("1.2.3"); device.getCustomData().put("number_5", 5); device.getCustomData().put("string_qwerty", "qwerty"); device.getCustomData().put("boolean_true", true); device.getCustomData().put("key_with_null_value", (String) null); device.getCustomData().put("datetime_1000", dateTime); device.getCustomData().put("version_1.2.3", version); assertTrue(criteria.isMet(fieldManager)); } }
28.206612
141
0.770876
3db278a901f1c227f125fd1f28f3eae2d1fffe1a
2,517
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.mklinger.micro.strings; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; import de.mklinger.micro.strings.ThrowsException.ThrowingRunnable; /** * Hamcrest matcher that executes a runnable and expects it to throw a given * exception type. * * @author Marc Klinger - mklinger[at]mklinger[dot]de */ public class ThrowsException extends TypeSafeMatcher<ThrowingRunnable> { @FunctionalInterface public interface ThrowingRunnable { void run() throws Exception; } private final Class<? extends Throwable> expectedExceptionType; private Throwable actualException; public ThrowsException(final Class<? extends Throwable> expectedExceptionType) { this.expectedExceptionType = expectedExceptionType; } public static ThrowsException throwsException(final Class<? extends Throwable> expectedExceptionType) { return new ThrowsException(expectedExceptionType); } @Override public void describeTo(final Description description) { description.appendText("Exception of type " + expectedExceptionType.getName() + " to be thrown"); } @Override protected void describeMismatchSafely(final ThrowingRunnable item, final Description mismatchDescription) { if (actualException == null) { mismatchDescription.appendText("no exception was thrown"); } else { mismatchDescription.appendText("was exception of type " + actualException.getClass().getName() + " was thrown"); } } @Override protected boolean matchesSafely(final ThrowingRunnable r) { try { r.run(); actualException = null; } catch (final Throwable e) { actualException = e; if (expectedExceptionType.isAssignableFrom(e.getClass())) { return true; } } return false; } }
33.56
115
0.762813
8bfd8eb5cd307d8441546cc7824f281efc5103d6
2,982
/* $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.etch.util.core.xml; import java.util.Map; /** * Description of StringBufWithEscape. */ public class StringBufWithEscape extends PlainStringBuf { /** * Constructs the StringBufWithEscape. * * @param descr * @param maxLen * @param maxEscapeLen * @param escapes */ public StringBufWithEscape( String descr, int maxLen, int maxEscapeLen, Map<String,Character> escapes ) { super( descr, maxLen ); this.maxEscapeLen = maxEscapeLen; this.escapes = escapes; } private final int maxEscapeLen; private final Map<String,Character> escapes; @Override public void append( char c ) { if (c == '&') { if (escapeBuffer != null) throw new UnsupportedOperationException( "bad char '"+c+"' in escape" ); escapeBuffer = new PlainStringBuf( "escape", maxEscapeLen ); } else if (escapeBuffer != null) { if (c == ';') { String s = escapeBuffer.toString(); escapeBuffer = null; super.append( parseEscape( s ) ); } else { escapeBuffer.append( c ); } } else { super.append( c ); } } private char parseEscape( String s ) { if (s.length() == 0) throw new UnsupportedOperationException( "empty escape" ); if (s.startsWith( "#" )) { try { int k = Integer.parseInt( s.substring( 1 ) ); if (k < 0 || k > 65535) throw new UnsupportedOperationException( "numeric escape out of range '"+s+"'" ); return (char) k; } catch ( NumberFormatException e ) { throw new UnsupportedOperationException( "bad numeric escape '"+s+"'" ); } } Character c = escapes.get( s ); if (c != null) return c.charValue(); c = escapes.get( s.toLowerCase() ); if (c != null) return c.charValue(); throw new UnsupportedOperationException( "unknown entity escape '"+s+"'" ); } @Override public int length() { int n = super.length(); if (escapeBuffer != null) return n+1; return n; } @Override public String toString() { if (escapeBuffer != null) throw new UnsupportedOperationException( "unfinished escape" ); return super.toString(); } private PlainStringBuf escapeBuffer; }
22.421053
86
0.663313
2745a13309a391fe41df4eab88af5e921e872226
985
package org.dspace.xmlworkflow.cristin; /** * Entity class to represent a bitstream being retrieved from Cristin */ public class CristinBitstream { private String url; private String name; private int order = -1; private String md5; private String mimetype; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } public String getMd5() { return md5; } public void setMd5(String md5) { this.md5 = md5; } public String getMimetype() { return mimetype; } public void setMimetype(String mimetype) { this.mimetype = mimetype; } }
15.390625
69
0.564467
3bbae6b9a0100d22d7dbeb2b214c953e6197bb6c
1,541
package modelo; import org.json.JSONException; import org.json.JSONObject; public class UsuarioFacebook { private Long id; private String email; private String first_name; private String last_name; private String picture; public UsuarioFacebook(JSONObject jsonUsuario) throws JSONException{ String[] fields = JSONObject.getNames(jsonUsuario); for (String field : fields) { if (field.equals("id")) { id = jsonUsuario.getLong("id"); continue; } if (field.equals("picture")) { picture = jsonUsuario.getString("picture"); continue; } if (field.equals("email")) { email = jsonUsuario.getString("email"); continue; } if (field.equals("first_name")) { first_name = jsonUsuario.getString("first_name"); continue; } if (field.equals("last_name")) { last_name = jsonUsuario.getString("last_name"); continue; } } } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } }
14.961165
69
0.663206
2ee13757f013eb2ce3475ab1d7b5164b3e67d397
241
package betterwithaddons.entity; public interface IHasSpirits { int getSpirits(); void setSpirits(int n); default boolean canAbsorbSpirits() { return false; }; default int absorbSpirits(int n) { return n; } }
17.214286
57
0.66805
eb5b72cc73cd23dfc4b98dc402ec981fcfe861eb
1,244
package me.jingbin.byrecyclerview.utils; import android.util.Log; public final class LogHelper { private static volatile boolean DEBUG = true; public static String logTag = "jingbin"; private LogHelper() { } /** * 打开Log * */ public static void enableLogging() { DEBUG = true; } /** * 关闭Log * * @author mslan * @date 2015年3月1日 下午5:14:50 */ public static void disableLogging() { DEBUG = false; } public static void v(String tag, String message) { if (DEBUG) { Log.v(tag, message); } } public static void d(String tag, String message) { if (DEBUG) { Log.d(tag, message); } } public static void i(String tag, String message) { if (DEBUG) { Log.i(tag, message); } } public static void w(String tag, String message) { if (DEBUG) { Log.w(tag, message); } } public static void e(String tag, String message) { if (DEBUG) { Log.e(tag, message); } } public static void e(String message) { if (DEBUG) { Log.e(logTag, message); } } }
18.848485
54
0.512058
5fee9778e464ccff8ea13ff8d195a55647fbfd17
258
package in.infocruise.techsupport.helper; import android.os.AsyncTask; public class DbAsyncTask extends AsyncTask<Void,Void,Void> { private SQLiteHandler db; @Override protected Void doInBackground(Void... voids) { return null; } }
21.5
60
0.72093
5e7b3e750f3e178a80198abaa8392879e28667e8
3,800
/*- * #%L * Nazgul Project: nazgul-tools-visualization-spi-doclet * %% * Copyright (C) 2010 - 2018 jGuru Europe AB * %% * Licensed under the jGuru Europe AB license (the "License"), based * on Apache License, Version 2.0; you may not use this file except * in compliance with the License. * * You may obtain a copy of the License at * * http://www.jguru.se/licenses/jguruCorporateSourceLicense-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package se.jguru.nazgul.tools.visualization.spi.doclet; import com.sun.javadoc.DocErrorReporter; import com.sun.javadoc.LanguageVersion; import com.sun.javadoc.RootDoc; /** * The Doclet specification within * Specification of a SimpleDoclet, implemented by classes which can be used as JavaDoc Doclet implementations. * * @author <a href="mailto:lj@jguru.se">Lennart J&ouml;relid</a>, jGuru Europe AB */ public interface SimpleDoclet { /** * A constant containing the value returned by a {@link SimpleDoclet} implementation when an option is unknown. */ int UNKNOWN_OPTION = 0; /** * Doclet start of execution. * * @param root A non-null {@link RootDoc} that represents the root of the program structure information * for one run of javadoc. Enables extracting all other program structure information data. * @return true if the start completed OK. */ boolean start(final RootDoc root); /** * <p>Validates the supplied javadoc options against this SimpleDoclet. * Each array contains the option as the first element in the array and its arguments as any following elements. * For example, given the command:</p> * <p> * <pre><code>javadoc -foo this that -bar other ...</code></pre> * <p>the RootDoc.options method will return</p> * * <pre> * <code> * options()[0][0] = "-foo" * options()[0][1] = "this" * options()[0][2] = "that" * options()[1][0] = "-bar" * options()[1][1] = "other" * </code> * </pre> * <p> * * @param options the spliced JavaDoc options provided to the javadoc command. * @param errorReporter The JavaDoc error reporter * @return {@code true} if the options were valid, and {@code false} otherwise. */ boolean validateJavaDocOptions(final String[][] options, final DocErrorReporter errorReporter); /** * <p>Any doclet that uses custom options must have a method called optionLength(String option) that returns an * int. For each custom option that you want your doclet to recognize, optionLength must return the number of * separate pieces or tokens in the option.</p> * <p>For example, the custom option {@code -foo bar} has 2 pieces, the -tag option itself and its value. * Hence, this optionLength method must return 2 for the {@code -foo} option.</p> * * @param option A javadoc option. * @return The length of the supplied option, including the option itself, or {@link #UNKNOWN_OPTION} for * unrecognized options. * @see DelegatingDoclet#optionLength(String) */ int optionLength(String option); /** * Retrieves the LanguageVersion of this {@link SimpleDoclet} instance. * Should normally be {@link LanguageVersion#JAVA_1_5}. * * @return the LanguageVersion of this {@link SimpleDoclet} instance. */ default LanguageVersion languageVersion() { return LanguageVersion.JAVA_1_5; } }
37.623762
116
0.672105
cf173d886c84bf0c00c28e65cf3dd2438e49aff1
4,202
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: http://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * http://plantuml.com/patreon (only 1$ per month!) * http://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 gen.lib.common; import static smetana.core.debug.SmetanaDebug.ENTERING; import static smetana.core.debug.SmetanaDebug.LEAVING; import gen.annotation.Original; import gen.annotation.Unused; import h.ST_GVC_s; import h.ST_dt_s; import h.ST_pointf; import h.ST_textspan_t; public class textspan__c { //3 n8tcl06mifdn779rzenam44z // pointf textspan_size(GVC_t *gvc, textspan_t * span) @Unused @Original(version="2.38.0", path="lib/common/textspan.c", name="textspan_size", key="n8tcl06mifdn779rzenam44z", definition="pointf textspan_size(GVC_t *gvc, textspan_t * span)") public static ST_pointf textspan_size(ST_GVC_s gvc, ST_textspan_t span) { // WARNING!! STRUCT return textspan_size_w_(gvc, span).copy(); } private static ST_pointf textspan_size_w_(ST_GVC_s gvc, ST_textspan_t span) { ENTERING("n8tcl06mifdn779rzenam44z","textspan_size"); try { System.err.println("Warning:textspan_size "+span); span.size.x = 30; span.size.y = 20; return span.size.copy(); } finally { LEAVING("n8tcl06mifdn779rzenam44z","textspan_size"); } } //3 9mfrgcpzz2d9f7nxfgx4nxj2q // Dt_t * textfont_dict_open(GVC_t *gvc) @Unused @Original(version="2.38.0", path="lib/common/textspan.c", name="textfont_dict_open", key="9mfrgcpzz2d9f7nxfgx4nxj2q", definition="Dt_t * textfont_dict_open(GVC_t *gvc)") public static ST_dt_s textfont_dict_open(ST_GVC_s gvc) { ENTERING("9mfrgcpzz2d9f7nxfgx4nxj2q","textfont_dict_open"); try { return null; //UNSUPPORTED("nexd6tbei8przmonjwzag8uf"); // Dt_t * textfont_dict_open(GVC_t *gvc) //UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // { //UNSUPPORTED("cdeb412fjgrtibum4qt0yxhc7"); // ( (&(gvc->textfont_disc))->key = (0), (&(gvc->textfont_disc))->size = (sizeof(textfont_t)), (&(gvc->textfont_disc))->link = (-1), (&(gvc->textfont_disc))->makef = (textfont_makef), (&(gvc->textfont_disc))->freef = (textfont_freef), (&(gvc->textfont_disc))->comparf = (textfont_comparf), (&(gvc->textfont_disc))->hashf = (NULL), (&(gvc->textfont_disc))->memoryf = (NULL), (&(gvc->textfont_disc))->eventf = (NULL) ); //UNSUPPORTED("d1t3xr23spgfbbggquvg4nodm"); // gvc->textfont_dt = dtopen(&(gvc->textfont_disc), Dtoset); //UNSUPPORTED("6ynzkfpi9sy9wbln45o4jajhp"); // return gvc->textfont_dt; //UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // } } finally { LEAVING("9mfrgcpzz2d9f7nxfgx4nxj2q","textfont_dict_open"); } } }
40.796117
465
0.686102
e9c32315f3398fb5482f2701d6a1cdca1a80c4a2
682
package jprobe.services.function; /** * This interface defines {@link Argument} observers. It declares one method, {@link #update(Argument, boolean)}, * which is called by observed Arguments to report changes in their validity. * * @author Tristan Bepler * * @see Argument * @see Argument#isValid() * */ public interface ArgumentListener { /** * This method is used to report changes in the validity of observed {@link Argument}s. * It is called by those Arguments. * @param arg - Argument object reporting changes * @param valid - new validity state * @see Argument * @see Argument#isValid() */ public void update(Argument<?> arg, boolean valid); }
26.230769
113
0.703812
8391abf97093eb0a92a19b69b49f2c0a1ef65438
2,741
/* * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 2.0, as published by the * Free Software Foundation. * * This program is also distributed with certain software (including but not * limited to OpenSSL) that is licensed under separate terms, as designated in a * particular file or component or in included license documentation. The * authors of MySQL hereby grant you an additional permission to link the * program and your derivative works with the separately licensed software that * they have included with MySQL. * * Without limiting anything contained in the foregoing, this file, which is * part of MySQL Connector/J, is also subject to the Universal FOSS Exception, * version 1.0, a copy of which can be found at * http://oss.oracle.com/licenses/universal-foss-exception. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, * for more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.mysql.cj.protocol.a; import static org.junit.jupiter.api.Assertions.assertEquals; import com.mysql.cj.protocol.MessageSender; /** * Common functionality for packet sender tests. */ public class PacketSenderTestBase { /** * Get a no-op packet sender that can be used when testing decorators. * * @return a MessageSender */ protected MessageSender<NativePacketPayload> getNoopPacketSender() { return new MessageSender<NativePacketPayload>() { public void send(byte[] packet, int packetLen, byte packetSequence) throws java.io.IOException { // no-op } @Override public MessageSender<NativePacketPayload> undecorateAll() { return this; } @Override public MessageSender<NativePacketPayload> undecorate() { return this; } }; } protected void fillPacketSequentially(byte[] packet) { for (int i = 0; i < packet.length; ++i) { packet[i] = (byte) i; } } protected void checkSequentiallyFilledPacket(byte[] packet, int offset, int len) { for (int i = 0; i < len; ++i) { assertEquals((byte) i, packet[offset + i]); } } }
36.546667
108
0.679314
ccaf00256d39460a5109c0b2d8daf74d2715bdcd
8,345
package com.github.songxzj.wxpay.v3.bean.result.combine; import com.github.songxzj.wxpay.v3.bean.result.BaseWxPayV3Result; import com.google.gson.annotations.SerializedName; import lombok.*; import java.io.Serializable; import java.util.List; /** * 通用如下: * 支付通知(https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter5_1_13.shtml) */ @Setter @Getter @ToString @EqualsAndHashCode(callSuper = true) @NoArgsConstructor public class WxCombineTransactionsStateResult extends BaseWxPayV3Result { private static final long serialVersionUID = 8106926247257904392L; /** * 合单商户appid * combine_appid * string[1,32] * 是 */ @SerializedName("combine_appid") private String combineAppid; /** * 合单商户号 * combine_mchid * string[1,32] * 是 */ @SerializedName("combine_mchid") private String combineMchid; /** * 合单商户订单号 * combine_out_trade_no * string[1,32] * 是 */ @SerializedName("combine_out_trade_no") private String combineOutTradeNo; /** * 场景信息 * scene_info * object * 否 */ @SerializedName("scene_info") private SceneInfo sceneInfo; /** * 子单信息 * sub_orders * array * 是 */ @SerializedName("sub_orders") private List<SubOrder> subOrders; /** * 支付者 * combine_payer_info * object * 否 */ @SerializedName("combine_payer_info") private CombinePayerInfo combinePayerInfo; /** * 场景信息 */ @Setter @Getter @ToString @NoArgsConstructor public static class SceneInfo implements Serializable { private static final long serialVersionUID = 7573674519776180059L; /** * 商户端设备号 * device_id * string[7,16] * 否 */ @SerializedName("device_id") private String deviceId; } /** * 子单信息 */ @Setter @Getter @ToString @NoArgsConstructor public static class SubOrder implements Serializable { private static final long serialVersionUID = 9213074386247061216L; /** * 子单商户号 * mchid * string[1,32] * 是 */ @SerializedName("mchid") private String mchid; /** * 交易类型 * trade_type * string[1,16] * 否 */ @SerializedName("trade_type") private String tradeType; /** * 交易状态 * trade_state * string[1,32] * 是 */ @SerializedName("trade_state") private String tradeState; /** * 付款银行 * bank_type * string[1,16] * 否 */ @SerializedName("bank_type") private String bankType; /** * 附加数据 * attach * string[1,128] * 否 */ @SerializedName("attach") private String attach; /** * 支付完成时间 * success_time * string[1,64] * 否 */ @SerializedName("success_time") private String successTime; /** * 微信支付订单号 * transaction_id * string[1,32] * 否 */ @SerializedName("transaction_id") private String transactionId; /** * 子单商户订单号 * out_trade_no * string[6,32] * 是 */ @SerializedName("out_trade_no") private String outTradeNo; /** * 优惠功能 * promotion_detail * array * 否 */ @SerializedName("promotion_detail") private List<PromotionDetail> promotionDetails; /** * 订单金额 * amount * object * 是 */ @SerializedName("amount") private Amount amount; } @Setter @Getter @ToString @NoArgsConstructor public static class PromotionDetail implements Serializable { private static final long serialVersionUID = 4013913476398824714L; /** * 券ID * coupon_id * string[1,32] * 是 */ @SerializedName("coupon_id") private String couponId; /** * 优惠名称 * name * string[1,64] * 否 */ @SerializedName("name") private String name; /** * 优惠范围 * scope * string[1,32] * 否 */ @SerializedName("scope") private String scope; /** * 优惠类型 * type * string[1,32] * 否 */ @SerializedName("type") private String type; /** * 优惠券面额 * amount * int * 是 */ @SerializedName("amount") private Integer amount; /** * 活动ID * stock_id * string[1,32] * 否 */ @SerializedName("stock_id") private String stockId; /** * 微信出资 * wechatpay_contribute * int * 否 */ @SerializedName("wechatpay_contribute") private Integer wechatpayContribute; /** * 商户出资 * merchant_contribute * int * 否 */ @SerializedName("merchant_contribute") private Integer merchantContribute; /** * 其他出资 * other_contribute * int * 否 */ @SerializedName("other_contribute") private Integer otherContribute; /** * 优惠币种 * currency * string[1,16] * 否 */ @SerializedName("currency") private String currency; /** * 单品列表 * goods_detail * array * 否 */ @SerializedName("goods_detail") private List<GoodsDetail> goodsDetails; } /** * 单品列表 */ @Setter @Getter @ToString @NoArgsConstructor public static class GoodsDetail implements Serializable { private static final long serialVersionUID = 5710961998130352574L; /** * 商品编码 * goods_id * string[1,32] * 是 */ @SerializedName("goods_id") private String goodsId; /** * 商品数量 * quantity * int * 是 */ @SerializedName("quantity") private Integer quantity; /** * 商品单价 * unit_price * int * 是 */ @SerializedName("unit_price") private Integer unitPrice; /** * 商品优惠金额 * discount_amount * int * 是 */ @SerializedName("discount_amount") private Integer discountAmount; /** * 商品备注 * goods_remark * string[1,128] * 否 */ @SerializedName("goods_remark") private String goodsRemark; } /** * 订单金额 */ @Setter @Getter @ToString @NoArgsConstructor public static class Amount implements Serializable { private static final long serialVersionUID = 6412751184390720459L; /** * 标价金额 * total_amount * int64 * 是 */ @SerializedName("total_amount") private Integer totalAmount; /** * 标价币种 * currency * string[1,8] * 否 */ @SerializedName("currency") private String currency; /** * 现金支付金额 * payer_amount * int64 * 是 */ @SerializedName("payer_amount") private Integer payerAmount; /** * 现金支付币种 * payer_currency * string[1,8] * 否 */ @SerializedName("payer_currency") private String payerCurrency; } /** * 支付者 */ @Setter @Getter @ToString @NoArgsConstructor public static class CombinePayerInfo implements Serializable { private static final long serialVersionUID = -1514375948726783878L; /** * 用户标识 * openid * string[1,128] * 是 */ @SerializedName("openid") private String openid; } }
19.543326
75
0.492031
08a5ac719d84ff58d4701e73f49a610bcce7268f
7,662
/* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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.dexscript.intellij.editor; import com.dexscript.psi.*; import com.dexscript.parser.GoTypes; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.lang.parameterInfo.*; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Set; public class GoParameterInfoHandler implements ParameterInfoHandlerWithTabActionSupport<GoArgumentList, Object, GoExpression> { @NotNull @Override public GoExpression[] getActualParameters(@NotNull GoArgumentList o) { return ArrayUtil.toObjectArray(o.getExpressionList(), GoExpression.class); } @NotNull @Override public IElementType getActualParameterDelimiterType() { return GoTypes.COMMA; } @NotNull @Override public IElementType getActualParametersRBraceType() { return GoTypes.RPAREN; } @NotNull @Override public Set<Class> getArgumentListAllowedParentClasses() { return ContainerUtil.newHashSet(); } @NotNull @Override public Set<Class> getArgListStopSearchClasses() { return ContainerUtil.newHashSet(); } @NotNull @Override public Class<GoArgumentList> getArgumentListClass() { return GoArgumentList.class; } @Override public boolean couldShowInLookup() { return true; } @Nullable @Override public Object[] getParametersForLookup(LookupElement item, ParameterInfoContext context) { return ArrayUtil.EMPTY_OBJECT_ARRAY; } @Nullable @Override public Object[] getParametersForDocumentation(Object p, ParameterInfoContext context) { return ArrayUtil.EMPTY_OBJECT_ARRAY; } @Nullable @Override public GoArgumentList findElementForParameterInfo(@NotNull CreateParameterInfoContext context) { // todo: see ParameterInfoUtils.findArgumentList return getList(context); } @Nullable private static GoArgumentList getList(@NotNull ParameterInfoContext context) { PsiElement at = context.getFile().findElementAt(context.getOffset()); return PsiTreeUtil.getParentOfType(at, GoArgumentList.class); } @Override public void showParameterInfo(@NotNull GoArgumentList argList, @NotNull CreateParameterInfoContext context) { PsiElement parent = argList.getParent(); if (!(parent instanceof GoCallExpr)) return; GoFunctionType type = findFunctionType(((GoCallExpr)parent).getExpression().getGoType(null)); if (type != null) { context.setItemsToShow(new Object[]{type}); context.showHint(argList, argList.getTextRange().getStartOffset(), this); } } @Nullable private static GoFunctionType findFunctionType(@Nullable GoType type) { if (type instanceof GoFunctionType || type == null) return (GoFunctionType)type; GoType base = type.getUnderlyingType(); return base instanceof GoFunctionType ? (GoFunctionType)base : null; } @Nullable @Override public GoArgumentList findElementForUpdatingParameterInfo(@NotNull UpdateParameterInfoContext context) { return getList(context); } @Override public void updateParameterInfo(@NotNull GoArgumentList list, @NotNull UpdateParameterInfoContext context) { context.setCurrentParameter(ParameterInfoUtils.getCurrentParameterIndex(list.getNode(), context.getOffset(), GoTypes.COMMA)); } @Nullable @Override public String getParameterCloseChars() { return ",("; } @Override public boolean tracksParameterIndex() { return true; } @Override public void updateUI(@Nullable Object p, @NotNull ParameterInfoUIContext context) { updatePresentation(p, context); } static String updatePresentation(@Nullable Object p, @NotNull ParameterInfoUIContext context) { if (p == null) { context.setUIComponentEnabled(false); return null; } GoSignature signature = p instanceof GoSignatureOwner ? ((GoSignatureOwner)p).getSignature() : null; if (signature == null) return null; GoParameters parameters = signature.getParameters(); List<String> parametersPresentations = getParameterPresentations(parameters, PsiElement::getText); StringBuilder builder = new StringBuilder(); int start = 0; int end = 0; if (!parametersPresentations.isEmpty()) { // Figure out what particular presentation is actually selected. Take in // account possibility of the last variadic parameter. int selected = isLastParameterVariadic(parameters.getParameterDeclarationList()) ? Math.min(context.getCurrentParameterIndex(), parametersPresentations.size() - 1) : context.getCurrentParameterIndex(); for (int i = 0; i < parametersPresentations.size(); ++i) { if (i != 0) { builder.append(", "); } if (i == selected) { start = builder.length(); } builder.append(parametersPresentations.get(i)); if (i == selected) { end = builder.length(); } } } else { builder.append(CodeInsightBundle.message("parameter.info.no.parameters")); } return context.setupUIComponentPresentation(builder.toString(), start, end, false, false, false, context.getDefaultParameterColor()); } /** * Creates a list of parameter presentations. For clarity we expand parameters declared as `a, b, c int` into `a int, b int, c int`. */ @NotNull public static List<String> getParameterPresentations(@NotNull GoParameters parameters, @NotNull Function<PsiElement, String> typePresentationFunction) { List<GoParameterDeclaration> paramDeclarations = parameters.getParameterDeclarationList(); List<String> paramPresentations = ContainerUtil.newArrayListWithCapacity(2 * paramDeclarations.size()); for (GoParameterDeclaration paramDeclaration : paramDeclarations) { boolean isVariadic = paramDeclaration.isVariadic(); List<GoParamDefinition> paramDefinitionList = paramDeclaration.getParamDefinitionList(); for (GoParamDefinition paramDefinition : paramDefinitionList) { String separator = isVariadic ? " ..." : " "; paramPresentations.add(paramDefinition.getText() + separator + typePresentationFunction.fun(paramDeclaration.getType())); } if (paramDefinitionList.isEmpty()) { String separator = isVariadic ? "..." : ""; paramPresentations.add(separator + typePresentationFunction.fun(paramDeclaration.getType())); } } return paramPresentations; } private static boolean isLastParameterVariadic(@NotNull List<GoParameterDeclaration> declarations) { GoParameterDeclaration lastItem = ContainerUtil.getLastItem(declarations); return lastItem != null && lastItem.isVariadic(); } }
35.472222
137
0.729705
b4ec9b306b36da5780ccc8d4d3d260e139d71b4d
15,988
/* * Copyright 2019 Andy Turner, University of Leeds. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.ac.leeds.ccg.v2d.geometry.envelope; import ch.obermuhlner.math.big.BigRational; import uk.ac.leeds.ccg.v2d.geometry.V2D_Point; import java.io.IOException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import uk.ac.leeds.ccg.generic.core.Generic_Environment; import uk.ac.leeds.ccg.generic.io.Generic_Defaults; import uk.ac.leeds.ccg.v2d.core.V2D_Environment; import uk.ac.leeds.ccg.v2d.geometry.V2D_LineSegment; import uk.ac.leeds.ccg.v2d.geometry.V2D_Point; import uk.ac.leeds.ccg.v2d.geometry.envelope.V2D_Envelope; /** * * @author geoagdt */ public class V2D_EnvelopeTest { V2D_Environment env; public V2D_EnvelopeTest() { } @BeforeAll public static void setUpClass() { } @AfterAll public static void tearDownClass() { } @BeforeEach public void setUp() { } @AfterEach public void tearDown() { } /** * A master controller for all tests. */ @Test public void testAll() { //testIsIntersectedBy(); //testToString(); //testUnion(); //testIsIntersectedBy_V2D_Envelope(); //testIsContainedBy(); //testIsIntersectedBy_V2D_Point(); //testIsIntersectedBy_V2D_Point(); //testIsIntersectedBy_BigRational_BigRational(); //testIsIntersectedBy_V2D_LineSegment(); //testGetIntersection(); //testGetEnvelope(); //testEquals(); //testGetxMin(); //testGetxMax(); //testGetyMin(); //testGetyMax(); } /** * Test of toString method, of class V2D_Envelope. */ @Test public void testToString() { System.out.println("toString"); V2D_Envelope instance = new V2D_Envelope(BigRational.ZERO, BigRational.ONE, BigRational.ZERO, BigRational.ONE);; String expResult = "V2D_Envelope(xMin=0, xMax=1, yMin=0, yMax=1)"; String result = instance.toString(); Assertions.assertEquals(expResult, result); } /** * Test of union method, of class V2D_Envelope. */ @Test public void testUnion() { System.out.println("union"); BigRational x0 = BigRational.ZERO; BigRational x1 = BigRational.ONE; BigRational x2 = BigRational.TWO; BigRational x3 = BigRational.valueOf(3); BigRational y0 = BigRational.ZERO; BigRational y1 = BigRational.ONE; BigRational y2 = BigRational.TWO; BigRational y3 = BigRational.valueOf(3); V2D_Envelope e = new V2D_Envelope(x1, x2, y1, y2); V2D_Envelope instance = new V2D_Envelope(x1, x2, y1, y2); V2D_Envelope expResult = new V2D_Envelope(x1, x2, y1, y2); V2D_Envelope result = instance.union(e); Assertions.assertEquals(expResult, result); // Test 2 e = new V2D_Envelope(x1, x2, y1, y2); instance = new V2D_Envelope(x0, x1, y1, y2); expResult = new V2D_Envelope(x0, x2, y1, y2); result = instance.union(e); Assertions.assertEquals(expResult, result); } /** * Test of isIntersectedBy method, of class V2D_Envelope. */ @Test public void testIsIntersectedBy_V2D_Envelope() { System.out.println("isIntersectedBy"); BigRational x0 = BigRational.ZERO; BigRational x1 = BigRational.ONE; BigRational x2 = BigRational.TWO; BigRational x3 = BigRational.valueOf(3); BigRational y0 = BigRational.ZERO; BigRational y1 = BigRational.ONE; BigRational y2 = BigRational.TWO; BigRational y3 = BigRational.valueOf(3); V2D_Envelope e = new V2D_Envelope(x1, x2, y1, y2); V2D_Envelope instance = new V2D_Envelope(x1, x2, y1, y2); boolean result = instance.isIntersectedBy(e); Assertions.assertTrue(result); // Test 2 e = new V2D_Envelope(x0, x1, y0, y1); instance = new V2D_Envelope(x1, x2, y1, y2); result = instance.isIntersectedBy(e); Assertions.assertTrue(result); // Test 3 e = new V2D_Envelope(x0, x1, y0, y1); instance = new V2D_Envelope(x2, x3, y2, y3); result = instance.isIntersectedBy(e); Assertions.assertFalse(result); System.out.println("isIntersectedBy"); // Test 4 boolean expResult; BigRational ONE = BigRational.ONE; BigRational TEN = BigRational.TEN; V2D_Point a; V2D_Point b = new V2D_Point(ONE, ONE); V2D_Envelope be = b.getEnvelope(); V2D_Envelope abe; BigRational aX = ONE; BigRational aY = ONE; // Test 1 for (int i = 0; i < 1000; i++) { aX = aX.divide(TEN); aY = aY.divide(TEN); a = new V2D_Point(aX, aY); //System.out.println("a " + a.toString()); abe = new V2D_Envelope(a, b); //System.out.println("abe " + abe.toString()); expResult = true; result = abe.isIntersectedBy(a.getEnvelope()); //System.out.println("abe.IsIntersectedBy(a.getEnvelope()) " + result); Assertions.assertEquals(expResult, result); result = abe.isIntersectedBy(be); //System.out.println("be " + be.toString()); //System.out.println("abe.IsIntersectedBy(be) " + result); Assertions.assertEquals(expResult, result); } } /** * Test of isContainedBy method, of class V2D_Envelope. */ @Test public void testIsContainedBy() { System.out.println("isContainedBy"); BigRational x0 = BigRational.ZERO; BigRational x1 = BigRational.ONE; BigRational x2 = BigRational.TWO; BigRational x3 = BigRational.valueOf(3); BigRational y0 = BigRational.ZERO; BigRational y1 = BigRational.ONE; BigRational y2 = BigRational.TWO; BigRational y3 = BigRational.valueOf(3); V2D_Envelope e = new V2D_Envelope(x0, x3, y0, y3); V2D_Envelope instance = new V2D_Envelope(x1, x2, y1, y2); boolean result = instance.isContainedBy(e); Assertions.assertTrue(result); // Test 2 e = new V2D_Envelope(x1, x2, y1, y2); instance = new V2D_Envelope(x0, x3, y0, y3); result = instance.isContainedBy(e); Assertions.assertFalse(result); // Test 3 e = new V2D_Envelope(x0, x3, y0, y3); instance = new V2D_Envelope(x1, x2, y1, BigRational.valueOf(4)); result = instance.isContainedBy(e); Assertions.assertFalse(result); } /** * Test of isIntersectedBy method, of class V2D_Envelope. */ @Test public void testIsIntersectedBy_V2D_Point() { System.out.println("isIntersectedBy"); BigRational x0 = BigRational.ZERO; BigRational x1 = BigRational.ONE; BigRational x2 = BigRational.TWO; BigRational x3 = BigRational.valueOf(3); BigRational y0 = BigRational.ZERO; BigRational y1 = BigRational.ONE; BigRational y2 = BigRational.TWO; BigRational y3 = BigRational.valueOf(3); V2D_Point p = new V2D_Point(x0, y0); V2D_Envelope instance = new V2D_Envelope(x0, x1, y0, y1); Assertions.assertTrue(instance.isIntersectedBy(p)); // Test 2 p = new V2D_Point(x1, y0); Assertions.assertTrue(instance.isIntersectedBy(p)); // Test 3 p = new V2D_Point(x0, y1); Assertions.assertTrue(instance.isIntersectedBy(p)); // Test 3 p = new V2D_Point(x1, y1); Assertions.assertTrue(instance.isIntersectedBy(p)); // Test 4 p = new V2D_Point(x3, y1); Assertions.assertFalse(instance.isIntersectedBy(p)); } /** * Test of isIntersectedBy method, of class V2D_Envelope. */ @Test public void testIsIntersectedBy_BigRational_BigRational() { System.out.println("isIntersectedBy"); BigRational x0 = BigRational.ZERO; BigRational x1 = BigRational.ONE; BigRational x2 = BigRational.TWO; BigRational x3 = BigRational.valueOf(3); BigRational y0 = BigRational.ZERO; BigRational y1 = BigRational.ONE; BigRational y2 = BigRational.TWO; BigRational y3 = BigRational.valueOf(3); V2D_Envelope instance = new V2D_Envelope(x0, x1, y0, y1); Assertions.assertTrue(instance.isIntersectedBy(x0, y0)); // Test 2 Assertions.assertTrue(instance.isIntersectedBy(x1, y0)); // Test 3 Assertions.assertTrue(instance.isIntersectedBy(x0, y1)); // Test 3 Assertions.assertTrue(instance.isIntersectedBy(x1, y1)); // Test 4 Assertions.assertFalse(instance.isIntersectedBy(x3, y1)); } /** * Test of isIntersectedBy method, of class V2D_Envelope. */ @Test public void testIsIntersectedBy_V2D_LineSegment() { System.out.println("isIntersectedBy"); BigRational x0 = BigRational.ZERO; BigRational x1 = BigRational.ONE; BigRational x2 = BigRational.TWO; BigRational x3 = BigRational.valueOf(3); BigRational y0 = BigRational.ZERO; BigRational y1 = BigRational.ONE; BigRational y2 = BigRational.TWO; BigRational y3 = BigRational.valueOf(3); V2D_Envelope instance = new V2D_Envelope(x0, x2, y0, y2); V2D_Point p0 = new V2D_Point(x0, y0); V2D_Point p1 = new V2D_Point(x0, y1); V2D_LineSegment l = new V2D_LineSegment(p0, p1); Assertions.assertTrue(instance.isIntersectedBy(l)); // Test 2 p0 = new V2D_Point(x3, y3); p1 = new V2D_Point(x3, y2); l = new V2D_LineSegment(p0, p1); Assertions.assertFalse(instance.isIntersectedBy(l)); // Test 3 p0 = new V2D_Point(x3, y3); p1 = new V2D_Point(x2, y2); l = new V2D_LineSegment(p0, p1); Assertions.assertTrue(instance.isIntersectedBy(l)); // Test 3 p0 = new V2D_Point(x3, y3); p1 = new V2D_Point(x0, y3); l = new V2D_LineSegment(p0, p1); Assertions.assertFalse(instance.isIntersectedBy(l)); // Test 4 p0 = new V2D_Point(x3, y3); p1 = new V2D_Point(x0, y2); l = new V2D_LineSegment(p0, p1); Assertions.assertTrue(instance.isIntersectedBy(l)); } /** * Test of getIntersection method, of class V2D_Envelope. */ @Test public void testGetIntersection() { System.out.println("getIntersection"); BigRational x0 = BigRational.ZERO; BigRational x1 = BigRational.ONE; BigRational x2 = BigRational.TWO; BigRational x3 = BigRational.valueOf(3); BigRational y0 = BigRational.ZERO; BigRational y1 = BigRational.ONE; BigRational y2 = BigRational.TWO; BigRational y3 = BigRational.valueOf(3); V2D_Envelope en = new V2D_Envelope(x0, x2, y0, y2); V2D_Envelope instance = new V2D_Envelope(x0, x1, y0, y1); V2D_Envelope expResult = new V2D_Envelope(x0, x1, y0, y1); V2D_Envelope result = instance.getIntersection(en); Assertions.assertEquals(expResult, result); // Test 2 en = new V2D_Envelope(x0, x1, y0, y1); instance = new V2D_Envelope(x0, x1, y0, y1); expResult = new V2D_Envelope(x0, x1, y0, y1); result = instance.getIntersection(en); Assertions.assertEquals(expResult, result); // Test 3 en = new V2D_Envelope(x0, x1, y0, y1); instance = new V2D_Envelope(x0, x2, y0, y2); expResult = new V2D_Envelope(x0, x1, y0, y1); result = instance.getIntersection(en); Assertions.assertEquals(expResult, result); // Test 4 en = new V2D_Envelope(x0, x3, y0, y3); instance = new V2D_Envelope(x0, x2, y0, y2); expResult = new V2D_Envelope(x0, x2, y0, y2); result = instance.getIntersection(en); Assertions.assertEquals(expResult, result); // Test 5 en = new V2D_Envelope(x0, x2, y0, y2); instance = new V2D_Envelope(x0, x1, y1, y3); expResult = new V2D_Envelope(x0, x1, y1, y2); result = instance.getIntersection(en); Assertions.assertEquals(expResult, result); // Test 6 en = new V2D_Envelope(x0, x2, y0, y3); instance = new V2D_Envelope(x0, x1, y1, y3); expResult = new V2D_Envelope(x0, x1, y1, y3); result = instance.getIntersection(en); Assertions.assertEquals(expResult, result); } /** * Test of getEnvelope method, of class V2D_Envelope. */ @Test public void testGetEnvelope() { System.out.println("getEnvelope"); BigRational z = BigRational.ZERO; V2D_Envelope instance = new V2D_Envelope(z, z, z, z); V2D_Envelope expResult = new V2D_Envelope(z, z, z, z); V2D_Envelope result = instance.getEnvelope(); Assertions.assertEquals(expResult, result); } /** * Test of equals method, of class V2D_Envelope. */ @Test public void testEquals() { System.out.println("equals"); BigRational z = BigRational.ZERO; Object o = new V2D_Envelope(z, z, z, z); V2D_Envelope instance = new V2D_Envelope(z, z, z, z); Assertions.assertTrue(instance.equals(o)); // Test 2 instance = new V2D_Envelope(z, z, z, BigRational.ONE); Assertions.assertFalse(instance.equals(o)); } /** * Test of hashCode method, of class V2D_Envelope. */ @Test public void testHashCode() { System.out.println("hashCode"); // Intentionally not tested. } /** * Test of getxMin method, of class V2D_Envelope. */ @Test public void testGetxMin() { System.out.println("getxMin"); BigRational z = BigRational.ZERO; V2D_Envelope instance = new V2D_Envelope(z, z, z, z); BigRational expResult = z; BigRational result = instance.getxMin(); Assertions.assertEquals(expResult, result); } /** * Test of getxMax method, of class V2D_Envelope. */ @Test public void testGetxMax() { System.out.println("getxMax"); BigRational z = BigRational.ZERO; V2D_Envelope instance = new V2D_Envelope(z, z, z, z); BigRational expResult = z; BigRational result = instance.getxMax(); Assertions.assertEquals(expResult, result); } /** * Test of getyMin method, of class V2D_Envelope. */ @Test public void testGetyMin() { System.out.println("getyMin"); BigRational z = BigRational.ZERO; V2D_Envelope instance = new V2D_Envelope(z, z, z, z); BigRational expResult = z; BigRational result = instance.getyMin(); Assertions.assertEquals(expResult, result); } /** * Test of getyMax method, of class V2D_Envelope. */ @Test public void testGetyMax() { System.out.println("getyMax"); BigRational z = BigRational.ZERO; V2D_Envelope instance = new V2D_Envelope(z, z, z, z); BigRational expResult = z; BigRational result = instance.getyMax(); } }
35.6875
120
0.621841
369d7b52e9647ad3c327402d89642d4bba8f522a
3,034
package com.jiaxy.cache; import com.jiaxy.cache.event.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * @author: wutao * @version: $Id:AbstractCacheFactory.java 2014/01/13 11:56 $ * */ public abstract class AbstractCacheFactory implements ICacheFactory { private static final Logger logger = LoggerFactory.getLogger(AbstractCacheFactory.class); private static final String CACHE_CONFIG_NAME = "cache/cachemeta.xml"; private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<String, Cache>(); private Set<String> cacheNames = new LinkedHashSet<String>(); private static List<CacheMeta> cacheMetas; private CacheEventMulticaster cacheEventMulticaster; static { InputStream in = AbstractCacheFactory.class.getClassLoader().getResourceAsStream(CACHE_CONFIG_NAME); if ( in == null ){ in = Thread.currentThread().getClass().getClassLoader().getResourceAsStream(CACHE_CONFIG_NAME); } cacheMetas = CacheMeta.parseCacheMetas(in); } @Override public void init(){ Collection<? extends Cache> caches = loadCaches(); this.cacheMap.clear(); if ( caches != null){ for (Cache cache : caches) { this.cacheMap.put(cache.getName(), cache); this.cacheNames.add(cache.getName()); } } cacheEventMulticaster = new SimpleCacheEventMulticaster(); addCacheListener(new CachePutListener()); addCacheListener(new CacheEvictListener()); addCacheListener(new CacheClearListener()); addCacheListener(new CacheGetListener()); } public void addCacheListener(CacheListener<? extends CacheEvent> listener) { if ( cacheEventMulticaster != null ){ cacheEventMulticaster.addCacheListener(listener); } } protected List<CacheMeta> getCacheMetas(){ return Collections.unmodifiableList(cacheMetas); } public Cache getCache(String name) { return this.cacheMap.get(name); } public Collection<String> getCacheNames() { return Collections.unmodifiableSet(this.cacheNames); } @Override public void publishCacheEvent(CacheEvent event) { cacheEventMulticaster.multicastEvent(event); } protected <T extends SmartCache>Cache instantiateCustomCache(Object nativeCache,CacheMeta meta){ try { Class<T> customCache = (Class<T>) Class.forName(meta.getClassName()); T cache = customCache.newInstance(); cache.setNativeCache(nativeCache); cache.fillCacheMetaValue(meta); return cache; } catch (Exception e) { logger.error(" instantiate {} failed", meta.getClassName(), e); } return null; } protected abstract Collection<? extends Cache> loadCaches(); }
29.456311
108
0.67238
6f58d042fc428c0b3b7c9de56339bae4e81829b8
2,708
package com.zscat.mallplus.sms.entity; import lombok.Data; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.copier.CopyOptions; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.zscat.mallplus.utils.BaseEntity; import java.util.Date; import lombok.Getter; import lombok.Setter; import java.math.BigDecimal; import java.io.Serializable; /** * @author wang * @date 2020-05-30 * 扫码购水记录 */ @Data @TableName("sms_water_buy_record") public class SmsWaterBuyRecord extends BaseEntity implements Serializable { @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 公众号id **/ @TableField("uniacid") private Integer uniacid; /** * 用户的openid **/ @TableField("open_id") private String openId; /** * 创建时间 **/ @TableField("create_time") private Date createTime; /** * 购买时间 **/ @TableField("buy_time") private Date buyTime; /** * 支付方式 **/ @TableField("pay_way") private Integer payWay; /** * 状态 **/ @TableField("status") private Integer status; /** * 充值金额 **/ @TableField("pay_fee") private BigDecimal payFee; /** * 实收金额 **/ @TableField("actual_fee") private BigDecimal actualFee; /** * 实际到账金额 **/ @TableField("actual_account") private BigDecimal actualAccount; /** * 唯一订单号 **/ @TableField("out_trade_no") private String outTradeNo; /** * 所属店铺 **/ @TableField("store_id") private Integer storeId; /** * 经销商id **/ @TableField("dealer_id") private Long dealerId; /** * 返回的唯一id,微信的 **/ @TableField("prepay_id") private String prepayId; /** * 微信支付订单号 */ @TableField("transaction_id") private String transactionId; /** * 分账唯一订单号 */ @TableField("rout_out_order_no") private String routOutOrderNo; /** * 微信分账单号,微信系统返回的唯一标识 */ @TableField("order_id") private String orderId; @TableField("first_amount") private BigDecimal firstAmount; @TableField("second_amount") private BigDecimal secondAmount; @TableField("third_amount") private BigDecimal thirdAmount; @TableField("rout_status") private Integer routStatus; @TableField("withdraw_status") private String withdrawStatus; @TableField("water_id") private Integer waterId; @TableField("device") private Long device; }
16.613497
75
0.626292
3366816861ecd7edf5ea0b45463e8d8f6c0ffbd9
1,174
package com.iwufang.merge.controller; import com.iwufang.merge.model.UserInfo; import com.iwufang.merge.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController public class UserController { @Autowired public UserService userService; @RequestMapping(value = "/test", method = RequestMethod.POST, consumes = "application/json", produces = "application/json;charset=UTF-8") public UserInfo login(@RequestBody UserInfo request){ UserInfo userInfoResponse = new UserInfo(); userInfoResponse = userService.getUserInfo(request); return userInfoResponse; } @RequestMapping(value = "/test2", method = RequestMethod.GET) public UserInfo login(@RequestParam String username, @RequestParam String password){ UserInfo request = new UserInfo(); request.setUsername("test"); request.setPassword("123456"); UserInfo userInfoResponse = userService.getUserInfo(request); System.out.println(userInfoResponse.getId()); return userInfoResponse; } }
36.6875
89
0.705281
17a982ee6409473985ec1f669255e6f177ef8b95
529
package com.rentmycar.rentmycar.validation; import org.springframework.stereotype.Service; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; @Service public class EmailValidator implements Predicate<String> { @Override public boolean test(String email) { Pattern pattern = Pattern.compile("^[a-zA-Z0-9_!#$%&’*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(email); return matcher.find(); } }
27.842105
121
0.697543
34dc1630ad9a0d4fd1a4a2d1bef6eeda34a85ca1
369
/* * Copyright © 02.10.2015 by O.I.Mudannayake. All Rights Reserved. */ package report.type; import report.Report; /** * * @author Ivantha */ public class PurchaseReturnReport extends Report{ public void newPRNReport(String prnNo){ map.clear(); map.put("prnNo", prnNo); this.generateReport("prn_report.jasper", map); } }
18.45
66
0.636856
dcba2952ffec98c816792de44c1d0aa5c6dac85f
17,248
package edu.utexas.tacc.tapis.jobs.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.utexas.tacc.tapis.jobs.dao.sql.SqlStatements; import edu.utexas.tacc.tapis.jobs.exceptions.JobException; import edu.utexas.tacc.tapis.jobs.exceptions.JobQueueException; import edu.utexas.tacc.tapis.jobs.exceptions.JobQueueFilterException; import edu.utexas.tacc.tapis.jobs.exceptions.JobQueuePriorityException; import edu.utexas.tacc.tapis.jobs.model.JobQueue; import edu.utexas.tacc.tapis.jobs.queue.JobQueueManagerNames; import edu.utexas.tacc.tapis.jobs.queue.SelectorFilter; import edu.utexas.tacc.tapis.shared.exceptions.TapisException; import edu.utexas.tacc.tapis.shared.exceptions.TapisJDBCException; import edu.utexas.tacc.tapis.shared.i18n.MsgUtils; import edu.utexas.tacc.tapis.shared.uuid.TapisUUID; import edu.utexas.tacc.tapis.shared.uuid.UUIDType; /** Lightweight DAO that uses the caller's datasource to connect to the * database. If this subproject becomes its own service, then it will * configure and use its own datasource. See Jobs for an example on * how to do this. */ public final class JobQueuesDao extends AbstractDao { /* ********************************************************************** */ /* Constants */ /* ********************************************************************** */ // Tracing. private static final Logger _log = LoggerFactory.getLogger(JobQueuesDao.class); // The default queue name and priority for all tenants. public static final int DEFAULT_TENANT_QUEUE_PRIORITY = 1; // Rabbitmq limit. public static final int MAX_QUEUE_NAME_LEN = 255; // From the amqp-0-9-1 reference: The queue name can be empty, or a sequence of // these characters: letters, digits, hyphen, underscore, period, or colon. private static Pattern _queueNamePattern = Pattern.compile("(\\w|\\.|-|_|:)+"); /* ********************************************************************** */ /* Fields */ /* ********************************************************************** */ /* ********************************************************************** */ /* Constructors */ /* ********************************************************************** */ /* ---------------------------------------------------------------------- */ /* constructor: */ /* ---------------------------------------------------------------------- */ /** This class depends on the calling code to provide a datasource for * db connections since this code in not part of a free-standing service. * * @param dataSource the non-null datasource */ public JobQueuesDao() throws TapisException {} /* ********************************************************************** */ /* Public Methods */ /* ********************************************************************** */ /* ---------------------------------------------------------------------- */ /* getJobQueueByName: */ /* ---------------------------------------------------------------------- */ /** Return the definition of the named queue or null if not found. * * @param queueName the name of the queue to search * @return the queue definition or null if not found * @throws TapisException */ public JobQueue getJobQueueByName(String queueName) throws TapisException { // Initialize result. JobQueue queue = null; // ------------------------- Call SQL ---------------------------- Connection conn = null; try { // Get a database connection. conn = getConnection(); // Get the select command. String sql = SqlStatements.SELECT_JOBQUEUE_BY_NAME; // Prepare the statement and fill in the placeholders. PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, queueName); // Issue the call for the 1 row result set. ResultSet rs = pstmt.executeQuery(); queue = populateJobQueues(rs); // Close the result and statement. rs.close(); pstmt.close(); // Commit the transaction. conn.commit(); } catch (Exception e) { // Rollback transaction. try {if (conn != null) conn.rollback();} catch (Exception e1){_log.error(MsgUtils.getMsg("DB_FAILED_ROLLBACK"), e1);} String msg = MsgUtils.getMsg("DB_SELECT_UUID_ERROR", "JobQueues", "allUUIDs", e.getMessage()); _log.error(msg, e); throw new TapisException(msg, e); } finally { // Always return the connection back to the connection pool. try {if (conn != null) conn.close();} catch (Exception e) { // If commit worked, we can swallow the exception. // If not, the commit exception will be thrown. String msg = MsgUtils.getMsg("DB_FAILED_CONNECTION_CLOSE"); _log.error(msg, e); } } return queue; } /* ---------------------------------------------------------------------- */ /* getJobQueuesByPriorityDesc: */ /* ---------------------------------------------------------------------- */ /** Return a non-empty list of queues. * * @return the non-empty list of defined queues * @throws TapisException on error or if the result list is empty */ public List<JobQueue> getJobQueuesByPriorityDesc() throws TapisException { // Initialize result. ArrayList<JobQueue> list = new ArrayList<>(); // ------------------------- Call SQL ---------------------------- Connection conn = null; try { // Get a database connection. conn = getConnection(); // Get the select command. String sql = SqlStatements.SELECT_JOBQUEUES_BY_PRIORITY_DESC; // Prepare the statement and fill in the placeholders. PreparedStatement pstmt = conn.prepareStatement(sql); // Issue the call for the 1 row result set. ResultSet rs = pstmt.executeQuery(); JobQueue obj = populateJobQueues(rs); while (obj != null) { list.add(obj); obj = populateJobQueues(rs); } // Close the result and statement. rs.close(); pstmt.close(); // Commit the transaction. conn.commit(); } catch (Exception e) { // Rollback transaction. try {if (conn != null) conn.rollback();} catch (Exception e1){_log.error(MsgUtils.getMsg("DB_FAILED_ROLLBACK"), e1);} String msg = MsgUtils.getMsg("DB_SELECT_UUID_ERROR", "JobQueues", "allUUIDs", e.getMessage()); throw new TapisException(msg, e); } finally { // Always return the connection back to the connection pool. try {if (conn != null) conn.close();} catch (Exception e) { // If commit worked, we can swallow the exception. // If not, the commit exception will be thrown. String msg = MsgUtils.getMsg("DB_FAILED_CONNECTION_CLOSE"); _log.error(msg, e); } } // Throw an exception is the list is empty. if (list.isEmpty()) { String msg = MsgUtils.getMsg("JOBS_QUEUE_NO_QUEUES"); throw new TapisException(msg); } return list; } /* ---------------------------------------------------------------------- */ /* createQueue: */ /* ---------------------------------------------------------------------- */ public void createQueue(JobQueue queue) throws TapisException { // ------------------------- Complete Input ---------------------- // Fill in any missing queue fields. if (queue.getCreated() == null) { Instant now = Instant.now(); queue.setCreated(now); queue.setLastUpdated(now); } if (StringUtils.isBlank(queue.getUuid())) queue.setUuid(new TapisUUID(UUIDType.JOB_QUEUE).toString()); // ------------------------- Check Input ------------------------- // Exceptions can be thrown from here. validateJobQueue(queue); // ------------------------- Call SQL ---------------------------- Connection conn = null; try { // Get a database connection. conn = getConnection(); // Insert into the job_queue table. // Create the command using table definition field order. String sql = SqlStatements.CREATE_JOBQUEUE; // Prepare the statement and fill in the placeholders. PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, queue.getName()); pstmt.setInt(2, queue.getPriority()); pstmt.setString(3, queue.getFilter()); pstmt.setString(4, queue.getUuid()); pstmt.setTimestamp(5, Timestamp.from(queue.getCreated())); pstmt.setTimestamp(6, Timestamp.from(queue.getLastUpdated())); // Issue the call and clean up statement. int rows = pstmt.executeUpdate(); if (rows != 1) _log.warn(MsgUtils.getMsg("DB_INSERT_UNEXPECTED_ROWS", "job_queues", rows, 1)); pstmt.close(); // Commit the transaction that may include changes to both tables. conn.commit(); // Note that the queue was created. _log.info(MsgUtils.getMsg("JOBS_JOB_QUEUE_CREATED", queue.getName())); } catch (Exception e) { // Rollback transaction. try {if (conn != null) conn.rollback();} catch (Exception e1){_log.error(MsgUtils.getMsg("DB_FAILED_ROLLBACK"), e1);} String msg = MsgUtils.getMsg("JOBS_JOB_QUEUE_CREATE_ERROR", queue.getName(), e.getMessage()); _log.error(msg, e); throw new JobException(msg, e); } finally { // Always return the connection back to the connection pool. if (conn != null) try {conn.close();} catch (Exception e) { // If commit worked, we can swallow the exception. // If not, the commit exception will be thrown. String msg = MsgUtils.getMsg("DB_FAILED_CONNECTION_CLOSE"); _log.error(msg, e); } } } /* ********************************************************************** */ /* Private Methods */ /* ********************************************************************** */ /* ---------------------------------------------------------------------- */ /* populateJobQueues: */ /* ---------------------------------------------------------------------- */ /** Populate a new JobQueues object with a record retrieved from the * database. The result set's cursor will be advanced to the next * position and, if a row exists, its data will be marshalled into a * JobQueues object. The result set is not closed by this method. * * NOTE: This method assumes all fields are returned table definition order. * * NOTE: This method must be manually maintained whenever the table schema changes. * * @param rs the unprocessed result set from a query. * @return a new model object or null if the result set is null or empty * @throws TapisJDBCException on SQL access or conversion errors */ private JobQueue populateJobQueues(ResultSet rs) throws TapisJDBCException { // Quick check. if (rs == null) return null; try { // Return null if the results are empty or exhausted. // This call advances the cursor. if (!rs.next()) return null; } catch (Exception e) { String msg = MsgUtils.getMsg("DB_RESULT_ACCESS_ERROR", e.getMessage()); _log.error(msg, e); throw new TapisJDBCException(msg, e); } // Populate the JobQueues object using table definition field order, // which is the order specified in all calling methods. JobQueue obj = new JobQueue(); try { obj.setId(rs.getInt(1)); obj.setName(rs.getString(2)); obj.setPriority(rs.getInt(3)); obj.setFilter(rs.getString(4)); obj.setUuid(rs.getString(5)); obj.setCreated(rs.getTimestamp(6).toInstant()); obj.setLastUpdated(rs.getTimestamp(7).toInstant()); } catch (Exception e) { String msg = MsgUtils.getMsg("DB_TYPE_CAST_ERROR", e.getMessage()); _log.error(msg, e); throw new TapisJDBCException(msg, e); } return obj; } /* ---------------------------------------------------------------------- */ /* validateJobQueue: */ /* ---------------------------------------------------------------------- */ private void validateJobQueue(JobQueue queue) throws TapisException { // The uuid is always set by caller, so no need to check here. if (StringUtils.isBlank(queue.getName())) { String msg = MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "createQueue", "name"); throw new TapisException(msg); } if (StringUtils.isBlank(queue.getFilter())) { String msg = MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "createQueue", "filter"); throw new TapisException(msg); } if (queue.getPriority() < 1) { String msg = MsgUtils.getMsg("JOBS_QUEUE_INVALID_PRIORITY"); throw new JobQueuePriorityException(msg); } // Check queue name for invalid length. if (queue.getName().length() > MAX_QUEUE_NAME_LEN) { String msg = MsgUtils.getMsg("JOBS_QUEUE_LONG_NAME", queue.getName().substring(0, 64)); throw new JobQueueException(msg); } // Check queue name for invalid characters. Matcher m = _queueNamePattern.matcher(queue.getName()); if (!m.matches()) { String msg = MsgUtils.getMsg("JOBS_QUEUE_INVALID_NAME", queue.getName()); throw new JobQueueException(msg); } // The queue name must begin with "tapis.jobq.submit." String prefix = JobQueueManagerNames.TAPIS_JOBQ_PREFIX + JobQueueManagerNames.SUBMIT_PART; if (!queue.getName().startsWith(prefix)) { String msg = MsgUtils.getMsg("JOBS_QUEUE_INVALID_NAME_PREFIX", prefix); throw new JobQueueException(msg); } // Double check the priority of the default queue. String defaultQueue = JobQueueManagerNames.getDefaultQueue(); if (defaultQueue.equals(queue.getName()) && (DEFAULT_TENANT_QUEUE_PRIORITY != queue.getPriority())) { String msg = MsgUtils.getMsg("JOBS_QUEUE_INVALID_DEFAULT_QUEUE_DEF", defaultQueue, DEFAULT_TENANT_QUEUE_PRIORITY); throw new JobQueuePriorityException(msg); } // Make sure no non-default queue has the default (lowest) priority. if (!defaultQueue.equals(queue.getName()) && (DEFAULT_TENANT_QUEUE_PRIORITY == queue.getPriority())) { String msg = MsgUtils.getMsg("JOBS_QUEUE_INVALID_NON_DEFAULT_QUEUE_DEF", queue.getName(), DEFAULT_TENANT_QUEUE_PRIORITY); throw new JobQueuePriorityException(msg); } // Validate the filter. validateFilter(queue.getFilter()); } /* ---------------------------------------------------------------------- */ /* validateFilter: */ /* ---------------------------------------------------------------------- */ /** Attempt to parse the (non-empty) filter. Parser errors are contained * in the thrown exception if things go wrong. * * @param filter the text of a SQL92-like filter. */ private void validateFilter(String filter) throws JobQueueFilterException { // Make sure if (StringUtils.isBlank(filter)) { String msg = MsgUtils.getMsg("JOBS_QUEUE_FILTER_EMPTY"); _log.error(msg); throw new JobQueueFilterException(msg); } // Try to parse the filter. SelectorFilter.parse(filter); } }
40.583529
104
0.522379
81cf17b55005ea0b90ea4fd85f11036a9032af64
1,959
package com.github.ruediste.rise.component; import java.time.Duration; import java.time.Instant; import java.util.Timer; import java.util.TimerTask; import javax.inject.Inject; import javax.inject.Singleton; import org.slf4j.Logger; import com.github.ruediste.rise.core.scopes.HttpScopeManager; /** * Manager of a timer cleaning up {@link ComponentPage}s which do not receive a * heartbeat anymore. * * @see HearbeatRequestParser * @see ComponentPageHandleRepository */ @Singleton public class PageScopeCleaner { @Inject Logger log; @Inject HttpScopeManager mgr; @Inject PageScopeManager pageScopeManager; @Inject ComponentPageHandleRepository repo; @Inject ComponentPage page; private Timer timer; public void start() { timer = new Timer("pageScopeCleanupThread", true); timer.schedule(new TimerTask() { @Override public void run() { mgr.runInEachSessionScope(() -> { for (PageHandle handle : repo.getPageHandles()) { Instant now = Instant.now(); if (handle.getEndOfLife().isAfter(now)) continue; try { synchronized (handle.lock) { if (handle.getEndOfLife().isAfter(now)) continue; pageScopeManager.inScopeDo(handle.pageScopeState, () -> { page.destroy(); }); } } catch (Throwable t) { log.error("Error in page scope cleanup thread", t); } } }); } }, 0L, Duration.ofSeconds(1).toMillis()); } public void stop() { timer.cancel(); } }
25.115385
89
0.517611
8965b547fe0494e34ed39d417bb5f6146b451832
1,755
package com.jqh.gpuimagelib.encodec; import android.content.Context; import android.opengl.GLES20; import com.jqh.gpuimagelib.opengl.GLSurfaceView; import com.jqh.gpuimagelib.render.CommonFboRender; import com.jqh.gpuimagelib.render.filter.BaseGPUImageFilter; import com.jqh.gpuimagelib.render.textrue.BaseTexture; public class JqhEncodecRender implements GLSurfaceView.GLRender { private Context context; private CommonFboRender commonFboRender; private int textureId; public JqhEncodecRender(Context context, int textureid) { this.context = context; this.textureId = textureid; commonFboRender = new CommonFboRender(); commonFboRender.init(context); } @Override public void onSurfaceCreate() { // 设置一下两个可以让水印背景透明 GLES20.glEnable (GLES20.GL_BLEND); GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); commonFboRender.onCreate(); } @Override public void onSurfaceChanged(int width, int height) { GLES20.glViewport(0,0, width, height); commonFboRender.setWH(width, height); } @Override public void onDrawFrame() { // 用颜色刷新 commonFboRender.onDraw(textureId); } public void addFilter(BaseGPUImageFilter filter) { this.commonFboRender.setFilter(filter); } public void addTexture(BaseTexture baseTexture) { if (baseTexture != null){ commonFboRender.addTexture(baseTexture); } } public void removeTexture(String key) { commonFboRender.removeTexture(key); } public void updateTexture(String id, float left, float top, float scale) { commonFboRender.updateTexture(id, left, top, scale); } }
26.590909
79
0.696866
9ee4fef0720a419a3093315b061458b652db3ba3
9,152
/* * MIT License * * Copyright (c) 2018 Charalampos Savvidis * * 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.lowbudget.chess.front.app; import com.lowbudget.chess.front.app.UIApplication.DialogCancelListener; import com.lowbudget.chess.front.app.UIApplication.RegistrationDialogSuccessListener; import com.lowbudget.chess.model.PlayerColor; import com.lowbudget.chess.model.Move; import com.lowbudget.chess.model.uci.engine.UCIEngineConfig; import com.lowbudget.chess.model.uci.engine.options.UCIOption; import java.util.Collections; import java.util.List; /** * <p>Describes a player of a chess game</p> * <p>This abstraction allows us to interact with human and engine players alike.</p> */ public interface Player { /** * <p>Listener that can be registered with a player and can be notified for various events during the player's * life-cycle.</p> * <p>This interface is created mostly for engine players, so the application can respond to player related events * (i.e. like displaying a registration dialog). For human players either most events do not apply or * they have trivial implementation (e.g. a human player is "ready" as soon as it is started)</p> */ interface PlayerListener { /** * Event fired when a player has been started. * Staring a player does not necessary mean that the player is ready to make moves since engine players * must perform some initialization first * @param player the player that has been started */ void onPlayerStarted(Player player); /** * Event fired when a player has been stopped * @param player the player that has been stopped */ void onPlayerStopped(Player player); /** * Event fired when a player has performed any initialization required upon startup and is now ready * @param player the player that is ready */ void onPlayerReady(Player player); /** * Event fired when a player has decided the best move to play * @param move the move decided by the player */ void onPlayerMove(Move move); /** * Event fired when an unexpected error has occurred * @param exception the error occurred */ void onPlayerError(Exception exception); /** * Event fired when a connection to an (engine) player has been lost */ void onPlayerUnexpectedDisconnection(); /** * Event fired when the engine player is copy-protected and cannot be used * @param name the player's name * @param color the color of the player */ void onPlayerCopyProtectionError(String name, PlayerColor color); /** * Event fired when the player's engine requires registration. In such a case it is assumed that the application * will prompt the user for the registration details * @param player the player representing the engine that needs registration * @param successListener a listener that is notified if the registration is successful * @param cancelListener a listener that is notified if the registration is cancelled */ void onPlayerRegistrationRequired(Player player, RegistrationDialogSuccessListener successListener, DialogCancelListener cancelListener); /** * Event fired when the engine sends information about its current thinking lines * @param info the engine information available as a simple string */ void onEngineInfoAvailable(String info); /** * Event fired when an engine player has performed the initialization required by the UCI protocol and has received * the engine's uci options available (i.e. the engine's config) just before the {@link #onPlayerReady(Player)} * event. This event gives the application a chance to set some values for the engine options other than the default ones. * @param engineConfig the engine's config received by the uci engine * @return a list of options modified by the listener (if any) */ List<UCIOption> onEngineConfigAvailable(UCIEngineConfig engineConfig); } /** * Empty implementation that allows to override only the methods of interest */ class PlayerListenerAdapter implements PlayerListener { @Override public void onPlayerStopped(Player player) {} @Override public void onPlayerStarted(Player player) {} @Override public void onPlayerReady(Player player) {} @Override public void onPlayerMove(Move move) {} @Override public void onPlayerError(Exception exception) {} @Override public void onPlayerUnexpectedDisconnection() {} @Override public void onPlayerCopyProtectionError(String name, PlayerColor color) {} @Override public void onPlayerRegistrationRequired(Player player, RegistrationDialogSuccessListener successListener, DialogCancelListener cancelListener) {} @Override public void onEngineInfoAvailable(String info) {} @Override public List<UCIOption> onEngineConfigAvailable(UCIEngineConfig engineConfig) { return Collections.emptyList(); } } /** * Returns the player's name * @return the player's name. This value should be used wherever the player's name is displayed */ String getName(); /** * Sets the player's name * @param name the new name to set */ void setName(String name); /** * Returns the player's color * @return the {@link PlayerColor} of this player (i.e. if it plays white or black pieces) */ PlayerColor getColor(); /** * Checks if this player is an engine * @return {@code true} if this player is an engine player, {@code false} otherwise */ boolean isEngine(); /** * Chesks if this player is a human * @return {@code true} if this player is a human player, {@code false} otherwise */ boolean isHuman(); /** * Adds a listener to this player to be notified for player events * @param playerListener the listener to add */ void addPlayerListener(PlayerListener playerListener); /** * Removes the player listener specified * @param playerListener the listener to remove */ void removePlayerListener(PlayerListener playerListener); /** * <p>Asks the player to start thinking for its next move.</p> * <p>This operation applies only to engine players since they usually need to send some information in order * for the engine to play</p> * @param lastFenPosition the FEN position of the board <strong>before</strong> the {@code move} was played * @param lastMove the last move made (if any). The current board position is defined by the {@code lastFenPosition} * after playing the {@code lastMove} * @param whiteRemainingTime the white player's remaining time (in millis) * @param blackRemainingTime the black player's remaining time (in millis) */ void startThinking(String lastFenPosition, Move lastMove, long whiteRemainingTime, long blackRemainingTime); /** * <p>Informs the player about its opponent.</p> * <p>This is useful for engine players that can send the "UCI_Opponent" option with the opponent's information</p> * @param opponent the opponent player */ void handShake(Player opponent); /** * <p>Checks if a player is ready so the time controls can be started.</p> * <p>Human players will probably return {@code true} immediately here as long as they have been started, engine * players however will probably need some time until they are connected with an engine.</p> * @return {@code true} if this player is ready, {@code false} otherwise */ boolean isReady(); /** * Performs any initialization required for the player to be able to start thinking for moves (i.e. this is the * place where engine players will initiate the connection to the engine) */ void start(); /** * Performs any cleanup required after the game is stopped (i.e. this is the place where engine players will * disconnect from the engine) */ void stop(); /** * Lets the player know that the game is paused. For engine players this means that they should not process any * more messages coming from the engine until the player is resumed */ void pause(); /** * Resumes a paused player. Engine players that have received any messages (i.e. an engine move) after pause, * should go on and process them now */ void resume(); }
36.608
148
0.739838
c8189b0df655e88a28ddfe558084b637c21e56ae
5,410
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package animal; import fazenda.Fazenda; import java.util.Calendar; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import util.HibernateUtil; /* * * @author Rafael */ public class AnimalDAOHibernate implements AnimalDAO { private Session session = HibernateUtil.getSessionFactory().openSession(); ; public void setSession(Session session) { this.session = session; } @Override public void salvar(Animal animal) { this.session.save(animal); } @Override public void atualizar(Animal animal) { this.session.update(animal); } @Override public void excluir(Animal animal) { this.session.delete(animal); } @Override public Animal carregar(Integer idAnimal) { return (Animal) this.session.get(Animal.class, idAnimal); } @Override public List<Animal> listarAll() { return this.session.createCriteria(Animal.class).list(); } @Override public List<Animal> listar(Fazenda fazenda) { Boolean ativaFemea = true; Criteria criteria = this.session.createCriteria(Animal.class); criteria.add(Restrictions.eq("fazenda", fazenda)); criteria.add(Restrictions.eq("ativaFemea", ativaFemea)); return criteria.list(); } @Override public List<Animal> listarPesado(Fazenda fazenda) { Boolean ativaFemea = true; Criteria criteria = this.session.createCriteria(Animal.class); criteria.add(Restrictions.eq("fazenda", fazenda)); criteria.add(Restrictions.eq("ativaFemea", ativaFemea)); criteria.addOrder(Order.desc("peso")); return criteria.list(); } @Override public List<Animal> listarSexo(String sexo, Fazenda fazenda) { Boolean ativaFemea = true; Criteria criteria = this.session.createCriteria(Animal.class); criteria.add(Restrictions.eq("fazenda", fazenda)); criteria.add(Restrictions.eq("sexo", sexo)); criteria.add(Restrictions.eq("ativaFemea", ativaFemea)); return criteria.list(); } @Override public List<Animal> listar1(java.util.Date inicio, java.util.Date fim, Fazenda fazenda) { Boolean ativaFemea = true; Criteria criteria = this.session.createCriteria(Animal.class); criteria.add(Restrictions.eq("fazenda", fazenda)); criteria.add(Restrictions.between("dataNascimento", inicio, fim)); criteria.add(Restrictions.eq("ativaFemea", ativaFemea)); return criteria.list(); } @Override public List<Animal> listar2(java.util.Date inicio, java.util.Date fim, String sexo, Fazenda fazenda) { Boolean ativaFemea = true; Criteria criteria = this.session.createCriteria(Animal.class); criteria.add(Restrictions.eq("fazenda", fazenda)); criteria.add(Restrictions.eq("sexo", sexo)); criteria.add(Restrictions.between("dataNascimento", inicio, fim)); criteria.add(Restrictions.eq("ativaFemea", ativaFemea)); return criteria.list(); } @Override public List<Animal> listarNascidaAno(Fazenda fazenda, int ano) { Calendar anoSel = Calendar.getInstance(); anoSel.set(Calendar.YEAR, ano); Boolean ativaFemea = true; Query query = session.createQuery("from animal where fazenda_idfazenda = :fazenda and year(dataNascimento)=:ano1 and ativaFemea =:ativaFemea"); query.setEntity("fazenda", fazenda); query.setInteger("ano1", anoSel.get(Calendar.YEAR)); query.setBoolean("ativaFemea", ativaFemea); return query.list(); } @Override public List<Animal> listarNascidaAnoSexo(String sexo, Fazenda fazenda, int ano) { Calendar anoSel = Calendar.getInstance(); anoSel.set(Calendar.YEAR, ano); Boolean ativaFemea = true; Query query = session.createQuery("from animal where sexo =:sexo and fazenda_idfazenda = :fazenda and year(dataNascimento)=:ano1 and ativaFemea =:ativaFemea"); query.setEntity("fazenda", fazenda); query.setString("sexo", sexo); query.setInteger("ano1", anoSel.get(Calendar.YEAR)); query.setBoolean("ativaFemea", ativaFemea); return query.list(); } @Override public List<Animal> listarNegativa(Fazenda fazenda) { Boolean ativaFemea = false; Criteria criteria = this.session.createCriteria(Animal.class); criteria.add(Restrictions.eq("fazenda", fazenda)); criteria.add(Restrictions.eq("ativaFemea", ativaFemea)); return criteria.list(); } @Override public List<Animal> listarSexoNegativa(String sexo, Fazenda fazenda) { Boolean ativaFemea = false; Criteria criteria = this.session.createCriteria(Animal.class); criteria.add(Restrictions.eq("fazenda", fazenda)); criteria.add(Restrictions.eq("sexo", sexo)); criteria.add(Restrictions.eq("ativaFemea", ativaFemea)); return criteria.list(); } }
34.903226
168
0.649908
10e9a7585ee682990b292dbe7540d1dc574b808b
3,176
package org.sakaiproject.archive.tool; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Path; import java.nio.file.Paths; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.sakaiproject.authz.api.SecurityService; import org.sakaiproject.component.api.ComponentManager; import org.sakaiproject.component.api.ServerConfigurationService; import org.sakaiproject.tool.api.SessionManager; /** * Download servlet for archive downloads. Restricted to super user as per normal archive tool * * @author Steve Swinsburg (steve.swinsburg@gmail.com) * */ @Slf4j public class DownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; private SecurityService securityService; private ServerConfigurationService serverConfigurationService; private SessionManager sessionManager; /** * inject dependencies */ public void init(ServletConfig config) throws ServletException { super.init(config); ComponentManager manager = org.sakaiproject.component.cover.ComponentManager.getInstance(); if(securityService == null) { securityService = (SecurityService) manager.get(SecurityService.class.getName()); } if(serverConfigurationService == null) { serverConfigurationService = (ServerConfigurationService) manager.get(ServerConfigurationService.class.getName()); } if(sessionManager == null) { sessionManager = (SessionManager) manager.get(SessionManager.class.getName()); } } /** * get file */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!securityService.isSuperUser()){ log.error("Must be super user to download archives"); response.sendError(HttpServletResponse.SC_FORBIDDEN, "Must be super user to download archives"); return; } String archiveName = request.getParameter("archive"); Path sakaiHome = Paths.get(serverConfigurationService.getSakaiHomePath()); Path archives = sakaiHome.resolve(serverConfigurationService.getString("archive.storage.path", "archive")); response.setContentType("application/zip"); response.setHeader("Content-Disposition","attachment;filename=" +archiveName); Path archivePath = archives.resolve(archiveName).normalize(); if (!archivePath.startsWith(archives)) { log.error(String.format("The archive file (%s) is not inside the archives folder (%s)", archivePath.toString(), archives.toString())); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Archive param must be a valid site archive. Param was: " + archiveName); return; } OutputStream out = response.getOutputStream(); try (InputStream in = FileUtils.openInputStream(archivePath.toFile())) { IOUtils.copyLarge(in, out); out.flush(); out.close(); } } }
34.150538
117
0.77267
1ae8210a48404ea5c466a2c13b0b066195edee90
4,711
package mod.acgaming.jockeys.client.renderer.entity; import net.minecraft.client.model.HierarchicalModel; import net.minecraft.client.model.geom.ModelLayerLocation; import net.minecraft.client.model.geom.ModelPart; import net.minecraft.client.model.geom.PartPose; import net.minecraft.client.model.geom.builders.CubeListBuilder; import net.minecraft.client.model.geom.builders.LayerDefinition; import net.minecraft.client.model.geom.builders.MeshDefinition; import net.minecraft.client.model.geom.builders.PartDefinition; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.Mth; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.EntityRenderersEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import mod.acgaming.jockeys.entity.SkeletonBat; @OnlyIn(Dist.CLIENT) public class SkeletonBatModel extends HierarchicalModel<SkeletonBat> { public static ModelLayerLocation SKELETON_BAT_LAYER = new ModelLayerLocation(new ResourceLocation("minecraft:player"), "skeleton_bat"); @SubscribeEvent public static void registerLayer(EntityRenderersEvent.RegisterLayerDefinitions event) { event.registerLayerDefinition(SKELETON_BAT_LAYER, SkeletonBatModel::createBodyLayer); } public static LayerDefinition createBodyLayer() { MeshDefinition meshdefinition = new MeshDefinition(); PartDefinition partdefinition = meshdefinition.getRoot(); PartDefinition partdefinition1 = partdefinition.addOrReplaceChild("head", CubeListBuilder.create().texOffs(0, 0).addBox(-3.0F, -3.0F, -3.0F, 6.0F, 6.0F, 6.0F), PartPose.ZERO); partdefinition1.addOrReplaceChild("right_ear", CubeListBuilder.create().texOffs(24, 0).addBox(-4.0F, -6.0F, -2.0F, 3.0F, 4.0F, 1.0F), PartPose.ZERO); partdefinition1.addOrReplaceChild("left_ear", CubeListBuilder.create().texOffs(24, 0).mirror().addBox(1.0F, -6.0F, -2.0F, 3.0F, 4.0F, 1.0F), PartPose.ZERO); PartDefinition partdefinition2 = partdefinition.addOrReplaceChild("body", CubeListBuilder.create().texOffs(0, 16).addBox(-3.0F, 4.0F, -3.0F, 6.0F, 12.0F, 6.0F).texOffs(0, 34).addBox(-5.0F, 16.0F, 0.0F, 10.0F, 6.0F, 1.0F), PartPose.ZERO); PartDefinition partdefinition3 = partdefinition2.addOrReplaceChild("right_wing", CubeListBuilder.create().texOffs(42, 0).addBox(-12.0F, 1.0F, 1.5F, 10.0F, 16.0F, 1.0F), PartPose.ZERO); partdefinition3.addOrReplaceChild("right_wing_tip", CubeListBuilder.create().texOffs(24, 16).addBox(-8.0F, 1.0F, 0.0F, 8.0F, 12.0F, 1.0F), PartPose.offset(-12.0F, 1.0F, 1.5F)); PartDefinition partdefinition4 = partdefinition2.addOrReplaceChild("left_wing", CubeListBuilder.create().texOffs(42, 0).mirror().addBox(2.0F, 1.0F, 1.5F, 10.0F, 16.0F, 1.0F), PartPose.ZERO); partdefinition4.addOrReplaceChild("left_wing_tip", CubeListBuilder.create().texOffs(24, 16).mirror().addBox(0.0F, 1.0F, 0.0F, 8.0F, 12.0F, 1.0F), PartPose.offset(12.0F, 1.0F, 1.5F)); return LayerDefinition.create(meshdefinition, 64, 64); } private final ModelPart root; private final ModelPart head; private final ModelPart body; private final ModelPart rightWing; private final ModelPart leftWing; private final ModelPart rightWingTip; private final ModelPart leftWingTip; public SkeletonBatModel(ModelPart p_170427_) { this.root = p_170427_; this.head = p_170427_.getChild("head"); this.body = p_170427_.getChild("body"); this.rightWing = this.body.getChild("right_wing"); this.rightWingTip = this.rightWing.getChild("right_wing_tip"); this.leftWing = this.body.getChild("left_wing"); this.leftWingTip = this.leftWing.getChild("left_wing_tip"); } public ModelPart root() { return this.root; } public void setupAnim(SkeletonBat p_102200_, float p_102201_, float p_102202_, float p_102203_, float p_102204_, float p_102205_) { this.head.xRot = p_102205_ * ((float) Math.PI / 180F); this.head.yRot = p_102204_ * ((float) Math.PI / 180F); this.head.zRot = 0.0F; this.head.setPos(0.0F, 0.0F, 0.0F); this.rightWing.setPos(0.0F, 0.0F, 0.0F); this.leftWing.setPos(0.0F, 0.0F, 0.0F); this.body.xRot = ((float) Math.PI / 4F) + Mth.cos(p_102203_ * 0.1F) * 0.15F; this.body.yRot = 0.0F; this.rightWing.yRot = Mth.cos(p_102203_ * 25.0F * ((float) Math.PI / 180F)) * (float) Math.PI * 0.25F; this.leftWing.yRot = -this.rightWing.yRot; this.rightWingTip.yRot = this.rightWing.yRot * 0.5F; this.leftWingTip.yRot = -this.rightWing.yRot * 0.5F; } }
55.423529
245
0.718107
3ffef3a9f798ebe7d14e40cc6f90609d15e9919a
357
package com.xorlev.gatekeeper.data; import lombok.Data; import java.io.Serializable; /** * 2013-07-27 * * @author Michael Rose <elementation@gmail.com> */ @Data public class Server implements Serializable { String host; Integer port; public Server(String host, Integer port) { this.host = host; this.port = port; } }
16.227273
48
0.661064
62d9fffe29eb05046634a9fab94961d1d033128b
2,281
package cn.study.common.base; import cn.hutool.core.collection.CollectionUtil; import cn.study.common.model.OrderQueryParam; import cn.study.common.model.QueryParam; import com.baomidou.mybatisplus.core.metadata.OrderItem; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.github.pagehelper.PageHelper; import org.springframework.data.domain.Pageable; import java.util.Arrays; import java.util.List; /** * @Desc : * @Create : zhaoey ~ 2020/05/23 */ public class BaseServiceImpl<M extends IBaseMapper<T>,T> extends ServiceImpl<M,T> implements IBaseService<T> { protected Page setPageParam(QueryParam queryParam) { return setPageParam(queryParam,null); } protected Page setPageParam(QueryParam queryParam, OrderItem defaultOrder) { Page page = new Page(); // 设置当前页码 page.setCurrent(queryParam.getPage()); // 设置页大小 page.setSize(queryParam.getLimit()); /** * 如果是queryParam是OrderQueryParam,并且不为空,则使用前端排序 * 否则使用默认排序 */ if (queryParam instanceof OrderQueryParam){ OrderQueryParam orderQueryParam = (OrderQueryParam) queryParam; List<OrderItem> orderItems = orderQueryParam.getOrders(); if (CollectionUtil.isEmpty(orderItems)){ page.setOrders(Arrays.asList(defaultOrder)); }else{ page.setOrders(orderItems); } }else{ page.setOrders(Arrays.asList(defaultOrder)); } return page; } protected void getPage(Pageable pageable) { getPage(pageable,true); } protected void getPage(Pageable pageable,boolean isOrder){ if (isOrder){ String order=null; if(pageable.getSort()!=null){ order= pageable.getSort().toString(); order=order.replace(":",""); if("UNSORTED".equals(order)){ order="id desc"; } } PageHelper.startPage(pageable.getPageNumber()+1, pageable.getPageSize(),order); }else{ PageHelper.startPage(pageable.getPageNumber()+1, pageable.getPageSize()); } } }
33.057971
110
0.637878
3416c4ad9dd47081ae0b17b2b2c78e8d8b115e62
4,538
package com.phoenix.phoenixtales.origins.world.feature.realm; import com.mojang.serialization.Codec; import com.phoenix.phoenixtales.origins.block.OriginsBlocks; import com.phoenix.phoenixtales.origins.block.blocks.OriginsLeavesBlock; import net.minecraft.block.BlockState; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.world.ISeedReader; import net.minecraft.world.gen.ChunkGenerator; import net.minecraft.world.gen.feature.Feature; import net.minecraft.world.gen.feature.NoFeatureConfig; import java.util.Random; public class HuiBushFeature extends Feature<NoFeatureConfig> { private final BlockState log = OriginsBlocks.HUI_LOG.getDefaultState(); private final BlockState leave = OriginsBlocks.HUI_LEAVES.getDefaultState().with(OriginsLeavesBlock.DISTANCE, 2); public HuiBushFeature(Codec<NoFeatureConfig> codec) { super(codec); } @Override public boolean generate(ISeedReader reader, ChunkGenerator generator, Random rand, BlockPos pos, NoFeatureConfig config) { BlockPos build = pos; for (build = build.up(); reader.isAirBlock(build) && build.getY() > 1; build = build.down()) { } if (this.canPlace(reader, build)) { build = build.up(); for (int i = 0; i < rand.nextInt(3); i++) { reader.setBlockState(build, log, 3); placeAround(reader, build, 0.7f, rand, false); build = build.up(); } BlockPos temp = build; switch (rand.nextInt(8)) { case 0: temp.north(); this.placeOp(reader, temp, rand); break; case 1: temp = temp.south(); this.placeOp(reader, temp, rand); break; case 2: temp = temp.east(); this.placeOp(reader, temp, rand); break; case 3: temp = temp.west(); this.placeOp(reader, temp, rand); break; case 4: temp = temp.north().east(); this.placeOp(reader, temp, rand); break; case 5: temp = build.south().west(); this.placeOp(reader, temp, rand); break; case 6: temp = temp.east().south(); this.placeOp(reader, temp, rand); break; case 7: temp = temp.west().north(); this.placeOp(reader, temp, rand); break; } return true; } return false; } private boolean canPlace(ISeedReader reader, BlockPos pos) { return !(reader.getBlockState(pos).matchesBlock(OriginsBlocks.HUI_LEAVES) || reader.getBlockState(pos).matchesBlock(OriginsBlocks.HUI_LOG) || reader.getBlockState(pos).matchesBlock(OriginsBlocks.HUO_LEAVES) || reader.getBlockState(pos).matchesBlock(OriginsBlocks.HUO_LOG)); } private void placeOp(ISeedReader reader, BlockPos temp, Random random) { for (int i = 0; i < random.nextInt(3); i++) { reader.setBlockState(temp, log, 3); placeAround(reader, temp, 0.7f, random, true); temp = temp.up(); } } private void placeAround(ISeedReader reader, BlockPos pos, float chance, Random random, boolean top) { if (top) { Direction[] directions = new Direction[]{Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST, Direction.UP}; for (Direction d : directions) { BlockPos pos1 = pos.offset(d); if (random.nextFloat() <= chance) { if (reader.getBlockState(pos1) != log) { reader.setBlockState(pos1, leave, 3); } } } } else { Direction[] directions = new Direction[]{Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST}; for (Direction d : directions) { BlockPos pos1 = pos.offset(d); if (random.nextFloat() <= chance) { if (reader.getBlockState(pos1) != log) { reader.setBlockState(pos1, leave, 3); } } } } } }
39.12069
281
0.545174
bfeca18ff697aca2e1c208895c858df9f3651fe8
1,063
package gr.personal.aggregator; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created by Nick Kanakis on 25/7/2017. * * Creates a new single thread that runs in the background an AggregatorRunnable instance. */ @Component public class AggregatorExecutor { @Autowired private Logger logger; @Autowired private AggregatorRunnable aggregator; private ExecutorService executorService; @PostConstruct //TODO: Disable postConstructor in integration testing. public void start(){ logger.info("Start data aggregation from Reddit API "); ExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); executorService.execute(aggregator); } public void stop() { logger.info("Stop data aggregation from Reddit API. "); executorService.shutdown(); } }
27.973684
90
0.752587
a0b1e645c297318e564a8d163b23016d361a6dec
257
package je.techtribes.component.github; import je.techtribes.util.ComponentException; public class GitHubException extends ComponentException { public GitHubException(String message, Throwable throwable) { super(message, throwable); } }
21.416667
65
0.770428
14d1e61dea9862ade1416208ac930a125e3adcd5
2,124
package eu.wauz.wauzcore.oneblock; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import eu.wauz.wauzcore.data.SeasonConfigurator; import eu.wauz.wauzcore.data.players.PlayerConfigurator; import eu.wauz.wauzcore.system.WauzDebugger; import eu.wauz.wauzcore.system.nms.NmsWorldBorder; /** * Used for managing one-block plots. * * @author Wauzmons */ public class OnePlotManager { /** * The size in blocks for one-block plots. */ public static final int PLOT_SIZE = 750; /** * The radius of the border around each plot. */ public static final int BORDER_RADIUS = 125; /** * The world used for the one block gamemode. */ private static final World WORLD = Bukkit.getWorld("SurvivalOneBlock"); /** * Gets the location of the next plot, that hasn't been claimed yet. * Automatically marks it as claimed afterwards. * * @return The location of the next free plot. * * @see SeasonConfigurator#getLastTakenPlot(World) * @see SeasonConfigurator#setLastTakenPlot(World, int) * @see OnePlotManager#getPlotLocation(int) */ public static Location getNextFreePlotLocation() { int plotIndex = SeasonConfigurator.getLastTakenPlot(WORLD) + 1; SeasonConfigurator.setLastTakenPlot(WORLD, plotIndex); return getPlotLocation(plotIndex); } /** * Gets the location of the plot with the given index. * * @param plotIndex The index of the plot. * * @return The location of the plot. * * @see OnePlotCalculator#getPlotGridPosition(int) */ public static Location getPlotLocation(int plotIndex) { int[] gridPosition = OnePlotCalculator.getPlotGridPosition(plotIndex); return new Location(WORLD, gridPosition[0] * PLOT_SIZE, 70, gridPosition[1] * PLOT_SIZE); } /** * Creates a world border around the plot for the given player. * * @param player The player to create the border for. */ public static void setUpBorder(Player player) { NmsWorldBorder.init(player, PlayerConfigurator.getCharacterSpawn(player), BORDER_RADIUS); WauzDebugger.log(player, "Created World Border"); } }
27.947368
91
0.735876
b97036cb89a5e706666cce523e3cd2e1814229fd
612
package app.lifeni.bms.entity.model; public class Role { private long roleId; private String roleName; private String permissions; public long getRoleId() { return roleId; } public void setRoleId(long roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getPermissions() { return permissions; } public void setPermissions(String permissions) { this.permissions = permissions; } }
18
52
0.629085
22a49197ce08795a0b6e10c066935fa4e47ada40
82
package com.rsk.java; public interface Address { String getFirstAddress(); }
13.666667
29
0.731707
b0e4de560f9d88d06ddd92c184a2ce658251a5de
436
import java.util.*; public class A3qno28 { public static int existance(String str,String str1) { if(str.contains(str1)) {//contains method is already O(n) so no need to optimize more as per question return str.indexOf(str1); } return -1; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); String str=sc.nextLine(); String str1=sc.nextLine(); System.out.println(existance(str,str1)); } }
25.647059
103
0.704128
252cdcd46a38c3df6bf27c69c6483407f3096db6
9,822
/******************************************************************************* * Copyright 2016 Antoine Nicolas SAMAHA * * 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.foc.business.notifier; import com.foc.business.printing.PrnLayoutDesc; import com.foc.desc.AutoPopulatable; import com.foc.desc.FocDesc; import com.foc.desc.field.FStringField; import com.foc.desc.field.FBoolField; import com.foc.desc.field.FField; import com.foc.list.FocList; import com.foc.list.FocListOrder; public class FocNotificationEmailTemplateDesc extends FocDesc implements FocNotificationEmailConst, AutoPopulatable { public static final String DB_TABLE_NAME = "NOTIF_EMAIL_TEMPLATE"; //Standard Templates public static final String USER_CREATION_TEMPLATE = "User Creation"; public static final String SUPPLIER_NOTFICATION_NEW_RFQ_TEMPLATE = "Supplier Notification New RFQ"; public static final String RFQ_SUPPLIER_SUBMIT_TEMPLATE = "RFQ Supplier Submit"; public static final String RFQ_SUPPLIER_REJECT_TEMPLATE = "RFQ Supplier Reject"; public static final String RFQ_SUPPLIER_REMINDER_TEMPLATE = "RFQ Supplier Reminder"; public static final String DEFAULT_PDF_PRINTOUT_SENDING = "PDF Printout Sending"; public FocNotificationEmailTemplateDesc() { super(FocNotificationEmailTemplate.class, FocDesc.DB_RESIDENT, DB_TABLE_NAME, false); FField focFld = addReferenceField(); focFld = new FStringField("NAME", "Name", FLD_TEMPLATE_NAME, false, 200); addField(focFld); focFld = new FStringField("SUBJECT", "Subject", FLD_SUBJECT, false, 1000); addField(focFld); focFld = new FStringField("TEXT", "Text", FLD_TEXT, false, 4000); addField(focFld); focFld = new FStringField("RECIPIENTS", "Recipients", FLD_RECIPIENTS, false, 1000); addField(focFld); focFld = new FStringField("BCC", "Bcc", FLD_BCC, false, 1000); addField(focFld); focFld = new FStringField("CC", "cc", FLD_CC, false, 1000); addField(focFld); focFld = new FStringField("LAYOUT_FILE", "File", FLD_PRN_FILE_NAME, false, PrnLayoutDesc.LEN_LAYOUT_FILE_NAME); addField(focFld); focFld = new FBoolField("FORMAT", "Html", FLD_HTML, false); addField(focFld); addIsSystemObjectField(); } @Override public FocList newFocList(){ FocList list = super.newFocList(); list.setDirectlyEditable(false); list.setDirectImpactOnDatabase(true); if(list.getListOrder() == null){ FocListOrder order = new FocListOrder(FLD_TEMPLATE_NAME); list.setListOrder(order); } return list; } public static FocList getList(int mode){ return getInstance().getFocList(mode); } public static FocDesc getInstance() { return getInstance(DB_TABLE_NAME, FocNotificationEmailTemplateDesc.class); } //--------------------------------------------------------- // AUTOPOPULATE //--------------------------------------------------------- private FocNotificationEmailTemplate addEmailTemplate_IfNotExist(FocList list, String name){ FocNotificationEmailTemplate template = (FocNotificationEmailTemplate) list.searchByPropertyStringValue(FLD_TEMPLATE_NAME, name); if(template == null){ template = (FocNotificationEmailTemplate) list.newEmptyItem(); template.setName(name); } return template; } @Override public boolean populate() { FocList list = FocNotificationEmailTemplateDesc.getInstance().getFocList(FocList.LOAD_IF_NEEDED); FocNotificationEmailTemplate template = addEmailTemplate_IfNotExist(list, SUPPLIER_NOTFICATION_NEW_RFQ_TEMPLATE); template.setSystemObject(true); template.setRecipients("$F{SUPPLIER_EMAILLIST}"); template.setSubject("EVERPRO new RFQ [$F{RFQ.CODE}] from $P{CURRENT_COMPANY.NAME}"); StringBuffer buffer = new StringBuffer("Dear $F{SUPPLIER_CONTACT.FULL_NAME},\n"); buffer.append("You have been invited by: '$P{CURRENT_COMPANY.NAME}' "); buffer.append("to bid on a new RFQ ($F{RFQ.CODE}).\n"); buffer.append("\n"); buffer.append("To reply online please follow this link:\n"); buffer.append("$P{URL}\n\n"); buffer.append("You must have already received in a previous email your username and password. If not, please contact '$P{CURRENT_COMPANY.NAME}'"); buffer.append("\n"); buffer.append("Regards,\n"); buffer.append("\n"); buffer.append("DO NOT REPLY TO THIS EMAIL PLEASE\n"); template.setText(buffer.toString()); template.validate(true); template = addEmailTemplate_IfNotExist(list, USER_CREATION_TEMPLATE); template.setSystemObject(true); template.setRecipients("$F{NAME}"); template.setSubject("Congratulations you have a user account at EVERPRO"); buffer = new StringBuffer("Dear $F{CONTACT.FULL_NAME},\n"); buffer.append(" Please find here under the user credential to login to Everpro:\n"); buffer.append(" EVerpro URL: $P{URL}\n"); buffer.append(" \n"); buffer.append(" Username: $F{NAME}\n"); buffer.append(" Password: $F{READABLE_PASSWORD}\n"); buffer.append(" \n"); buffer.append(" Please change your username and password upon login."); buffer.append(" "); buffer.append(" Regards,"); template.setText(buffer.toString()); template.validate(true); template = addEmailTemplate_IfNotExist(list, RFQ_SUPPLIER_SUBMIT_TEMPLATE); template.setSystemObject(true); template.setRecipients("$P{PROCUREMENT_CONFIG.OUR_PROCUREMENT_EMAIL}"); template.setSubject("RFQ Supplier Submit"); buffer = new StringBuffer("Dear $F{COMPANY.NAME},\n"); buffer.append(" We have reviewed your quotation and we decided to $P{MULTIPLE_CHOICE_LABEL(SBMISSION_STATE)} quotation $F{RFQ.CODE}.\n"); buffer.append(" For more info please contact $F{SUPPLIER_CONTACT.FULL_NAME}\n"); buffer.append(" Email: $F{SUPPLIER_CONTACT.ADR_BK_PARTY.EMAIL}\n"); buffer.append(" Phone: $F{SUPPLIER_CONTACT.ADR_BK_PARTY.PHONE1}\n"); buffer.append(" Fax: $F{SUPPLIER_CONTACT.ADR_BK_PARTY.FAX}\n"); buffer.append(" \n"); buffer.append(" "); buffer.append(" Regards,"); template.setText(buffer.toString()); template.validate(true); template = addEmailTemplate_IfNotExist(list, RFQ_SUPPLIER_REJECT_TEMPLATE); template.setSystemObject(true); template.setRecipients("$P{PROCUREMENT_CONFIG.OUR_PROCUREMENT_EMAIL}"); template.setSubject("RFQ Supplier Reject"); buffer = new StringBuffer("Dear $F{COMPANY.NAME},\n"); buffer.append(" We have reviewed your quotation and we decided to $P{MULTIPLE_CHOICE_LABEL(SBMISSION_STATE)} quotation $F{RFQ.CODE} .\n"); buffer.append(" For more info please contact $F{SUPPLIER_CONTACT.FULL_NAME}\n"); buffer.append(" Email: $F{SUPPLIER_CONTACT.ADR_BK_PARTY.EMAIL}\n"); buffer.append(" Phone: $F{SUPPLIER_CONTACT.ADR_BK_PARTY.PHONE1}\n"); buffer.append(" Fax: $F{SUPPLIER_CONTACT.ADR_BK_PARTY.FAX}\n"); buffer.append(" \n"); buffer.append(" "); buffer.append(" Regards,"); template.setText(buffer.toString()); template.validate(true); template = addEmailTemplate_IfNotExist(list, RFQ_SUPPLIER_REMINDER_TEMPLATE); template.setSystemObject(true); template.setRecipients(""); template.setSubject("RFQ Supplier Reminder"); template.setPrintFileName("RFQ Reply / Simple"); buffer = new StringBuffer("Dear $F{SUPPLIER_CONTACT.FULL_NAME},\n"); buffer.append("This email to remind you .\n"); buffer.append("\n"); buffer.append("\n"); buffer.append("$P{CURRENT_COMPANY.NAME}"); buffer.append("egards,"); template.setText(buffer.toString()); template.validate(true); template = addEmailTemplate_IfNotExist(list, DEFAULT_PDF_PRINTOUT_SENDING); template.setSystemObject(true); template.setRecipients(""); template.setSubject("Email sent by $P{CURRENT_COMPANY.NAME} using EVERPRO"); buffer = new StringBuffer("Hello,\n"); buffer.append("\n"); buffer.append("Kindly find the attached document sent to you on behalf of $P{CURRENT_COMPANY.NAME} using EVERPRO software.\n"); buffer.append("\n"); buffer.append("\n"); buffer.append("Regards,"); buffer.append("\n"); buffer.append("\n"); buffer.append("DO NOT REPLY TO THIS EMAIL PLEASE\n"); template.setText(buffer.toString()); template.validate(true); list.validate(true); return false; } @Override public String getAutoPopulatableTitle() { return "e-Mail Templates"; } public static FocNotificationEmailTemplate getFocNotificationEmailTemplateByName(String name){ FocNotificationEmailTemplate focNotificationEmailTemplate = null; if(FocNotificationEmailTemplateDesc.getInstance() != null){ FocList focNotificationEmailTemplateList = FocNotificationEmailTemplateDesc.getInstance().getFocList(); focNotificationEmailTemplate = (FocNotificationEmailTemplate) focNotificationEmailTemplateList.searchByPropertyStringValue(FocNotificationEmailTemplateDesc.FLD_TEMPLATE_NAME, name); } return focNotificationEmailTemplate; } }
43.460177
185
0.695174
c5922665ce221a7f399ce90315054594561ccc5c
3,826
package com.aiden.dev.simpleboard.modules.post; import com.aiden.dev.simpleboard.modules.account.Account; import com.aiden.dev.simpleboard.modules.main.PostService; import com.aiden.dev.simpleboard.modules.post.form.WritePostForm; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import org.modelmapper.ModelMapper; import org.springframework.data.domain.PageRequest; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.*; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) class PostServiceTest { @InjectMocks PostService postService; @Mock PostRepository postRepository; @Spy ModelMapper modelMapper; @DisplayName("모든 게시글 조회 테스트") @Test void getPosts() { // When postService.getPosts(PageRequest.of(0, 10), "aa", null); // Then verify(postRepository).findAll(any(PageRequest.class)); } @DisplayName("제목으로 게시글 조회 테스트") @Test void getPosts_by_title() { // When postService.getPosts(PageRequest.of(0, 10), "title", "test"); // Then verify(postRepository).findByTitleContains(anyString(), any(PageRequest.class)); } @DisplayName("작성자로 게시글 조회 테스트") @Test void getPosts_by_writer() { // When postService.getPosts(PageRequest.of(0, 10), "writer", "test"); // Then verify(postRepository).findByAccount_NicknameContains(anyString(), any(PageRequest.class)); } @DisplayName("게시글 작성 테스트") @Test void writeNewPost() { // Given WritePostForm writePostForm = new WritePostForm(); writePostForm.setTitle("title"); writePostForm.setSecret(false); writePostForm.setContents("contents"); Account account = Account.builder() .loginId("test") .password("test") .nickname("test") .email("test@email.com") .build(); account.generateEmailCheckToken(); // When postService.writeNewPost(writePostForm, account); // Then verify(postRepository).save(any(Post.class)); } @DisplayName("게시글 상세 정보 조회 테스트") @Test void getPostDetail() { // When postService.getPostDetail(1L); // Then verify(postRepository).findById(anyLong()); } @DisplayName("게시글 삭제 테스트") @Test void deletePost() { // When postService.deletePost(1L); // Then verify(postRepository).deleteById(anyLong()); } @DisplayName("게시글 수정 테스트") @Test void updatePost() { // Given Post post = Post.builder() .title("title") .build(); given(postRepository.findById(any())).willReturn(Optional.of(post)); // When postService.updatePost(1L, new WritePostForm()); // Then verify(postRepository).findById(anyLong()); } @DisplayName("조회수 증가 테스트") @Test void increaseHits() { // Given Post post = Post.builder() .title("title") .hits(0L) .build(); // When postService.increaseHits(post); // Then assertThat(post.getHits()).isEqualTo(1); } @DisplayName("특정 사용자 게시글 삭제 테스트") @Test void deleteComments() { // When postService.deletePosts(new Account()); // Then verify(postRepository).deleteByAccount(any(Account.class)); } }
26.386207
99
0.621275
951d556ee637429c2709275cb6206a3a7c52ed55
4,901
/* * 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 ed.biordm.sbol.toolkit.transform; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.sbolstandard.core2.Component; import org.sbolstandard.core2.ComponentDefinition; import org.sbolstandard.core2.SBOLConversionException; import org.sbolstandard.core2.SBOLDocument; import org.sbolstandard.core2.SBOLReader; import org.sbolstandard.core2.SBOLValidationException; import org.sbolstandard.core2.SequenceAnnotation; /** * * @author jhay */ public class TemplateTransformerTestFull { TemplateTransformer templateTransformer = new TemplateTransformer(); SBOLDocument doc; static String SEQUENCE_ONTO_PREF = "http://identifiers.org/so/"; @Before public void generateSBOLDocument() throws IOException, SBOLValidationException, SBOLConversionException { String fName = "cyano_full_template.xml"; File file = new File(getClass().getResource(fName).getFile()); try { doc = SBOLReader.read(file); } catch (IOException e) { e.printStackTrace(); throw e; } doc.setDefaultURIprefix("http://bio.ed.ac.uk/a_mccormick/cyano_source/"); doc.setComplete(true); doc.setCreateDefaults(true); } /** * Test of instantiateFromTemplate method, of class TemplateTransformer. */ @Test public void testInstantiateFromTemplate() throws Exception { SBOLDocument doc = new SBOLDocument(); String defaultURIPrefix = "http://bio.ed.ac.uk/a_mccormick/cyano_source/"; doc.setDefaultURIprefix(defaultURIPrefix); doc.setComplete(true); doc.setCreateDefaults(true); // Test creation of new component definition based on DNA_REGION template ComponentDefinition region = doc.createComponentDefinition("region1", "1.0.0", ComponentDefinition.DNA_REGION); //TopLevel tl = doc.createCopy(region, "region2"); String newName = "region2"; String newVersion = "1.0.1"; String newDescription = "Deep copy of DNA_REGION component"; ComponentDefinition newCmp = templateTransformer.instantiateFromTemplate(region, newName, newVersion, newDescription, doc); assertEquals(newName, newCmp.getDisplayId()); assertEquals(newVersion, newCmp.getVersion()); assertEquals(newDescription, newCmp.getDescription()); assertEquals(region.getTypes(), newCmp.getTypes()); assertEquals(region.getRoles(), newCmp.getRoles()); } /** * Test if the sub-components from the AmpR component definition are properly * copied to the new parent plasmid. */ @Test public void testBackboneSubComponents() throws Exception { String backboneDispId = "backbone"; String version = "1.0.0"; ComponentDefinition backbone = doc.getComponentDefinition(backboneDispId, version); assertNotNull(backbone); for (Component cmp : backbone.getComponents()) { //System.out.println(cmp.getDisplayId()); } for (SequenceAnnotation seqAnn : backbone.getSequenceAnnotations()) { //System.out.println(seqAnn.getDisplayId()); } String templateDispId = "cyano_codA_Km"; String newName = "johnny_cyano_codA_Km"; String desc = "test plasmid from template"; ComponentDefinition templatePlasmid = doc.getComponentDefinition(templateDispId, version); ComponentDefinition newCmp = templateTransformer.instantiateFromTemplate(templatePlasmid, newName, version, desc, doc); String backboneCmpDispId = "backbone"; ComponentDefinition newAmpR = newCmp.getComponent(backboneCmpDispId).getDefinition(); for (Component cmp : newAmpR.getComponents()) { //System.out.println(cmp.getDisplayId()); assertTrue(backbone.getComponents().contains(cmp)); } for (SequenceAnnotation seqAnn : newAmpR.getSequenceAnnotations()) { //System.out.println(seqAnn.getDisplayId()); assertTrue(backbone.getSequenceAnnotations().contains(seqAnn)); } for (Component cmp : newCmp.getSortedComponents()) { System.out.println(cmp.getDisplayId()); ComponentDefinition curCmpDef = cmp.getDefinition(); System.out.println(curCmpDef.getDisplayId()); for (SequenceAnnotation seqAnn : curCmpDef.getSequenceAnnotations()) { System.out.println(seqAnn.getDisplayId()); } } } }
36.849624
119
0.686595
9d02209ca0018a845a528451e9805a446438141b
250
package cn.edu.jxnu.design.adapter; public class Adapter extends Adaptee implements TargetInterface { @Override public void standardApiForCurrentSystem() { super.specificApiForCurrentSystem();// 使用源类的特殊功能,加以包装 } //// 适配器类,继承了被适配类,同时实现标准接口 }
20.833333
65
0.78
d6ea25ea94802c7d9414ce5317adf96d4f4ce1ad
914
package graph; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; public class Download_File { /** * Downloads files and returns string representation * @param url to download from * @return string representation * @throws Exception */ public static String downloadFile(String url) throws Exception { URL website = new URL(url); URLConnection connection = website.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( connection.getInputStream())); StringBuilder response = new StringBuilder(); String inputLine; while ((inputLine = in.readLine()) != null) response.append(inputLine + "\n"); in.close(); return response.toString(); } }
27.69697
68
0.62035
9a6ba5df65f832872cc3ac505a8d264db4c40c63
5,455
package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.Multiset.Entry; import com.google.common.primitives.Ints; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import javax.annotation.Nullable; @GwtCompatible(emulated = true, serializable = true) public abstract class ImmutableMultiset<E> extends ImmutableCollection<E> implements Multiset<E> { private static final ImmutableMultiset<Object> EMPTY = new RegularImmutableMultiset(ImmutableMap.of(), 0); private transient ImmutableSet<Entry<E>> entrySet; abstract Entry<E> getEntry(int i); public static <E> ImmutableMultiset<E> of() { return EMPTY; } public static <E> ImmutableMultiset<E> of(E element) { return copyOfInternal(element); } public static <E> ImmutableMultiset<E> of(E e1, E e2) { return copyOfInternal(e1, e2); } public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3) { return copyOfInternal(e1, e2, e3); } public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4) { return copyOfInternal(e1, e2, e3, e4); } public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4, E e5) { return copyOfInternal(e1, e2, e3, e4, e5); } public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E... others) { return new Builder().add(e1).add(e2).add(e3).add(e4).add(e5).add(e6).add(others).build(); } public static <E> ImmutableMultiset<E> copyOf(E[] elements) { return copyOf(Arrays.asList(elements)); } public static <E> ImmutableMultiset<E> copyOf(Iterable<? extends E> elements) { if (elements instanceof ImmutableMultiset) { ImmutableMultiset<E> result = (ImmutableMultiset) elements; if (!result.isPartialView()) { return result; } } return copyOfInternal(elements instanceof Multiset ? Multisets.cast(elements) : LinkedHashMultiset.create(elements)); } private static <E> ImmutableMultiset<E> copyOfInternal(E... elements) { return copyOf(Arrays.asList(elements)); } private static <E> ImmutableMultiset<E> copyOfInternal(Multiset<? extends E> multiset) { return copyFromEntries(multiset.entrySet()); } static <E> ImmutableMultiset<E> copyFromEntries(Collection<? extends Entry<? extends E>> entries) { long size = 0; Builder<E, Integer> builder = ImmutableMap.builder(); for (Entry<? extends E> entry : entries) { int count = entry.getCount(); if (count > 0) { builder.put(entry.getElement(), Integer.valueOf(count)); size += (long) count; } } if (size == 0) { return of(); } return new RegularImmutableMultiset(builder.build(), Ints.saturatedCast(size)); } public static <E> ImmutableMultiset<E> copyOf(Iterator<? extends E> elements) { Multiset multiset = LinkedHashMultiset.create(); Iterators.addAll(multiset, elements); return copyOfInternal(multiset); } ImmutableMultiset() { } public UnmodifiableIterator<E> iterator() { return new 1(this, entrySet().iterator()); } public boolean contains(@Nullable Object object) { return count(object) > 0; } public boolean containsAll(Collection<?> targets) { return elementSet().containsAll(targets); } @Deprecated public final int add(E e, int occurrences) { throw new UnsupportedOperationException(); } @Deprecated public final int remove(Object element, int occurrences) { throw new UnsupportedOperationException(); } @Deprecated public final int setCount(E e, int count) { throw new UnsupportedOperationException(); } @Deprecated public final boolean setCount(E e, int oldCount, int newCount) { throw new UnsupportedOperationException(); } @GwtIncompatible("not present in emulated superclass") int copyIntoArray(Object[] dst, int offset) { Iterator i$ = entrySet().iterator(); while (i$.hasNext()) { Entry<E> entry = (Entry) i$.next(); Arrays.fill(dst, offset, entry.getCount() + offset, entry.getElement()); offset += entry.getCount(); } return offset; } public boolean equals(@Nullable Object object) { return Multisets.equalsImpl(this, object); } public int hashCode() { return Sets.hashCodeImpl(entrySet()); } public String toString() { return entrySet().toString(); } public ImmutableSet<Entry<E>> entrySet() { ImmutableSet<Entry<E>> immutableSet = this.entrySet; if (immutableSet != null) { return immutableSet; } immutableSet = createEntrySet(); this.entrySet = immutableSet; return immutableSet; } private final ImmutableSet<Entry<E>> createEntrySet() { return isEmpty() ? ImmutableSet.of() : new EntrySet(this, null); } Object writeReplace() { return new SerializedForm(this); } public static <E> Builder<E> builder() { return new Builder(); } }
31.715116
125
0.63648
c74bb8f28195660f33036e5427f16d0c34b758a0
3,208
package com.gmail.borlandlp.minigamesdtools.config; import com.gmail.borlandlp.minigamesdtools.MinigamesDTools; import java.io.File; public enum ConfigPath { MAIN(new File(MinigamesDTools.getInstance().getDataFolder(), "config.yml"), false, "main"), MESSAGES(new File(MinigamesDTools.getInstance().getDataFolder(), "messages.yml"), false, "messages"), CONDITIONS(new File(MinigamesDTools.getInstance().getDataFolder(), "conditions.yml"), false, "conditions"), CACHE_POINTS(new File(MinigamesDTools.getInstance().getDataFolder(), "cache" + File.separator + "points"), true, "cache_points"), TEAMS(new File(MinigamesDTools.getInstance().getDataFolder(), "teams.yml"), false, "teams"), ARENA_FOLDER(new File(MinigamesDTools.getInstance().getDataFolder(), "arenas"), true, "arenas"), HOTBAR_SLOTS(new File(MinigamesDTools.getInstance().getDataFolder().getAbsoluteFile(), "hotbarslots.yml"), false, "hotbar_slots"), HOTBAR(new File(MinigamesDTools.getInstance().getDataFolder().getAbsoluteFile(), "hotbars.yml"), false, "hotbar"), ACTIVE_POINT(new File(MinigamesDTools.getInstance().getDataFolder().getAbsoluteFile(), "activepoints.yml"), false, "active_point"), ACTIVE_POINT_REACTIONS(new File(MinigamesDTools.getInstance().getDataFolder().getAbsoluteFile(), "activepointsreactions.yml"), false, "active_point_reactions"), ACTIVE_POINT_BEHAVIORS(new File(MinigamesDTools.getInstance().getDataFolder().getAbsoluteFile(), "activepointbehaviors.yml"), false, "active_point_behaviors"), SCENARIO_CHAIN(new File(MinigamesDTools.getInstance().getDataFolder().getAbsoluteFile(), "scenariochain.yml"), false, "scenario_chain"), SCENARIO(new File(MinigamesDTools.getInstance().getDataFolder().getAbsoluteFile(), "scenario.yml"), false, "scenario"), ARENA_LOBBY(new File(MinigamesDTools.getInstance().getDataFolder().getAbsoluteFile(), "arena_lobby.yml"), false, "arena_lobby"), SERVER_LOBBY(new File(MinigamesDTools.getInstance().getDataFolder().getAbsoluteFile(), "lobby.yml"), false, "server_lobby"), ADDONS(new File(MinigamesDTools.getInstance().getDataFolder().getAbsoluteFile(), "addons"), true, "addons"), INVENTORY_GUI(new File(MinigamesDTools.getInstance().getDataFolder().getAbsoluteFile(), "inventory_gui.yml"), false, "inventory_gui"), INVENTORY_GUI_SLOT(new File(MinigamesDTools.getInstance().getDataFolder().getAbsoluteFile(), "inventory_gui_slot.yml"), false, "inventory_gui_slot"), BULLETS(new File(MinigamesDTools.getInstance().getDataFolder().getAbsoluteFile(), "bullets.yml"), false, "bullets"); private File path; private boolean isDir; private String typeId; ConfigPath(File p, boolean isDirectory, String typeId) { this.isDir = isDirectory; this.path = p; this.typeId = typeId; } public boolean isDir() { return isDir; } public File getPath() { return path; } public String getTypeId() { return typeId; } public static ConfigPath getByPoolId(String pool_id) { for (ConfigPath path : ConfigPath.values()) { if(path.getTypeId().equals(pool_id)) return path; } return null; } }
55.310345
164
0.727868
354c9be010a1a770c84a32a5d5a7dfa15d658998
3,903
import java.lang.Math.*; // matematica import java.util.Scanner; import java.util.Objects; import java.math.RoundingMode; // arredondamento de casas decimais import java.text.DecimalFormat; // arredondamento de casas decimais public class P1nX { private static DecimalFormat df2 = new DecimalFormat("#.##"); // objeto de formato de duas casas decimais private static double calcula(double r) // metodo de classe de calculo da area do circulo { double resultado = Math.PI * r * r; System.out.println ("A area do circulo e': " + df2.format(resultado) + " unidades de area."); return resultado; } private static double calcula(double b, double a) // metodo de classe de calculo da area do retangulo { double resultado = a * b; System.out.println ("A area do retangulo e': " + df2.format(resultado) + " unidades de area."); return resultado; } private static double calcula(double l1, double l2, double l3) // metodo de classe de calculo da area do triangulo { double s, area = 0; int ok; if (l1 + l2 <= l3 || l1 + l3 <= l2 || l2 + l3 <= l1) // verifica se e' triangulo { ok = 0; // triangulo invalido System.out.println("Nao forma um triangulo."); } else { ok = 1; // triangulo valido } if(ok==1) { s = (l1+l2+l3)/2; area = Math.sqrt(s*(s-l1)*(s-l2)*(s-l3)); System.out.println("A area do triangulo e': "+ df2.format(area) +" unidades de area."); } return area; } private static void classifica(double l1, double l2, double l3) // metodo de classe de classificacao do triangulo { int ok; if (l1 + l2 <= l3 || l1 + l3 <= l2 || l2 + l3 <= l1) // verifica se e' triangulo { ok = 0; // triangulo invalido } else { ok = 1; // triangulo valido } if(ok==1) { // Verifica triangulo equilatero if (l1 == l2 && l2 == l3 ) System.out.println("O triangulo e' equilatero."); // Verifica triangulo isosceles else if (l1 == l2 || l2 == l3 || l3 == l1 ) System.out.println("O triangulo e' isosceles."); // Senao e' triangulo escaleno else System.out.println("O triangulo e' escaleno."); } } public static void main (String[]args) { if (args.length==0) // se nao houver argumentos { System.out.println("Numero de argumentos insuficiente"); } if (args.length>=4) // se o numero de argumentos for igual ou maior a quatro { System.out.println("Numero de argumentos excessivo"); } boolean valido = true; for (int i = 0; i < args.length; i++) // loop de verificacao de validade dos argumentos { boolean numeric = true; try { // verifica se e' numero Double num = Double.parseDouble(args[i]); } catch (NumberFormatException e) { numeric = false; valido = false; } if (!numeric) // se nao e' numero imprime a linha abaixo { System.out.println((i+1)+"o argumento, “"+ args[i] +"”, nao eh numero"); } } if(valido) { if (args.length==1) // se ha um argumento, e' um circulo { double a1 = Double.parseDouble(args[0]); // conversao de string para double calcula(a1); } if (args.length==2) // se ha dois argumentos, e' um retangulo { double b1 = Double.parseDouble(args[0]); // conversoes de string para double double b2 = Double.parseDouble(args[1]); calcula(b1, b2); } if (args.length==3) // se ha tres argumentos e' um triangulo { double c1 = Double.parseDouble(args[0]); // conversoes de string para double double c2 = Double.parseDouble(args[1]); double c3 = Double.parseDouble(args[2]); calcula(c1, c2, c3); classifica(c1, c2, c3); } } } }
28.911111
119
0.585447
26d528fb285b76633fc38d1e503c38156dd3871e
4,420
package com.example.EcommerceApp.order; import com.example.EcommerceApp.product.model.CannotBuyOwnProductException; import com.example.EcommerceApp.product.model.Product; import com.example.EcommerceApp.product.service.ProductService; import com.example.EcommerceApp.security.model.User; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.core.parameters.P; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class OrderServiceTest { @Mock private OrderRepository orderRepository; @Mock private ProductService productService; @InjectMocks private OrderService orderService; @Test public void should_register_valid_order() { // given Product product = new Product(); product.setFullName("product's fullname"); List<Product> products = List.of( product ); ClientData clientData = new ClientData(); clientData.setFirstName("first name"); User user = new User("username","passwd","email@em.pl"); ProductOrder order = new ProductOrder(); order.setClientData(clientData); when(orderRepository.save(order)).thenReturn(order); // when orderService.registerOrder(order,products,user); // then verify(orderRepository,times(1)).save(order); } @Test public void should_throw_when_empty_cart() { // given List<Product> products = new LinkedList<>(); ClientData clientData = new ClientData(); clientData.setFirstName("first name"); User user = new User("username","passwd","email@em.pl"); ProductOrder order = new ProductOrder(); order.setClientData(clientData); // when + then assertThatThrownBy(() -> { orderService.registerOrder(order, products, user); }).isInstanceOf(OrderWithEmptyCartException.class); verify(orderRepository,times(0)).save(order); } @Test public void should_throw_when_product_is_already_present_in_cart() { // given Long dupId = 1L; Product product = new Product(); product.setId(dupId); product.setFullName("product's fullname"); List<Product> products = List.of( product ); when(productService.findProduct(1L)).thenReturn(product); // when + then assertThatThrownBy(() -> { orderService.addProductToCart(dupId,products); }).isInstanceOf(ProductAlreadyPresentInCart.class).hasMessageContaining(Long.toString(dupId)); } @Test public void should_add_product_to_cart() { // given Product product = new Product(); product.setId(1L); product.setFullName("product's fullname"); List<Product> products = new ArrayList<>(); products.add(product); Long id = 2L; Product newProduct = new Product(); newProduct.setId(id); newProduct.setFullName("product 2"); when(productService.findProduct(id)).thenReturn(newProduct); // when orderService.addProductToCart(id,products); // then assertThat(products).contains(newProduct); } @Test public void should_throw_when_trying_to_buy_own_product() { // given Product product1 = new Product(); product1.setId(1L); product1.setFullName("product1"); Product product2 = new Product(); product2.setId(2L); product2.setFullName("product2"); List<Product> cart = List.of(product1,product2); List<Product> own = List.of(product1); User user = new User("usrnme","passwd","em@em.em"); when(productService.findByUser(user)).thenReturn(own); // when assertThatThrownBy(() -> { orderService.validateProductList(cart,user); }).isInstanceOf(CannotBuyOwnProductException.class).hasMessageContaining(Long.toString(product1.getId())); } }
25.549133
114
0.659955
aa8ddc57cd3f2e0fef06066a090fc755b969d5ed
2,199
package leetcode.review; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author: wyj * @date: 2021/07/12 */ public class R18_1 { //给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + // d 的值与 target 相等?找出所有满足条件且不重复的四元组。 // 注意:答案中不可以包含重复的四元组。 // 示例 1: //输入:nums = [1,0,-1,0,-2,2], target = 0 //输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] // 示例 2: //输入:nums = [], target = 0 //输出:[] /** * 执行耗时:139 ms,击败了6.44% 的Java用户 * 内存消耗:38.9 MB,击败了44.16% 的Java用户 */ public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> list=new ArrayList<>(); Arrays.sort(nums); for (int a = 0; a < nums.length-3; a++) { if(a-1>=0&&nums[a]==nums[a-1]){ continue; } for (int b=a+1;b<nums.length-2;b++){ if(b-1>=a+1&&nums[b]==nums[b-1]){ continue; } for (int c=b+1;c<nums.length-1;c++){ if(c-1>=b+1&&nums[c]==nums[c-1]){ continue; } for(int d=c+1;d<nums.length;d++){ if(d-1>=c+1&&nums[d]==nums[d-1]){ continue; } //因为是从最小起步的因此,一旦四数之和比target大,就没有继续的必要 if(nums[a]+nums[b]+nums[c]+nums[d]>target){ break; }else if(nums[a]+nums[b]+nums[c]+nums[d]==target){ List<Integer> tmp=new ArrayList<>(); tmp.add(nums[a]); tmp.add(nums[b]); tmp.add(nums[c]); tmp.add(nums[d]); list.add(tmp); } } } } } return list; } public static void main(String[] args) { List<List<Integer>> list = new R18_1().fourSum(new int[]{1, 0, -1, 0, -2, 2}, 0); for (List<Integer> integers : list) { System.out.println(integers); } } }
31.414286
89
0.411551
d40a01f9d66ece72848b213fa78cae82fb88f3b8
1,098
package com.nevergetme.autumn.tencent.solution08; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[] a = new int[n]; int[] pos = new int[n]; pos[0] = m; int sum = 0; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); sum += a[i]; } int time = 1; int maxpos = 0; while (sum > 0) { for (int i = Math.min(maxpos, n - 1); i >= 0; i--) { if (a[i] >= pos[i]) { a[i] -= pos[i]; sum -= pos[i]; } else { if (i + 1 < n) { pos[i + 1] += (pos[i] - a[i]); } pos[i] = a[i]; sum -= a[i]; a[i] = 0; maxpos = Math.max(i + 1, maxpos); } } time++; } System.out.println(time); } }
27.45
64
0.343352
233aff770354a2b0bd2c872d575579c95112775e
3,583
/* * MIT License * * Copyright (c) 2014-2018 David Moskowitz * * 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.infoblazer.gp.application.syntheticdata.generator; import java.util.Random; /** * Created by David on 9/20/2015. */ public class GenerateMGHENMG implements SyntheticDataGenerator { public Double[][] generate() { Double randomVals[] = new Double[] { 0.8440964138066118, 0.9532661055224593, 0.06636753866027945, 0.8620971393379627, 0.2100850778694464, 0.4894196903422636, 0.11588139131258257, 0.47264417635200906, 0.08408151444136325, 0.5657337444733351, 0.695537452821834, 0.6371301993098292, 0.11797947216718663, 0.6643411155833825, 0.35853611038911015, 0.8617986087216263, 0.028791106927193777, 0.8136196388158929, 0.01620324342793167, 0.6569433423303102, 0.2871394142441621, 0.10838147285823774, 0.43001491262576674, 0.47020747316392664, 0.5455742442961969, 0.859267154912505, 0.5342809689449174, 0.3258840447272048, 0.5628455094036957, 0.46854285555526787, 0.6234535818110518 } ; Double[] mg = new Double[1200]; for (int i = 0; i < 31; i++) { mg[i] = randomVals[i]; } for (int i = 31; i < 1200; i++) { mg[i] = mg[i - 1] + 0.2 * mg[i - 31] / (1 + Math.pow(mg[i - 31], 10)) - 0.1 * mg[i - 1]; } Double[][] result = new Double[401][2]; Double y; for (int x = 0; x < 401; x++) { result[x][0] = Double.valueOf(x); if (x <= 200) { //LG , seeded off initial generation y = mg[999 + x]; } else if (x > 300) { y = result[x - 1][1] + 0.2 * result[x - 31][1] / (1 + Math.pow(result[x - 31][1], 10)) - 0.1 * result[x - 1][1]; } else { //OZ y = 0.3 * result[x - 2][1] + 1 - 1.4 * (result[x - 1][1] * result[x - 1][1]); } result[x][1] = y; } return result; } }
35.127451
128
0.54005
efc5ae74820717569b70b9af7d697fe1916162ac
4,376
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2011, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc.. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.metamodel.source.annotations.xml.mocker; import org.jboss.logging.Logger; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.jaxb.mapping.orm.JaxbAccessType; import org.hibernate.internal.jaxb.mapping.orm.JaxbAttributes; import org.hibernate.internal.jaxb.mapping.orm.JaxbEntityListeners; import org.hibernate.internal.jaxb.mapping.orm.JaxbIdClass; import org.hibernate.internal.jaxb.mapping.orm.JaxbMappedSuperclass; import org.hibernate.internal.jaxb.mapping.orm.JaxbPostLoad; import org.hibernate.internal.jaxb.mapping.orm.JaxbPostPersist; import org.hibernate.internal.jaxb.mapping.orm.JaxbPostRemove; import org.hibernate.internal.jaxb.mapping.orm.JaxbPostUpdate; import org.hibernate.internal.jaxb.mapping.orm.JaxbPrePersist; import org.hibernate.internal.jaxb.mapping.orm.JaxbPreRemove; import org.hibernate.internal.jaxb.mapping.orm.JaxbPreUpdate; /** * Mock <mapped-superclass> to {@link javax.persistence.MappedSuperclass @MappedSuperClass} * * @author Strong Liu */ class MappedSuperclassMocker extends AbstractEntityObjectMocker { private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, MappedSuperclassMocker.class.getName() ); private JaxbMappedSuperclass mappedSuperclass; MappedSuperclassMocker(IndexBuilder indexBuilder, JaxbMappedSuperclass mappedSuperclass, EntityMappingsMocker.Default defaults) { super( indexBuilder, defaults ); this.mappedSuperclass = mappedSuperclass; } @Override protected void applyDefaults() { DefaultConfigurationHelper.INSTANCE.applyDefaults( mappedSuperclass, getDefaults() ); } @Override protected void processExtra() { create( MAPPED_SUPERCLASS ); } @Override protected JaxbAttributes getAttributes() { return mappedSuperclass.getAttributes(); } @Override protected JaxbAccessType getAccessType() { return mappedSuperclass.getAccess(); } @Override protected boolean isMetadataComplete() { return mappedSuperclass.isMetadataComplete() != null && mappedSuperclass.isMetadataComplete(); } @Override protected boolean isExcludeDefaultListeners() { return mappedSuperclass.getExcludeDefaultListeners() != null; } @Override protected boolean isExcludeSuperclassListeners() { return mappedSuperclass.getExcludeSuperclassListeners() != null; } @Override protected JaxbIdClass getIdClass() { return mappedSuperclass.getIdClass(); } @Override protected JaxbEntityListeners getEntityListeners() { return mappedSuperclass.getEntityListeners(); } protected String getClassName() { return mappedSuperclass.getClazz(); } @Override protected JaxbPrePersist getPrePersist() { return mappedSuperclass.getPrePersist(); } @Override protected JaxbPreRemove getPreRemove() { return mappedSuperclass.getPreRemove(); } @Override protected JaxbPreUpdate getPreUpdate() { return mappedSuperclass.getPreUpdate(); } @Override protected JaxbPostPersist getPostPersist() { return mappedSuperclass.getPostPersist(); } @Override protected JaxbPostUpdate getPostUpdate() { return mappedSuperclass.getPostUpdate(); } @Override protected JaxbPostRemove getPostRemove() { return mappedSuperclass.getPostRemove(); } @Override protected JaxbPostLoad getPostLoad() { return mappedSuperclass.getPostLoad(); } }
30.601399
130
0.791819
5c6c2a199507558e419f7949c4d033d9b9cbce12
3,021
package chav1961.bt.mnemoed.entities; import java.awt.geom.AffineTransform; import java.io.IOException; import chav1961.purelib.basic.exceptions.PrintingException; import chav1961.purelib.basic.exceptions.SyntaxException; import chav1961.purelib.streams.JsonStaxParser; import chav1961.purelib.streams.JsonStaxPrinter; import chav1961.purelib.streams.interfaces.JsonStaxParserLexType; public class LocationProp extends AffineEntityProp { private PrimitiveValueSource xLocation; private PrimitiveValueSource yLocation; public LocationProp(final PrimitiveValueSource xLocation, final PrimitiveValueSource yLocation) { if (xLocation == null) { throw new NullPointerException("X location can't be null"); } else if (yLocation == null) { throw new NullPointerException("Y Location can't be null"); } else { this.xLocation = xLocation; this.yLocation = yLocation; } } @Override public AffineTransform getAffineTransform() { return AffineTransform.getTranslateInstance(0, 0); } public PrimitiveValueSource getXLocation() { return xLocation; } public void setXLocation(final PrimitiveValueSource xLocation) throws NullPointerException { if (xLocation == null) { throw new NullPointerException("X location to set can't be null"); } else { this.xLocation = xLocation; } } public PrimitiveValueSource getYLocation() { return yLocation; } public void setYLocation(final PrimitiveValueSource yLocation) throws NullPointerException { if (xLocation == null) { throw new NullPointerException("X location to set can't be null"); } else { this.yLocation = yLocation; } } @Override public void upload(final JsonStaxPrinter printer) throws PrintingException, IOException { if (printer == null) { throw new NullPointerException("Stax printer can't be null"); } else { printer.startArray(); printer.startObject().name(getArgType(xLocation.getClass()).name()); xLocation.upload(printer); printer.endObject(); printer.startObject().name(getArgType(yLocation.getClass()).name()); yLocation.upload(printer); printer.endObject(); printer.endArray(); } } @Override public void download(final JsonStaxParser parser) throws SyntaxException, IOException { if (parser.current() == JsonStaxParserLexType.START_ARRAY) { parser.next(); setXLocation(parsePrimitiveValueSource(parser)); if (parser.current() == JsonStaxParserLexType.LIST_SPLITTER) { parser.next(); setYLocation(parsePrimitiveValueSource(parser)); } else { throw new SyntaxException(parser.row(), parser.col(), "',' is missing"); } if (parser.current() == JsonStaxParserLexType.END_ARRAY) { parser.next(); } else { throw new SyntaxException(parser.row(), parser.col(), "']' is missing"); } } else { throw new SyntaxException(parser.row(), parser.col(), "'[' is missing"); } } @Override public String toString() { return "LocationProp [xLocation=" + xLocation + ", yLocation=" + yLocation + "]"; } }
28.5
98
0.731546
cdd53fb475675a40c8424ca0e461cce4d35ebc75
525
package org.jboss.resteasy.test.resource.path.resource; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; @Path("resource") public class LocatorWithClassHierarchyLocatorResource extends LocatorWithClassHierarchyMiddleResource { @Path("locator/{id1}/{id2}") public LocatorWithClassHierarchyMiddleResource locatorHasArguments(@PathParam("id1") String id1, @PathParam("id2") String id2) { return new LocatorWithClassHierarchyMiddleResource(id1, id2); } }
35
103
0.72381
f1a0258821672b6812a268e0bdace28822fe012e
5,698
package au.com.codeka.warworlds.server.ctrl; import java.sql.Statement; import java.util.ArrayList; import org.joda.time.DateTime; import au.com.codeka.common.model.BaseBuilding; import au.com.codeka.common.model.BuildingDesign; import au.com.codeka.common.model.DesignKind; import au.com.codeka.warworlds.server.RequestException; import au.com.codeka.warworlds.server.data.SqlResult; import au.com.codeka.warworlds.server.data.SqlStmt; import au.com.codeka.warworlds.server.data.Transaction; import au.com.codeka.warworlds.server.model.Building; import au.com.codeka.warworlds.server.model.BuildingPosition; import au.com.codeka.warworlds.server.model.Colony; import au.com.codeka.warworlds.server.model.DesignManager; import au.com.codeka.warworlds.server.model.Star; public class BuildingController { private DataBase db; public BuildingController() { db = new DataBase(); } public BuildingController(Transaction trans) { db = new DataBase(trans); } public Building createBuilding(Star star, Colony colony, String designID, String notes) throws RequestException { try { Building building = new Building(star, colony, designID, notes); db.createBuilding(colony, building); colony.getBuildings().add(building); // TODO: hard-coded? if (building.getDesignID().equals("hq")) { new EmpireController().setHomeStar(colony.getEmpireID(), star.getID()); } return building; } catch(Exception e) { throw new RequestException(e); } } public Building upgradeBuilding(Star star, Colony colony, int buildingID) throws RequestException { Building existingBuilding = null; for (BaseBuilding building : colony.getBuildings()) { if (((Building) building).getID() == buildingID) { existingBuilding = (Building) building; break; } } if (existingBuilding == null) { throw new RequestException(404); } BuildingDesign design = (BuildingDesign) DesignManager.i.getDesign(DesignKind.BUILDING, existingBuilding.getDesignID()); if (existingBuilding.getLevel() > design.getUpgrades().size()) { return existingBuilding; } try { db.upgradeBuilding(existingBuilding); return existingBuilding; } catch(Exception e) { throw new RequestException(e); } } public ArrayList<BuildingPosition> getBuildings(int empireID, long minSectorX, long minSectorY, long maxSectorX, long maxSectorY) throws RequestException { try { return db.getBuildings(empireID, minSectorX, minSectorY, maxSectorX, maxSectorY); } catch(Exception e) { throw new RequestException(e); } } private static class DataBase extends BaseDataBase { public DataBase() { super(); } public DataBase(Transaction trans) { super(trans); } public void createBuilding(Colony colony, Building building) throws Exception { String sql = "INSERT INTO buildings (star_id, colony_id, empire_id," + " design_id, build_time, level, notes)" + " VALUES (?, ?, ?, ?, ?, ?, ?)"; try (SqlStmt stmt = prepare(sql, Statement.RETURN_GENERATED_KEYS)) { stmt.setInt(1, colony.getStarID()); stmt.setInt(2, colony.getID()); stmt.setInt(3, colony.getEmpireID()); stmt.setString(4, building.getDesignID()); stmt.setDateTime(5, DateTime.now()); stmt.setInt(6, 1); stmt.setString(7, building.getNotes()); stmt.update(); building.setID(stmt.getAutoGeneratedID()); } } public void upgradeBuilding(Building building) throws Exception { String sql = "UPDATE buildings SET level = level+1 WHERE id = ?"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, building.getID()); stmt.update(); building.setLevel(building.getLevel()+1); } } public ArrayList<BuildingPosition> getBuildings(int empireID, long minSectorX, long minSectorY, long maxSectorX, long maxSectorY) throws Exception { String sql = "SELECT buildings.*, sectors.x AS sector_x, sectors.y AS sector_y," + " stars.x AS offset_x, stars.y AS offset_y " + " FROM buildings" + " INNER JOIN stars ON buildings.star_id = stars.id" + " INNER JOIN sectors ON stars.sector_id = sectors.id" + " WHERE buildings.empire_id = ?" + " AND sectors.x >= ? AND sectors.x <= ?" + " AND sectors.y >= ? AND sectors.y <= ?"; try (SqlStmt stmt = prepare(sql)) { stmt.setInt(1, empireID); stmt.setLong(2, minSectorX); stmt.setLong(3, maxSectorX); stmt.setLong(4, minSectorY); stmt.setLong(5, maxSectorY); SqlResult res = stmt.select(); ArrayList<BuildingPosition> buildings = new ArrayList<BuildingPosition>(); while (res.next()) { buildings.add(new BuildingPosition(res)); } return buildings; } } } }
39.846154
128
0.580379
ee1d2f695bc20e9db78988742689cc9963ccb129
18,526
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package nl.uva.cs.lobcder.rest; import lombok.AllArgsConstructor; import lombok.Data; import lombok.extern.java.Log; import nl.uva.cs.lobcder.auth.MyPrincipal; import nl.uva.cs.lobcder.auth.Permissions; import nl.uva.cs.lobcder.resources.LogicalData; import nl.uva.cs.lobcder.resources.PDRIDescr; import nl.uva.cs.lobcder.rest.wrappers.LogicalDataWrapped; import nl.uva.cs.lobcder.util.CatalogueHelper; import nl.uva.cs.lobcder.util.Constants; import nl.uva.cs.lobcder.util.GridHelper; import nl.uva.cs.lobcder.util.PropertiesHelper; import javax.annotation.Nonnull; import javax.naming.NamingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.*; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.logging.Level; /** * @author dvasunin */ @Log @Path("items/") public class Items extends CatalogueHelper { private int defaultRowLimit; @Context UriInfo info; @Context HttpServletRequest request; @Context HttpServletResponse servletResponse; public Items() throws NamingException, IOException { defaultRowLimit = PropertiesHelper.getDefaultRowLimit(); } @Data @AllArgsConstructor class MyData { Long uid; String path; } private List<LogicalDataWrapped> queryLogicalData(MyData myData, int limit, PreparedStatement ps1, PreparedStatement ps2, MyPrincipal mp, Connection cn) throws Exception { List<LogicalDataWrapped> ldwl = new LinkedList<>(); Queue<MyData> dirs = new LinkedList<>(); dirs.offer(myData); MyData dir; while((dir = dirs.poll()) != null) { ps1.setLong(1, dir.getUid()); ps1.setInt(20, limit + 1); try (ResultSet resultSet = ps1.executeQuery()) { while (resultSet.next()) { Long uid = resultSet.getLong(1); String datatype = resultSet.getString(4); String ldName = resultSet.getString(5); String owner = resultSet.getString(3); Permissions p = getCatalogue().getPermissions(uid, owner, cn); if (mp.canRead(p) && uid != 1) { LogicalData logicalData = new LogicalData(); logicalData.setUid(uid); logicalData.setParentRef(myData.getUid()); logicalData.setOwner(owner); logicalData.setType(datatype); logicalData.setName(ldName); logicalData.setCreateDate(resultSet.getTimestamp(6).getTime()); logicalData.setModifiedDate(resultSet.getTimestamp(7).getTime()); logicalData.setLength(resultSet.getLong(8)); logicalData.setContentTypesAsString(resultSet.getString(9)); logicalData.setPdriGroupId(resultSet.getLong(10)); logicalData.setSupervised(resultSet.getBoolean(11)); logicalData.setChecksum(resultSet.getString(12)); logicalData.setLastValidationDate(resultSet.getLong(13)); logicalData.setLockTokenID(resultSet.getString(14)); logicalData.setLockScope(resultSet.getString(15)); logicalData.setLockType(resultSet.getString(16)); logicalData.setLockedByUser(resultSet.getString(17)); logicalData.setLockDepth(resultSet.getString(18)); logicalData.setLockTimeout(resultSet.getLong(19)); logicalData.setDescription(resultSet.getString(20)); logicalData.setDataLocationPreference(resultSet.getString(21)); logicalData.setStatus(resultSet.getString(22)); LogicalDataWrapped ldw = new LogicalDataWrapped(); ldw.setLogicalData(logicalData); ldw.setPermissions(p); ldw.setPath(myData.getPath().concat("/").concat(logicalData.getName())); if (!logicalData.isFolder() && mp.isAdmin()) { List<PDRIDescr> pdriDescr = getCatalogue().getPdriDescrByGroupId(logicalData.getPdriGroupId(), cn); for (PDRIDescr pdri : pdriDescr) { if (pdri.getResourceUrl().startsWith("lfc") || pdri.getResourceUrl().startsWith("srm") || pdri.getResourceUrl().startsWith("gftp")) { pdriDescr.remove(pdri); GridHelper.initGridProxy(pdri.getUsername(), pdri.getPassword(), null, false); pdri.setPassword(GridHelper.getProxyAsBase64String()); pdriDescr.add(pdri); } } ldw.setPdriList(pdriDescr); } ldwl.add(ldw); limit--; } if(limit == 0) break; } } if(limit != 0) { ps2.setLong(1, dir.getUid()); try(ResultSet resultSet = ps2.executeQuery()){ while (resultSet.next()) { Long myUid = resultSet.getLong(1); String myOwner = resultSet.getString(2); String myPath = dir.getPath().concat("/").concat(resultSet.getString(3)); Permissions p = getCatalogue().getPermissions(myUid, myOwner, cn); if (mp.canRead(p) && myUid != 1) { dirs.offer(new MyData(myUid, myPath)); } } } } else { break; } } return ldwl; } private List<LogicalDataWrapped> queryLogicalData(@Nonnull MyPrincipal mp, @Nonnull Connection cn) throws Exception { MultivaluedMap<String, String> queryParameters = info.getQueryParameters(); boolean addFlag = true; String rootPath = (queryParameters.containsKey("path") && queryParameters.get("path").iterator().hasNext()) ? queryParameters.get("path").iterator().next() : "/"; if (!rootPath.equals("/") && rootPath.endsWith("/")) { rootPath = rootPath.substring(0, rootPath.length() - 1); } int rowLimit; try { rowLimit = (queryParameters.containsKey("limit") && queryParameters.get("limit").iterator().hasNext()) ? Integer.valueOf(queryParameters.get("limit").iterator().next()).intValue() : defaultRowLimit; } catch (Throwable th) { rowLimit = defaultRowLimit; } LogicalData ld = getCatalogue().getLogicalDataByPath(io.milton.common.Path.path(rootPath), cn); List<LogicalDataWrapped> logicalDataWrappedList = new ArrayList<>(); if (ld == null || rowLimit < 1) { return logicalDataWrappedList; } Permissions p = getCatalogue().getPermissions(ld.getUid(), ld.getOwner(), cn); if (mp.canRead(p)) { try (PreparedStatement ps1 = cn.prepareStatement("SELECT uid, parentRef, " + "ownerId, datatype, ldName, createDate, modifiedDate, ldLength, " + "contentTypesStr, pdriGroupRef, isSupervised, checksum, lastValidationDate, " + "lockTokenID, lockScope, lockType, lockedByUser, lockDepth, lockTimeout, " + "description, locationPreference, status " + "FROM ldata_table WHERE (parentRef = ?) " + "AND (? OR (isSupervised = ?)) " + "AND (? OR (createDate BETWEEN FROM_UNIXTIME(?) AND FROM_UNIXTIME(?))) " + "AND (? OR (createDate >= FROM_UNIXTIME(?))) " + "AND (? OR (createDate <= FROM_UNIXTIME(?))) " + "AND (? OR (modifiedDate BETWEEN FROM_UNIXTIME(?) AND FROM_UNIXTIME(?))) " + "AND (? OR (modifiedDate >= FROM_UNIXTIME(?))) " + "AND (? OR (modifiedDate <= FROM_UNIXTIME(?))) " + "AND (? OR (ldName LIKE CONCAT('%', ? , '%')))" + "LIMIT ?"); PreparedStatement ps2 = cn.prepareStatement("SELECT uid, ownerId, " + "ldName FROM ldata_table WHERE parentRef = ? AND datatype = '" + Constants.LOGICAL_FOLDER + "'")) { { if (queryParameters.containsKey("name") && queryParameters.get("name").iterator().hasNext()) { String name = queryParameters.get("name").iterator().next(); ps1.setBoolean(18, false); ps1.setString(19, name); addFlag &= ld.getName().contains(name); } else { ps1.setBoolean(18, true); ps1.setString(19, ""); } if (queryParameters.containsKey("cStartDate") && queryParameters.get("cStartDate").iterator().hasNext() && queryParameters.containsKey("cEndDate") && queryParameters.get("cEndDate").iterator().hasNext()) { long cStartDate = Long.valueOf(queryParameters.get("cStartDate").iterator().next()); long cEndDate = Long.valueOf(queryParameters.get("cEndDate").iterator().next()); ps1.setBoolean(4, false); ps1.setBoolean(7, true); ps1.setBoolean(9, true); ps1.setLong(5, cStartDate); ps1.setLong(6, cEndDate); ps1.setLong(8, 0); ps1.setLong(10, 0); addFlag &= (ld.getCreateDate() >= cStartDate * 1000) && (ld.getCreateDate() <= cEndDate * 1000); } else if (queryParameters.containsKey("cStartDate") && queryParameters.get("cStartDate").iterator().hasNext()) { long cStartDate = Long.valueOf(queryParameters.get("cStartDate").iterator().next()); ps1.setBoolean(4, true); ps1.setBoolean(7, false); ps1.setBoolean(9, true); ps1.setLong(5, 0); ps1.setLong(6, 0); ps1.setLong(8, cStartDate); ps1.setLong(10, 0); addFlag &= (ld.getCreateDate() >= cStartDate * 1000); } else if (queryParameters.containsKey("cEndDate") && queryParameters.get("cEndDate").iterator().hasNext()) { long cEndDate = Long.valueOf(queryParameters.get("cEndDate").iterator().next()); ps1.setBoolean(4, true); ps1.setBoolean(7, true); ps1.setBoolean(9, false); ps1.setLong(5, 0); ps1.setLong(6, 0); ps1.setLong(8, 0); ps1.setLong(10, cEndDate); addFlag &= (ld.getCreateDate() <= cEndDate * 1000); } else { ps1.setBoolean(4, true); ps1.setBoolean(7, true); ps1.setBoolean(9, true); ps1.setLong(5, 0); ps1.setLong(6, 0); ps1.setLong(8, 0); ps1.setLong(10, 0); } if (queryParameters.containsKey("mStartDate") && queryParameters.get("mStartDate").iterator().hasNext() && queryParameters.containsKey("mEndDate") && queryParameters.get("mEndDate").iterator().hasNext()) { long mStartDate = Long.valueOf(queryParameters.get("mStartDate").iterator().next()); long mEndDate = Long.valueOf(queryParameters.get("mEndDate").iterator().next()); ps1.setBoolean(11, false); ps1.setBoolean(14, true); ps1.setBoolean(16, true); ps1.setLong(12, mStartDate); ps1.setLong(13, mEndDate); ps1.setLong(15, 0); ps1.setLong(17, 0); addFlag &= (ld.getModifiedDate() >= mStartDate * 1000) && (ld.getModifiedDate() <= mEndDate * 1000); } else if (queryParameters.containsKey("mStartDate") && queryParameters.get("mStartDate").iterator().hasNext()) { long mStartDate = Long.valueOf(queryParameters.get("mStartDate").iterator().next()); ps1.setBoolean(11, true); ps1.setBoolean(14, false); ps1.setBoolean(16, true); ps1.setLong(12, 0); ps1.setLong(13, 0); ps1.setLong(15, mStartDate); ps1.setLong(17, 0); addFlag &= (ld.getModifiedDate() >= mStartDate * 1000); } else if (queryParameters.containsKey("mEndDate") && queryParameters.get("mEndDate").iterator().hasNext()) { long mEndDate = Long.valueOf(queryParameters.get("mEndDate").iterator().next()); ps1.setBoolean(11, true); ps1.setBoolean(14, true); ps1.setBoolean(16, false); ps1.setLong(12, 0); ps1.setLong(13, 0); ps1.setLong(15, 0); ps1.setLong(17, mEndDate); addFlag &= (ld.getModifiedDate() <= mEndDate * 1000); } else { ps1.setBoolean(11, true); ps1.setBoolean(14, true); ps1.setBoolean(16, true); ps1.setLong(12, 0); ps1.setLong(13, 0); ps1.setLong(15, 0); ps1.setLong(17, 0); } if (queryParameters.containsKey("isSupervised") && queryParameters.get("isSupervised").iterator().hasNext()) { boolean isSupervised = Boolean.valueOf(queryParameters.get("isSupervised").iterator().next()); ps1.setBoolean(2, false); ps1.setBoolean(3, isSupervised); addFlag &= (ld.getSupervised() == isSupervised); } else { ps1.setBoolean(2, true); ps1.setBoolean(3, true); } if (addFlag) { LogicalDataWrapped ldw = new LogicalDataWrapped(); ldw.setLogicalData(ld); ldw.setPath(rootPath); ldw.setPermissions(p); if (mp.isAdmin()) { List<PDRIDescr> pdriDescr = getCatalogue().getPdriDescrByGroupId(ld.getPdriGroupId(), cn); for (PDRIDescr pdri : pdriDescr) { if (pdri.getResourceUrl().startsWith("lfc") || pdri.getResourceUrl().startsWith("srm") || pdri.getResourceUrl().startsWith("gftp")) { pdriDescr.remove(pdri); GridHelper.initGridProxy(pdri.getUsername(), pdri.getPassword(), null, false); pdri.setPassword(GridHelper.getProxyAsBase64String()); pdriDescr.add(pdri); } } ldw.setPdriList(pdriDescr); } logicalDataWrappedList.add(ldw); rowLimit--; } if(rowLimit != 0) { logicalDataWrappedList.addAll(queryLogicalData(new MyData(ld.getUid(), rootPath.equals("/") ? "" : rootPath), rowLimit, ps1, ps2, mp, cn)); } } } } return logicalDataWrappedList; } @Path("query/") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public List<LogicalDataWrapped> getXml() throws Exception { try (Connection cn = getCatalogue().getConnection()) { MyPrincipal mp = (MyPrincipal) request.getAttribute("myprincipal"); List<LogicalDataWrapped> res = queryLogicalData(mp, cn); return res; } catch (SQLException ex) { log.log(Level.SEVERE, null, ex); throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); } } @Path("dri/") public DRItemsResource getDRI() { return new DRItemsResource(getCatalogue(), request, servletResponse, info); } @Path("permissions/") public SetBulkPermissionsResource getPermissions() { return new SetBulkPermissionsResource(getCatalogue(), request); } }
52.481586
176
0.499946
ddbd37e2ad7f74d93e7fd00de49f22cda332abd4
87
package com.springcloud.fooddelivery.repository; public interface MenuRepository { }
14.5
48
0.827586
fb511da915a41399e1f89e4fea45b4baffa6d40b
989
import org.junit.rules.ExternalResource; import org.sql2o.*; public class DatabaseRule extends ExternalResource { @Override protected void before() { DB.sql2o = new Sql2o("jdbc:postgresql://localhost:5432/cooking_test", null, null); } @Override protected void after() { try(Connection con = DB.sql2o.open()) { String deleteIngredientsQuery = "DELETE FROM ingredients *;"; String deleteRecipesQuery = "DELETE FROM recipes *;"; String deleteIngredientsRecipesQuery = "DELETE FROM ingredients_recipes *;"; String deleteTagsQuery = "DELETE FROM tags *;"; String deleteRecipesTagsQuery = "DELETE FROM recipes_tags *;"; con.createQuery(deleteIngredientsQuery).executeUpdate(); con.createQuery(deleteRecipesQuery).executeUpdate(); con.createQuery(deleteIngredientsRecipesQuery).executeUpdate(); con.createQuery(deleteTagsQuery).executeUpdate(); con.createQuery(deleteRecipesTagsQuery).executeUpdate(); } } }
35.321429
86
0.724975
e71795929f58f9582948be6f71b90ace18c95a2c
4,915
package hk.hku.cecid.edi.sfrm.com; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.FileInputStream; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.util.Iterator; import java.util.Collection; import hk.hku.cecid.piazza.commons.io.FileSystem; /** * A folders payload represent a folder hierarchical with * the set of payloads.<br> * * Creation Date: 5/10/2006 * * @author Twinsen Tsang * @version 1.0.1 * @since 1.0.0 */ public class FoldersPayload extends NamedPayloads{ /** * The partnershipId provider used by this payloads. */ private String partnershipId; /** * The messageId used by this payloads. */ private String messageId; /** * The total size of all payloads within the folders. */ private long totalSize = -1; /** * The number of files within the folders. */ private int numOfFiles = -1; /** * Protected Explicit Constructor. * * This constructor is mainly used for creating * a new payload proxy including the physical * file and the proxy object. * * @param payloadsName * The name of the newly created payload. * @param initialState * The initialState of the payloads, * see {@link PayloadsState} for details. * @param owner * The owner of the payloads. * @since * 1.0.2 * @throws Exception * Any kind of exceptions. */ protected FoldersPayload( String payloadsName, int initialState, PayloadsRepository owner) throws IOException { super(payloadsName, initialState, owner); this.decode(); } /** * Protected Explicit Constructor. * * @param payloads * The payloads directory. * @param owner * The owner of this payload. * @since * 1.0.0 * @throws IOException * If the payload is not directory. */ protected FoldersPayload( File payloads, PayloadsRepository owner) throws IOException { super(payloads, owner); if (!payloads.isDirectory()) throw new IOException("Payloads is not a folder."); this.decode(); } /** * @return the partnership id of the payloads. */ public String getPartnershipId() { return partnershipId; } /** * @return the message of the payloads. */ public String getMessageId() { return this.messageId; } /** * @return the total size within the folders. */ public long getSize() { if (this.totalSize == -1){ this.totalSize = 0; Collection c = new FileSystem(this.getRoot()) .getFiles(true); Iterator itr = c.iterator(); FileChannel fc; while(itr.hasNext()){ try{ fc = new FileInputStream ((File)itr.next()).getChannel(); this.totalSize += fc.size(); fc.close(); } catch(IOException e){ // Continue. } } this.numOfFiles = c.size(); } return this.totalSize; } /** * @return the number of files within the folders. */ public int getNumOfFiles() { if (this.numOfFiles == -1){ this.numOfFiles = new FileSystem(this.getRoot()).getFiles(true).size(); } return this.numOfFiles; } /** * Clear all the content and the folder for this payload. */ public void clearPayloadCache() { FileSystem fs = new FileSystem(this.getRoot()); fs.purge(); } /** * The outgoing payload does not support <code>load</code> method. */ public InputStream load() throws IOException { throw new IOException("Unable to load content from directory."); } /** * The outgoing payload does not support <code>loadChannel</code> method. */ public ReadableByteChannel loadChannel() throws IOException { throw new IOException("Unable to load channel from directory."); } /** * The outgoing payload does not support <code>save</code> method. */ public void save(InputStream content, boolean append) throws IOException { throw new IOException("Unable to write content to directory."); } /** * Decode the payload root to become some useful information.<br><br> * * Only the partnershipId (the first token) is assigned. * * @throws ArrayIndexOutOfBoundsException * if the decoding fails due to the filename is in wrong format. */ protected void decode() throws ArrayIndexOutOfBoundsException { if (this.getTokens().size() < 2) throw new ArrayIndexOutOfBoundsException( "Invalid Folders Payload Format."); this.partnershipId = (String) this.getTokens().get(0); this.messageId = (String) this.getTokens().get(1); } /** * */ protected void encode() { // TODO: Encode Folders Payload } /** * toString method */ public String toString() { StringBuffer ret = new StringBuffer(super.toString()); ret .append("PartnershipId:" + this.partnershipId + " \n") .append("MessageId :" + this.messageId + " \n"); return ret.toString(); } }
21.004274
74
0.657782
16c24bd2046c5b832ce6940b582190e1b33f48da
5,320
/******************************************************************************* * Copyright (c)2014 Prometheus Consulting * * 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 nz.co.senanque.workflow; import java.util.Collection; import java.util.Map; import java.util.StringTokenizer; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import nz.co.senanque.forms.WorkflowForm; import nz.co.senanque.messaging.MessageMapper; import nz.co.senanque.messaging.MessageSender; import nz.co.senanque.process.instances.ComputeType; import nz.co.senanque.process.instances.ProcessDefinition; import nz.co.senanque.process.instances.TaskBase; import nz.co.senanque.schemaparser.FieldDescriptor; import nz.co.senanque.validationengine.ValidationEngine; import nz.co.senanque.workflow.instances.Audit; import nz.co.senanque.workflow.instances.ProcessInstance; import nz.co.senanque.workflow.instances.TaskStatus; import org.apache.commons.lang.NotImplementedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.messaging.Message; /** * Used as a mock for the workflow manager. It is used in tests but it is also used by the plugin parser which * only needs to validate rather than actually run a process. * * @author Roger Parkinson * */ public class WorkflowManagerMock extends WorkflowManagerAbstract { private static final Logger log = LoggerFactory .getLogger(WorkflowManagerMock.class); public WorkflowManagerMock() { } public WorkflowManagerMock(String messageNames, String computeNames) { if (messageNames != null) { StringTokenizer st = new StringTokenizer(messageNames, ","); MessageSender<String> ms = new MessageSender<String>(){ @Override public boolean send(String graph, long correlationId) { return false; }}; while (st.hasMoreTokens()) { getMessages().put(st.nextToken(), ms); } } if (computeNames != null) { ComputeType<String> ct = new ComputeType<String>(){ @Override public void execute(ProcessInstance processInstance, String context, Map<String, String> map) { }}; StringTokenizer st = new StringTokenizer(computeNames, ","); while (st.hasMoreTokens()) { this.getComputeTypes().put(st.nextToken(), ct); } } } @PostConstruct public void init() { findBeans(); } @PreDestroy public void shutdown() { } @Override public Object getField(ProcessInstance processInstance, FieldDescriptor fd) { throw new NotImplementedException(); } @Override public ProcessInstance launch(String processName, Object o, String comment, String bundleName) { ProcessDefinition processDefinition = getProcessDefinition(processName); if (processDefinition == null) { throw new WorkflowException("Failed to find process definition named "+processName); } ProcessInstance processInstance = new ProcessInstance(); processInstance.setComment(comment); processInstance.setBundleName(bundleName); return processInstance; } @Override public void execute(long id) { } @Override public void executeDeferredEvent(long deferredEventId) { } @Override public void processMessage(ProcessInstance processInstance, Message<?> message, MessageMapper messageMapper) { } @Override public Object getContext(String objectInstance) { return null; } @Override public void mergeContext(Object context) { } @Override public String createContextDescriptor(Object o) { return null; } @Override protected void tickleParentProcess(ProcessInstance processInstance, TaskStatus status) { } @Override protected TaskBase endOfProcessDetected(ProcessInstance processInstance, Audit currentAudit) { return null; } @Override public long save(WorkflowForm workflowForm) { return 0; } @Override public WorkflowForm getLaunchForm(String processName) { return null; } @Override public WorkflowForm getCurrentForm(ProcessInstance processInstance) { return null; } @Override public long launch(WorkflowForm launchForm, String comment, String bundleName) { return 0; } @Override public ValidationEngine getValidationEngine() { return null; } @Override public Collection<Audit> getAudits(ProcessInstance processInstance) { // TODO Auto-generated method stub return null; } @Override public ProcessInstance refresh(ProcessInstance processInstance) { // TODO Auto-generated method stub return null; } @Override public ProcessInstance lockProcessInstance(ProcessInstance processInstance, boolean techSupport, String userName) { // TODO Auto-generated method stub return null; } @Override public void finishLaunch(long processId) { // TODO Auto-generated method stub } }
27.42268
110
0.738158
36dadaecd92e27b741d8bbfdc40e1079674f4875
2,409
package org.miaohong.newfishchatserver.core.rpc.client; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import lombok.Getter; import lombok.Setter; import org.miaohong.newfishchatserver.core.execption.ClientCoreException; import org.miaohong.newfishchatserver.core.lb.strategy.AbstractServiceStrategy; import org.miaohong.newfishchatserver.core.lb.strategy.StrategyConstants; import org.miaohong.newfishchatserver.core.rpc.client.proxy.ProxyConstants; import org.miaohong.newfishchatserver.core.rpc.eventbus.EventBus; import org.miaohong.newfishchatserver.core.rpc.eventbus.EventBusManager; import org.miaohong.newfishchatserver.core.rpc.register.RegisterConstants; import org.miaohong.newfishchatserver.core.rpc.register.listener.ServiceCacheListenerImpl; import org.miaohong.newfishchatserver.core.util.ClassUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ConsumerConfig<T> { private static final Logger LOG = LoggerFactory.getLogger(ConsumerConfig.class); private final EventBus eventBus = EventBusManager.get(); protected Class<T> proxyClass; @Getter private String proxy = ProxyConstants.PROXY_JDK; @Getter private String register = RegisterConstants.REGISTER_ZOOKEEPER; @Getter private String strategy = StrategyConstants.STRATEGY_RANDOM; @Getter @Setter private String interfaceId; public ConsumerConfig() { eventBus.register(new AbstractServiceStrategy.RpcClientHandlerListener()); eventBus.register(ServiceCacheListenerImpl.get()); } @SuppressWarnings("unchecked") public Class<T> getProxyClass() { if (proxyClass != null) { return proxyClass; } try { if (!Strings.isNullOrEmpty(interfaceId)) { proxyClass = ClassUtils.forName(interfaceId); Preconditions.checkNotNull(proxyClass); if (!proxyClass.isInterface()) { throw new ClientCoreException("interfaceId must set interface class, not implement class"); } } else { LOG.error("interfaceId is null"); throw new ClientCoreException("interfaceId must be not null"); } } catch (Exception e) { throw new ClientCoreException(e.getMessage(), e); } return proxyClass; } }
35.426471
111
0.716895
5330a5585d0b8bd25673a4b902abdd976ff673e6
453
package de.gishmo.mvp4g.client.ui.page02; import com.mvp4g.client.annotation.Presenter; import com.mvp4g.client.presenter.BasePresenter; import de.gishmo.mvp4g.client.Mvp4gHyperlinkEventBus; @Presenter(view = IPage02View.class) public class Page02Presenter extends BasePresenter<IPage02View, Mvp4gHyperlinkEventBus> implements IPage02View.IPage02Presenter { public void onShowPage02() { eventBus.setContentView(view.asWidget()); } }
26.647059
62
0.801325