blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
4cfa8f3d0970c0969047f6269211f5949796c6c8
Java
linschris/data-structures-projects
/Homework5/src/NodeState.java
UTF-8
4,915
2.921875
3
[]
no_license
import java.util.Map; import java.util.List; import java.util.LinkedList; import java.util.TreeMap; class NodeState extends State { class Edge { int src; int dst; int cost; public Edge(int src, int dst, int cost) { this.src = src; this.dst = dst; this.cost = cost; } } private int currNode; private TreeMap<Integer, Integer> heuristics; private TreeMap<Integer, LinkedList<Edge>> edges; public NodeState(String s) { this.heuristics = new TreeMap<Integer, Integer>(); this.edges = new TreeMap<Integer, LinkedList<Edge>>(); String[] lines = s.split("\\|"); int num_nodes = 0; int num_edges = 0; this.currNode = Integer.parseInt(lines[0]); for (int lineNum = 1; lineNum < lines.length; lineNum++) { String line = lines[lineNum]; String[] parts = line.split(":"); String[] srcString = parts[0].split(" "); int src = Integer.parseInt(srcString[0]); int heuristic = Integer.parseInt(srcString[1].substring(1, srcString[1].length() - 1)); this.heuristics.put(src, heuristic); if (!this.edges.containsKey(src)) { this.edges.put(src, new LinkedList<Edge>()); } if (parts.length == 1) { continue; } for (String dstStrings : parts[1].split(", ")) { if (dstStrings.startsWith(" ")) { dstStrings = dstStrings.substring(1); } String[] dstString = dstStrings.split(" "); int dst = Integer.parseInt(dstString[0]); int cost = Integer.parseInt(dstString[1].substring(1, dstString[1].length() - 1)); this.edges.get(src).add(new Edge(src, dst, cost)); } } } public List<Action> getActions() { LinkedList<Action> actions = new LinkedList<Action>(); List<Edge> outEdges = this.edges.get(this.currNode); if (outEdges != null) { for (Edge edge : this.edges.get(this.currNode)) { actions.add(new Action( edge.src + "->" + edge.dst + " (" + edge.cost + ")", edge.cost, new NodeState(this.toString(edge.dst)) )); } } return actions; } public int heuristicTo(State goal) { return this.heuristics.get(this.currNode); } private String getGraphString() { String result = ""; for (Map.Entry<Integer, LinkedList<Edge>> entry : this.edges.entrySet()) { int src = entry.getKey(); LinkedList<Edge> outEdges = entry.getValue(); result += "|" + src + " (" + this.heuristics.get(src) + "):"; if (outEdges.size() > 0) { String edgeString = ""; for (Edge outEdge : outEdges) { edgeString += ", " + outEdge.dst + " (" + outEdge.cost + ")"; } result += edgeString.substring(1); } } return result.substring(1); } private String toString(int node) { return node + "|" + this.getGraphString(); } public String toString() { return this.toString(this.currNode); } public void print() { LinkedList<String> lines = new LinkedList<String>(); lines.add("// Visualize at http://viz-js.com/"); lines.add("digraph {"); for (Map.Entry<Integer, LinkedList<Edge>> entry : this.edges.entrySet()) { int src = entry.getKey(); if (src == this.currNode) { lines.add(" " + src + " [label=\"" + src + " (" + this.heuristics.get(src) + ")\" style=filled, fillcolor=\"#C0C0C0\"]"); } else { lines.add(" " + src + " [label=\"" + src + " (" + this.heuristics.get(src) + ")\"]"); } LinkedList<Edge> outEdges = entry.getValue(); for (Edge outEdge : outEdges) { lines.add(" " + src + " -> " + outEdge.dst + " [label=\"" + outEdge.cost + "\"]"); } } lines.add("}"); for (String line : lines) { System.out.println(line); } } public static void main(String[] args) { String[] strings = { "1", "1 (1): 2 (1), 3 (1), 4 (1)", "1 (1): 5 (1)", "2 (1): 6 (1)", "3 (1): 6 (1)", "4 (1): 6 (1)", "5 (1): 6 (1)", }; String graphString = ""; for (String list : strings) { graphString += "|" + list; } graphString = graphString.substring(1); NodeState graph = new NodeState(graphString); System.out.println(graph); graph.print(); } }
true
517a5d9de9c3f0229e3cda423d983850cb93b6e9
Java
acmcms/acm-plug-webdav
/java/ru/myx/webdav/WebDavResponse.java
UTF-8
5,812
2.203125
2
[]
no_license
/* * Copyright 1997-1998 by Marc Eaddy, Jonathan Shapiro, Shao Rong; ALL RIGHTS * RESERVED * * Permission to use, copy, modify, and distribute this software and its * documentation for research and educational purpose and without fee is hereby * granted, provided that the above copyright notice appear in all copies and * that both that the copyright notice and warranty disclaimer appear in * supporting documentation, and that the names of the copyright holders or any * of their entities not be used in advertising or publicity pertaining to * distribution of the software without specific, written prior permission. Use * of this software in whole or in parts for direct commercial advantage * requires explicit prior permission. * * The copyright holders disclaim all warranties with regard to this software, * including all implied warranties of merchantability and fitness. In no event * shall the copyright holders be liable for any special, indirect or * consequential damages or any damages whatsoever resulting from loss of use, * data or profits, whether in an action of contract, negligence or other * tortuous action, arising out of or in connection with the use or performance * of this software. */ package ru.myx.webdav; import org.w3c.dom.Element; import ru.myx.ae3.answer.Reply; import ru.myx.util.HashMapPrimitiveInt; /** Wraps the HttpServletResponse class to abstract the specific protocol used. To support other * protocols we would only need to modify this class and the WebDavRetCode classes. * * @see WebDavRetCode * @author Marc Eaddy * @version 1.0, 16 Nov 1997 */ @SuppressWarnings("javadoc") class WebDavResponse { /** This Map contains the mapping of HTTP and WebDAV status codes to descriptive text. This is a * static variable. */ private static final HashMapPrimitiveInt<String> mapStatusCodes = new HashMapPrimitiveInt<>(); /** Status code (413) indicating the server is refusing to process a request because the request * entity is larger than the server is willing or able to process. */ public static final int SC_REQUEST_TOO_LONG = 413; /** Status code (418) indicating the entity body submitted with the PATCH method was not * understood by the resource. */ public static final int SC_UNPRCESSABLE_ENTITY = 418; // This // one // colides // with // HTTP // 1.1 // "418 Reauthentication Required" /** Status code (419) indicating that the resource does not have sufficient space to record the * state of the resource after the execution of this method. */ public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE = 419; // This // one // colides // with // HTTP // 1.1 // "419 Proxy Reauthentication Required" /** Status code (420) indicating the method was not executed on a particular resource within its * scope because some part of the method's execution failed causing the entire method to be * aborted. */ public static final int SC_METHOD_FAILURE = 420; /** Status code (423) indicating the destination resource of a method is locked, and either the * request did not contain a valid Lock-Info header, or the Lock-Info header identifies a lock * held by another principal. */ public static final int SC_LOCKED = 423; static { final HashMapPrimitiveInt<String> codes = WebDavResponse.mapStatusCodes; // HTTP 1.0 Server status codes -- see RFC 1945 codes.put(Reply.CD_OK, "OK"); codes.put(Reply.CD_CREATED, "Created"); codes.put(Reply.CD_ACCEPTED, "Accepted"); codes.put(Reply.CD_EMPTY, "No Content"); codes.put(Reply.CD_MOVED, "Moved Permanently"); codes.put(Reply.CD_LOOKAT, "Moved Temporarily"); codes.put(Reply.CD_UNMODIFIED, "Not Modified"); codes.put(Reply.CD_BADQUERY, "Bad Request"); codes.put(Reply.CD_UNAUTHORIZED, "User Authentication Required"); codes.put(Reply.CD_DENIED, "Forbidden"); codes.put(Reply.CD_UNKNOWN, "Not Found"); codes.put(Reply.CD_EXCEPTION, "Internal Server Error"); codes.put(Reply.CD_UNIMPLEMENTED, "Not Implemented"); codes.put(Reply.CD_BADGATEWAY, "Bad Gateway"); codes.put(Reply.CD_BUSY, "Service Unavailable"); // HTTP 1.1 Server status codes -- see RFC 2048 codes.put(Reply.CD_CONTINUE, "Continue"); codes.put(Reply.CD_BADMETHOD, "Method Not Allowed"); codes.put(Reply.CD_CONFLICT, "Conflict"); codes.put(Reply.CD_FAILED_PRECONDITION, "Precondition Failed"); codes.put(WebDavResponse.SC_REQUEST_TOO_LONG, "Request Too Long"); codes.put(Reply.CD_UNSUPPORTED_FORMAT, "Unsupported Media Type"); // WebDav Server-specific status codes codes.put(Reply.CD_MULTISTATUS, "Multi-Status"); codes.put(WebDavResponse.SC_UNPRCESSABLE_ENTITY, "Unprocessable Entity"); codes.put(WebDavResponse.SC_INSUFFICIENT_SPACE_ON_RESOURCE, "Insufficient Space On Resource"); codes.put(WebDavResponse.SC_METHOD_FAILURE, "Method Failure"); codes.put(WebDavResponse.SC_LOCKED, "Locked"); } static Element createHttpStatusElement(final int nHttpStatusCode) { final String strStatusText = "HTTP/1.1 " + nHttpStatusCode + " " + WebDavResponse.getStatusText(nHttpStatusCode); final Element element = WebdavXML.createElement("status"); element.appendChild(WebdavXML.createTextNode(strStatusText)); return element; } /** Returns the HTTP status text for the HTTP or WebDav status code specified by looking it up * in the static mapping. This is a static function. * * @param nHttpStatusCode * [IN] HTTP or WebDAV status code * @return A string with a short descriptive phrase for the HTTP status code (e.g., "OK"). */ static String getStatusText(final int nHttpStatusCode) { return nHttpStatusCode != Reply.CD_EXCEPTION && !WebDavResponse.mapStatusCodes.containsKey(nHttpStatusCode) ? WebDavResponse.getStatusText(Reply.CD_EXCEPTION) : WebDavResponse.mapStatusCodes.get(nHttpStatusCode); } }
true
f1d7c2626e5a2d47f6eb34973b0175b7f5e7402c
Java
yhxxxbl/EditManifestPlugin
/plugin/src/main/java/com/wkl/manifest/plugin/ManifestExtension.java
UTF-8
1,054
2.03125
2
[ "Apache-2.0" ]
permissive
package com.wkl.manifest.plugin; import com.wkl.manifest.config.ApplicationConfig; import com.wkl.manifest.utils.Utils; import org.gradle.api.Action; import org.gradle.api.Project; /** * Created by <a href="mailto:wangkunlin1992@gmail.com">Wang kunlin</a> * <p> * On 2018-04-16 */ public class ManifestExtension { private ApplicationConfig mApplicationConfig; public ManifestExtension(Project project) { mApplicationConfig = new ApplicationConfig(project); } public void application(Action<ApplicationConfig> action) { action.execute(mApplicationConfig); } public ApplicationConfig getApplicationConfig() { return mApplicationConfig; } public static ManifestExtension getConfig(Project project) { return project.getExtensions().getByType(ManifestExtension.class); } public String parseProperty() { StringBuilder container = new StringBuilder("ManifestExtension:"); mApplicationConfig.parseProperty(container); return Utils.generateMD5(container.toString()); } }
true
02dca1d4be392a3678bc73436559752947d78e05
Java
sqsgalaxys/workspace
/javase/Traffic0.2/src/cn/agrin/Direction.java
UTF-8
225
1.75
2
[]
no_license
package cn.agrin; public enum Direction { // S2N,S2W,E2W,E2S, // N2S,N2E,W2E,W2N, // S2E,E2N,N2W,W2S; STOP, S2N,S2W,S2E, E2W,E2S,E2N, N2S,N2E,N2W, W2E,W2N,W2S; //STOP,S2N,S2W,S2E,E2W,E2S,E2N,N2S,N2E,N2W,W2E,W2N,W2S, }
true
a738070f21d4559a2307042993dfde52ac12efdc
Java
gvs048/Repo_05172013
/5172013/testCases/src/test/java/com/dealwallet/webdriver/selenium05082013/Dealwallet1.java
UTF-8
2,408
2.46875
2
[]
no_license
package com.dealwallet.webdriver.selenium05082013; import org.openqa.selenium.WebDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import jxl.*; import jxl.read.biff.BiffException; import jxl.write.Label; import jxl.write.WritableCell; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; public class Dealwallet1 { WebDriver d; @BeforeMethod public void startup() { //d=new FirefoxDriver(); } @AfterMethod public void stop() { //d.quit(); } /*@Test public void testReading() throws InterruptedException, BiffException, IOException, WriteException { Workbook workbook = Workbook.getWorkbook(new File("C:\\Users\\Tsss-Pc1\\Desktop\\login.xls")); Sheet sheet = workbook.getSheet(0); Cell a1 = sheet.getCell(0,0); Cell b2 = sheet.getCell(1,0); String stringa1 = a1.getContents(); String stringb2 = b2.getContents(); System.out.println(stringa1); System.out.println(stringb2); } */ /*@Test public void testWriting() { try { WritableWorkbook workbook = Workbook.createWorkbook(new File("C:\\Users\\Tsss-Pc1\\Desktop\\login1.xls")); WritableSheet sheet = workbook.createSheet("First Sheet", 0); Label label = new Label(2,0, "pass"); sheet.addCell(label); workbook.write(); workbook.close(); } catch (IOException | WriteException e) { // TODO Auto-generated catch block e.printStackTrace(); } }*/ @Test public void testReading() throws InterruptedException, BiffException, IOException, WriteException { File file=new File("C:\\Users\\Tsss-Pc1\\Desktop\\login.xls"); //WritableWorkbook workbook = Workbook.getWorkbook("C:\\Users\\Tsss-Pc1\\Desktop\\login.xls"); Workbook workbook = Workbook.getWorkbook(file); WritableWorkbook copy = Workbook.createWorkbook(new File("C:\\Users\\Tsss-Pc1\\Desktop\\login1.xls"), workbook); WritableSheet sheet2 = copy.getSheet(0); WritableCell cell = sheet2.getWritableCell(1, 0); if (cell.getType() == CellType.LABEL) { Label l = (Label) cell; l.setString("modified cell"); } Label label = new Label(2, 0, "New label record"); sheet2.addCell(label); copy.write(); copy.close(); } }
true
9491cb9129a72e98df9a0754d03e70764af2e110
Java
HelpChat/PlaceholderAPI-Discord-Bot
/src/main/java/at/helpch/papibot/core/framework/BinderModule.java
UTF-8
756
2.09375
2
[ "MIT" ]
permissive
package at.helpch.papibot.core.framework; import at.helpch.papibot.core.objects.tasks.Task; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; // ------------------------------ // Copyright (c) PiggyPiglet 2018 // https://www.piggypiglet.me // ------------------------------ public final class BinderModule extends AbstractModule { private final Class clazz; public BinderModule(Class clazz) { this.clazz = clazz; } public Injector createInjector() { return Guice.createInjector(this); } @Override @SuppressWarnings("unchecked") public void configure() { bind(clazz).toInstance(clazz); requestStaticInjection(Task.class); } }
true
7c29b6f700348a67fa4c65631e7f70e0eef5f178
Java
Hades957/Learning-for-Java
/app01/src/com/yunsi/thread/PrintNumRunnable.java
WINDOWS-1252
395
3.15625
3
[]
no_license
package com.yunsi.thread; public class PrintNumRunnable implements Runnable { public void run() { Thread t = Thread.currentThread(); System.out.println("PrintNumRunnable ߳ƣ"+t.getName()); for(int i=1;i<=20;i++) { System.out.print(i+" "); /* * long start = System.currentTimeMillis(); * while((System.currentTimeMillis()-start)<=1000) {} */ } } }
true
02f67a64f76104e986a5528a1737429cc5542d7b
Java
seasarorg/s2struts
/s2struts/src/test/java/org/seasar/struts/pojo/processor/commands/WrapS2BeanValidatorFormTest.java
UTF-8
2,601
1.898438
2
[ "Apache-2.0" ]
permissive
package org.seasar.struts.pojo.processor.commands; import org.apache.struts.action.ActionForm; import org.apache.struts.chain.commands.ActionCommand; import org.apache.struts.chain.contexts.ActionContext; import org.apache.struts.chain.contexts.ServletActionContext; import org.apache.struts.config.impl.ModuleConfigImpl; import org.apache.struts.validator.BeanValidatorForm; import org.seasar.extension.unit.S2TestCase; import org.seasar.struts.mock.MockActionMapping; import org.seasar.struts.pojo.form.S2BeanValidatorForm; import org.seasar.struts.pojo.processor.TestActionForm; import org.seasar.struts.pojo.processor.TestPojoForm; /** * * @author Katsuhiko Nagashima * */ public class WrapS2BeanValidatorFormTest extends S2TestCase { private MockActionMapping mapping; private ActionContext context; private ActionCommand command = new WrapS2BeanValidatorForm(); protected void setUp() throws Exception { super.setUp(); } protected void setUpAfterContainerInit() throws Exception { this.mapping = new MockActionMapping(); this.mapping.setModuleConfig(new ModuleConfigImpl()); this.mapping.setName("beanForm"); this.context = new ServletActionContext(this.getServletContext(), this.getRequest(), this.getResponse()); this.context.setActionConfig(this.mapping); } public void testWrap() throws Exception { ActionForm form = new BeanValidatorForm(new TestPojoForm()); this.context.setActionForm(form); this.getRequest().getSession().setAttribute(this.mapping.getAttribute(), form); boolean result = this.command.execute(this.context); assertFalse(result); Object bean = this.context.getActionForm(); assertTrue(bean instanceof S2BeanValidatorForm); bean = this.getRequest().getSession().getAttribute(this.mapping.getAttribute()); assertTrue(bean instanceof S2BeanValidatorForm); } public void testNoWrap() throws Exception { ActionForm form = new TestActionForm(); this.context.setActionForm(form); this.getRequest().getSession().setAttribute(this.mapping.getAttribute(), form); boolean result = this.command.execute(this.context); assertFalse(result); Object bean = this.context.getActionForm(); assertFalse(bean instanceof S2BeanValidatorForm); bean = this.getRequest().getSession().getAttribute(this.mapping.getAttribute()); assertFalse(bean instanceof S2BeanValidatorForm); } }
true
1d16e6c25ef0a5a1622c962d4f77a1c2ac8936a1
Java
Codez01/Java
/Robot/MoreSpecialRobot.java
UTF-8
1,978
3.75
4
[]
no_license
public class MoreSpecialRobot extends SpecialRobot { private int battery; public MoreSpecialRobot() { // a defualt constructor that is inherited from the superclass robot with adding the battery percentage super(); this.battery = 100; } public MoreSpecialRobot(String a) { // a constructor that is inherited from the superclass robot with adding the battery percentage super(a); this.battery = 100; } public MoreSpecialRobot(String a, int x, int y, int f) { // a consturctor that is inherited from the super class robot with adding the battery percentage super(a, x, y, f); this.battery = 100; } public int getBattery() { // method for geeting the value of battery return battery; } public void move() { // a method that is used to move the robot to a specific direction with losing 1 percent of battery each move , //and it is an inherited method if (this.battery > 0) { if (super.getPositionX() != 0 && super.getFacing() == WEST) { super.move(); battery--; } else if (super.getPositionY() != 0 && super.getFacing() == SOUTH) { super.move(); battery--; } else if (super.getFacing() == NORTH) { super.move(); battery--; } else if (super.getFacing() == EAST) { super.move(); battery--; } } } public String toString() { // this method is for showing the type style. like the robot is at ( X,y) facing : north , battery percentage : if (super.getFacing() == 1) { String n =super.toString(); String s = " battery at :" + battery + "%" ; return n+s ; } else if (super.getFacing() == 2) { String n =super.toString(); String s = " battery at :" + battery + "%" ; return n+s ; } else if (super.getFacing() == 3) { String n =super.toString(); String s = " battery at :" + battery + "%" ; return n+s ; } else { String n =super.toString(); String s = " battery at :" + battery + "%" ; return n+s ; } } }
true
a63fea8a314e7c883ed0a9b20f50859cfb818d61
Java
Bravery413/Data_Structure
/src/leetcode/everyday/year2020/july/Solution0717.java
UTF-8
922
3.328125
3
[]
no_license
package leetcode.everyday.year2020.july; /** * @author: Bravery * @create: 2020-07-17 23:05 **/ public class Solution0717 { public static int searchInsert(int[] nums, int target) { return searchInsert(nums, target, 0, nums.length); } public static int searchInsert(int[] nums, int target, int left, int right) { if (left >= right) { if (nums[left]>target){ return left; }else { return left+1; } } int mid = (left + right) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] > target) { right = mid - 1; } else { left = mid + 1; } return searchInsert(nums, target, left, right); } public static void main(String[] args) { int[] nums={1,3,5,6}; System.out.println(searchInsert(nums,2)); } }
true
44d1c2e0d2fce202836ae37bd58da363e60af11c
Java
LambdaExpression/One-stop-frame
/src/main/java/org/tcat/frame/enums/EnumsMsg.java
UTF-8
2,503
2.5625
3
[]
no_license
package org.tcat.frame.enums; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.tcat.frame.exception.code.CodeMsg; import org.tcat.frame.util.StringUtils; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; /** * 枚举 多语言消息 * Created by Lin on 2017/8/18. */ public final class EnumsMsg { private static Logger logger = LoggerFactory.getLogger(CodeMsg.class); private static Map<String, Map<String, String>> MULTI_LANGUAGE = new ConcurrentHashMap<>(); private EnumsMsg() { } static { for (MultiLanguage multiLanguage : MultiLanguage.values()) { init("enums/enums_" + multiLanguage.name() + ".properties", multiLanguage.name()); } } /** * 初始化 对应的语言 * * @param path * @param language */ private static void init(String path, String language) { Map<String, String> map = new ConcurrentHashMap<>(); Resource resource = new ClassPathResource(path); Properties props = new Properties(); InputStreamReader isr = null; try { isr = new InputStreamReader(resource.getInputStream(), "UTF-8"); props.load(isr); props.forEach((k, v) -> { map.put(k.toString(), v.toString()); }); MULTI_LANGUAGE.put(language, map); } catch (IOException e) { logger.info("枚举 预加载失败"); } finally { if (isr != null) { try { isr.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 根据语言和枚举路径 获取对应语言的枚举 * * @param multiLanguage 语言枚举 * @param enumsPath 枚举路径 classPath + "#" + 枚举名 * @return 对应枚举语言 */ public static String getMsg(MultiLanguage multiLanguage, String enumsPath) { if (multiLanguage == null || StringUtils.isEmptyByTrim(enumsPath)) { return null; } Map<String, String> msgMap = MULTI_LANGUAGE.get(multiLanguage.name()); if (msgMap == null) { return null; } return msgMap.get(enumsPath); } }
true
e276f62aafa0b255a1ae94f46c3b7265b4ca6a0d
Java
TStavnychyi/CityNow
/app/src/main/java/com/tstv/infofrom/ui/weather/WeatherView.java
UTF-8
286
1.765625
2
[]
no_license
package com.tstv.infofrom.ui.weather; import com.tstv.infofrom.model.weather.Weather; import com.tstv.infofrom.ui.base.BaseView; /** * Created by tstv on 21.09.2017. */ public interface WeatherView extends BaseView { void setData(Weather data); void hideRefreshing(); }
true
84e25a228f3a08b25c2469f630ce4227c2f992d8
Java
RGU5Android/JavaDemoCDAC
/08.04.MultipleInterfaceImplementation/src/p1/ITest3.java
UTF-8
62
1.5625
2
[ "Apache-2.0" ]
permissive
package p1; public interface ITest3 { void itest3(); }
true
2e845d83ffa143cb88fdc0345b9f129af111b287
Java
edap-io/edap
/edap-protobuf-wire/src/main/java/io/edap/protobuf/wire/Syntax.java
UTF-8
1,291
2.296875
2
[]
no_license
/* * Copyright 2020 The edap Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.edap.protobuf.wire; /** * protocol buffer的协议版本 */ public enum Syntax { PROTO_2("proto2"), PROTO_3("proto3"); private final String value; Syntax(String value) { this.value = value; } public String getValue() { return value; } public static Syntax fromValue(String value) { switch (value) { case "proto2": return Syntax.PROTO_2; case "proto3": return Syntax.PROTO_3; default: throw new IllegalArgumentException( "no enum value Syntax " + value); } } }
true
1d8d9d70bb48df8a43b5ae9d7903bdafcd5d2aed
Java
lindianfeng/webgm
/src/main/java/com/kaka/webgm/repository/GameServerRepository.java
UTF-8
300
1.90625
2
[ "MIT" ]
permissive
package com.kaka.webgm.repository; import com.kaka.webgm.domain.GameServer; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface GameServerRepository extends JpaRepository<GameServer, Long> { List<GameServer> findAllByOrderByServerNameAsc(); }
true
242570bd13aad97bbb0aecccf461b4996adbf7a5
Java
jacobthewest/FamilyMapClient
/server/src/main/java/service/FillService.java
UTF-8
26,286
3.21875
3
[]
no_license
package service; import dataAccess.*; import model.Event; import model.Person; import model.User; import result.ApiResult; import result.FillResult; import java.util.*; /** * Implements methods to serve the API route <code>/fill/[username]/{generations}</code> */ public class FillService { private final int DEFAULT_GENERATIONS = 4; private List<String> MALE_NAMES = new ArrayList<String>(); private List<String> FEMALE_NAMES = new ArrayList<String>(); private List<String> LAST_NAMES = new ArrayList<String>(); private List<String> CITIES = new ArrayList<String>(); private List<String> COUNTRIES = new ArrayList<String>(); private List<Double> LATITUDES = new ArrayList<Double>(); private List<Double> LONGITUDES = new ArrayList<Double>(); private List<Event> generatedEvents = new ArrayList<Event>(); private List<Person> generatedPersons = new ArrayList<Person>(); private final int MIN_PARENT_CHILD_AGE_DIFFERENCE = 13; private final int MAX_BIRTHING_AGE = 50; private final int MAX_DEATH_AGE = 120; private final int ADULT_AGE = 18; private static final int CURRENT_YEAR = Calendar.getInstance().get(Calendar.YEAR); private Random random = new Random(); private PersonDao personDao = null; private UserDao userDao = null; private EventDao eventDao = null; /** * Populates the server's database with generated data for the specified user name. * The required "username" parameter must be a user already registered with the server. If there is * any data in the database already associated with the given user name, it is deleted. The * optional "generations" parameter lets the caller specify the number of generations of ancestors * to be generated, and must be a non-negative integer (the default is 4, which results in 31 new * persons each with associated events). * @param userName The userName of User to fill. * @param generations The number of generations to generate. * @return The FillResult from attempting to fill the database. */ public FillResult fill(String userName, int generations) { setUpDataForFill(); try { Database db = new Database(); setUpDatabase(db); createDaosAndSetConnections(db); FillResult paramCheck = errorCheckParameters(userName, generations, db); if(paramCheck != null) return paramCheck; // The required "username" parameter must be a user already registered with the server Person preDeletePersonCopy = personDao.getPersonByAssociatedUsername(userName); User u = userDao.getUserByUserName(userName); if(preDeletePersonCopy == null && u == null) { db.closeConnection(); return new FillResult(ApiResult.INVALID_FILL_PARAM, "userName does not exist within the server"); } // In case the user exists in the database as a user and not yet as a person if(preDeletePersonCopy == null) { preDeletePersonCopy = new Person(u.getPersonID(), u.getUserName(), u.getFirstName(), u.getLastName(), u.getGender(), null, null, null); } // If there is any data in the database already associated with the given user name, it is deleted. deletePreExistingUserData(userName, preDeletePersonCopy, db); // Create the root person Person rootPerson = createRootPerson(preDeletePersonCopy); setRootPersonAndAddToGeneratedPersons(rootPerson, userName, preDeletePersonCopy); // Make the user between 18 and 120 years old int birthYear = CURRENT_YEAR - random.nextInt((MAX_DEATH_AGE + 1) - ADULT_AGE); generateFillPersonBirthAndAddToGeneratedEvents(birthYear, rootPerson); // Let the recursion begin. After this function this.generatedEvents and this.generatedPersons // will be completely full. generateAncestry(rootPerson, birthYear, generations); // Insert created Events and Persons into database insertEventsAndPersonsIntoDatabase(); // Close db connection, commit, and return a successful FillResult return finishFill(db); } catch(DatabaseException e) { return new FillResult(ApiResult.INTERNAL_SERVER_ERROR, "Error filling with userName: '" + userName + "' and '" + generations + "' generations. Error: " + e.getMessage()); } } /** * Populates the server's database with generated data for the specified user name. * The required "username" parameter must be a user already registered with the server. If there is * any data in the database already associated with the given user name, it is deleted. The * optional "generations" parameter lets the caller specify the number of generations of ancestors * to be generated, and must be a non-negative integer (the default is 4, which results in 31 new * persons each with associated events). * @param userName the userName of User to fill * @return The FillResult from attempting to fill the database. */ public FillResult fill(String userName) { final int DEFAULT_GENERATIONS = 4; return fill(userName, DEFAULT_GENERATIONS); } /** * Initializes the MALE_NAMES array list. */ private void setMaleNames() { String[] firstNamesDudes = new String[]{"James", "John", "Michael", "Robert", "David", "Richard", "Joseph", "Charles", "Paul", "Daniel", "Mark", "George", "Steven", "Edward", "Brian", "Donald", "Ronald", "Jose", "Gary", "Timothy", "Joshua", "Raymond", "Andrew", "Jacob", "Henry", "Carl", "Ryan", "Roger", "Harold", "Samuel", "Benjamin", "Adam", "Harry", "Jeremy", "Aaron"}; for(String singleName:firstNamesDudes) { this.MALE_NAMES.add(singleName); } } /** * Initializes the FEMALE_NAMES array list. */ private void setFemaleNames() { String[] firstNamesChicks = new String[]{"Mary", "Patricia", "Linda", "Barbara", "Jennifer", "Elizabeth", "Maria", "Holly", "Shannon", "Trudy", "Nancy", "Lisa", "Susan", "Karen", "Natalie", "Katherine", "Ruth", "Donna", "Carol", "Virginia", "Rebecca", "Sarah", "Rachel", "Allison", "Katelyn", "Karla", "Aubrey", "Samantha", "Alexandra", "Hannah", "Melissa", "Amy", "Martha", "Debra", "Janet", "Julie"}; for(String singleName:firstNamesChicks) { this.FEMALE_NAMES.add(singleName); } } /** * Initializes the LAST_NAMES array list. */ private void setLastNames() { String[] lastNames = new String[]{"Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore", "Taylor", "Anderson", "Jackson", "White", "Harris", "Martin", "Pugmire", "Yorgason", "Briggs", "Vanderwerken", "VanCott", "Davidson", "West", "Jacklyn", "Hernandez", "Scott", "Hill", "Baker", "Wright", "King", "Walker", "Allen", "Lee", "Robinson", "Clark", "Martinez", "Garcia", "Philips", "Turner", "Parker", "Evans", "Collins", "Edwards", "Carter", "Mitchell", "James", "Roberts", "Cook", "Reed", "Stewards", "Winfrey", "Murphey", "Bell", "Morgan", "Cook"}; for(String singleName: lastNames) { this.LAST_NAMES.add(singleName); } } /** * Initializes the CITIES array list. Index positions match exactly with the other * location array lists to make event creation easier. */ private void setCities() { String[] cities = new String[]{"Boise", "Salt Lake City", "Ogden", "Orem", "Provo", "Saint George", "Twin Falls", "Rigby", "Jerome", "Fillmore", "Beaver", "Logan", "Brigham City", "Burley", "Rupert", "Rexburg", "Santaquin", "Tooele", "Sandy", "Riverton", "Nephi", "Delta", "Emery", "Price", "Spanish Fork", "West Valley City", "Moab", "Auburn", "Jamestown", "Fulton", "Bedford", "Stuart", "San Angelo", "Woodbridge", "Vista", "South Bend", "Davenport", "Sparks", "Green Bay", "San Mateo", "Tyler", "League City", "Lewisville", "Waterbury", "Jurupa Valley", "West Palm Beach", "Antioch", "High Point", "Miami Gardens", "Murrieta", "Springfield", "El Monte", "College Station", "Richardson", "Berkeley", "Columbia", "Athens", "Lafayette", "Hampton", "Pasadena", "Paterson", "Rockford", "Joliet", "Kansas City", "Vancouver", "Tallahassee", "Columbus", "Amarillo", "Irvine", "Arlington", "Memphis", "Indianapolis", "Dallas", "Gastonia", "Forestville", "Houston", "Yuma", "Tempe", "Peoria", "Bloomington", "Utqiagvik", "Fargo"}; for(String singleCity: cities) { this.CITIES.add(singleCity); } } /** * Initializes the COUNTRIES array list. Currently we only care about USA cities so her we are. */ private void setCountries() { String[] countries = new String[]{"USA"}; for(String singleCountry: countries) { this.COUNTRIES.add(singleCountry); } } /** * Initializes the LATITUDES array list. Index positions match exactly with the other * location array lists to make event creation easier. */ private void setLatitudes() { double[] latitudes = new double[]{43.615791, 40.760780, 41.222759, 40.297119, 40.233845, 37.108284, 42.563181, 43.672219, 42.724137, 38.96675, 38.279582, 41.735211, 41.510372, 42.538116, 42.616386, 43.826071, 39.97558, 40.534265, 40.569705, 40.518701, 39.71002, 39.352381, 38.923149, 39.599506, 40.115007, 40.696682, 38.571738, 42.933334, 42.095554, 38.846668, 41.392502, 27.192223, 31.442778, 40.560001, 33.193611, 41.676388, 41.543056, 39.554443, 44.513332, 37.554169, 32.349998, 29.499722, 33.038334, 41.556110, 34.000000, 26.709723, 38.005001, 35.970554, 25.942122, -80.269920, 39.799999, 34.073334, 30.601389, 32.965557, 37.871666, 38.951561, 33.950001, 30.216667, 37.034946, 34.156113, 40.914745, 42.259445, 41.520557, 39.106667, 45.633331, 30.455000, 32.492222, 35.199165, 33.669445, 32.705002, 35.117500, 39.791000, 32.779167, 35.255280, 38.473625, 29.749907, 32.698437,33.427204, 33.580944, 44.840797, 71.290558, 46.877186 }; for(double singleLat: latitudes) { this.LATITUDES.add(singleLat); } } /** * Initializes the LONGITUDES array list. Index positions match exactly with the other * location array lists to make event creation easier. */ private void setLongitudes() { double[] longitudes = new double[]{-116.201576, -111.891045, -111.970421, -111.695007, -111.658531, -113.583277, -114.460278, -111.914829, -114.518435, -112.323686, -112.641291, -111.834857, -112.015716, -113.793261, -113.67082, -111.789532, -111.785249, -112.298452, -111.897282, -111.931665, -111.828546, -112.57362, -111.250477, -110.811215, -111.654713, -111.959172, -109.550796, -76.566666, -79.238609, -91.948059, -81.534447, -80.243057, -100.450279, -74.290001, -117.241112, -86.250275, -90.590836, -119.735558, -88.015831, -122.313057, -95.300003, -95.089722, -97.006111, -73.041389, -117.483330, -80.064163, -121.805832, -79.997498, -80.269920, -117.202499, -89.650002, -118.027496, -96.314445, -96.715836, -122.272781, -92.328636, -83.383331, -92.033333, -76.360123, -118.131943, -74.162827, -89.064445, -88.150558, -94.676392, -122.599998, -84.253334, -84.940277, -101.845276, -117.823059, -97.122780, -89.971107, -86.148003, -96.808891, -81.180275, -122.889992, -95.358421, -114.650398, -111.939896, -112.237068, -93.298279, -156.788605, -96.789803 }; for(double singleLong: longitudes) { this.LONGITUDES.add(singleLong); } } /** * Initializes all of the class member variables that we need. * I keep this out of the main functions to keep things more clear. */ private void setUpDataForFill() { setMaleNames(); setFemaleNames(); setLastNames(); setCities(); setCountries(); setLatitudes(); setLongitudes(); } /** * Creates an object that represents a parent * @param personID Identifier of the person to create * @param gender Gender of the person * @param lastName lastName of the person. Is NULL if male * @return A Person object representing a child's parent */ private Person createPersonObject(String personID, String gender, String firstName, String lastName, boolean isRootPerson) { // Randomly make their username, first name, and mom's last name String firstNameCopy = firstName; String lastNameCopy = lastName; Person person = new Person(personID, UUID.randomUUID().toString(), firstNameCopy, lastNameCopy, gender, UUID.randomUUID().toString(), UUID.randomUUID().toString(), null); return person; } /** * Creates an object that represents a parent * @param personID Identifier of the person to create * @param gender Gender of the person * @param lastName lastName of the person. Is NULL if male * @return A Person object representing a child's parent */ private Person createPersonObject(String personID, String gender, String lastName, boolean isRootPerson) { // Randomly make their username, first name, and mom's last name String firstName; String lastNameCopy = lastName; if(gender.equals("f")) { firstName = getRandomFemaleName(); lastNameCopy = getRandomLastName(); } else { if(isRootPerson) { lastNameCopy = getRandomLastName(); } firstName = getRandomMaleName(); } Person person = new Person(personID, UUID.randomUUID().toString(), firstName, lastNameCopy, gender, UUID.randomUUID().toString(), UUID.randomUUID().toString(), null); return person; } /** * Recursively generates person and event data for the requested number of generations * and adds the generated objects to the generatedPersons and generatedEvent array lists * @param child Object representing a child * @param childBirthYear Year the child was born * @param generations The number of generations to generate */ private void generateAncestry(Person child, int childBirthYear, int generations) { if(generations == 0) { return; } // Generate Mom and Dad // Get their personID's from child Person mom = createPersonObject(child.getMotherId(), "f", null, false); Person dad = createPersonObject(child.getFatherId(), "m", child.getLastName(), false); // Set the parent's associatedUserName mom.setAssociatedUsername(child.getAssociatedUsername()); dad.setAssociatedUsername(child.getAssociatedUsername()); if(generations == 1) { mom.setMotherId(null); mom.setFatherId(null); dad.setMotherId(null); dad.setFatherId(null); } // dad and mom get spouse id from each other mom.setSpouseId(dad.getPersonID()); dad.setSpouseId(mom.getPersonID()); // Add dad and mom to the generatedPersons data this.generatedPersons.add(mom); this.generatedPersons.add(dad); // Marry mom and dad // Create identical marriage events just with their own personID's and associatedUsernames Event momMarriage = generateWifeMarriageEvent(mom, dad, childBirthYear); Event dadMarriage = generateHusbandMarriage(momMarriage, dad); // Add the two events to the generatedEventsData this.generatedEvents.add(momMarriage); this.generatedEvents.add(dadMarriage); // Create mom and dads birthdays, deathdays, and baptisms // Get their birth years for the recursive call int dadBirthYear = generateAndAddParentLifeEvents(dad, dadMarriage.getYear(), childBirthYear); int momBirthYear = generateAndAddParentLifeEvents(mom, momMarriage.getYear(), childBirthYear); int parentsMarriageYear = dadMarriage.getYear(); // generateAncestry on dad and mom. int dadsGenerationsNum = generations - 1; int momsGenerationsNum = generations - 1; generateAncestry(dad, dadBirthYear, dadsGenerationsNum); generateAncestry(mom, momBirthYear, momsGenerationsNum); } /** * Creates an event object for any given eventType * @param eventType The type of event * @param eventYear When the event happened. * @param person Person for whom the event belongs * @return An Event object */ private Event createEvent(String eventType, int eventYear, Person person) { int randomIndexForLocation = random.nextInt(this.CITIES.size()); String city = this.CITIES.get(randomIndexForLocation); double latitude = this.LATITUDES.get(randomIndexForLocation); double longitude = this.LONGITUDES.get(randomIndexForLocation); String country = this.COUNTRIES.get(0); return new Event(UUID.randomUUID().toString(), person.getAssociatedUsername(), person.getPersonID(), latitude, longitude, country, city, eventType, eventYear); } private Event generateHusbandMarriage(Event wifeMarriage, Person husband) { return new Event(wifeMarriage.getEventID(), husband.getAssociatedUsername(), husband.getPersonID(), wifeMarriage.getLatitude(), wifeMarriage.getLongitude(), wifeMarriage.getCountry(), wifeMarriage.getCity(), wifeMarriage.getEventType(), wifeMarriage.getYear()); } /** * Create a parents birthday, baptism, and maybe death event * @param parent Person object representing the parent * @param marriageYear The year the parent was married * @return The parent's birth year */ private int generateAndAddParentLifeEvents(Person parent, int marriageYear, int childBirthYear) { int birthYear = getParentBirthYear(marriageYear, childBirthYear); int baptismYear = birthYear + 8; // They ALL are members of the church haha Event birth = createEvent("Birth", birthYear, parent); Event baptism = createEvent("Baptism", baptismYear, parent); this.generatedEvents.add(birth); this.generatedEvents.add(baptism); int parentAgeAtMarriage = marriageYear - birthYear; // For the test cases the parents are always dead. // MAX_DEATH_AGE - currentParentAge. I do this so the parent dies at 120 or under. int deathYear = marriageYear + random.nextInt(MAX_DEATH_AGE - parentAgeAtMarriage); Event death = createEvent("Death", deathYear, parent); this.generatedEvents.add(death); return birthYear; } /** * Generates a marriage event for the wife only. Husband marriage event can be coppied * and then its event associatedUsername and personID can be manually set. * @param wife Person object representing the wife * @param husband Person object representing the wife * @param childBirthYear Year the couples child was born * @return An Event object representing the marriage */ private Event generateWifeMarriageEvent(Person wife, Person husband, int childBirthYear) { int randomIndexForLocation = random.nextInt(this.CITIES.size()); String city = this.CITIES.get(randomIndexForLocation); double latitude = this.LATITUDES.get(randomIndexForLocation); double longitude = this.LONGITUDES.get(randomIndexForLocation); String country = this.COUNTRIES.get(0); int marriageYear = childBirthYear - random.nextInt(7); // We will say that all children are born // within 6 years of marriage Event wifeMarriage = new Event(UUID.randomUUID().toString(), wife.getAssociatedUsername(), wife.getPersonID(), latitude, longitude, country, city, "Marriage", marriageYear); return wifeMarriage; } /** * @return A random female name */ private String getRandomFemaleName() { int randomIndex = random.nextInt(this.FEMALE_NAMES.size()); return this.FEMALE_NAMES.get(randomIndex); } /** @return A random male name */ private String getRandomMaleName() { int randomIndex = random.nextInt(this.MALE_NAMES.size()); return this.MALE_NAMES.get(randomIndex); } /** * @return A random last name */ private String getRandomLastName() { int randomIndex = random.nextInt(this.LAST_NAMES.size()); return this.LAST_NAMES.get(randomIndex); } private void createDaosAndSetConnections(Database db) { eventDao = new EventDao(); personDao = new PersonDao(); userDao = new UserDao(); eventDao.setConnection(db.getConnection()); personDao.setConnection(db.getConnection()); userDao.setConnection(db.getConnection()); } private void insertEventsAndPersonsIntoDatabase() { try { for(Event singleEvent: this.generatedEvents) { eventDao.insertEvent(singleEvent); } for(Person singlePerson: this.generatedPersons) { personDao.insertPerson(singlePerson); } } catch(DatabaseException ex) { System.out.println("Problem in insertEventsAndPersonsIntoDatabase() function in FillService class: " + ex.getMessage()); } } private void setUpDatabase(Database db) { try { db.loadDriver(); db.openConnection(); db.initializeTables(); db.commitConnection(true); } catch(DatabaseException ex) { System.out.println("Problem in setUpDatabase() function in FillService class: " + ex.getMessage()); } } private void setRootPersonAndAddToGeneratedPersons(Person rootPerson, String userName, Person preDeletePersonCopy) { rootPerson.setAssociatedUsername(userName); rootPerson.setPersonID(preDeletePersonCopy.getPersonID()); this.generatedPersons.add(rootPerson); } private void generateFillPersonBirthAndAddToGeneratedEvents(int birthYear, Person rootPerson) { Event childBirth = createEvent("Birth", birthYear, rootPerson); // Makes sure the preDeletePerson is born this.generatedEvents.add(childBirth); } private Person createRootPerson(Person preDeletePersonCopy) { // String gender; // // // Randomly get person's gender // int result = random.nextInt(2); // if(result == 0){ // gender = "m"; // } else{ // gender = "f"; // } return createPersonObject(preDeletePersonCopy.getPersonID(), preDeletePersonCopy.getGender(), preDeletePersonCopy.getFirstName(), preDeletePersonCopy.getLastName(), true); } private FillResult errorCheckParameters(String userName, int generations, Database db) { if(userName == null) { try { db.closeConnection(); } catch (DatabaseException e) { e.printStackTrace(); } return new FillResult(ApiResult.INVALID_FILL_PARAM, "userName is null"); } if(generations < 0) { try { db.closeConnection(); } catch (DatabaseException e) { e.printStackTrace(); } return new FillResult(ApiResult.INVALID_FILL_PARAM, "Must request non-negative number of " + "generations. Generations requested: " + generations); } return null; } private void deletePreExistingUserData(String userName, Person preDeletePersonCopy, Database db) { try { eventDao.deleteAllEventsForAssociatedUsername(userName); personDao.deletePerson(preDeletePersonCopy.getPersonID()); db.commitConnection(true); } catch(DatabaseException ex) { System.out.println("Problem in deletePreExistingUserData() function in FillService class: " + ex.getMessage()); } } private FillResult finishFill(Database db) { try { db.commitConnection(true); db.closeConnection(); return new FillResult(this.generatedPersons.size(), this.generatedEvents.size()); } catch(DatabaseException ex) { System.out.println("Problem in finishFill() function in FillService class: " + ex.getMessage()); } return null; } private int getParentBirthYear(int marriageYear, int childBirthYear) { boolean getNewParentBirthYear = true; int parentBirthYear = 0; // Make parent 13 years older than child while(getNewParentBirthYear) { // We are assuming people will get married between 18 and 24 years of age // So we get their birthYear by saying they are 18 + (0 to 6) years old when they were married. parentBirthYear = marriageYear - (ADULT_AGE + random.nextInt(7)); // Get's a random ma // Check if parent-child age difference is ok int parentChildAgeDifference = parentBirthYear - childBirthYear; if(parentChildAgeDifference >= MIN_PARENT_CHILD_AGE_DIFFERENCE) getNewParentBirthYear = false; // Check if maximum birthing age for parent is ok int parentAgeAtChildBirth = (childBirthYear - parentBirthYear); if(parentAgeAtChildBirth <= MAX_BIRTHING_AGE) getNewParentBirthYear = false; } return parentBirthYear; } }
true
286a02b9d93583349d7945f3f03020f44b7e401d
Java
wigforss/Ka-Spring
/spring-2.5/src/main/java/org/kasource/spring/transaction/package-info.java
UTF-8
484
1.765625
2
[]
no_license
/** * Transaction Utility classes. * * <b>TransactionListener</b> * Implement this interface to listen to transaction events. * * <b>TransactionResult</b> * An enumeration of possible outcomes when a transaction is committed. * * <b>TransactionSupport</b> * Lets the client register itself as a TransactionListener. * * <b>TransactionSupportImpl</b> * Implementation of TransactionSupport. * * * * @author rikardwi **/ package org.kasource.spring.transaction;
true
8b3d4068d4c87a4496a82d6a44fae855ff27375e
Java
CorbaVerteilteSysteme2/Iteration1
/IDL-Definitions/src/idls/BoardModules/BasicServices/_AdministrationServiceStub.java
UTF-8
7,742
1.765625
2
[]
no_license
package BoardModules.BasicServices; /** * BoardModules/BasicServices/_AdministrationServiceStub.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from idls/BoardModules.idl * Donnerstag, 14. Januar 2016 14:02 Uhr MEZ */ public class _AdministrationServiceStub extends org.omg.CORBA.portable.ObjectImpl implements BoardModules.BasicServices.AdministrationService { public void createVirtualGroup (String vgroupname) { org.omg.CORBA.portable.InputStream $in = null; try { org.omg.CORBA.portable.OutputStream $out = _request ("createVirtualGroup", true); $out.write_string (vgroupname); $in = _invoke ($out); return; } catch (org.omg.CORBA.portable.ApplicationException $ex) { $in = $ex.getInputStream (); String _id = $ex.getId (); throw new org.omg.CORBA.MARSHAL (_id); } catch (org.omg.CORBA.portable.RemarshalException $rm) { createVirtualGroup (vgroupname ); } finally { _releaseReply ($in); } } // createVirtualGroup public void loginToVirtualGroup (String vgroupname) { org.omg.CORBA.portable.InputStream $in = null; try { org.omg.CORBA.portable.OutputStream $out = _request ("loginToVirtualGroup", true); $out.write_string (vgroupname); $in = _invoke ($out); return; } catch (org.omg.CORBA.portable.ApplicationException $ex) { $in = $ex.getInputStream (); String _id = $ex.getId (); throw new org.omg.CORBA.MARSHAL (_id); } catch (org.omg.CORBA.portable.RemarshalException $rm) { loginToVirtualGroup (vgroupname ); } finally { _releaseReply ($in); } } // loginToVirtualGroup public String[] getAllVirtualGroups () { org.omg.CORBA.portable.InputStream $in = null; try { org.omg.CORBA.portable.OutputStream $out = _request ("getAllVirtualGroups", true); $in = _invoke ($out); String $result[] = BoardModules.StringListHelper.read ($in); return $result; } catch (org.omg.CORBA.portable.ApplicationException $ex) { $in = $ex.getInputStream (); String _id = $ex.getId (); throw new org.omg.CORBA.MARSHAL (_id); } catch (org.omg.CORBA.portable.RemarshalException $rm) { return getAllVirtualGroups ( ); } finally { _releaseReply ($in); } } // getAllVirtualGroups public void forwardMessageToBoards (String[] boards, BoardModules.Message message) throws BoardModules.DestinationUnreachable { org.omg.CORBA.portable.InputStream $in = null; try { org.omg.CORBA.portable.OutputStream $out = _request ("forwardMessageToBoards", true); BoardModules.StringListHelper.write ($out, boards); BoardModules.MessageHelper.write ($out, message); $in = _invoke ($out); return; } catch (org.omg.CORBA.portable.ApplicationException $ex) { $in = $ex.getInputStream (); String _id = $ex.getId (); if (_id.equals ("IDL:BoardModules/DestinationUnreachable:1.0")) throw BoardModules.DestinationUnreachableHelper.read ($in); else throw new org.omg.CORBA.MARSHAL (_id); } catch (org.omg.CORBA.portable.RemarshalException $rm) { forwardMessageToBoards (boards, message ); } finally { _releaseReply ($in); } } // forwardMessageToBoards public void createUser (BoardModules.User newuser) { org.omg.CORBA.portable.InputStream $in = null; try { org.omg.CORBA.portable.OutputStream $out = _request ("createUser", true); BoardModules.UserHelper.write ($out, newuser); $in = _invoke ($out); return; } catch (org.omg.CORBA.portable.ApplicationException $ex) { $in = $ex.getInputStream (); String _id = $ex.getId (); throw new org.omg.CORBA.MARSHAL (_id); } catch (org.omg.CORBA.portable.RemarshalException $rm) { createUser (newuser ); } finally { _releaseReply ($in); } } // createUser public String[] getAllUsers () { org.omg.CORBA.portable.InputStream $in = null; try { org.omg.CORBA.portable.OutputStream $out = _request ("getAllUsers", true); $in = _invoke ($out); String $result[] = BoardModules.StringListHelper.read ($in); return $result; } catch (org.omg.CORBA.portable.ApplicationException $ex) { $in = $ex.getInputStream (); String _id = $ex.getId (); throw new org.omg.CORBA.MARSHAL (_id); } catch (org.omg.CORBA.portable.RemarshalException $rm) { return getAllUsers ( ); } finally { _releaseReply ($in); } } // getAllUsers public void removeUser (BoardModules.User user) throws BoardModules.UnknownUser { org.omg.CORBA.portable.InputStream $in = null; try { org.omg.CORBA.portable.OutputStream $out = _request ("removeUser", true); BoardModules.UserHelper.write ($out, user); $in = _invoke ($out); return; } catch (org.omg.CORBA.portable.ApplicationException $ex) { $in = $ex.getInputStream (); String _id = $ex.getId (); if (_id.equals ("IDL:BoardModules/UnknownUser:1.0")) throw BoardModules.UnknownUserHelper.read ($in); else throw new org.omg.CORBA.MARSHAL (_id); } catch (org.omg.CORBA.portable.RemarshalException $rm) { removeUser (user ); } finally { _releaseReply ($in); } } // removeUser // Type-specific CORBA::Object operations private static String[] __ids = { "IDL:BoardModules/BasicServices/AdministrationService:1.0"}; public String[] _ids () { return (String[])__ids.clone (); } private void readObject (java.io.ObjectInputStream s) throws java.io.IOException { String str = s.readUTF (); String[] args = null; java.util.Properties props = null; org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); try { org.omg.CORBA.Object obj = orb.string_to_object (str); org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); _set_delegate (delegate); } finally { orb.destroy() ; } } private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException { String[] args = null; java.util.Properties props = null; org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); try { String str = orb.object_to_string (this); s.writeUTF (str); } finally { orb.destroy() ; } } } // class _AdministrationServiceStub
true
77664dde15e17e2da792fed72b1a5112a24e080a
Java
pac4j/pac4j
/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/facebook/FacebookMusicListen.java
UTF-8
5,425
2.234375
2
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
package org.pac4j.oauth.profile.facebook; import java.io.Serial; import java.io.Serializable; import java.util.Date; import static org.pac4j.core.util.CommonHelper.newDate; /** * This class represents a Facebook music listened. * * @author Jerome Leleu * @since 1.2.0 */ public final class FacebookMusicListen implements Serializable { @Serial private static final long serialVersionUID = 3904637830042371121L; private String id; private FacebookObject from; private Date startTime; private Date endTime; private Date publishTime; private FacebookApplication application; private FacebookMusicData song; private FacebookMusicData musician; private FacebookMusicData radioStation; private String type; private Boolean noFeedStory; /** * <p>Getter for the field <code>id</code>.</p> * * @return a {@link String} object */ public String getId() { return id; } /** * <p>Setter for the field <code>id</code>.</p> * * @param id a {@link String} object */ public void setId(String id) { this.id = id; } /** * <p>Getter for the field <code>from</code>.</p> * * @return a {@link FacebookObject} object */ public FacebookObject getFrom() { return from; } /** * <p>Setter for the field <code>from</code>.</p> * * @param from a {@link FacebookObject} object */ public void setFrom(FacebookObject from) { this.from = from; } /** * <p>Getter for the field <code>startTime</code>.</p> * * @return a {@link Date} object */ public Date getStartTime() { return newDate(startTime); } /** * <p>Setter for the field <code>startTime</code>.</p> * * @param startTime a {@link Date} object */ public void setStartTime(Date startTime) { this.startTime = newDate(startTime); } /** * <p>Getter for the field <code>endTime</code>.</p> * * @return a {@link Date} object */ public Date getEndTime() { return newDate(endTime); } /** * <p>Setter for the field <code>endTime</code>.</p> * * @param endTime a {@link Date} object */ public void setEndTime(Date endTime) { this.endTime = newDate(endTime); } /** * <p>Getter for the field <code>publishTime</code>.</p> * * @return a {@link Date} object */ public Date getPublishTime() { return newDate(publishTime); } /** * <p>Setter for the field <code>publishTime</code>.</p> * * @param publishTime a {@link Date} object */ public void setPublishTime(Date publishTime) { this.publishTime = newDate(publishTime); } /** * <p>Getter for the field <code>application</code>.</p> * * @return a {@link FacebookApplication} object */ public FacebookApplication getApplication() { return application; } /** * <p>Setter for the field <code>application</code>.</p> * * @param application a {@link FacebookApplication} object */ public void setApplication(FacebookApplication application) { this.application = application; } /** * <p>Getter for the field <code>type</code>.</p> * * @return a {@link String} object */ public String getType() { return type; } /** * <p>Setter for the field <code>type</code>.</p> * * @param type a {@link String} object */ public void setType(String type) { this.type = type; } /** * <p>Getter for the field <code>noFeedStory</code>.</p> * * @return a {@link Boolean} object */ public Boolean getNoFeedStory() { return noFeedStory; } /** * <p>Setter for the field <code>noFeedStory</code>.</p> * * @param noFeedStory a {@link Boolean} object */ public void setNoFeedStory(Boolean noFeedStory) { this.noFeedStory = noFeedStory; } /** * <p>Getter for the field <code>song</code>.</p> * * @return a {@link FacebookMusicData} object */ public FacebookMusicData getSong() { return song; } /** * <p>Setter for the field <code>song</code>.</p> * * @param song a {@link FacebookMusicData} object */ public void setSong(FacebookMusicData song) { this.song = song; } /** * <p>Getter for the field <code>musician</code>.</p> * * @return a {@link FacebookMusicData} object */ public FacebookMusicData getMusician() { return musician; } /** * <p>Setter for the field <code>musician</code>.</p> * * @param musician a {@link FacebookMusicData} object */ public void setMusician(FacebookMusicData musician) { this.musician = musician; } /** * <p>Getter for the field <code>radioStation</code>.</p> * * @return a {@link FacebookMusicData} object */ public FacebookMusicData getRadioStation() { return radioStation; } /** * <p>Setter for the field <code>radioStation</code>.</p> * * @param radioStation a {@link FacebookMusicData} object */ public void setRadioStation(FacebookMusicData radioStation) { this.radioStation = radioStation; } }
true
6bd68a08b1a830641bbc17ce556c80104a935e0f
Java
genepattern/genepattern-server
/src/org/genepattern/server/webapp/jsf/JobResultsFilterBean.java
UTF-8
6,182
1.921875
2
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
/******************************************************************************* * Copyright (c) 2003-2022 Regents of the University of California and Broad Institute. All rights reserved. *******************************************************************************/ package org.genepattern.server.webapp.jsf; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.faces.model.SelectItem; import org.genepattern.server.UserAccountManager; import org.genepattern.server.auth.GroupPermission; import org.genepattern.server.auth.IGroupMembershipPlugin; import org.genepattern.server.domain.BatchJob; import org.genepattern.server.domain.BatchJobDAO; import org.genepattern.server.user.UserDAO; import org.genepattern.server.webservice.server.dao.AnalysisDAO; /** * Backing bean for the drop-down menu on the Job Results page. * Save values to database so they can be loaded in the next session. * * @author pcarr */ public class JobResultsFilterBean implements Serializable { private String userId = null; private boolean showEveryonesJobs = false; private String selectedGroup = null; private Set<String> selectedGroups = new HashSet<String>(); //cached values private int jobCount = -1; public JobResultsFilterBean() { //requires a valid user id setUserId(UIBeanHelper.getUserId()); } public void setUserId(String userId) { this.userId = userId; this.jobCount = -1; this.showEveryonesJobs = Boolean.valueOf(new UserDAO().getPropertyValue(userId, "showEveryonesJobs", String.valueOf(showEveryonesJobs))); this.selectedGroups.clear(); this.selectedGroup = new UserDAO().getPropertyValue(userId, "jobResultsFilter", null); if (selectedGroup != null) { this.selectedGroups.add(selectedGroup); this.showEveryonesJobs = false; } } public Object getJobFilter() { String displayBatch = (String) UIBeanHelper.getSession().getAttribute(JobBean.DISPLAY_BATCH); if (displayBatch != null) { selectedGroup = BatchJob.BATCH_KEY + displayBatch; } if (selectedGroup != null) { return selectedGroup; } if (showEveryonesJobs) { return "#ALL_JOBS"; } else { return "#MY_JOBS"; } } public void setJobFilter(Object obj) { this.jobCount = -1; this.selectedGroup = null; this.selectedGroups.clear(); this.showEveryonesJobs = false; String menuVal = null; if (obj instanceof String) { menuVal = (String) obj; } if (menuVal != null && menuVal.equals("#MY_JOBS")) { } else if (menuVal != null && menuVal.equals("#ALL_JOBS")) { this.showEveryonesJobs = true; } else if (menuVal != null) { selectedGroup = menuVal; selectedGroups.add(menuVal); } UserDAO userDao = new UserDAO(); userDao.setProperty(UIBeanHelper.getUserId(), "showEveryonesJobs", String.valueOf(showEveryonesJobs)); userDao.setProperty(UIBeanHelper.getUserId(), "jobResultsFilter", selectedGroup); } public List<SelectItem> getJobFilterMenu() { List<SelectItem> rval = new ArrayList<SelectItem>(); rval.add(new SelectItem("#MY_JOBS", "My job results")); rval.add(new SelectItem("#ALL_JOBS", "All job results")); //add groups to the list String userId = UIBeanHelper.getUserId(); IGroupMembershipPlugin groupMembership = UserAccountManager.instance().getGroupMembership(); Set<String> groups = new HashSet<String>(groupMembership.getGroups(userId)); List<BatchJob> batches = new BatchJobDAO().findByUserId(userId); if (groups.contains(GroupPermission.PUBLIC)) { rval.add(new SelectItem(GroupPermission.PUBLIC, "Public job results")); groups.remove(GroupPermission.PUBLIC); } for(String group : groups) { rval.add(new SelectItem(group, "In group: " + group)); } for (BatchJob batchJob: batches){ rval.add(new SelectItem(BatchJob.BATCH_KEY+batchJob.getJobNo(), "Batch: "+batchJob.getJobNo())); } return rval; } public void resetJobCount() { this.jobCount = -1; } public int getJobCount() { if (jobCount < 0) { if (selectedGroup != null) { if (selectedGroup.startsWith(BatchJob.BATCH_KEY)){ jobCount = new BatchJobDAO().getNumBatchJobs(selectedGroup); return jobCount; }else{ // get the count of jobs in the selected group this.jobCount = new AnalysisDAO().getNumJobsInGroups(selectedGroups); return this.jobCount; } } else if (!showEveryonesJobs) { this.jobCount = new AnalysisDAO().getNumJobsByUser(userId); return this.jobCount; } boolean isAdmin = AuthorizationHelper.adminServer(); if (isAdmin) { this.jobCount = new AnalysisDAO().getNumJobsTotal(); return this.jobCount; } IGroupMembershipPlugin groupMembership = UserAccountManager.instance().getGroupMembership(); Set<String> groups = groupMembership.getGroups(userId); this.jobCount = new AnalysisDAO().getNumJobsByUser(userId, groups); return this.jobCount; } return jobCount; } //legacy support (not to be called from JSF pages, but rather from JobBean.java) public boolean isShowEveryonesJobs() { return showEveryonesJobs; } public void setSelectedGroup(String selectedGroup) { this.selectedGroup = selectedGroup; } public String getSelectedGroup() { return selectedGroup; } public Set<String> getSelectedGroups() { return selectedGroups; } }
true
15e82ad548c101b54487c002ade5b59df0b172bc
Java
ArseniyJ4J/akulikov
/chapter_001/src/main/java/ru/job4j/array/ArrayDuplicate.java
UTF-8
758
3.578125
4
[ "Apache-2.0" ]
permissive
package ru.job4j.array; import java.util.Arrays; /** * Class Delete duplicate of string array. * @author akulikov * @since 11.05.2017 * @version 1 */ public class ArrayDuplicate { /** * Метод выполняющий удаление дубликатов в массиве строк. * @param array - массив строк. * @return - возвращение. */ public String[] remove(String[] array) { int lim = array.length - 1; int z = 0; for (int i = 0; i < lim; i++) { for (int e = i + 1; e <= lim - z; e++) { String buffer; if (array[i] == array[e]) { buffer = array[e]; array[e] = array[lim - z]; array[lim - z] = buffer; z++; e--; } } } return Arrays.copyOf(array, array.length - z); } }
true
ce528ac2a00a0df2beb0ce0855cfca92e3d8559a
Java
JingShan666/LmModel
/Moteduan/src/main/java/bbc/com/moteduan_lib/renzheng/WaitingDialog.java
UTF-8
1,987
2.421875
2
[]
no_license
package bbc.com.moteduan_lib.renzheng; import bbc.com.moteduan_lib.R; public class WaitingDialog extends android.app.Dialog{ private android.content.Context mContext; private boolean isCancel; private String message; private android.view.View mView; private static WaitingDialog mDialog; /** * 弹出等待框 */ public static synchronized void show(android.content.Context context, String message, Boolean isCancel){ if (mDialog != null) { mDialog.cancel(); mDialog = null; } mDialog = new WaitingDialog(context, message, isCancel); mDialog.show(); } /** * 取消等待框 */ public static synchronized void cancelDialog(){ if (mDialog != null) { mDialog.cancel(); mDialog = null; } } public WaitingDialog(android.content.Context context, String message, Boolean isCancel) { super(context); this.mContext = context; this.isCancel = isCancel; this.message = message; } public void setMessage(String strMessage){ if(mView != null){ ((android.widget.TextView)mView.findViewById(R.id.tv)).setText(strMessage); } } @Override public synchronized void show() { setCancelable(isCancel); requestWindowFeature(android.view.Window.FEATURE_NO_TITLE); getWindow().setBackgroundDrawableResource(R.drawable.waiting_dialog_bg); getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN, android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN); if(message==null || message.equals("")){ setContentView(R.layout.waiting_dialog); }else { mView = android.view.LayoutInflater.from(mContext).inflate(R.layout.waiting_dialog, null); setMessage(message); setContentView(mView); } super.show(); } public synchronized void cancel(){ dismiss(); } @Override public boolean onKeyDown(int keyCode, android.view.KeyEvent event) { if(keyCode == android.view.KeyEvent.KEYCODE_BACK && isCancel){ dismiss(); return true; } return super.onKeyDown(keyCode, event); } }
true
68a2777304cef24014bb45fbb9060c6ad36efbcd
Java
haifeiforwork/ehr-moo
/ikep4-lightpack/src/main/java/com/lgcns/ikep4/lightpack/award/service/impl/AwardAdminServiceImpl.java
UTF-8
25,784
1.789063
2
[]
no_license
/* * Copyright (C) 2011 LG CNS Inc. * All rights reserved. * * 모든 권한은 LG CNS(http://www.lgcns.com)에 있으며, * LG CNS의 허락없이 소스 및 이진형식으로 재배포, 사용하는 행위를 금지합니다. */ package com.lgcns.ikep4.lightpack.award.service.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import com.lgcns.ikep4.lightpack.award.dao.AwardDao; import com.lgcns.ikep4.lightpack.award.model.Award; import com.lgcns.ikep4.lightpack.award.model.AwardGroup; import com.lgcns.ikep4.lightpack.award.service.AwardAdminService; import com.lgcns.ikep4.lightpack.award.service.AwardItemService; import com.lgcns.ikep4.support.security.acl.model.ACLGroupPermission; import com.lgcns.ikep4.support.security.acl.model.ACLResourcePermission; import com.lgcns.ikep4.support.security.acl.service.ACLService; import com.lgcns.ikep4.support.user.group.model.Group; import com.lgcns.ikep4.support.user.member.model.User; import com.lgcns.ikep4.support.user.role.model.Role; import com.lgcns.ikep4.util.idgen.service.IdgenService; /** * AwardAdminService 구현체 클래스 */ @Service public class AwardAdminServiceImpl implements AwardAdminService { /** The log. */ protected final Log log = LogFactory.getLog(this.getClass()); /** The award dao. */ @Autowired private AwardDao awardDao; /** The idgen service. */ @Autowired private IdgenService idgenService; @SuppressWarnings("unused") @Autowired private AwardItemService awardItemService; @Autowired private ACLService aclService; /** 위지윅에디터에서 업로드 가능한 이미지 미디어타입 목록 */ private final List<String> supportedImageMediaTypeList = Arrays.asList("image/gif", "image/jpeg", "image/png", "image/swf", "image/psd", "image/bmp", "image/tiff_ii", "image/tiff_mm", "image/jpc", "image/jp2", "image/jpx", "image/jb2", "image/swc", "image/iff", "image/wbmp", "image/xbm"); /* * (non-Javadoc) * @see com.lgcns.ikep4.lightpack.award.service.AwardAdminService# * checkSupportedImageMediaType(java.lang.String) */ public Boolean checkSupportedImageMediaType(String imageType) { for(String target : this.supportedImageMediaTypeList) { if(target.equals(imageType)) { return true; } } return false; //return Arrays.binarySearch(this.supportedImageMediaTypeList.toArray(new String[0]), imageType) > 0; } /** * 게시판 목록 */ public List<Award> listByAwardRootIdMap(Map<String, String> map) { List<Award> awardList = this.awardDao.listByAwardRootIdMap(map); return awardList; } /* * (non-Javadoc) * @see * com.lgcns.ikep4.lightpack.award.service.AwardAdminService#listByAwardRootId * (java.lang.String) */ public List<Award> listByAwardRootIdPermission(String awardRootId, String portalId,String userId) { Map<String, Object> parameter = new HashMap<String, Object>(); parameter.put("awardRootId", awardRootId); parameter.put("portalId", portalId); parameter.put("userId", userId); List<Award> awardList = this.awardDao.listByAwardRootIdPermission(parameter); return awardList; } /* * (non-Javadoc) * @see * com.lgcns.ikep4.lightpack.award.service.AwardAdminService#listByAwardRootId * (java.lang.String) */ public List<Award> listByAwardRootId(String awardRootId, String portalId) { Map<String, Object> parameter = new HashMap<String, Object>(); parameter.put("awardRootId", awardRootId); parameter.put("portalId", portalId); List<Award> awardList = this.awardDao.listByAwardRootId(parameter); return awardList; } public List<Award> listByAwardRootIdMobile(String awardRootId, String portalId) { Map<String, Object> parameter = new HashMap<String, Object>(); parameter.put("awardRootId", awardRootId); parameter.put("portalId", portalId); List<Award> awardList = this.awardDao.listByAwardRootIdMobile(parameter); return awardList; } public List<Award> listByAwardRootIdPer(Map<String, Object> param) { List<Award> awardList = this.awardDao.listByAwardRootIdPer(param); return awardList; } public List<Award> listByAwardRootIdPerMobile(Map<String, Object> param) { List<Award> awardList = this.awardDao.listByAwardRootIdPerMobile(param); return awardList; } /* * (non-Javadoc) * @see * com.lgcns.ikep4.lightpack.award.service.AwardAdminService#readAward(java * .lang.String) */ public Award readAward(String awardId) { Award award = this.awardDao.get(awardId); // 게시판의 조상목록을 조회한다. award.setParentList(this.awardDao.getParents(awardId)); // 게시판의 손자목록을 조회한다. award.setChildList(this.awardDao.getChildren(awardId)); //게시판 읽기 권한을 세팅 this.setupAwardReadPermission(award); //게시판 쓰기 권한을 세팅 this.setupAwardWritePermission(award); this.setupAwardAdminPermission(award); return award; } public Award readAward2(String awardId) { Award award = this.awardDao.get(awardId); return award; } /** * 게시판 읽기 권한을 세팅하는 메서드 * * @param award 게시판 모델 클래스 */ private void setupAwardReadPermission(Award award) { //읽기 권한 정보를 가져온다. ACLResourcePermission readPermission = this.aclService.getSystemPermission(Award.AWARD_ACL_CLASS_NAME, award.getAwardId(), "READ"); if(readPermission != null) { readPermission = this.aclService.listDetailPermission(readPermission); List<User> readUserList = readPermission.getAssignUserDetailList(); List<Group> readGroupList = readPermission.getGroupDetailList(); List<Role> readRoleList = readPermission.getRoleDetailList(); List<ACLGroupPermission> readPermissionList = readPermission.getGroupPermissionList(); if(readGroupList != null) { List <AwardGroup> readAwardGroupList = new ArrayList<AwardGroup>(); AwardGroup awardGroup = null; for(Group group : readGroupList) { awardGroup = new AwardGroup(); awardGroup.setGroupId(group.getGroupId()); awardGroup.setGroupName(group.getGroupName()); //System.out.println("@@@@@@@@@@@@@@@@@@@@@:group.getGroupId():"+group.getGroupId()+":group.getGroupName():"+group.getGroupName()); for(ACLGroupPermission aclGroupPermission : readPermissionList) { //System.out.println("@@@@@@@@@@@@@@@@@@@@@:aclGroupPermission.getGroupId():"+aclGroupPermission.getGroupId()); //System.out.println("@@@@@@@@@@@@@@@@@@@@@:aclGroupPermission.getHierarchyPermission():"+aclGroupPermission.getHierarchyPermission()); if(aclGroupPermission.getGroupId().equals(group.getGroupId())) { awardGroup.setHierarchied(aclGroupPermission.getHierarchyPermission()); } } readAwardGroupList.add(awardGroup); } award.setReadGroupList(readAwardGroupList); } award.setReadUserList(readUserList); award.setReadRoleList(readRoleList); award.setReadPermission(readPermission.getOpen()); } } /** * 게시판 쓰기 권한을 세팅하는 메서드 * * @param award 게시판 모델 클래스 */ private void setupAwardWritePermission(Award award) { //쓰기 권한 정보를 가져온다. ACLResourcePermission writePermission = this.aclService.getSystemPermission(Award.AWARD_ACL_CLASS_NAME, award.getAwardId(), "WRITE"); if(writePermission != null) { writePermission = this.aclService.listDetailPermission(writePermission); List<Group> writeGroupList = writePermission.getGroupDetailList(); List<ACLGroupPermission> wirtePermissionList = writePermission.getGroupPermissionList(); if(writeGroupList != null) { List<AwardGroup> writeAwardGroupList = new ArrayList<AwardGroup>(); AwardGroup awardGroup = null; for(Group group : writeGroupList) { awardGroup = new AwardGroup(); awardGroup.setGroupId(group.getGroupId()); awardGroup.setGroupName(group.getGroupName()); for(ACLGroupPermission aclGroupPermission : wirtePermissionList) { if(aclGroupPermission.getGroupId().equals(group.getGroupId())) { awardGroup.setHierarchied(aclGroupPermission.getHierarchyPermission()); continue; } } writeAwardGroupList.add(awardGroup); } award.setWriteGroupList(writeAwardGroupList); } award.setWritePermission(writePermission.getOpen()); List<User> writeUserList = writePermission.getAssignUserDetailList(); award.setWriteUserList(writeUserList); List<Role> writeRoleList = writePermission.getRoleDetailList(); award.setWriteRoleList(writeRoleList); } } private void setupAwardAdminPermission(Award award) { //쓰기 권한 정보를 가져온다. ACLResourcePermission adminPermission = this.aclService.getSystemPermission(Award.AWARD_ACL_CLASS_NAME, award.getAwardId(), "ADMIN"); if(adminPermission != null) { adminPermission = this.aclService.listDetailPermission(adminPermission); List<Group> adminGroupList = adminPermission.getGroupDetailList(); List<ACLGroupPermission> wirtePermissionList = adminPermission.getGroupPermissionList(); if(adminGroupList != null) { List<AwardGroup> adminAwardGroupList = new ArrayList<AwardGroup>(); AwardGroup awardGroup = null; for(Group group : adminGroupList) { awardGroup = new AwardGroup(); awardGroup.setGroupId(group.getGroupId()); awardGroup.setGroupName(group.getGroupName()); for(ACLGroupPermission aclGroupPermission : wirtePermissionList) { if(aclGroupPermission.getGroupId().equals(group.getGroupId())) { awardGroup.setHierarchied(aclGroupPermission.getHierarchyPermission()); continue; } } adminAwardGroupList.add(awardGroup); } award.setAdminGroupList(adminAwardGroupList); } award.setAdminPermission(adminPermission.getOpen()); List<User> adminUserList = adminPermission.getAssignUserDetailList(); award.setAdminUserList(adminUserList); List<Role> adminRoleList = adminPermission.getRoleDetailList(); award.setAdminRoleList(adminRoleList); } } /* * (non-Javadoc) * @see * com.lgcns.ikep4.lightpack.award.service.AwardAdminService#createAward * (com.lgcns.ikep4.lightpack.award.model.Award) */ public String createAward(Award award) { final String generatedId = this.idgenService.getNextId(); award.setAwardId(generatedId); //1Level Award 생성시 Foreign key 제약조건 오류 방지 if("".equals(award.getAwardParentId())) { award.setAwardParentId(null); } String awardId = this.awardDao.create(award); //게시판인경우 권한 정보를 저장한다. if("0".equals(award.getAwardType())) { this.createWritePermission(award); this.createReadPermission(award); } //게시판인경우 권한 정보를 저장한다. if("2".equals(award.getAwardType())) { this.createReadPermission(award); } return awardId; } /** * 쓰기 권한을 수정한다. * * @param award 게시판 모델 객체 */ private void updateWritePermission(Award award) { ACLResourcePermission writePermission = this.aclService.getSystemPermission(Award.AWARD_ACL_CLASS_NAME, award.getAwardId(), "WRITE"); writePermission.setAssignUserIdList(null); writePermission.setGroupPermissionList(null); writePermission.setOpen(award.getWritePermission()); if(award.getWritePermission() == 0) { //쓰기 권한 사용자 정보를 넣는다. if(award.getWriteUserList() != null) { for(User user : award.getWriteUserList()) { writePermission.addAssignUserId(user.getUserId()); } } //쓰기 권한 관리자 정보를 넣는다. if(award.getWriteGroupList() != null) { for(AwardGroup group : award.getWriteGroupList()) { writePermission.addGroupPermission(group.getGroupId(), group.getHierarchied()); } } if(award.getWriteRoleList() != null) { //쓰기 권한 관리자 정보를 넣는다. for(Role role : award.getWriteRoleList()) { writePermission.addRoleId(role.getRoleId()); } } } // portalId 읽어오기 User user = (User) RequestContextHolder.currentRequestAttributes().getAttribute("ikep.user", RequestAttributes.SCOPE_SESSION); this.aclService.updateSystemPermission(writePermission,user.getPortalId()); } private void updateAdminPermission(Award award) { ACLResourcePermission adminPermission = this.aclService.getSystemPermission(Award.AWARD_ACL_CLASS_NAME, award.getAwardId(), "ADMIN"); adminPermission.setAssignUserIdList(null); adminPermission.setGroupPermissionList(null); adminPermission.setOpen(award.getAdminPermission()); if(award.getAdminPermission() == 0) { //쓰기 권한 사용자 정보를 넣는다. if(award.getAdminUserList() != null) { for(User user : award.getAdminUserList()) { adminPermission.addAssignUserId(user.getUserId()); } } //쓰기 권한 관리자 정보를 넣는다. if(award.getAdminGroupList() != null) { for(AwardGroup group : award.getAdminGroupList()) { adminPermission.addGroupPermission(group.getGroupId(), group.getHierarchied()); } } if(award.getAdminRoleList() != null) { //쓰기 권한 관리자 정보를 넣는다. for(Role role : award.getAdminRoleList()) { adminPermission.addRoleId(role.getRoleId()); } } } // portalId 읽어오기 User user = (User) RequestContextHolder.currentRequestAttributes().getAttribute("ikep.user", RequestAttributes.SCOPE_SESSION); this.aclService.updateSystemPermission(adminPermission,user.getPortalId()); } /** * 읽기 권한을 수정한다. * * @param award 게시판 모델 객체 */ private void updateReadPermission(Award award) { ACLResourcePermission readPermission = this.aclService.getSystemPermission(Award.AWARD_ACL_CLASS_NAME, award.getAwardId(), "READ"); readPermission.setAssignUserIdList(null); readPermission.setGroupPermissionList(null); readPermission.setRoleIdList(null); readPermission.setOpen(award.getReadPermission()); if(award.getReadPermission() == 0) { //읽기 권한 사용자 정보를 넣는다. if(award.getReadUserList() != null) { for(User user : award.getReadUserList()) { readPermission.addAssignUserId(user.getUserId()); } } //읽기 권한 관리자 정보를 넣는다. if(award.getReadGroupList() != null) { for(AwardGroup group : award.getReadGroupList()) { readPermission.addGroupPermission(group.getGroupId(), group.getHierarchied()); } } if(award.getReadRoleList() != null) { //읽기 권한 관리자 정보를 넣는다. for(Role role : award.getReadRoleList()) { readPermission.addRoleId(role.getRoleId()); } } } // portalId 읽어오기 User user = (User) RequestContextHolder.currentRequestAttributes().getAttribute("ikep.user", RequestAttributes.SCOPE_SESSION); this.aclService.updateSystemPermission(readPermission, user.getPortalId()); } /** * 쓰기권한을 생성한다. * * @param award 게시판 모델 객체 */ private void createWritePermission(Award award) { ACLResourcePermission writePermission = new ACLResourcePermission(); // 시스템 리소스의 타입을 입력한다. writePermission.setClassName(Award.AWARD_ACL_CLASS_NAME); // 시스템 리소스 이름을 입력한다. writePermission.setResourceName(award.getAwardId()); // 시스템 리소스에 대한 설명을 입력한다. writePermission.setResourceDescription(award.getAwardName()); // 사용자 아이디를 입력한다. writePermission.setUserId(award.getUpdaterId()); // 사용자 이름을 입력한다. writePermission.setUserName(award.getUpdaterName()); // 오퍼레이션 이름을 입력한다. writePermission.setOperationName("WRITE"); writePermission.setOpen(award.getWritePermission()); if(award.getWritePermission() == 0) { // 시스템 리소스의 오픈여부를 입력한다, 1=오픈, 0=비오픈 if(award.getWriteUserList() != null) { //쓰기 권한 사용자 정보를 넣는다. for(User user : award.getWriteUserList()) { writePermission.addAssignUserId(user.getUserId()); } } if(award.getWriteGroupList() != null) { //쓰기 권한 관리자 정보를 넣는다. for(AwardGroup group : award.getWriteGroupList()) { writePermission.addGroupPermission(group.getGroupId(), group.getHierarchied()); } } if(award.getWriteRoleList() != null) { //쓰기 권한 관리자 정보를 넣는다. for(Role role : award.getWriteRoleList()) { writePermission.addRoleId(role.getRoleId()); } } } this.aclService.createSystemPermission(writePermission); } private void createAdminPermission(Award award) { ACLResourcePermission adminPermission = new ACLResourcePermission(); // 시스템 리소스의 타입을 입력한다. adminPermission.setClassName(Award.AWARD_ACL_CLASS_NAME); // 시스템 리소스 이름을 입력한다. adminPermission.setResourceName(award.getAwardId()); // 시스템 리소스에 대한 설명을 입력한다. adminPermission.setResourceDescription(award.getAwardName()); // 사용자 아이디를 입력한다. adminPermission.setUserId(award.getUpdaterId()); // 사용자 이름을 입력한다. adminPermission.setUserName(award.getUpdaterName()); // 오퍼레이션 이름을 입력한다. adminPermission.setOperationName("ADMIN"); adminPermission.setOpen(award.getAdminPermission()); if(award.getAdminPermission() == 0) { // 시스템 리소스의 오픈여부를 입력한다, 1=오픈, 0=비오픈 if(award.getAdminUserList() != null) { //쓰기 권한 사용자 정보를 넣는다. for(User user : award.getAdminUserList()) { adminPermission.addAssignUserId(user.getUserId()); } } if(award.getAdminGroupList() != null) { //쓰기 권한 관리자 정보를 넣는다. for(AwardGroup group : award.getAdminGroupList()) { adminPermission.addGroupPermission(group.getGroupId(), group.getHierarchied()); } } if(award.getAdminRoleList() != null) { //쓰기 권한 관리자 정보를 넣는다. for(Role role : award.getAdminRoleList()) { adminPermission.addRoleId(role.getRoleId()); } } } this.aclService.createSystemPermission(adminPermission); } /** * 읽기 권한을 생성한다. * * @param award 게시판 모델 객체 */ private void createReadPermission(Award award) { ACLResourcePermission readPermission = new ACLResourcePermission(); // 시스템 리소스의 타입을 입력한다. readPermission.setClassName(Award.AWARD_ACL_CLASS_NAME); // 시스템 리소스 이름을 입력한다. readPermission.setResourceName(award.getAwardId()); // 시스템 리소스에 대한 설명을 입력한다. readPermission.setResourceDescription(award.getAwardName()); // 시스템 리소스의 오픈여부를 입력한다, 1=오픈, 0=비오픈 readPermission.setOpen(award.getReadPermission()); // 사용자 아이디를 입력한다. readPermission.setUserId(award.getUpdaterId()); // 사용자 이름을 입력한다. readPermission.setUserName(award.getUpdaterName()); // 오퍼레이션 이름을 입력한다. readPermission.setOperationName("READ"); if(award.getReadPermission() == 0) { if( award.getReadUserList() != null) { //읽기 권한 사용자 정보를 넣는다. for(User user : award.getReadUserList()) { readPermission.addAssignUserId(user.getUserId()); } } if( award.getReadGroupList() != null) { //읽기 권한 관리자 정보를 넣는다. for(AwardGroup group : award.getReadGroupList()) { readPermission.addGroupPermission(group.getGroupId(), group.getHierarchied()); } } if(award.getReadRoleList() != null) { //읽기 권한 관리자 정보를 넣는다. for(Role role : award.getReadRoleList()) { readPermission.addRoleId(role.getRoleId()); } } } this.aclService.createSystemPermission(readPermission); } /* * (non-Javadoc) * @see * com.lgcns.ikep4.lightpack.award.service.AwardAdminService#updateAward * (com.lgcns.ikep4.lightpack.award.model.Award) */ public void updateAward(Award award) { //1Level Award 생성시 Foreign key 제약조건 오류 방지 if("".equals(award.getAwardParentId())) { award.setAwardParentId(null); } this.awardDao.update(award); //게시판인 경우 권한 정보를 저장한다. if("0".equals(award.getAwardType())) { //권한이 생성되어 있는지 확인하고 생성되어 있으면 업데이트 아니면 생성을 한다. if(this.aclService.getSystemPermission(Award.AWARD_ACL_CLASS_NAME, award.getAwardId(), "READ") == null) { this.createReadPermission(award); } else { this.updateReadPermission(award); } if(this.aclService.getSystemPermission(Award.AWARD_ACL_CLASS_NAME, award.getAwardId(), "WRITE") == null) { this.createWritePermission(award); } else { this.updateWritePermission(award); } if(this.aclService.getSystemPermission(Award.AWARD_ACL_CLASS_NAME, award.getAwardId(), "ADMIN") == null) { this.createAdminPermission(award); } else { this.updateAdminPermission(award); } } //카테고리인 경우 읽기 권한 정보를 저장한다. if("2".equals(award.getAwardType())) { //권한이 생성되어 있는지 확인하고 생성되어 있으면 업데이트 아니면 생성을 한다. if(this.aclService.getSystemPermission(Award.AWARD_ACL_CLASS_NAME, award.getAwardId(), "READ") == null) { this.createReadPermission(award); } else { this.updateReadPermission(award); } } } /* * (non-Javadoc) * @see * com.lgcns.ikep4.lightpack.award.service.AwardAdminService#physicalDeleteAward * (java.lang.String) */ public void physicalDeleteAward(String awardId) { /* //게시판 정보를 조회한다. Award award = this.awardDao.get(awardId); //권한을 삭제한다. this.aclService.deleteSystemPermission(Award.AWARD_ACL_CLASS_NAME, award.getAwardId()); // 게시판에 게시글과 관련 정보를 모두 삭제한다. this.awardItemService.adminDeleteAwardItemInAward(awardId); // 게시판을 삭제한다. this.awardDao.physicalDelete(awardId); */ this.updateAwardDeleteField(awardId, Award.AWARD_DELETE_WAIT); List<Award> awardList = this.awardDao.listChildrenAward(awardId); for(Award award : awardList) { this.updateAwardDeleteField(award.getAwardId(), Award.AWARD_DELETE_WAIT); } } /* * (non-Javadoc) * @see * com.lgcns.ikep4.lightpack.award.service.AwardAdminService#listParentAward * (java.lang.String) */ public List<Award> listParentAward(String awardId) { return this.awardDao.getParents(awardId); } /* * (non-Javadoc) * @see * com.lgcns.ikep4.lightpack.award.service.AwardAdminService#updateAwardMove * (com.lgcns.ikep4.lightpack.award.model.Award) */ public void updateAwardMove(Award after) { Award before = this.awardDao.get(after.getAwardId()); // 이동전의 위치에서는 자기 기준으로 정렬숫자가 높은 놈들은 -1 해준다. this.awardDao.updateSortOderDecrease(before); // 이동후의 위치에서는 자기 기준으로 정렬숙자가 높은 놈들은 +1 해준다. this.awardDao.updateSortOderIncrease(after); //1Level Award 생성시 Foreign key 제약조건 오류 방지 if("".equals(after.getAwardParentId())) { after.setAwardParentId(null); } this.awardDao.updateMove(after); } /* * (non-Javadoc) * @see com.lgcns.ikep4.lightpack.award.service.AwardAdminService# * readHasPermissionAward(java.lang.String, java.lang.String) */ public Award readHasPermissionAward(String userId, String awardRootId) { return this.awardDao.readHasPermissionAward(userId, awardRootId); } /* * (non-Javadoc) * @see * com.lgcns.ikep4.lightpack.award.service.AwardAdminService#listChildrenAward * (java.lang.String) */ public List<Award> listChildrenAward(String awardId) { return this.awardDao.listChildrenAward(awardId); } /* * (non-Javadoc) * @see * com.lgcns.ikep4.lightpack.award.service.AwardAdminService#listChildrenAward * (java.lang.String) */ public List<Award> listChildrenAward(String awardId, String portalId) { Map<String, Object> parameter = new HashMap<String, Object>(); parameter.put("awardId", awardId); parameter.put("portalId", portalId); return this.awardDao.listChildrenAward(parameter); } /* (non-Javadoc) * @see com.lgcns.ikep4.lightpack.award.service.AwardAdminService#updateAwardDeleteField(java.lang.Integer) */ public void updateAwardDeleteField(String awardId, Integer status) { Map<String, Object> parameter = new HashMap<String, Object>(); parameter.put("awardId", awardId); parameter.put("status", status); this.awardDao.updateAwardDeleteField(parameter); } public void updateAwardMenuType(boolean isTree) { awardDao.updateAwardMenuType(isTree ? "TREE" : "MENU"); } public boolean isAwardMenuTree() { boolean isTree = false; String type = awardDao.selectAwardMenuType(); if(type.equalsIgnoreCase("tree")) isTree = true; return isTree; } public List<Award> getAwardMenuList() { // TODO Auto-generated method stub return this.awardDao.getAwardMenuList(); } }
true
ec247f202abb0d00330c8f91f4344e38aa3f0cf1
Java
missaouib/keystore
/keystore/src/test/java/ru/urvanov/keystore/controller/ControllerTestBase.java
UTF-8
4,999
2.015625
2
[]
no_license
package ru.urvanov.keystore.controller; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.context.HttpRequestResponseHolder; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.request.RequestPostProcessor; import ru.urvanov.keystore.domain.UserAccess; import ru.urvanov.keystore.domain.UserAccessCode; import ru.urvanov.keystore.domain.UserDetailsImpl; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml", "file:src/main/webapp/WEB-INF/spring/root-context.xml" }) @ActiveProfiles("test") public abstract class ControllerTestBase { @Autowired protected UserDetailsService userDetailsService; protected UsernamePasswordAuthenticationToken prepareSecurity( String userName) { UserDetailsImpl userDetails = (UserDetailsImpl) userDetailsService .loadUserByUsername(userName); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( userDetails, userDetails.getPassword(), userDetails.getAuthorities()); for (UserAccessCode userAccessCode : UserAccessCode.values()) { UserAccess userAccess = userDetails.getUser().getUserAccesses() .get(userAccessCode); if (userAccess == null) { userAccess = new UserAccess(); userAccess.setCode(userAccessCode); userAccess.setUser(userDetails.getUser()); } userAccess.setAccess(true); userDetails.getUser().getUserAccesses() .put(userAccessCode, userAccess); } return token; } protected class UserDetailsRequestPostProcessor extends SecurityContextRequestPostProcessorSupport implements RequestPostProcessor { private final String username; protected UserDetailsRequestPostProcessor(String username) { this.username = username; } public MockHttpServletRequest postProcessRequest( MockHttpServletRequest request) { UsernamePasswordAuthenticationToken authentication = authentication(request .getServletContext()); save(authentication, request); return request; } private UsernamePasswordAuthenticationToken authentication( ServletContext servletContext) { return prepareSecurity(username); } } /** * Support class for {@link RequestPostProcessor}'s that establish a Spring * Security context */ private static abstract class SecurityContextRequestPostProcessorSupport { private SecurityContextRepository repository = new HttpSessionSecurityContextRepository(); final void save(Authentication authentication, HttpServletRequest request) { SecurityContext securityContext = SecurityContextHolder .createEmptyContext(); securityContext.setAuthentication(authentication); save(securityContext, request); } final void save(SecurityContext securityContext, HttpServletRequest request) { HttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder( request, response); this.repository.loadContext(requestResponseHolder); request = requestResponseHolder.getRequest(); response = requestResponseHolder.getResponse(); this.repository.saveContext(securityContext, request, response); } } }
true
540569eb2f2573d30fadc91110dd4d579da4df91
Java
farizaghayev/AndroidMaryTTS
/marylib/src/main/java/marytts/util/data/AlignLabelsUtils.java
UTF-8
5,012
2.265625
2
[]
no_license
/** * Copyright 2011 DFKI GmbH. * All Rights Reserved. Use is subject to license terms. * <p/> * This file is part of MARY TTS. * <p/> * MARY TTS is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3 of the License. * <p/> * 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. * <p/> * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package marytts.util.data; import marytts.signalproc.analysis.Label; /** * @author marc */ public class AlignLabelsUtils { public static int[][] alignLabels(Label[] labs1, Label[] labs2, double PDeletion, double PInsertion, double PSubstitution) { double PCorrect = 1.0 - (PDeletion + PInsertion + PSubstitution); int n = labs1.length; int m = labs2.length; double D; int[][] labelMap = null; if (n == 0 || m == 0) { D = m; return labelMap; } int i, j; double[][] d = new double[n + 1][m + 1]; for (i = 0; i < d.length; i++) { for (j = 0; j < d[i].length; j++) d[i][j] = 0.0; } int[][] p = new int[n + 1][m + 1]; for (i = 0; i < p.length; i++) { for (j = 0; j < p[i].length; j++) p[i][j] = 0; } double z = 1; d[0][0] = z; for (i = 1; i <= n; i++) d[i][0] = d[i - 1][0] * PDeletion; for (j = 1; j <= m; j++) d[0][j] = d[0][j - 1] * PInsertion; String strEvents = "DISC"; double c; double tmp; for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { if (labs1[i - 1].phn.compareTo(labs2[j - 1].phn) == 0) c = PCorrect; else c = PSubstitution; int ind = 1; d[i][j] = d[i - 1][j] * PDeletion; tmp = d[i][j - 1] * PInsertion; if (tmp > d[i][j]) { d[i][j] = tmp; ind = 2; } tmp = d[i - 1][j - 1] * c; if (tmp > d[i][j]) { d[i][j] = tmp; ind = 3; } if (ind == 3 && labs1[i - 1].phn.compareTo(labs2[j - 1].phn) == 0) ind = 4; //Events 1:Deletion, 2:Insertion, 3:Substitution, 4:Correct p[i][j] = ind; } } //Backtracking D = d[n][m]; int k = 1; int[] E = new int[m * n]; E[k - 1] = p[n][m]; i = n + 1; j = m + 1; int t = m; while (true) { if (E[k - 1] == 3 || E[k - 1] == 4) { i = i - 1; j = j - 1; } else if (E[k - 1] == 2) j = j - 1; else if (E[k - 1] == 1) i = i - 1; if (p[i - 1][j - 1] == 0) { while (j > 1) { k = k + 1; j = j - 1; E[k - 1] = 2; } break; } else { k = k + 1; E[k - 1] = p[i - 1][j - 1]; } t = t - 1; } //Reverse the order int[] Events = new int[k]; for (t = k; t >= 1; t--) Events[t - 1] = E[k - t]; int[][] tmpLabelMap = new int[n * m][2]; int ind = 0; int ind1 = 0; int ind2 = 0; for (t = 1; t <= k; t++) { if (Events[t - 1] == 3 || Events[t - 1] == 4) //Substitution or correct { tmpLabelMap[ind][0] = ind1; tmpLabelMap[ind][1] = ind2; ind1++; ind2++; ind++; } else if (Events[t - 1] == 1) //An item in seq1 is deleted in seq2 { ind1++; } else if (Events[t - 1] == 2) //An item is inserted in seq2 { ind2++; } } if (ind > 0) { labelMap = new int[ind][2]; for (i = 0; i < labelMap.length; i++) { labelMap[i][0] = tmpLabelMap[i][0]; labelMap[i][1] = tmpLabelMap[i][1]; } } return labelMap; } //This version assumes that there can only be insertions and deletions but no substitutions // (i.e. text based alignment with possible differences in pauses only) public static int[][] alignLabels(Label[] seq1, Label[] seq2) { return alignLabels(seq1, seq2, 0.05, 0.05, 0.05); } }
true
e55cb66b559e0f89af1653592ce699e85eb3c88b
Java
devansh-299/practiceschool-project
/patient-api/src/main/java/com/devansh/patientapi/service/PatientServiceImpl.java
UTF-8
1,043
2.40625
2
[]
no_license
package com.devansh.patientapi.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.devansh.patientapi.dao.PatientDao; import com.devansh.patientapi.model.Patient; @Service public class PatientServiceImpl implements PatientService { @Autowired private PatientDao patientDao; public PatientServiceImpl () { } @Override public List<Patient> getPatients() { return patientDao.findAll(); } @Override public Patient getCourse(long patientId) { return patientDao.getOne(patientId); } @Override public String addPatient(Patient patient) { patientDao.save(patient); return "Created patient with id: " + patient.getId(); } @Override public String updatePatient(Patient patient) { patientDao.save(patient); return "Updated the patient with id: " + patient.getId(); } @Override public void deletePatient(long patientId) { Patient patient = patientDao.getOne(patientId); patientDao.delete(patient); } }
true
9b8d0558eae07d296fcbbab9ef59e6c79e8b9e38
Java
ningrain/ssm_crud
/src/main/java/com/gta/proxy/Mover.java
UTF-8
70
1.945313
2
[]
no_license
package com.gta.proxy; public interface Mover { void move(); }
true
d1deb3aefd9c16706c1ad1a375f19c0314e0ff80
Java
kunalbarve/MyCodes-Preparations
/src/InterviewExams/VeizonHarshit.java
UTF-8
783
3.234375
3
[]
no_license
package InterviewExams; import java.util.TreeMap; public class VeizonHarshit { static TreeMap<Integer, Integer> map = new TreeMap<>(); static int maxCount = 0; static void customSort(int[] arr) { for(int i = 0; i< arr.length; i++){ int number = arr[i]; if(map.containsKey(number)){ int count = map.get(number); count++; map.put(number, count); if(count > maxCount) maxCount = count; }else{ map.put(number, 1); } } for(int j = 1; j <= maxCount; j++){ for(int number : map.keySet()){ int value = map.get(number); if(j == value){ for(int k = 0; k<value; k++){ System.out.println(number); } } } } } public static void main(String[] args) { int[] arr = {3, 1, 2, 2, 4}; customSort(arr); } }
true
afa56987754cd53f42620ba67554b12c810d0412
Java
penggy/crystal
/src/main/java/com/github/crystal/dao/PageBean.java
UTF-8
1,378
2.46875
2
[]
no_license
package com.github.crystal.dao; import java.util.ArrayList; import java.util.List; import com.wordnik.swagger.annotations.ApiModel; import com.wordnik.swagger.annotations.ApiModelProperty; /** * 分页实体 * * @author <a href=mailto:wu.peng@starit.com.cn>wu.peng</a> 2012-6-12 * * @param <T> */ @ApiModel("分页数据") public class PageBean<T> { @ApiModelProperty("当前页从总量第N条开始(从0算起)") private int start; @ApiModelProperty("每页大小") private int limit; @ApiModelProperty("实际总量") private long count; @ApiModelProperty("分页数据") private List<T> data = new ArrayList<T>(); public PageBean() { } public PageBean(int start, int limit) { this.start = start; this.limit = limit; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public long getCount() { return count; } public void setCount(long count) { this.count = count; } public List<T> getData() { return data; } public void setData(List<T> data) { this.data = data; } public String toString() { return "PageBean [start=" + start + ", limit=" + limit + ", count=" + count + ", data=" + data + "]"; } }
true
a67dc9fa4a327c6b8255213e26291ec7186d0023
Java
9597yashKulkarni/ExpenditureDiary-App
/Calender.java
UTF-8
1,995
2.359375
2
[ "Apache-2.0" ]
permissive
package com.example.yash.expediturediary; import android.content.Intent; import android.icu.util.Calendar; import android.os.Build; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.DatePicker; public class Calender extends AppCompatActivity { @RequiresApi(api = Build.VERSION_CODES.N) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calender); DatePicker dp= (DatePicker) findViewById(R.id.datePicker); Button insert= (Button) findViewById(R.id.button); Button display= (Button) findViewById(R.id.button2); final Calendar c =Calendar.getInstance(); final int year=c.get(Calendar.YEAR); final int month=c.get(Calendar.MONTH); final int day=c.get(Calendar.DAY_OF_MONTH); System.out.print(year+" "+month+" "+day); /* final int day=dp.getDayOfMonth(); final int month=dp.getMonth()+1; final int year=dp.getYear();*/ insert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i=new Intent(Calender.this,Insert.class); i.putExtra("Day",day); i.putExtra("Month",month); i.putExtra("Year",year); startActivity(i); } }); display.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i1=new Intent(Calender.this,Display.class); i1.putExtra("Day",day); i1.putExtra("Month",month); i1.putExtra("Year",year); startActivity(i1); } }); } }
true
59b331c0df202324dcbe33739c919ef857bfb3e6
Java
Ramesh138/batchoneselenium
/src/com/selenium/testngprograms/TC1.java
UTF-8
925
2.734375
3
[]
no_license
package com.selenium.testngprograms; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class TC1 { @BeforeClass public void beforeclassm1() { System.out.println(" BC.t1"); } @AfterClass public void afterclassm1() { System.out.println(" AC.t1"); } @BeforeMethod public void beforem1() { System.out.println(" B1.t1"); } @AfterMethod public void afterm1() { System.out.println("A1.t1"); } @Test @Parameters({"fullname","lname","fname"}) public void t1(String fullname,String lname,String fname) { System.out.println(" t1"); System.out.println("my full name :"+fullname); System.out.println("my last name :"+lname); System.out.println("my first name :"+fname); } }
true
b4f771a8eb2a235594f020272215a143ae352b29
Java
bbossgroups/bboss-elastic-tran
/bboss-datatran-fileftp/src/main/java/org/frameworkset/tran/input/file/FileReaderTask.java
UTF-8
52,204
1.671875
2
[ "Apache-2.0" ]
permissive
package org.frameworkset.tran.input.file; import com.frameworkset.util.BaseSimpleStringUtil; import com.frameworkset.util.FileUtil; import com.frameworkset.util.SimpleStringUtil; import org.frameworkset.tran.BaseDataTran; import org.frameworkset.tran.DataImportException; import org.frameworkset.tran.DataTranPlugin; import org.frameworkset.tran.Record; import org.frameworkset.tran.file.monitor.FileInodeHandler; import org.frameworkset.tran.file.monitor.FileManager; import org.frameworkset.tran.ftp.FtpConfig; import org.frameworkset.tran.plugin.InputPlugin; import org.frameworkset.tran.plugin.file.input.FileInputConfig; import org.frameworkset.tran.record.CommonData; import org.frameworkset.tran.record.FieldMappingUtil; import org.frameworkset.tran.schedule.Status; import org.frameworkset.tran.schedule.TaskContext; import org.frameworkset.tran.task.TranStopReadEOFCallback; import org.frameworkset.tran.task.TranStopReadEOFCallbackContext; import org.frameworkset.tran.util.TranUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.RandomAccessFile; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.Thread.sleep; /** * @author xutengfei,yin-bp@163.com * @description * @create 2021/3/15 */ public class FileReaderTask extends FieldManager{ private static Logger logger = LoggerFactory.getLogger(FileReaderTask.class); protected FileInfo fileInfo; protected FileInputConfig fileImportConfig; /** * 文件监听事件服务 */ protected FileListenerService fileListenerService; /** * 文件开始行标识正则 */ private Pattern pattern; private boolean rootLevel; protected boolean enableMeta; protected BaseDataTran fileDataTran; private RandomAccessFile raf ; //状态 0启用 1失效 public static final int STATUS_OK = 0; public static final int STATUS_NO = 1; private int status = STATUS_OK; protected Status currentStatus; protected volatile boolean taskEnded; protected volatile boolean taskEndOrStop; protected volatile boolean interrupted; /** * jsondata:标识文本记录是json格式的数据,true 将值解析为json对象,false - 不解析,这样值将作为一个完整的message字段存放到上报数据中 */ private boolean jsondata ; protected Thread worker ; protected long oldLastModifyTime = -1L; protected long lastExecuteTime = -1L; protected long checkFileModifyInterval = 1000L; protected long closeOlderTime ; protected CloseOldedFileAssert closeOldedFileAssert; protected IgnoreFileAssert ignoreFileAssert; protected long ignoreOlderTime ; protected TaskContext taskContext; protected FileConfig fileConfig; protected boolean fileOlded; protected boolean fileCompleteErrored; protected boolean fileDeleted; /** * 文件采集偏移量 */ protected long pointer; public FileReaderTask(TaskContext taskContext, File file, String fileId, FileConfig fileConfig, FileListenerService fileListenerService, BaseDataTran fileDataTran, Status currentStatus , FileInputConfig fileImportConfig ) { this.fileImportConfig = fileImportConfig; this.sleepAwaitTimeAfterFetch = fileImportConfig.getSleepAwaitTimeAfterFetch(); this.sleepAwaitTimeAfterCollect = fileImportConfig.getSleepAwaitTimeAfterCollect(); this.fileListenerService = fileListenerService; String charSet = fileConfig.getCharsetEncode() ; if(charSet == null || charSet.equals("")){ charSet = this.fileListenerService.getFileInputConfig().getCharsetEncode(); } this.pointer = 0; this.fileConfig = fileConfig; this.taskContext = taskContext; if(taskContext instanceof FileTaskContext) { this.fileInfo = ((FileTaskContext)taskContext).getFileInfo(); } if(fileConfig.getFileHeadLineRexPattern() != null){ pattern = fileConfig.getFileHeadLineRexPattern() ; } closeOlderTime = fileConfig.getCloseOlderTime() == null?0:fileConfig.getCloseOlderTime(); ignoreOlderTime = fileConfig.getIgnoreOlderTime() == null?0:fileConfig.getIgnoreOlderTime(); this.closeOldedFileAssert = fileConfig.getCloseOldedFileAssert(); this.ignoreFileAssert = fileConfig.getIgnoreFileAssert(); rootLevel = this.fileListenerService.getFileInputConfig().isRootLevel(); jsondata = this.fileListenerService.getFileInputConfig().isJsondata(); enableMeta = this.fileListenerService.getFileInputConfig().isEnableMeta(); checkFileModifyInterval = this.fileListenerService.getFileInputConfig().getCheckFileModifyInterval(); this.fileDataTran = fileDataTran; this.currentStatus = currentStatus; } public FileReaderTask(String fileId, Status currentStatus, FileInputConfig fileImportConfig ) { this.fileImportConfig = fileImportConfig; this.currentStatus = currentStatus; this.fileInfo = new FileInfo( fileId); this.sleepAwaitTimeAfterFetch = fileImportConfig.getSleepAwaitTimeAfterFetch(); this.sleepAwaitTimeAfterCollect = fileImportConfig.getSleepAwaitTimeAfterCollect(); } public FileInfo getFileInfo() { return fileInfo; } public TaskContext getTaskContext() { return taskContext; } /** * 检测文件是否被重命名,如果重命名则标识文件还存在 * 1 文件被删除 * 2 文件被重命名,能够识别本目录下面重命名的文件 * -1 未知状态 判断过程中出错了,返回未知状态 * @param logFileId * @return */ public int fileExist(String logFileId){ FileConfig fileConfig = fileInfo.getFileConfig(); if(!fileInfo.getFileConfig().isEnableInode()){ return 1; } File logDir = fileConfig.getLogDir(); FilenameFilter filter = fileConfig.getFilter(); try { if (logDir.isDirectory() && logDir.exists()) { File[] files = logDir.listFiles(filter); File file = null; for (int i = 0; files != null && i < files.length; i++) { file = files[i]; String fileId = FileInodeHandler.inode(file,fileConfig.isEnableInode()); if(fileId.equals(logFileId) ){ //文件存在,被重命名了 return 2; } } } //文件被删除了 return 1; } catch(Exception e){ //判断过程中出错了,返回未知状态 return -1; } } /** * 判断文件是否被重命名 * @param logFile * @return */ public boolean fileRenamed(File logFile){ FileConfig fileConfig = fileInfo.getFileConfig(); if(!fileConfig.isEnableInode()){ return false; } String logFileId = FileInodeHandler.inode(logFile,fileConfig.isEnableInode()); return !fileInfo.getFileId().equals(logFileId); } public FileReaderTask(TaskContext taskContext, File file, String fileId, FileConfig fileConfig, long pointer, FileListenerService fileListenerService, BaseDataTran fileDataTran, Status currentStatus , FileInputConfig fileImportConfig ) { this( taskContext,file,fileId, fileConfig,fileListenerService,fileDataTran,currentStatus, fileImportConfig ); this.pointer = pointer; } protected void registEndJob(){ fileDataTran.setTranStopReadEOFCallback(new TranStopReadEOFCallback() { @Override public void call(TranStopReadEOFCallbackContext tranStopReadEOFCallbackContext) { try { // if (taskEndOrStop) { File file = fileInfo.getFile(); boolean removed = false; if(tranStopReadEOFCallbackContext.isReachEOFClose()) { if(tranStopReadEOFCallbackContext.getException() == null) { if (logger.isInfoEnabled()) logger.info("{} reached eof and will be closed.", FileReaderTask.this.toString()); fileListenerService.moveTaskToComplete(FileReaderTask.this); removed = true; try { if (fileImportConfig.isBackupSuccessFiles())//备份采集完的数据文件,默认保留一周,过期清理 backupFile(currentStatus.getRelativeParentDir(), fileInfo.getFile()); else if (fileConfig.isDeleteEOFFile())//删除文件 { if (logger.isInfoEnabled()) logger.info("delete {} on reached eof file.", file.getCanonicalPath()); file.delete(); } } catch (Exception e) { logger.warn("", e); } } else { if (logger.isInfoEnabled()) logger.info("Move failed collect file to Failed Tasks {}. ", FileReaderTask.this.toString()); fileListenerService.removeFailedTask(FileReaderTask.this); removed = true; } } // else { if(fileDeleted){ if(logger.isInfoEnabled()) logger.info("文件[{}]被删除,终止作业,只清理作业任务,停止转换通道,清理和销毁通道任务上下文,当文件回来或者文件恢复后重新分配新的采集通道采集数据",fileInfo.getFilePath()); fileListenerService.doDelete(fileInfo.getFileId()); } else if(tranStopReadEOFCallbackContext.getException() != null){ if(!removed) { if (logger.isInfoEnabled()) logger.info("Move failed collect file to Failed Tasks {}. tranStopReadEOFCallbackContext.getException() is not null.", FileReaderTask.this.toString()); fileListenerService.removeFailedTask(FileReaderTask.this); removed = true; } } else if(fileOlded){ if(logger.isInfoEnabled()) logger.info("文件[{}]超过静默时间或者空闲时间内容未变化,完成采集作业",fileInfo.getFilePath()); fileListenerService.addOldedFileTask(currentStatus.getFileId(),new FileReaderTask(currentStatus.getFileId() ,currentStatus,fileImportConfig)); // fileDataTran.getDataTranPlugin().handleOldedTask(currentStatus); } else if(fileCompleteErrored){ if(!removed) { if (logger.isInfoEnabled()) logger.info("Move failed collect file to Failed Tasks {}. ", FileReaderTask.this.toString()); fileListenerService.removeFailedTask(FileReaderTask.this); removed = true; } } else if(interrupted){ if(logger.isInfoEnabled()) logger.info("文件[{}]采集被中断,终止作业,只清理作业任务,停止转换通道,清理和销毁通道任务上下文,当文件回来或者文件恢复后重新分配新的采集通道采集数据",fileInfo.getFilePath()); fileListenerService.doDelete(fileInfo.getFileId());//是否需要专门的中断文件管理队列,待定 } // } // } } finally { fileDataTran.getDataTranPlugin().afterCall(getTaskContext()); destroyTaskContext(); } } }); } public void start(){ String threadName = null; if(fileConfig.isEnableInode()) { threadName = "FileReaderTask-Thread|" + fileInfo.getFilePath() + "|" + fileInfo.getFileId(); } else{ threadName = "FileReaderTask-Thread|"+fileInfo.getFilePath() ; } registEndJob(); // worker.setDaemon(true); worker = new Thread(new Work(),threadName ); if(logger.isInfoEnabled()) logger.info(threadName+" started.Current Status is "+currentStatus.toString()); worker.start(); } public void interruptWork(){ if(worker != null){ worker.interrupt(); try { worker.join(); } catch (InterruptedException e) { // e.printStackTrace(); } } } public String getFilePath() { return fileInfo.getFilePath(); } public boolean isEnableInode(){ return fileInfo.getFileConfig().isEnableInode(); } public class Work implements Runnable{ @Override public void run() { logger.info("文件内容{}采集任务开始.", fileInfo.getFilePath()); boolean delete = false; boolean olded = false; boolean errorComplete = false; File file = fileInfo.getFile(); String fileId = fileInfo.getFileId(); long pauseScheduleTimeStamp = 0L; DataTranPlugin dataTranPlugin = fileListenerService.getBaseDataTranPlugin(); InputPlugin inputPlugin = dataTranPlugin.getInputPlugin(); boolean _taskEndOrStop = false; do { try { _taskEndOrStop = taskEnded || dataTranPlugin.checkTranToStop() || inputPlugin.isStopCollectData(); if (_taskEndOrStop) { logger.info("退出文件内容采集循环:taskEnded={},dataTranPlugin.checkTranToStop = {},inputPlugin.isStopCollectData={},file={}", taskEnded,dataTranPlugin.checkTranToStop(),inputPlugin.isStopCollectData(),fileInfo.getFilePath()); break; } if (file.exists()) { long lastModifyTime = FileManager.getFileLastTimestamp(file); if (oldLastModifyTime == -1L) { oldLastModifyTime = lastModifyTime; long s = System.currentTimeMillis(); execute(); long end = System.currentTimeMillis(); lastExecuteTime = end - s; continue; } else if (oldLastModifyTime == lastModifyTime) { long idleTime = System.currentTimeMillis() - oldLastModifyTime; if (pauseScheduleTimeStamp > 0L) {//计算暂停时间,并将暂停时间从空闲时间中剔除 long pauseScheduleTime = System.currentTimeMillis() - pauseScheduleTimeStamp; idleTime = idleTime - pauseScheduleTime; } if (closeOlderTime > 0L && idleTime >= closeOlderTime) {//已经超过指定的最大空闲静默时间,停止文件监控作业 if (closeOldedFileAssert == null) { olded = true; } else { olded = closeOldedFileAssert.canClose(fileInfo); if (!olded) { if (logger.isDebugEnabled()) { logger.debug("文件[新:{}|{},老:{}],idleTime:{},内容超过{}毫秒未变化,已经超过指定的最大空闲静默时间closeOlderTime,停止本文件采集作业,olded:{}", fileInfo.getFilePath(), fileInfo.getFileId(), fileInfo.getOriginFilePath(), idleTime, closeOlderTime, olded); } } } if (olded) { if (logger.isInfoEnabled()) logger.info("文件[{}|{}]idleTime:{},内容超过{}毫秒未变化,已经超过指定的最大空闲静默时间closeOlderTime,停止本文件采集作业.", fileInfo.getFilePath(), fileInfo.getFileId(), idleTime, closeOlderTime); break; } } if (ignoreOlderTime > 0L && idleTime >= ignoreOlderTime) {//已经超过指定的最大空闲静默时间,停止文件监控作业 // logger.info("file[{}|{}] idleTime:{},ignoreOlderTime:{}",fileInfo.getFilePath(),fileInfo.getFileId(),idleTime,ignoreOlderTime); if (ignoreFileAssert == null) { olded = true; } else { olded = ignoreFileAssert.canIgnore(fileInfo); } if (olded) { if (logger.isInfoEnabled()) logger.info("文件[{}|{}]idleTime:{},内容超过{}毫秒未变化,已经超过指定的最大空闲静默时间ignoreOlderTime,停止本文件采集作业.", fileInfo.getFilePath(), fileInfo.getFileId(), idleTime, ignoreOlderTime); break; } } if (closeOldedFileAssert != null) { olded = closeOldedFileAssert.canClose(fileInfo); if (olded) { logger.info("文件[新:{}|{},老:{}]内容已经采集完毕,停止本文件采集作业.", fileInfo.getFilePath(), fileInfo.getFileId(), fileInfo.getOriginFilePath()); break; } } if (ignoreFileAssert != null) { olded = ignoreFileAssert.canIgnore(fileInfo); if (olded) { logger.info("文件[新:{}|{},老:{}]内容已经采集完毕,停止本文件采集作业.", fileInfo.getFilePath(), fileInfo.getFileId(), fileInfo.getOriginFilePath()); break; } } try { sleep(checkFileModifyInterval); } catch (InterruptedException e) { if(logger.isDebugEnabled()) logger.debug("文件内容采集线程checkFileModifyInterval休眠期中断异常:"+fileInfo.getFilePath(),e); break; } continue; } else { boolean pauseSchedule = fileListenerService.isSchedulePaussed(false);//这里需要关闭采集自动暂停机制,不能影响其他并行采集的文件调度 if (pauseSchedule) { pauseScheduleTimeStamp = System.currentTimeMillis(); if (logger.isInfoEnabled()) logger.info("Ignore Paused FileReader[{}] Task,waiting for next resume schedule sign to continue.", fileInfo.getFilePath()); try { sleep(checkFileModifyInterval); } catch (InterruptedException e) { if(logger.isDebugEnabled()) logger.debug("文件内容采集线程checkFileModifyInterval休眠期中断异常:"+fileInfo.getFilePath(),e); break; } continue; } else { pauseScheduleTimeStamp = 0L; } if (fileRenamed(file)) //文件重命名,等待文件被清理重新更新新的File对象 { File fileIdFile = FileInodeHandler.getFileByInode(fileConfig, fileId);//查找重命名后的文件 if (fileIdFile != null) {//文件发生了重命名 String filePath = FileInodeHandler.change(fileIdFile.getAbsolutePath()); if (logger.isInfoEnabled()) logger.info("Rename file {} to {}", fileInfo.getOriginFilePath(), filePath); changeFile(filePath, fileIdFile); file = fileIdFile; if (!fileInfo.isCloseEOF() && fileConfig.isCloseRenameEOF()) fileInfo.setCloseEOF(true);//设置关闭标识,重命名的文件被采集完后关闭 } else { delete = true; break; } } oldLastModifyTime = lastModifyTime; long s = System.currentTimeMillis(); execute(); long end = System.currentTimeMillis(); lastExecuteTime = end - s; if (sleepAwaitTimeAfterFetch <= 0L && sleepAwaitTimeAfterCollect > 0L) { try { sleep(sleepAwaitTimeAfterCollect);//采集完毕后休息一会儿再继续 } catch (InterruptedException e) { if(logger.isDebugEnabled()) logger.debug("文件内容采集线程sleepAwaitTimeAfterCollect休眠期中断异常:"+fileInfo.getFilePath(),e); break; } } // try { // sleep(checkFileModifyInterval);//采集完毕后休息一会儿再继续 // } catch (InterruptedException e) { // break; // } continue; } } else { //可能的删除文件,待处理 int lable = fileExist(fileId);//根据文件号识别文件是否被删除 if (lable == 1 || lable == -1)//文件被删除或未知 { delete = true; break; } try { sleep(checkFileModifyInterval); } catch (InterruptedException e) { if(logger.isDebugEnabled()) logger.debug("文件内容采集线程checkFileModifyInterval休眠期中断异常:"+fileInfo.getFilePath(),e); break; } continue; } } catch (Exception e){ logger.error("文件内容采集异常:"+fileInfo.getFilePath(),e); fileDataTran.getDataTranPlugin().throwException(getTaskContext(),e); if(!fileDataTran.getDataTranPlugin().isContinueOnError()){ errorComplete = true; break; } } }while(true); if(delete){ //文件被删除,只清理作业任务,停止转换通道,清理和销毁通道任务上下文,当文件回来或者文件恢复后重新分配新的采集通道采集数据 if(logger.isInfoEnabled()) logger.info("文件[{}]被删除,停止文件内容采集,只清理作业任务,停止转换通道,清理和销毁通道任务上下文,当文件回来或者文件恢复后重新分配新的采集通道采集数据",fileInfo.getFilePath()); // fileListenerService.doDelete(fileId); //need test /** fileListenerService.addCompletedFileTask(currentStatus.getFileId(),new FileReaderTask(currentStatus.getFileId() ,currentStatus)); fileDataTran.getDataTranPlugin().handleOldedTask(currentStatus); */ fileDeleted = true; taskEnded(); // fileDataTran.getDataTranPlugin().afterCall(getTaskContext()); // destroyTaskContext(); } else if(olded){ if(logger.isInfoEnabled()) logger.info("文件[{}]超过静默时间或者空闲时间内容未变化,完成文件内容采集,等待内容处理完毕后终止文件采集通道。",fileInfo.getFilePath()); fileOlded = true; try { sendReadEOFcloseEvent(pointer); } catch (IOException e) { logger.warn("sendReadEOFcloseEvent failed:",e); } catch (InterruptedException e) { logger.warn("sendReadEOFcloseEvent failed:",e); } taskEnded(); // fileDataTran.getDataTranPlugin().afterCall(getTaskContext()); // destroyTaskContext(); } else if(errorComplete){ //dataTraan execute afterCall and destroyTaskContext if(logger.isInfoEnabled()) logger.info("文件[{}]采集异常,终止文件内容采集,等待内容处理完毕后终止文件采集通道",fileInfo.getFilePath()); fileCompleteErrored = true; taskEnded(); // fileDataTran.getDataTranPlugin().afterCall(getTaskContext()); // destroyTaskContext(); } else{ //dataTraan execute afterCall and destroyTaskContext if(_taskEndOrStop) { taskEndOrStop = _taskEndOrStop; if(logger.isInfoEnabled()) { if(taskEnded) { logger.info("数据内容采集完成:{},等待内容处理完毕后终止文件采集通道", fileInfo.getFilePath()); } else{ logger.info("停止数据内容采集:{},等待内容处理完毕后终止文件采集通道", fileInfo.getFilePath()); } } } else{ interrupted = true; if(logger.isInfoEnabled()) { logger.info("文件[{}]任务中断,导致终止文件内容采集,等待内容处理完毕后终止文件采集通道", fileInfo.getFilePath()); } } taskEnded(); // fileDataTran.getDataTranPlugin().afterCall(getTaskContext()); // destroyTaskContext(); } } } public boolean isInterrupted() { return interrupted; } public boolean isTaskEndOrStop() { return taskEndOrStop; } class Line{ private String line; private boolean eof; private boolean eol; Line(String line, boolean eof,boolean eol) { this.line = line; this.eof = eof; this.eol = eol; } public String getLine() { return line; } public boolean isEof() { return eof; } public boolean isRollbackPreLine(){ // return eof && !eol && !fileInfo.getFileConfig().isCloseEOF(); return eof && !eol && !fileInfo.isCloseEOF(); } } public Status getCurrentStatus() { return currentStatus; } /** * Reads the next line of text from this file. This method successively * reads bytes from the file, starting at the current file pointer, * until it reaches a line terminator or the end * of the file. Each byte is converted into a character by taking the * byte's value for the lower eight bits of the character and setting the * high eight bits of the character to zero. This method does not, * therefore, support the full Unicode character set. * * <p> A line of text is terminated by a carriage-return character * ({@code '\u005Cr'}), a newline character ({@code '\u005Cn'}), a * carriage-return character immediately followed by a newline character, * or the end of the file. Line-terminating characters are discarded and * are not included as part of the string returned. * * <p> This method blocks until a newline character is read, a carriage * return and the byte following it are read (to see if it is a newline), * the end of the file is reached, or an exception is thrown. * * @return the next line of text from this file, or null if end * of file is encountered before even one byte is read. * @exception IOException if an I/O error occurs. */ public final Line readLine(long startPointer) throws IOException { StringBuilder input = new StringBuilder(); int c = -1; boolean eol = false; while (!eol) { switch (c = raf.read()) { case -1: case '\n': eol = true; break; case '\r': eol = true; long cur = raf.getFilePointer(); if ((raf.read()) != '\n') { raf.seek(cur); } break; default: input.append((char)c); break; } } if ((c == -1) ) { if(input.length() == 0) return new Line(null,true,true); else{ // if(fileConfig.isCloseEOF()) if(fileInfo.isCloseEOF()) return new Line(input.toString(),true,false); else{ // 需要结束本次采集 raf.seek(startPointer); return new Line(null,true,false); } } } else return new Line(input.toString(),false,eol); } private boolean reachEOFClosed(Line line){ // if(fileConfig.isCloseEOF() && line.isEof()){ if(fileInfo.isCloseEOF() && line.isEof()){ return true; } return false; } /** * 单位:毫秒 * 从文件采集(fetch)一个batch的数据后,休息一会,避免cpu占用过高,在大量文件同时采集时可以设置,大于0有效,默认值0 */ protected long sleepAwaitTimeAfterFetch = 0L; /** * 单位:毫秒 * 从文件采集完成一个任务后,休息一会,避免cpu占用过高,在大量文件同时采集时可以设置,大于0有效,默认值0 */ protected long sleepAwaitTimeAfterCollect = 0L; protected void execute() { boolean reachEOFClosed = false; File file = fileInfo.getFile(); DataTranPlugin dataTranPlugin = fileListenerService.getBaseDataTranPlugin(); InputPlugin inputPlugin = dataTranPlugin.getInputPlugin(); try { if(taskEnded || inputPlugin.isStopCollectData()) return; String charsetEncode = fileInfo.getCharsetEncode(); // synchronized (this){ 单线程处理,无需同步处理 if(raf == null) { RandomAccessFile raf = new RandomAccessFile(file, "r"); //文件重新写了,则需要重新读取 if(pointer > raf.length()){ pointer = 0; this.currentStatus.getCurrentLastValueWrapper().setLastValue(0L); } raf.seek(pointer); this.raf = raf; } //缓存 StringBuilder builder = new StringBuilder(); Line line_; String line = null; List<Record> recordList = new ArrayList<Record>(); //批量处理记录数 int fetchSize = this.fileListenerService.getImportContext().getFetchSize(); int skipHeaderLines = this.fileConfig.getSkipHeaderLines(); int readLines = 0; long startPointer = pointer; long prePointer = 0; boolean firstReader = startPointer == 0; boolean firstRow = true; while(true){ prePointer = raf.getFilePointer(); line_ = readLine( startPointer); reachEOFClosed = reachEOFClosed(line_); if(line_.getLine() != null) { line = line_.getLine(); if(firstReader && skipHeaderLines > 0 && readLines < skipHeaderLines){ pointer = raf.getFilePointer(); startPointer = pointer; readLines ++; if(!reachEOFClosed) { if(inputPlugin.isStopCollectData()) break; continue; } else { break; } } // else{ // rowStarted = true; // pointer = raf.getFilePointer(); // prePointer = pointer; // } if (charsetEncode != null) line = new String(line.getBytes("ISO-8859-1"), charsetEncode); if (null != pattern) {//多行记录匹配模式 Matcher m = pattern.matcher(line); if (m.find() && builder.length() > 0) {//下行记录行开始 pointer = raf.getFilePointer(); // result(file, pointer, builder.toString(), recordList,reachEOFClosed); //应该使用下行记录开始的位置 if(firstRow){ firstRow = false; result(file, prePointer, builder.toString(), recordList,reachEOFClosed); } else{ result(file, prePointer, builder.toString(), recordList,reachEOFClosed); } startPointer = prePointer; //分批处理数据 if (fetchSize > 0 && ( recordList.size() >= fetchSize)) { fileDataTran.appendData(new CommonData(recordList)); try { fetchAwaitSleep(); } catch (InterruptedException e) { break; } recordList = new ArrayList<Record>(); } builder.setLength(0); if(inputPlugin.isStopCollectData()){ break; } } if (builder.length() > 0) { builder.append(TranUtil.lineSeparator); } builder.append(line); if(reachEOFClosed){ pointer = raf.getFilePointer(); result(file,pointer,builder.toString(), recordList,reachEOFClosed); // startPointer = pointer; builder.setLength(0); break; } } else { pointer = raf.getFilePointer(); result(file, pointer, line, recordList,reachEOFClosed); startPointer = pointer; //分批处理数据 if (fetchSize > 0 && recordList.size() >= fetchSize) { fileDataTran.appendData(new CommonData(recordList)); try { fetchAwaitSleep(); } catch (InterruptedException e) { break; } recordList = new ArrayList<Record>(); } if(reachEOFClosed || inputPlugin.isStopCollectData()) break; } } else{ break; } } if(builder.length() > 0 ){ if(!line_.isRollbackPreLine()) { pointer = raf.getFilePointer(); result(file, pointer, builder.toString(), recordList, reachEOFClosed); } builder.setLength(0); builder = null; } if(recordList.size() > 0 ){ fileDataTran.appendData(new CommonData(recordList)); try { fetchAwaitSleep(); } catch (InterruptedException e) { } } //如果设置了文件结束,及结束作业,则进行相应处理,需迁移到通道结束处进行归档和删除处理 if(reachEOFClosed){ /** * 发送空记录 */ pointer = raf.getFilePointer(); sendReadEOFcloseEvent(pointer); taskEnded(); } // } }catch (InterruptedException e){ // logger.error("",e); } catch (Exception e){ throw new DataImportException("",e); } finally { destroy(); } } protected void sendReadEOFcloseEvent(long pointer) throws IOException, InterruptedException { List<Record> recordList = new ArrayList<Record>(1); recordList.add(new FileLogRecord(taskContext,true,pointer,true,true)); fileDataTran.appendData(new CommonData(recordList)); } protected void backupFile(String relativeParentDir,File file) throws IOException { String sourcePath = fileConfig.getSourcePath(); if(fileConfig.isScanChild()) { //需要备份到子目录 String parentDir = SimpleStringUtil.getPath( fileImportConfig.getBackupSuccessFileDir(),relativeParentDir); String path = file.getCanonicalPath(); String toPath = SimpleStringUtil.getPath(parentDir, file.getName()); FileUtil.bakFile(path, toPath); if (logger.isInfoEnabled()) logger.info("Backup File {} to {}.", path,toPath); } else{ String path = file.getCanonicalPath(); String toPath = SimpleStringUtil.getPath(fileImportConfig.getBackupSuccessFileDir(), file.getName()); FileUtil.bakFile(path, toPath); if (logger.isInfoEnabled()) logger.info("Backup File {} to {}.", path,toPath); } } public void destroy(){ if(raf != null){ try { raf.close(); } catch (IOException e) { logger.warn("raf.close failed:",e); } raf = null; } } public void destroyTaskContext(){ taskContext = null; } /** * 检查记录内容是否是需要采集的记录内容 * @param line * @return */ private boolean regexCheck(String line,Pattern[] patterns,LineMatchType matchType){ // Pattern[] includes = fileConfig.getIncludeLinesRexPattern(); // Pattern[] excludes = fileConfig.getExcludeLinesRexPattern(); boolean find = false; for(Pattern inc:patterns){ find = matchType == LineMatchType.REGEX_CONTAIN?inc.matcher(line).find(): inc.matcher(line).matches(); if(find) break; } return find; } /** * 检查记录内容是否是需要采集的记录内容 * @param line * @return */ private boolean stringCheck(String line,String[] patterns,LineMatchType matchType){ // Pattern[] includes = fileConfig.getIncludeLinesRexPattern(); // Pattern[] excludes = fileConfig.getExcludeLinesRexPattern(); boolean find = false; for(String inc:patterns){ switch (matchType){ case STRING_CONTAIN: find = line.contains(inc); break; case STRING_EQUALS: find = line.equals(inc); break; case STRING_END: find = line.endsWith(inc); break; case STRING_PREFIX: find = line.startsWith(inc); break; default: break; } if(find) break; } return find; } private boolean includeCheck(String line,String[] includeLines,LineMatchType includeLineMatchType){ boolean find = false; switch (includeLineMatchType){ case REGEX_CONTAIN: case REGEX_MATCH: Pattern[] includes = fileConfig.getIncludeLinesRexPattern(); find = regexCheck(line,includes,includeLineMatchType); break; case STRING_CONTAIN: case STRING_EQUALS: case STRING_END: case STRING_PREFIX: find = stringCheck(line,fileConfig.getIncludeLines(),includeLineMatchType); break; default: break; } return find; } private boolean excludeCheck(String line,String[] excludeLines,LineMatchType excludeLineMatchType){ boolean find = false; if(excludeLines != null && excludeLines.length > 0){ switch (excludeLineMatchType){ case REGEX_CONTAIN: case REGEX_MATCH: Pattern[] excludes = fileConfig.getExcludeLinesRexPattern(); if(regexCheck(line,excludes,excludeLineMatchType)){ find = true; } break; case STRING_CONTAIN: case STRING_EQUALS: case STRING_END: case STRING_PREFIX: if(stringCheck(line,excludeLines,excludeLineMatchType)) find = true; break; default: break; } } return find; } /** * 检查记录内容是否是需要采集的记录内容 * @param line * @return */ private boolean check(String line){ String[] includeLines = fileConfig.getIncludeLines(); String[] excludeLines = fileConfig.getExcludeLines(); LineMatchType includeLineMatchType = fileConfig.getIncludeLineMatchType(); LineMatchType excludeLineMatchType = fileConfig.getExcludeLineMatchType(); if(includeLines != null && includeLines.length > 0){ boolean find = includeCheck(line,includeLines, includeLineMatchType); if(find){ if(excludeCheck( line, excludeLines, excludeLineMatchType)) find = false; } return find; } else{ boolean find = true; if(excludeCheck( line, excludeLines, excludeLineMatchType)) find = false; return find; } } /** * 检查记录内容长度是否超过最大长度,如果超过就需要截取掉超过的内容 * @param line * @return */ private String checkMaxLength(String line){ int maxLength = fileConfig.getMaxBytes(); if(maxLength > 0 && line.length() > maxLength){ line = line.substring(0,maxLength); } return line; } private boolean needNotSplit(){ return SimpleStringUtil.isEmpty(fileConfig.getFieldSplit()) || SimpleStringUtil.isEmpty(fileConfig.getCellMappingList()); } private void result(File file, long pointer, String line,List<Record> recordList,boolean reachEOFClosed) { if(!check(line)){ recordList.add(new FileLogRecord(taskContext,true,pointer,reachEOFClosed,false)); } else { Map result = new HashMap(); try { if (jsondata) { //json Map json = SimpleStringUtil.json2Object(line, Map.class); Map addFields = this.getAddFields(); if(addFields != null && addFields.size() > 0){ json.putAll(addFields); } Map<String, Object> ignoreFields = getIgnoreFields(); if(ignoreFields != null && ignoreFields.size() > 0){ Iterator iterator = ignoreFields.keySet().iterator(); while (iterator.hasNext()){ json.remove(iterator.next()); } } //同级 if (rootLevel) { result = json; } else {//不同级 result.put("json", json); } } else { if(needNotSplit()) { line = checkMaxLength(line); result.put("@message", line); } else { FieldMappingUtil.buildRecord(result, line,fileConfig.getCellMappingList(),fileConfig.getFieldSplit()); } Map addFields = getAddFields(); if (addFields != null && addFields.size() > 0) { result.putAll(addFields); } } } catch (Exception e) { // not json result.put("@message", line); Map addFields = getAddFields(); if(addFields != null && addFields.size() > 0){ result.putAll(addFields); } } Map common = common(file, pointer); if (enableMeta) { result.put("@filemeta", common); result.put("@timestamp",new Date()); } recordList.add(new FileLogRecord(taskContext,common,result,pointer,reachEOFClosed)); } } //公共数据 protected Map common(File file, long pointer) { Map common = new HashMap(); common.put("hostIp", BaseSimpleStringUtil.getIp()); common.put("hostName",BaseSimpleStringUtil.getHostName()); common.put("filePath",FileInodeHandler.change(file.getAbsolutePath())); common.put("pointer",pointer); common.put("fileId",fileInfo.getFileId()); FtpConfig ftpConfig = this.fileConfig.getFtpConfig(); if(ftpConfig != null){ common.put("ftpDir",ftpConfig.getRemoteFileDir()); common.put("ftpIp",ftpConfig.getFtpIP()); common.put("ftpPort",ftpConfig.getFtpPort()); common.put("ftpUser",ftpConfig.getFtpUser() != null?ftpConfig.getFtpUser():"-"); common.put("ftpProtocol",ftpConfig.getTransferProtocolName()); } return common; } public String getFileId() { return fileInfo.getFileId(); } // private ReentrantLock changeFileLock = new ReentrantLock(); public void changeFile(String filePath,File file){ try { // changeFileLock.lock(); fileInfo.setFile(file); fileInfo.setFilePath(filePath); if (currentStatus != null) { // currentStatus.setFilePath(FileInodeHandler.change(file.getAbsolutePath())); currentStatus.setRealPath(filePath);//设置实际文件地址,原文件地址不变 } } finally { // changeFileLock.unlock(); } } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } @Override public String toString() { return "{\"file\":\""+ FileInodeHandler.change(fileInfo.getFile().getAbsolutePath())+"\",\"fileId\":\"" +fileInfo.getFileId()+"\",\"pointer\":"+pointer+"}"; } public boolean isTaskEnded() { return taskEnded; } public void taskEnded() { if(taskEnded) return; synchronized (this) { if(taskEnded) return; this.taskEnded = true; // this.currentStatus.setStatus(ImportIncreamentConfig.STATUS_COMPLETE); this.fileDataTran.stop(false); } } public BaseDataTran getFileDataTran() { return fileDataTran; } protected void fetchAwaitSleep() throws InterruptedException{ if(sleepAwaitTimeAfterFetch > 0L) { try { sleep(sleepAwaitTimeAfterFetch); } catch (InterruptedException e) { throw e; } } } }
true
c23690f57b16228fb05abb653d476eae4c81a506
Java
dastuer/myBatis_learning
/mybatis04/src/test/java/mapperTest.java
UTF-8
1,255
2.3125
2
[]
no_license
import com.hu.mapper.StudentMapper; import com.hu.mapper.TeacherMapper; import com.hu.mapper.TeacherMapper01; import com.hu.utils.MybatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test; public class mapperTest { @Test public void testGetStudents(){ SqlSession session = MybatisUtil.getSession(); StudentMapper mapper = session.getMapper(StudentMapper.class); System.out.println(mapper.getStudents()); session.close(); } @Test public void testGetTeacher(){ SqlSession session = MybatisUtil.getSession(); TeacherMapper mapper = session.getMapper(TeacherMapper.class); System.out.println(mapper.getTeachers()); session.close(); } @Test public void getMyStudent(){ SqlSession session = MybatisUtil.getSession(); TeacherMapper01 mapper = session.getMapper(TeacherMapper01.class); System.out.println(mapper.getStudents(1)); session.close(); } @Test public void getMyStudent01(){ SqlSession session = MybatisUtil.getSession(); TeacherMapper01 mapper = session.getMapper(TeacherMapper01.class); System.out.println(mapper.getStudents01(1)); session.close(); } }
true
50c9ab1137a109cb2a08ee7644d1c326c55ef5af
Java
yuanchunzhang/wecube-platform
/platform-core/src/main/java/com/webank/wecube/platform/core/dto/PluginPackageDataModelDto.java
UTF-8
5,658
2.1875
2
[ "Apache-2.0" ]
permissive
package com.webank.wecube.platform.core.dto; import com.webank.wecube.platform.core.domain.plugin.PluginPackageDataModel; import com.webank.wecube.platform.core.domain.plugin.PluginPackageEntity; import java.util.Set; import java.util.stream.Collectors; import static com.google.common.collect.Sets.newLinkedHashSet; public class PluginPackageDataModelDto { public static enum Source { PLUGIN_PACKAGE, DATA_MODEL_ENDPOINT } private String id; private Integer version; private String packageName; private boolean isDynamic; private String updatePath; private String updateMethod; private String updateSource; private Long updateTime; private Set<PluginPackageEntityDto> pluginPackageEntities; public PluginPackageDataModelDto() { } public PluginPackageDataModelDto(String id, Integer version, String packageName, boolean isDynamic, String updatePath, String updateMethod, String updateSource, Long updateTime, Set<PluginPackageEntityDto> pluginPackageEntities) { this.id = id; this.version = version; this.packageName = packageName; this.isDynamic = isDynamic; this.updatePath = updatePath; this.updateMethod = updateMethod; this.updateSource = updateSource; this.updateTime = updateTime; this.pluginPackageEntities = pluginPackageEntities; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } public boolean isDynamic() { return isDynamic; } public void setDynamic(boolean dynamic) { isDynamic = dynamic; } public String getUpdatePath() { return updatePath; } public void setUpdatePath(String updatePath) { this.updatePath = updatePath; } public String getUpdateMethod() { return updateMethod; } public void setUpdateMethod(String updateMethod) { this.updateMethod = updateMethod; } public String getUpdateSource() { return updateSource; } public void setUpdateSource(String updateSource) { this.updateSource = updateSource; } public Long getUpdateTime() { return updateTime; } public void setUpdateTime(Long updateTime) { this.updateTime = updateTime; } public Set<PluginPackageEntityDto> getPluginPackageEntities() { return pluginPackageEntities; } public void setPluginPackageEntities(Set<PluginPackageEntityDto> pluginPackageEntities) { this.pluginPackageEntities = pluginPackageEntities; } public static PluginPackageDataModel toDomain(PluginPackageDataModelDto dataModelDto) { PluginPackageDataModel dataModel = new PluginPackageDataModel(); if (null != dataModelDto.getId()) { dataModel.setId(dataModelDto.getId()); } if (null != dataModelDto.getVersion()) { dataModel.setVersion(dataModelDto.getVersion()); } dataModel.setPackageName(dataModelDto.getPackageName()); if (dataModelDto.isDynamic()) { dataModel.setDynamic(true); dataModel.setUpdatePath(dataModelDto.getUpdatePath()); dataModel.setUpdateMethod(dataModelDto.getUpdateMethod()); } else { dataModel.setDynamic(false); } dataModel.setUpdateSource(dataModelDto.getUpdateSource()); dataModel.setUpdateTime(dataModelDto.getUpdateTime()); if (null != dataModelDto.getPluginPackageEntities() && dataModelDto.getPluginPackageEntities().size() > 0) { Set<PluginPackageEntity> pluginPackageEntities = dataModelDto.getPluginPackageEntities().stream().map(entityDto -> PluginPackageEntityDto.toDomain(entityDto, dataModel)).collect(Collectors.toSet()); dataModel.setPluginPackageEntities(pluginPackageEntities); } return dataModel; } public static PluginPackageDataModelDto fromDomain(PluginPackageDataModel savedPluginPackageDataModel) { PluginPackageDataModelDto dataModelDto = new PluginPackageDataModelDto(); dataModelDto.setId(savedPluginPackageDataModel.getId()); dataModelDto.setVersion(savedPluginPackageDataModel.getVersion()); dataModelDto.setPackageName(savedPluginPackageDataModel.getPackageName()); dataModelDto.setUpdateSource(savedPluginPackageDataModel.getUpdateSource()); dataModelDto.setUpdateTime(savedPluginPackageDataModel.getUpdateTime()); dataModelDto.setDynamic(savedPluginPackageDataModel.isDynamic()); if (savedPluginPackageDataModel.isDynamic()) { dataModelDto.setUpdatePath(savedPluginPackageDataModel.getUpdatePath()); dataModelDto.setUpdateMethod(savedPluginPackageDataModel.getUpdateMethod()); } if (null != savedPluginPackageDataModel.getPluginPackageEntities() && savedPluginPackageDataModel.getPluginPackageEntities().size() > 0) { Set<PluginPackageEntityDto> pluginPackageEntities = newLinkedHashSet(); savedPluginPackageDataModel.getPluginPackageEntities().forEach(entity->pluginPackageEntities.add(PluginPackageEntityDto.fromDomain(entity))); dataModelDto.setPluginPackageEntities(pluginPackageEntities); } return dataModelDto; } }
true
c583a9fd5dc6a1c8bab4a0851a5a864d66086c57
Java
MewX/contendo-viewer-v1.6.3
/org/apache/batik/parser/DefaultPointsHandler.java
UTF-8
900
1.851563
2
[ "SMLNJ", "Apache-1.1", "Apache-2.0", "BSD-2-Clause" ]
permissive
/* */ package org.apache.batik.parser; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class DefaultPointsHandler /* */ implements PointsHandler /* */ { /* 31 */ public static final DefaultPointsHandler INSTANCE = new DefaultPointsHandler(); /* */ /* */ public void startPoints() throws ParseException {} /* */ /* */ public void point(float x, float y) throws ParseException {} /* */ /* */ public void endPoints() throws ParseException {} /* */ } /* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/batik/parser/DefaultPointsHandler.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
true
2101d01664ddea069500d1146bcc6ae9430d2c2d
Java
critoma/dad
/lectures/c03/src/S09_Sockets/tcpsmtp04/eu/ase/net/smtp/Base64Encoder.java
UTF-8
15,597
2.578125
3
[ "MIT" ]
permissive
package eu.ase.net.smtp; // System imports import java.lang.String; import java.text.ParseException; // Local imports // (None) /******************************************************************************* * Base-64 encoding methods. * * <p> * Base-64 encoding (a.k.a. radix-64 encoding) is a form of encoding binary data * in 6-bit units. (6 bits provides 64 distinct binary values, hence the moniker * base-<i>64</i> or radix-<i>64</i>.) Groups of three 8-bit octets (bytes), * totalling 24 bits, can be converted into four 6-bit units. Each 6-bit unit * can in turn be represented by one of 64 unique printable ASCII (8-bit) * characters. * * <p> * Converting straight binary data (as a sequence of 8-bit octets) into a * base-64 representation is thus simply the the process of packing groups of * three 8-bit octets into four 6-bit units, and then substituting each 6-bit * unit with its corresponding ASCII character code. * * <p> * Converting base-64 encoded data (as a sequence of 8-bit characters) back into * straight binary data is the reverse operation, substituting each base-64 * ASCII character code with its corresponding 6-bit unit, then unpacking groups * of four 6-bit units into three 8-bit octets. * * <p> * A 65th special ASCII character is used to indicate trailing padding in * base-64 encoded data. * * <p> * This class can be used as a simple replacement for the * {@link sun.misc.BASE64Encoder} class. * * <!-- --------------------------------------------------------------------- --> * @version $Revision: 1.2 $ $Date: 2005/04/10 20:05:52 $ * @since 2003-02-26 * @author * David R. Tribble * (<a href="mailto:david@tribble.com">david@tribble.com</a>). * <br> * * Copyright 2003-2005 by David R. Tribble, all rights reserved. * <br> * Permission is granted to freely use and distribute this source * code provided that the original copyright and authorship notices * remain intact. * * @see Base64Decoder * @see sun.misc.BASE64Encoder */ public class Base64Encoder { // Identification /** Revision information. */ static final String REV = "@(#)tribble/util/Base64Encoder.java $Revision: 1.2 $ $Date: 2005/04/10 20:05:52 $\n"; /** Class revision number. */ public static final int SERIES = 102; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Public static methods /*************************************************************************** * Encode binary data as base-64 characters. * * <!-- ----------------------------------------------------------------- --> * @param data (const) * Binary data, as an array of bytes (8-bit octets). * * @return * A printable ASCII string containing the contents of <tt>data</tt> encoded * as base-64 characters. This string will contain * <tt>data.length*4/3+<i>p</i></tt> characters, where <tt><i>p</i></tt> is * 0, 1, or 2, so as to make the total output length a multiple of 4. * * @see #encodeAsString(byte[], int, int) encodeAsString() * @see Base64Decoder#decodeString(String) Base64Decoder.decodeString() * * @since 1.1, 2003-02-26 */ public static String encodeAsString(/*const*/ byte[] data) { // Encode the binary data as base-64 characters return (encodeAsString(data, 0, data.length)); } /*************************************************************************** * Encode binary data as base-64 characters. * * <!-- ----------------------------------------------------------------- --> * @param data (const) * Binary data, as an array of bytes (8-bit octets). * * @param off * Index of the first byte (octet) within <tt>data</tt> to encode. * * @param len * Number of bytes (octets) within <tt>data</tt> to encode. * * @return * A printable ASCII string containing the contents of <tt>data</tt> encoded * as base-64 characters. This string will contain * <tt>len*4/3+<i>p</i></tt> characters, where <tt><i>p</i></tt> is * 0, 1, or 2, so as to make the total output length a multiple of 4. * * @see #encodeAsBytes(byte[], int, int) encodeAsBytes() * @see Base64Decoder#decodeString(String, byte[], int) * Base64Decoder.decodeString() * * @since 1.1, 2003-02-26 */ public static String encodeAsString(/*const*/ byte[] data, int off, int len) { byte[] b; // Encode 8-bit bytes as base-64 character bytes b = encodeAsBytes(data, off, len); // Return the encoded character bytes as a string return (new String(b)); } /*************************************************************************** * Encode binary data as base-64 character octets. * * <!-- ----------------------------------------------------------------- --> * @param data (const) * Binary data, as an array of bytes (8-bit octets). * * @return * An array of bytes containing printable ASCII characters representating the * contents of <tt>data</tt> encoded as base-64 characters. This array will * contain <tt>data.length*4/3+<i>p</i></tt> characters, where * <tt><i>p</i></tt> is 0, 1, or 2, so as to make the total output length a * multiple of 4. * * @see #encodeAsBytes(byte[], int, int) encodeAsBytes() * @see Base64Decoder#decodeBytes(byte[]) Base64Decoder.decodeBytes() * * @since 1.1, 2005-04-01 */ public static byte[] encodeAsBytes(/*const*/ byte[] data) { // Encode the binary data as base-64 characters return (encodeAsBytes(data, 0, data.length)); } /*************************************************************************** * Encode binary data as base-64 characters. * * <!-- ----------------------------------------------------------------- --> * @param data (const) * Binary data, as an array of bytes (8-bit octets). * * @param off * Index of the first byte (octet) within <tt>data</tt> to encode. * * @param len * Number of bytes (octets) within <tt>data</tt> to encode. * * @return * An array of bytes containing printable ASCII characters containing the * contents of <tt>data</tt> encoded as base-64 characters. This array will * contain <tt>data.length*4/3+<i>p</i></tt> characters, where * <tt><i>p</i></tt> is 0, 1, or 2, so as to make the total output length a * multiple of 4. * * @see #encodeAsBytes(byte[], int, int, byte[], int) encodeAsBytes() * @see Base64Decoder#decodeBytes(byte[], int, int) * Base64Decoder.decodeBytes() * * @since 1.1, 2005-04-01 */ public static byte[] encodeAsBytes(/*const*/ byte[] data, int off, int len) { byte[] enc; int olen; // Allocate the output buffer olen = (data.length+3-1)/3*4; enc = new byte[olen]; // Encode the binary data as base-64 characters encodeAsBytes(data, off, len, enc, 0); return (enc); } /*************************************************************************** * Encode binary data as base-64 characters. * * <p> * Base-64 (a.k.a. radix-64) encoding converts 8-bit bytes (octets) into * characters by encoding 6 bits of data (sextets) in each output character; * thus 3 8-bit input bytes can be converted into 4 6-bit output characters * (for a total of 24 data bits). Any input bytes left over (two or less) * are converted and padded. * * <pre> * +---------------+---------------+---------------+ * | octet | octet | octet | * |7 6 5 4 3 2 1 0|7 6 5 4 3 2 1 0|7 6 5 4 3 2 1 0| input octets * :- - - - - -:- -:- - - -:- - - -:- -:- - - - - -: * |5 4 3 2 1 0|5 4 3 2 1 0|5 4 3 2 1 0|5 4 3 2 1 0| output sextets * | sextet | sextet | sextet | sextet | * +-----------+-----------+-----------+-----------+ * * +---------------+---------------+ - - - - - - - + * | octet | octet | no data : * |7 6 5 4 3 2 1 0|7 6 5 4 3 2 1 0| : input octets * :- - - - - -:- -:- - - -:- - - -:- -:- - - - - -: * |5 4 3 2 1 0|5 4 3 2 1 0|5 4 3 2 z z| '=' | output sextets * | sextet | sextet | sextet | padding | * +-----------+-----------+-----------+-----------+ * * +---------------+ - - - - - - - + - - - - - - - + * | octet | no data : no data : * |7 6 5 4 3 2 1 0| : : input octets * :- - - - - -:- -:- - - -:- - - -:- -:- - - - - -: * |5 4 3 2 1 0|5 4 z z z z| '=' | '=' | output sextets * | sextet | sextet | padding | padding | * +-----------+-----------+-----------+-----------+ </pre> * * <p> * For example, the following table list some octet sequences and their * resulting sextet encodings: * <pre> * 11,11,11 => 04,11,04,11 * 11,22,33 => 04,12,08,33 * FF,FF,FF => 3F,3F,3F,3F * 11,11 => 04,11,04, = * FF,FF => 3F,3F,3C, = * 11 => 04,10, =, = * FF => 3F,30, =, = * FF,00,FF,00,FF,00 => 3F,30,03,3F,00,0F,3C,00 </pre> * * <!-- ----------------------------------------------------------------- --> * @param data (const) * Binary data, as an array of bytes (8-bit octets). * * @param off * Index of the first byte (octet) within <tt>data</tt> to encode. * * @param len * Number of bytes (octets) within <tt>data</tt> to encode. * * @param enc * An array of bytes into which will be written printable ASCII characters * representating the contents of <tt>data</tt> encoded as base-64 * characters. * * @param encOff * Index of the first byte (octet) within <tt>enc</tt> to write to. * * @return * The number of bytes (8-bit octets) actually written into <tt>enc</tt>. * This will be exactly <tt>len*4/3+<i>p</i></tt> bytes, where * <tt><i>p</i></tt> is 0, 1, or 2, so as to make the total output length a * multiple of 4. * * @see #encodeAsBytes(byte[], int, int, byte[], int) encodeAsBytes() * @see Base64Decoder#decodeBytes(byte[], int, int) * Base64Decoder.decodeBytes() * * @since 1.1, 2005-04-01 */ public static int encodeAsBytes(/*const*/ byte[] data, int off, int len, byte[] enc, int encOff) { int d; int i; int o; // Convert the input bytes in chunks, 24 bits (3 octets) at a time len += off; i = off; o = encOff; while (i < len-2) { // Convert a single 24-bit chunk (3 octets into 4 sextets) d = ((data[i+0] & 0xFF) << 16) | ((data[i+1] & 0xFF) << 8) | ((data[i+2] & 0xFF)); i += 3; enc[o++] = toBase64((d >> 18) & 0x3F); enc[o++] = toBase64((d >> 12) & 0x3F); enc[o++] = toBase64((d >> 6) & 0x3F); enc[o++] = toBase64((d) & 0x3F); } // Convert leftover input bytes, if any if (i < len-1) { // Two input bytes left, requires one padding char d = ((data[i+0] & 0xFF) << 16) | ((data[i+1] & 0xFF) << 8); enc[o++] = toBase64((d >> 18) & 0x3F); enc[o++] = toBase64((d >> 12) & 0x3F); enc[o++] = toBase64((d >> 6) & 0x3F); enc[o++] = '='; } else if (i < len) { // One input byte left, requires two padding chars d = ((data[i+0] & 0xFF) << 16); enc[o++] = toBase64((d >> 18) & 0x3F); enc[o++] = toBase64((d >> 12) & 0x3F); enc[o++] = '='; enc[o++] = '='; } // Done return (o-encOff); } /*************************************************************************** * Convert a 6-bit binary value into its corresponding base-64 printable * ASCII character code. * * <!-- ----------------------------------------------------------------- --> * @param bits * A 6-bit binary value in the range [0,63]; or the value 64, indicating the * special trailing padding character code; or the character <tt>'?'</tt>, * indicating an invalid 6-bit code. * * @return * A printable ASCII character code. * * @see Base64Decoder#fromBase64 Base64Decoder.fromBase64() * * @since 1.1, 2003-02-26 */ public static byte toBase64(int bits) { // This averages 2.85 comparisons per call if (bits >= 52) { if (bits < 62) return ((byte) (bits-52+'0')); if (bits == 62) return ((byte) '+'); if (bits == 63) return ((byte) '/'); if (bits == 64) return ((byte) '='); return ((byte) '?'); } if (bits >= 26) return ((byte) (bits-26+'a')); if (bits >= 0) return ((byte) (bits-0+'A')); return ((byte) '?'); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Variables // (None) // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Public constructors /*************************************************************************** * Default constructor. * * <p> * This constructor is provided for compatibility with the * {@link sun.misc.BASE64Encoder} class, which allows this class to be used * as a simple replacement for it. * * @since 1.2, 2005-04-10 */ public Base64Encoder() { // Do nothing } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Public methods /*************************************************************************** * Encode binary data as base-64 characters. * * <p> * This method produces the same result as the <tt>encode()</tt> method * of the {@link sun.misc.BASE64Encoder} class. * * <!-- ----------------------------------------------------------------- --> * @param data (const) * Binary data, as an array of bytes (8-bit octets). * * @return * A printable ASCII string containing the contents of <tt>data</tt> encoded * as base-64 characters. This string will contain * <tt>data.length*4/3+<i>p</i></tt> characters, where <tt><i>p</i></tt> is * 0, 1, or 2, so as to make the total output length a multiple of 4. * * @see #encodeAsString(byte[]) encodeAsString() * @see Base64Decoder#decodeString(String) Base64Decoder.decodeString() * * @since 1.2, 2005-04-10 */ public String encode(/*const*/ byte[] data) { // Encode the binary data as base-64 characters return (encodeAsString(data, 0, data.length)); } } // End Base64Encoder.java
true
396873b61152c4a5189f18c4c06c4d19ea1b71d1
Java
carlorizzante/Software-Construction-2---Object-Oriented-Design
/StudentRecord/src/model/Registrar.java
UTF-8
1,940
3.140625
3
[]
no_license
package model; import exceptions.CourseFullException; import exceptions.MissingPrereqException; import java.util.LinkedList; import java.util.List; public class Registrar { private String name; private List<Transcript> students; public Registrar(String name) { this.name = name; students = new LinkedList<>(); } // getters public String getName() { return name; } public List<Transcript> getStudents() { return students; } // MODIFIES: this // EFFECTS: returns true if the student (represented as a transcript) was successfully added to the // Registrar's list. Remember to check if the student already exists in the list public boolean addStudent(Transcript stu) { if (!students.contains(stu)) { students.add(stu); return true; } else { return false; } } // REQUIRES: that the student represented by the transcript has the necessary prerequisite required // to take the course. // MODIFIES: the transcript object passed in as parameter // EFFECTS: given the REQUIRES clause holds, the student represented by the transcript is registered in the given // course public boolean registerStudent(Course c, Transcript tct) { try { tct.addCourse(c); return true; } catch (MissingPrereqException | CourseFullException e) { System.out.println(e.getMessage()); return false; } } // EFFECTS: promotes all students to their next year level. It should throw GPATooLowException or // NoCoursesTakenException public void promoteAllStudents() { for (Transcript student : students) { try { student.promoteStudent(); } catch (Exception e) { System.out.println(e.getMessage()); } } } }
true
0b0d8d815f05e73e8700ad973b9a59bd24a12f7b
Java
anubhavkasturia/Stack
/StackUsingLinkedList.java
UTF-8
1,323
3.875
4
[]
no_license
public class StackUsingLinkedList { private class Node{ int data; Node next; } Node top; StackUsingLinkedList(){ this.top=null; } public boolean isEmpty(){ if(top==null){ return true; }else{ return false; } } public boolean isFull(){ Node temp=new Node(); if(temp==null){ System.out.println("Heap overflow"); return true; }else{ return false; } } public void push(int data) { Node temp = new Node(); if (temp == null) { System.out.print("Heap Overflow"); return; } temp.data=data; temp.next=top; top=temp; } public void display() { // check for stack underflow if (top == null) { System.out.println("Stack is empty"); } else { Node temp = top; while (temp != null) { System.out.println(temp.data); temp = temp.next; } } } public int stackTop(){ if(top==null){ System.out.println("Stack is empty"); } return top.data; } }
true
e634da4808d2047c7b3bab8285339d0e643e253e
Java
Desarik98/Lab3-CVDS
/src/test/java/edu/eci/cvds/tdd/registry/RegistryTest.java
UTF-8
1,616
2.703125
3
[]
no_license
package edu.eci.cvds.tdd.registry; import org.junit.Assert; import org.junit.Test; public class RegistryTest { private Registry registry = new Registry(); @Test public void validateInvalidAge() { Person person = new Person(); person.setAge(-1); RegisterResult result = registry.registerVoter(person); Assert.assertEquals(RegisterResult.INVALID_AGE, result); } @Test public void validateDuplicatedId(){ Person daniel = new Person("Daniel",1019139154,22,Gender.MALE,true); Person camila = new Person("Camila",1019139154,22,Gender.FEMALE,true); camila.setId(1019139154); RegisterResult result = registry.registerVoter(daniel); result = registry.registerVoter(camila); Assert.assertEquals(RegisterResult.DUPLICATED,result); } @Test public void validateDeadPerson(){ Person daniel = new Person("Daniel",1019139154,22,Gender.MALE,false); RegisterResult result = registry.registerVoter(daniel); Assert.assertEquals(RegisterResult.DEAD,result); } @Test public void validateUnderagePerson(){ Person daniel = new Person("Daniel",1019139154,16,Gender.MALE,true); RegisterResult result = registry.registerVoter(daniel); Assert.assertEquals(RegisterResult.UNDERAGE,result); } @Test public void validateRegistratedPerson(){ Person daniel = new Person("Daniel",1019139154,22,Gender.MALE,true); RegisterResult result = registry.registerVoter(daniel); Assert.assertEquals(RegisterResult.VALID,result); } }
true
4928cdc5f0aa8161b5dd09ae93d018da030033cf
Java
andyradz/smartstore
/smartstore-sdk/smartstore-sdk-core/src/main/java/com/codigo/smartstore/sdk/core/compare/IComparable.java
UTF-8
712
2.90625
3
[]
no_license
package com.codigo.smartstore.sdk.core.compare; import org.checkerframework.checker.nullness.qual.NonNull; /** * Interfejs deklaruje kontrakt opisujący mechanizm porównywania dwóch obiektów. * Implementacja interfajsu będzie miała postaci operatora porównania. * * @author andrzej.radziszewski * @version 1.0.0.0 * @since 2017 * @category operator */ @FunctionalInterface public interface IComparable { /** * @param leftOperand Lewy operand operatora porównania * @param rightOperand Prawy operand operatora porównania * @return Wynik operacji porównania w postaci logicznej TRUE,FALSE */ boolean compare(@NonNull Comparable<?> leftOperand, @NonNull Comparable<?> rightOperand); }
true
c6ad817c952e64bd99008751f34bf6d43de00d7a
Java
kiiib/Java-HomeWork
/BookStore/src/BookStore.java
UTF-8
3,617
3.421875
3
[]
no_license
/** * Created by Jianbin Liu on 4/5/2016. */ import java.util.ArrayList; import java.util.EnumSet; import java.util.Scanner; import java.io.Console; import java.util.regex.Matcher; import java.util.regex.Pattern; public class BookStore { private static Book books; public static void main(String[] args){ printBooks(); orderBook(); } /** * 印出書籍清單 */ private static void printBooks(){ System.out.println("********** Welcome to Book Store **********"); for(Book book: Book.values()){ System.out.printf("%-1s)%-1s\t%.2f元\n",book.getBookID(),book.getBookTitle(),book.getBookPrice()); } } /** * 訂購書籍 */ private static void orderBook(){ Console cons = System.console(); ArrayList<String> bookList = new ArrayList<String>(); //訂購書籍list ArrayList<String> bookAmountList = new ArrayList<String>(); //訂購書籍數量list String buyerName; String buyerTel; String isContinue; //是否繼續購買 String bookNumber; //書籍編號 String bookAmount; //書籍購買數量 boolean isNext; do { bookNumber = cons.readLine("請輸入訂購書籍(1~6): "); if(isOrderBookNumberFormat(bookNumber)){ bookList.add(bookNumber); }else { isContinue = cons.readLine("繼續選購嗎?(Y/N)"); continue; } bookAmount = cons.readLine("數量: "); if(isOrderBookAmountFormat(bookAmount)){ bookAmountList.add(bookAmount); }else{ isContinue = cons.readLine("繼續選購嗎?(Y/N)"); continue; } isContinue = cons.readLine("繼續選購嗎?(Y/N)"); }while (isContinue.toUpperCase().equals("Y")); do{ isNext = true; buyerName = cons.readLine("請輸入您的姓名: "); buyerTel = cons.readLine("請輸入聯絡電話: "); if(!isOrderFormat(buyerName, buyerTel)){ isNext = false; } }while (!isNext); BookOrder newOrder = new BookOrder(bookList, bookAmountList, buyerName, buyerTel); newOrder.printOrder(); } /** * isOrderBookNumberFormat * @param bookNumber 書籍代碼 * @return boolean */ private static boolean isOrderBookNumberFormat(String bookNumber){ if(!bookNumber.matches("[1-6]")) { System.out.println("請輸入正確書籍代碼!"); return false; } return true; } /** * isOrderBookAmountFormat * @param bookAmount 書籍購買數量 * @return boolean */ private static boolean isOrderBookAmountFormat(String bookAmount){ if(!bookAmount.matches("\\d+")) { System.out.println("請輸入數量!"); return false; } return true; } /** * 驗證訂購格式 * @param name 購買人姓名 * @param phone 購買人電話 * @return boolean */ private static boolean isOrderFormat(String name, String phone){ if(name.matches("[a-zA-Z]+[0-9]*") && phone.matches("[0-9]{4}-[0-9]{6}")) return true; if(!name.matches("[a-zA-Z]+[0-9]*")) { System.out.println("請輸入正確姓名!"); } if(!phone.matches("[0-9]{4}-[0-9]{6}")){ System.out.println("電話格式有誤! (格式: 0000-000000)"); } return false; } }
true
664b475cf3656dd17ed3ee469a2afc341035e9a0
Java
HHSAPCompSci2020/capstone-project-jej
/GravityBall/src/Menu.java
UTF-8
2,283
2.90625
3
[]
no_license
import java.awt.Point; import java.io.IOException; import java.io.InputStream; import java.awt.Rectangle; import javax.imageio.ImageIO; import java.awt.Image; import processing.core.PImage; /** * @author APCS Demos 2021, modified for own use by Jensen and Jim */ public class Menu extends Screen { private DrawingSurface surface; private Rectangle start; private Rectangle howToPlay; private PImage title; private PImage background; public Menu(DrawingSurface surface) { super(800,600); this.surface = surface; start = new Rectangle(800/2-100,600/2-100,150,50); howToPlay = new Rectangle(800/2-100,600/2,150,50); } /** * sets up the image */ public void setup() { InputStream is = getClass().getClassLoader().getResourceAsStream("gravityball1.png"); try { Image i = ImageIO.read(is); title = new PImage(i); } catch (IOException e) { e.printStackTrace(); } is = getClass().getClassLoader().getResourceAsStream("nature.jpg"); try { Image i = ImageIO.read(is); background = new PImage(i); } catch (IOException e) { e.printStackTrace(); } //title = surface.loadImage("gravityball1"); //background = surface.loadImage("data/nature.jpg"); } /** * draws the screen */ public void draw() { surface.pushStyle(); surface.background(255,255,255); surface.image(background,0,0,800,600); surface.fill(255); surface.rect(start.x, start.y, start.width, start.height, 10, 10, 10, 10); surface.fill(0); String str = "Play"; float w = surface.textWidth(str); surface.text(str, start.x+start.width/2-w/2, start.y+start.height/2); surface.fill(255); surface.rect(howToPlay.x, howToPlay.y, howToPlay.width, howToPlay.height, 10, 10, 10, 10); surface.fill(0); str = "How to Play"; w = surface.textWidth(str); surface.text(str, howToPlay.x+howToPlay.width/2-w/2, howToPlay.y+howToPlay.height/2); surface.image(title, 100, 80,600,100); surface.popStyle(); } /** * detects the buttons */ public void mousePressed() { Point p = surface.actualCoordinatesToAssumed(new Point(surface.mouseX,surface.mouseY)); if (start.contains(p)) surface.switchScreen(ScreenSwitcher.LVLSELECT); else if(howToPlay.contains(p)) surface.switchScreen(ScreenSwitcher.INSTRUCTION); } }
true
ebcf18f0cb37203741fe034a06008a3d33fcb938
Java
sidneyperota/financeiro
/src/visao/FrmPrincipal.java
UTF-8
2,783
2.671875
3
[]
no_license
package visao; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.FlowLayout; import javax.swing.JDesktopPane; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JMenu; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class FrmPrincipal extends JFrame { private JPanel contentPane; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { FrmPrincipal frame = new FrmPrincipal(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public FrmPrincipal() { setTitle("Controle de Caixa"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setExtendedState(MAXIMIZED_BOTH); //setBounds(450, 200, 754, 477); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu mnCaixa = new JMenu("Caixa"); menuBar.add(mnCaixa); JMenuItem mntmNewMenuItem = new JMenuItem("Consulta"); mnCaixa.add(mntmNewMenuItem); JMenuItem mntmNewMenuItem_1 = new JMenuItem("Altera\u00E7\u00E3o"); mnCaixa.add(mntmNewMenuItem_1); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); JPanel panel = new JPanel(); FlowLayout flowLayout = (FlowLayout) panel.getLayout(); flowLayout.setVgap(20); contentPane.add(panel, BorderLayout.NORTH); JPanel panel_1 = new JPanel(); contentPane.add(panel_1, BorderLayout.CENTER); panel_1.setLayout(new BorderLayout(0, 0)); JDesktopPane desktopPane = new JDesktopPane(); // Evento OnClick do Lancamento de Caixa mntmNewMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JIFrmConsultaMovimento jifrmConsultaMovimento = new JIFrmConsultaMovimento(); jifrmConsultaMovimento.setVisible( true ); desktopPane.add( jifrmConsultaMovimento ); } }); JMenuItem mntmLanamento = new JMenuItem("Lan\u00E7amento"); mntmLanamento.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { FrmLancCaixa frmLancCaixa = new FrmLancCaixa(); frmLancCaixa.setVisible( true ); desktopPane.add( frmLancCaixa ); } }); mnCaixa.add(mntmLanamento); panel_1.add(desktopPane, BorderLayout.CENTER); JPanel panel_2 = new JPanel(); FlowLayout flowLayout_1 = (FlowLayout) panel_2.getLayout(); flowLayout_1.setVgap(20); contentPane.add(panel_2, BorderLayout.SOUTH); } }
true
d4cd28e01d15d5545bb5ae125bf80d18563ffe3a
Java
13igg/Coding-Challenges
/misc/Java/CodingProblems/LinkedLists/RemoveLinkedListDups.java
UTF-8
1,137
3.546875
4
[]
no_license
package LinkedLists; import java.util.HashSet; //remove dups //use a hashset //store the previous node //if the set contains next's data, set previous.next = next //else, add the data to the set //remove dups with no buffer //take current, and then //use a runner that checks ahead the list //set the next = to that next //O(n) time - one pass through the linked list public class RemoveLinkedListDups { public void RemoveDups(LinkedListNode n) { HashSet<Integer> set = new HashSet<Integer>(); LinkedListNode previous = null; while(n != null) { if(set.contains(n.data)) previous.next = n.next; else { set.add(n.data); previous = n; } n = n.next; } } //************************************************************************ public void RemoveDupsNoBuffer(LinkedListNode head) { LinkedListNode current = head; while(current != null) { LinkedListNode runner = current; while(runner.next != null) { if(runner.next.data == current.data) runner.next = runner.next.next; else runner = runner.next; } current = current.next; } } }
true
caf41a8b5dd6e22824e5a56ceeab06bfac83f4be
Java
Parizat0129/Spring2020B18_Java
/src/OffieceHours/Practice_03_25_2020/NestedIf_Practice.java
UTF-8
666
3.15625
3
[]
no_license
package OffieceHours.Practice_03_25_2020; public class NestedIf_Practice { public static void main(String[] args) { byte weekDays=9; boolean validNumber= weekDays>0 && weekDays<8; String result=" "; if(validNumber){ if(weekDays==1){ result="Monday"; }else if(weekDays==2){ result="Tuesday"; }else if(weekDays==3){ result="Wednesday"; }else if(weekDays==4){ result="Thursday"; }else if(weekDays==5){ result="Saturday"; }else{ result="Sunday"; } }else{ result="Invalid Entry"; } } }
true
d5cff2ffd123d29d27d16a1550ec4130235571c3
Java
simsim466/foodcourt
/src/main/java/web/meal/AdminMealController.java
UTF-8
1,735
2.296875
2
[]
no_license
package web.meal; import model.Meal; import model.Restaurant; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; @RestController @RequestMapping(value = AdminMealController.ADMIN_MEAL, produces = MediaType.APPLICATION_JSON_VALUE) public class AdminMealController extends AbstractMealController { static final String ADMIN_MEAL = "/meal/admin"; static final int ADMIN_ID = 10; @GetMapping("/{mealId}/{resId}") public Meal getWithRestaurant(@PathVariable int mealId, @PathVariable int resId) { return super.getWithRestaurant(mealId, resId, ADMIN_ID); } @DeleteMapping("/{mealId}/{resId}") @ResponseStatus(HttpStatus.NO_CONTENT) public void delete(@PathVariable int mealId, @PathVariable int resId) { super.delete(mealId, resId, ADMIN_ID); } @PutMapping(value = "/{resId}", consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Meal> createWithLocation(@RequestBody Meal meal, @PathVariable int resId) { Meal created = super.create(meal, resId, ADMIN_ID); URI uriOfNewResource = ServletUriComponentsBuilder.fromCurrentContextPath() .path(ADMIN_MEAL + "/{id}") .buildAndExpand(created.getId()).toUri(); return ResponseEntity.created(uriOfNewResource).body(created); } @PutMapping("/{resId}") @ResponseStatus(HttpStatus.NO_CONTENT) public void update(@RequestBody Meal meal, @PathVariable int resId) { super.create(meal, resId, ADMIN_ID); } }
true
e4248b0694d8549a081975c050985e9ac394148b
Java
jtomaszewska/technologie-programowania-rozproszonego
/TPO3_TJ_S15313/src/zad1/Main.java
UTF-8
1,056
3.25
3
[]
no_license
/** * @author Tomaszewska Justyna S15313 */ package zad1; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException, InterruptedException { Server server = new Server("localhost", 8090); Client client1 = new Client("client 1"); client1.addListener((msg) -> System.out.println("client 1: otrzymalem wiadomosc " + msg)); Client client2 = new Client("client 2"); client2.addListener((msg) -> System.out.println("client 2: otrzymalem wiadomosc " + msg)); Thread serverThread = new Thread(() -> { server.startServer(); System.out.println("Server exit"); }); serverThread.start(); new Thread(() -> client1.startClient()).start(); new Thread(() -> client2.startClient()).start(); Thread.sleep(9000); client1.send("wiadomosc 1 "); client2.send("wiadomosc 2"); Thread.sleep(5000); client1.disconnect(); client2.disconnect(); server.stop(); } }
true
4b8b449e8f11544cd4e9c0f1a39cc09e6ab72fc6
Java
GDanielAvram/tiendaOnline
/src/com/tiendaOnline/service/ClienteEntityServiceImpl.java
ISO-8859-10
1,075
2.15625
2
[]
no_license
package com.tiendaOnline.service; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import com.tiendaOnline.dao.ClienteDao; import com.tiendaOnline.model.ClienteEntity; @Transactional @Service public class ClienteEntityServiceImpl implements ClienteEntityService{ @Autowired private ClienteDao clienteDao; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Override public ClienteEntity autenticarUsuario(String usuario, String contrasea) { return clienteDao.autenticarUsuario(usuario, contrasea); } @Override public ClienteEntity findByUsername(String username) { return clienteDao.findByUsername(username); } @Override public ClienteEntity create(ClienteEntity clienteEntity) { clienteEntity.setPassword(bCryptPasswordEncoder.encode(clienteEntity.getPassword())); return clienteDao.create(clienteEntity); } }
true
e9b18b2e8acfe549548b24eecd10ba175c1b2c54
Java
lichao20000/WEB
/src/main/java/com/linkage/module/itms/resource/bio/SpeedTest1000MBIO.java
UTF-8
1,581
1.867188
2
[]
no_license
package com.linkage.module.itms.resource.bio; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.linkage.commons.util.StringUtil; import com.linkage.litms.LipossGlobals; import com.linkage.module.itms.resource.dao.DevBatchRestartQueryDAO; import com.linkage.module.itms.resource.dao.SpeedTest1000MDAO; @SuppressWarnings("rawtypes") public class SpeedTest1000MBIO { private static Logger logger = LoggerFactory.getLogger(SpeedTest1000MBIO.class); private SpeedTest1000MDAO dao; public List<Map> queryCityId(String area_id){ return dao.queryCityId(area_id); } public List<Map> query(String speedRet,String bandwidth,String startTime,String endTime,String cityId,int curPage_splitPage, int num_splitPage){ return dao.query(speedRet, bandwidth, startTime, endTime, cityId, curPage_splitPage, num_splitPage); } public int queryCount(String speedRet,String bandwidth,String startTime,String endTime,String cityId,int curPage_splitPage, int num_splitPage){ return dao.queryCount(speedRet, bandwidth, startTime, endTime, cityId, curPage_splitPage, num_splitPage); } public List<Map> toExcel(String speedRet,String bandwidth,String startTime,String endTime,String cityId,int curPage_splitPage, int num_splitPage){ return dao.toExcel(speedRet, bandwidth, startTime, endTime, cityId); } public SpeedTest1000MDAO getDao() { return dao; } public void setDao(SpeedTest1000MDAO dao) { this.dao = dao; } }
true
f33246d66eb9eb17b7952421ea9204155792653e
Java
tanianegrete/java
/Clases/Persona.java
UTF-8
545
2.40625
2
[]
no_license
package Clases; public class Persona { private String colorPelo; private String nombre; private int edad; public String getNombre() { return this.nombre; } public String getColorPelo() { return colorPelo; } public void setColorPelo(String colorPelo) { this.colorPelo = colorPelo; } public int getEdad() { return edad; } public void setEdad(int ayo) { int ayoActual= 2021; this.edad = ayoActual- ayo; } public void setNombre(String nombre) { this.nombre = nombre; } }
true
0328760da1e6ff954f77722846fca1f947d8a070
Java
jiuzhou9/learn
/src/test/java/com/test/demo/thread/create/Demo.java
UTF-8
3,144
3.515625
4
[]
no_license
package com.test.demo.thread.create; import org.junit.Test; /** * Created by jiuzhou on 2017/5/28. */ public class Demo { /** * 继承Thread的方式创建线程 * 测试join方法作用 */ @Test public void testJoin(){ ThreadNO1 t1 = new ThreadNO1(); ThreadNO1 t2 = new ThreadNO1(); t1.setName("我是第一号线程"); t2.setName("我是第二号线程"); t1.start(); t2.start(); /*-------------------------------*/ //join方法:当方法所在前线程A等待线程B(调用join的线程)执行完毕再往下执行; // 如果没有join方法,线程A不会等待线程B执行完毕就会往下执行 //换句话说就是有join就是异步变同步,如果没有join就是异步线程 try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } /*-------------------------------*/ System.out.println(t1.isAlive()); } /** * 实现runnable接口方式创建线程 * 测试join方法作用 */ @Test public void testRunnable(){ RunnableNO1 r1 = new RunnableNO1(); Thread t1 = new Thread(r1); Thread t2 = new Thread(r1); t1.setName("第一条线程"); t2.setName("第二条线程"); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(t1.isAlive()); } /** * Thread和Runnable的区别:Runnable可以共享资源,但是Thread不可以共享资源 */ @Test public void testThreadTicket(){ ThreadTicket t1 = new ThreadTicket(); ThreadTicket t2 = new ThreadTicket(); t1.setName("t1"); t2.setName("t2"); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Thread和Runnable的区别:Runnable可以共享资源,但是Thread不可以共享资源 */ @Test public void testRunnableTicket(){ RunnableTicket runnableTicket = new RunnableTicket(); Thread t1 = new Thread(runnableTicket); Thread t2 = new Thread(runnableTicket); t1.setName("t1"); t2.setName("t2"); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } } @Test public void testCreate(){ //第一种方式 //ThreadNO1 thread = new ThreadNO1(); //第二种方式 // RunnableNO1 runnableNO1 = new RunnableNO1(); Thread thread = new Thread(new RunnableNO1()); thread.start(); System.out.println(1); thread.interrupt(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }
true
13dac6973e69d6c41f47af03db1c2cc7dc77b17c
Java
dipakprasad1726/LearningPortal
/src/main/java/com/learning/portal/ResourceController/CourseResourse.java
UTF-8
3,224
2.40625
2
[]
no_license
package com.learning.portal.ResourceController; import com.learning.portal.exceptions.CountryNotFoundException; import com.learning.portal.exceptions.CourseNotFoundException; import com.learning.portal.exceptions.QueryFailureException; import com.learning.portal.model.AddPricingComponentRequest; import com.learning.portal.model.Course; import com.learning.portal.model.GetCourseRequest; import com.learning.portal.model.db.QueryManager; import org.json.JSONException; import org.json.JSONObject; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.inject.Inject; import javax.ws.rs.ext.Provider; import java.sql.SQLException; import java.util.List; @RequestMapping("course") @Provider @RestController public class CourseResourse { @Inject private QueryManager queryManager; public CourseResourse(QueryManager queryManager){ this.queryManager = queryManager; } @GetMapping("/") public List<Course> getAllCourses() throws SQLException { return queryManager.getAllCourse(); } @GetMapping("/{id}/{countryCode}") public Course getCourse(@PathVariable int id,@PathVariable String countryCode) throws SQLException { Course course = queryManager.getCourseById(id,countryCode); if(course==null) throw new CourseNotFoundException(); else return course; } @GetMapping("/getCourse") public Course getCourse(GetCourseRequest getCourseRequest) throws SQLException { Course course = queryManager.getCourse(getCourseRequest); if(course==null) throw new CourseNotFoundException(); else return course; } @PutMapping("/addNewCourse") public ResponseEntity<Object> addNewCourse(Course course) throws SQLException, JSONException { if(queryManager.addNewCourse(course)){ throw new QueryFailureException(); }else{ JSONObject jo = new JSONObject(); jo.put("status","SUCCESS"); jo.put("message","Course added successfully"); return new ResponseEntity<>(jo.toString(), HttpStatus.ACCEPTED); } } @PutMapping("/addNewPricingComponent") public ResponseEntity<Object> addNewPricingComponent(AddPricingComponentRequest addPricingComponentRequest) throws SQLException, JSONException { if(!queryManager.addNewPricingComponent(addPricingComponentRequest)) throw new QueryFailureException(); JSONObject jo = new JSONObject(); jo.put("status","SUCCESS"); jo.put("message","Pricing component "+addPricingComponentRequest.getComponentName()+" added successfully"); return new ResponseEntity<>(jo.toString(), HttpStatus.ACCEPTED); } @PutMapping("/editCourse") public ResponseEntity<Object> editCourse(Course course) throws JSONException, SQLException { if(!queryManager.editCourse(course)) throw new QueryFailureException(); JSONObject jo = new JSONObject(); jo.put("status","SUCCESS"); jo.put("message","Course "+course.getCourseName()+" edited successfully"); return new ResponseEntity<>(jo.toString(), HttpStatus.ACCEPTED); } }
true
cb4f4a670d7b42c9f9352ce158db5d39bf2d7624
Java
cjqCN/tinypk
/tinypk-service/src/main/java/com/github/cjqcn/tinypk/service/internal/LongRedisBasedInstanceIdLock.java
UTF-8
975
2.328125
2
[ "Apache-2.0" ]
permissive
package com.github.cjqcn.tinypk.service.internal; import org.springframework.data.redis.core.RedisOperations; import java.util.concurrent.ThreadLocalRandom; /** * @author chenjinquan */ public class LongRedisBasedInstanceIdLock extends RedisBasedInstanceIdLock<Long> { private static final int DEFAULT_OFFSET = 0; private static final int DEFAULT_LIMIT = 1024; private final int offset; private final int limit; public LongRedisBasedInstanceIdLock(String scope, RedisOperations<String, String> redisOperations, int offset, int limit) { super(scope, redisOperations); this.offset = offset; this.limit = limit; } public LongRedisBasedInstanceIdLock(RedisOperations<String, String> redisOperations) { this(DEFAULT_SCOPE, redisOperations, DEFAULT_OFFSET, DEFAULT_LIMIT); } @Override protected Long randomInstanceId() { return ThreadLocalRandom.current().nextLong(offset, limit); } }
true
6879c3067ab11c227797800629965b97cb02999a
Java
GennadyMV/tmc-core-abandoned
/src/test/java/fi/helsinki/cs/tmc/client/core/async/task/AbstractTaskTest.java
UTF-8
6,316
2.484375
2
[]
no_license
package fi.helsinki.cs.tmc.client.core.async.task; import fi.helsinki.cs.tmc.client.core.async.Task; import fi.helsinki.cs.tmc.client.core.async.TaskListener; import fi.helsinki.cs.tmc.client.core.async.TaskProgressListener; import fi.helsinki.cs.tmc.client.core.async.TaskResult; import fi.helsinki.cs.tmc.client.core.async.exception.TaskFailureException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; public class AbstractTaskTest { private class InterruptInstantlyTask extends AbstractTask<String> { public InterruptInstantlyTask(final TaskListener listener) { super("interruptInstantlyTask", listener); } @Override protected String work() throws InterruptedException, TaskFailureException { throw new InterruptedException(); } @Override protected void cleanUp() { setProgress(1, 1); } } private class FailInstantlyTask extends AbstractTask<String> { public FailInstantlyTask(final TaskListener listener) { super("failInstantlyTask", listener); } @Override protected String work() throws InterruptedException, TaskFailureException { throw new TaskFailureException(); } @Override protected void cleanUp() { setProgress(1, 1); } } private class FinishInstantlyTask extends AbstractTask<String> { public FinishInstantlyTask(final TaskListener listener) { super("finishInstantlyTask", listener); } @Override protected String work() throws InterruptedException, TaskFailureException { return "success"; } @Override protected void cleanUp() { setProgress(1, 1); } } private class NeverFinishTask extends AbstractTask<String> { public NeverFinishTask(final TaskListener listener) { super("neverFinishTask", listener); } @Override protected String work() throws InterruptedException, TaskFailureException { while (true) { checkForInterrupt(); } } @Override protected void cleanUp() { setProgress(1, 1); } } private TaskListener listener; private TaskProgressListener progressListener; @Before public void setUp() { listener = mock(TaskListener.class); progressListener = mock(TaskProgressListener.class); } @Test public void successCallsListenerCorrectly() { final Task task = new FinishInstantlyTask(listener); task.addProgressListener(progressListener); task.run(); //Assert cleanUp() not called. Only increment is in cleanUp() verify(progressListener, times(0)).onProgress(1, 1); assertEquals("finishInstantlyTask", task.getDescription()); verify(progressListener).onStart(); verify(listener).onSuccess(any(TaskResult.class)); verify(progressListener).onEnd(); verifyNoMoreInteractions(listener, progressListener); } @Test public void interruptCallsListenerCorrectly() { final Task task = new InterruptInstantlyTask(listener); task.addProgressListener(progressListener); task.run(); assertEquals("interruptInstantlyTask", task.getDescription()); verify(progressListener).onStart(); verify(listener).onInterrupt(any(TaskResult.class)); // cleanup() called verify(progressListener).onProgress(1, 1); verify(progressListener).onEnd(); verifyNoMoreInteractions(listener, progressListener); } @Test public void failureCallsListenerCorrectly() { final Task task = new FailInstantlyTask(listener); task.addProgressListener(progressListener); task.run(); assertEquals("failInstantlyTask", task.getDescription()); verify(progressListener).onStart(); verify(listener).onFailure(any(TaskResult.class)); // cleanup() called verify(progressListener).onProgress(1, 1); verify(progressListener).onEnd(); verifyNoMoreInteractions(listener, progressListener); } @Test public void taskCanBeInterruptedWhenSubmittedToExecutorService() throws InterruptedException { final Task task = new NeverFinishTask(listener); task.addProgressListener(progressListener); final Future<?> job = Executors.newFixedThreadPool(1).submit(task); Thread.sleep(500); job.cancel(true); Thread.sleep(500); assertEquals("neverFinishTask", task.getDescription()); verify(progressListener).onStart(); verify(listener).onInterrupt(any(TaskResult.class)); verify(progressListener).onEnd(); verifyNoMoreInteractions(listener); } @Test public void canSetMultipleProgressListenersAndRemoveThem() throws InterruptedException, ExecutionException { final Task task = new AbstractTask<Object>(null, mock(TaskListener.class)) { @Override protected Object work() throws InterruptedException, TaskFailureException { setProgress(1, 1); return null; } @Override protected void cleanUp() { } }; final TaskProgressListener progressListener1 = mock(TaskProgressListener.class); final TaskProgressListener progressListener2 = mock(TaskProgressListener.class); final TaskProgressListener progressListener3 = mock(TaskProgressListener.class); task.addProgressListener(progressListener1); task.addProgressListener(progressListener2); task.addProgressListener(progressListener3); task.removeProgressListener(progressListener2); Executors.newSingleThreadExecutor().submit(task).get(); verify(progressListener1, times(1)).onStart(); verify(progressListener2, times(0)).onStart(); verify(progressListener3, times(1)).onStart(); } }
true
ad33271a3dbdd92ccee1f07ef6944fd7a8b7e601
Java
alexandrofernando/java
/topcoder/SkiResortsEasy.java
UTF-8
277
2.828125
3
[]
no_license
public class SkiResortsEasy { public int minCost(int[] altitude) { int cost = 0; for (int i = 1; i < altitude.length; i++) { if (altitude[i] > altitude[i - 1]) { cost += altitude[i] - altitude[i - 1]; altitude[i] = altitude[i - 1]; } } return cost; } }
true
5f848a26fb10e64fb4b7155cc37360fdf021355c
Java
ramilmsh-archive/cs308_slogo
/src/controller/channel/messages/LanguageChange.java
UTF-8
321
2.453125
2
[ "MIT" ]
permissive
package controller.channel.messages; public class LanguageChange extends Message{ public String language; /** * Create a new message * * @param language: type of language of commands to be interpreted */ public LanguageChange(String language) { this.language = language; } }
true
ea19c20172771153c07707f4068de7e2ef2965f3
Java
gustavjon/slingerORM
/android/src/main/java/net/daverix/slingerorm/android/internal/InsertableContentValues.java
UTF-8
1,864
2.15625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2014 David Laurell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.daverix.slingerorm.android.internal; import android.content.ContentValues; import net.daverix.slingerorm.mapping.InsertableValues; public class InsertableContentValues implements InsertableValues { private final ContentValues mValues = new ContentValues(); @Override public void put(String fieldName, byte[] value) { mValues.put(fieldName, value); } @Override public void put(String fieldName, String value) { mValues.put(fieldName, value); } @Override public void put(String fieldName, double value) { mValues.put(fieldName, value); } @Override public void put(String fieldName, float value) { mValues.put(fieldName, value); } @Override public void put(String fieldName, int value) { mValues.put(fieldName, value); } @Override public void put(String fieldName, boolean value) { mValues.put(fieldName, value); } @Override public void put(String fieldName, short value) { mValues.put(fieldName, value); } @Override public void put(String fieldName, long value) { mValues.put(fieldName, value); } @Override public ContentValues getData() { return mValues; } }
true
31ae323add13cdd69ba3ba0a8d78732257090bd1
Java
RoboCup-Humanoid-TC/GameController
/src/data/hl/HLDropIn5.java
UTF-8
284
2.28125
2
[]
no_license
package data.hl; /** * This class sets attributes given by the humanoid-league rules. * * @author Michel-Zen */ public class HLDropIn5 extends HLDropIn { public HLDropIn5() { leagueName = "HL Drop In (5)"; robotsPlaying = 5; teamSize = 5; } }
true
c7af539c24b173517b735656f5536c9a5b6b2b37
Java
benjaminhuanghuang/ben-leetcode
/0854_K-Similar_Strings/solution.java
UTF-8
1,907
3.703125
4
[]
no_license
package cn.huang.leetcode; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Set; /* 854. K-Similar Strings Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B. Given two anagrams A and B, return the smallest K for which A and B are K-similar. Example 1: Input: A = "ab", B = "ba" Output: 1 Example 2: Input: A = "abc", B = "bca" Output: 2 Example 3: Input: A = "abac", B = "baca" Output: 2 Example 4: Input: A = "aabc", B = "abca" Output: 2 Note: 1 <= A.length == B.length <= 20 A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'} */ public class LC_0854_KSimilarStrings { /* https://leetcode.com/problems/k-similar-strings/discuss/140099/JAVA-BFS-32-ms-cleanconciseexplanationwhatever */ public int kSimilarity(String A, String B) { if (A.equals(B)) return 0; Set<String> vis= new HashSet<>(); Queue<String> q= new LinkedList<>(); q.add(A); vis.add(A); int res=0; while(!q.isEmpty()){ res++; for (int sz=q.size(); sz>0; sz--){ String s= q.poll(); int i=0; while (s.charAt(i)==B.charAt(i)) i++; for (int j=i+1; j<s.length(); j++){ if (s.charAt(j)==B.charAt(j) || s.charAt(i)!=B.charAt(j) ) continue; String temp= swap(s, i, j); if (temp.equals(B)) return res; if (vis.add(temp)) q.add(temp); } } } return res; } public String swap(String s, int i, int j){ char[] ca=s.toCharArray(); char temp=ca[i]; ca[i]=ca[j]; ca[j]=temp; return new String(ca); } }
true
8369123f50939ee012b3a6a034edd5c307c6a78d
Java
NagamaniVellore/CollobrationProject
/cde/src/main/java/com/niit/cde/DAO/FriendDAO.java
UTF-8
549
1.992188
2
[]
no_license
package com.niit.cde.DAO; import java.util.List; import com.niit.cde.Model.Friend; public interface FriendDAO { public boolean add(Friend friend); public boolean update(Friend friend); public boolean delete(String username, String friendId); public void setOnline(String username); public void setOffline(String username); public List<Friend> getMyFriend(String username); public List<Friend> getFriendRequestSentByMe(String username); public List<Friend> getNewFriendRequest(String friendId); }
true
9af65d51396392de9de9d641c48b5518571c4e57
Java
PabloSorrentino/QMP
/src/test/java/TipoPrendaTest.java
UTF-8
3,565
2.609375
3
[]
no_license
import org.junit.jupiter.api.Test; import quemepongo.clases.Atuendo; import quemepongo.clases.Borrador; import quemepongo.clases.Prenda; import quemepongo.enums.Material; import quemepongo.enums.TipoPrenda; import quemepongo.enums.TramaPrenda; import quemepongo.excepciones.CategoriaNoSeCondiceConElTipoException; import quemepongo.enums.CategoriaPrenda; import quemepongo.excepciones.FaltanDefinirAspectosException; import static org.junit.jupiter.api.Assertions.*; public class TipoPrendaTest { @Test public void unaRemeraNoEsUnCalzado() { assertThrows(CategoriaNoSeCondiceConElTipoException.class, () ->new Prenda(TipoPrenda.REMERA_MANGA_CORTA, Material.ALGODON, TramaPrenda.ESTAMPADO, CategoriaPrenda.CALZADO, "rojo", null) ); } @Test public void unAnteojoEsUnAccesorio() { quemepongo.clases.Prenda prenda = new Prenda(TipoPrenda.ANTEOJO_SOL, Material.PLASTICO, TramaPrenda.LISA, CategoriaPrenda.ACCESORIO, "negro", null); assertEquals(prenda.getCategoriaPrenda(), CategoriaPrenda.ACCESORIO); } @Test public void unaPolleraDeTelaEsDeTelaYNoEsParteSuperior(){ quemepongo.clases.Prenda prenda = new quemepongo.clases.Prenda(TipoPrenda.POLLERA, Material.TELA, TramaPrenda.RAYADA,CategoriaPrenda.PARTE_INFERIOR,"verde", "amarilla"); assertNotEquals(prenda.getCategoriaPrenda(), CategoriaPrenda.PARTE_SUPERIOR); assertEquals(prenda.getMaterial().name(), "TELA"); } @Test public void unaMochilaNoEsUnaPrendaSuperior() { assertThrows(CategoriaNoSeCondiceConElTipoException.class, () ->new quemepongo.clases.Prenda(TipoPrenda.MOCHILA, Material.KEVLAR, null,CategoriaPrenda.PARTE_SUPERIOR,"rojo", "negro") ); } @Test public void unaMochilaEsUnAccesorioDeColorRojoYNegro() { quemepongo.clases.Prenda prenda = new quemepongo.clases.Prenda(TipoPrenda.MOCHILA, Material.KEVLAR, null,CategoriaPrenda.ACCESORIO,"rojo", "negro"); assertEquals(prenda.getColorPrimario(), "rojo"); assertEquals(prenda.getColorSecundario(), "negro"); } @Test public void unAtuendoTieneCuatroPrendas() { Atuendo atuendo = new Atuendo(); atuendo.agregarPrenda(new Prenda(TipoPrenda.ANTEOJO_SOL, Material.PLASTICO, TramaPrenda.LISA, CategoriaPrenda.ACCESORIO, "negro", null)); atuendo.agregarPrenda(new Prenda(TipoPrenda.REMERA_MANGA_CORTA, Material.ALGODON, TramaPrenda.ESTAMPADO, CategoriaPrenda.PARTE_SUPERIOR, "rojo", null)); atuendo.agregarPrenda(new Prenda(TipoPrenda.PANTALON, Material.JEAN, null,CategoriaPrenda.PARTE_INFERIOR,"azul", null)); atuendo.agregarPrenda(new Prenda(TipoPrenda.ZAPATILLA, Material.TELA, TramaPrenda.RAYADA, CategoriaPrenda.CALZADO,"negro", "blanco")); assertEquals(atuendo.getPrendas().size(), 4); } @Test public void unBorradorDeUnaCamisaSinTipoTiraException() { Borrador borrador = new Borrador(); borrador.setCategoriaPrenda(CategoriaPrenda.PARTE_SUPERIOR); borrador.setColorPrimario("azul"); borrador.setTrama(TramaPrenda.LISA); borrador.setMaterial(Material.TELA); assertThrows(FaltanDefinirAspectosException.class, () -> borrador.crearPrenda() ); } @Test public void porDefectoLaTramaEsLisa() { assertEquals(new Prenda(TipoPrenda.ANTEOJO_SOL, Material.PLASTICO, null, CategoriaPrenda.ACCESORIO, "negro", null).getTrama(), TramaPrenda.LISA); } }
true
075af8faf76199e3dcd5c50b3ebd602d103da68d
Java
sunshiqiang/git-msc
/msc-web-medic/src/main/java/com/shyl/msc/home/controller/HomeController.java
UTF-8
4,808
2.015625
2
[]
no_license
package com.shyl.msc.home.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.RequestMapping; import com.shyl.common.entity.PageRequest; import com.shyl.common.entity.Sort; import com.shyl.common.entity.Sort.Direction; import com.shyl.common.framework.annotation.CurrentUser; import com.shyl.common.web.controller.BaseController; import com.shyl.msc.dm.service.IProductService; import com.shyl.sys.entity.AttributeItem; import com.shyl.msc.set.entity.Notice; import com.shyl.sys.service.IAttributeItemService; import com.shyl.msc.set.service.ICompanyService; import com.shyl.msc.set.service.IHospitalService; import com.shyl.msc.set.service.INoticeService; import com.shyl.sys.entity.FileManagement; import com.shyl.sys.entity.User; import com.shyl.sys.service.IFileManagementService; /** * 首页Controller * * @author a_Q * */ @Controller @RequestMapping("/home") public class HomeController extends BaseController { @Resource private IHospitalService hospitalService; @Resource private INoticeService noticeService; @Resource private IProductService productService; @Resource private ICompanyService companyService; @Resource private IFileManagementService fileManagementService; @Resource private IAttributeItemService attributeItemService; @Override protected void init(WebDataBinder binder) { } /** * * @return */ @RequestMapping("") public String home(@CurrentUser User user){ if(user.getOrganization().getOrgType() != null &&user.getOrganization().getOrgType()== 9) return "sys/user/sql"; return "home/homeForY"; } /** * 系统消息 * @return */ @RequestMapping("/msg") public String msg(){ return "home/msg"; } /** * 公告 * @return */ @RequestMapping("/notice") public String notice(Model model, @CurrentUser User user){ Sort sort = new Sort(Direction.DESC,"publishDate"); PageRequest pageable = new PageRequest(); Map<String, Object> query = new HashMap<String, Object>(); query.put("t#status_I_EQ", 1); pageable.setQuery(query); pageable.setSort(sort); List<Notice> list = noticeService.list(user.getProjectCode(), pageable); for (Notice notice : list) { List<FileManagement> l =fileManagementService.findByKeyFlag(user.getProjectCode(), "notice_"+notice.getId()); if(l == null || l.size() == 0){ notice.setFileManagement(null); } } while(list.size()>5){ list.remove(5); } model.addAttribute("noticeList", list); return "home/notice"; } /** * 公告详情 * @return */ @RequestMapping("/notice/sub") public String noticeSub(Long id,Model model, @CurrentUser User user){ System.out.println("id="+id); Notice notice = noticeService.getById(user.getProjectCode(), id); List<FileManagement> l =fileManagementService.findByKeyFlag(user.getProjectCode(), "notice_"+notice.getId()); for (FileManagement fileManagement : l) { notice.getFileManagement().add(fileManagement); } if(notice.getFileManagement().size() == 0){ notice.setFileManagement(null); } model.addAttribute("notice", notice) ; return "home/noticeSub"; } /** * 监管者 基本信息统计 * @return */ @RequestMapping("/monitorTotal") public String monitorTotal(Model model,@CurrentUser User user){ Map<String , Object> productMap = productService.count(user.getProjectCode()); Map<String, Object> hospitalMap = hospitalService.count(user.getProjectCode()); Map<String, Object> producerMap = companyService.count(user.getProjectCode(), "isProducer=1"); Map<String, Object> vendorMap = companyService.count(user.getProjectCode(), "isVendor=1"); model.addAttribute("productCount", productMap.get("COUNT")); model.addAttribute("hospitalCount", hospitalMap.get("COUNT")); model.addAttribute("producerCount", producerMap.get("COUNT")); model.addAttribute("vendorCount", vendorMap.get("COUNT")); return "home/monitorTotal"; } /** * index * @return */ @RequestMapping("/index") public String index(@CurrentUser User user,Model model){ AttributeItem attributeItem = attributeItemService.queryByAttrAndItemNo(user.getProjectCode(),"publicUser", "B2B_HOMETITLE"); if(attributeItem != null){ model.addAttribute("hometitle", attributeItem.getField3()); } AttributeItem logo = attributeItemService.queryByAttrAndItemNo("", "LOGININFO", "LOGO"); if(logo != null){ model.addAttribute("logo", logo.getField3()); } return "index"; } /** * center * @return */ @RequestMapping("/center") public String center(@CurrentUser User user,Model model){ return "center"; } }
true
4c03376fa40580ced32ee238bb56d4d1691a3a7c
Java
rakter1/Eclipse-Code
/TestNgProject/src/test/java/com/ui/ListenerDemoTest.java
UTF-8
287
1.554688
2
[]
no_license
package com.ui; import org.testng.Assert; import org.testng.annotations.Test; public class ListenerDemoTest extends BaseTest{ @Test(retryAnalyzer =Retry.class) public void launchApp() { driver.get("https://www.ebay.com/"); Assert.assertTrue(false); Assert.fail(); } }
true
8f257abff47424eba88f24da7bce21b7e25e91da
Java
bellmit/jxhk
/src/main/java/com/usky/sms/field/FieldLayoutItemDO.java
UTF-8
1,879
2.140625
2
[]
no_license
package com.usky.sms.field; import org.hibernate.cfg.Comment; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.usky.sms.core.AbstractBaseDO; @Entity @Table(name = "T_FIELD_LAYOUT_ITEM") @Comment("字段配置明细") public class FieldLayoutItemDO extends AbstractBaseDO { private static final long serialVersionUID = 2143369486195545369L; /** 字段布局 */ private FieldLayoutDO layout; /** 是否隐藏 */ private Boolean hidden; /** 是否必填 */ private Boolean required; /** 渲染器 */ private String renderer; /** ID */ private String key; /** 描述 */ private String description; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "LAYOUT_ID") @Comment("字段布局") public FieldLayoutDO getLayout() { return layout; } public void setLayout(FieldLayoutDO layout) { this.layout = layout; } @Column @Comment("是否隐藏") public Boolean getHidden() { return hidden; } public void setHidden(Boolean hidden) { this.hidden = hidden; } @Column @Comment("是否必填") public Boolean getRequired() { return required; } public void setRequired(Boolean required) { this.required = required; } @Column(length = 50) @Comment("渲染器") public String getRenderer() { return renderer; } public void setRenderer(String renderer) { this.renderer = renderer; } @Column(name = "`key`", length = 50) @Comment("ID") public String getKey() { return key; } public void setKey(String key) { this.key = key; } @Column(length = 255) @Comment("描述") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
true
bc45ecf85c09e24f3ec343eb99959da76bc7b935
Java
finnflyer/CaseDB
/src/main/java/com/demo/service/testcase/TestCaseService.java
UTF-8
1,414
1.601563
2
[]
no_license
package com.demo.service.testcase; import com.demo.model.testcase.*; import com.demo.service.BaseService; import java.util.List; import java.util.Map; /** * Created by Admin on 2016/9/2. */ public interface TestCaseService extends BaseService<TestCase> { Map<Integer, String> findTestCaseBrandAllForMap(); Map<Integer, String> findTestCaseFunctionAllForMap(); Map<Integer, String> findSupportOSAllForMap(); Map<Integer, String> findLanguageAllForMap(); Map<Integer,String> findTestCaseModeAllForMap(); List<LanguagesBean> findLanguageBeanAll(); List<TestCaseHistroy> findTestCaseHistoryAll(); TestCaseInfo findTestCaseInfoByCaseInfoStkey(String key); TestCaseInfo findTestCaseInfoByCaseKey(String key); List<TestCaseContent> findCaseContentByCaseKey(String key); List<CaseLanguage> findCaseLanguageByCaseId(String key); TestCaseInfo findTestCaseInfoByCasekey(String key); List<PictureBean> findPictureByCaseContentkey(String key); void saveTestCaseInfo(TestCaseInfo info); void saveTestCaseContent(TestCaseContent content); void saveCaseLanMap(List<CaseLanguage> caseLan); void savePictureBean(PictureBean pb); void updateTestCaseInfo(TestCaseInfo info); void updateCaseLanguage(CaseLanguage temp); void updateCaseContent(TestCaseContent content); void saveTestcaseHistory(TestCaseHistroy caseHistroy); }
true
e68de66db8d14240422028d670b769556f379999
Java
bonedragon1/TTMS-SSM
/src/xupt/se/ttms/controller/EmployeeController.java
UTF-8
4,925
2.578125
3
[]
no_license
package xupt.se.ttms.controller; import java.net.URLEncoder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView; import xupt.se.ttms.domain.Employee; import xupt.se.ttms.service.EmployeeService; import xupt.se.ttms.util.PageParams; /** * 处理登陆用户请求控制器 * @author zhangrong */ @Controller public class EmployeeController { // 自动注入EmployeeService @Autowired @Qualifier("employeeService") private EmployeeService employeeService; // 处理/employee/link请求,打开员工模块首页 @RequestMapping(value="/employee/link") public String link() { return "/employee/index"; } // 处理/employee/searchByPage请求,处理分页请求 // 如果删除数据,也会调用此方法再次查询,这里会显示delResult删除结果(此参数查询时不用,所以这里设置非必须提供) @RequestMapping(value="/employee/searchByPage") public ModelAndView searchByPage(String employeeName, int currentPage, ModelAndView mv, @RequestParam(required=false) String delResult) { // System.out.println("employeeName=" + employeeName + " ; currentPage" + currentPage); // 由findEmployeePageByName方法将分页信息写进去 PageParams params=new PageParams(); mv.addObject("allEmployee", employeeService.findEmployeePageByName(employeeName, currentPage, params)); mv.addObject("currentPage", params.getCurrentPage()); mv.addObject("allCount", params.getAllCount()); mv.addObject("allPageCount", params.getAllPageCount()); mv.addObject("searchEmployeeName", employeeName); mv.addObject("delResult", delResult); mv.setViewName("/employee/index"); return mv; } // 处理/employee/openAdd请求,打开增加员工页面 @RequestMapping(value="/employee/openAdd") public String openAdd() { return "/employee/add"; } // 处理/employee/save请求,增加员工信息 @SuppressWarnings("finally") @RequestMapping(value="/employee/save") public ModelAndView save(Employee employee, ModelAndView mv) { try { employeeService.insert(employee); mv.addObject("message", "添加成功,请继续添加!"); } catch(Exception e) { mv.addObject("message", "添加失败,用户编号已存在或数据格式有误!"); } finally { mv.setViewName("/employee/add"); return mv; } } // 处理/employee/openUpdate请求,打开更新员工页面 @RequestMapping(value="/employee/openUpdate") public ModelAndView openUpdate(int empId, ModelAndView mv) { Employee employee=employeeService.findEmployeeById(empId); mv.addObject("employee", employee); mv.setViewName("/employee/update"); return mv; } // 处理/employee/update请求,更新员工信息 @SuppressWarnings("finally") @RequestMapping(value="/employee/update") public ModelAndView update(Employee employee, ModelAndView mv) { // System.out.println(employee.toString()); try { employeeService.update(employee); mv.addObject("message", "更新成功!"); } catch(Exception e) { mv.addObject("message", "更新失败,用户编号已存在或数据格式有误!"); } finally { mv.addObject("employee", employee); mv.setViewName("/employee/update"); return mv; } } // 处理/employee/delete请求,删除员工信息 @SuppressWarnings("finally") @RequestMapping(value="/employee/delete") public ModelAndView delete(int empId, String employeeName, int currentPage, ModelAndView mv) { // System.out.println(empId + " " + employeeName + " " + currentPage); String delResult=""; try { employeeService.delete(empId); delResult=URLEncoder.encode("删除成功!", "utf-8"); } catch(Exception e) { delResult=URLEncoder.encode("删除失败,此用户为登录用户!", "utf-8"); } finally { String url="../employee/searchByPage?employeeName=" + employeeName + "&currentPage=" + currentPage + "&delResult=" + delResult; mv.setView(new RedirectView(url)); return mv; } } }
true
6f45a70ff1be9cfbd6a7eab66a5ac1594c9fe3e7
Java
pforget/PlanningWeekend
/PlanningWeekend/src/main/java/TAA/Dao/UserDao.java
UTF-8
602
2.078125
2
[]
no_license
package TAA.Dao; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; import TAA.entities.User; import TAA.entities.Location; import TAA.entities.Sport; @Transactional public interface UserDao extends JpaRepository<User, Long>{ @Query(" select u from User u " + " where u.username = ?1") Optional<User> findUserWithName(String username); }
true
9e2e3a1e63c64c0a2890f98a8e9a492aab4daaa5
Java
aliyun/aliyun-openapi-java-sdk
/aliyun-java-sdk-vpc/src/main/java/com/aliyuncs/vpc/model/v20160428/GetVpcPrefixListEntriesResponse.java
UTF-8
2,907
1.882813
2
[ "Apache-2.0" ]
permissive
/* * 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.aliyuncs.vpc.model.v20160428; import java.util.List; import com.aliyuncs.AcsResponse; import com.aliyuncs.vpc.transform.v20160428.GetVpcPrefixListEntriesResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class GetVpcPrefixListEntriesResponse extends AcsResponse { private String requestId; private String nextToken; private Long totalCount; private Long count; private List<PrefixListCidrs> prefixListEntry; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getNextToken() { return this.nextToken; } public void setNextToken(String nextToken) { this.nextToken = nextToken; } public Long getTotalCount() { return this.totalCount; } public void setTotalCount(Long totalCount) { this.totalCount = totalCount; } public Long getCount() { return this.count; } public void setCount(Long count) { this.count = count; } public List<PrefixListCidrs> getPrefixListEntry() { return this.prefixListEntry; } public void setPrefixListEntry(List<PrefixListCidrs> prefixListEntry) { this.prefixListEntry = prefixListEntry; } public static class PrefixListCidrs { private String prefixListId; private String cidr; private String description; private String regionId; public String getPrefixListId() { return this.prefixListId; } public void setPrefixListId(String prefixListId) { this.prefixListId = prefixListId; } public String getCidr() { return this.cidr; } public void setCidr(String cidr) { this.cidr = cidr; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getRegionId() { return this.regionId; } public void setRegionId(String regionId) { this.regionId = regionId; } } @Override public GetVpcPrefixListEntriesResponse getInstance(UnmarshallerContext context) { return GetVpcPrefixListEntriesResponseUnmarshaller.unmarshall(this, context); } @Override public boolean checkShowJsonItemName() { return false; } }
true
2f3d9d3df8cb188d7c20ff5cbd0eface93175927
Java
elvyn/SMSMailerPrefs
/app/src/main/java/com/example/ankit/SMSMailerPrefs/AddReceiverActivity.java
UTF-8
1,283
2.3125
2
[]
no_license
package com.example.ankit.SMSMailerPrefs; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.EditText; public class AddReceiverActivity extends AppCompatActivity { private static final String DISPLAY_RECEIVER_ADDRESS = SettingsStorage.DISPLAY_RECEIVER_ADDRESS; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_receiver); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } public void saveDetails() { EditText text = (EditText)findViewById(R.id.receiver_email); String email_address = text.getText().toString(); if (!(email_address.equals(DISPLAY_RECEIVER_ADDRESS) || email_address.equals(""))) { (new SettingsStorage(getApplicationContext())).addReceivers(email_address); } /* Reset the text value to default address */ text.setText(""); text.setHint(DISPLAY_RECEIVER_ADDRESS); } public void saveDetails(View a) { saveDetails(); } }
true
ff8f94446b61fba2470aa06bff42019123e0c18b
Java
mario10-7/RuneSpire-2D
/Game Client/src/com/daybreak/Quests/QuestObjective.java
UTF-8
380
2.453125
2
[]
no_license
package com.daybreak.Quests; public class QuestObjective { int ID; String type; String text; public QuestObjective(int ID,String type) { this.ID = ID; this.type = type; } public void complete(){} public boolean checkConditions() { return false; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
true
f540538d264c585eb9b79d95e4e92bb61856f865
Java
ssriha0/sl-b2b-platform
/OMSStaging/src/main/java/com/newco/marketplace/webservices/dao/ShcUpsellPayment.java
UTF-8
1,606
2.140625
2
[]
no_license
package com.newco.marketplace.webservices.dao; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.UniqueConstraint; /** * ShcUpsellPayment entity. * * @author MyEclipse Persistence Tools */ @Entity @Table(name = "shc_upsell_payment", uniqueConstraints = { @UniqueConstraint(columnNames = { "shc_order_id" }) }) public class ShcUpsellPayment extends AbstractShcUpsellPayment implements java.io.Serializable { // Constructors /** * */ private static final long serialVersionUID = 1L; /** default constructor */ public ShcUpsellPayment() { // intentionally blank } /** minimal constructor */ public ShcUpsellPayment(Integer shcUpsellPaymentId, String paymentMethodInd, String paymentAccNo) { super(shcUpsellPaymentId, paymentMethodInd, paymentAccNo); } /** full constructor */ public ShcUpsellPayment(Integer shcUpsellPaymentId, ShcOrder shcOrder, String paymentMethodInd, String paymentAccNo, String paymentExpDate, String authNo, String secPaymentMethodInd, String secPaymentAccNo, String secPaymentExpDate, String secAuthNo, Double amountCollected, Double priAmountCollected, Double secAmountCollected, Date createdDate, Date modifiedDate, String modifiedBy) { super(shcUpsellPaymentId, shcOrder, paymentMethodInd, paymentAccNo, paymentExpDate, authNo, secPaymentMethodInd, secPaymentAccNo, secPaymentExpDate, secAuthNo, amountCollected, priAmountCollected, secAmountCollected, createdDate, modifiedDate, modifiedBy); } }
true
ecdc668880c56719f860b3a7740ac7a26c830524
Java
wil0w/Cheat-Pack-2
/com/kodehawa/event/events/EventRender3D.java
UTF-8
256
1.75
2
[]
no_license
package com.kodehawa.event.events; import com.kodehawa.event.Event; /** * Used for non-ortho renders * * @author godshawk * */ public class EventRender3D extends Event { public EventRender3D( Object source ) { super( source ); } }
true
de6d9e574175c8ad6cc44750b77005337610bb23
Java
jldaren/urgent-project
/modules.middleware/middleware-workflow/workflow-webapp-wicket/src/main/java/com/daren/workflow/webapp/wicket/page/EntInformationPage.java
UTF-8
6,403
1.953125
2
[]
no_license
package com.daren.workflow.webapp.wicket.page; import com.daren.core.util.DateUtil; import com.daren.core.web.component.navigator.CustomerPagingNavigator; import com.daren.enterprise.api.biz.IEnterpriseBeanService; import com.daren.enterprise.entities.EnterpriseBean; import com.googlecode.wicket.jquery.core.Options; import com.googlecode.wicket.jquery.ui.form.button.AjaxButton; import com.googlecode.wicket.jquery.ui.panel.JQueryFeedbackPanel; import com.googlecode.wicket.jquery.ui.widget.tabs.TabbedPanel; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.tabs.AbstractTab; import org.apache.wicket.extensions.markup.html.tabs.ITab; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.panel.Fragment; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.RepeatingView; import org.apache.wicket.markup.repeater.data.DataView; import org.apache.wicket.markup.repeater.data.ListDataProvider; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.Model; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; /** * @类描述:企业信息查询 * @创建人: 张清欣 * @创建时间:2015/1/7 * @修改人: * @修改时间: * @修改备注: */ public class EntInformationPage extends Panel { private final TabbedPanel tabPanel; private final RepeatingView repeatingView = new RepeatingView("repeatingView"); DataProvider provider = new DataProvider(); private String qymc; //注入服务 @Inject private IEnterpriseBeanService enterpriseBeanService; public EntInformationPage(String id) { super(id); Options options = new Options(); tabPanel = new TabbedPanel("tabs", this.newTabList(), options); this.add(tabPanel); } /** * 添加tabs * @return */ private List<ITab> newTabList() { List<ITab> tabs = new ArrayList<ITab>(); tabs.add(new AbstractTab(Model.of("企业信息查询")) { private static final long serialVersionUID = 1L; @Override public WebMarkupContainer getPanel(String panelId) { return new MainFragment(panelId, "mainPanel"); } }); return tabs; } //列表显示 public class MainFragment extends Fragment { private final JQueryFeedbackPanel feedbackPanel; private final WebMarkupContainer container; public MainFragment(String id, String markupId) { super(id, markupId, EntInformationPage.this); container = new WebMarkupContainer("container"); this.add(container.setOutputMarkupId(true)); //add feedback feedbackPanel = new JQueryFeedbackPanel("feedback"); container.add(feedbackPanel.setOutputMarkupId(true)); //add table final WebMarkupContainer table = new WebMarkupContainer("table"); container.add(table.setOutputMarkupId(true)); //add listview final DataView<EnterpriseBean> listView = new DataView<EnterpriseBean>("rows", provider, 10) { private static final long serialVersionUID = 1L; @Override protected void populateItem(Item<EnterpriseBean> item) { final EnterpriseBean row = item.getModelObject(); item.add(new Label("qymc", row.getQymc())); item.add(new Label("clsj", DateUtil.convertDateToString(row.getClsj(), DateUtil.shortSdf))); item.add(new Label("frdb", row.getFrdb())); item.add(new Label("qylxfs", row.getQylxfs())); item.add(new Label("cyrs", row.getCyrs())); item.add(new Label("addresszc", row.getAddresszc())); item.add(new Label("addressjy", row.getAddressjy())); //add delete button //item.add(initDeleteButton(row)); }; }; table.add(listView); //增加分页指示器 CustomerPagingNavigator pagingNavigator = new CustomerPagingNavigator("navigator", listView) {}; table.add(pagingNavigator); //增加form Form dictForm = new Form("form", new CompoundPropertyModel(EntInformationPage.this)); TextField textField = new TextField("qymc"); textField.setRequired(false); dictForm.add(textField.setOutputMarkupId(true)); //find button dictForm.add(initFindButton(provider, dictForm)); this.add(dictForm); } /** * 初始化查询按钮 * @return */ private AjaxButton initFindButton(final DataProvider provider, Form form) { return new AjaxButton("find", form) { @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { EnterpriseBean dictBean = new EnterpriseBean();// form.getModelObject(); dictBean.setQymc(qymc); provider.setDictBean(dictBean); target.add(container); } @Override protected void onError(AjaxRequestTarget target, Form<?> form) { target.add(feedbackPanel); } }; } } /** * 查询数据提供者 */ class DataProvider extends ListDataProvider<EnterpriseBean> { private EnterpriseBean dictBean = null; public void setDictBean(EnterpriseBean dictBean) { this.dictBean = dictBean; } @Override protected List<EnterpriseBean> getData() { //类型为空时候,返回全部记录 if (dictBean == null || null == dictBean.getQymc()|| "".equals(dictBean.getQymc().trim()) ) return enterpriseBeanService.getAllEntity(); else { return enterpriseBeanService.getEnterpriseByQymc(dictBean.getQymc()); } } } }
true
302c749c5d5c82e8d3da1cb33bf5cfec7c90706b
Java
ghozt777/DSA-Bootcamp-Java-Solutions
/Practice/binarySearchVideo/q2/Main.java
UTF-8
1,432
3.875
4
[]
no_license
// FLOOR OF A NUMBER USING BINARY SEARCH /* This is a program that calculates the largest number in a sorted array that is eihter equal to or smaller than a target number */ import java.util.Scanner; import java.util.Arrays; class Main{ public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter n: "); int n = in.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) arr[i] = in.nextInt(); System.out.println("Enter target: "); int target = in.nextInt(); int floor = findFloor(arr,target); if(floor==-1) System.out.println("There is no floor in the array : "+ Arrays.toString(arr)+" for the target : "+target); else System.out.println("Floor for target: "+target+" in the array: "+Arrays.toString(arr)+" is at index: "+floor+" with a value of :"+arr[floor]); in.close(); } static int findFloor(int[] arr,int target){ // condition where no floor exsists if(arr[0]>target) return -1; int ans = -1; int start = 0; int end = arr.length-1; int mid = 0; while(start<=end){ mid = start + (end-start) / 2; if(arr[mid]<target) start = mid + 1; else if(arr[mid]>target) end = mid - 1; else return mid; } ans = end; return ans; } }
true
9a40c2d07c09e92dcf8a5f9758b620e77cac2e4e
Java
cheunyu/ais_msa_sevices
/src/com/scyb/aisweather/webservice/client/Coastal/ClientTest.java
UTF-8
2,532
2.296875
2
[]
no_license
package com.scyb.aisweather.webservice.client.Coastal; import com.scyb.aisweather.webservice.bo.*; import com.scyb.aisweather.webservice.client.WsClinetAuthHandler; import org.apache.cxf.binding.soap.interceptor.SoapInterceptor; import org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor; import org.apache.ws.security.WSConstants; import org.apache.ws.security.handler.WSHandlerConstants; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.util.*; /** * Created by foo on 2015/4/9. */ public class ClientTest { public static void main(String[] args) throws Exception{ Map<String, Object> outProps = new HashMap<String, Object>(); outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN); outProps.put(WSHandlerConstants.USER, "admin"); outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT); outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, WsClinetAuthHandler.class.getName()); ArrayList<SoapInterceptor> list = new ArrayList<SoapInterceptor>(); list.add(new SAAJOutInterceptor()); list.add(new WSS4JOutInterceptor(outProps)); JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(ICoastalService.class); factory.setAddress(""); factory.getOutInterceptors().addAll(list); ICoastalService coastalService = (ICoastalService) factory.create(); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date()); XMLGregorianCalendar gc = null; try { gc = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal); } catch (Exception e) { e.printStackTrace(); } List<Coastal> coastalList = coastalService.coastalService(gc); for(int i=0;i<coastalList.size();i++) { System.out.println(coastalList.get(i).toString()); } // JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance(); // org.apache.cxf.endpoint.Client client = dcf.createClient("http://localhost:8080/services/hwf?wsdl"); // HydrologyWeatherForecastBo hwfBo = new HydrologyWeatherForecastBo(); // hwfBo. // Object[] objects=client.invoke("hwfBroadcastService", "张三"); // //输出调用结果 // System.out.println(objects[0].toString()); } }
true
4fd5763a23ebc4b7bfaf0e025ef8e39f4640a177
Java
BioinformatikGoettingen/TFClass
/src/main/java/de/sybig/tfclass/OntologyClassConverter.java
UTF-8
2,407
2.546875
3
[]
no_license
package de.sybig.tfclass; import de.sybig.oba.client.OboClass; import de.sybig.oba.client.OboConnector; import java.util.HashMap; import java.util.Map; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Converts an ontology class to a string and back again. As unique identifier * of an ontology class its name, without the name space, is chosen. The * converted objects are stored in a static map to retrieve the ontology class * for a key. If the user does not select an option from the suggestion list, * but type the name, the value of the input field is submitted to this * converter and not the the value of the option of the list. Therefor the * labels of the ontology classes are also stored as keys. * * @author juergen.doenitz@bioinf.med.uni-goettingen.de */ @FacesConverter(value = "ontologyClassConverter") public class OntologyClassConverter implements Converter { private static volatile Map<String, Object> cache; private static Logger log = LoggerFactory .getLogger(OntologyClassConverter.class); private HashMap<String, Object> labelCache; public OntologyClassConverter() { super(); } @Override public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) { log.trace("request conversion for {} from {}", submittedValue, getCache().size()); if (submittedValue == null || submittedValue.trim().equals("")) { return null; } else { if (getCache().containsKey(submittedValue)) { return getCache().get(submittedValue); } log.warn( "Could not convert string '{}' back to object, string not found in map {}", submittedValue, getCache().size()); return null; } } @Override public String getAsString(FacesContext facesContext, UIComponent component, Object value) { log.debug("converting String '{}' to class ", value); if (value == null || value.equals("")) { return ""; } else { String name = ((OboClass) value).getName(); getCache().put(name, value); getCache().put(((OboClass) value).getLabel(), value); return name; } } private Map<String, Object> getCache() { if (cache == null) { cache = new HashMap<String, Object>(); } return cache; } }
true
02f957171822a9c579b94c1ee2f5a278adf18c95
Java
bzsol/Tobacco-Shop-SFM
/SFM/src/main/java/hu/sfm/utils/JPAProductDAO.java
UTF-8
1,024
2.546875
3
[]
no_license
package hu.sfm.utils; import hu.sfm.entity.Product; import javax.persistence.TypedQuery; import java.util.List; public class JPAProductDAO implements ProductDAO{ @Override public void saveProduct(Product p) { entityManager.getTransaction().begin(); entityManager.persist(p); entityManager.getTransaction().commit(); } @Override public void deleteProduct(Product p) { entityManager.getTransaction().begin(); entityManager.remove(p); entityManager.getTransaction().commit(); } @Override public void updateProduct(Product p) { saveProduct(p); } @Override public List<Product> getProducts() { TypedQuery<Product> query = entityManager.createQuery("SELECT p FROM Product p", Product.class); List<Product> product = query.getResultList(); return product; } @Override public void close() throws Exception { entityManager.close(); entityManagerFactory.close(); } }
true
d4179ad2ca121aa4aec6f43f3b91e1d2220768c1
Java
Emermv/centinela
/app/src/main/java/com/centinela/service/AlertService.java
UTF-8
6,095
2.078125
2
[]
no_license
package com.centinela.service; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.Image; import android.net.Uri; import android.os.Build; import android.support.annotation.NonNull; import android.util.Log; import android.widget.Toast; import com.centinela.model.Alert; import com.centinela.model.Evidences; import com.google.android.gms.tasks.Continuation; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.nio.ByteBuffer; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; public class AlertService { public void save(final ArrayList<File> evidence_list, final Context context, String description) throws FileNotFoundException { SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_MULTI_PROCESS); final Alert alert =new Alert(); final ProgressDialog dialog = ProgressDialog.show(context, "", "Enviando alerta... espere un momento", true); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); Date date = new Date(); alert.setCreation_date(dateFormat.format(date)); alert.setCreation_time(timeFormat.format(date)); alert.setDevice_name(getDeviceName()); alert.setDevice_version(Build.VERSION.CODENAME); alert.setUser_id(prefs.getString("user","0")); alert.setUser_avatar( prefs.getString( "avatar","" ) ); alert.setUser_name( prefs.getString( "name","" ) ); alert.setDescription(description); alert.setLat("3838833"); alert.setLng("93873"); alert.setDirection("Av Alameda San Marcos, Distrito de Chorrillos Lima Perú"); alert.setShow( false ); alert.setState( false ); alert.setEvidences_size( evidence_list.size() ); final ArrayList<Evidences> evidences1=new ArrayList<>(); final DatabaseReference mDatabase= FirebaseDatabase.getInstance().getReference("/alerts"); String key=mDatabase.push().getKey(); alert.setId(key); FirebaseStorage storage = FirebaseStorage.getInstance(); final StorageReference reference=storage.getReference().child("alerts/"+alert.getId()+".png"); for (int i=0;i<evidence_list.size();i++){ Bitmap bitmap = BitmapFactory.decodeFile(evidence_list.get(i).getAbsolutePath()); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 30, stream); byte[] byteArray = stream.toByteArray(); bitmap.recycle(); /* File file = new File("/temp/abc.txt"); //init array with file length byte[] bytesArray = new byte[(int) file.length()]; FileInputStream fis = new FileInputStream(file); fis.read(bytesArray); //read file into bytes[] fis.close(); */ UploadTask uploadTask = reference.putBytes(byteArray); final int j=i; Task<Uri> uriTask=uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() { @Override public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception { dialog.dismiss(); if (!task.isSuccessful()) { throw task.getException(); } // Continue with the task to get the download URL return reference.getDownloadUrl(); } }).addOnCompleteListener(new OnCompleteListener<Uri>() { @Override public void onComplete(@NonNull Task<Uri> task) { if (task.isSuccessful()) { Uri downloadUri = task.getResult(); Evidences e=new Evidences(); e.setPath(downloadUri.toString()); e.setTitle("evidencia 1"); evidences1.add(e); if(j==evidence_list.size()-1){ mDatabase.child(alert.getId()).setValue(alert); for (int k=0;k<evidences1.size();k++){ String file_key=mDatabase.child(alert.getId()).child("evidences").push().getKey(); mDatabase.child(alert.getId()).child("evidences").child(file_key).setValue(evidences1.get(k)); } dialog.dismiss(); Toast.makeText(context,"Alerta enviada correctamente!", Toast.LENGTH_LONG).show(); } } else { Log.d("FIREBASE","Error al subir el archivo"); } } }); } } public String getDeviceName() { String manufacturer = Build.MANUFACTURER; String model = Build.MODEL; if (model.startsWith(manufacturer)) { return capitalize(model); } else { return capitalize(manufacturer) + " " + model; } } private String capitalize(String s) { if (s == null || s.length() == 0) { return ""; } char first = s.charAt(0); if (Character.isUpperCase(first)) { return s; } else { return Character.toUpperCase(first) + s.substring(1); } } }
true
f3ac5ce9537fad188d4799d8d5fb01bf23279b37
Java
gergoterek/BloodStream
/src/main/java/com/elte/BloodStream/service/NewsService.java
UTF-8
2,192
2.203125
2
[]
no_license
package com.elte.BloodStream.service; import com.elte.BloodStream.model.Faq; import com.elte.BloodStream.model.News; import com.elte.BloodStream.repository.NewsRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; import java.util.Optional; @Service public class NewsService { @Autowired NewsRepository newsRepository; //USER - ADMIN - /news/all public Iterable<News> getAllNews() { return newsRepository.findAll(); } //NURSE - /news/create public ResponseEntity<News> createNews(News news) { News createNews = new News(); createNews.setTitle(news.getTitle()); createNews.setText(news.getText()); createNews.setPublishDate(news.getPublishDate()); return ResponseEntity.ok(newsRepository.save(news)); } //NURSE - news/delete/{id} public ResponseEntity<News> deleteNews(Integer newsID) { try { newsRepository.deleteById(newsID); return ResponseEntity.ok().build(); } catch (Exception e) { return ResponseEntity.notFound().build(); } } //NURSE - /news/modify public ResponseEntity<News> modifyNews(News news, Integer newsID){ Optional<News> oldNews = newsRepository.findByNewsId(newsID); if (oldNews.isPresent()) { News createdNews = oldNews.get(); createdNews.setTitle(news.getTitle()); createdNews.setText(news.getText()); createdNews.setPublishDate(news.getPublishDate()); return ResponseEntity.ok(newsRepository.save(createdNews)); } else { return ResponseEntity.notFound().build(); } } //NURSE - faq/{id} public ResponseEntity<News> getNews(Integer id) { Optional<News> foundNews = newsRepository.findByNewsId(id); if (foundNews.isPresent()){ return ResponseEntity.ok(foundNews.get()); } else{ return ResponseEntity.badRequest().build(); } } }
true
24da4e3238373509bd1b28cce6de21b77238a221
Java
KaterynaSymonova/TestAutomationWebDriver
/src/test/java/com/epam/testwebdriver/TestSignature.java
UTF-8
973
2.265625
2
[]
no_license
package com.epam.testwebdriver; import com.epam.step.Steps; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; /** * Created by Kateryna_Symonova on 10/19/2015. */ public class TestSignature { private Steps steps; private final String login = "testautomationuser1"; private final String password = "kf,fhfnjhbz"; private final String SIGNATURE = "Best regards"; @BeforeTest public void singIn () { steps = new Steps(); steps.loginUser(login, password); } @Test public void testSignature () { steps.clickSettings(); steps.goToSignaturePage(); steps.setSignature(SIGNATURE); steps.saveSignature(); steps.clickNewMessage(); Assert.assertEquals(steps.checkSignature(SIGNATURE), true); } @AfterTest public void closeDriver() { steps.closeDriver(); } }
true
9aecf32572d30a4288720bb96ae8bdfc63fbe30f
Java
GuoGuiRong/OOAD
/behavior_model/src/observer/MySubjectImpl.java
UTF-8
412
2.515625
3
[]
no_license
package observer; /** * Created by GuiRunning on 2017/12/1. */ public class MySubjectImpl extends MySubject { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public MySubjectImpl(){ super(); } public MySubjectImpl(String name){ super(); this.name = name; } }
true
b14f9a898aa4ab9782a39b8e74f46c1e85f86083
Java
wtan02/LeetCode
/src/binarytree/maxDepth/maxDepth.java
UTF-8
129
2.046875
2
[]
no_license
package binarytree.maxDepth; import binarytree.TreeNode; public interface maxDepth { int maxDepth(TreeNode root); }
true
db096859458f43e0349249a72bbdee6e79be24a8
Java
marnikitta/sandbox
/internship/logic-parser/src/main/java/org/stepik/marshalkin/Literal.java
UTF-8
397
2.4375
2
[]
no_license
package org.stepik.marshalkin; public enum Literal implements Primary { TRUE { @Override public Primary negated() { return Literal.FALSE; } }, FALSE { @Override public Primary negated() { return Literal.TRUE; } }; @Override public OrExpression<AndExpression<Primary>> normalized() { return new OrExpression<>(new AndExpression<>(this)); } }
true
1282dffce8347ffc3cd005652bcf819124d2fbae
Java
kimyen/audit-pipeline
/src/main/java/org/sagebionetworks/audit/App.java
UTF-8
642
2.046875
2
[ "MIT" ]
permissive
package org.sagebionetworks.audit; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) { final ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("/database.xml"); context.registerShutdownHook(); ConcreteType concreteType = context.getBean(ConcreteType.class); concreteType.doWork(); CertifiedUser certifiedUser = context.getBean(CertifiedUser.class); certifiedUser.doWork(); context.close(); } }
true
e368f4e7b3b8e5b19dfa1e7a44be49ebf38ba61a
Java
pmkiedrowicz/javabyd3
/src/test/java/com/sda/javabyd3/toki/exg0041/ex07/SqrtThisTableTest.java
UTF-8
965
2.609375
3
[]
no_license
package com.sda.javabyd3.toki.exg0041.ex07; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.util.Arrays; public class SqrtThisTableTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void expectingMaxValue() { JustForInputInt justForInputInt = new JustForInputInt(); SqrtThisTable sqrtThisTable = new SqrtThisTable(); int[] inPut = {22, 56, 82}; double[] doubles = {22, 56, 82}; // double[] outPut = new double[inPut.length]; // for (int i = 0; i < inPut.length; i++) { // outPut[i] = inPut[i]; // } double[] outPut = {4.69, 7.48, 9.06}; Assert.assertEquals("StreamIntTable does not work correctly. Expected '4.69, 7.48, 9.06' but got: " + sqrtThisTable, Arrays.toString(outPut), Arrays.toString(sqrtThisTable.sqrtThis(doubles))); } }
true
d26761a32ff06c4c7fc098267df8988b1dd24787
Java
c2y2/ppp-mysql-web
/src/main/java/com/org/c2y2/base/IService.java
UTF-8
1,510
2.359375
2
[]
no_license
package com.org.c2y2.base; import java.util.List; import java.util.Map; public interface IService<T extends Entity> { /** * description 添加方法 * @return void */ public abstract void insert(T t) throws Exception; /** * description 删除方法 * @return void */ public abstract void delete(T t) throws Exception; /** * description 修改方法 * @return void */ public abstract void update(T t) throws Exception; /** * description 通过id查询方法 * @return 对象 */ public abstract T findById(Integer id) throws Exception; /** * 按条件查询 * @param t T 查询条件 * @return * @throws Exception */ public abstract List<T> find(T t) throws Exception; /** * 按条件分页查询 * @param t T 查询条件 * @return * @throws Exception */ public abstract PageModel<T> findOnPage(T t, PageModel<T> pm) throws Exception; /** * 按条件查询 * @param map Map<String, Object> 查询条件 * @return * @throws Exception */ public abstract List<T> find(Map<String, Object> map) throws Exception; /** * 按条件分页查询 * @param map Map<String, Object> 查询条件 * @return * @throws Exception */ public abstract PageModel<T> findOnPage(Map<String, Object> map, PageModel<T> pm) throws Exception; /** * 获取下一个ID * @return * @throws Exception */ public Integer getNextId() throws Exception; }
true
f969818fbc55b478f981f6bbcfcbe83cce88bcc6
Java
dugaolong/cili
/app/src/main/java/www/dugaolong/com/xianshishigongjiao/ui/IndexActivity.java
UTF-8
5,488
2.21875
2
[]
no_license
package www.dugaolong.com.xianshishigongjiao.ui; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.SearchView; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import www.dugaolong.com.xianshishigongjiao.R; import www.dugaolong.com.xianshishigongjiao.utils.ActivityManager; /** * Created by dugaolong on 17/9/11. */ public class IndexActivity extends AppCompatActivity { private SearchView mSearchView; private ListView mListView; private ArrayAdapter mAdapter; private List<String> listOld = new ArrayList<>(); private List<String> listNew = new ArrayList(); private String str; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.index); // 得到联系人名单的指针 initViews(); listOld.add("战狼2"); listOld.add("维多利亚"); listOld.add("杨幂"); listOld.add("王李丹妮"); listOld.add("郭书瑶"); listOld.add("老炮儿"); listOld.add("服务"); listOld.add("主播"); listOld.add("avi"); listOld.add("av"); listNew.addAll(listOld); mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listNew); // 添加Activity到堆栈 ActivityManager.getAppManager().addActivity(this); } /** * 初始化视图 */ private void initViews() { mListView = (ListView) findViewById(R.id.listView); // mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrs)); mListView.setTextFilterEnabled(true); mListView.setAdapter(mAdapter); mListView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(mListView.getWindowToken(), 0); // 输入法如果是显示状态,那么就隐藏输入法 } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); mSearchView = (SearchView) findViewById(R.id.searchView); mSearchView.setIconifiedByDefault(false); // mSearchView.setSubmitButtonEnabled(true); // mSearchView.onActionViewExpanded(); // mSearchView.setBackgroundColor(0x2200aa00); // mSearchView.setBackgroundResource(R.color.blue1); // 设置搜索文本监听 mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { private String TAG = getClass().getSimpleName(); // 当点击搜索按钮时触发该方法 @Override public boolean onQueryTextSubmit(String queryText) { Log.d(TAG, "onQueryTextSubmit = " + queryText); if (mSearchView != null) { // 得到输入管理对象 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { // 这将让键盘在所有的情况下都被隐藏,但是一般我们在点击搜索按钮后,输入法都会乖乖的自动隐藏的。 imm.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0); // 输入法如果是显示状态,那么就隐藏输入法 } mSearchView.clearFocus(); // 不获取焦点 } return true; } // 当搜索内容改变时触发该方法 @Override public boolean onQueryTextChange(String queryText) { Log.d(TAG, "onQueryTextChange = " + queryText); str = queryText; for (String temp : listOld) { if (temp.contains(queryText)) { listNew.add(temp); } } mAdapter.notifyDataSetChanged(); // 交换指针,展示新的数据 return true; } }); } public void onButtonClick(View view){ // Toast.makeText(this,"button",Toast.LENGTH_LONG).show(); if(TextUtils.isEmpty(str)) return; Toast.makeText(this,str,Toast.LENGTH_LONG).show(); Intent intent = new Intent(this,TabLayoutActivity.class); intent.putExtra("data",str); startActivity(intent); } @Override protected void onDestroy() { super.onDestroy(); // OkHttpProxy.cancel(OkHttpManager.getInstance()); // 结束Activity&从堆栈中移除 ActivityManager.getAppManager().finishActivity(this); } }
true
7ad4fdf4fb75bbfac00149f509124158600cf4fa
Java
cuongbphv/Specialized-Essay
/ProgramingForum/src/main/java/com/tlcn/programingforum/util/IDGeneratorUtil.java
UTF-8
946
2.234375
2
[]
no_license
package com.tlcn.programingforum.util; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.id.UUIDGenerator; import org.hibernate.service.ServiceRegistry; import org.hibernate.type.Type; import java.io.Serializable; import java.util.Properties; /** * @author Huy Pham */ public class IDGeneratorUtil extends UUIDGenerator { private String entityName; @Override public void configure(Type type, Properties params, ServiceRegistry dialect) { entityName = params.getProperty(ENTITY_NAME); super.configure(type, params, dialect); } @Override public Serializable generate(SharedSessionContractImplementor session, Object object) { Serializable id = session.getEntityPersister(entityName, object).getIdentifier(object, session); if (id == null) { return CommonUtil.generateUUID(); } else { return id; } } }
true
ac22db12263acd2f26974818964dc84f5624ebe1
Java
xiaodin1/stone-mvc
/src/main/java/stone/mvc/views/impl/XmlDataViewHandler.java
UTF-8
377
1.9375
2
[ "Apache-2.0" ]
permissive
package stone.mvc.views.impl; import javax.servlet.http.HttpServletRequest; import stone.mvc.views.AbstractDataViewHandler; public class XmlDataViewHandler extends AbstractDataViewHandler { @Override public String getType() { return "xml"; } @Override public String getMimetype(HttpServletRequest request) { return "text/xml"; } }
true
28361eec9f016ee40dad4b5982e895405d318284
Java
NahuLD/java-launch-library
/src/main/java/me/nahu/launchlibrary/entities/rocket/RocketFamily.java
UTF-8
646
2.3125
2
[ "MIT" ]
permissive
package me.nahu.launchlibrary.entities.rocket; import me.nahu.launchlibrary.entities.Entity; import me.nahu.launchlibrary.entities.agency.AgencyQuery; import java.util.List; /** * Rocket Family entity class. * {@code https://launchlibrary.net/docs/1.4/api.html#rocketfamily} for more information. */ public class RocketFamily extends Entity { private List<AgencyQuery.Agency> agencies; /** * Get array of {@link AgencyQuery.Agency} collaborating on the {@link RocketFamily}. * @return {@link List<AgencyQuery.Agency>} agencies. */ public List<AgencyQuery.Agency> getAgencies() { return agencies; } }
true
1727fc04d960c0a0f8579cbe4497639864b83852
Java
mounikakoppula/my-project
/Logindemo/src/logincontroller.java
UTF-8
1,374
2.328125
2
[]
no_license
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class logincontroller extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public logincontroller() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //System.out.println("doPost"); String username=request.getParameter("username"); String password=request.getParameter("password"); LoginDAO loginDAO =new LoginDAO(); if(loginDAO.isValidUser(username,password)==true) { PrintWriter out=response.getWriter(); out.println("valid user"); RequestDispatcher dispatcher; dispatcher=request.getRequestDispatcher("home.html"); dispatcher.forward(request,response); } else { // RequestDispatcher dispatcher = request.getRequestDispatcher("login.html"); PrintWriter writer=response.getWriter(); writer.println("invalid...plese try agin"); // dispatcher.include(request,response); } } }
true
83665ac06650039507335d1f101a2cff95480020
Java
wingpark/designPattern
/singleton/dp/singleton/HungrySingleton.java
UTF-8
424
2.5625
3
[]
no_license
/** * @Title: HungrySingleton.java * @Description: 饥饿单例模式 * @author wby * @date 2016年7月25日 下午5:29:45 * @version V1.0 */ package dp.singleton; public class HungrySingleton { private static final HungrySingleton singleton = new HungrySingleton(); private HungrySingleton() { super(); } public static HungrySingleton getSingleton() { return singleton; } }
true
359954b6c87a3782fea7ccf37657142ccbcb9826
Java
BaneManojlovic/NDexample1
/app/src/main/java/com/bitnovisad/ndexample1/PlayerDetailsActivity.java
UTF-8
2,526
2.640625
3
[]
no_license
package com.bitnovisad.ndexample1; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.squareup.picasso.Picasso; public class PlayerDetailsActivity extends AppCompatActivity { protected boolean isNetworkConnected() { try { ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); return (mNetworkInfo == null) ? false : true; }catch (NullPointerException e){ return false; } } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.player_details_fragment); //toast message to handle if there is no internet connection if(isNetworkConnected() == false){ Toast.makeText(this, R.string.no_internet_msg, Toast.LENGTH_LONG).show(); } //call for method that give data for player details screen getIncomingIntent(); } //method for catching incoming intent public void getIncomingIntent() { if (getIntent().hasExtra("image_url") && getIntent().hasExtra("ply_name") && getIntent().hasExtra("ply_position")) { String imageUrl = getIntent().getStringExtra("image_url"); String playerName = getIntent().getStringExtra("ply_name"); String playerPosition = getIntent().getStringExtra("ply_position"); setImage(imageUrl, playerName, playerPosition); } } //seting values from intent into layout public void setImage(String imageUrl, String playerName, String playerPosition) { ImageView image = (ImageView) findViewById(R.id.iv_player_details); Picasso.with(this) .load(imageUrl) .resize(400, 400) .centerCrop() .into(image); TextView namePly = (TextView) findViewById(R.id.tv_player_details_player_name); namePly.setText(playerName); TextView positionPly = (TextView) findViewById(R.id.tv_player_details_player_position); positionPly.setText(playerPosition); } }
true
e4274635128fbfc3bf1fe7b05c9474fbc413a1f3
Java
yuyivie/Design_Patterns
/src/observer/example1/Test2.java
GB18030
264
2.1875
2
[]
no_license
package observer.example1; /** * @author yu *ͨۼʽij */ public class Test2 { public static void main(String[] args) { // HanFeiZi2 hanFeiZi = new HanFeiZi2(); hanFeiZi.haveBreakfast(); hanFeiZi.haveFun(); } }
true
77426cbd655085ddd8b9364db3ce2a7a7d182bd6
Java
SuzyWu2014/coprhd-controller
/exportLibraries/storagedrivers/3par/src/main/java/com/emc/storageos/hp3par/utils/HP3PARConstants.java
UTF-8
5,317
1.828125
2
[]
no_license
/* * Copyright 2016 EMC Corporation * All Rights Reserved */ package com.emc.storageos.hp3par.utils; public class HP3PARConstants { public static final String DRIVER_NAME ="HP-3PAR"; public static final String IP_ADDRESS = "IP_ADDRESS"; public static final String PORT_NUMBER = "PORT_NUMBER"; public static final String USER_NAME = "USER_NAME"; public static final String PASSWORD = "PASSWORD"; public static final String S_NON_EXISTENT_HOST = "17"; public static final Integer I_NON_EXISTENT_HOST = 17; public static final Integer OP_SUCCESS = 0; public static Long KILO_BYTE = (long) 1024; public static Long MEGA_BYTE = (long) 1024 * 1024; public static final Integer MODE_SUSPENDED = 1; public static final Integer MODE_TARGET = 2; public static final Integer TYPE_FREE = 3; public static final Integer TYPE_DISK = 2; public static final Integer LINK_READY = 4; public static final String TASK_TYPE_DISCOVER_STORAGE_SYSTEM="discover-storage-system"; public static final String TASK_TYPE_DISCOVER_STORAGE_POOLS="discover-storage-pools"; public static final String TASK_TYPE_DISCOVER_STORAGE_PORTS="discover-storage-ports"; public static final String TASK_TYPE_DISCOVER_STORAGE_HOSTS="discover-storage-hosts"; public static final String TASK_TYPE_GET_STORAGE_VOLUMES="get-storage-volumes"; public static final String TASK_TYPE_CREATE_STORAGE_VOLUMES="create-storage-volumes"; public static final String TASK_TYPE_EXPAND_STORAGE_VOLUMES="expand-storage-volumes"; public static final String TASK_TYPE_DELETE_STORAGE_VOLUMES="delete-storage-volumes"; public static final String TASK_TYPE_EXPORT_STORAGE_VOLUMES="export-storage-volumes"; public static final String TASK_TYPE_UNEXPORT_STORAGE_VOLUMES="unexport-storage-volumes"; public static final String TASK_TYPE_CREATE_SNAPSHOT_VOLUMES="create-snapshot-volumes"; public static final String TASK_TYPE_RESTORE_SNAPSHOT_VOLUMES="restore-snapshot-volumes"; public static final String TASK_TYPE_DELETE_SNAPSHOT_VOLUMES="delete-snapshot-volumes"; public static final String TASK_TYPE_CREATE_CLONE_VOLUMES="create-clone-volumes"; public static final String TASK_TYPE_RESTORE_CLONE_VOLUMES="restore-clone-volumes"; public static final String TASK_TYPE_DETACH_CLONE_VOLUMES="detach-clone-volumes"; public static final String TASK_TYPE_DELETE_CLONE_VOLUMES="delete-clone-volumes"; public static final String TASK_TYPE_CREATE_CONSISTENCY_GROUP = "create-consistency-group"; public static final String TASK_TYPE_DELETE_CONSISTENCY_GROUP = "delete-consistency-group"; public static final String TASK_TYPE_SNAPSHOT_CONSISTENCY_GROUP = "snapshot-consistency-group"; public static final String TASK_TYPE_CLONE_CONSISTENCY_GROUP = "clone-consistency-group"; public static final String TASK_TYPE_UPDATE_CONSISTENCY_GROUP = "update-consistency-group"; public static final String TASK_TYPE_DELETE_SNAPSHOT_CONSISTENCY_GROUP = "delete-snapshot-consistency-group"; public static final String TASK_TYPE_DELETE_CLONE_CONSISTENCY_GROUP = "delete-clone-consistency-group"; public static final String TASK_TYPE_REMOVE_VOLUME_FROM_CONSISTENCY_GROUP = "remove-volume-from-consistency-group"; public static final String TASK_TYPE_ADD_VOLUME_TO_CONSISTENCY_GROUP = "add-volume-to-consistency-group"; public static final String VLUN_DOES_NOT_EXIST = "VLUN does not exist"; public static enum provisioningType { FULL("FULL" , 1), TPVV("TPVV", 2), SNP("SNP", 3), PEER("PEER", 4), TDVV("TDVV", 5); public String type= ""; public int value = 0; public String getType() { return type; } public void setType(String type) { this.type = type; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } provisioningType(String type, int value) { this.type = type; this.value= value; } } public static enum copyType { BASE("BASE" , 1), PHYSICAL_COPY("PHYSICAL_COPY", 2), VIRTUAL_COPY("VIRTUAL_COPY", 3); public String type= ""; public int value = 0; public String getType() { return type; } public void setType(String type) { this.type = type; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } copyType(String type, int value) { this.type = type; this.value= value; } } public static enum vLunType { EMPTY("EMPTY" , 1), PORT("PORT", 2), HOST("HOST", 3), MATCHED_SET("MATCHED_SET", 4), HOST_SET("HOST_SET", 5); public String type= ""; public int value = 0; public String getType() { return type; } public void setType(String type) { this.type = type; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } vLunType(String type, int value) { this.type = type; this.value= value; } } }
true
da729123c887d6b44023d9355ff3b656a0004b3c
Java
tao-tao/BusinessModuleDesign
/avicit.ui.view.navigator/src/avicit/ui/view/module/IPriority.java
UTF-8
102
1.820313
2
[]
no_license
package avicit.ui.view.module; public interface IPriority { public abstract int getPriority(); }
true
631c544ad6f924b1444895db786ff5695d143110
Java
louismarie/budgetview
/siteweaver/src/main/com/designup/siteweaver/custom/dup/DupBookTourFormatter.java
UTF-8
798
2.5
2
[]
no_license
package com.designup.siteweaver.custom.dup; import com.designup.siteweaver.generation.generators.BookTourGenerator; import com.designup.siteweaver.html.HtmlWriter; import com.designup.siteweaver.model.Page; public class DupBookTourFormatter implements BookTourGenerator.Formatter { public void writeStart(HtmlWriter writer) { writer.write("<div class=\"booktour\">"); } public void writePath(Page nextPage, HtmlWriter writer) { writer.write(nextPage.getFilePath()); } public void writeLink(Page nextPage, HtmlWriter writer) { writer.writeLink(nextPage.getTitle(), nextPage.getUrl()); } public void writeTitle(Page nextPage, HtmlWriter writer) { writer.write(nextPage.getTitle()); } public void writeEnd(HtmlWriter writer) { writer.write("</div>"); } }
true
431c6a5d85f35cb5536a256f4a59452c4049416d
Java
supertassu/db
/example/src/main/java/me/tassu/db/example/DBExample.java
UTF-8
1,111
2.828125
3
[]
no_license
package me.tassu.db.example; import me.tassu.db.impl.sql.mysql.MySQLDatabase; import me.tassu.db.sql.column.Column; import me.tassu.db.sql.table.Table; import me.tassu.db.util.DataType; public class DBExample { public static void main(String[] args) { MySQLDatabase database = MySQLDatabase.builder() .host("localhost") .port(3306) .username("root") .password("root") .database("test") .build(); Column[] columns = new Column[] { database.column("random_column", DataType.STRING), database.column("another_column", DataType.INTEGER), database.column("is_it_good", DataType.BOOLEAN), database.column("how_am_i_supposed_to_get_ideas_from_names", DataType.NUMBER).setAllowNull(false), database.column("im_finally_done", DataType.LONG_INTEGER) }; Table table = database.table("random_table", columns).setPrimaryColumns("random_column"); System.out.print(table.toString()); } }
true
98c6ab68ee7589f33aaf6f7253a3ebec0b0c8101
Java
15583000287/First_Ribbon_Client
/src/main/java/com/example/ribbon/PingUrlTest.java
UTF-8
1,426
3.09375
3
[]
no_license
package com.example.ribbon; import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.PingUrl; import com.netflix.loadbalancer.Server; import java.util.ArrayList; import java.util.List; /** * Pring机制(判断服务器是否存活) * * 在负载均衡器中,提供了 Ping 的机制,每隔一段时间,会去 Ping 服务器,判断服务器是否存活。 * * 该工作由 IPing 接口的实现类负责,如果单独使用 Ribbon,在默认情况下,不会激活 Ping 机制 * * 默认的实现类为 DummyPing。 * *自定义Ping: * 1.实现IPing接口 * 2.实现接口方法 */ public class PingUrlTest { public static void main(String[] args) throws Exception{ // 创建负载均衡器 BaseLoadBalancer lb = new BaseLoadBalancer(); // 添加服务器 List<Server> servers = new ArrayList<Server>(); // 8080 端口连接正常 servers.add(new Server("localhost", 8080)); // 一个不存在的端口 servers.add(new Server("localhost", 8888)); lb.addServers(servers); // 设置 IPing 实现类 lb.setPing(new PingUrl()); // 设置 Ping 时间间隔为 2 秒 lb.setPingInterval(2); // Thread.sleep(6000); for(Server s : lb.getAllServers()) { System.out.println(s.getHostPort() + " 状态:" + s.isAlive()); } } }
true
30240bb49f7653c5b523e08c434f7fc2c7d7a3b0
Java
knobel/coursera-algorithms-01
/dequesrandomizedqueues/src/test/java/RandomizedQueueTest.java
UTF-8
1,455
2.9375
3
[]
no_license
import org.junit.Before; import org.junit.Test; import java.util.Iterator; /** * Created by michal on 11.12.16. */ public class RandomizedQueueTest { RandomizedQueue<String> randomizedQueue; @Before public void setUp() throws Exception { randomizedQueue = new RandomizedQueue<>(); } @Test public void isEmpty() throws Exception { } @Test public void size() throws Exception { } @Test public void enqueue() throws Exception { } @Test public void dequeue() throws Exception { randomizedQueue.enqueue("Test1"); randomizedQueue.enqueue("Test2"); randomizedQueue.enqueue("Test3"); randomizedQueue.enqueue("Test4"); randomizedQueue.enqueue("Test5"); Iterator<String> iterator = randomizedQueue.iterator(); String s1 = iterator.next(); String s2 = iterator.next(); String s3 = iterator.next(); String s4 = iterator.next(); String s5 = iterator.next(); printQueue(); randomizedQueue.dequeue(); printQueue(); randomizedQueue.dequeue(); printQueue(); } @Test public void sample() throws Exception { } private void printQueue() { System.out.println("###################"); for (String s : randomizedQueue) { System.out.println(s); } System.out.println("###################"); } }
true