blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d5608e75b79f238c915a1c1afb795a5d31472fe6 | bcd1fc3eb382d56375bf4c8f14a5fafe3efea9dd | /src/main/java/in/spacex/web/rest/errors/package-info.java | d770914f0e9f259528b49ede9d045578bf91251e | [] | no_license | sureshputla/SpaceX | 4f3153751acaadea7e26ec9b9231aeeee0f60ed0 | 5f622edc86c6418aa408fae4e83de27c1a28564f | refs/heads/master | 2023-05-10T05:30:59.811221 | 2021-05-16T07:12:57 | 2021-05-16T07:12:57 | 231,739,070 | 0 | 0 | null | 2023-05-07T16:26:28 | 2020-01-04T09:32:08 | Java | UTF-8 | Java | false | false | 184 | java | /**
* Specific errors used with Zalando's "problem-spring-web" library.
*
* More information on https://github.com/zalando/problem-spring-web
*/
package in.spacex.web.rest.errors;
| [
"[email protected]"
] | |
1c41c1a5addfc4d2500ab2ca9f2cfccf4671aa01 | 564a9fa52c6ec92605637e812baccd8cda7f992f | /travel-portal-web/src/main/java/ru/ipccenter/travelportal/data/holders/DepartmentInfo.java | 14c4379c980f5e241333b360fe96a47f1cb15ecb | [] | no_license | meelvin182/travelportal | 79443954998eff8d7a458565437e04b221f6ea49 | 2415e7083474b363fe929ef5d72cfd0f8e88a473 | refs/heads/master | 2022-07-07T20:31:26.913292 | 2019-08-16T20:19:59 | 2019-08-16T20:19:59 | 39,040,191 | 0 | 0 | null | 2022-06-29T16:41:50 | 2015-07-13T22:14:51 | Java | UTF-8 | Java | false | false | 4,265 | java | package ru.ipccenter.travelportal.data.holders;
import ru.ipccenter.travelportal.common.model.objects.Department;
import ru.ipccenter.travelportal.common.model.objects.Employee;
import ru.ipccenter.travelportal.common.model.objects.User;
import ru.ipccenter.travelportal.services.AbstractByIdFactory;
import ru.ipccenter.travelportal.services.DepartmentService;
import ru.ipccenter.travelportal.services.EmployeeService;
import java.math.BigInteger;
import java.util.Collections;
import java.util.List;
public final class DepartmentInfo {
public static enum DepartmentType {
COMMON(new BigInteger("9223372036854775728"), "Common department"),
TRAVEL_SUPPORT(new BigInteger("9223372036854775727"), "Travel suppport"),
IT(new BigInteger("9223372036854775726"), "System support department");
private DepartmentType(BigInteger roleId, String roleName) {
this.roleId = roleId;
this.roleName = roleName;
}
private final BigInteger roleId;
private final String roleName;
public BigInteger getRoleId() {
return roleId;
}
public String getRoleName() {
return roleName;
}
public static DepartmentType valueOf(BigInteger roleId) {
for (DepartmentType type: values()) {
if (type.getRoleId().equals(roleId)) {
return type;
}
}
return null;
}
}
private BigInteger departmentId;
private String name;
private DepartmentType type;
private BigInteger managerId;
private List<EmployeeInfo> employees;
private EmployeeInfo selectedEmployee;
public DepartmentInfo() {
this.type = DepartmentType.COMMON;
this.employees = Collections.emptyList();
}
public DepartmentInfo(BigInteger id, DepartmentService service) {
this();
if (id != null) {
loadDepartmentInfo(id, service);
}
}
private void loadDepartmentInfo(final BigInteger id, final DepartmentService departmentService) {
final Department departmentBean = departmentService.getDepartment(id);
final Employee managerBean = departmentBean.getManager();
departmentId = departmentBean.getId();
name = departmentBean.getName();
if (managerBean != null) {
final User userBean = managerBean.getUser();
managerId = managerBean.getId();
if (userBean != null) {
type = DepartmentType.valueOf(userBean.getRoleId());
}
managerBean.unused();
}
final EmployeeService employeeService = departmentService.getEmployeeService();
employees = employeeService.getEmployeesForDepartment(
departmentId,
new AbstractByIdFactory<EmployeeInfo>() {
@Override
public EmployeeInfo create(BigInteger id) {
final Employee employee = employeeService.getEmployee(id);
final EmployeeInfo employeeInfo = new EmployeeInfo(employee);
employee.unused();
return employeeInfo;
}
});
departmentBean.unused();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DepartmentType getType() {
return type;
}
public void setType(DepartmentType type) {
this.type = type;
}
public BigInteger getId() {
return departmentId;
}
public BigInteger getManagerId() {
return managerId;
}
public void setManagerId(BigInteger managerId) {
this.managerId = managerId;
}
public List<EmployeeInfo> getEmployees() {
return employees;
}
public EmployeeInfo getSelectedEmployee() {
return selectedEmployee;
}
public void setSelectedEmployee(EmployeeInfo selectedEmployee) {
this.selectedEmployee = selectedEmployee;
}
}
| [
"[email protected]"
] | |
1df2fbf22eb9dfcc2b43a5c6fef7649c8b89b407 | c9f2bd34255a1f7822fe0fbf4c7e51fa26eede14 | /daikon-5.5.14/java/daikon/dcomp/StackVer.java | f29dd8127af573e6def187342a829258771469e0 | [] | no_license | billy-mosse/jconsume | eca93b696eaf8edcb8af5730eebd95f49e736fd4 | b782a55f20c416a73c967b2225786677af5f52ba | refs/heads/master | 2022-09-22T18:10:43.784966 | 2020-03-09T01:00:38 | 2020-03-09T01:00:38 | 97,016,318 | 4 | 0 | null | 2022-09-01T22:58:04 | 2017-07-12T14:18:01 | C | UTF-8 | Java | false | false | 20,958 | java | package daikon.dcomp;
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache BCEL" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* "Apache BCEL", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.bcel.Const;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.JsrInstruction;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.RET;
import org.apache.bcel.generic.ReturnInstruction;
import org.apache.bcel.generic.ReturnaddressType;
import org.apache.bcel.generic.Type;
import org.apache.bcel.verifier.VerificationResult;
import org.apache.bcel.verifier.exc.AssertionViolatedException;
import org.apache.bcel.verifier.exc.VerifierConstraintViolatedException;
import org.apache.bcel.verifier.structurals.ControlFlowGraph;
import org.apache.bcel.verifier.structurals.ExceptionHandler;
import org.apache.bcel.verifier.structurals.ExecutionVisitor;
import org.apache.bcel.verifier.structurals.Frame;
import org.apache.bcel.verifier.structurals.InstConstraintVisitor;
import org.apache.bcel.verifier.structurals.InstructionContext;
import org.apache.bcel.verifier.structurals.LocalVariables;
import org.apache.bcel.verifier.structurals.OperandStack;
import org.apache.bcel.verifier.structurals.UninitializedObjectType;
/*>>>
import org.checkerframework.checker.nullness.qual.*;
*/
/**
* This is a slightly modified version of Pass3bVerifier from BCEL. It uses LimitedConstaintVisitor
* rather than InstConstraintVisitor to implement the constraints. The LimitedConstraintVisitor
* doesn't do any checking outside of the current class and removes some checks so that this will
* pass on the JDK. This version also provides the ability to get the contents of the stack for each
* instruction in the method.
*
* <p>This PassVerifier verifies a method of class file according to pass 3, so-called structural
* verification as described in The Java Virtual Machine Specification, 2nd edition. More detailed
* information is to be found at the do_verify() method's documentation.
*
* @version $Id$
* @author <A HREF="http://www.inf.fu-berlin.de/~ehaase">Enver Haase</A>
* @see #get_stack_types()
*/
@SuppressWarnings({"rawtypes", "nullness", "interning"}) // third-party code
public final class StackVer {
/* TODO: Throughout pass 3b, upper halves of LONG and DOUBLE
are represented by Type.UNKNOWN. This should be changed
in favour of LONG_Upper and DOUBLE_Upper as in pass 2. */
/**
* An InstructionContextQueue is a utility class that holds (InstructionContext, ArrayList) pairs
* in a Queue data structure. This is used to hold information about InstructionContext objects
* externally --- i.e. that information is not saved inside the InstructionContext object itself.
* This is useful to save the execution path of the symbolic execution of the Pass3bVerifier -
* this is not information that belongs into the InstructionContext object itself. Only at
* "execute()"ing time, an InstructionContext object will get the current information we have
* about its symbolic execution predecessors.
*/
private static final class InstructionContextQueue {
private List<InstructionContext> ics = new ArrayList<InstructionContext>();
private List<ArrayList<InstructionContext>> ecs =
new ArrayList<ArrayList<InstructionContext>>();
/**
* TODO
*
* @param ic
* @param executionChain
*/
public void add(InstructionContext ic, ArrayList<InstructionContext> executionChain) {
ics.add(ic);
ecs.add(executionChain);
}
/**
* TODO
*
* @return
*/
public boolean isEmpty() {
return ics.isEmpty();
}
/** TODO */
public void remove() {
this.remove(0);
}
/**
* TODO
*
* @param i
*/
public void remove(int i) {
ics.remove(i);
ecs.remove(i);
}
/**
* TODO
*
* @param i
* @return
*/
public InstructionContext getIC(int i) {
return ics.get(i);
}
/**
* TODO
*
* @param i
* @return
*/
public ArrayList<InstructionContext> getEC(int i) {
return ecs.get(i);
}
/**
* TODO
*
* @return
*/
public int size() {
return ics.size();
}
} // end Inner Class InstructionContextQueue
// /**
// * This modified version of InstContraintVisitor causes the verifier
// * not to load any other classes as part of verification (causing it
// * to presume that information in this class is correct. This is
// * necessary for efficiency and also prevents some other problems
// */
// private static class MyLimitedConstraintVisitor
// extends InstConstraintVisitor {
//
// public void visitLoadClass(LoadClass o){
// // System.out.println ("Skipping visitLoadClass " + o);
// }
// public void visitINVOKEVIRTUAL(INVOKEVIRTUAL o){
// // TODO JHP: This should really check the arguments (for when
// // we use this code as a verifier)
// // System.out.println ("Skipping invoke virtual " + o);
// }
//
// public void visitNEW (NEW o) {
// // All this does is make sure that the new object is as expected.
// // It fails if it can't find it, which we would prefer it not
// // to do.
// }
//
// public void visitLDC(LDC o){
// // Skipping check because LDC has new capabilities in 1.5 not
// // supported by this check (it allows constant classes in addition
// // to strings, integers, and floats
// }
//
// public void visitLDC_W(LDC_W o){
// // Skipping check because LDC has new capabilities in 1.5 not
// // supported by this check (it allows constant classes in addition
// // to strings, integers, and floats
// }
// }
/** In DEBUG mode, the verification algorithm is not randomized. */
private static final boolean DEBUG = true;
/** The Verifier that created this. */
// private Verifier myOwner;
/** The types on the stack for each instruction by byte code offset */
// Set by do_stack_ver().
private /*@MonotonicNonNull*/ StackTypes stack_types;
/**
* This class should only be instantiated by a Verifier.
*
* @see org.apache.bcel.verifier.Verifier
*/
public StackVer() {}
/**
* Return the types on the stack at each byte code offset. Only valid after do_stack_ver() is
* called.
*/
public StackTypes get_stack_types() {
return stack_types;
}
/**
* Whenever the outgoing frame situation of an InstructionContext changes, all its successors are
* put [back] into the queue [as if they were unvisited]. The proof of termination is about the
* existence of a fix point of frame merging.
*/
private void circulationPump(
ControlFlowGraph cfg,
InstructionContext start,
Frame vanillaFrame,
InstConstraintVisitor icv,
ExecutionVisitor ev) {
final Random random = new Random();
InstructionContextQueue icq = new InstructionContextQueue();
stack_types.set(start.getInstruction().getPosition(), vanillaFrame);
// new ArrayList() <=> no Instruction was executed before
start.execute(vanillaFrame, new ArrayList<InstructionContext>(), icv, ev);
// => Top-Level routine (no jsr call before)
icq.add(start, new ArrayList<InstructionContext>());
// LOOP!
while (!icq.isEmpty()) {
InstructionContext u;
ArrayList<InstructionContext> ec;
if (!DEBUG) {
int r = random.nextInt(icq.size());
u = icq.getIC(r);
ec = icq.getEC(r);
icq.remove(r);
} else {
u = icq.getIC(0);
ec = icq.getEC(0);
icq.remove(0);
}
// this makes Java grumpy
// ArrayList<InstructionContext> oldchain = (ArrayList<InstructionContext>) (ec.clone());
ArrayList<InstructionContext> oldchain = new ArrayList<InstructionContext>(ec);
// this makes Java grumpy
// ArrayList<InstructionContext> newchain = (ArrayList) (ec.clone());
ArrayList<InstructionContext> newchain = new ArrayList<InstructionContext>(ec);
newchain.add(u);
if ((u.getInstruction().getInstruction()) instanceof RET) {
// We can only follow _one_ successor, the one after the
// JSR that was recently executed.
RET ret = (RET) (u.getInstruction().getInstruction());
ReturnaddressType t =
(ReturnaddressType) u.getOutFrame(oldchain).getLocals().get(ret.getIndex());
InstructionContext theSuccessor = cfg.contextOf(t.getTarget());
// Sanity check
InstructionContext lastJSR = null;
int skip_jsr = 0;
for (int ss = oldchain.size() - 1; ss >= 0; ss--) {
if (skip_jsr < 0) {
throw new AssertionViolatedException("More RET than JSR in execution chain?!");
}
//System.err.println("+"+oldchain.get(ss));
if ((oldchain.get(ss)).getInstruction().getInstruction() instanceof JsrInstruction) {
if (skip_jsr == 0) {
lastJSR = oldchain.get(ss);
break;
}
skip_jsr--;
}
if ((oldchain.get(ss)).getInstruction().getInstruction() instanceof RET) {
skip_jsr++;
}
}
if (lastJSR == null) {
throw new AssertionViolatedException(
"RET without a JSR before in ExecutionChain?! EC: '" + oldchain + "'.");
}
JsrInstruction jsr = (JsrInstruction) (lastJSR.getInstruction().getInstruction());
if (theSuccessor != (cfg.contextOf(jsr.physicalSuccessor()))) {
throw new AssertionViolatedException(
"RET '"
+ u.getInstruction()
+ "' info inconsistent: jump back to '"
+ theSuccessor
+ "' or '"
+ cfg.contextOf(jsr.physicalSuccessor())
+ "'?");
}
Frame f = u.getOutFrame(oldchain);
stack_types.set(theSuccessor.getInstruction().getPosition(), f);
if (theSuccessor.execute(f, newchain, icv, ev)) {
// This makes 5.0 grumpy: icq.add(theSuccessor, (ArrayList) newchain.clone());
icq.add(theSuccessor, new ArrayList<InstructionContext>(newchain));
}
} else { // "not a ret"
// Normal successors. Add them to the queue of successors.
InstructionContext[] succs = u.getSuccessors();
for (int s = 0; s < succs.length; s++) {
InstructionContext v = succs[s];
Frame f = u.getOutFrame(oldchain);
stack_types.set(v.getInstruction().getPosition(), f);
if (v.execute(f, newchain, icv, ev)) {
// This makes 5.0 grumpy: icq.add(v, (ArrayList) newchain.clone());
icq.add(v, new ArrayList<InstructionContext>(newchain));
}
}
} // end "not a ret"
// Exception Handlers. Add them to the queue of successors.
// [subroutines are never protected; mandated by JustIce]
ExceptionHandler[] exc_hds = u.getExceptionHandlers();
for (int s = 0; s < exc_hds.length; s++) {
InstructionContext v = cfg.contextOf(exc_hds[s].getHandlerStart());
// TODO: the "oldchain" and "newchain" is used to determine the subroutine
// we're in (by searching for the last JSR) by the InstructionContext
// implementation. Therefore, we should not use this chain mechanism
// when dealing with exception handlers.
// Example: a JSR with an exception handler as its successor does not
// mean we're in a subroutine if we go to the exception handler.
// We should address this problem later; by now we simply "cut" the chain
// by using an empty chain for the exception handlers.
//if (v.execute(new Frame(u.getOutFrame(oldchain).getLocals(), new OperandStack (u.getOutFrame().getStack().maxStack(), (exc_hds[s].getExceptionType()==null? Type.THROWABLE : exc_hds[s].getExceptionType())) ), newchain), icv, ev){
//icq.add(v, (ArrayList) newchain.clone());
Frame f =
new Frame(
u.getOutFrame(oldchain).getLocals(),
new OperandStack(
u.getOutFrame(oldchain).getStack().maxStack(),
(exc_hds[s].getExceptionType() == null
? Type.THROWABLE
: exc_hds[s].getExceptionType())));
stack_types.set(v.getInstruction().getPosition(), f);
if (v.execute(f, new ArrayList<InstructionContext>(), icv, ev)) {
icq.add(v, new ArrayList<InstructionContext>());
}
}
} // while (!icq.isEmpty()) END
InstructionHandle ih = start.getInstruction();
do {
if ((ih.getInstruction() instanceof ReturnInstruction) && (!(cfg.isDead(ih)))) {
InstructionContext ic = cfg.contextOf(ih);
Frame f = ic.getOutFrame(new ArrayList<InstructionContext>());
// TODO: This is buggy, we check only the top-level return instructions
// this way. Maybe some maniac returns from a method when in a subroutine?
LocalVariables lvs = f.getLocals();
for (int i = 0; i < lvs.maxLocals(); i++) {
if (lvs.get(i) instanceof UninitializedObjectType) {
this.addMessage(
"Warning: ReturnInstruction '"
+ ic
+ "' may leave method with an uninitialized object in the local variables array '"
+ lvs
+ "'.");
}
}
OperandStack os = f.getStack();
for (int i = 0; i < os.size(); i++) {
if (os.peek(i) instanceof UninitializedObjectType) {
this.addMessage(
"Warning: ReturnInstruction '"
+ ic
+ "' may leave method with an uninitialized object on the operand stack '"
+ os
+ "'.");
}
}
}
} while ((ih = ih.getNext()) != null);
}
/**
* Implements the pass 3b data flow analysis as described in the Java Virtual Machine
* Specification, Second Edition. As it is doing so it keeps track of the stack and local
* variables at each instruction.
*
* @see org.apache.bcel.verifier.statics.Pass2Verifier#getLocalVariablesInfo(int)
*/
public VerificationResult do_stack_ver(MethodGen mg) {
/*
if (! myOwner.doPass3a(method_no).equals(VerificationResult.VR_OK)){
return VerificationResult.VR_NOTYET;
}
*/
// Pass 3a ran before, so it's safe to assume the JavaClass object is
// in the BCEL repository.
// JavaClass jc = Repository.lookupClass(myOwner.getClassName());
ConstantPoolGen constantPoolGen = mg.getConstantPool();
// Init Visitors
InstConstraintVisitor icv = new LimitedConstraintVisitor();
icv.setConstantPoolGen(constantPoolGen);
ExecutionVisitor ev = new ExecutionVisitor();
ev.setConstantPoolGen(constantPoolGen);
try {
stack_types = new StackTypes(mg);
icv.setMethodGen(mg);
////////////// DFA BEGINS HERE ////////////////
if (!(mg.isAbstract() || mg.isNative())) { // IF mg HAS CODE (See pass 2)
// false says don't check if jsr subroutine is covered by exception handler
ControlFlowGraph cfg = new ControlFlowGraph(mg, false);
// Build the initial frame situation for this method.
Frame f = new Frame(mg.getMaxLocals(), mg.getMaxStack());
if (!mg.isStatic()) {
if (mg.getName().equals(Const.CONSTRUCTOR_NAME)) {
Frame.setThis(new UninitializedObjectType(new ObjectType(mg.getClassName())));
f.getLocals().set(0, Frame.getThis());
} else {
@SuppressWarnings("nullness") // unannotated: org.apache.bcel.verifier.structurals.Frame
/*@NonNull*/ UninitializedObjectType dummy = null;
Frame.setThis(dummy);
f.getLocals().set(0, new ObjectType(mg.getClassName()));
}
}
Type[] argtypes = mg.getArgumentTypes();
int twoslotoffset = 0;
for (int j = 0; j < argtypes.length; j++) {
if (argtypes[j] == Type.SHORT
|| argtypes[j] == Type.BYTE
|| argtypes[j] == Type.CHAR
|| argtypes[j] == Type.BOOLEAN) {
argtypes[j] = Type.INT;
}
f.getLocals().set(twoslotoffset + j + (mg.isStatic() ? 0 : 1), argtypes[j]);
if (argtypes[j].getSize() == 2) {
twoslotoffset++;
f.getLocals().set(twoslotoffset + j + (mg.isStatic() ? 0 : 1), Type.UNKNOWN);
}
}
circulationPump(cfg, cfg.contextOf(mg.getInstructionList().getStart()), f, icv, ev);
}
} catch (VerifierConstraintViolatedException ce) {
ce.extendMessage("Constraint violated in method '" + mg + "':\n", "");
return new VerificationResult(VerificationResult.VERIFIED_REJECTED, ce.getMessage());
} catch (RuntimeException re) {
// These are internal errors
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
re.printStackTrace(pw);
throw new AssertionViolatedException(
"Some RuntimeException occured while verify()ing class '"
+ mg.getClassName()
+ "', method '"
+ mg
+ "'. Original RuntimeException's stack trace:\n---\n"
+ sw
+ "---\n");
}
return VerificationResult.VR_OK;
}
// Code from PassVerifier in BCEL so that we don't have to extend it
/** The (warning) messages. */
private ArrayList<String> messages = new ArrayList<String>(); //Type of elements: String
/**
* This method adds a (warning) message to the message pool of this PassVerifier. This method is
* normally only internally used by BCEL's class file verifier "JustIce" and should not be used
* from the outside.
*/
public void addMessage(String message) {
messages.add(message);
}
}
// Local Variables:
// tab-width: 2
// End:
| [
"[email protected]"
] | |
72c10682e539dc0671a7616a1ae0b22092186117 | 53a31f9e9573f63c25b96adcfc769441dd8c9a33 | /day07-code/src/cn/gpns/day07/demo03/Demo04RandomGame.java | f0b7387ce33878f68645c22181e53b82d022ee26 | [] | no_license | HXKLH/javaStudy | 3a84e7f9b47b40619b39b5dd96334d213a791126 | aedf2f6513194490f9a1eb1982414687e43d60e9 | refs/heads/master | 2023-04-11T14:08:13.314129 | 2021-04-18T15:38:09 | 2021-04-18T15:38:09 | 359,183,618 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 998 | java | package cn.gpns.day07.demo03;
import java.util.Random;
import java.util.Scanner;
/*
题目:用代码模拟猜数字游戏
*/
public class Demo04RandomGame {
public static void main( String[] args ) {
int n = 100;
System.out.println("你需要从0到"+(n-1)+"中才一个整数中猜一个数!");
int num = getRandomNum(n);
int gesture = gestureNum();
while (gesture != num) {
if (gesture > num) {
System.out.println("你猜的数字大了!");
} else if (gesture < num) {
System.out.println("你猜的数小了!");
}
gesture = gestureNum();
}
System.out.println("恭喜你猜对了!游戏结束!");
}
public static int getRandomNum( int n ) {
return new Random().nextInt(n);
}
public static int gestureNum() {
System.out.println("你猜的数字是:");
return new Scanner(System.in).nextInt();
}
}
| [
"[email protected]"
] | |
d437107c7967cdfa4715a9c724dabe876ceb7ad5 | 49de7b4a17082926d3bf0707eed2d0cfef36dc25 | /src/irie/Main.java | d52cc138e2104394d9f6d23819e8183d9c990f42 | [
"MIT"
] | permissive | adkSpence/abscondo | e518707782852b5d7deb2ae5f209a0b5bc23f275 | 9911dbae44f8d5d1b76c11ad9e259b3105f156ef | refs/heads/master | 2020-06-21T14:54:08.298500 | 2019-07-18T01:39:23 | 2019-07-18T01:39:23 | 197,485,588 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,143 | java | package irie;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class Main extends Application {
public static Stage main_stage, home_stage;
protected static Scene splash_scene, home_scene;
protected static StackPane splash_layout;
protected static BorderPane home_layout;
@Override
public void start(Stage primaryStage) throws Exception {
main_stage = primaryStage;
displaySplashScreen();
}
public static void displaySplashScreen() throws Exception {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("views/SplashScreen.fxml"));
splash_layout = loader.load();
splash_scene = new Scene(splash_layout);
main_stage.setScene(splash_scene);
main_stage.initStyle(StageStyle.TRANSPARENT);
main_stage.show();
}
public static void displayHomePage() throws Exception {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("views/HomeView.fxml"));
home_layout = loader.load();
home_scene = new Scene(home_layout);
home_stage = new Stage();
home_stage.setScene(home_scene);
home_stage.setMaximized(true);
home_stage.setTitle("Abscondo");
home_stage.getIcons().add(new Image("irie/views/assets/icon.png"));
home_stage.show();
main_stage.close();
}
public static void displaySignOut() throws Exception {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("views/SplashScreen.fxml"));
splash_layout = loader.load();
splash_scene = new Scene(splash_layout);
Stage signout_stage = new Stage();
signout_stage.setScene(splash_scene);
signout_stage.initStyle(StageStyle.TRANSPARENT);
signout_stage.show();
}
}
| [
"[email protected]"
] | |
0cc315d7790a9c6795a6f7bf25e69bac7f1d35b2 | 1f77145aef5fbf35344271322d9afce36e8c913d | /guns-vip-main/src/main/java/cn/stylefeng/guns/yinhua/admin/model/result/OrderPropNoteResult.java | 5a60a3167df8a8b12cc1fd175e3d529b2dfc3017 | [] | no_license | ShengHuaQian/guns-vip | b080f81da8ae1651403a9ef1315bd35dcc414d66 | b6e6cc56ce373c2d375dbecb819e0daccd66e06d | refs/heads/master | 2022-11-25T10:27:22.548231 | 2020-07-31T16:17:00 | 2020-07-31T16:17:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 668 | java | package cn.stylefeng.guns.yinhua.admin.model.result;
import lombok.Data;
import java.util.Date;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* <p>
*
* </p>
*
* @author xiexin
* @since 2020-03-14
*/
@Data
public class OrderPropNoteResult implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 生产单编号
*/
private String orderNum;
/**
* 是否完成
*/
private Integer flagDo;
/**
* 内容
*/
private String text;
/**
* 预计结束时间
*/
private Date overTime;
/**
* 名字
*/
private String userName;
}
| [
"[email protected]"
] | |
51e7e4405ea9e82ebf597be7bd1c140c4f390373 | 5f833db272928e1490ff62e8296c3d65b39c1992 | /modules/core/test/com/haulmont/cuba/core/SpringPersistenceTest.java | 2c57f8f1a19b615fd97f06c3b0d4daed121e9806 | [
"Apache-2.0"
] | permissive | cuba-platform/cuba-thesis | 4f1e563ec3f6ba3d1f252939af9de9ee217438e6 | 540baeedafecbc11d139e16cadefccb351e50e51 | refs/heads/master | 2021-01-08T16:58:33.119292 | 2017-05-25T06:23:01 | 2017-05-25T06:30:56 | 242,084,081 | 3 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,362 | java | /*
* Copyright (c) 2008-2016 Haulmont.
*
* 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.haulmont.cuba.core;
import com.haulmont.cuba.testsupport.TestContainer;
import org.junit.ClassRule;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SpringPersistenceTest {
@ClassRule
public static TestContainer cont = TestContainer.Common.INSTANCE;
@Test
public void test() {
Transaction tx = cont.persistence().createTransaction();
try {
EntityManager em = cont.persistence().getEntityManager();
em.setSoftDeletion(false);
assertFalse(em.isSoftDeletion());
nestedMethod();
nestedTxMethod();
em = cont.persistence().getEntityManager();
assertFalse(em.isSoftDeletion());
tx.commit();
} finally {
tx.end();
}
}
private void nestedMethod() {
EntityManager em = cont.persistence().getEntityManager();
assertFalse(em.isSoftDeletion());
}
private void nestedTxMethod() {
Transaction tx = cont.persistence().createTransaction();
try {
EntityManager em = cont.persistence().getEntityManager();
assertTrue(em.isSoftDeletion());
nestedTxMethod2();
tx.commit();
} finally {
tx.end();
}
}
private void nestedTxMethod2() {
Transaction tx = cont.persistence().createTransaction();
try {
EntityManager em = cont.persistence().getEntityManager();
assertTrue(em.isSoftDeletion());
tx.commit();
} finally {
tx.end();
}
}
}
| [
"[email protected]"
] | |
57a46b6fab34e498db7ea828827ae4d758e80807 | ba1f1dece609de547aa5d2b8bf5ee53913776504 | /_src/Chapter01/src/com/ioc/di/setter/BalanceSheet.java | e3ef27403b7cfe0ca0417d6936368ea7acb9b98e | [
"Apache-2.0",
"MIT"
] | permissive | paullewallencom/java-978-1-7882-9625-0 | 7d5d4394ab67faa14c2ebc26a5611101296a5d68 | 99fa2992eb46214c94d72465b0fe5c3f02fc64dd | refs/heads/main | 2023-02-14T02:23:43.043655 | 2020-12-27T00:48:53 | 2020-12-27T00:48:53 | 319,158,421 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 665 | java | package com.ioc.di.setter;
import java.util.List;
import com.ioc.di.IExportData;
import com.ioc.di.IFetchData;
public class BalanceSheet {
private IExportData exportDataObj= null;
private IFetchData fetchDataObj= null;
//Setter injection for Export Data
public void setExportDataObj(IExportData exportDataObj) {
this.exportDataObj = exportDataObj;
}
//Setter injection for Fetch Data
public void setFetchDataObj(IFetchData fetchDataObj) {
this.fetchDataObj = fetchDataObj;
}
public Object generateBalanceSheet(){
List<Object[]> dataLst = fetchDataObj.fetchData();
return exportDataObj.exportData(dataLst);
}
}
| [
"[email protected]"
] | |
6385e3ae189394597b6a927494f97f947b977a4c | 32197545c804daccd40eea4a2e1f49cd5e845740 | /sharding-sphere/sharding-jdbc-core/src/test/java/io/shardingjdbc/core/AllTests.java | b02dff243af1db1557c57de5ed62759abe3a22bd | [
"Apache-2.0"
] | permissive | dream7319/personal_study | 4235a159650dcbc7713a43d8be017d204ef3ecda | 19b49b00c9f682f9ef23d40e6e60b73772f8aad4 | refs/heads/master | 2020-03-18T17:25:04.225765 | 2018-07-08T11:54:41 | 2018-07-08T11:54:44 | 135,027,431 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 977 | java | /*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.core;
import io.shardingjdbc.core.integrate.AllIntegrateTests;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({
AllUnitTests.class,
AllIntegrateTests.class
})
public class AllTests {
}
| [
"[email protected]"
] | |
8dc40031a8152d331b5ddb21cf5cb018375553cb | 3283e61cedc185edfb7cf7867513275f4b242484 | /usbserial/src/main/java/com/lz/usbserial/driver/UsbSpiInterface.java | e55dcf7f33130e326a571478b7147f726093bc05 | [] | no_license | liuzhao1006/Serial_liuzhao | bd91c50021751d8025746c3f07ea31c3754101a9 | 50d49d6f3d50d942427e503f5ce01c904ea15b1a | refs/heads/master | 2020-04-13T12:01:06.806697 | 2019-04-25T01:44:17 | 2019-04-25T01:44:17 | 163,190,290 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 759 | java | package com.lz.usbserial.driver;
public interface UsbSpiInterface
{
// Clock dividers;
int DIVIDER_2 = 2;
int DIVIDER_4 = 4;
int DIVIDER_8 = 8;
int DIVIDER_16 = 16;
int DIVIDER_32 = 32;
int DIVIDER_64 = 64;
int DIVIDER_128 = 128;
// Common SPI operations
boolean connectSPI();
void writeMOSI(byte[] buffer);
void readMISO(int lengthBuffer);
void writeRead(byte[] buffer, int lenghtRead);
void setClock(int clockDivider);
void selectSlave(int nSlave);
void setMISOCallback(UsbMISOCallback misoCallback);
void closeSPI();
// Status information
int getClockDivider();
int getSelectedSlave();
interface UsbMISOCallback
{
int onReceivedData(byte[] data);
}
}
| [
"[email protected]"
] | |
21542f2725912dae5ec4d8c459f5b6749b8281f2 | 456c103b8b3d8a3e6268f48d1bd01e4e44fbd3db | /Project2/src/cn/han/myjob/utilsDatabase/ConnectionInstance.java | 65e5ddac158a1f08eafce3cda49bdeae4ef12b33 | [] | no_license | hxt532084126/Heaven | d73b56612bdd2a20b0eb5a0849c01ae917d7378e | 6662f6396e64f7e733da4266701ecce3bba4d606 | refs/heads/master | 2021-01-22T11:04:07.841236 | 2017-02-16T11:58:16 | 2017-02-16T11:58:16 | 82,064,249 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 879 | java | package cn.han.myjob.utilsDatabase;
import java.sql.Connection;
//获取连接器conn1,conn2,conn3
public class ConnectionInstance {
public Connection getConnection1(){
Connection conn1 = null;
try {
conn1 = DataSourceFactory.getConnection(DataSourceFactory.DataSourceName.test1_ds);
} catch (Exception e1) {
System.out.println(e1);
}
return conn1;
}
public Connection getConnection2(){
Connection conn2 = null;
try {
conn2 = DataSourceFactory.getConnection(DataSourceFactory.DataSourceName.test2_ds);
} catch (Exception e1) {
System.out.println(e1);
}
return conn2;
}
public Connection getConnection3(){
Connection conn3 = null;
try {
conn3 = DataSourceFactory.getConnection(DataSourceFactory.DataSourceName.test3_ds);
} catch (Exception e1) {
System.out.println(e1);
}
return conn3;
}
}
| [
"[email protected]"
] | |
668ab333b7afb6631b586446b5b173d38ffa1b21 | f8ba8ef475227de8ae069d278c0f1d6958d069ef | /src/main/java/com/github/admarc/validator/UniqueProperty.java | 024e0b7407ca8030f0b6e7634a9865e44d7083fa | [] | no_license | admarc/hydra | 49d18b9d3b81c312f0aa8a706f181ddaed7ebfd4 | f43490eda4ac6bcf95b58267baef1a539dc09d37 | refs/heads/master | 2022-06-05T12:25:36.281141 | 2019-11-04T21:50:00 | 2019-11-04T21:50:00 | 168,860,740 | 0 | 0 | null | 2019-11-04T21:50:01 | 2019-02-02T17:58:55 | Java | UTF-8 | Java | false | false | 656 | java | package com.github.admarc.validator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Documented
@Constraint(validatedBy = UniquePropertyValidator.class)
@Target({ ElementType.TYPE, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface UniqueProperty {
String name();
String message() default "Property value is not unique";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface List {
UniqueProperty[] value();
}
} | [
"[email protected]"
] | |
d87a81377e16a687636b9dbb747ee74208ec227b | 5c8b7185e2f3799cc66b6818aa4ee583485c7829 | /com/planet_ink/coffee_mud/Abilities/Spells/Spell_ForkedLightning.java | 040d393989e89fbc366302808dfa713b4fb22203 | [
"Apache-2.0"
] | permissive | cmk8514/BrainCancerMud | 6ec70a47afac7a9239a6181554ce309b211ed790 | cc2ca1defc9dd9565b169871c8310a3eece2500a | refs/heads/master | 2021-04-07T01:28:52.961472 | 2020-03-21T16:29:03 | 2020-03-21T16:29:03 | 248,631,086 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,664 | java | package com.planet_ink.coffee_mud.Abilities.Spells;
import java.util.List;
import java.util.Set;
import com.planet_ink.coffee_mud.Abilities.interfaces.Ability;
import com.planet_ink.coffee_mud.Common.interfaces.CMMsg;
import com.planet_ink.coffee_mud.Items.interfaces.Weapon;
import com.planet_ink.coffee_mud.MOBS.interfaces.MOB;
import com.planet_ink.coffee_mud.core.CMClass;
import com.planet_ink.coffee_mud.core.CMLib;
import com.planet_ink.coffee_mud.core.CMath;
import com.planet_ink.coffee_mud.core.interfaces.Physical;
/*
Copyright 2003-2017 Bo Zimmerman
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.
*/
public class Spell_ForkedLightning extends Spell
{
@Override
public String ID()
{
return "Spell_ForkedLightning";
}
private final static String localizedName = CMLib.lang().L("Forked Lightning");
@Override
public String name()
{
return localizedName;
}
@Override
public int maxRange()
{
return adjustedMaxInvokerRange(2);
}
@Override
public int abstractQuality()
{
return Ability.QUALITY_MALICIOUS;
}
@Override
public int classificationCode()
{
return Ability.ACODE_SPELL|Ability.DOMAIN_EVOCATION;
}
@Override
public long flags()
{
return Ability.FLAG_AIRBASED;
}
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final Set<MOB> h=properTargets(mob,givenTarget,auto);
if(h==null)
{
mob.tell(L("There doesn't appear to be anyone here worth electrocuting."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
if(mob.location().show(mob,null,this,verbalCastCode(mob,null,auto),L(auto?"A thunderous crack of lightning erupts!":"^S<S-NAME> invoke(s) a thunderous crack of forked lightning.^?")+CMLib.protocol().msp("lightning.wav",40)))
{
for (final Object element : h)
{
final MOB target=(MOB)element;
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),null);
final CMMsg msg2=CMClass.getMsg(mob,target,this,CMMsg.MSK_CAST_MALICIOUS_VERBAL|CMMsg.TYP_ELECTRIC|(auto?CMMsg.MASK_ALWAYS:0),null);
if((mob.location().okMessage(mob,msg))&&((mob.location().okMessage(mob,msg2))))
{
mob.location().send(mob,msg);
mob.location().send(mob,msg2);
invoker=mob;
final int maxDie=(int)Math.round(CMath.div(adjustedLevel(mob,asLevel)+(2*super.getX1Level(mob)),2.0));
int damage = CMLib.dice().roll(maxDie,7,1);
if((msg.value()>0)||(msg2.value()>0))
damage = (int)Math.round(CMath.div(damage,2.0));
if(target.location()==mob.location())
CMLib.combat().postDamage(mob,target,this,damage,CMMsg.MASK_ALWAYS|CMMsg.TYP_ELECTRIC,Weapon.TYPE_STRIKING,L("A bolt <DAMAGE> <T-NAME>!"));
}
}
}
}
else
return maliciousFizzle(mob,null,L("<S-NAME> attempt(s) to invoke a ferocious spell, but the spell fizzles."));
// return whether it worked
return success;
}
}
| [
"[email protected]"
] | |
97a2da1076413d05e6345010bbb74fad0bc4b5bf | 4af4ba14ea9cd3dab5098433e10dc19e8d27dd3c | /orders/orders-common/src/main/java/com/study/cloud/orderscommon/OrderOutput.java | 661412d38a88dfc6299bdb94a230e034f49a3d2b | [] | no_license | yngil/learn_spring_cloud | ced02c0b0100e114d3c9ba2c90cd4b7c9af73c40 | 8fae8f74d409cbaee15f5d6f4dc979184943d8e7 | refs/heads/master | 2020-06-29T16:56:00.599208 | 2019-09-06T09:30:09 | 2019-09-06T09:30:09 | 200,572,227 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 178 | java | package com.study.cloud.orderscommon;
import lombok.Data;
import java.util.Date;
@Data
public class OrderOutput {
private String orderCode;
private Date createTime;
}
| [
"[email protected]"
] | |
966490dee82d47c1ea396e413a3d70baa3fd1568 | a6aa78e28472878be55651e2cc86d9dfaf4601ce | /code/source/tundra/hjson.java | 6dc1c48f7ce7a867f26ff44832d5165f9be25ab6 | [
"MIT"
] | permissive | sasimanam/Tundra | e7a4be9787cfa836d3be5755d0533be1e001ccd1 | 5f241745d1fd1cf2625bef1418d05a85a4ff8dbd | refs/heads/master | 2021-05-02T07:48:12.083820 | 2018-01-09T02:36:08 | 2018-01-09T02:36:08 | 120,838,453 | 0 | 0 | null | 2018-02-09T01:08:16 | 2018-02-09T01:08:16 | null | UTF-8 | Java | false | false | 2,825 | java | package tundra;
// -----( IS Java Code Template v1.2
// -----( CREATED: 2017-05-07 10:50:33 EST
// -----( ON-HOST: 192.168.66.129
import com.wm.data.*;
import com.wm.util.Values;
import com.wm.app.b2b.server.Service;
import com.wm.app.b2b.server.ServiceException;
// --- <<IS-START-IMPORTS>> ---
import java.io.IOException;
import java.nio.charset.Charset;
import permafrost.tundra.data.IDataHelper;
import permafrost.tundra.data.IDataHjsonParser;
import permafrost.tundra.io.InputStreamHelper;
import permafrost.tundra.lang.CharsetHelper;
import permafrost.tundra.lang.ExceptionHelper;
import permafrost.tundra.lang.ObjectConvertMode;
import permafrost.tundra.lang.ObjectHelper;
// --- <<IS-END-IMPORTS>> ---
public final class hjson
{
// ---( internal utility methods )---
final static hjson _instance = new hjson();
static hjson _newInstance() { return new hjson(); }
static hjson _cast(Object o) { return (hjson)o; }
// ---( server methods )---
public static final void emit (IData pipeline)
throws ServiceException
{
// --- <<IS-START(emit)>> ---
// @subtype unknown
// @sigtype java 3.5
// [i] record:0:optional $document
// [i] - object:1:optional recordWithNoID
// [i] field:0:optional $encoding
// [i] field:0:optional $mode {"stream","bytes","string"}
// [o] object:0:optional $content
IDataCursor cursor = pipeline.getCursor();
try {
IData document = IDataHelper.get(cursor, "$document", IData.class);
Charset charset = IDataHelper.get(cursor, "$encoding", Charset.class);
ObjectConvertMode mode = IDataHelper.get(cursor, "$mode", ObjectConvertMode.class);
if (document != null) {
IDataHelper.put(cursor, "$content", ObjectHelper.convert(IDataHjsonParser.getInstance().emit(document, charset), charset, mode), false);
}
} catch (IOException ex) {
ExceptionHelper.raise(ex);
} finally {
cursor.destroy();
}
// --- <<IS-END>> ---
}
public static final void parse (IData pipeline)
throws ServiceException
{
// --- <<IS-START(parse)>> ---
// @subtype unknown
// @sigtype java 3.5
// [i] object:0:optional $content
// [i] field:0:optional $encoding
// [o] record:0:optional $document
// [o] - object:1:optional recordWithNoID
IDataCursor cursor = pipeline.getCursor();
try {
Object content = IDataHelper.get(cursor, "$content");
Charset charset = IDataHelper.get(cursor, "$encoding", Charset.class);
if (content != null) {
IDataHelper.put(cursor, "$document", IDataHjsonParser.getInstance().parse(InputStreamHelper.normalize(content, charset), charset), false);
}
} catch (IOException ex) {
ExceptionHelper.raise(ex);
} finally {
cursor.destroy();
}
// --- <<IS-END>> ---
}
}
| [
"[email protected]"
] | |
233feeb956690ce6616e7ce33b69e197ed24cbe6 | 40e49454c44e41bdc546f6e53629247b4d70094e | /src/com/javarush/test/level14/lesson08/home05/Keyboard.java | a8ff1b6c77f457ccb8af0a5d864eba772a02aee0 | [] | no_license | Senyacmd/JavaRushHomeWork | c5930cb7bccdd348b0ae07cba8e235c755ac8758 | 5825b8ce077a19cb8f48991380d1baa0e8e5c8b6 | refs/heads/master | 2021-01-13T08:36:38.183180 | 2016-10-28T22:11:26 | 2016-10-28T22:12:16 | 72,226,746 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 234 | java | package com.javarush.test.level14.lesson08.home05;
/**
* Created by Алексей on 12.04.2014.
*/
public class Keyboard implements CompItem
{
public String getName() {
return this.getClass().getSimpleName();
}
}
| [
"[email protected]"
] | |
733f1853527792708d2a460dda49210c7f8f212e | e45643b3b8cbacf608aacadb0dfd010c63bb45e4 | /gmall-sms/src/main/java/com/atguigu/gmall/sms/dao/SpuLadderDao.java | 4c9be73f484af18560abc9eba6d02a14ec23834c | [
"Apache-2.0"
] | permissive | jun1454495073/gmall | 17a147b9230fdb78755c1f39bf137e982902741d | 7cdcadc1decc2d98f538f23143e350a0b68a5f04 | refs/heads/master | 2022-12-19T22:12:26.158335 | 2020-01-06T11:20:13 | 2020-01-06T11:20:13 | 231,484,652 | 0 | 0 | Apache-2.0 | 2022-12-15T23:34:52 | 2020-01-03T00:54:46 | JavaScript | UTF-8 | Java | false | false | 382 | java | package com.atguigu.gmall.sms.dao;
import com.atguigu.gmall.sms.entity.SpuLadderEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 商品阶梯价格
*
* @author lixianfeng
* @email [email protected]
* @date 2020-01-04 11:55:45
*/
@Mapper
public interface SpuLadderDao extends BaseMapper<SpuLadderEntity> {
}
| [
"[email protected]"
] | |
fef96189c2fe044a4fcc1336185eb1577bfc746d | 491b3d8df8ad70b80cacb7464213785d19f8c052 | /app/src/main/java/com/geely/app/geelyapprove/common/utils/NetworkHttpManager.java | 4284fb02277afb6ab7e16e77acec5eb16d00e29d | [] | no_license | zwywan/OrientalPearlOA | ad15438c92640bc0719568809f71e02de2f048ae | ad52d51c164f5b1ad3eddf426a802647391fc527 | refs/heads/master | 2021-06-21T18:53:57.337420 | 2017-08-17T06:29:59 | 2017-08-17T06:29:59 | 100,437,080 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,059 | java | package com.geely.app.geelyapprove.common.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
public class NetworkHttpManager {
/**
* 判断是否有网络连接
*/
public boolean isNetworkConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable();
}
}
return false;
}
/**
* 判断wifi网络是否可用
*/
public boolean isWifiConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWiFiNetworkInfo = mConnectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWiFiNetworkInfo != null) {
return mWiFiNetworkInfo.isAvailable();
}
}
return false;
}
/**
* 判断mobile网络是否可用
*/
public boolean isMobileConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mMobileNetworkInfo = mConnectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mMobileNetworkInfo != null) {
return mMobileNetworkInfo.isAvailable();
}
}
return false;
}
/**
* 获取当前的网络状态 :没有网络-0:WIFI网络1:4G网络-4:3G网络-3:2G网络-2
* 自定义
*
* @param context
* @return
*/
public static int getAPNType(Context context) {
//结果返回值
int netType = 0;
//获取手机所有连接管理对象
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//获取NetworkInfo对象
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
//NetworkInfo对象为空 则代表没有网络
if (networkInfo == null) {
return netType;
}
//否则 NetworkInfo对象不为空 则获取该networkInfo的类型
int nType = networkInfo.getType();
if (nType == ConnectivityManager.TYPE_WIFI) {
//WIFI
netType = 1;
} else if (nType == ConnectivityManager.TYPE_MOBILE) {
int nSubType = networkInfo.getSubtype();
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//3G 联通的3G为UMTS或HSDPA 电信的3G为EVDO
if (nSubType == TelephonyManager.NETWORK_TYPE_LTE
&& !telephonyManager.isNetworkRoaming()) {
netType = 4;
} else if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
|| nSubType == TelephonyManager.NETWORK_TYPE_HSDPA
|| nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0
&& !telephonyManager.isNetworkRoaming()) {
netType = 3;
//2G 移动和联通的2G为GPRS或EGDE,电信的2G为CDMA
} else if (nSubType == TelephonyManager.NETWORK_TYPE_GPRS
|| nSubType == TelephonyManager.NETWORK_TYPE_EDGE
|| nSubType == TelephonyManager.NETWORK_TYPE_CDMA
&& !telephonyManager.isNetworkRoaming()) {
netType = 2;
} else {
netType = 2;
}
}
return netType;
}
}
| [
"[email protected]"
] | |
eb44ccdc5f18db9b6dd812c93f4e6b190bcb5788 | fa16ece8eee9fd8173c841bda4c66b32b7e45e54 | /app/src/androidTest/java/com/emomtimer/ExampleInstrumentedTest.java | fc9d874b53388e39f32cd14862c1905fe8e8ad28 | [] | no_license | telday/interval_timer | 46832580a5a598215abf8c5bc9e955841abefbf8 | 2686b1bd83736cb35404c515f51788e38579b778 | refs/heads/master | 2022-05-27T17:43:08.897869 | 2020-05-05T03:13:48 | 2020-05-05T03:13:48 | 257,136,988 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 710 | java | package com.emomtimer;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.emomtimer", appContext.getPackageName());
}
}
| [
"[email protected]"
] | |
86a72057009cca8b92373d1a7e10f5e70b978bb9 | 929ea06b1b8a224dc136a2b7d1bfd590e4886b5c | /src/main/java/ihavenotime/TransactionGateV3_1.java | 1bae07b8535dc2e9fd8ed5694946b5a5ddf779d3 | [] | no_license | gitter-badger/wewlc | ce000b2c0941c7c5ead82293bf3261bd121f6593 | 7536199269bb4aa81901694e306f18a67d661536 | refs/heads/master | 2020-12-26T01:29:05.373163 | 2014-09-03T07:04:31 | 2014-09-03T07:04:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,106 | java | package ihavenotime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import dependencies.Entry;
import dependencies.TransactionBundle;
public class TransactionGateV3_1 {
private TransactionBundle transactionBundle;
public TransactionGateV3_1(TransactionBundle transactionBundle) {
this.transactionBundle = transactionBundle;
}
// Example of 'Sprout Method' technique
public void postEntries(List<Entry> entries) {
List<Entry> entriesToAdd = uniqueEntries(entries);
for(Iterator<Entry> it = entriesToAdd.iterator(); it.hasNext();) {
Entry entry = it.next();
entry.postDate();
}
transactionBundle.getListManager().add(entriesToAdd);
}
// This is the 'Sprout Method'
private List<Entry> uniqueEntries(List<Entry> entries) {
List<Entry> result = new ArrayList<Entry>();
for (Iterator<Entry> it = entries.iterator(); it.hasNext();) {
Entry entry = (Entry) it.next();
if(!transactionBundle.getListManager().hasEntry(entry)) {
result.add(entry);
}
}
return result;
}
/*
* More code. Not shown to keep things simple.
*/
} | [
"[email protected]"
] | |
29f8acd40c8a89185e06ab45334cd59b936a79f7 | 87feb5cf057c3ae4066d773e0e5cfbe35757b0d9 | /jsf-app/src/main/java/dominio/ModeloAvaliacao.java | c238eb2e7d07b4e9e115e977a58fcd0951355570 | [] | no_license | thiagovtenorio/sgad | 33683d6562ed822c254be6dca10f78f3fc004ecc | 32e1d1de650ae19c07b07a2c31ae2f676899e790 | refs/heads/master | 2023-01-21T22:49:16.228205 | 2020-12-01T23:59:26 | 2020-12-01T23:59:26 | 288,261,163 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 652 | java | package dominio;
import java.util.ArrayList;
public class ModeloAvaliacao {
private int idModeloAvaliacao;
private String nome;
private ArrayList<ModeloAfirmativa> afirmativas;
public int getIdModeloAvaliacao() {
return idModeloAvaliacao;
}
public void setIdModeloAvaliacao(int idModeloAvaliacao) {
this.idModeloAvaliacao = idModeloAvaliacao;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public ArrayList<ModeloAfirmativa> getAfirmativas() {
return afirmativas;
}
public void setAfirmativas(ArrayList<ModeloAfirmativa> afirmativas) {
this.afirmativas = afirmativas;
}
}
| [
"[email protected]"
] | |
9ed5966d597a3eb3ca1208d05c6174760ed1d812 | 4813220d14cfcfc7001a14b9fd2979da0a611c2d | /src/controllers/order/WriteOrderInFileController.java | 1b9b43093f1ee0d5dae86b3052ffa302503abaaf | [] | no_license | Vitalij-prog/warehouseClient | 82c4afc51f13d54df7a6889de16e992f92e54f1c | 0ab960eda6af4b7fcb7857221480fc7f5a36973c | refs/heads/master | 2023-01-24T08:26:46.143935 | 2020-12-11T10:47:13 | 2020-12-11T10:47:13 | 310,833,550 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,507 | java | package controllers.order;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import sample.ClientSocket;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class WriteOrderInFileController {
@FXML
private Label orderIdLabel;
@FXML
private Button writeOrderButton;
@FXML
private Label successLabel;
int i = 0;
@FXML
public void initialize() {
orderIdLabel.setText(Integer.toString(ClientSocket.order.getId()));
orderIdLabel.setVisible(true);
writeOrderButton.setOnAction(event -> {
try {
if(i == 0) {
i++;
FileWriter fw = new FileWriter("./src/files/orders.txt", true);
String str = ClientSocket.order.getId() + "/" +
ClientSocket.order.getUser_name() + "/" +
ClientSocket.order.getProd_name() + "/" +
ClientSocket.order.getAmount() + "/" +
ClientSocket.order.getPrice() + "/" +
ClientSocket.order.getDate() + "\r\n";
fw.write(str);
fw.flush();
fw.close();
successLabel.setVisible(true);
writeOrderButton.setDisable(true);
}
} catch(IOException e) {
System.out.println(e);
}
});
}
}
| [
"[email protected]"
] | |
3bd8573da8dd38152ab2913c0c6feaf690d8833a | 28921a1faba8b61a076cca5857b12755537acffb | /example/android/app/src/main/java/com/vdian/flutter/hybridrouterexample/translucent/NoTranslucentActivity.java | 50265a23e0769b5656dcaf6592b850823fb37048 | [
"MIT"
] | permissive | weidian/hybrid_router | 42b7650a98444c5b35b80977586db15dcdb9e07f | 80d516ea9b55e796f22b8a2c680e11855b5c5b63 | refs/heads/develop | 2021-08-22T01:57:59.439627 | 2020-05-20T09:18:15 | 2020-05-20T09:18:15 | 185,332,968 | 152 | 9 | MIT | 2020-03-16T02:47:53 | 2019-05-07T06:15:31 | Java | UTF-8 | Java | false | false | 3,440 | java | // MIT License
// -----------
// Copyright (c) 2019 WeiDian Group
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
package com.vdian.flutter.hybridrouterexample.translucent;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import com.vdian.flutter.hybridrouter.page.FlutterRouteOptions;
import com.vdian.flutter.hybridrouterexample.FlutterExampleActivity;
import com.vdian.flutter.hybridrouterexample.R;
public class NoTranslucentActivity extends AppCompatActivity {
public static final String TAG = "FlutterLifecycle" + Build.VERSION.SDK_INT;
private static final int REQUEST_CODE = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG, "onCreate:" + this);
setContentView(R.layout.activity_notranslucent);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(NoTranslucentActivity.this, SetResultActivity.class), REQUEST_CODE);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Intent intent = FlutterExampleActivity.builder().route(new FlutterRouteOptions.Builder("example")
.setArgs("Jump from no translucent theme activity")
.build()).buildIntent(getApplicationContext());
startActivity(intent);
finish();
}
}
@Override
public void onStart() {
super.onStart();
Log.e(TAG, "onStart:" + this);
}
@Override
public void onResume() {
super.onResume();
Log.e(TAG, "onResume:" + this);
}
@Override
public void onPause() {
super.onPause();
Log.e(TAG, "onPause:" + this);
}
@Override
public void onStop() {
super.onStop();
Log.e(TAG, "onStop:" + this);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy:" + this);
}
}
| [
"[email protected]"
] | |
47064723a00e4ee2b91615cf6b1b844c577779ed | 6f36b8d606f99a7aca476aa9ec78aa751f298a13 | /src/main/java/com/qingfeng/leetcode/list/找出两个链表交点.java | 6fc3794f8fbefe99b0adc644838fdab6620c079b | [] | no_license | shihangqi/LeetCodePractice | d0685175d3a9b5d46ab47b084660a69e9af35e0a | 4fdc4dff37a225e67941e3cfc4f5336fb3226c1c | refs/heads/master | 2022-12-25T05:11:15.837118 | 2020-07-28T11:05:15 | 2020-07-28T11:05:15 | 278,619,745 | 0 | 0 | null | 2020-10-13T23:28:15 | 2020-07-10T11:44:55 | Java | UTF-8 | Java | false | false | 552 | java | package com.qingfeng.leetcode.list;
import common.ListNode;
/**
* @author shihangqi
* @ClassName: 找出两个链表交点
* @Description:
* @date 2020/7/21 6:51 下午
*/
public class 找出两个链表交点 {
//例如以下示例中 A 和 B 两个链表相交于 c1:
public ListNode process(ListNode headA, ListNode headB) {
ListNode l1 = headA, l2 = headB;
while (l1 != l2) {
l1 = (l1 == null) ? headB : l1.next;
l2 = (l2 == null) ? headA : l2.next;
}
return l1;
}
}
| [
"[email protected]"
] | |
2b8203d5cc5751ad66f78494ad3a3e6a4bbf1fe9 | 6c888f79464b401a928387f63295721521de0fda | /slideServlet02/src/main/java/com/fernandolle/mertins/servlets/Logout.java | f320c3dc2bbe18858d96a41b91a36b8a097b682e | [] | no_license | fernandOlle/NetBeansProjects | 8ec34c5174dff7e89954d26bf3fb3e0bc5a11c95 | 74ee126286f55d8f920ce801bcdf4fcaec588cd7 | refs/heads/master | 2023-05-13T18:29:55.679599 | 2021-05-28T17:54:35 | 2021-05-28T17:54:35 | 371,779,900 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,533 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.fernandolle.mertins.servlets;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author owzi
*/
//@WebServlet(name = "logout", urlPatterns = {"/logout"})
public class Logout extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
Cookie loginCookie = null;
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("logadoNaMerTIns")) {
cookie.setMaxAge(0);
resp.addCookie(loginCookie);
break;
}
}
}
// if (loginCookie != null) {
// loginCookie.setMaxAge(0);
// resp.addCookie(loginCookie);
// }
RequestDispatcher dispBackward = req.getRequestDispatcher("/");
dispBackward.forward(req, resp);
}
}
| [
"[email protected]"
] | |
cdaf11ec52703779ad79b8f6ecc2274bc9c1e3b4 | a004b79be8ed73ffcf2e064fd900f9830dc31272 | /src/creational/abstractfactory/AbstractFactoryExample.java | 3c4f51a4fdb804aae0ce80a45406e25393286abb | [] | no_license | Sowaznebrowa/GunDesignPatterns | 003e27d6f69ff7f0e41479c35bdc21053c2c6b2d | c873261047f3ee0755df12e82491e0ab9b317f72 | refs/heads/master | 2022-05-20T18:09:34.036322 | 2020-04-20T11:24:56 | 2020-04-20T11:24:56 | 256,859,055 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 638 | java | package creational.abstractfactory;
import java.util.List;
import java.util.Random;
public class AbstractFactoryExample {
public static void print(){
String randomName = List.of("walther", "lucznik").get(new Random().nextInt(2));
// get the gun factory for a name
GunFactory factory = GunFactoryProducer.getFactory(randomName);
// use the random factory to create the rifle
Rifle rifle = factory.getRifle();
rifle.printDescription();
// use the random factory to create the pistol
Pistol pistol = factory.getPistol();
pistol.printDescription();
}
}
| [
"[email protected]"
] | |
96189c585adee18c548997b8431cfa782fd34c63 | e601d79823b855026fabe9c97e816c5b2a6819a2 | /authorize/src/main/java/com/wang/authorize/service/impl/LogServiceImpl.java | d26225111a6f5e7282fbaa7c3ac9b384519dead9 | [] | no_license | wangjunhao330/cloud | d6e3331df08732ef910b9ab2b703c3a5b77794c5 | d2f0f25a2660979b732b742e368f72dea7fface8 | refs/heads/master | 2022-11-20T05:21:32.889685 | 2020-04-27T14:06:37 | 2020-04-27T14:06:37 | 230,350,849 | 0 | 0 | null | 2022-11-15T23:35:19 | 2019-12-27T01:22:10 | Java | UTF-8 | Java | false | false | 1,665 | java | package com.wang.authorize.service.impl;
import com.wang.authorize.entity.User;
import com.wang.authorize.jwtUtils.JwtUtils;
import com.wang.authorize.service.LogService;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
* 登录相关service实现类
* 用于获取token、
*
* @author wangjunhao
* @version 1.0
* @date 2020/1/4 19:01
* @since JDK 1.8
*/
@Service(value = "logService")
public class LogServiceImpl implements LogService {
private Logger logger = LoggerFactory.getLogger(LogServiceImpl.class);
@Autowired
private JwtUtils jwtUtils;
@Override
public String getToken(User user) {
Map<String, Object> map = new HashMap<>(4);
map.put("username", user.getUsernmae());
map.put("roleId", user.getRoleId());
return jwtUtils.createJwt(user.getUserId() + "", user.getUsernmae(), map, "login");
}
@Override
public User parseToken(String token) {
if (null == token) {
return null;
}
Claims claims = jwtUtils.parseJwt(token);
return claimsToUser(claims);
}
/**
* 将claims内容装换为user实体类
*
* @param claims
* @return com.wang.authorize.entity.User
* @throws
* @Date 2020/1/5 14:47
* @Author wangjunhao
**/
private User claimsToUser(Claims claims) {
User user = new User();
user.setUsernmae(claims.get("usernmae", String.class));
return user;
}
}
| [
"[email protected]"
] | |
ed3539f93aed5f264adde2ee3f14c3077596530d | a28a2e3792ebf56408a55a4a990002acd5b4dd43 | /konig-core/src/main/java/io/konig/formula/DirectionStep.java | 79f597ce4c6cc0a35c034daf45c541df27e052ac | [] | no_license | zednis/konig | e01a77e40bf934af928b457f3afc0d1f2bc2e623 | 9b3e52f0fe53fec7ce2ffcf239d33256b4067a44 | refs/heads/master | 2021-07-11T18:11:06.415290 | 2017-10-12T11:51:43 | 2017-10-12T11:51:43 | 106,723,389 | 0 | 0 | null | 2017-10-12T17:19:14 | 2017-10-12T17:19:14 | null | UTF-8 | Java | false | false | 1,414 | java | package io.konig.formula;
/*
* #%L
* Konig Core
* %%
* Copyright (C) 2015 - 2017 Gregory McFall
* %%
* 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.
* #L%
*/
import io.konig.core.io.PrettyPrintWriter;
public class DirectionStep extends AbstractFormula implements PathStep {
private Direction direction;
private PathTerm term;
public DirectionStep(Direction direction, PathTerm term) {
this.direction = direction;
this.term = term;
}
public Direction getDirection() {
return direction;
}
public PathTerm getTerm() {
return term;
}
@Override
public void print(PrettyPrintWriter out) {
if (!(term instanceof VariableTerm)) {
direction.print(out);
}
term.print(out);
}
@Override
public void dispatch(FormulaVisitor visitor) {
visitor.enter(this);
direction.dispatch(visitor);
term.dispatch(visitor);
visitor.exit(this);
}
}
| [
"[email protected]"
] | |
12aee71a65008e9e979b266ea1fb398611ab4709 | 5613e52ded235aa33f2dc744e8c6bb04d9cbcf4c | /master/working/player/Plookify-5/src/trackplayer/OoController.java | 147645605c2018b1b9ace29d137caa6c53bec253 | [] | no_license | salmansamie/Plookify | 11a66fd66c3c56fc78e00f49b2faf193fa23a2c7 | 27e57f89a4a1c9210b5d37ee2978eea83d1a127e | refs/heads/master | 2021-03-19T12:09:48.139086 | 2016-12-26T23:13:52 | 2016-12-26T23:13:52 | 77,410,774 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,616 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package trackplayer;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.Tab;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
/**
* FXML Controller class
*
* @author Zilan Su
*/
public class OoController implements Initializable {
private BorderPane tets1;
private Tab radio;
@FXML
private BorderPane pPnae;
@FXML
private Tab rPane;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
Parent root1,root2,root3;
//Integrating other group members work
try {
root1 = FXMLLoader.load(getClass().getResource("player.fxml"));
pPnae.setBottom(root1);
root2 = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
pPnae.setTop(root2);
// root3 = FXMLLoader.load(getClass().getResource("RadioFXML.fxml"));
// rPane.setContent(root3);
} catch (IOException ex) {
Logger.getLogger(OoController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| [
"[email protected]"
] | |
3857b26f41af43a8311926b0d3037f1ea665dc9c | ea96bc0aabfcf781219309c1e16a2fb04e4aafd6 | /app/src/main/java/com/dreamgyf/dim/bizpage/splash/presenter/SplashPresenter.java | 781a846d6eee40cee8915b525d2966d5748ecdb1 | [] | no_license | dreamgyf/Dim | 1fb466fc47f46a9b0c48f12763873dc5120d5c98 | cd4ff3a3dc6a3c51c6b7c2f2a14ec89cc6c94eb8 | refs/heads/master | 2021-01-03T20:56:47.976016 | 2020-10-14T07:50:21 | 2020-10-14T07:50:21 | 240,233,061 | 6 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,698 | java | package com.dreamgyf.dim.bizpage.splash.presenter;
import android.app.Activity;
import android.content.Intent;
import android.widget.Toast;
import com.dreamgyf.dim.bizpage.main.view.MainActivity;
import com.dreamgyf.dim.base.http.exception.HttpRespException;
import com.dreamgyf.dim.base.http.exception.NetworkConnectException;
import com.dreamgyf.dim.base.mqtt.exception.MqttConnectException;
import com.dreamgyf.dim.base.mvp.presenter.BasePresenter;
import com.dreamgyf.dim.bizpage.login.listener.OnLoginListener;
import com.dreamgyf.dim.bizpage.login.model.LoginModel;
import com.dreamgyf.dim.bizpage.login.view.LoginActivity;
import com.dreamgyf.dim.sharedpreferences.DataAccessUtils;
import com.dreamgyf.dim.bizpage.splash.model.SplashModel;
import com.dreamgyf.dim.bizpage.splash.view.SplashActivity;
import com.dreamgyf.dim.utils.PermissionsUtils;
import java.util.Map;
import retrofit2.HttpException;
public class SplashPresenter extends BasePresenter<SplashModel, SplashActivity> implements ISplashPresenter {
private Activity mActivity;
public SplashPresenter(SplashActivity view) {
super(view);
}
@Override
protected void onAttach() {
mActivity = getView();
verifyPermissions();
}
@Override
protected void onDetach() {
}
@Override
protected SplashModel bindModel() {
return new SplashModel();
}
@Override
public void verifyPermissions() {
if(!PermissionsUtils.verifyStoragePermissions(mActivity)) {
tryLogin();
}
}
@Override
public void tryLogin() {
Map<String, String> userInfo = DataAccessUtils.getUserAccount(mActivity);
if (userInfo.get("username") != null) {
LoginModel loginModel = new LoginModel();
loginModel.setOnLoginListener(new OnLoginListener() {
@Override
public void onLoginSuccess(String username, String passwordSha256) {
Intent intent = new Intent(mActivity, MainActivity.class);
mActivity.startActivity(intent);
mActivity.finish();
}
@Override
public void onLoginFailed(Throwable t) {
Toast toast = Toast.makeText(mActivity, null, Toast.LENGTH_SHORT);
if (t instanceof NetworkConnectException || t instanceof HttpRespException || t instanceof HttpException || t instanceof MqttConnectException) {
toast.setText(t.getMessage());
} else {
toast.setText("未知错误");
}
toast.show();
Intent intent = new Intent(mActivity, LoginActivity.class);
mActivity.startActivity(intent);
mActivity.finish();
}
});
loginModel.login(userInfo.get("username"), userInfo.get("password"));
} else {
Intent intent = new Intent(mActivity, LoginActivity.class);
mActivity.startActivity(intent);
mActivity.finish();
}
}
}
| [
"[email protected]"
] | |
12d656f9609c6578601026e9ff8f361f0db8eb84 | 6f72e08ffd9c49e150000aa5c06f063449b9b981 | /src/main/java/br/com/aleandro/Startup.java | 6866f3eee38510df2624e3a4640147db966bb515 | [] | no_license | aleandrodalan/RestWithSpringBootUdemy | 5347e8044e45323386ae1e4d0eae80627152752e | c421e62dadbdbf6e94cf212902e65410ba68c8ec | refs/heads/master | 2020-12-23T10:28:40.436051 | 2020-08-24T20:04:51 | 2020-08-24T20:04:51 | 237,124,268 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 287 | java | package br.com.aleandro;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Startup {
public static void main(String[] args) {
SpringApplication.run(Startup.class, args);
}
}
| [
"[email protected]"
] | |
0cb0d574a2d6ebaca5eb217e0cb36cafba9eaefa | 63b01f913445f88e596198f0603d8ef843e506ca | /src/main/java/com/vitiger/comcast/genericUtility/WebDriverUtility.java | e0be31652991614e9cee3c58fcb208c8c5fee237 | [] | no_license | cchaitra-arasi/SDET-20 | 876cdb88eb1b7baebea02a960604c9acaabfdffd | 02eb44b1c51617e97ceed4cb5e50dd7942e820bf | refs/heads/master | 2023-07-17T13:55:53.114168 | 2021-08-29T19:55:41 | 2021-08-29T19:55:41 | 401,128,112 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,207 | java | package com.vitiger.comcast.genericUtility;
import java.io.File;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.google.common.io.Files;
/**
*
* This class contains webdriver specific generic methods
* @author Admin
*
*/
public class WebDriverUtility {
/**
* this method wait for 20 sec for page loading
* @param driver
*/
public void waitUntilPageLoad(WebDriver driver)
{
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
/**
* This method wait for the element to be visible
* @param driver
* @param element
*/
public void waitForElementVisibility(WebDriver driver,WebElement element)
{
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOf(element));
}
/**
* This method wait for the element to be clicked , its custom wait created to avoid elemenInterAceptable Exception
* @param element
* @throws InterruptedException
*/
public void waitAndClick(WebElement element) throws InterruptedException
{
int count = 0;
while(count<20) {
try {
element.click();
break;
}catch(Throwable e){
Thread.sleep(1000);
count++;
}
}
}
/**
* this methods enables user to handle dropdown using visible text
* @param element
* @param option
*/
public void select(WebElement element, String option)
{
Select select=new Select(element);
select.selectByVisibleText(option);
}
/**
* this methods enables user to handle dropdown using index
* @param element
* @param index
*/
public void select(WebElement element, int index)
{
Select select=new Select(element);
select.selectByIndex(index);
}
/**
* This method will perform mouse over action
* @param driver
* @param element
*/
public void mouseOver(WebDriver driver,WebElement element)
{
Actions act = new Actions(driver);
act.moveToElement(element).perform();
}
/**
* This method performs right click operation
* @param driver
* @param element
*/
public void rightClick(WebDriver driver,WebElement element)
{
Actions act = new Actions(driver);
act.contextClick(element).perform();
}
/**
* This method helps to switch from one window to another
* @param driver
* @param partialWinTitle
*/
public void switchToWindow(WebDriver driver, String partialWinTitle)
{
Set<String> window = driver.getWindowHandles();
Iterator<String> it = window.iterator();
while(it.hasNext())
{
String winId=it.next();
String title=driver.switchTo().window(winId).getTitle();
if(title.contains(partialWinTitle))
{
break;
}
}
}
/**
* Accept alert
* @param driver
*/
public void acceptAlert(WebDriver driver)
{
driver.switchTo().alert().accept();
}
/**
* Cancel Alert
* @param driver
*/
public void cancelAlert(WebDriver driver)
{
driver.switchTo().alert().dismiss();
}
/**
* This method used for scrolling action in a webpage
* @param driver
* @param element
*/
public void scrollToWebElement(WebDriver driver, WebElement element) {
JavascriptExecutor js=(JavascriptExecutor)driver;
int y= element.getLocation().getY();
js.executeScript("window.scrollBy(0,"+y+")", element);
}
public void switchFrame(WebDriver driver,int index) {
driver.switchTo().frame(index);
}
public void switchFrame(WebDriver driver,WebElement element) {
driver.switchTo().frame(element);
}
public void switchFrame(WebDriver driver,String idOrName) {
driver.switchTo().frame(idOrName);
}
public void takeScreenshot(WebDriver driver, String screenshotName) throws Throwable {
TakesScreenshot ts=(TakesScreenshot)driver;
File src=ts.getScreenshotAs(OutputType.FILE);
File dest=new File(" "+screenshotName+".PNG");
Files.copy(src, dest);
}
/**
* pass enter Key appertain in to Browser
* @param driver
*/
public void passEnterKey(WebDriver driver) {
Actions act = new Actions(driver);
act.sendKeys(Keys.ENTER).perform();
}
}
| [
"Admin@DESKTOP-1U8B136"
] | Admin@DESKTOP-1U8B136 |
c335bd7d92119d3cc1062cefc728e328fcbe42bc | 48e835e6f176a8ac9ae3ca718e8922891f1e5a18 | /benchmark/training/org/geoserver/security/web/jdbc/group/JDBCGroupListPageTest.java | 9a3ef3dc2f5eca0bea96922e73234c6c3528c631 | [] | no_license | STAMP-project/dspot-experiments | f2c7a639d6616ae0adfc491b4cb4eefcb83d04e5 | 121487e65cdce6988081b67f21bbc6731354a47f | refs/heads/master | 2023-02-07T14:40:12.919811 | 2019-11-06T07:17:09 | 2019-11-06T07:17:09 | 75,710,758 | 14 | 19 | null | 2023-01-26T23:57:41 | 2016-12-06T08:27:42 | null | UTF-8 | Java | false | false | 791 | java | /**
* (c) 2014 Open Source Geospatial Foundation - all rights reserved
* (c) 2001 - 2013 OpenPlans
* This code is licensed under the GPL 2.0 license, available at the root
* application directory.
*/
package org.geoserver.security.web.jdbc.group;
import org.geoserver.security.web.group.GroupListPageTest;
import org.junit.Test;
public class JDBCGroupListPageTest extends GroupListPageTest {
@Test
public void testRemoveWithRoles() throws Exception {
withRoles = true;
addAdditonalData();
doRemove(((getTabbedPanelPath()) + ":panel:header:removeSelectedWithRoles"));
}
@Test
public void testRemoveJDBC() throws Exception {
addAdditonalData();
doRemove(((getTabbedPanelPath()) + ":panel:header:removeSelected"));
}
}
| [
"[email protected]"
] | |
cfc3d9b2664f9a62414696bf5502718f39bc83f2 | 256a3596eb3a9c694d2015b173c51b4e20b82ae0 | /DailyRhythmPortal/drp-ws-client/target/generated-sources/wsimport/com/bestbuy/bbym/ise/iseclientucs/NotificationStatusWithCachedUpgradeCheckPutRequest.java | ec49c447f6cf6adfdcb36b922e7697b35d20967b | [] | no_license | sellasiyer/maven-drp | a8487325586bb6018d08a6cdb4078ce0ef5d5989 | cbbab7027e1ee64cdaf9956a82c6ad964bb9ec86 | refs/heads/master | 2021-01-01T19:15:47.427243 | 2012-11-03T13:04:14 | 2012-11-03T13:04:14 | 5,146,773 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,485 | java |
package com.bestbuy.bbym.ise.iseclientucs;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for NotificationStatusWithCachedUpgradeCheckPutRequest complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="NotificationStatusWithCachedUpgradeCheckPutRequest">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="subscriberStatuses" type="{http://bestbuy.com/bbym/ucs}SubscriberNotificationStatus" maxOccurs="unbounded"/>
* <element name="mobilePhoneNumber" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="zip" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="internationalBusinessHierarchy" type="{http://bestbuy.com/bbym/ucs}InternationalBusinessHierarchy"/>
* <element name="sourceSystem" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="capTransactionId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="locationId" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="userId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="language" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "NotificationStatusWithCachedUpgradeCheckPutRequest", propOrder = {
"subscriberStatuses",
"mobilePhoneNumber",
"zip",
"internationalBusinessHierarchy",
"sourceSystem",
"capTransactionId",
"locationId",
"userId",
"language"
})
public class NotificationStatusWithCachedUpgradeCheckPutRequest {
@XmlElement(required = true)
protected List<SubscriberNotificationStatus> subscriberStatuses;
@XmlElement(required = true)
protected String mobilePhoneNumber;
@XmlElement(required = true)
protected String zip;
@XmlElement(required = true)
protected InternationalBusinessHierarchy internationalBusinessHierarchy;
@XmlElement(required = true)
protected String sourceSystem;
@XmlElement(required = true)
protected String capTransactionId;
protected int locationId;
protected String userId;
protected String language;
/**
* Gets the value of the subscriberStatuses property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the subscriberStatuses property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSubscriberStatuses().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SubscriberNotificationStatus }
*
*
*/
public List<SubscriberNotificationStatus> getSubscriberStatuses() {
if (subscriberStatuses == null) {
subscriberStatuses = new ArrayList<SubscriberNotificationStatus>();
}
return this.subscriberStatuses;
}
/**
* Gets the value of the mobilePhoneNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMobilePhoneNumber() {
return mobilePhoneNumber;
}
/**
* Sets the value of the mobilePhoneNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMobilePhoneNumber(String value) {
this.mobilePhoneNumber = value;
}
/**
* Gets the value of the zip property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getZip() {
return zip;
}
/**
* Sets the value of the zip property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setZip(String value) {
this.zip = value;
}
/**
* Gets the value of the internationalBusinessHierarchy property.
*
* @return
* possible object is
* {@link InternationalBusinessHierarchy }
*
*/
public InternationalBusinessHierarchy getInternationalBusinessHierarchy() {
return internationalBusinessHierarchy;
}
/**
* Sets the value of the internationalBusinessHierarchy property.
*
* @param value
* allowed object is
* {@link InternationalBusinessHierarchy }
*
*/
public void setInternationalBusinessHierarchy(InternationalBusinessHierarchy value) {
this.internationalBusinessHierarchy = value;
}
/**
* Gets the value of the sourceSystem property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSourceSystem() {
return sourceSystem;
}
/**
* Sets the value of the sourceSystem property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSourceSystem(String value) {
this.sourceSystem = value;
}
/**
* Gets the value of the capTransactionId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCapTransactionId() {
return capTransactionId;
}
/**
* Sets the value of the capTransactionId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCapTransactionId(String value) {
this.capTransactionId = value;
}
/**
* Gets the value of the locationId property.
*
*/
public int getLocationId() {
return locationId;
}
/**
* Sets the value of the locationId property.
*
*/
public void setLocationId(int value) {
this.locationId = value;
}
/**
* Gets the value of the userId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUserId() {
return userId;
}
/**
* Sets the value of the userId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUserId(String value) {
this.userId = value;
}
/**
* Gets the value of the language property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLanguage() {
return language;
}
/**
* Sets the value of the language property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLanguage(String value) {
this.language = value;
}
}
| [
"[email protected]"
] | |
82c4d211ce4a3e853a9caa8f54bf4b8045abcd7a | 1cb6996ca1a3ddfca95748217c12d83abcbf88e2 | /src/team_play/MoveParser.java | 166df260ddbe331f7b100589f9dd8ffbb792f443 | [] | no_license | garrett92895/PRO180---Assignments | 5693e04074ebdda908d92e7ea4038cdce01062e7 | f5e2da9205d042180750a52af9737dcb7459d56b | refs/heads/master | 2016-09-11T10:13:16.226973 | 2014-06-10T19:41:55 | 2014-06-10T19:41:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,652 | java | package team_play;
public class MoveParser {
private static PieceMap h = new PieceMap();
public Directive parseMove(String[] chessMoves)
{
Directive returnDirective = null;
//Output depends on the number of directives
switch(chessMoves.length)
{
case 1:
returnDirective = new PlaceDirective(
chessMoves[0].charAt(0),
chessMoves[0].charAt(1),
chessMoves[0].charAt(2) - 'a',
Math.abs(Character.getNumericValue(chessMoves[0].charAt(3)) - 8));
break;
case 2:
if(chessMoves[1].endsWith("*"))
{
returnDirective = new CaptureDirective(
chessMoves[0].charAt(0) - 'a',
Math.abs(Character.getNumericValue(chessMoves[0].charAt(1)) - 8),
chessMoves[1].charAt(0) - 'a',
Math.abs(Character.getNumericValue(chessMoves[1].charAt(1)) - 8));
}
else
{
returnDirective = new MoveDirective(
chessMoves[0].charAt(0) - 'a',
Math.abs(Character.getNumericValue(chessMoves[0].charAt(1)) - 8),
chessMoves[1].charAt(0) - 'a',
Math.abs(Character.getNumericValue(chessMoves[1].charAt(1)) - 8));
}
break;
case 4:
returnDirective = new CastleDirective(
chessMoves[0].charAt(0) - 'a',
Math.abs(Character.getNumericValue(chessMoves[0].charAt(1)) - 8),
chessMoves[1].charAt(0) - 'a',
Math.abs(Character.getNumericValue(chessMoves[1].charAt(1)) - 8),
new MoveDirective(
chessMoves[2].charAt(0) - 'a',
Math.abs(Character.getNumericValue(chessMoves[2].charAt(1)) - 8),
chessMoves[3].charAt(0) - 'a',
Math.abs(Character.getNumericValue(chessMoves[3].charAt(1)) - 8))
);
}
return returnDirective;
}
}
| [
"[email protected]"
] | |
1a486164fcc2b7f6e73fd4140d98a00827ae11ef | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/11/11_97d13894106c117ce2835c7fb155f8e0fbf4a7d1/Instances/11_97d13894106c117ce2835c7fb155f8e0fbf4a7d1_Instances_s.java | 7280f5e791196badb3c246d9bef365c8456178a8 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 12,299 | java | /**
* Copyright (c) 2012-2013, JCabi.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the jcabi.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jcabi.mysql.maven.plugin;
import com.jcabi.aspects.Loggable;
import com.jcabi.log.Logger;
import com.jcabi.log.VerboseProcess;
import com.jcabi.log.VerboseRunnable;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import javax.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.CharEncoding;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
/**
* Running instances of MySQL.
*
* <p>The class is thread-safe.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
* @since 0.1
* @checkstyle ClassDataAbstractionCoupling (500 lines)
* @checkstyle MultipleStringLiterals (500 lines)
*/
@ToString
@EqualsAndHashCode(of = "processes")
@Loggable(Loggable.INFO)
@SuppressWarnings("PMD.DoNotUseThreads")
final class Instances {
/**
* User.
*/
private static final String USER = "root";
/**
* Password.
*/
private static final String PASSWORD = "root";
/**
* Database name.
*/
private static final String DBNAME = "root";
/**
* Running processes.
*/
private final transient ConcurrentMap<Integer, Process> processes =
new ConcurrentHashMap<Integer, Process>(0);
/**
* Start a new one at this port.
* @param port The port to start at
* @param dist Path to MySQL distribution
* @param target Where to keep temp data
* @throws IOException If fails to start
*/
public void start(final int port, @NotNull final File dist,
@NotNull final File target) throws IOException {
synchronized (this.processes) {
if (this.processes.containsKey(port)) {
throw new IllegalArgumentException(
String.format("port %d is already busy", port)
);
}
final Process proc = this.process(port, dist, target);
this.processes.put(port, proc);
Runtime.getRuntime().addShutdownHook(
new Thread(
new Runnable() {
@Override
public void run() {
Instances.this.stop(port);
}
}
)
);
}
}
/**
* Stop a running one at this port.
* @param port The port to stop at
*/
public void stop(final int port) {
synchronized (this.processes) {
final Process proc = this.processes.get(port);
if (proc != null) {
proc.destroy();
this.processes.remove(proc);
}
}
}
/**
* Start a new process.
* @param port The port to start at
* @param dist Path to MySQL distribution
* @param target Where to keep temp data
* @return Process started
* @throws IOException If fails to start
*/
private Process process(final int port, final File dist, final File target)
throws IOException {
if (target.exists()) {
FileUtils.deleteDirectory(target);
Logger.info(this, "deleted %s directory", target);
}
if (target.mkdirs()) {
Logger.info(this, "created %s directory", target);
}
new File(target, "temp").mkdirs();
final File socket = new File(target, "mysql.sock");
final ProcessBuilder builder = this.builder(
dist,
"bin/mysqld",
"--general_log",
"--console",
"--innodb_buffer_pool_size=64M",
"--innodb_log_file_size=64M",
"--log_warnings",
String.format("--binlog-ignore-db=%s", Instances.DBNAME),
String.format("--basedir=%s", dist),
String.format("--lc-messages-dir=%s", new File(dist, "share")),
String.format("--datadir=%s", this.data(dist, target)),
String.format("--tmpdir=%s", new File(target, "temp")),
String.format("--socket=%s", socket),
String.format("--pid-file=%s", new File(target, "mysql.pid")),
String.format("--port=%d", port)
).redirectErrorStream(true);
builder.environment().put("MYSQL_HOME", dist.getAbsolutePath());
final Process proc = builder.start();
final Thread thread = new Thread(
new VerboseRunnable(
new Callable<Void>() {
@Override
public Void call() throws Exception {
new VerboseProcess(proc).stdout();
return null;
}
}
)
);
thread.setDaemon(true);
thread.start();
this.configure(dist, port, this.waitFor(socket, port));
return proc;
}
/**
* Prepare and return data directory.
* @param dist Path to MySQL distribution
* @param target Where to create it
* @return Directory created
* @throws IOException If fails
*/
private File data(final File dist, final File target) throws IOException {
final File dir = new File(target, "data");
if (SystemUtils.IS_OS_WINDOWS) {
FileUtils.copyFile(
new File(dist, "my-default.ini"),
new File(dist, "support-files/my-default.cnf")
);
}
new VerboseProcess(
this.builder(
dist,
"scripts/mysql_install_db",
"--no-defaults",
"--force",
String.format("--datadir=%s", dir)
)
).stdout();
return dir;
}
/**
* Wait for this file to become available.
* @param socket The file to wait for
* @param port Port to wait for
* @return The same socket, but ready for usage
* @throws IOException If fails
*/
private File waitFor(final File socket, final int port) throws IOException {
final long start = System.currentTimeMillis();
long age = 0;
while (true) {
if (socket.exists()) {
Logger.info(
this,
"socket %s is available after %[ms]s of waiting",
socket, age
);
break;
}
if (Instances.isOpen(port)) {
Logger.info(
this,
"port %s is available after %[ms]s of waiting",
port, age
);
break;
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new IllegalStateException(ex);
}
age = System.currentTimeMillis() - start;
if (age > TimeUnit.MINUTES.toMillis(1)) {
throw new IOException(
Logger.format(
"socket %s is not available after %[ms]s of waiting",
socket, age
)
);
}
}
return socket;
}
/**
* Configure the running MySQL server.
* @param dist Directory with MySQL distribution
* @param port The port it's running on
* @param socket Socket of it
* @throws IOException If fails
*/
private void configure(final File dist, final int port, final File socket)
throws IOException {
new VerboseProcess(
this.builder(
dist,
"bin/mysqladmin",
String.format("--port=%d", port),
String.format("--user=%s", Instances.USER),
String.format("--socket=%s", socket),
"--host=127.0.0.1",
"password",
Instances.PASSWORD
)
).stdout();
final Process process = this.builder(
dist,
"bin/mysql",
String.format("--port=%d", port),
String.format("--user=%s", Instances.USER),
String.format("--password=%s", Instances.PASSWORD),
String.format("--socket=%s", socket)
).start();
final PrintWriter writer = new PrintWriter(
new OutputStreamWriter(
process.getOutputStream(), CharEncoding.UTF_8
)
);
writer.print("CREATE DATABASE ");
writer.print(Instances.DBNAME);
writer.println(";");
writer.close();
new VerboseProcess(process).stdout();
}
/**
* Make process builder with this commands.
* @param dist Distribution directory
* @param name Name of the cmd to run
* @param cmds Commands
* @return Process builder
*/
private ProcessBuilder builder(final File dist, final String name,
final String... cmds) {
String label = name;
final Collection<String> commands = new LinkedList<String>();
if (!new File(dist, label).exists()) {
label = String.format("%s.exe", name);
if (!new File(dist, label).exists()) {
label = String.format("%s.pl", name);
commands.add("perl");
}
}
commands.add(new File(dist, label).getAbsolutePath());
commands.addAll(Arrays.asList(cmds));
Logger.info(this, "$ %s", StringUtils.join(commands, " "));
return new ProcessBuilder()
.command(commands.toArray(new String[commands.size()]))
.directory(dist);
}
/**
* Port is open.
* @param port The port to check
* @return TRUE if it's open
*/
private static boolean isOpen(final int port) {
boolean open;
try {
new Socket((String) null, port);
open = true;
} catch (IOException ex) {
open = false;
}
return open;
}
}
| [
"[email protected]"
] | |
9768f052842c3afb925a4641e395494f01d82231 | 92e1ffd5222afd335ea4a29c619f6e0b43740d0e | /src/amat/report/PropertyReport.java | ff666a12eefb30be8a6133427d7f16aab3039de8 | [
"Apache-2.0"
] | permissive | tipplerow/amat | 5e0d215065bd8653db26659b449c06df4d3a9ab4 | 353f07c5f8b71aa8f8c8beb0e16e1a8547d0312c | refs/heads/master | 2021-09-12T16:45:35.405288 | 2018-04-18T22:52:59 | 2018-04-18T22:52:59 | 120,043,918 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,249 | java |
package amat.report;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import jam.app.JamProperties;
import jam.io.IOUtil;
import amat.driver.AmatDriver;
/**
* Records the system properties that were set during the simulation.
*/
public final class PropertyReport extends AmatReport {
private final Map<String, String> propertyMap = new TreeMap<String, String>();
private PropertyReport() {}
private static PropertyReport instance = null;
/**
* The system property with this name must be {@code true} to
* schedule the report for execution.
*/
public static final String RUN_PROPERTY = "amat.PropertyReport.run";
/**
* Base name of the report file.
*/
public static final String REPORT_NAME = "system-prop.txt";
/**
* Returns the single report instance.
*
* @return the single report instance.
*/
public static PropertyReport instance() {
if (instance == null)
instance = new PropertyReport();
return instance;
}
/**
* Runs the system property report if the system property
* {@link PropertyReport#RUN_PROPERTY} is {@code true}.
*/
public static void run() {
if (runRequested())
instance().report();
}
private static boolean runRequested() {
return JamProperties.getOptionalBoolean(RUN_PROPERTY, false);
}
private void report() {
assemble();
PrintWriter writer = openWriter(REPORT_NAME);
for (Map.Entry<String, String> entry : propertyMap.entrySet())
writer.println(String.format("%-50s = %s", entry.getKey(), entry.getValue()));
IOUtil.close(writer);
}
private void assemble() {
Properties properties = System.getProperties();
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String key = entry.getKey().toString();
String value = entry.getValue().toString();
if (reportProperty(key))
propertyMap.put(key, value);
}
}
private boolean reportProperty(String key) {
return key.startsWith("jam.") || key.startsWith("amat.");
}
}
| [
"[email protected]"
] | |
8cf7c96ee0fa3cc5e630f6f2b99dfdf15f828209 | 3a74ace88440085d7c6af36b4d9d334c66923dca | /src/test/java/de/pinpoint/client/locationclient/RestClientTest.java | 8a406d895d1a67c0db6e21dcbe00ac9f615081fc | [] | no_license | PinPoint/PinPoint-Client | e8321f23bb5e095f4c9c66a23cfb3b4cf3e24310 | ee24394acee90f2e98d7f4ece990d87a54ee4a4a | refs/heads/master | 2023-02-15T22:18:25.348476 | 2021-01-13T20:24:13 | 2021-01-13T20:24:13 | 308,303,024 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,013 | java | package de.pinpoint.client.locationclient;
import de.pinpoint.client.TestConstants;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RestClientTest {
static UserInfo EXAMPLE_USER = new UserInfo(TestConstants.STEVE_UUID, "Steve", "#FFFFFF", PinPointPosition.NULL_ISLAND);
@Test
void testPostInfo() throws IOException {
RestClient client = (RestClient) new RestClientFactory().produceRestClient(TestConstants.TEST_BACKEND);
UserInfo info = EXAMPLE_USER;
client.postInfo(info);
}
@Test
void testGetInfoList() throws IOException {
RestClient client = (RestClient) new RestClientFactory().produceRestClient(TestConstants.TEST_BACKEND);
client.getInfoList(UUID.randomUUID());
}
@Test
void testGetNewUuid() throws IOException {
RestClient client = (RestClient) new RestClientFactory().produceRestClient(TestConstants.TEST_BACKEND);
client.getNewUuid();
}
@Test
void testCheckPostedInfo() throws IOException {
RestClient client = (RestClient) new RestClientFactory().produceRestClient(TestConstants.TEST_BACKEND);
UserInfo info = EXAMPLE_USER;
client.postInfo(info);
Collection<UserInfo> userList = client.getInfoList(UUID.randomUUID());
assertTrue(userList.size() > 0);
assertTrue(userList.contains(info));
}
@Test
void testGetNewUuidEquals() throws IOException {
RestClient client = (RestClient) new RestClientFactory().produceRestClient(TestConstants.TEST_BACKEND);
UUID uuid1 = client.getNewUuid();
UUID uuid2 = client.getNewUuid();
assertNotEquals(uuid1, uuid2);
}
private UserInfo randomUserInfo() {
return new UserInfo(UUID.randomUUID(), "Alex", "#FFFFFF", PinPointPosition.NULL_ISLAND);
}
} | [
"[email protected]"
] | |
ff3335fba5518ac17d16650db1785680a7e0190d | 779aa5eae9c91a7d01a10fe1f29c7df0bb508e8a | /ambiente/semillero-hbt/semillero-padre/semillero-servicios/src/main/java/com/hbt/semillero/rest/GestionarPersonasRest.java | 3a671b88776bf76fbfb4f231868d77f0656aa333 | [] | no_license | ericvarillalambertinez/seminario | a49c5f521a78f6df9605723d0d8d073fa5a052b4 | 1c9bf12b9706540d569e53e412033d617b65f041 | refs/heads/master | 2022-12-01T09:35:49.000887 | 2019-12-20T02:58:53 | 2019-12-20T02:58:53 | 225,514,400 | 0 | 0 | null | 2022-11-24T07:02:55 | 2019-12-03T02:38:02 | Java | UTF-8 | Java | false | false | 2,261 | java | package com.hbt.semillero.rest;
import java.util.List;
import javax.ejb.EJB;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import com.hbt.semillero.Exceptions.RolPersonajeExceptions;
import com.hbt.semillero.dto.PersonasDTO;
import com.hbt.semillero.ejb.IGestionarPersonasLocal;
/**
* <b>Descripción:<b> Clase que determina el servicio rest que permite gestionar
* una Persona
*
* @author Eric Varilla
* @version
*/
@Path("/GestionarPersona")
public class GestionarPersonasRest {
final static Logger logger = Logger.getLogger(GestionarRolPersonajeRest.class);
/**
* Atriburo que permite gestionar una Persona
*/
@EJB
private IGestionarPersonasLocal gestionarPersonaBean;
/**
* Crea las personas en el sistema.
* http://localhost:8085/semillero-servicios/rest/GestionarPersona/crearPersona
*
* @param persona
* @return
*/
@POST
@Path("/crearPersona")
public Response crearPersona(PersonasDTO personaNueva) {
try {
gestionarPersonaBean.crearPersona(personaNueva);
return Response.status(Response.Status.CREATED).entity("Persona Creada exitosamente..").build();
} catch (RolPersonajeExceptions e) {
logger.error("Se capturo la excepcion y la informacion del codigo es: " + e.getCodigo() + " mensaje: "
+ e.getMensaje());
return Response.status(Response.Status.BAD_REQUEST).entity(e).build();
}
};
/**
*
* Metodo encargado de traer la informacion de todos las perosnas
* http://localhost:8085/semillero-servicios/rest/GestionarPersona/consultarRolPersonaje
*
* @return
*/
@GET
@Path("/consultarRolPersonaje")
@Produces(MediaType.APPLICATION_JSON)
public Response consultarRolPersonaje() {
List<PersonasDTO> persona = null;
try {
persona = gestionarPersonaBean.consultarPersonas();
return Response.status(Response.Status.OK).entity(persona).build();
} catch (RolPersonajeExceptions e) {
logger.error("Se capturo la excepcion y la informacion del codigo es: " + e.getCodigo() + " mensaje: "
+ e.getMensaje());
return Response.status(Response.Status.BAD_REQUEST).entity(e).build();
}
};
}
| [
"[email protected]"
] | |
cffd80cb4e4c92139902f156453055d8989b1629 | 3c10a56e790c39523ca88538972b79247dcd1c49 | /app/src/main/java/com/example/parinaz/chainstoresapp/adapter/MarkedProductsAdapter.java | 205096861fcd602e17668c5c38252f79f08768c5 | [] | no_license | parinazAsghari/project | 21b8e89c1f4ab3bfa43313190d72fb2db8dd0a70 | 65a5087b54c904c1f012cb7d0ada3338b22c2f73 | refs/heads/master | 2020-08-31T22:56:02.354201 | 2019-11-08T17:44:23 | 2019-11-08T17:44:23 | 218,806,490 | 0 | 0 | null | 2019-11-08T17:44:25 | 2019-10-31T16:08:52 | Java | UTF-8 | Java | false | false | 4,822 | java | package com.example.parinaz.chainstoresapp.adapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.parinaz.chainstoresapp.R;
import com.example.parinaz.chainstoresapp.object.MarkedProducts;
import com.example.parinaz.chainstoresapp.object.Store;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class MarkedProductsAdapter extends RecyclerView.Adapter<MarkedProductsAdapter.ViewHolder> {
List<MarkedProducts> productList ;
List<Store> storeList;
Context context;
int xmlView ;
public MarkedProductsAdapter(List<MarkedProducts> productList,List<Store> storeList , Context context , int xmlView ) {
this.productList =(productList == null) ? new ArrayList<MarkedProducts>() : productList;
this.storeList = (storeList == null) ? new ArrayList<Store>() : storeList;
this.context = context;
this.xmlView = xmlView;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(xmlView , parent , false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(productList.get(position));
}
@Override
public int getItemCount() {
return productList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name , price , reducedPrice , discount , stock;
ImageView image , storeIcon;
public ViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.product_name_tv);
price = itemView.findViewById(R.id.price_tv);
reducedPrice = itemView.findViewById(R.id.reduced_price_tv);
discount = itemView.findViewById(R.id.discount_tv);
image = itemView.findViewById(R.id.product_image);
stock = itemView.findViewById(R.id.product_stock);
storeIcon = itemView.findViewById(R.id.product_store_icon);
}
public void bind(MarkedProducts product) {
if(product.getDiscount() == 0){
discount.setVisibility(View.GONE);
reducedPrice.setVisibility(View.GONE);
price.setTextColor(context.getResources().getColor(R.color.text_color));
price.setTextSize(TypedValue.COMPLEX_UNIT_PX,context.getResources().getDimension(R.dimen.largeTextSize));
} else {
discount.setText(product.getDiscount() + "% تخفیف");
reducedPrice.setText(product.getReducedPrice() + " تومان");
price.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
}
name.setText(product.getName());
price.setText(product.getPrice() + " تومان");
Picasso.with(context).load(product.getImage()).into(image);
Picasso.with(context).load(product.getStoreIcon()).into(storeIcon);
if(product.getStock() == 0) {
stock.setVisibility(View.VISIBLE);
price.setVisibility(View.GONE);
reducedPrice.setVisibility(View.GONE);
discount.setVisibility(View.GONE);
}else {
stock.setVisibility(View.GONE);
}
}
}
public void productListOnclickListener(int position , Intent intent){
intent.putExtra("productName" , productList.get(position).getName());
intent.putExtra("productDiscount" , productList.get(position).getDiscount());
intent.putExtra("productPrice" , productList.get(position).getPrice());
intent.putExtra("productReducedPrice" , productList.get(position).getReducedPrice());
intent.putExtra("productImage" , productList.get(position).getPicAddress());
intent.putExtra("productCode" , productList.get(position).getCode());
intent.putExtra("productCategory" , productList.get(position).getCategory());
intent.putExtra("productStoreBranchId" , productList.get(position).getStoreBranchId());
intent.putExtra("stock" , productList.get(position).getStock());
intent.putExtra("image" , productList.get(position).getImage());
intent.putExtra("storeIcon" , productList.get(position).getStoreIcon());
intent.putExtra("storeName" , productList.get(position).getStoreName());
}
}
| [
"[email protected]"
] | |
66159647b9e4db0fcc69b305c7ec03696d36bedf | 53e69b0380a0074fb92a16a0865b5b74ed556de8 | /app/src/main/java/ru/arvalon/rx/chapter9/GameGridView.java | aeeb08bed12aadf2a1ab97506ebb7de4ce8ad506 | [] | no_license | arvalon/RXJava | 5e4bb10c5d52f879d8792c44b3a0c69381672652 | 0065d067cdadf33e590342ef4e9b1b94c4d8a1aa | refs/heads/master | 2023-03-02T22:53:23.343789 | 2023-02-20T09:27:44 | 2023-02-20T09:28:05 | 199,412,189 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,345 | java | package ru.arvalon.rx.chapter9;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import ru.arvalon.rx.R;
import ru.arvalon.rx.chapter9.pojo.FullGameState;
import ru.arvalon.rx.chapter9.pojo.GameGrid;
import ru.arvalon.rx.chapter9.pojo.GameSymbol;
import ru.arvalon.rx.chapter9.pojo.GridPosition;
import static ru.arvalon.rx.MainActivity.LOGTAG;
public class GameGridView extends View {
private FullGameState data;
private int width;
private int height;
private final Paint linePaint;
private final Paint winnerLinePaint;
private final Paint bitmapPaint;
private final Bitmap blackPlayerBitmap;
private final Bitmap redPlayerBitmap;
private final Rect bitmapSrcRect;
public GameGridView(Context context) {
this(context, null);
}
public GameGridView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public GameGridView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
linePaint = new Paint();
linePaint.setColor(Color.BLACK);
linePaint.setStrokeWidth(8f);
winnerLinePaint = new Paint();
winnerLinePaint.setColor(Color.BLACK);
winnerLinePaint.setStrokeWidth(30f);
bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
blackPlayerBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.symbol_black_circle);
redPlayerBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.symbol_red_circle);
bitmapSrcRect = new Rect(0, 0, blackPlayerBitmap.getWidth(), blackPlayerBitmap.getHeight());
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
width = right - left;
height = bottom - top;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
Log.d(LOGTAG, "width: " + width + ", height: " + height);
final float gridWidth = getGridWidth();
final float gridHeight = getGridHeight();
final float tileWidth = width / gridWidth;
final float tileHeight = height / gridHeight;
drawSymbols(canvas, gridWidth, gridHeight, tileWidth, tileHeight);
drawGridLines(canvas, gridWidth, gridHeight, tileWidth, tileHeight);
if (data.getGameStatus().isEnded()) {
drawWinner(canvas, tileWidth, tileHeight,
data.getGameStatus().getWinningPositionStart(),
data.getGameStatus().getWinningPositionEnd());
}
}
private void drawSymbols(Canvas canvas,
float gridWidth, float gridHeight,
float tileWidth, float tileHeight) {
if (data == null) {
return;
}
GameGrid gameGrid = data.getGameState().getGameGrid();
for (int i = 0; i < gridWidth; i++) {
for (int n = 0; n < gridHeight; n++) {
GameSymbol symbol = gameGrid.getSymbolAt(i, n);
RectF dst = new RectF(i * tileWidth, n * tileHeight,
(i + 1) * tileWidth, (n + 1) * tileHeight);
if (symbol == GameSymbol.BLACK) {
canvas.drawBitmap(
blackPlayerBitmap,
bitmapSrcRect, dst,
bitmapPaint);
} else if (symbol == GameSymbol.RED) {
canvas.drawBitmap(
redPlayerBitmap,
bitmapSrcRect, dst,
bitmapPaint);
}
}
}
}
private void drawGridLines(Canvas canvas,
float gridWidth, float gridHeight,
float tileWidth, float tileHeight) {
for (int i = 0; i <= gridWidth; i++) {
Log.d(LOGTAG, "line " + i);
canvas.drawLine(i * tileWidth, 0, i * tileWidth, height, linePaint);
}
for (int n = 0; n <= gridHeight; n++) {
canvas.drawLine(0, n * tileHeight, width, n * tileHeight, linePaint);
}
}
private void drawWinner(Canvas canvas,
float tileWidth, float tileHeight,
GridPosition start, GridPosition end) {
canvas.drawLine(
start.getX() * tileWidth + tileWidth / 2,
start.getY() * tileHeight + tileHeight / 2,
end.getX() * tileWidth + tileWidth / 2,
end.getY() * tileHeight + tileHeight / 2,
winnerLinePaint);
}
public void setData(FullGameState data) {
this.data = data;
invalidate();
}
public int getGridWidth() {
return data.getGameState().getGameGrid().getWidth();
}
public int getGridHeight() {
return data.getGameState().getGameGrid().getHeight();
}
}
| [
"[email protected]"
] | |
238c1de3ebd0a469d446d07e95962ff19791ce77 | e5850bbacb224a8bcc31dba6a3778d631e05b19b | /src/oop/lab03/shapes/Circle/Cirlce.java | f24a14c3b1f4fa2ef5c858a3de8a4c1aad026357 | [] | no_license | TeoV00/OOP-Lab03 | f4d51d670709590687e4b840c2f616f5ec7eb88c | 04c24b9c091e403ff044a144dbb67012a564afa8 | refs/heads/master | 2023-01-12T18:35:09.925077 | 2020-11-12T23:24:04 | 2020-11-12T23:24:04 | 312,407,978 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 625 | java | package oop.lab03.shapes.Circle;
import oop.lab03.shapes.interfaces.*;
public class Cirlce implements Shape{
private static final double CONTS_MULTIPLIER = 2;
private static final double AREA_EXP = 2;
private final double radius;
public Cirlce(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return (Math.PI * Math.pow(this.radius, AREA_EXP));
}
@Override
public double getPerimeter() {
return (CONTS_MULTIPLIER * Math.PI *this.radius);
}
public double getRadius() {
return this.radius;
}
}
| [
"[email protected]"
] | |
6269e2833724f8e85d102d0fcc549fa47f9f6a16 | e2d1ad7bfd684f4d49469130e166efd6f47b59af | /design_pattern/src/main/java/com/study/book/interpreter/example5/ReadXmlExpression.java | e98c44f5a6495c4979c0d598ff8d7157f813a801 | [] | no_license | snowbuffer/jdk-java-basic | 8545aef243c2d0a2749ea888dbe92bec9b49751c | 2414167f93569d878b2d802b9c70af906b605c7a | refs/heads/master | 2022-12-22T22:10:11.575240 | 2021-07-06T06:13:38 | 2021-07-06T06:13:38 | 172,832,856 | 0 | 1 | null | 2022-12-16T04:40:12 | 2019-02-27T03:04:57 | Java | GB18030 | Java | false | false | 406 | java | package com.study.book.interpreter.example5;
/**
* 用于处理自定义Xml取值表达式的接口
*/
public abstract class ReadXmlExpression {
/**
* 解释表达式
*
* @param c 上下文
* @return 解析过后的值,为了通用,可能是单个值,也可能是多个值,
* 因此就返回一个数组
*/
public abstract String[] interpret(Context c);
}
| [
"[email protected]"
] | |
5e2e3bae8fccf513dcb999330f0f456d01498adc | e76c81c498fd1b5dfe6eac1146ea379f92c3868a | /Hari/Eercise-1/Sales.java | 701f68bfbacc4dc01964ea549cb651b9af0df35b | [] | no_license | Harini241/java-Exercise-1 | 8270550d770c47cfba174497e02a2310fbe4a78c | 05009b64dd5a7c6f475d13a0313a66d7c48c70aa | refs/heads/master | 2022-05-29T13:05:52.009871 | 2020-04-30T04:03:09 | 2020-04-30T04:03:09 | 259,917,390 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,056 | java | import java.util.Scanner;
public class Sales {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the amount of your purchase: ");
double purchaseAmount = input.nextDouble();
System.out.println();
System.out.println("Your purchase amount is: $" + purchaseAmount);
System.out.println();
double statetax = purchaseAmount * 0.085;
System.out.println("The State sales tax for this purchase is: $" + (int)(statetax * 100)/100.0);
System.out.println();
double countytax = purchaseAmount * 0.025;
System.out.println("The County sales tax for this purchase is: $" + (int)(countytax * 100)/100.0);
System.out.println();
double totaltax = countytax + statetax;
System.out.println("The total amount of sales tax that you will pay for this purchase will be: $"+ String.format("%.2f",totaltax));
System.out.println();
double total = totaltax + purchaseAmount;
System.out.println("The total amount of your purchase including the sales tax will be: $" + String.format("%.2f",total));
}
}
| [
"[email protected]"
] | |
447cf942575776275f03bb218ddda6bab554329a | 6fd531929722f2d6b23047ab4700bd72dba8568d | /App/ITalker/factory/src/main/java/www/yyh/com/factory/data/user/ContactRepository.java | ea1d684c9e2dea00954c86eb8ddd721e122613e4 | [] | no_license | yanyonghua/YYHMessager | f4a2ecd2555f73fd82c179c9d923faf6cf8e1d7f | f223763bb57f28e18c3bc1a769612f602e2875bc | refs/heads/master | 2021-07-08T01:40:06.306422 | 2020-07-16T08:32:08 | 2020-07-16T08:32:08 | 140,655,013 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,408 | java | package www.yyh.com.factory.data.user;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import java.util.List;
import www.yyh.com.factory.data.BaseDbRepository;
import www.yyh.com.factory.data.DataSource;
import www.yyh.com.factory.model.db.User;
import www.yyh.com.factory.model.db.User_Table;
import www.yyh.com.factory.persistence.Account;
/**
* 联系人仓库
* Created by 56357 on 2018/6/23
*/
public class ContactRepository extends BaseDbRepository<User>
implements ContactDataSource{
@Override
public void load(DataSource.SucceedCallback<List<User>> callback) {
super.load(callback);
//加载本地数据库数据
SQLite.select()
.from(User.class)
.where(User_Table.isFollow.eq(true))//是否是订阅用户
.and(User_Table.id.notEq(Account.getUserId()))//通过非自己的id
.orderBy(User_Table.name,true)//通过名字排序
.limit(100)//限制100条数据
.async()//异步操作
.queryListResultCallback(this)
.execute();
}
/**
* 检查一个User是否是我需要关注的数据
* @param user User
* @return true 是我关注的数据
*/
@Override
protected boolean isRequired(User user){
return user.isFollow()&&!user.getId().equals(Account.getUserId());
}
}
| [
"[email protected]"
] | |
e41184621de4a781fc272c482eb065b2847dd315 | a60546cfc7662be8b2a3d7bf7ba59e61ca02c401 | /singleton/src/main/java/singleton/ThreadSafeDoubleCheckLocking.java | a522cb35c19792fc1467b10c9fe42747ae40f5c8 | [
"MIT"
] | permissive | osy0907/object-oriented-design-patterns | d73bfcd2b48fc033e421cf1db98d5a588db0a950 | 68939dba763e612b19e8761fb0c93e89347607e7 | refs/heads/main | 2023-08-23T21:59:50.239467 | 2021-10-14T10:15:08 | 2021-10-14T10:15:08 | 412,171,950 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,044 | java | package singleton;
public final class ThreadSafeDoubleCheckLocking {
private static volatile ThreadSafeDoubleCheckLocking instance;
private static boolean flag = true;
/**
* private constructor to prevent client from instantiating.
*/
private ThreadSafeDoubleCheckLocking() {
// to prevent instantiating by Reflection call
if (flag) {
flag = false;
} else {
throw new IllegalStateException("Already initialized.");
}
}
/**
* Public accessor.
*
* @return an instance of the class.
*/
public static ThreadSafeDoubleCheckLocking getInstance() {
// local variable increases performance by 25 percent
// Joshua Bloch "Effective Java, Second Edition", p. 283-284
var result = instance;
// Check if singleton instance is initialized.
// If it is initialized then we can return the instance.
if (result == null) {
// It is not initialized but we cannot be sure because some other thread might have
// initialized it in the meanwhile.
// So to make sure we need to lock on an object to get mutual exclusion.
synchronized (ThreadSafeDoubleCheckLocking.class) {
// Again assign the instance to local variable to check if it was initialized by some
// other thread while current thread was blocked to enter the locked zone.
// If it was initialized then we can return the previously created instance
// just like the previous null check.
result = instance;
if (result == null) {
// The instance is still not initialized so we can safely
// (no other thread can enter this zone)
// create an instance and make it our singleton instance.
instance = result = new ThreadSafeDoubleCheckLocking();
}
}
}
return result;
}
} | [
"[email protected]"
] | |
94394e8f0434fd7b3191d7224b76a3bbf0d07010 | 0429ec7192a11756b3f6b74cb49dc1ba7c548f60 | /src/main/java/com/linkage/module/itms/resource/act/FunctionDeploymentByDevTypeACT.java | 190eeb4f92bfca161aee067c38987d2dcd55bc30 | [] | no_license | lichao20000/WEB | 5c7730779280822619782825aae58506e8ba5237 | 5d2964387d66b9a00a54b90c09332e2792af6dae | refs/heads/master | 2023-06-26T16:43:02.294375 | 2021-07-29T08:04:46 | 2021-07-29T08:04:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,046 | java |
package com.linkage.module.itms.resource.act;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.linkage.litms.common.util.DateTimeUtil;
import com.linkage.module.itms.resource.bio.FunctionDeploymentByDevTypeBIO;
import action.splitpage.splitPageAction;
/**
* @author Administrator (Ailk No.)
* @version 1.0
* @since 2013-12-9
* @category com.linkage.module.itms.resource.act
* @copyright Ailk NBS-Network Mgt. RD Dept.
*/
public class FunctionDeploymentByDevTypeACT extends splitPageAction implements
SessionAware, ServletRequestAware
{
private static Logger logger = LoggerFactory
.getLogger(FunctionDeploymentByDevTypeACT.class);
private Map session;
private HttpServletRequest request;
// 结束时间
private String endOpenDate = "";
// 结束时间
private String endOpenDate1 = "";
// 厂商文件列表
private Map<String, String> vendorMap;
// 功能
private String gn;
// 厂商
private String vendorId;
// 型号
private String modelId;
private String ajax;
private List<Map> data; // 需要导出的结果集,必须是处理过的可以直接显示的结果
private String[] column; // 需要导出的列名,对应data中的键值
private String[] title; // 显示在导出文档上的列名
private String fileName; // 导出的文件名(不包括后缀名)
// 统计信息
private List<Map> deployList;
// 统计详细明细
private List<Map> deployDevTypeList;
private FunctionDeploymentByDevTypeBIO bio;
/**
* 初始化页面数据
*/
@Override
public String execute() throws Exception
{
logger.debug("FunctionDeploymentByDevTypeACT=>execute()");
endOpenDate = getEndDate();
vendorMap = bio.getVendor();
return "init";
}
/**
* 查询新增功能部署报表设备型号情况
*
* @return
*/
public String quertFunctionDeployByDevType()
{
logger.debug("FunctionDeploymentByDevTypeACT=>quertFunctionDeployByDevTypeList()");
this.setTime();
deployList = bio
.quertFunctionDeployByDevType(vendorId, modelId, endOpenDate1, gn);
return "list";
}
/**
* 导出新增功能部署报表设备型号情况
*
* @return
*/
public String quertFunctionDeployByDevTypeExcel()
{
logger.debug("FunctionDeploymentByDevTypeACT=>quertFunctionDeployByDevTypeList()");
this.setTime();
deployList = bio
.quertFunctionDeployByDevType(vendorId, modelId, endOpenDate1, gn);
String excelCol = "modelType#deploy_total";
String excelTitle = "设备型号#已开通终端数";
column = excelCol.split("#");
title = excelTitle.split("#");
fileName = "deployTypeListTotal";
data = deployList;
return "excel";
}
/**
* 新增功能部署报表设备型号情况明细页面
*
* @return
*/
public String quertFunctionDeployByDevTypeList()
{
logger.debug("FunctionDeploymentByDevTypeACT=>quertFunctionDeployByDevTypeList()");
this.setTime();
deployDevTypeList = bio.quertFunctionDeployByDevTypeList(vendorId, modelId,
endOpenDate1, gn, curPage_splitPage, num_splitPage);
maxPage_splitPage = bio.countQuertFunctionDeployByDevTypeList(vendorId, modelId,
endOpenDate1, gn, curPage_splitPage, num_splitPage);
return "devlist";
}
/**
* 导出新增功能部署报表设备型号情况明细页面
*
* @return
*/
public String quertFunctionDeployByDevTypeListExcel()
{
logger.debug("FunctionDeploymentByDevTypeACT=>quertFunctionDeployByDevTypeListExcel()");
this.setTime();
deployDevTypeList = bio.excelQuertFunctionDeployByDevTypeList(vendorId, modelId,
gn, endOpenDate1);
String excelCol = "city_name#loid#device_serialnumber#start_time#status#timelist#device_model";
String excelTitle = "区域#LOID#设备序列号#部署时间#开通状态#采样周期#设备型号";
column = excelCol.split("#");
title = excelTitle.split("#");
fileName = "deployDevTypeList";
data = deployDevTypeList;
return "excel";
}
// 当前时间的23:59:59,如 2011-05-11 23:59:59
private String getEndDate()
{
GregorianCalendar now = new GregorianCalendar();
SimpleDateFormat fmtrq = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
// now.set(Calendar.HOUR_OF_DAY, 23);
// now.set(Calendar.MINUTE, 59);
// now.set(Calendar.SECOND, 59);
String time = fmtrq.format(now.getTime());
return time;
}
/**
* 时间转化
*/
private void setTime()
{
logger.debug("setTime()" + endOpenDate);
DateTimeUtil dt = null;// 定义DateTimeUtil
if (endOpenDate == null || "".equals(endOpenDate))
{
endOpenDate1 = null;
}
else
{
dt = new DateTimeUtil(endOpenDate);
endOpenDate1 = String.valueOf(dt.getLongTime());
}
}
@Override
public void setServletRequest(HttpServletRequest request)
{
this.request = request;
}
@Override
public void setSession(Map<String, Object> session)
{
this.session = session;
}
public String getEndOpenDate()
{
return endOpenDate;
}
public void setEndOpenDate(String endOpenDate)
{
this.endOpenDate = endOpenDate;
}
public String getEndOpenDate1()
{
return endOpenDate1;
}
public void setEndOpenDate1(String endOpenDate1)
{
this.endOpenDate1 = endOpenDate1;
}
public Map<String, String> getVendorMap()
{
return vendorMap;
}
public void setVendorMap(Map<String, String> vendorMap)
{
this.vendorMap = vendorMap;
}
public String getGn()
{
return gn;
}
public void setGn(String gn)
{
this.gn = gn;
}
public String getVendorId()
{
return vendorId;
}
public void setVendorId(String vendorId)
{
this.vendorId = vendorId;
}
public String getModelId()
{
return modelId;
}
public void setModelId(String modelId)
{
this.modelId = modelId;
}
public String getAjax()
{
return ajax;
}
public void setAjax(String ajax)
{
this.ajax = ajax;
}
public List<Map> getData()
{
return data;
}
public void setData(List<Map> data)
{
this.data = data;
}
public String[] getColumn()
{
return column;
}
public void setColumn(String[] column)
{
this.column = column;
}
public String[] getTitle()
{
return title;
}
public void setTitle(String[] title)
{
this.title = title;
}
public String getFileName()
{
return fileName;
}
public void setFileName(String fileName)
{
this.fileName = fileName;
}
public List<Map> getDeployList()
{
return deployList;
}
public void setDeployList(List<Map> deployList)
{
this.deployList = deployList;
}
public FunctionDeploymentByDevTypeBIO getBio()
{
return bio;
}
public void setBio(FunctionDeploymentByDevTypeBIO bio)
{
this.bio = bio;
}
public List<Map> getDeployDevTypeList()
{
return deployDevTypeList;
}
public void setDeployDevTypeList(List<Map> deployDevTypeList)
{
this.deployDevTypeList = deployDevTypeList;
}
}
| [
"di4zhibiao.126.com"
] | di4zhibiao.126.com |
84b9d62687a93d70c3a76a516e9a2ffd4dc92b4e | 5a14e08240fc39ded67c535f5087b11fd8f6b2c7 | /6.3-Backend_Deployment_With_AWS_ElasticBeanstalk/demo/src/main/java/com/example/demo/model/TodoEntity.java | 55fb8c8ca9afb4de5eba5d333b5110797a1a9c93 | [] | no_license | viaSSH/todo-application | e1bde62eac8d6de034d45253f66412e0c029b30a | 327f5a7c22cb482b13efc32ac3a1a90b822c67cc | refs/heads/main | 2023-08-24T08:35:38.034617 | 2021-10-08T21:42:14 | 2021-10-08T21:42:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 638 | java | package com.example.demo.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.GenericGenerator;
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Table(name = "Todo")
public class TodoEntity {
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
private String id;
private String userId;
private String title;
private boolean done;
}
| [
"[email protected]"
] | |
049c4ae1fde080e24af4333e878a6a38028582d1 | 15643194837b25c852dd6f20be88f7a7cac22075 | /XQuery_processor/src/main/java/CustomizedXQueryVisitor.java | b2b8f62e5f77f4df538ac927295d1c5789b07d4f | [] | no_license | BaomoZhou/CSE232B | 6fe3f2fbe2a8af00dacd4ea7722e2733fd5f686e | bccaa46ce875a0083330e9ab28e929dee8f191e2 | refs/heads/master | 2021-01-09T02:27:03.283479 | 2017-03-18T04:14:20 | 2017-03-18T04:14:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 41,205 | java | import java.util.*;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import java.util.LinkedList;
/**
* Created by onion on 2/18/17.
*/
public class CustomizedXQueryVisitor extends XQueryBaseVisitor<LinkedList>{
private HashMap<String, LinkedList<Node>> contextMap = new HashMap<>();
private Stack<HashMap<String, LinkedList<Node>>> contextStack = new Stack<>();
Document outputDoc = null;
private Document doc = null;
boolean needRewrite = true;
public CustomizedXQueryVisitor(){
try {
DocumentBuilderFactory docBF = DocumentBuilderFactory.newInstance();
DocumentBuilder docB = docBF.newDocumentBuilder();
outputDoc = docB.newDocument();
doc = docB.newDocument();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
@Override public LinkedList<Node> visitFLWR(XQueryParser.FLWRContext ctx) {
LinkedList<Node> results = new LinkedList<>();
HashMap<String, LinkedList<Node>> contextMapOld = new HashMap<>(contextMap);
contextStack.push(contextMapOld);
//System.out.println(ctx.forClause().xq(0).getText().startsWith("join"));
if (!needRewrite){
//if (!needRewrite || ctx.forClause().xq(0).getText().startsWith("join")){
FLWRHelper(0, results, ctx);
}
else{
String rewrited = reWriter(ctx);
if (rewrited == ""){
FLWRHelper(0, results, ctx);
}
else
results = XQuery.evalRewrited(rewrited);
}
contextMap = contextStack.pop();
return results;
}
private String reWriter(XQueryParser.FLWRContext ctx){
//PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
String output = "";
int numFor;// nums of for clause
numFor = ctx.forClause().var().size();
List<HashSet<String>> classify = new LinkedList<HashSet<String>>();
List<String> relation = new LinkedList<String>();
for(int i=0; i < numFor;i++) {
String key = ctx.forClause().var(i).getText();
String parent = ctx.forClause().xq(i).getText().split("/")[0];
int size = classify.size();
boolean found = false;
// construct the classification
for(int j = 0; j < size; j++) {
HashSet<String> curSet = classify.get(j);
if(curSet.contains(parent)) {
curSet.add(key);
found = true;
break;
}
}
if(!found) {
HashSet<String> newSet = new HashSet<String>();
newSet.add(key);
classify.add(newSet);
relation.add(key);
}
}
//where clause
String[] where = ctx.whereClause().cond().getText().split("and");
String[][] cond = new String[where.length][2];
for(int i = 0; i < where.length;i++) {
cond[i][0] = where[i].split("eq|=")[0];
cond[i][1] = where[i].split("eq|=")[1];
}
if(classify.size() == 1) {
System.out.println("No need to join!");
return "";
}
/*
the relation that the where condition belongs to. it could belong to two relations at most
*/
int[][] relaWhere = new int[cond.length][2];
for(int i=0; i < cond.length; i++) {
String cur0 = cond[i][0];
String cur1 = cond[i][1];
relaWhere[i][0] = -1;
relaWhere[i][1] = -1;
for(int j = 0; j < classify.size();j++) {
if(classify.get(j).contains(cur0)) {
relaWhere[i][0] = j;
}
if(classify.get(j).contains(cur1)) {
relaWhere[i][1] = j;
}
}
}
int class_size = classify.size();
//print out
output += "for $tuple in";
//writer.print("For $tuple in join (");
System.out.print("for $tuple in");
for (int i = 1; i < class_size;i++) {
output += " join (";
System.out.print(" join (");
}
//for clause
//print eq: [af1,al1],[af21,al21]
output = Print2Join(classify, ctx, output,cond,relaWhere);
if(class_size > 2) {
output = Print3Join(classify, ctx, output, cond, relaWhere);
}
if(class_size > 3) {
output = Print4Join(classify, ctx, output, cond, relaWhere);
}
if(class_size > 4) {
output = Print5Join(classify, ctx, output, cond, relaWhere);
}
if(class_size > 5) {
output = Print6Join(classify, ctx, output, cond, relaWhere);
}
/*
return clause
*/
String retClause = ctx.returnClause().rt().getText();
String[] tempRet = retClause.split("\\$");
for (int i = 0; i < tempRet.length-1; i++) {
tempRet[i] = tempRet[i]+"$tuple/";
}
retClause = tempRet[0];
for (int i = 1; i < tempRet.length; i++) {
String[] cur1 = tempRet[i].split(",",2);
String[] cur2 = tempRet[i].split("}",2);
String[] cur3 = tempRet[i].split("/",2);
String[] cur = cur1;
if(cur2[0].length() < cur[0].length()) {
cur = cur2;
}
if(cur3[0].length() < cur[0].length()) {
cur = cur3;
}
tempRet[i] = cur[0] + "/*";
// if(cur[1].charAt(0) == '$' || cur[1].charAt(0) == '<') {
// tempRet[i] += ",";
// }else {
// tempRet[i] += "/";
// }
if(cur == cur1) {
tempRet[i] += ",";
}else if(cur == cur2) {
tempRet[i] += "}";
}else {
tempRet[i] += "/";
}
tempRet[i] += cur[1];
retClause = retClause + tempRet[i];
}
// int end = tempRet.length-1;
// String[] cur = tempRet[end].split("}",2);
// tempRet[end] = cur[0] + "/*}";
// tempRet[end] += cur[1];
// retClause = retClause + tempRet[end];
output += "return\n";
output += retClause+"\n";
System.out.println("return");
System.out.println(retClause);
/*
write in txt
*/
writer w = new writer();
w.writing("input/output.txt",output);
return output;
}
private String PrintJoinCond(LinkedList<String> ret0, LinkedList<String> ret1, String output) {
output += " [";
System.out.print(" [");
for(int i = 0; i < ret0.size();i++) {
output +=ret0.get(i);
System.out.print(ret0.get(i));
if(i != ret0.size()-1) {
output +=",";
System.out.print(",");
}
}
output +="], [";
System.out.print("], [");
for(int i = 0; i < ret1.size();i++) {
output +=ret1.get(i);
System.out.print(ret1.get(i));
if(i != ret1.size()-1) {
output +=",";
System.out.print(",");
}
}
output += "] ";
System.out.print("] ");
return output;
}
private String Print2Join(List<HashSet<String>> classify, XQueryParser.FLWRContext ctx, String output,String[][] cond,int[][] relaWhere) {
//for clause
int numFor = ctx.forClause().var().size();
//for(int i = 0; i < classify.size(); i++) {
for(int i = 0; i < 2; i++) {
HashSet<String> curSet = classify.get(i);
String tuples = "";
int count = 0;
//print for
for(int k = 0; k < numFor; k++) {
String key = ctx.forClause().var(k).getText();
if(curSet.contains(key)){
if(count == 0) {
output += "for " + key + " in " + ctx.forClause().xq(k).getText();
System.out.print("for " + key + " in " + ctx.forClause().xq(k).getText());
count++;
}else {
output += ",\n";
output += " " + key + " in " + ctx.forClause().xq(k).getText();
System.out.println(",");
System.out.print(" " + key + " in " + ctx.forClause().xq(k).getText());
}
if(tuples.equals("")) {
tuples = tuples + " <" + key.substring(1) + "> " + " {" + key + "} " + " </" + key.substring(1) + ">";
}else {
tuples = tuples + ", <" + key.substring(1) + "> " + " {" + key + "} " + " </" + key.substring(1) + ">";
}
}
}
output += "\n";
System.out.print("\n");
//print where
for(int j = 0;j < cond.length;j++) {
int count1 = 0;
if(relaWhere[j][1] == -1 && curSet.contains(cond[j][0])) {
if(count1 == 0){
count1++;
output += "where " + cond[j][0] + " eq " + cond[j][1] +"\n";
System.out.println("where " + cond[j][0] + " eq " + cond[j][1]);
}else {
output += " and " + cond[j][0] + " eq " + cond[j][1] + "\n";
System.out.println(" and " + cond[j][0] + " eq " + cond[j][1]);
}
}
}
//print return
tuples = "<tuple> "+tuples+" </tuple>,";
output += " return" + tuples + "\n";
System.out.println(" return" + tuples);
}
//return
LinkedList<String> ret0 = new LinkedList<String>();
LinkedList<String> ret1 = new LinkedList<String>();
for(int i = 0; i < cond.length; i++) {
if (relaWhere[i][0] == 1 && relaWhere[i][1] == 0) {
ret0.add(cond[i][1].substring(1));
ret1.add(cond[i][0].substring(1));
}else if(relaWhere[i][0] == 0 && relaWhere[i][1] == 1) {
ret0.add(cond[i][0].substring(1));
ret1.add(cond[i][1].substring(1));
}
}
output = PrintJoinCond(ret0,ret1,output);
output += ")\n";
System.out.println(")");
return output;
}
private String Print3Join(List<HashSet<String>> classify, XQueryParser.FLWRContext ctx,String output,String[][] cond,int[][] relaWhere) {
int numFor = ctx.forClause().var().size();
HashSet<String> curSet = classify.get(2);
String tuples = "";
int count = 0;
//print for
for(int k = 0; k < numFor; k++) {
String key = ctx.forClause().var(k).getText();
if(curSet.contains(key)){
if(count == 0) {
output += ",for " + key + " in " + ctx.forClause().xq(k).getText();
System.out.print(",for " + key + " in " + ctx.forClause().xq(k).getText());
count++;
}else {
output += ",\n";
output += " " + key + " in " + ctx.forClause().xq(k).getText();
System.out.println(",");
System.out.print(" " + key + " in " + ctx.forClause().xq(k).getText());
}
if(tuples.equals("")) {
tuples = tuples + " <" + key.substring(1) + "> " + " {" + key + "} " + " </" + key.substring(1) + ">";
}else {
tuples = tuples + ", <" + key.substring(1) + "> " + " {" + key + "} " + " </" + key.substring(1) + ">";
}
}
}
output += "\n";
System.out.print("\n");
//print where
for(int j = 0;j < cond.length;j++) {
int count1 = 0;
if(relaWhere[j][1] == -1 && curSet.contains(cond[j][0])) {
if(count1 == 0){
count1++;
output += "where " + cond[j][0] + " eq " + cond[j][1] +"\n";
System.out.println("where " + cond[j][0] + " eq " + cond[j][1]);
}else {
output += " and " + cond[j][0] + " eq " + cond[j][1] + "\n";
System.out.println(" and " + cond[j][0] + " eq " + cond[j][1]);
}
}
}
//print return
tuples = "<tuple> "+tuples+" </tuple>,";
output += " return" + tuples + "\n";
System.out.println(" return" + tuples);
LinkedList<String> ret0 = new LinkedList<String>();
LinkedList<String> ret2 = new LinkedList<String>();
for(int i = 0; i < cond.length; i++) {
if (relaWhere[i][0] == 2 && (relaWhere[i][1] == 1 || relaWhere[i][1] == 0)){
ret0.add(cond[i][1].substring(1));
ret2.add(cond[i][0].substring(1));
}else if((relaWhere[i][0] == 1 || relaWhere[i][0] == 0) && relaWhere[i][1] == 2) {
ret0.add(cond[i][0].substring(1));
ret2.add(cond[i][1].substring(1));
}
}
output = PrintJoinCond(ret0,ret2,output);
output += ")\n";
System.out.println(")");
return output;
}
private String Print4Join(List<HashSet<String>> classify, XQueryParser.FLWRContext ctx,String output,String[][] cond,int[][] relaWhere) {
int numFor = ctx.forClause().var().size();
HashSet<String> curSet = classify.get(3);
String tuples = "";
int count = 0;
//print for
for(int k = 0; k < numFor; k++) {
String key = ctx.forClause().var(k).getText();
if(curSet.contains(key)){
if(count == 0) {
output += ",for " + key + " in " + ctx.forClause().xq(k).getText();
System.out.print(",for " + key + " in " + ctx.forClause().xq(k).getText());
count++;
}else {
output += ",\n";
output += " " + key + " in " + ctx.forClause().xq(k).getText();
System.out.println(",");
System.out.print(" " + key + " in " + ctx.forClause().xq(k).getText());
}
if(tuples.equals("")) {
tuples = tuples + " <" + key.substring(1) + "> " + " {" + key + "} " + " </" + key.substring(1) + ">";
}else {
tuples = tuples + ", <" + key.substring(1) + "> " + " {" + key + "} " + " </" + key.substring(1) + ">";
}
}
}
output += "\n";
System.out.print("\n");
//print where
for(int j = 0;j < cond.length;j++) {
int count1 = 0;
if(relaWhere[j][1] == -1 && curSet.contains(cond[j][0])) {
if(count1 == 0){
count1++;
output += "where " + cond[j][0] + " eq " + cond[j][1] +"\n";
System.out.println("where " + cond[j][0] + " eq " + cond[j][1]);
}else {
output += " and " + cond[j][0] + " eq " + cond[j][1] + "\n";
System.out.println(" and " + cond[j][0] + " eq " + cond[j][1]);
}
}
}
//print return
tuples = "<tuple> "+tuples+" </tuple>,";
output += " return" + tuples + "\n";
System.out.println(" return" + tuples);
LinkedList<String> ret0 = new LinkedList<String>();
LinkedList<String> ret2 = new LinkedList<String>();
for(int i = 0; i < cond.length; i++) {
if (relaWhere[i][0] == 3 && (relaWhere[i][1] >= 0 && relaWhere[i][1] <= 2)){
ret0.add(cond[i][1].substring(1));
ret2.add(cond[i][0].substring(1));
}else if((relaWhere[i][0] >= 0 && relaWhere[i][0] <= 2) && relaWhere[i][1] == 3) {
ret0.add(cond[i][0].substring(1));
ret2.add(cond[i][1].substring(1));
}
}
output = PrintJoinCond(ret0,ret2,output);
output += ")\n";
System.out.println(")");
return output;
}
private String Print5Join(List<HashSet<String>> classify, XQueryParser.FLWRContext ctx,String output,String[][] cond,int[][] relaWhere,) {
int numFor = ctx.forClause().var().size();
HashSet<String> curSet = classify.get(4);
String tuples = "";
int count = 0;
//print for
for(int k = 0; k < numFor; k++) {
String key = ctx.forClause().var(k).getText();
if(curSet.contains(key)){
if(count == 0) {
output += ",for " + key + " in " + ctx.forClause().xq(k).getText();
System.out.print(",for " + key + " in " + ctx.forClause().xq(k).getText());
count++;
}else {
output += ",\n";
output += " " + key + " in " + ctx.forClause().xq(k).getText();
System.out.println(",");
System.out.print(" " + key + " in " + ctx.forClause().xq(k).getText());
}
if(tuples.equals("")) {
tuples = tuples + " <" + key.substring(1) + "> " + " {" + key + "} " + " </" + key.substring(1) + ">";
}else {
tuples = tuples + ", <" + key.substring(1) + "> " + " {" + key + "} " + " </" + key.substring(1) + ">";
}
}
}
output += "\n";
System.out.print("\n");
//print where
for(int j = 0;j < cond.length;j++) {
int count1 = 0;
if(relaWhere[j][1] == -1 && curSet.contains(cond[j][0])) {
if(count1 == 0){
count1++;
output += "where " + cond[j][0] + " eq " + cond[j][1] +"\n";
System.out.println("where " + cond[j][0] + " eq " + cond[j][1]);
}else {
output += " and " + cond[j][0] + " eq " + cond[j][1] + "\n";
System.out.println(" and " + cond[j][0] + " eq " + cond[j][1]);
}
}
}
//print return
tuples = "<tuple> "+tuples+" </tuple>,";
output += " return" + tuples + "\n";
System.out.println(" return" + tuples);
LinkedList<String> ret0 = new LinkedList<String>();
LinkedList<String> ret2 = new LinkedList<String>();
for(int i = 0; i < cond.length; i++) {
if (relaWhere[i][0] == 2 && (relaWhere[i][1] == 1 || relaWhere[i][1] == 0)){
ret0.add(cond[i][1].substring(1));
ret2.add(cond[i][0].substring(1));
}else if((relaWhere[i][0] == 1 || relaWhere[i][0] == 0) && relaWhere[i][1] == 2) {
ret0.add(cond[i][0].substring(1));
ret2.add(cond[i][1].substring(1));
}
}
output = PrintJoinCond(ret0,ret2,output);
output += ")\n";
System.out.println(")");
return output;
}
private String Print6Join(List<HashSet<String>> classify, XQueryParser.FLWRContext ctx,String output,String[][] cond,int[][] relaWhere) {
int numFor = ctx.forClause().var().size();
HashSet<String> curSet = classify.get(5);
String tuples = "";
int count = 0;
//print for
for(int k = 0; k < numFor; k++) {
String key = ctx.forClause().var(k).getText();
if(curSet.contains(key)){
if(count == 0) {
output += ",for " + key + " in " + ctx.forClause().xq(k).getText();
System.out.print(",for " + key + " in " + ctx.forClause().xq(k).getText());
count++;
}else {
output += ",\n";
output += " " + key + " in " + ctx.forClause().xq(k).getText();
System.out.println(",");
System.out.print(" " + key + " in " + ctx.forClause().xq(k).getText());
}
if(tuples.equals("")) {
tuples = tuples + " <" + key.substring(1) + "> " + " {" + key + "} " + " </" + key.substring(1) + ">";
}else {
tuples = tuples + ", <" + key.substring(1) + "> " + " {" + key + "} " + " </" + key.substring(1) + ">";
}
}
}
output += "\n";
System.out.print("\n");
//print where
for(int j = 0;j < cond.length;j++) {
int count1 = 0;
if(relaWhere[j][1] == -1 && curSet.contains(cond[j][0])) {
if(count1 == 0){
count1++;
output += "where " + cond[j][0] + " eq " + cond[j][1] +"\n";
System.out.println("where " + cond[j][0] + " eq " + cond[j][1]);
}else {
output += " and " + cond[j][0] + " eq " + cond[j][1] + "\n";
System.out.println(" and " + cond[j][0] + " eq " + cond[j][1]);
}
}
}
//print return
tuples = "<tuple> "+tuples+" </tuple>,";
output += " return" + tuples + "\n";
System.out.println(" return" + tuples);
LinkedList<String> ret0 = new LinkedList<String>();
LinkedList<String> ret2 = new LinkedList<String>();
for(int i = 0; i < cond.length; i++) {
if (relaWhere[i][0] == 2 && (relaWhere[i][1] == 1 || relaWhere[i][1] == 0)){
ret0.add(cond[i][1].substring(1));
ret2.add(cond[i][0].substring(1));
}else if((relaWhere[i][0] == 1 || relaWhere[i][0] == 0) && relaWhere[i][1] == 2) {
ret0.add(cond[i][0].substring(1));
ret2.add(cond[i][1].substring(1));
}
}
output = PrintJoinCond(ret0,ret2,output);
output += ")\n";
System.out.println(")");
return output;
}
@Override public LinkedList<Node> visitJoinXQ(XQueryParser.JoinXQContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitJoinClause(XQueryParser.JoinClauseContext ctx) {
LinkedList<Node> left = visit(ctx.xq(0));
LinkedList<Node> right = visit(ctx.xq(1));
int idSize = ctx.idList(0).ID().size();
String [] idListLeft = new String [idSize];
String [] idListRight = new String [idSize];
for (int i = 0; i < idSize; i++){
idListLeft[i] = ctx.idList(0).ID(i).getText();
idListRight[i] = ctx.idList(1).ID(i).getText();
}
HashMap<String, LinkedList<Node>> hashMapOnLeft = buildHashTable(left, idListLeft);
LinkedList<Node> result = probeJoin(hashMapOnLeft, right, idListLeft, idListRight);
return result;
}
private LinkedList<Node> probeJoin(HashMap<String, LinkedList<Node>> hashMapOnLeft, LinkedList<Node> right, String [] idListLeft, String []idListRight){
LinkedList<Node> result = new LinkedList<>();
for (Node tuple: right){
LinkedList<Node> children = getChildren(tuple);
String key = "";
for (String hashAtt: idListRight) {
for (Node child: children){
if (hashAtt.equals(child.getNodeName())) {
key += child.getFirstChild().getTextContent();
}
}
}
if (hashMapOnLeft.containsKey(key))
result.addAll(product(hashMapOnLeft.get(key),tuple));
}
return result;
}
private LinkedList<Node> product(LinkedList<Node> leftList, Node right){
LinkedList<Node> result = new LinkedList<>();
for (Node left: leftList){
LinkedList<Node> newTupleChildren = getChildren(left);
newTupleChildren.addAll(getChildren(right));
result.add(makeElem("tuple", newTupleChildren));
}
return result;
}
private HashMap buildHashTable(LinkedList<Node> tupleList, String [] hashAtts){
HashMap<String, LinkedList<Node>> result = new HashMap<>();
for (Node tuple: tupleList){
LinkedList<Node> children = getChildren(tuple);
String key = "";
for (String hashAtt: hashAtts) {
for (Node child: children){
if (hashAtt.equals(child.getNodeName()))
key += child.getFirstChild().getTextContent();
}
}
if (result.containsKey(key))
result.get(key).add(tuple);
else{
LinkedList<Node> value = new LinkedList<>();
value.add(tuple);
result.put(key, value);
}
}
return result;
}
private void FLWRHelper(int k, LinkedList<Node> results, XQueryParser.FLWRContext ctx){
int numFor;
numFor = ctx.forClause().var().size();
if (k == numFor){
if (ctx.letClause() != null) visit(ctx.letClause());
if (ctx.whereClause() != null)
if (visit(ctx.whereClause()).size() == 0) return;
LinkedList<Node> result = visit(ctx.returnClause());
results.addAll(result);
}
else{
String key = ctx.forClause().var(k).getText();
LinkedList<Node> valueList = visit(ctx.forClause().xq(k));
for (Node node: valueList){
HashMap<String, LinkedList<Node>> contextMapOld = new HashMap<>(contextMap);
contextStack.push(contextMapOld);
LinkedList<Node> value = new LinkedList<>(); value.add(node);
contextMap.put(key, value);
if (k+1 <= numFor)
FLWRHelper(k+1, results, ctx);
contextMap = contextStack.pop();
}
}
}
@Override public LinkedList<Node> visitTagXQ(XQueryParser.TagXQContext ctx) {
String tagName = ctx.startTag().tagName().getText();
LinkedList<Node> nodeList = visit(ctx.xq());
Node node = makeElem(tagName, nodeList);
LinkedList<Node> result = new LinkedList<>();
result.add(node);
return result;
}
@Override public LinkedList<Node> visitApXQ(XQueryParser.ApXQContext ctx) {
String ap = ctx.getText();
LinkedList<Node> results = XPath.evalAp(ap);
return results;
}
@Override public LinkedList<Node> visitLetXQ(XQueryParser.LetXQContext ctx) {
HashMap<String, LinkedList<Node>> contextMapOld = new HashMap<>(contextMap);
contextStack.push(contextMapOld);
LinkedList<Node> result = visitChildren(ctx);
contextMap = contextStack.pop();
return result;
}
@Override public LinkedList<Node> visitCommaXQ(XQueryParser.CommaXQContext ctx) {
LinkedList<Node> result = new LinkedList<>();
copyOf(visit(ctx.xq(0)), result);
result.addAll(visit(ctx.xq(1)));
return result;
}
@Override public LinkedList<Node> visitVarXQ(XQueryParser.VarXQContext ctx) {
return contextMap.get(ctx.getText());
}
@Override public LinkedList<Node> visitScXQ(XQueryParser.ScXQContext ctx) {
String str = ctx.StringConstant().getText();
int len = str.length();
str = str.substring(1,len-1);
Node node = makeText(str);
LinkedList<Node> result = new LinkedList<>();
result.add(node);
return result;
}
@Override public LinkedList<Node> visitBraceXQ(XQueryParser.BraceXQContext ctx) {
return visit(ctx.xq());
}
@Override public LinkedList<Node> visitSingleSlashXQ(XQueryParser.SingleSlashXQContext ctx) {
LinkedList<Node> currentNodes = new LinkedList<>();
copyOf(visit(ctx.xq()), currentNodes);
LinkedList<Node> results = XPath.evalRp(currentNodes, ctx.rp().getText());
return results;
}
@Override public LinkedList<Node> visitDoubleSlashXQ(XQueryParser.DoubleSlashXQContext ctx) {
LinkedList<Node> currentNodes = new LinkedList<>();
copyOf(visit(ctx.xq()), currentNodes);
LinkedList<Node> descendants = getDescendants(currentNodes);
currentNodes.addAll(descendants);
LinkedList<Node> results = XPath.evalRp(currentNodes, ctx.rp().getText());
return results;
}
private void copyOf(LinkedList<Node> l1, LinkedList<Node> l2){
for (Node node : l1)
l2.add(node);
}
/*
private LinkedList<Node> forClauseHelper(int k, XQueryParser.ForClauseContext ctx){
String key = ctx.var(k).getText();
LinkedList<Node> valueList = visit(ctx.xq(k));
for (Node node: valueList){
HashMap<String, LinkedList<Node>> contextMapOld = new HashMap<>(contextMap);
contextStack.push(contextMapOld);
LinkedList<Node> value = new LinkedList<>(); value.add(node);
contextMap.put(key, value);
if (k+1 < ctx.var().size())
forClauseHelper(k+1, ctx);
contextMap = contextStack.pop();
}
}*/
@Override public LinkedList<Node> visitForClause(XQueryParser.ForClauseContext ctx) {
//forClauseHelper(0, ctx);
return null;
}
@Override public LinkedList<Node> visitLetClause(XQueryParser.LetClauseContext ctx) {
for (int i = 0; i < ctx.var().size(); i++) {
String key = ctx.var(i).getText();
LinkedList<Node> value = visit(ctx.xq(i));
contextMap.put(key, value);
}
return null;
}
@Override public LinkedList<Node> visitWhereClause(XQueryParser.WhereClauseContext ctx) {
return visit(ctx.cond());
}
@Override public LinkedList<Node> visitReturnClause(XQueryParser.ReturnClauseContext ctx) {
return visit(ctx.rt());
}
@Override public LinkedList<Node> visitTagReturn(XQueryParser.TagReturnContext ctx) {
String tagName = ctx.startTag().tagName().getText();
LinkedList<Node> nodeList = visit(ctx.rt());
Node node = makeElem(tagName, nodeList);
LinkedList<Node> result = new LinkedList<>();
result.add(node);
return result;
}
@Override public LinkedList<Node> visitXqReturn(XQueryParser.XqReturnContext ctx) { return visit(ctx.xq()); }
@Override public LinkedList<Node> visitCommaReturn(XQueryParser.CommaReturnContext ctx) {
LinkedList<Node> result = visit(ctx.rt(0));
result.addAll(visit(ctx.rt(1)));
return result;
}
@Override public LinkedList<Node> visitBraceCond(XQueryParser.BraceCondContext ctx) {
return visit(ctx.cond());
}
private boolean satisfyCondHelper(int k, XQueryParser.SatisfyCondContext ctx){
int numFor = ctx.var().size();
if (k == numFor){
if (visit(ctx.cond()).size() == 1)
return true;
}
else{
String key = ctx.var(k).getText();
LinkedList<Node> valueList = visit(ctx.xq(k));
for (Node node: valueList){
HashMap<String, LinkedList<Node>> contextMapOld = new HashMap<>(contextMap);
contextStack.push(contextMapOld);
LinkedList<Node> value = new LinkedList<>(); value.add(node);
contextMap.put(key, value);
if (k+1 <= numFor)
if (satisfyCondHelper(k+1, ctx)) {
contextMap = contextStack.pop();
return true;
}
contextMap = contextStack.pop();
}
}
return false;
}
@Override public LinkedList<Node> visitSatisfyCond(XQueryParser.SatisfyCondContext ctx) {
LinkedList<Node> result = new LinkedList<>();
if (satisfyCondHelper(0, ctx)){
Node True = doc.createTextNode("true");
result.add(True);
}
return result;
}
@Override public LinkedList<Node> visitEmptyCond(XQueryParser.EmptyCondContext ctx) {
LinkedList<Node> xqResult = visit(ctx.xq());
LinkedList<Node> result = new LinkedList<>();
if (xqResult.isEmpty()){
Node True = doc.createTextNode("true");
result.add(True);
}
return result;
}
@Override public LinkedList<Node> visitOrCond(XQueryParser.OrCondContext ctx) {
LinkedList<Node> left = new LinkedList<>(visit(ctx.cond(0)));
LinkedList<Node> right = new LinkedList<>(visit(ctx.cond(1)));
LinkedList<Node> result = new LinkedList<>();
if (left.size() > 0 || right.size() > 0){
Node True = doc.createTextNode("true");
result.add(True);
}
return result;
}
@Override public LinkedList<Node> visitAndCond(XQueryParser.AndCondContext ctx) {
LinkedList<Node> left = new LinkedList<>(visit(ctx.cond(0)));
LinkedList<Node> right = new LinkedList<>(visit(ctx.cond(1)));
LinkedList<Node> result = new LinkedList<>();
if (left.size() > 0 && right.size() > 0){
Node True = doc.createTextNode("true");
result.add(True);
}
return result;
}
@Override public LinkedList<Node> visitIsCond(XQueryParser.IsCondContext ctx) {
LinkedList<Node> left = new LinkedList<>(visit(ctx.xq(0)));
LinkedList<Node> right = new LinkedList<>(visit(ctx.xq(1)));
LinkedList<Node> result = new LinkedList<>();
for (Node l: left)
for (Node r: right)
if (l.isSameNode(r)){
Node True = doc.createTextNode("true");
result.add(True);
return result;
}
return result;
}
@Override public LinkedList<Node> visitEqCond(XQueryParser.EqCondContext ctx) {
LinkedList<Node> left = new LinkedList<>(visit(ctx.xq(0)));
LinkedList<Node> right = new LinkedList<>(visit(ctx.xq(1)));
LinkedList<Node> result = new LinkedList<>();
for (Node l: left)
for (Node r: right)
if (l.isEqualNode(r)){
Node True = doc.createTextNode("true");
result.add(True);
return result;
}
return result;
}
@Override public LinkedList<Node> visitNotCond(XQueryParser.NotCondContext ctx) {
LinkedList<Node> oppResult = new LinkedList<>(visit(ctx.cond()));
LinkedList<Node> result = new LinkedList<>();
if (oppResult.isEmpty()){
Node True = doc.createTextNode("true");
result.add(True);
}
return result;
}
@Override public LinkedList<Node> visitStartTag(XQueryParser.StartTagContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitEndTag(XQueryParser.EndTagContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitVar(XQueryParser.VarContext ctx) {
return visitChildren(ctx);
}
private Node makeText(String s){
Node result = doc.createTextNode(s);
return result;
}
private Node makeElem(String tag, LinkedList<Node> list){
Node result = outputDoc.createElement(tag);
for (Node node : list) {
if (node != null) {
Node newNode = outputDoc.importNode(node, true);
result.appendChild(newNode);
}
}
return result;
}
//from XPath
@Override public LinkedList<Node> visitDoubleAP(XQueryParser.DoubleAPContext ctx) {return visitChildren(ctx);}
@Override public LinkedList<Node> visitSingleAP(XQueryParser.SingleAPContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitDoc(XQueryParser.DocContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitBraceRP(XQueryParser.BraceRPContext ctx) { return visitChildren(ctx);}
@Override public LinkedList<Node> visitDoubleSlashRP(XQueryParser.DoubleSlashRPContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitTextRP(XQueryParser.TextRPContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitAttRP(XQueryParser.AttRPContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitParentRP(XQueryParser.ParentRPContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitSelfRP(XQueryParser.SelfRPContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitFilterRP(XQueryParser.FilterRPContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitCommaRP(XQueryParser.CommaRPContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitChildrenRP(XQueryParser.ChildrenRPContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitTagRP(XQueryParser.TagRPContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitSingleSlashRP(XQueryParser.SingleSlashRPContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitEqFilter(XQueryParser.EqFilterContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitNotFilter(XQueryParser.NotFilterContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitAndFilter(XQueryParser.AndFilterContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitIsFilter(XQueryParser.IsFilterContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitRpFilter(XQueryParser.RpFilterContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitBraceFilter(XQueryParser.BraceFilterContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitOrFilter(XQueryParser.OrFilterContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitTagName(XQueryParser.TagNameContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitAttName(XQueryParser.AttNameContext ctx) { return visitChildren(ctx); }
@Override public LinkedList<Node> visitFilename(XQueryParser.FilenameContext ctx) { return visitChildren(ctx); }
public static LinkedList<Node> getChildren(LinkedList<Node> n){
/**
* return the children of the a node (just the next level)
*/
LinkedList<Node> childrenList = new LinkedList<Node>();
for(int j = 0; j < n.size(); j++) {
Node curNode = n.get(j);
for (int i = 0; i < curNode.getChildNodes().getLength(); i++) {
childrenList.add(curNode.getChildNodes().item(i));
}
}
return childrenList;
}
public static LinkedList<Node> getChildren(Node curNode){
LinkedList<Node> childrenList = new LinkedList<Node>();
for (int i = 0; i < curNode.getChildNodes().getLength(); i++) {
childrenList.add(curNode.getChildNodes().item(i));
}
return childrenList;
}
public LinkedList<Node> getParents(LinkedList<Node> input) {
LinkedList<Node> res = new LinkedList<Node>();
for(int i = 0; i < input.size(); i++) {
Node parentNode = input.get(i).getParentNode();
if(!res.contains(parentNode)) {
res.add(parentNode);
}
}
return res;
}
public LinkedList<Node> getDescendants(LinkedList<Node> list) {
LinkedList<Node> desc = new LinkedList<Node>();
for(int i = 0; i < list.size(); i++) {
if(list.get(i).getChildNodes().getLength() != 0) {
for(int j = 0; j < list.get(i).getChildNodes().getLength(); j++) {
desc.addAll(getAllNodes(list.get(i).getChildNodes().item(j)));
}
}
}
return desc;
}
public LinkedList<Node> getAllNodes(Node n) {
LinkedList<Node> allNodes = new LinkedList<Node>();
for(int i = 0; i < n.getChildNodes().getLength(); i++) {
allNodes.addAll( getAllNodes( n.getChildNodes().item(i) ) );
}
allNodes.add(n);
return allNodes;
}
}
| [
"[email protected]"
] | |
f2e3d84baac5170d89f4a2d9d436a1cc82ddc219 | de0e1d7de3e86191d26395d7dffc0cae52e51986 | /Test/hxgraph/src/main/java/com/hxgraph/model/imp/raw/KLinePointModel.java | 154023e7f278f88afdf6c482e3a97d183b09a447 | [
"MIT"
] | permissive | liulinru13/HxGraph | 232fb3a0c3dcefd8fabf818e98d41e6c62ccb1ee | 5fc7726dfc537a540ebefeb6f2a4e71d92c26b68 | refs/heads/master | 2021-01-22T07:52:07.143773 | 2017-10-30T03:44:59 | 2017-10-30T03:44:59 | 92,581,438 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,978 | java | package com.hxgraph.model.imp.raw;
import com.hxgraph.model.Constant;
import com.hxgraph.model.imp.PointImp;
/**
* k线 一个点的数据结构
* Created by liulinru on 2017/4/25.
*/
public class KLinePointModel extends PointImp {
private double dOpenValue;//开
private double dHighValue;//高
private double dLowValue;//低
private double dCloseValue;//收
private double dPointWidth = Constant.fDefaultBarWidth;//宽度
private boolean bIsStroke = true;//填充类型,默认为不填充内部
private boolean bIsLine = false;//是否使用线条替代柱子
private float fXcoordinateRaw = 1.0f;//原始x坐标,一般为1.0f,表示与上一个点距离一个单位的步长
private float fOpenCoordinate;
private float fHighCoordinate;
private float fLowCoordinate;
private float fCloseCoordinate;
public double getdOpenValue() {
return dOpenValue;
}
public void setdOpenValue(double dOpenValue) {
this.dOpenValue = dOpenValue;
}
public double getdHighValue() {
return dHighValue;
}
public void setdHighValue(double dHighValue) {
this.dHighValue = dHighValue;
}
public boolean isbIsLine() {
return bIsLine;
}
public void setbIsLine(boolean bIsLine) {
this.bIsLine = bIsLine;
}
public double getdLowValue() {
return dLowValue;
}
public void setdLowValue(double dLowValue) {
this.dLowValue = dLowValue;
}
public double getdCloseValue() {
return dCloseValue;
}
public void setdCloseValue(double dCloseValue) {
this.dCloseValue = dCloseValue;
}
public double getdPointWidth() {
return dPointWidth;
}
public void setdPointWidth(double dPointWidth) {
this.dPointWidth = dPointWidth;
}
public boolean isbIsStroke() {
return bIsStroke;
}
public void setbIsStroke(boolean bIsStroke) {
this.bIsStroke = bIsStroke;
}
public float getfXcoordinateRaw() {
return fXcoordinateRaw;
}
public void setfXcoordinateRaw(float fXcoordinateRaw) {
this.fXcoordinateRaw = fXcoordinateRaw;
}
public float getfOpenCoordinate() {
return fOpenCoordinate;
}
public void setfOpenCoordinate(float fOpenCoordinate) {
this.fOpenCoordinate = fOpenCoordinate;
}
public float getfHighCoordinate() {
return fHighCoordinate;
}
public void setfHighCoordinate(float fHighCoordinate) {
this.fHighCoordinate = fHighCoordinate;
}
public float getfLowCoordinate() {
return fLowCoordinate;
}
public void setfLowCoordinate(float fLowCoordinate) {
this.fLowCoordinate = fLowCoordinate;
}
public float getfCloseCoordinate() {
return fCloseCoordinate;
}
public void setfCloseCoordinate(float fCloseCoordinate) {
this.fCloseCoordinate = fCloseCoordinate;
}
}
| [
"[email protected]"
] | |
ee34f96fb1ba7f4def0857a25788a8c955fc1df3 | 0fd10e2766e09250b544fb2050e0822a84a4f372 | /src/main/java/com/liuwu/util/CacheUtil.java | 48507d91eb5054e0e10405a382db671704c6a703 | [] | no_license | liuwu365/my-springboot-demo | 66a53f54abcea1855b2d5a6bb0d2eeba6cfb5857 | 28b24e0c8dd29a11fc88ea2862d9da47624a4a3f | refs/heads/master | 2021-01-20T12:25:08.182284 | 2018-03-25T08:33:15 | 2018-03-25T08:33:15 | 90,362,750 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,694 | java | package com.liuwu.util;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.util.Hashing;
import redis.clients.util.Pool;
import redis.clients.util.Sharded;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
/**
* Created by liuwu
* Create Date 04/15/16.
* Version 1.0
*/
public class CacheUtil {
private static final Logger logger = LoggerFactory.getLogger(CacheUtil.class);
private static Pool<ShardedJedis> jedisPool;
private static volatile CacheUtil instance;
private static Object object = new Object();
public static CacheUtil getInstance() {
if (instance != null) {
return instance;
} else {
synchronized (object) {
if (instance == null) {
instance = new CacheUtil();
}
}
return instance;
}
}
public CacheUtil() {
initPool();
}
private void initPool() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxWaitMillis(1000);
poolConfig.setMinIdle(2);
poolConfig.setMaxIdle(100);
poolConfig.setMaxTotal(2000);
poolConfig.setBlockWhenExhausted(false);
try {
//String configPath = System.getProperty("yt.env", "dev") + "/redis.properties";
String configPath = "redis.properties";
logger.info("load redis config, path:{}", configPath);
PropertiesConfiguration configuration = new PropertiesConfiguration();
InputStream in = this.getClass().getClassLoader().getResourceAsStream(configPath);
configuration.load(in);
List<JedisShardInfo> shards = new ArrayList();
//String name = configuration.getString("name");
String cluster = configuration.getString("cluster");
String[] hosts = cluster.split(";");
for (String s : hosts) {
String[] str = s.split(":");
String host = str[0];
String port = str[1];
JedisShardInfo jedis = new JedisShardInfo(host, Integer.valueOf(port));
shards.add(jedis);
}
jedisPool = new ShardedJedisPool(poolConfig, shards, Hashing.MURMUR_HASH,
Sharded.DEFAULT_KEY_TAG_PATTERN);
} catch (Exception ex) {
logger.error("init redis error", ex);
}
}
public String get(String key) {
ShardedJedis jedis = null;
String result = null;
try {
jedis = jedisPool.getResource();
result = jedis.get(key);
} catch (Exception e) {
logger.error("get value from redis error|key={}|ex={}", key, ErrorWriterUtil.WriteError(e).toString());
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
} else {
jedisPool.returnBrokenResource(jedis);
}
return result;
}
}
public void set(String key, String value) {
ShardedJedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.set(key, value);
} catch (Exception e) {
logger.error("set value to redis error|key={}|value={}|ex={}", key, value, StringUtil.stackTrace(e));
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
} else {
jedisPool.returnBrokenResource(jedis);
}
}
}
public void set(String key, String value, Integer expiry) {
ShardedJedis jedis = null;
try {
jedis = jedisPool.getResource();
if (CheckUtil.isEmpty(expiry) || expiry.equals(-1)) {
jedis.set(key, value);
} else {
jedis.setex(key, expiry, value);
}
} catch (Exception e) {
logger.error("set value to redis error|key={}|value={}|expiry={}|ex={}", key, value, expiry, ErrorWriterUtil.WriteError(e).toString());
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
} else {
jedisPool.returnBrokenResource(jedis);
}
}
}
//********************************************** 对象操作 start **************************************************************
/**
* 向缓存中设置对象
*
* @param key
* @param value
* @return
*/
public boolean set(byte[] key, byte[] value, Integer expiry) {
ShardedJedis jedis = null;
try {
jedis = jedisPool.getResource();
if (CheckUtil.isEmpty(expiry) || expiry.equals(-1)) {
jedis.set(key, value);
} else {
jedis.setex(key, expiry, value);
}
return true;
} catch (Exception e) {
logger.error("set value to redis error key={}|value={}|expiry={}|ex={}", key, value, expiry, ErrorWriterUtil.WriteError(e));
return false;
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
} else {
jedisPool.returnBrokenResource(jedis);
}
}
}
public byte[] get(byte[] key) {
ShardedJedis jedis = null;
byte[] result = null;
try {
jedis = jedisPool.getResource();
result = jedis.get(key);
} catch (Exception e) {
logger.error("get redis error key={}|ex={}", key, ErrorWriterUtil.WriteError(e));
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
} else {
jedisPool.returnBrokenResource(jedis);
}
return result;
}
}
// public boolean del(byte[] key){
// ShardedJedis jedis = null;
// try {
// jedis = jedisPool.getResource();
// jedis.del(key);
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }finally{
// jedisPool.returnResource(jedis);
// }
// }
public long del(byte[] key) {
return onRedisSync(jedis -> jedis.del(key));
}
public boolean sadd(byte[] key, byte[] member) {
ShardedJedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.sadd(key, member);
return true;
} catch (Exception e) {
logger.error("sadd value to redis error key={}|member={}|ex={}", key, member, ErrorWriterUtil.WriteError(e));
return false;
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
} else {
jedisPool.returnBrokenResource(jedis);
}
}
}
public Set<byte[]> getsadd(byte[] key) {
ShardedJedis jedis = null;
Set<byte[]> result = null;
try {
jedis = jedisPool.getResource();
result = jedis.smembers(key);
} catch (Exception e) {
logger.error("getsadd redis error key={}|ex={}", key, ErrorWriterUtil.WriteError(e));
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
} else {
jedisPool.returnBrokenResource(jedis);
}
return result;
}
}
public boolean sadd(String key, String member) {
ShardedJedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.sadd(key, member);
return true;
} catch (Exception e) {
logger.error("sadd redis error key={}|member={}|ex={}", key, member, ErrorWriterUtil.WriteError(e));
return false;
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
} else {
jedisPool.returnBrokenResource(jedis);
}
}
}
public Set<String> getsadd(String key) {
ShardedJedis jedis = null;
Set<String> result = null;
try {
jedis = jedisPool.getResource();
result = jedis.smembers(key);
} catch (Exception e) {
logger.error("getsadd redis error key={}|ex={}", key, ErrorWriterUtil.WriteError(e));
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
} else {
jedisPool.returnBrokenResource(jedis);
}
return result;
}
}
/**
* 从set中删除value
*
* @param key
* @return
*/
public boolean removeSetValue(String key, String value) {
ShardedJedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.srem(key, value);
return true;
} catch (Exception ex) {
logger.error("removeSetValue redis error ex={}", ex);
return false;
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
} else {
jedisPool.returnBrokenResource(jedis);
}
}
}
public boolean hset(String key, String field, String value) {
ShardedJedis jedis = null;
boolean result = false;
try {
jedis = jedisPool.getResource();
jedis.hset(key, field, value);
result = true;
} catch (Exception e) {
logger.error("hset redis error key={}|field={}|value={}|ex={}", key, field, value, ErrorWriterUtil.WriteError(e));
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
} else {
jedisPool.returnBrokenResource(jedis);
}
return result;
}
}
public String hget(String key, String field) {
ShardedJedis jedis = null;
String result = null;
try {
jedis = jedisPool.getResource();
result = jedis.hget(key, field);
} catch (Exception e) {
logger.error("hget redis error key={}|field={}|ex={}", key, field, ErrorWriterUtil.WriteError(e));
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
} else {
jedisPool.returnBrokenResource(jedis);
}
return result;
}
}
public Map<String, String> hgetAll(String key) {
ShardedJedis jedis = null;
Map<String, String> result = null;
try {
jedis = jedisPool.getResource();
result = jedis.hgetAll(key);
} catch (Exception e) {
logger.error("hgetAll redis error key={}|ex={}", key, ErrorWriterUtil.WriteError(e));
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
} else {
jedisPool.returnBrokenResource(jedis);
}
return result;
}
}
public boolean hdel(String key, String field) {
ShardedJedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.hdel(key, field);
return true;
} catch (Exception e) {
logger.error("hdel redis error key={}|field={}|ex={}", key, field, ErrorWriterUtil.WriteError(e));
return false;
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
} else {
jedisPool.returnBrokenResource(jedis);
}
}
}
/**
* 批量删除以某字符串前缀的key(hset存的数据)
*
* @param cacheName
* @param pre_str
*/
public static void batchHsetDel(String cacheName, String pre_str) {
Map<String, String> map = CacheUtil.getInstance().hgetAll(cacheName);
for (String key : map.keySet()) {
if (key.contains(pre_str)) {
CacheUtil.getInstance().hdel(cacheName, key);
}
}
}
//********************************************** 对象操作 end **************************************************************
public long del(String key) {
return onRedisSync(jedis -> jedis.del(key));
}
public long expire(String key, int seconds) {
return onRedisSync(jedis -> jedis.expire(key, seconds));
}
public long incr(String key) {
return onRedisSync(jedis -> jedis.incr(key));
}
public long incrBy(String key, int value) {
return onRedisSync(jedis -> jedis.incrBy(key, value));
}
public <T> T onRedisSync(Function<ShardedJedis, T> handler) {
ShardedJedis jedis = null;
T result = null;
try {
jedis = jedisPool.getResource();
result = handler.apply(jedis);
} catch (Exception e) {
logger.error("handler redis sync error", e);
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
} else {
jedisPool.returnBrokenResource(jedis);
}
return result;
}
}
}
| [
"[email protected]"
] | |
b5f02b7c0ad0e6f09ae1853179138f06f355d582 | 2a9eec205d40b7caddd530797eacd5c0080c4a67 | /代理模式/Agent/src/Test.java | 1bd398b931a3c20b82c540b4e212ad1b339b4e0f | [] | no_license | liulongjie8/DesignModel | 8978f35703b475585272758a770742f3d84bfd82 | bc44d616f1143da4370f252275ec91a84e4af6ac | refs/heads/master | 2020-03-28T11:48:49.127341 | 2018-09-11T02:47:20 | 2018-09-11T02:47:20 | 148,248,686 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 577 | java | public class Test {
public static void main(String[] args) {
//使用继承实现代理
MoveAble car = new Car2();
car.move();
System.out.println("******************************************");
//使用聚合实现代理
Car base = new Car();
car = new Car3(base);
car.move();
System.out.println("******************************************");
CarTimeProxy timeProxy = new CarTimeProxy(base);
CarLogProxy logProxy = new CarLogProxy(timeProxy);
logProxy.move();
}
}
| [
"[email protected]"
] | |
64452afc5a85bcbd6637694735e35fbd00cfb362 | c21f90be6ddf174d09dfa673ceaf1b11bcf0bfaa | /pinyougou-portal-web/src/main/java/com/pinyougou/portal/controller/ContentController.java | d03adf985c0c1c418a8bc46c6664d5aa616054df | [] | no_license | huguocong/pinyougou | e17ab70408b22c8f80646e5cf99afdb9555b9de3 | 3d3d7536da1e726e2a7625eba9b0db1398c71c23 | refs/heads/master | 2022-12-25T06:45:39.508987 | 2019-07-31T03:14:44 | 2019-07-31T03:14:44 | 199,753,474 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 672 | java | package com.pinyougou.portal.controller;
import java.util.List;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.pinyougou.content.service.ContentService;
import com.pinyougou.pojo.TbContent;
@RestController
@RequestMapping("/content")
public class ContentController {
@Reference
private ContentService contentService;
// 根据广告分类ID查询广告列表
@RequestMapping("/indByCategoryId")
public List<TbContent> findByCategoryId(Long categoryId) {
return contentService.findbycategerid(categoryId);
}
}
| [
"[email protected]"
] | |
039f00dc5b232691c73e53d454e49b16d3b4c034 | cc03789c0e4d7079011fe96e6a7c95a0da0fe735 | /e-sens-non-repudiation/src/main/java/eu/esens/abb/nonrep/etsi/rem/EventReasons.java | 67f38319ae9305fa275ed224835685443b485c0f | [] | no_license | health-information-exchange/openncp | d6bf161291be4ec970bd82b6ec3831ba20932476 | c8a82d8f152a5862e2846a576f5fc1e4f000be04 | refs/heads/master | 2020-06-23T11:53:43.065836 | 2017-04-21T18:36:59 | 2017-04-21T18:36:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,435 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.12.29 at 12:47:48 PM CET
//
package eu.esens.abb.nonrep.etsi.rem;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for EventReasonsType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="EventReasonsType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://uri.etsi.org/02640/v1#}EventReason" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "EventReasonsType", namespace = "http://uri.etsi.org/02640/v1#", propOrder = {
"eventReasons"
})
@XmlRootElement(name = "EventReasons", namespace = "http://uri.etsi.org/02640/v1#")
public class EventReasons {
@XmlElement(name = "EventReason", required = true)
protected List<EventReason> eventReasons;
/**
* Gets the value of the eventReasons property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the eventReasons property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getEventReasons().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link EventReason }
*
*
*/
public List<EventReason> getEventReasons() {
if (eventReasons == null) {
eventReasons = new ArrayList<EventReason>();
}
return this.eventReasons;
}
}
| [
"[email protected]"
] | |
25decae329d7c8c5d0f3f28004fe9f639e5b4011 | 745423c238792e5644bd10709c71596e0dec8bfc | /src/HashSet/XoaPhanTuTrongHashSetPhuongThucClear.java | 4fefbaf03560f81baea0fdd8b58df55281e1df9e | [] | no_license | buithom199/Basic | 04a0914eacec9d0d25503ff3c7857851d6034004 | a2894330b8cf4479bbf73cc153f38d952d96524f | refs/heads/master | 2023-06-07T07:05:52.887958 | 2021-07-01T01:53:31 | 2021-07-01T01:53:31 | 381,877,213 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 860 | java | package HashSet;
import java.util.HashSet;
public class XoaPhanTuTrongHashSetPhuongThucClear {
public static void main(String[] args) {
float fNumber;
HashSet<Float> hashSetFloat = new HashSet<>();
//thêm các phần tử vào hashSetFloat
hashSetFloat.add(7.17f);
hashSetFloat.add(19.14f);
hashSetFloat.add(1.11f);
hashSetFloat.add(20.14f);
//Xóa toàn bộ các phần tử trong hashSetFloat
//Sử dụng phương thức clear()
hashSetFloat.clear();
//Sau khi xóa thì trong hashSetFloat
//sẽ không có phần tử nào
//phương thức isEmpty() dưới đây sẽ kiểm tra
//nếu hashSetFloat không có giá trị
//thì sẽ hiển thị thông báo "Không có phần tử"
if(hashSetFloat.isEmpty()) {
System.out.println("Không có phần tử");
}
}
}
| [
"[email protected]"
] | |
c3e8dcd7014477f112977ee8a7f85e645d103e40 | 3c7651266f384282ed5642eca51c154d8e29ae03 | /src/test/java/de/danielflow/project/PermissionsLite/AppTest.java | 44e6d44dd3e904688c595a2dd7150b1ac210225a | [] | no_license | BukkitFlow/PermissionsLite | 530be32e17e3375f65d6701dd612307032e3f0cc | f4eadf710a085f99749f48874ff351628f6da69c | refs/heads/master | 2021-01-25T14:55:49.981687 | 2018-03-03T23:03:23 | 2018-03-03T23:03:23 | 123,735,809 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 703 | java | package de.danielflow.project.PermissionsLite;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| [
"[email protected]"
] | |
84febc6a063a85835830bffb51714c1199d02896 | 09925746a272cfa7aa5c447ca97bf1ef854ecb86 | /src/Day30_arrays/StudentArray.java | 94e6f3e03b5a786d3154255ea216c2c5b63a200d | [] | no_license | oledjan/Neighbors.java | 38582205aafc09f7108f6b683b2278977eabafb1 | 03dadf4189197430d1c6284035ed5107600c3366 | refs/heads/master | 2023-05-04T06:15:30.473647 | 2021-05-27T23:13:05 | 2021-05-27T23:13:05 | 371,525,696 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,563 | java | package Day30_arrays;
public class StudentArray {
public static void main(String[] args) {
String [] student1 = new String[5];
student1[0] = "AD1234";
student1[1] = "Adam";
student1[2] = "Smith";
student1[3] = "B22";
student1[4] = "202-543-1234";
// 2nd way how you do array when you know all info
String [] student2 = {"MK4421", "Mike", "Bloomberg", "B22", "703-432-1234"};
System.out.println("student id = "+ student1[0]);
System.out.println("student1 first Name = "+ student1[1]);
System.out.println("student1 last Name = "+ student1 [2]);
System.out.println("student1 Batch number = "+ student1[3]);
System.out.println("student1 student mobile number = "+ student1 [4]);
System.out.println("student data length: " + student1.length);
// check if student1 data array contains 5 items.
// true: pass: array has correct length
// false: fail: has incorrect length
if (student1.length == 5) {
System.out.println("PASS: array has correct length");
} else{
System.out.println("FAIL: has incorrect length");
} //"Adam" --> ADAM space Smith --> SMITH
System.out.println((student1[1].toUpperCase() + " " + student1[2].toUpperCase()));
// read mobile from array and store into variable
String mobileNum = student1[4];
System.out.println(mobileNum.startsWith("204")); // false we don't have number 204
}
}
| [
"[email protected]"
] | |
2dbf0a1a03c02b0afb3e3502c0cd3b01a72b2f73 | 8a8254c83cc2ec2c401f9820f78892cf5ff41384 | /baseline/materialistic/app/src/test/java/baseline/io/github/hidroh/materialistic/test/TestListActivity.java | 88adbf20dc50fbb201f17812fae3e61b35a0e6e5 | [
"Apache-2.0"
] | permissive | VU-Thesis-2019-2020-Wesley-Shann/subjects | 46884bc6f0f9621be2ab3c4b05629e3f6d3364a0 | 14a6d6bb9740232e99e7c20f0ba4ddde3e54ad88 | refs/heads/master | 2022-12-03T05:52:23.309727 | 2020-08-19T12:18:54 | 2020-08-19T12:18:54 | 261,718,101 | 0 | 0 | null | 2020-07-11T12:19:07 | 2020-05-06T09:54:05 | Java | UTF-8 | Java | false | false | 493 | java | package baseline.io.github.hidroh.materialistic.test;
import android.view.Menu;
import static org.robolectric.Shadows.shadowOf;
public class TestListActivity extends baseline.io.github.hidroh.materialistic.ListActivity {
@Override
public void supportInvalidateOptionsMenu() {
Menu optionsMenu = shadowOf(this).getOptionsMenu();
if (optionsMenu != null) {
onCreateOptionsMenu(optionsMenu);
onPrepareOptionsMenu(optionsMenu);
}
}
}
| [
"[email protected]"
] | |
7ff00b6e95b2b4f80c4bf9b8218d33c9263fb2d2 | 79595075622ded0bf43023f716389f61d8e96e94 | /app/src/main/java/android/webkit/JsPromptResult.java | ecece3810b9f386f96673ab506d324d25381d46c | [] | no_license | dstmath/OppoR15 | 96f1f7bb4d9cfad47609316debc55095edcd6b56 | b9a4da845af251213d7b4c1b35db3e2415290c96 | refs/heads/master | 2020-03-24T16:52:14.198588 | 2019-05-27T02:24:53 | 2019-05-27T02:24:53 | 142,840,716 | 7 | 4 | null | null | null | null | UTF-8 | Java | false | false | 425 | java | package android.webkit;
import android.webkit.JsResult.ResultReceiver;
public class JsPromptResult extends JsResult {
private String mStringResult;
public void confirm(String result) {
this.mStringResult = result;
confirm();
}
public JsPromptResult(ResultReceiver receiver) {
super(receiver);
}
public String getStringResult() {
return this.mStringResult;
}
}
| [
"[email protected]"
] | |
52f2cf392994e0c166e3c271dcf8945f90ae7b35 | 469f95fc1fc1d202193ce092a3f69537766b3276 | /app/src/androidTest/java/com/example/markmycar/ExampleInstrumentedTest.java | cc237280abc0301ff0190de3976b52ade8a45602 | [] | no_license | dczerwinski/Mark_my_car | 7b128fc62b5a881a5dcf34d28ad90db5d7c3fcab | 5cc38db62e77a952d9d1e8a8736d7e54f23db75e | refs/heads/master | 2022-01-11T20:54:05.358517 | 2019-07-07T19:50:07 | 2019-07-07T19:50:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 713 | java | package com.example.markmycar;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.markmycar", appContext.getPackageName());
}
}
| [
"[email protected]"
] | |
3e23735bf7759b2123df74c651d01b07f8e7e879 | 5bf1d631977f22aee3d2caf4a23988af0994bcce | /hazelcast/src/main/java/com/hazelcast/concurrent/atomicreference/SetAndGetOperation.java | 7a3aa73aa352cea4cc77da55b9244b251a57bdb1 | [
"Apache-2.0"
] | permissive | drewrm/hazelcast | b0a898e1aedb9344e42036e4d21bd4b24a14e6ac | b5eaf967dfc2137a116ce5e3e0d1974aa9002c6c | refs/heads/master | 2020-12-26T01:30:11.205588 | 2014-02-14T05:19:30 | 2014-02-14T05:19:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,264 | java | package com.hazelcast.concurrent.atomicreference;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.spi.Operation;
import java.io.IOException;
public class SetAndGetOperation extends AtomicReferenceBackupAwareOperation {
private Data newValue;
private Data returnValue;
public SetAndGetOperation() {
}
public SetAndGetOperation(String name, Data newValue) {
super(name);
this.newValue = newValue;
}
@Override
public void run() throws Exception {
ReferenceWrapper reference = getReference();
reference.getAndSet(newValue);
returnValue = newValue;
}
@Override
public Object getResponse() {
return returnValue;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeObject(newValue);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
newValue = in.readObject();
}
@Override
public Operation getBackupOperation() {
return new SetBackupOperation(name, newValue);
}
} | [
"[email protected]"
] | |
5e79dc2e6f7151f941db1d44bae786f7c4a80845 | 73267be654cd1fd76cf2cb9ea3a75630d9f58a41 | /services/dli/src/main/java/com/huaweicloud/sdk/dli/v1/model/ListDatabasesResponse.java | ae1543e4daf742cc6ccaae92abd38e430d1ad508 | [
"Apache-2.0"
] | permissive | huaweicloud/huaweicloud-sdk-java-v3 | 51b32a451fac321a0affe2176663fed8a9cd8042 | 2f8543d0d037b35c2664298ba39a89cc9d8ed9a3 | refs/heads/master | 2023-08-29T06:50:15.642693 | 2023-08-24T08:34:48 | 2023-08-24T08:34:48 | 262,207,545 | 91 | 57 | NOASSERTION | 2023-09-08T12:24:55 | 2020-05-08T02:27:00 | Java | UTF-8 | Java | false | false | 4,507 | java | package com.huaweicloud.sdk.dli.v1.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.huaweicloud.sdk.core.SdkResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
/**
* Response Object
*/
public class ListDatabasesResponse extends SdkResponse {
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "is_success")
private Boolean isSuccess;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "message")
private String message;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "database_count")
private Integer databaseCount;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "databases")
private List<Database> databases = null;
public ListDatabasesResponse withIsSuccess(Boolean isSuccess) {
this.isSuccess = isSuccess;
return this;
}
/**
* 执行请求是否成功。“true”表示请求执行成功。
* @return isSuccess
*/
public Boolean getIsSuccess() {
return isSuccess;
}
public void setIsSuccess(Boolean isSuccess) {
this.isSuccess = isSuccess;
}
public ListDatabasesResponse withMessage(String message) {
this.message = message;
return this;
}
/**
* 系统提示信息,执行成功时,信息可能为空。
* @return message
*/
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public ListDatabasesResponse withDatabaseCount(Integer databaseCount) {
this.databaseCount = databaseCount;
return this;
}
/**
* 数据库的总数。
* @return databaseCount
*/
public Integer getDatabaseCount() {
return databaseCount;
}
public void setDatabaseCount(Integer databaseCount) {
this.databaseCount = databaseCount;
}
public ListDatabasesResponse withDatabases(List<Database> databases) {
this.databases = databases;
return this;
}
public ListDatabasesResponse addDatabasesItem(Database databasesItem) {
if (this.databases == null) {
this.databases = new ArrayList<>();
}
this.databases.add(databasesItem);
return this;
}
public ListDatabasesResponse withDatabases(Consumer<List<Database>> databasesSetter) {
if (this.databases == null) {
this.databases = new ArrayList<>();
}
databasesSetter.accept(this.databases);
return this;
}
/**
* 查询所有数据库的响应参数。
* @return databases
*/
public List<Database> getDatabases() {
return databases;
}
public void setDatabases(List<Database> databases) {
this.databases = databases;
}
@Override
public boolean equals(java.lang.Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
ListDatabasesResponse that = (ListDatabasesResponse) obj;
return Objects.equals(this.isSuccess, that.isSuccess) && Objects.equals(this.message, that.message)
&& Objects.equals(this.databaseCount, that.databaseCount) && Objects.equals(this.databases, that.databases);
}
@Override
public int hashCode() {
return Objects.hash(isSuccess, message, databaseCount, databases);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ListDatabasesResponse {\n");
sb.append(" isSuccess: ").append(toIndentedString(isSuccess)).append("\n");
sb.append(" message: ").append(toIndentedString(message)).append("\n");
sb.append(" databaseCount: ").append(toIndentedString(databaseCount)).append("\n");
sb.append(" databases: ").append(toIndentedString(databases)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| [
"[email protected]"
] | |
a31ea6b1fd687a212c07824a639dbba0a5642c15 | 79864def3f1baca500e640a8ace2ec87c469d56e | /java01/src/step06/Test01_5.java | f9bea20117f9d8d5a5a0931712c144cd9f32f4be | [] | no_license | kwonbongsoo/BIT93 | d483fa0b1f3e3698fa79bf442b09614b56854115 | 880c81e0a3c8953dc8d7195a417b3f3dd46cdcd8 | refs/heads/master | 2021-05-15T12:26:17.113391 | 2017-10-26T17:36:41 | 2017-10-26T17:36:41 | 108,443,715 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 675 | java | /*
*/
package step06;
public class Test01_5 {
public static void main(String[] args) {
Student2 s1 = new Student2();
s1.init( "홍길동", 100, 100, 100);
s1.compute();
s1.print();
Student2 s2 = new Student2();
s2.init("임꺽정", 90, 90, 90);
s2.compute();
s2.print();
Student s3 = new Student();
Student.init(s3, "유관순", 80, 80, 80);
Student.compute(s3);
Student.print(s3);
//객체 인스턴스 함수의 static 의 차이
//사용법이 다르다.
//static 으로 선언하면 this 기능이 내장 되어 있지 않아 파라미터로 객체주소를 넘겨줘야 한다.
}
}
| [
"[email protected]"
] | |
b8e9fa169bcea903e995404a625d1f17ac55493e | 516831802f4461c8819e18e22b3ff6f0d4eae065 | /src/main/java/com/w/prod/models/entity/enums/UserType.java | 33f391a695d1ff1046d18672ae2aa861eb499561 | [] | no_license | mirchev1977/worth-products-store | 686eea2f4a4c873eb9142f04e19e304b7ac034d7 | e2ef9ea0c6da8252438c617b1dbc9eb69bd09f1e | refs/heads/master | 2023-04-01T06:42:12.399078 | 2021-04-18T09:44:36 | 2021-04-18T09:44:36 | 353,992,166 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 90 | java | package com.w.prod.models.entity.enums;
public enum UserType {
Company, University
}
| [
"[email protected]"
] | |
de62d853d41cafbe52507c3e89d677bb66a78308 | b4b62c5c77ec817db61820ccc2fee348d1d7acc5 | /src/main/java/com/alipay/api/domain/KbAdvertAddChannelRequest.java | c620d76b3c05480312116f2470acca162f0dfc93 | [
"Apache-2.0"
] | permissive | zhangpo/alipay-sdk-java-all | 13f79e34d5f030ac2f4367a93e879e0e60f335f7 | e69305d18fce0cc01d03ca52389f461527b25865 | refs/heads/master | 2022-11-04T20:47:21.777559 | 2020-06-15T08:31:02 | 2020-06-15T08:31:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,023 | java | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 口碑客渠道信息
*
* @author auto create
* @since 1.0, 2017-03-03 10:40:48
*/
public class KbAdvertAddChannelRequest extends AlipayObject {
private static final long serialVersionUID = 1692477237218825325L;
/**
* 描述信息(页面上不展现)
*/
@ApiField("memo")
private String memo;
/**
* 渠道名称
*/
@ApiField("name")
private String name;
/**
* 类型可以通过koubei.advert.data.conf.query查询
OFFLINE:线下推广
*/
@ApiField("type")
private String type;
public String getMemo() {
return this.memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
}
| [
"[email protected]"
] | |
fc68a126b32de9c03d465379093c9fd0131d529b | 089ea1149c451eaaaaa6c023f5242a8e61dbe8c8 | /App/src/main/java/com/example/demo/info/TimerInfo.java | 11538eee12115cd88901823a32ce44ae689516bb | [] | no_license | ferain95/quartzApp | 6f65f1f1e41312e1cd0e6ab300a009d4e1cd3581 | 158b9787d96a9ddab3df9c4ccff5ca953fe92a02 | refs/heads/master | 2023-03-05T09:30:20.481233 | 2021-02-19T10:20:02 | 2021-02-19T10:20:02 | 340,293,944 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,443 | java | package com.example.demo.info;
import java.io.Serializable;
public class TimerInfo implements Serializable {
private int totalFireCount;
private int remainingFireCount;
private boolean runForever;
private long repeatIntervalMs;
private long initialSetOffMs;
private String callbackData;
public int getRemainingFireCount() {
return remainingFireCount;
}
public void setRemainingFireCount(int remainingFireCount) {
this.remainingFireCount = remainingFireCount;
}
public int getTotalFireCount() {
return totalFireCount;
}
public void setTotalFireCount(int totalFireCount) {
this.totalFireCount = totalFireCount;
}
public boolean isRunForever() {
return runForever;
}
public void setRunForever(boolean runForever) {
this.runForever = runForever;
}
public long getRepeatIntervalMs() {
return repeatIntervalMs;
}
public void setRepeatIntervalMs(long repeatIntervalMs) {
this.repeatIntervalMs = repeatIntervalMs;
}
public long getInitialSetOffMs() {
return initialSetOffMs;
}
public void setInitialSetOffMs(long initialSetOffMs) {
this.initialSetOffMs = initialSetOffMs;
}
public String getCallbackData() {
return callbackData;
}
public void setCallbackData(String callbackData) {
this.callbackData = callbackData;
}
}
| [
"[email protected]"
] | |
61cc15331f2d5ae09418caff887eecd367d16ea4 | a130768c1822b37da11fd518ef9c3b7b67c2d693 | /sample-db/src/main/java/com/ai/sample/db/service/RateShoppingPropertyDetailsServiceImpl.java | 25fc41d45f31c151e602770856139a1c2a42caa4 | [] | no_license | aatmasidha/examplecode | 3cbfd9594b427f5a268379cd824c5612c2da301c | 3138cce25a54d1aae1594f0c1a9077a48aafc1a1 | refs/heads/master | 2021-01-19T02:49:38.284433 | 2017-04-05T12:29:07 | 2017-04-05T12:32:45 | 87,295,262 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,745 | java | package com.ai.sample.db.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ai.sample.common.dto.configuration.CityDTO;
import com.ai.sample.common.dto.rateshopping.RateShoppingPropertyDTO;
import com.ai.sample.common.exception.ISellDBException;
import com.ai.sample.db.dao.rateshopping.RateShoppingPropertyDetailsDao;
import com.ai.sample.db.model.rateshopping.RateShoppingPropertyDetails;
@Service("rateShoppingPropertyDetailsService")
@Transactional
public class RateShoppingPropertyDetailsServiceImpl implements
RateShoppingPropertyDetailsService {
Logger logger = Logger.getLogger(RateShoppingPropertyDetailsServiceImpl.class);
@Autowired
RateShoppingPropertyDetailsDao rateShoppingPropertyDetailsDao;
@Override
public void saveOrUpdateRateShoppingRateShoppingPropertyDetails(
RateShoppingPropertyDTO propertyDetailsDTO) throws ISellDBException {
logger.debug("Update / Save Rateshopping property record for property" + propertyDetailsDTO.toString());
try
{
RateShoppingPropertyDetails rateShoppingPropertyDetails = null;
String propertyCode = propertyDetailsDTO.getPropertyCode();
rateShoppingPropertyDetails = rateShoppingPropertyDetailsDao.findRateShoppingPropertyDetailsPropertyCode(propertyCode);
if(rateShoppingPropertyDetails == null )
{
rateShoppingPropertyDetails
= new RateShoppingPropertyDetails(propertyDetailsDTO.getName(), propertyCode,
propertyDetailsDTO.getHotelChainName(), propertyDetailsDTO.getAddress(),
propertyDetailsDTO.getCountry(), propertyDetailsDTO.getState(), propertyDetailsDTO.getCity(),
propertyDetailsDTO.getPinCode(), propertyDetailsDTO.getCapcity(), propertyDetailsDTO.getRanking(),
propertyDetailsDTO.getPropertyStatus(), propertyDetailsDTO.getHotelCurrency(), propertyDetailsDTO.getLongitude(),
propertyDetailsDTO.getLatitude(), propertyDetailsDTO.getCreationDate(), propertyDetailsDTO.getLastUpdateDate());
}
rateShoppingPropertyDetailsDao.saveRateShoppingPropertyDetails(rateShoppingPropertyDetails);
}
catch(RuntimeException e)
{
e.printStackTrace();
logger.error("RuntimeException in RateShoppingPropertyDetailsServiceImpl : " + e.getCause());
throw new ISellDBException(-1, e.getMessage());
}
}
@Override
public List<RateShoppingPropertyDTO> findAllHotelRateShoppingPropertyDetails()
throws ISellDBException {
List<RateShoppingPropertyDetails> rateShoppingPropertyList = rateShoppingPropertyDetailsDao.findAllRateShoppingProperties();
List<RateShoppingPropertyDTO> rateShoppingPropertyDTOList = new ArrayList<RateShoppingPropertyDTO>();
for(RateShoppingPropertyDetails rateShoppingProperty : rateShoppingPropertyList)
{
RateShoppingPropertyDTO rateShoppingPropertyDTO = new RateShoppingPropertyDTO(rateShoppingProperty.getName(), rateShoppingProperty.getPropertyCode(), rateShoppingProperty.getHotelChainName(),
rateShoppingProperty.getAddress(), rateShoppingProperty.getCountry(), rateShoppingProperty.getState(), rateShoppingProperty.getCity(),
rateShoppingProperty.getPinCode(), rateShoppingProperty.getCapcity(), /*rateShoppingProperty.getRanking(),*/ rateShoppingProperty.getPropertyStatus(),
/*rateShoppingProperty.getHotelCurrency(),*/ rateShoppingProperty.getLongitude(), rateShoppingProperty.getLatitude(), null, rateShoppingProperty.getCreationDate(), rateShoppingProperty.getLastUpdateDate());
rateShoppingPropertyDTOList.add(rateShoppingPropertyDTO);
}
return rateShoppingPropertyDTOList;
}
@Override
public List<RateShoppingPropertyDTO> findRateShoppingPropertyDetailsByPropertyName(
String propertyName) throws ISellDBException {
// TODO Auto-generated method stub
return null;
}
@Override
public List<RateShoppingPropertyDTO> findRateShoppingPropertyDetailsByPropertyCode(
String propertyCode) throws ISellDBException {
// TODO Auto-generated method stub
return null;
}
@Override
public List<RateShoppingPropertyDTO> findRateShoppingUnmappedProperties()
throws ISellDBException {
List<RateShoppingPropertyDetails> rateShoppingPropertyDetailsList = rateShoppingPropertyDetailsDao.findListOfUnmappedRateShoppingProperties();
List<RateShoppingPropertyDTO> rateShoppingUnmappedPropertyDetailsDTOList = new ArrayList<RateShoppingPropertyDTO>();
for(RateShoppingPropertyDetails rateShoppingPropertyDetails : rateShoppingPropertyDetailsList)
{
CityDTO cityDto = new CityDTO(rateShoppingPropertyDetails.getCity(),
rateShoppingPropertyDetails.getState(), rateShoppingPropertyDetails.getCountry());
RateShoppingPropertyDTO propertyDetailsDto = new RateShoppingPropertyDTO(rateShoppingPropertyDetails.getId(), rateShoppingPropertyDetails.getName(), rateShoppingPropertyDetails.getPropertyCode(),
rateShoppingPropertyDetails.getHotelChainName(), rateShoppingPropertyDetails.getAddress(),
rateShoppingPropertyDetails.getCountry(), rateShoppingPropertyDetails.getState(), rateShoppingPropertyDetails.getCity(),
rateShoppingPropertyDetails.getPinCode(), rateShoppingPropertyDetails.getCapcity(), rateShoppingPropertyDetails.getPropertyStatus(),
rateShoppingPropertyDetails.getLongitude(), rateShoppingPropertyDetails.getLatitude(), null,
rateShoppingPropertyDetails.getCreationDate(), new Date());
propertyDetailsDto.setRanking(rateShoppingPropertyDetails.getRanking());
rateShoppingUnmappedPropertyDetailsDTOList.add(propertyDetailsDto);
}
return rateShoppingUnmappedPropertyDetailsDTOList;
}
}
| [
"[email protected]"
] | |
950ac7eb5869d458a6bfacf7f46dd3c6cbeac180 | 76b922645092c53e3eabcbcf52269c62b521ed3e | /app/src/androidTest/java/com/example/sec/woodongsa/ApplicationTest.java | d8ff3ee08f3ecf0f1cfa62cc6f1204567a1a40de | [] | no_license | hanjimin/Woodongsa | 3703edd5d19a96275811b5558fd1b2208b89604c | d451f913d733f29a249655f44eb8c031927c5496 | refs/heads/master | 2021-01-10T11:04:19.283261 | 2016-03-16T05:08:59 | 2016-03-16T05:08:59 | 54,001,612 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 356 | java | package com.example.sec.woodongsa;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | [
"[email protected]"
] | |
65f9d77ae52fc306419af9a8173ce98dd903bbcc | 109d94ff5665115344626d6dcc9dc9c0b810a3c6 | /04-JPA/src/main/java/carservice/Application.java | e0ab4a79e824a5598fad18cd4a10fc9024dcaa31 | [] | no_license | jbcamp/sort-spring-boot | a74e037f625ad08f46ba5a97c5eda93e8700469a | 66b3be24582298a8773bad64677b1186ae0cd291 | refs/heads/master | 2016-09-05T16:39:24.142339 | 2014-10-13T14:02:15 | 2014-10-13T14:02:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 568 | java | package carservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.repository.CrudRepository;
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| [
"[email protected]"
] | |
a0fd477863e6d376a04068be524162b68ee6da3c | c55ba96bdf1983126b6944b0f90bc5c564e0601f | /src/main/java/org/gbif/cli/converter/UuidConverter.java | dc28fc42034b33be127bb30b9248e1420b421b29 | [
"Apache-2.0"
] | permissive | gbif/gbif-cli | c39f778a77b9bce7eae5e06f26d96c4ac054a972 | e10aec43a4848d082e08b973732c1f325f9afefc | refs/heads/master | 2023-05-02T12:46:40.788822 | 2021-01-20T08:14:49 | 2021-01-20T08:14:49 | 15,904,171 | 0 | 1 | Apache-2.0 | 2023-04-15T17:03:53 | 2014-01-14T14:21:05 | Java | UTF-8 | Java | false | false | 478 | java | package org.gbif.cli.converter;
import java.util.UUID;
import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.ParameterException;
/**
* Converts parameters into UUIDs.
*/
public class UuidConverter implements IStringConverter<UUID> {
@Override
public UUID convert(String value) {
try {
return UUID.fromString(value);
} catch(IllegalArgumentException ex) {
throw new ParameterException(value + " is not a valid uuid");
}
}
}
| [
"[email protected]"
] | |
319201b26c7b11243e6459a6007c7199eaf61056 | 6705ac34d021b8cf4802fd54d8e1d28e0a32b956 | /d_24_homework_xiejun/src/main/java/com/example/d_24_homework/Special/SpecialFragment.java | d37316fd62617d775d61289d00b608d0546a2908 | [] | no_license | androidxiejun/xiejunproject | d1b13cc3e536aa70a4f624c11d5d91b7bd8b7888 | d3648467217f6dcb95ab66e0eb8ea60bfae1fd3a | refs/heads/master | 2020-09-27T09:35:25.381879 | 2016-08-20T02:37:20 | 2016-08-20T02:37:20 | 66,050,794 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,832 | java | package com.example.d_24_homework.Special;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.d_24_homework.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2016/8/7.
*/
public class SpecialFragment extends Fragment{
private Context mContext;
private TabLayout mTabLayout;
private ViewPager mVp;
private MySpecialAdapter mAdapter;
private SpecialFragmentLeft specialFragmentLeft;
private SpecialFragmentRight specialFragmentRight;
private List<String>titleList=new ArrayList<>();
private List<Fragment>fragmentList=new ArrayList<>();
public static SpecialFragment newInstance(){
return new SpecialFragment();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext=getContext();
specialFragmentLeft=SpecialFragmentLeft.newInstance();
specialFragmentRight=SpecialFragmentRight.newInstance();
mAdapter=new MySpecialAdapter(getFragmentManager());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.special_fragment_layout,container,false);
mVp= (ViewPager) view.findViewById(R.id.view_pager_special);
initTabLayout(view);
initTitle();
mVp.setAdapter(mAdapter);
mTabLayout.setupWithViewPager(mVp);
return view;
}
private void initTitle(){
titleList.add(" 暴打星期三 ");
titleList.add(" 新游周刊 ");
fragmentList.add(specialFragmentLeft);
fragmentList.add(specialFragmentRight);
}
private void initTabLayout(View view){
mTabLayout= (TabLayout) view.findViewById(R.id.special_tab_layout);
}
class MySpecialAdapter extends FragmentPagerAdapter {
public MySpecialAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return fragmentList==null? 0:fragmentList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return titleList.get(position);
}
}
}
| [
"[email protected]"
] | |
a927dc2cbdd728e84ca0cb6e39fa42caa02e866d | b2af2a4d776b06be4cb6fddb7633a61809d00f5b | /Java Code/BetterCombat/src/me/WhitePrism/BetterCombat/CombatPlayer.java | 82e75a4e867374a315cd00e390058c1cf267d61f | [] | no_license | codeWorth/Code | b5b85017299f2fd9787b3c6629fa213e41c98c49 | f47075c7c15ebfc2f6b29922f0f1760e59088ccf | refs/heads/master | 2020-05-21T04:22:51.555391 | 2017-01-03T00:26:39 | 2017-01-03T00:26:39 | 44,289,002 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 16,766 | java | package me.WhitePrism.BetterCombat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitRunnable;
public class CombatPlayer{
//general player information
public Player player;
public JavaPlugin plugin;
//changing member variables
//charging bars
public double attackCharge = 99;
public double defendCharge = 99;
public double energy = 99;
//misc changing member variables
public int tick = 0;
public boolean stuned = false;
public double dismemberedAmount = 0;
public ItemStack itemInHandAtDismember = null;
public boolean shouldReportAxeUnrage = true;
public boolean shouldReportSwordUnrage = true;
public ItemStack selectedPotion = null;
public int selectedSlot = 0;
//reporting variables
public boolean sword100 = false;
public boolean swordFull = false;
public boolean axe100 = false;
public boolean axeFull = false;
//Rage variables
public double swordRage = 0;
public double axeRage = 0;
public boolean swordEnraged = false;
public boolean axeEnraged = false;
public double swordTimeForRageReset = 35; //ticks
public double axeTimeForRageReset = 4; //ticks
//variables related to the choke hold
public boolean isInChokeHold = false; //if this player is the on being choked.
public boolean isChockingOther = false; //if this player is the one chocking the other player
public double chokeAmount = 0;
private final int ticksForLessAir = 30;
public CombatPlayer chokePartner;
//variables related to stunning
public Location stunPlace;
public BukkitRunnable runningStun;
//all constants
//attack related constants
private final double attackChange = 1.5;
private final double aboveAttack100Change = 0.5;
//defend related constants
private final double defendRegen = 1;
private final double defendChange = 2.25;
private final double maxDefend = 100;
//spell costs
private final double dotAddChange = 40;
//energy related constants
private final double energyRegen = 1;
private final double maxEnergy = 100;
//misc. constants
private final double angleRange = 60;
private final double dist = -1;
private final double maxAttack = 300; //highest of all weapon's maxAttack, or more
private final double decreaseForRage = 0.5;
//ArrayLists
private static Map<String, CombatPlayer> combatplayers = new HashMap<String, CombatPlayer>();
private List<Dot> Dots = new ArrayList<Dot>();
private CombatPlayer(Player player, JavaPlugin plugin) {
this.player = player;
this.plugin = plugin;
final CombatPlayer combPlayer = this;
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable (){
public void run(){
update(combPlayer);
}
}, 0, 1);
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable (){
public void run(){
useDots(combPlayer);
}
}, 0, 20);
combatplayers.put(player.getName(), this);
}
// Return a running instance (or create a new one)
public static CombatPlayer getInstanceOfPlayer(Player player, JavaPlugin plugin) {
if(!combatplayers.containsKey(player.getName())) {
return new CombatPlayer(player,plugin);
}
else if(combatplayers.containsKey(player.getName())) {
return combatplayers.get(player.getName());
}
else {
return null;
}
}
//Methods run on the scheduler
public void update(CombatPlayer player){
if (this.stuned){
this.player.teleport(this.stunPlace);
}
if (player.attackCharge < player.maxAttack && !this.swordEnraged){
if (player.attackCharge >= 100 && !this.sword100){
player.player.sendMessage(ChatColor.RED + "Sword attack at 100 percent!");
this.sword100 = true;
}
if (player.attackCharge * Axe.attackBarMult >= 100 && !this.axe100){
player.player.sendMessage(ChatColor.RED + "Axe attack at 100 percent!");
this.axe100 = true;
}
if (player.attackCharge < 100){
player.attackCharge += player.attackChange;
} else {
player.attackCharge += player.aboveAttack100Change;
}
if (player.attackCharge >= player.maxAttack){
player.attackCharge = player.maxAttack;
}
if (player.attackCharge >= Sword.maxAttack && !this.swordFull){
player.player.sendMessage(ChatColor.RED + "Sword attack fully charged!");
this.swordFull = true;
}
if (player.attackCharge * Axe.attackBarMult >= Axe.maxAttack && !this.axeFull){
player.player.sendMessage(ChatColor.RED + "Axe attack fully charged!");
this.axeFull = true;
}
} else if (this.swordEnraged){
player.attackCharge = Sword.maxAttack;
player.defendCharge = this.maxDefend;
}
if (player.player.isBlocking()){
if (player.defendCharge > 0){
player.defendCharge += player.defendChange * -1;
if (player.defendCharge <= 0){
player.defendCharge = 0;
}
}
} else {
if (player.defendCharge < player.maxDefend){
if (player.defendCharge < 100 && player.defendCharge+player.defendRegen > 100){
player.player.sendMessage(ChatColor.RED + "Blocking at 100 percent!");
}
player.defendCharge += player.defendRegen;
if (player.defendCharge >= player.maxDefend){
player.defendCharge = player.maxDefend;
player.player.sendMessage(ChatColor.GREEN + "Block fully charged!");
}
}
}
if (player.energy < player.maxEnergy){
player.energy += player.energyRegen;
if (player.energy >= player.maxEnergy){
player.energy = player.maxEnergy;
player.player.sendMessage(ChatColor.YELLOW + "Energy fully charged!");
}
}
if (this.tick % this.ticksForLessAir == 0 && this.isChockingOther){
this.chokingHandleBoolean(this.changeChoke(), this);
}
if (this.swordEnraged){
this.swordRage -= this.decreaseForRage;
if (this.swordRage <= 0){
this.swordEnraged = false;
}
} else {
if (this.swordTimeForRageReset <= 0){
if (this.shouldReportSwordUnrage){
this.swordTimeForRageReset = 0;
this.player.sendMessage(ChatColor.AQUA + "You have lost your sword rage." );
this.swordRage = 0;
this.shouldReportSwordUnrage = false;
}
} else {
this.swordTimeForRageReset -= 1;
}
if (this.swordRage >= 100){
this.swordEnraged = true;
this.shouldReportSwordUnrage = true;
this.swordTimeForRageReset = 1;
this.player.sendMessage(ChatColor.AQUA + "Your sword has become " + ChatColor.RED + " enraged!");
}
}
if (this.axeEnraged){
Axe.critChance = 0.6;
Axe.attackBarMult = 1.25;
Axe.stunChance = 0.6;
this.axeRage -= this.decreaseForRage;
if (this.axeRage <= 0){
Axe.critChance = 0.1;
Axe.attackBarMult = 0.75;
Axe.stunChance = 0.1;
this.axeEnraged = false;
}
} else {
if (this.axeTimeForRageReset <= 0){
if (this.shouldReportAxeUnrage){
this.axeTimeForRageReset = 0;
this.player.sendMessage(ChatColor.AQUA + "You have lost your axe rage." );
this.axeRage = 0;
this.shouldReportAxeUnrage = false;
}
} else {
this.axeTimeForRageReset -= 1;
}
if (this.axeRage >= 100){
this.axeEnraged = true;
this.shouldReportAxeUnrage = true;
this.axeTimeForRageReset = 1;
this.player.sendMessage(ChatColor.AQUA + "Your axe has become " + ChatColor.RED + " enraged!");
}
}
if (this.dismemberedAmount > 0){
this.dismemberedAmount -= 1;
if (this.dismemberedAmount <= 0){
this.player.setItemInHand(this.itemInHandAtDismember);
this.player.sendMessage(ChatColor.AQUA + "Your arm has healed!");
}
}
this.tick += 1;
}
public void useDots(CombatPlayer player){
List<Integer> toRemoveIndecies = new ArrayList<Integer>();
double totalDamage = 0;
int length = this.Dots.toArray().length;
for(int i = 0;i < length;i++) {
Dot thisDot = this.Dots.get(i);
double damage = thisDot.tick();
if (damage == 0){
toRemoveIndecies.add(i);
} else {
totalDamage += damage;
}
}
for (Integer removeIndex : toRemoveIndecies){
this.Dots.remove(removeIndex);
}
if (totalDamage > 0){
player.player.damage(totalDamage);
}
}
//Stun methods
public void cancelStun(){
if (this.stuned){
this.stuned = false;
this.runningStun.cancel();
this.player.removePotionEffect(PotionEffectType.CONFUSION);
}
}
public boolean changeChoke(){
if (this.isChockingOther){
this.chokeAmount += Sword.chokeChange;
this.chokePartner.chokeAmount = this.chokeAmount;
if (this.chokeAmount <= -0.8 && this.chokeAmount + Sword.chokeChange > 0.8){
this.player.sendMessage(ChatColor.RED + "Your enemy is slipping from your grasp!");
this.chokePartner.player.sendMessage(ChatColor.RED + "You are slipping from the enemy's grasp!");
}
if (this.chokeAmount >= 0.8 && this.chokeAmount - Sword.chokeChange < 0.8){
this.player.sendMessage(ChatColor.RED + "You feel the enemy begin to lose consciousness.");
this.chokePartner.player.sendMessage(ChatColor.RED + "You begin to feel dizzy and light headed, you are running out of air!");
}
if (this.chokeAmount > 0 && this.chokeAmount - Sword.chokeChange < 0){
this.player.sendMessage(ChatColor.AQUA + "You have gained the upper hand!");
this.chokePartner.player.sendMessage(ChatColor.RED + "You have lost the upper hand!");
}
if (this.chokeAmount < 0 && this.chokeAmount + Sword.chokeChange > 0){
this.player.sendMessage(ChatColor.RED + "You have lost the upper hand!");
this.chokePartner.player.sendMessage(ChatColor.RED + "You have gained the upper hand!");
}
if (this.chokeAmount >= 1){
return true;
}
} else {
this.chokeAmount -= Sword.chokeChange;
this.chokePartner.chokeAmount = this.chokeAmount;
if (this.chokeAmount <= -0.8 && this.chokeAmount + Sword.chokeChange > 0.8){
this.chokePartner.player.sendMessage(ChatColor.RED + "Your enemy is slipping from your grasp!");
this.player.sendMessage(ChatColor.RED + "You are slipping from the enemy's grasp!");
}
if (this.chokeAmount >= 0.8 && this.chokeAmount - Sword.chokeChange < 0.8){
this.chokePartner.player.sendMessage(ChatColor.RED + "You feel the enemy begin to lose consciousness.");
this.player.sendMessage(ChatColor.RED + "You begin to feel dizzy and light headed, you are running out of air!");
}
if (this.chokeAmount > 0 && this.chokeAmount - Sword.chokeChange < 0){
this.chokePartner.player.sendMessage(ChatColor.AQUA + "You have gained the upper hand!");
this.player.sendMessage(ChatColor.RED + "You have lost the upper hand!");
}
if (this.chokeAmount < 0 && this.chokeAmount + Sword.chokeChange > 0){
this.chokePartner.player.sendMessage(ChatColor.RED + "You have lost the upper hand!");
this.player.sendMessage(ChatColor.RED + "You have gained the upper hand!");
}
if (this.chokeAmount <= -1){
return true;
}
}
return false;
}
//Method to add a dot
public boolean addDot(Dot dot, CombatPlayer attacker){
if (attacker.energy >= attacker.dotAddChange){
attacker.energy -= attacker.dotAddChange;
this.Dots.add(dot);
return true;
} else {
return false;
}
}
public void addDot(Dot dot){
this.Dots.add(dot);
}
//Method to move for Shadow Step
public void moveForShadowstep(Entity onEntity){
Location selectedVector = onEntity.getLocation();
double angleInRadians = (selectedVector.getYaw() + 90) / 180 * Math.PI;
double xMult = Math.cos(angleInRadians);
double zMult = Math.sin(angleInRadians);
Location newPlayerPos = new Location(this.player.getWorld(), selectedVector.getX() + this.dist * xMult, selectedVector.getY(), selectedVector.getZ() + this.dist * zMult, selectedVector.getYaw(), this.player.getLocation().getPitch());
this.player.teleport(newPlayerPos);
}
//Reports values
public void printValues(){
this.player.sendMessage("You have " + this.attackCharge + " attack power, " + this.defendCharge + " block power, and " + String.valueOf(this.energy) + " energy.");
}
//Utility tests
public boolean isBehind(Entity infront){
double behindAngle = (this.player.getLocation().getYaw() + 360) % 360 + 360;
double infrontAngle = (infront.getLocation().getYaw() + 360) % 360 + 360;
if (behindAngle - this.angleRange < infrontAngle && infrontAngle < behindAngle + this.angleRange){
return true;
}
return false;
}
public boolean isWithinRange(Entity entity2, double distance){
return this.player.getLocation().distance(entity2.getLocation()) <= distance;
}
public boolean isInAir(){
return !((Entity)this.player).isOnGround();
}
public boolean inDisabledState(){
return this.isChockingOther || this.stuned || this.isInChokeHold;
}
//Handlers of various events
public void chokingHandleBoolean(boolean doneChoke, CombatPlayer player){
if (doneChoke){
if (player.isInChokeHold){
player.isInChokeHold = false;
player.chokePartner.isChockingOther = false;
player.player.sendMessage(ChatColor.AQUA + "You have escaped from the choke hold!");
player.cancelStun();
player.chokePartner.player.sendMessage(ChatColor.RED + "Your victim has escaped and you have been stuned!");
Sword.stun(3, player, player.chokePartner);
} else if (player.isChockingOther){
player.isChockingOther = false;
player.chokePartner.isInChokeHold = false;
Dot killDot = new Dot(0);
killDot.dotTime = 5;
killDot.dps = 7;
player.chokePartner.player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 9000, 0));
player.chokePartner.player.sendMessage(ChatColor.RED + "The world darkens around you...");
player.player.sendMessage(ChatColor.AQUA + "You successfully dispatched your enemy!");
player.chokePartner.cancelStun();
player.chokePartner.player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 90000, 0));
player.chokePartner.addDot(killDot);
}
}
}
public void handleAnyClick(PlayerInteractEvent event){
if ((event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK) && (this.isChockingOther || this.isInChokeHold)){
boolean doneChoke = this.changeChoke();
event.setCancelled(true);
this.chokingHandleBoolean(doneChoke, this);
} else if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK){
/*int power = Wand.isWand(event.getPlayer().getItemInHand());
if (this.selectedPotion != null && power > 0){
if (this.selectedPotion.getType() == Material.POTION){
Wand.castPotion(this,power);
} else if (SpellItem.isSpellItem(this.selectedPotion)){
Wand.castSpell(this, power);
}
}*/
}
if (this.stuned){
event.setCancelled(true);
}
}
public void removeThis(){
CombatPlayer.combatplayers.remove(this.player.getName());
}
//resets values when the player dies
public void resetForDeath(){
this.Dots.clear();
if (this.isChockingOther || this.isInChokeHold){
this.isChockingOther = false;
this.isInChokeHold = false;
this.chokePartner.isChockingOther = false;
this.chokePartner.isInChokeHold = false;
this.player.removePotionEffect(PotionEffectType.CONFUSION);
this.player.removePotionEffect(PotionEffectType.BLINDNESS);
this.swordEnraged = false;
this.swordRage = 0;
this.axeEnraged = false;
this.axeRage = 0;
this.cancelStun();
}
}
} | [
"[email protected]"
] | |
df2a0cee68d97ee081ccae55b3ec03042facda80 | 922740af238f81eceb55a39aa4341c03eb6a5c0d | /app/src/main/java/com/example/amankumar/layouttest/Adapter/ChatListAdapter.java | 67dda9dc6a0ffa5357ab75a810afba1d6aa21890 | [] | no_license | zDimacedRuler/Huest-Android- | 0d7b28698f5aceb127ba47d36c34d4ea0ee47ced | f2d24f57e44e417b1215f63b034e3bd987ad6ece | refs/heads/master | 2020-12-25T14:34:11.232198 | 2016-06-25T08:51:12 | 2016-06-25T08:51:12 | 61,934,982 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 976 | java | package com.example.amankumar.layouttest.Adapter;
import android.app.Activity;
import android.view.View;
import android.widget.TextView;
import com.example.amankumar.layouttest.Model.ChatListModel;
import com.example.amankumar.layouttest.R;
import com.firebase.client.Firebase;
import com.firebase.ui.FirebaseListAdapter;
/**
* Created by AmanKumar on 4/18/2016.
*/
public class ChatListAdapter extends FirebaseListAdapter<ChatListModel> {
public ChatListAdapter(Activity activity, Class<ChatListModel> modelClass, int modelLayout, Firebase ref) {
super(activity, modelClass, modelLayout, ref);
}
@Override
protected void populateView(View v, ChatListModel model, int position) {
TextView nameText = (TextView) v.findViewById(R.id.text_view_nameLV);
TextView locationText = (TextView) v.findViewById(R.id.text_view_providesLV);
nameText.setText(model.getUsername());
locationText.setText(model.getCity());
}
}
| [
"[email protected]"
] | |
949af78b6cb2a4eee49abdd05fdab15cf65d5660 | 39e2ebf7b71baadbb6ff5aa4bc5d7396848ee8a2 | /Ch2/src/Fibonacci.java | 0252656036a6862c683b0b587d0a852b8acf3e89 | [] | no_license | scarletqueen/AP_CS | cfd284008b465b51dfc25b6db90edb720fdd0b90 | cabb0cceb859f75c49295ddafc276f36ff13e76f | refs/heads/master | 2023-05-11T10:26:20.943011 | 2021-05-29T19:09:47 | 2021-05-29T19:09:47 | 328,299,848 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 514 | java | import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
long n1 = 1;
long n2;
int numTerm;
System.out.println("Enter number of terms:");
numTerm = s.nextInt();
for (int i = 0; i <= numTerm-1; i++ ) {
if (n1>1) {
System.out.println(i);
}
n1 = i + n1;
n2 = n1;
System.out.println(n2);
}
}
}
| [
"[email protected]"
] | |
ae72f33097b8dda4c4fe9a5e2f5de5c2fa3dae4f | 478213a8cd55ea5c10327e35e5962f416a7a8816 | /src/pl/s21790/tetris/Shape.java | 0dd910eac160fd76fcd62ce4ab9576ded44364f2 | [] | no_license | s21790-pj/projekt-programistyczny-s21790-pj | 9ddbf3e0110e1cdf41b510e878f304caf217ae30 | bf514f70456f28bdbae0fc78865bd9c9b9b0c7d2 | refs/heads/master | 2022-10-15T23:33:52.234605 | 2020-06-11T16:40:18 | 2020-06-11T16:40:18 | 271,335,986 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,284 | java | package pl.s21790.tetris;
import java.util.Random;
public class Shape {
enum Blocks {
emptyBlock(new int[][] {{0, 0}, {0, 0}, {0, 0}, {0, 0}}),
Iblock(new int[][] {{0, -1}, {0, 0}, {0, 1}, {0, 2}}),
Tblock(new int[][] {{-1, 0}, {0, 0}, {1, 0}, {0, 1}}),
Oblock(new int[][] {{0, 0}, {1, 0}, {0, 1}, {1, 1}}),
Lblock(new int[][] {{-1, -1}, {0, -1}, {0, 0}, {0, 1}}),
Jblock(new int[][] {{1, -1}, {0, -1}, {0, 0}, {0, 1}}),
Sblock(new int[][] {{0, -1}, {0, 0}, {1, 0}, {1, 1}}),
Zblock(new int[][] {{0, -1}, {0, 0}, {-1, 0}, {-1, 1}}),
;
public int[][] coordinates;
Blocks(int[][] coordinates) {
this.coordinates = coordinates;
}
}
private Blocks blockShape;
private int[][] coordinates;
public Shape() {
coordinates = new int[4][2];
setShape(Blocks.emptyBlock);
}
public void setShape(Blocks shape) {
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 2; ++j) {
coordinates[i][j] = shape.coordinates[i][j];
}
}
blockShape = shape;
}
private void setX(int pointer, int x) {
coordinates[pointer][0] = x;
}
private void setY(int pointer, int y) {
coordinates[pointer][1] = y;
}
public int x(int pointer) {
return coordinates[pointer][0];
}
public int y(int pointer) {
return coordinates[pointer][1];
}
public Blocks getShape() {
return blockShape;
}
public void randomShapeGenerator() {
Random random = new Random();
int x = Math.abs(random.nextInt()) % 7 + 1;
Blocks[] values = Blocks.values();
setShape(values[x]);
}
public int minY() {
int min = coordinates[0][1];
for (int i = 0; i < 4; i++) {
min = Math.min(min, coordinates[i][1]);
}
return min;
}
public Shape rotateLeft() {
if(blockShape == Blocks.Oblock){
return this;
}
Shape result = new Shape();
result.blockShape = blockShape;
for(int i = 0; i < 4; i++) {
result.setX(i, y(i));
result.setY(i, -x(i));
}
return result;
}
}
| [
"[email protected]"
] | |
1f07b30f27da73c5d1e7715ec4317c1270e6ce7b | bb885460e65c76df1ebb92259ceb02695c3f014a | /phoneweb/src/main/java/com/dht/pojo/PaymentDetail.java | 00552569359c405141491d19591e777910126aa1 | [] | no_license | duonghuuthanh/jsfsaleapp | 1799b45b045c43f5436f88b15fa6c59e0f504571 | 05887a923eb25d96449f08c820540789de801a32 | refs/heads/main | 2023-06-05T02:54:06.090314 | 2021-06-26T01:49:02 | 2021-06-26T01:49:02 | 318,164,210 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,105 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.dht.pojo;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
*
* @author duonghuuthanh
*/
@Entity
@Table(name = "payment_detail")
public class PaymentDetail implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne
@JoinColumn(name = "payment_id")
private Payment payment;
@ManyToOne
@JoinColumn(name = "product_id")
private Product product;
private BigDecimal price;
private int count;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the payment
*/
public Payment getPayment() {
return payment;
}
/**
* @param payment the payment to set
*/
public void setPayment(Payment payment) {
this.payment = payment;
}
/**
* @return the product
*/
public Product getProduct() {
return product;
}
/**
* @param product the product to set
*/
public void setProduct(Product product) {
this.product = product;
}
/**
* @return the price
*/
public BigDecimal getPrice() {
return price;
}
/**
* @param price the price to set
*/
public void setPrice(BigDecimal price) {
this.price = price;
}
/**
* @return the count
*/
public int getCount() {
return count;
}
/**
* @param count the count to set
*/
public void setCount(int count) {
this.count = count;
}
}
| [
"[email protected]"
] | |
51c106bb318ae759519e1848d0dc1c9ffe72a880 | 215b247ecc5ea8ed078b5782f784ac64ba6a6a81 | /src/daoTask/TaskDAOInterface.java | 7e07be5ff7a073d240fea595d90b508fad78ae0f | [] | no_license | tusharchopratech/task_manager_csc | 129e6468acecba17ccb385daf97402f06955b719 | cb4468f49bd70f74c4bf979d8f0a04ab74ba2097 | refs/heads/main | 2023-05-11T21:59:12.012269 | 2021-06-06T15:41:02 | 2021-06-06T15:41:02 | 374,397,148 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 529 | java | package daoTask;
import java.util.ArrayList;
import model.BeanTask;
public interface TaskDAOInterface {
public BeanTask insert(BeanTask beanTask);
public BeanTask update(BeanTask beanTask);
public boolean delete(String userId);
public BeanTask searchById(String userId);
public ArrayList<BeanTask> searchTasksByProjectId(String projectId);
public ArrayList<BeanTask> searchTasksByBuildId(String buildId);
public ArrayList<BeanTask> showAll();
public ArrayList<BeanTask> searchSubTasksBtTaskId(String taskId);
}
| [
"[email protected]"
] | |
32b00bd3d5add21f85605d660b15ad0fcb64b128 | fdc806ae8bf11085044778023d29eeeca212301c | /30DaysOfCode/D_03-ConditionalStatements/Solution.java | 28b8cbae3d20d435ec794e4fd0c09d84c5792eb6 | [] | no_license | gergely-kiss/HackerRank | ec8fffa9174827ef56065c7766b33fe5eaa1cca5 | 159776d118b534c924954336cd911735abde0c09 | refs/heads/master | 2020-04-18T02:31:47.459988 | 2019-02-04T17:37:12 | 2019-02-04T17:37:12 | 167,166,155 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 806 | java | import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if(N % 2 != 0){
System.out.println("Weird");
}else{
if(N >=2 && N <=5){
System.out.println("Not Weird");}
else if(N >=6 && N <= 20){
System.out.println("Weird");}
else if (N> 20){
System.out.println("Not Weird");
}
}
scanner.close();
}
}
| [
"[email protected]"
] | |
142ea068985f27fff4603f8074dfa6dac2ea88a0 | 948fea78bd2c518ea0c356e33070d74fa1244c1e | /xc-service-manage-course/src/main/java/com/xuecheng/manage_course/controller/CategoryController.java | ae7c5e34b73b09246f10301b9ab58b9d8a97dc66 | [] | no_license | a1844993587/ckzx | 627824d7bffd501c0ba3030bd4337ee7934b3f8b | a5e66a19b8035d89bed1a6563df0c6e2e5b7e8a8 | refs/heads/master | 2022-12-08T07:23:58.062107 | 2019-10-25T10:59:52 | 2019-10-25T10:59:52 | 217,510,950 | 0 | 0 | null | 2022-11-24T06:27:07 | 2019-10-25T10:34:15 | Java | UTF-8 | Java | false | false | 827 | java | package com.xuecheng.manage_course.controller;
import com.xuecheng.api.course.CategoryControllerApi;
import com.xuecheng.framework.domain.course.ext.CategoryNode;
import com.xuecheng.manage_course.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Alex Yu
* @date 2019/9/18 14:04
*/
@RestController
@RequestMapping("/category")
public class CategoryController implements CategoryControllerApi {
@Autowired
private CategoryService categoryService;
@Override
@GetMapping("/list")
public CategoryNode findList() {
return categoryService.selectList();
}
}
| [
"[email protected]"
] | |
4660480f8222e33a25f0f8241f49d68ff62746d7 | f207ed65c1b0ae387894bbce4bc8e7b6225c061a | /app/src/main/java/chickenzero/ht/com/lienquan/models/Skill.java | 677037e4bddb4f854b5072c6b95dc971da095dc4 | [] | no_license | RohidanTiger/LienQuan | e4ee9d107f7a8b0ff6d3acf317280773bc4cd095 | 4d2a3ef16ceca946a7c0e857dfe8712d4d434b73 | refs/heads/master | 2021-01-19T14:28:52.771431 | 2019-10-17T15:36:28 | 2019-10-17T15:36:28 | 88,163,515 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,143 | java | package chickenzero.ht.com.lienquan.models;
/**
* Created by QuyDV on 4/12/17.
*/
public class Skill {
private String id;
private String name;
private String desc;
private String mana;
private String youtube;
public Skill() {
}
public Skill(String id, String name, String desc, String mana, String youtube) {
this.id = id;
this.name = name;
this.desc = desc;
this.mana = mana;
this.youtube = youtube;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getMana() {
return mana;
}
public void setMana(String mana) {
this.mana = mana;
}
public String getYoutube() {
return youtube;
}
public void setYoutube(String youtube) {
this.youtube = youtube;
}
}
| [
"[email protected]"
] | |
81c612dffc34093b9ccb595ed8ffd8729e0dcfe4 | 07ef8242c5d165a92052d1f9e06267b372129554 | /AtCoderBeginnerContest/src/abc137/b/Main.java | a772ee75f109305b02bc6bc259d2ca79a9359ee9 | [] | no_license | hysmo1988/atcoder | 357adc177c78fa5d228314fe38d5b1d45bd4eb3f | 2a75ece9bbb920e9ca58961ea2b2548d81d24c7c | refs/heads/master | 2023-01-05T10:02:59.713962 | 2020-11-01T13:43:43 | 2020-11-01T13:43:43 | 222,070,871 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 407 | java | package abc137.b;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int K = sc.nextInt();
int X = sc.nextInt();
sc.close();
int[] r = new int[(K * 2) - 1];
int x = X - K + 1;
for(int i = 0; i < r.length; i++) {
r[i] = x;
x++;
}
for(int i = 0; i < r.length; i++) {
System.out.print(r[i] + " ");
}
}
}
| [
"[email protected]"
] | |
c8255f43b384be2f39c662c8884963b65e7c1b8a | e9013107bd9ccf258828e339202a3b23d1005262 | /meservice/src/main/java/com/teammental/meservice/BaseCrudServiceImpl.java | ae000007436ddebd60cb125f1a66c77c272846b7 | [
"Apache-2.0"
] | permissive | mental-party/meparty | 1fa30efd1ba690b64d5e3c80bed1b88b7c9cd53d | 705d16aa15c4a9c9d7cd6c779438a9df090b0144 | refs/heads/master | 2021-09-28T20:44:24.448326 | 2018-11-20T12:07:57 | 2018-11-20T12:07:57 | 113,290,126 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,155 | java | package com.teammental.meservice;
import com.teammental.mecore.stereotype.entity.Entity;
import com.teammental.medto.FilterDto;
import com.teammental.medto.IdDto;
import com.teammental.meexception.dto.DtoCreateException;
import com.teammental.meexception.dto.DtoCrudException;
import com.teammental.meexception.dto.DtoDeleteException;
import com.teammental.meexception.dto.DtoNotFoundException;
import com.teammental.meexception.dto.DtoUpdateException;
import com.teammental.memapper.types.Mapper;
import com.teammental.merepository.BaseJpaRepository;
import java.io.Serializable;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public abstract class BaseCrudServiceImpl<DtoT extends IdDto<IdT>, IdT extends Serializable>
implements BaseCrudService<DtoT, IdT> {
private static final Logger LOGGER = LoggerFactory.getLogger(BaseCrudServiceImpl.class);
@Autowired
private Mapper mapper;
// region override methods
@Override
public final Page<DtoT> findAll() throws DtoCrudException {
return findAll(null);
}
@Override
public final Page<DtoT> findAll(FilterDto filterDto) throws DtoCrudException {
LOGGER.debug("findAll of " + getDtoClass().getSimpleName() + " started");
try {
Page<DtoT> dtos = doFindAll(filterDto);
LOGGER.debug("findAll of " + getDtoClass().getSimpleName() + " ended");
return dtos;
} catch (DtoCrudException ex) {
LOGGER.error("findAll of " + getDtoClass().getSimpleName()
+ " throwed a DtoCrudException");
throw ex;
}
}
@Override
public final DtoT findById(final IdT id) throws DtoCrudException {
LOGGER.debug("findById of " + getDtoClass().getSimpleName()
+ " started, with parameter: id=" + id);
try {
DtoT dto = doFindById(id);
LOGGER.debug("findById of " + getDtoClass().getSimpleName()
+ " ended, with parameter: id=" + id);
return dto;
} catch (DtoCrudException ex) {
LOGGER.error("findById of " + getDtoClass().getSimpleName()
+ " throwed a DtoCrudException");
throw ex;
}
}
@Override
public final IdT save(final DtoT dto) throws DtoCrudException {
if (dto == null) {
return null;
}
if (dto.getId() == null) {
LOGGER.debug("create of " + getDtoClass().getSimpleName()
+ " started, with parameter: dto=" + dto.toString());
try {
IdT id = doCreate(dto);
LOGGER.debug("create of " + getDtoClass().getSimpleName() + " ended");
return id;
} catch (DtoCrudException ex) {
LOGGER.error("insert of " + getDtoClass().getSimpleName()
+ " throwed a DtoCrudException");
throw ex;
}
} else {
LOGGER.debug("update of " + getDtoClass().getSimpleName()
+ " started, with parameter: dto=" + dto.toString());
try {
IdT idResult = doUpdate(dto);
LOGGER.debug("update of " + getDtoClass().getSimpleName() + " ended");
return idResult;
} catch (DtoCrudException ex) {
LOGGER.error("update of " + getDtoClass().getSimpleName()
+ " throwed an DtoCrudException");
throw ex;
}
}
}
@Override
public final boolean delete(final IdT id) throws DtoCrudException {
LOGGER.debug("delete of " + getDtoClass().getSimpleName()
+ " started, with parameter: id=" + id.toString());
try {
boolean result = doDelete(id);
LOGGER.debug("delete of " + getDtoClass().getSimpleName() + " ended");
return result;
} catch (DtoCrudException ex) {
LOGGER.error("delete of " + getDtoClass().getSimpleName()
+ " throwed a DtoCrudException");
throw ex;
}
}
// endregion override methods
// region protected default methods
protected Page<DtoT> doFindAll(FilterDto filterDto) throws DtoCrudException {
Page entities;
if (filterDto == null) {
entities = new PageImpl<>(getRepository().findAll());
} else {
entities = getRepository().findAll(filterDto.getPage().toPageRequest());
}
if (!entities.hasContent()) {
throw new DtoNotFoundException();
}
return (Page<DtoT>) entities.map(p -> mapper.map(p, getDtoClass()));
}
protected DtoT doFindById(final IdT id) throws DtoCrudException {
Optional optionalEntity = getRepository().findById(id);
if (!optionalEntity.isPresent()) {
throw new DtoNotFoundException();
}
return mapper.map(optionalEntity.get(), getDtoClass());
}
protected IdT doCreate(final DtoT dto) throws DtoCrudException {
try {
Object entity = mapper.map(dto, getEntityClass());
entity = getRepository().save(entity);
DtoT dtoResult = mapper.map(entity, getDtoClass());
return dtoResult.getId();
} catch (Exception ex) {
throw new DtoCreateException(dto, ex);
}
}
protected IdT doUpdate(final DtoT dto) throws DtoCrudException {
Optional optionalEntity = getRepository().findById(dto.getId());
if (!optionalEntity.isPresent()) {
throw new DtoNotFoundException();
}
Object entity = mapper.map(dto, optionalEntity.get());
try {
Object resultEntity = getRepository().save(entity);
DtoT dtoResult = mapper.map(resultEntity, getDtoClass());
return dtoResult.getId();
} catch (Exception ex) {
throw new DtoUpdateException(dto, ex);
}
}
protected boolean doDelete(final IdT id) throws DtoCrudException {
try {
getRepository().deleteById(id);
return true;
} catch (Exception ex) {
throw new DtoDeleteException(ex);
}
}
// endregion protected default methods
// region abstract methods
protected abstract BaseJpaRepository getRepository();
protected abstract Class<? extends DtoT> getDtoClass();
protected abstract Class<? extends Entity> getEntityClass();
// endregion abstract methods
}
| [
"[email protected]"
] | |
6c50a4984027c30d7dd6b8376f8bbf3d3dd4f2cd | 7d28d457ababf1b982f32a66a8896b764efba1e8 | /platform-dao/src/test/java/ua/com/fielden/platform/dao/EntityWithHyperlinkDao.java | f953b2b414ff0292c232dfc132ce31ec28acedc7 | [
"MIT"
] | permissive | fieldenms/tg | f742f332343f29387e0cb7a667f6cf163d06d101 | f145a85a05582b7f26cc52d531de9835f12a5e2d | refs/heads/develop | 2023-08-31T16:10:16.475974 | 2023-08-30T08:23:18 | 2023-08-30T08:23:18 | 20,488,386 | 17 | 9 | MIT | 2023-09-14T17:07:35 | 2014-06-04T15:09:44 | JavaScript | UTF-8 | Java | false | false | 586 | java | package ua.com.fielden.platform.dao;
import com.google.inject.Inject;
import ua.com.fielden.platform.entity.annotation.EntityType;
import ua.com.fielden.platform.entity.query.IFilter;
import ua.com.fielden.platform.serialisation.jackson.entities.EntityWithHyperlink;
/**
* A DAO for {@link EntityWithHyperlink} used for testing.
*
* @author 01es
*
*/
@EntityType(EntityWithHyperlink.class)
public class EntityWithHyperlinkDao extends CommonEntityDao<EntityWithHyperlink> {
@Inject
protected EntityWithHyperlinkDao(final IFilter filter) {
super(filter);
}
}
| [
"[email protected]"
] | |
efe2bc82992c1522869166aab85215922b36d413 | 32b837b86d1f402a6a9565b29e8fdb1e805bdbab | /src/main/java/com/example/demo/service/FileUploadServiceImpl.java | cd505ec64645c47a3e2a9f171ccd89a787725f22 | [] | no_license | EricChai1003/FINRA-FileUpload | 566ea0776f91012fbc57161b8019f4e18255b09b | dc94e94eda4e6a3cbd2274b088f660036a36c45d | refs/heads/master | 2021-08-19T22:11:53.515365 | 2017-11-27T14:57:39 | 2017-11-27T14:57:39 | 112,206,617 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,139 | java | package com.example.demo.service;
import com.example.demo.dao.FileUploadDAO;
import com.example.demo.entity.FileData;
import com.example.demo.utility.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class FileUploadServiceImpl implements FileUploadService {
private final Path baseLoc = Paths.get(FileUploadUtil.FILE_LOCATION);
@Autowired
private FileUploadDAO fileUploadDAO;
@Override
public FileData save(MultipartFile uploadFile) {
FileData file = FileUploadUtil.convertToFileData(uploadFile);
FileData result = fileUploadDAO.save(file);
try {
FileUploadUtil.saveUploadedFile(uploadFile, file);
} catch (IOException e) {
throw new RuntimeException("Fail to save file", e);
}
return result;
}
@Override
public FileData getFile(String fileName) {
return fileUploadDAO.findByFileName(fileName);
}
@Override
public List<String> loadAll() {
try {
List<String> paths = Files.walk(this.baseLoc, 1)
.filter(path -> !path.equals(this.baseLoc))
.map(path -> this.baseLoc.relativize(path))
.map(path -> path.getFileName().toString())
.collect(Collectors.toList());
return paths;
} catch(IOException e) {
throw new RuntimeException("Fail to read stored file", e);
}
}
@Override
public void deleteAll() {
FileSystemUtils.deleteRecursively(baseLoc.toFile());
}
@Override
public void init() {
try {
Files.createDirectories(baseLoc);
} catch(IOException e) {
throw new RuntimeException("Fail to initialize storage", e);
}
}
}
| [
"[email protected]"
] | |
867f57068b67801c1f12c16259f8e1b121e6cabf | 69b917e0d0b83ac7cf03a77a94fbf850d0c11d0e | /mobile/EvShare/app/src/main/java/com/example/ioc/evshare/network/actionsBus/actions/events/GetPhotoAction.java | 85721472f9cbfaf4210e7891359090afe5d4891f | [] | no_license | teodorst/ioc | de2c09036dd25dc649671435c3632357d034e9bf | cc73b42a380465490f9ab10bf93fb7aa07ea534c | refs/heads/master | 2021-05-01T21:33:42.709895 | 2017-01-17T16:41:40 | 2017-01-17T16:41:40 | 72,932,599 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,274 | java | package com.example.ioc.evshare.network.actionsBus.actions.events;
import com.example.ioc.evshare.network.actionsBus.actions.BaseNetworkEvent;
import com.example.ioc.evshare.network.actionsBus.actions.events.message.GetPhotoActionMessage;
import com.example.ioc.evshare.network.actionsBus.actions.events.message.GetThumbnailActionMessage;
import com.example.ioc.evshare.network.actionsBus.actions.events.message.ReceiveImageActionMessage;
public class GetPhotoAction extends BaseNetworkEvent {
public static final GetThumbnailAction.OnLoadingError FAILED_DOWNLAOD_PHOTO_ACTION = new GetThumbnailAction.OnLoadingError(UNHANDLED_MSG, UNHANDLED_CODE);
public static class OnLoadingStart extends BaseNetworkEvent.OnStart<GetPhotoActionMessage> {
public OnLoadingStart(GetPhotoActionMessage message) {
super(message);
}
}
public static class OnLoadedSuccess extends BaseNetworkEvent.OnDone<ReceiveImageActionMessage> {
public OnLoadedSuccess(ReceiveImageActionMessage response) {
super(response);
}
}
public static class OnLoadingError extends BaseNetworkEvent.OnFailed {
public OnLoadingError(String errorMessage, int code) {
super(errorMessage, code);
}
}
}
| [
"[email protected]"
] | |
4290dea65642e61666a23593be2c9409ef6ac77e | 075b1b94e188b954276c8271fd04b9504aab1e6c | /src/main/java/top/tomxwd/nio/easytest/NIOServer.java | 31f9b046a98f4c5e9f1efc915d9bf029100125df | [] | no_license | tomxwd/netty-test | bd291a24901f59b149f392b6d6f8e5dcc7078d89 | 989881b4b2b6a2bdbf9c32c81485bad082df4caf | refs/heads/master | 2022-10-23T12:31:54.025190 | 2020-04-21T13:25:26 | 2020-04-21T13:25:26 | 225,026,791 | 1 | 1 | null | 2022-10-04T23:55:54 | 2019-11-30T14:48:35 | Java | UTF-8 | Java | false | false | 3,349 | java | package top.tomxwd.nio.easytest;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
/**
* @author xieweidu
* @createDate 2019-11-30 22:22
*/
public class NIOServer {
public static void main(String[] args) throws IOException {
// 创建ServerSocketChannel -> ServerSocket
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
// 得到一个Selector对象
Selector selector = Selector.open();
// 绑定端口6666,在服务器端监听
serverSocketChannel.socket().bind(new InetSocketAddress(6666));
// 设置为非阻塞
serverSocketChannel.configureBlocking(false);
// 把ServerSocketChannel注册到Selector,关心的事件是OP_ACCEPT
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
// 循环等待客户端连接
while (true) {
// 这里等待一秒,如果没有事件发生就返回
if (selector.select(1000) == 0) {
// 没有事件发生
System.out.println("服务器等待了一秒,无连接");
continue;
}
// 如果返回>0,就获取到相关的SelectionKey集合
// 1. 如果返回的>0,表示已经获取到关注的事件
// 2. 通过selectedKeys() 返回关注事件的集合
// 通过selectionKeys反向获取通道
Set<SelectionKey> selectionKeys = selector.selectedKeys();
// 遍历Set<SelectionKey>集合,使用迭代器遍历
Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
while (keyIterator.hasNext()) {
// 获取到SelectionKey
SelectionKey key = keyIterator.next();
// 根据key对应的通道发生的事件做相应的处理
if (key.isAcceptable()) {
// 如果是OP_ACCEPT事件,有新的客户端连接
// 给该客户端生成SocketChannel
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
System.out.println("客户端连接成功,生成了一个SocketChannel" + socketChannel.hashCode());
// 将当前的socketChannel注册到Selector上,关注事件为OP_READ,同时给SocketChannel关联一个Buffer
socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
}
if (key.isReadable()) {
// 如果是OP_READ事件
// 通过key反向获取到对应的channel
SocketChannel channel = (SocketChannel) key.channel();
// 获取到该channel关联的Buffer
ByteBuffer buffer = (ByteBuffer) key.attachment();
channel.read(buffer);
System.out.println("from 客户端 : " + new String(buffer.array()));
buffer.clear();
}
// 手动从集合中删除当前的selectKey,防止重复操作
keyIterator.remove();
}
}
}
}
| [
"[email protected]"
] | |
b299bbdb2218c9b299a5fea3ecc04c416537d118 | 52fa23fc740c23667bce5cf83ec40d6f6ae1b3bf | /core/src/main/java/eu/excitementproject/eop/core/utilities/dictionary/wordnet/jmwn/JmwnDictionaryManager.java | f37e3cb9959af4bbf642ef12b697fd8200ef6301 | [] | no_license | omerlevy/Excitement-Open-Platform | 0f7ebf7a625895266bbd67f3d4e3956c38f4b529 | b3548e5c44dccb88015fdd82085221044e91a944 | refs/heads/master | 2020-04-03T06:52:35.059339 | 2013-07-31T15:36:15 | 2013-07-31T15:36:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,814 | java | package eu.excitementproject.eop.core.utilities.dictionary.wordnet.jmwn;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import eu.excitementproject.eop.core.utilities.dictionary.wordnet.WordNetInitializationException;
public class JmwnDictionaryManager {
String configFileName = "multiwordnet.properties";
File configFile;
// File configFile = new File("/hardmnt/destromath0/home/nastase/Project/EXC/WN/JMWN-1.2/conf/multiwordnet.properties");
public JmwnDictionaryManager() {
findConfigFile(new File("./"));
}
// issues with passing this parameter from the WordnetLexicalResourcesFactory.java
public JmwnDictionaryManager(String configFile){
if (configFile.matches(".*properties")) {
this.configFile = new File(configFile);
} else {
findConfigFile(new File(configFile));
}
}
public JmwnDictionaryManager(File configFile) {
if (configFile.getName().matches(".*properties")) {
this.configFile = configFile;
} else {
findConfigFile(configFile);
}
}
public JmwnDictionary newDictionary() throws WordNetInitializationException {
System.out.println("\nInitializing MultiWordNet from file " + configFile.getName());
return new JmwnDictionary(this.configFile);
}
private void findConfigFile(File file) {
File thisDir = file;
if (! file.isDirectory()) {
thisDir = new File("./");
}
File[] files = new File[1];
/* File[] files = thisDir.listFiles( new FilenameFilter(){
public boolean accept(File dir, String name) {
return name.endsWith("multiwordnet.properties");
}
});
if (files.length > 0 ) {
System.out.println("Configuration file found: " + files[0]);
this.configFile = files[0];
} else {
System.err.println("JmwnDictionaryManager.java: Could not find configuration file multiwordnet.properties");
System.exit(1);
}
*/
try {
files = FindFile.FindFileRecursively(thisDir, configFileName).toArray(files);
if (files.length < 1) {
System.err.println("Configuration file not found");
System.exit(1);
}
this.configFile = files[0];
} catch (FileNotFoundException e) {
System.err.println("Configuration file not found");
System.exit(1);
}
}
private static class FindFile{
static public List<File> FindFileRecursively(File directory, String matchingPattern) throws FileNotFoundException {
List<File> matchingFiles = new ArrayList<File>();
if (directory != null && directory.isDirectory()) {
for (File file : directory.listFiles()) {
if (file.isFile() && file.getName().matches(matchingPattern)) {
matchingFiles.add(file);
} else {
matchingFiles.addAll(FindFile.FindFileRecursively(file, matchingPattern));
}
}
}
return matchingFiles;
}
}
}
| [
"[email protected]"
] | |
cda26b4fba2d752d2ef46b5c88e5078a72725338 | 643b681d676b7916c1eab4cc7c0e76ca35718d0d | /app/src/main/java/nlaz/notificationdemo/MyAlarmService.java | f68ab140514621ac35738ef4eb5c99e90ab18a0d | [] | no_license | txcsmad/AndroidNotificationDemo | 506ad707964ed0f0e8da8966ad6063f0f84b2237 | 3a1daa68f9bc187757163b2f3ab851b196e16655 | refs/heads/master | 2020-12-25T03:49:32.849436 | 2015-03-28T18:48:05 | 2015-03-28T18:48:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,063 | java | package nlaz.notificationdemo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import org.parceler.Parcels;
/**
* Created by nlazaris on 3/25/15.
*/
public class MyAlarmService extends Service
{
private Task task;
private NotificationManager mManager;
@Override
public IBinder onBind(Intent arg0)
{
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
task = Parcels.unwrap(intent.getParcelableExtra("TASK"));
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
createNotification();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
}
public void createNotification() {
// Prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(this, NotificationReceiver.class);
intent.putExtra("TASK",Parcels.wrap(task));
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// Build notification
// Actions are just fake
Notification notification = new Notification.Builder(this)
.setContentTitle(task.getTitle())
.setContentText(task.getDescription())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
@Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
| [
"[email protected]"
] | |
aae507596e39bc595d7650a0c5171d5281c20ee9 | b725fd31bc92b3b771e1f79f8689896904df346d | /Labo/Clase 25/src/Azucarada.java | 0bb78c5e122089a6bcf59d2dbf5971a16f95e2e0 | [] | no_license | MaximoGismondi/TareasLabo | b699ecf16beb9517895cbc85491cf9e8116beec5 | c03ce38b48081cb6227e1655c08bb486326bda14 | refs/heads/master | 2023-02-22T17:43:18.698217 | 2020-09-15T16:17:37 | 2020-09-15T16:17:37 | 252,253,848 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 412 | java | package com.company.Bebidas;
public class Azucarada extends Bebida {
private double cantAzucar;
public Azucarada(String nombre, double cantAzucar) {
super(nombre, 1, cantAzucar*10);
this.cantAzucar = cantAzucar;
}
public double getCantAzucar() {
return cantAzucar;
}
public void setCantAzucar(double cantAzucar) {
this.cantAzucar = cantAzucar;
}
}
| [
"[email protected]"
] | |
67cd783cbae1d76cca17d8c3db8b13485146a332 | 00afc9391168dea279a6ed7934f4f0bbb19af386 | /src/test/java/concurrency/ch3/MutexTest.java | 1fbac0dea480bb31c141801c39a87081b890c93a | [
"MIT"
] | permissive | SudarsanSridharan16/java-concurrency | c7f0993c1dcf67aaa9a64ea524127b901be76cee | 9c23850054a2ef8a7e2f880fded2e9993c081446 | refs/heads/master | 2020-03-19T02:03:35.536313 | 2014-01-18T00:57:50 | 2014-01-18T00:57:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 964 | java | package concurrency.ch3;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import org.junit.Test;
/**
* Count to two with two threads.
*
* @author Jason Gowan
*
*/
public class MutexTest {
private final Semaphore mutex = new Semaphore(1);
private final Semaphore done = new Semaphore(0);
private int count = 0;
@Test
public void test() throws InterruptedException {
callCounter();
callCounter();
done.acquire(2); // wait for both counters to complete
System.out.println(count);
assertEquals(2, count);
}
private void callCounter() {
Executors.newSingleThreadExecutor()
.submit(new Counter());
}
private class Counter implements Runnable{
public void run() {
try {
mutex.acquire();
count = count + 1;
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
mutex.release();
done.release();
}
}
}
}
| [
"[email protected]"
] | |
abe3459486f9e5ad4d834723d64c803bba54a7ea | 35005e1f081d51f6bf9e4f16dba3635ae2f31329 | /app/src/main/java/com/example/downloaddemo/TimeActivity.java | d07458e0582e26802a55ca4381c53353275d2359 | [] | no_license | tataxqy/DownloadDemo | 4c4bb75f3ed11da486fb1b26e1b69cbcb971218e | b1195c7083624f96cf344ecbde35565118019290 | refs/heads/master | 2020-05-17T00:32:05.461700 | 2019-04-25T09:08:21 | 2019-04-25T09:08:21 | 183,398,027 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,812 | java | package com.example.downloaddemo;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.lang.ref.WeakReference;
public class TimeActivity extends AppCompatActivity {
public static final int INT = 1001;
private TextView timetextview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time);
timetextview=findViewById(R.id.tv_time);
TimeHandler handler=new TimeHandler(this);
Message message=Message.obtain();
message.what= INT;
message.arg1=10;
handler.sendMessageDelayed(message,1000);
}
public static class TimeHandler extends Handler{
final WeakReference<TimeActivity> timeActivityWeakReference;
//构造器
public TimeHandler(TimeActivity timeActivity) {
this.timeActivityWeakReference = new WeakReference<>(timeActivity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
TimeActivity activity=timeActivityWeakReference.get();//获取活动
switch (msg.what){
case INT:
int value=msg.arg1;
activity.timetextview.setText(String.valueOf(--value));
//重新构造一个mssage:
Message message=Message.obtain();
message.what=INT;
message.arg1=value;
if(value>0)
{
sendMessageDelayed(message,1000);
}
break;
}
}
}
}
| [
"[email protected]"
] | |
af58476afb1979f66327b09b495bfc2d8398bc14 | 5e064abd3580c21db35448133016075906face39 | /DesafioDeLógica.java | 1a38aeb75c85735149e7a864926047bef4a12672 | [] | no_license | JacksonBuzzano/DesafioDoRelogio | a5f99dae305232d4ab99193a500d023672f93473 | 2731d8e515d83d980be791ba22e44d2509a724a0 | refs/heads/master | 2022-11-28T19:39:37.487294 | 2020-08-08T17:27:09 | 2020-08-08T17:27:09 | 286,087,052 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,627 | java | package desafiodelógica;
import java.util.GregorianCalendar;
import javax.swing.JOptionPane;
public class DesafioDeLógica {
public static void main(String[] args) {
int hr;
int mn;
JOptionPane.showMessageDialog(null, "Digite uma hora entre 00:00 e 12:00");
//Pegar a hora que o usuário digitar
String hora = JOptionPane.showInputDialog("Favor digitar uma hora válida!");
hr = Integer.parseInt(hora);
//Pegar o minuto que o usuário digitar
String minuto = JOptionPane.showInputDialog("Favor digitar um minuto válido!");
mn = Integer.parseInt(minuto);
//Condição pra verificar se a hora esta entre o intervalo solicitado
if (hr < 0) {
JOptionPane.showMessageDialog(null, "Hora MENOR que 00!");
return;
} else if (hr > 12) {
JOptionPane.showMessageDialog(null, "Hora MAIOR que 12!");
return;
} else if (mn < 0) {
JOptionPane.showMessageDialog(null, "Minuto MENOR que 00!");
return;
} else if (mn > 60) {
JOptionPane.showMessageDialog(null, "Miuto MAIOR que 60!");
return;
}
PegarHora horaAtual = new PegarHora();
GregorianCalendar gc = new GregorianCalendar(2020, 7, 8, hr, mn);
long anguloReal = horaAtual.retornaAnguloRelogio(gc);
//Exibe o Resultado
JOptionPane.showMessageDialog(null, "O Ângulo entre a hora informada: " + hr + ":" + mn+"H"
+ " é de " + anguloReal + "º");
}
}
| [
"[email protected]"
] | |
8da4d5357d4e5542f164b6f18227b140d48e840b | 72e3650eaeb008bb3cc9ff3f7baf3c78ddddce12 | /app/src/main/java/com/androlord/farmerapp/LanguageHelper/MainActivityLauncher.java | 1192fbbd231a88c57a10653d10975b4289fd5d23 | [] | no_license | Abhinav-Mani/FarmerApp | fae59d086103e0af711f761c0c2130b19661f593 | 83c288ce27c162f2574a3cc99c9b7b2878bb331c | refs/heads/master | 2020-12-13T17:07:48.026300 | 2020-02-09T22:19:56 | 2020-02-09T22:19:56 | 234,479,886 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,704 | java | package com.androlord.farmerapp.LanguageHelper;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import com.androlord.farmerapp.MainActivity;
public class MainActivityLauncher extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updateLocaleIfNeeded();
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void updateLocaleIfNeeded() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
if (sharedPreferences.contains(SettingsFragment.LANGUAGE_SETTING)) {
String locale = sharedPreferences.getString(
SettingsFragment.LANGUAGE_SETTING, "");
Locale localeSetting = new Locale(locale);
if (!localeSetting.equals(Locale.getDefault())) {
Resources resources = getResources();
Configuration conf = resources.getConfiguration();
conf.locale = localeSetting;
resources.updateConfiguration(conf,
resources.getDisplayMetrics());
Intent refresh = new Intent(this, MainActivityLauncher.class);
startActivity(refresh);
finish();
}
}
}
} | [
"[email protected]"
] | |
0a5193fdde8c6cda02561c13c3a0cc177ffc1474 | f595b10317736e770965680deb11f7f7be92f427 | /src/partable/webdb/server/Util.java | fccd769f3c0b4519220a3db50842142a452fec30 | [] | no_license | jcnossen/partregistry-appengine | 017ec8ff06b4ad99072893e297164c5675b7b7fa | 5afb51ef07a0671dd2d797c7233c62dffff79a3f | refs/heads/master | 2020-12-24T14:18:49.064805 | 2014-05-06T00:15:53 | 2014-05-06T00:15:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,584 | java | package partable.webdb.server;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import java.util.logging.Logger;
public class Util
{
public static Logger log;
public static String streamToString(InputStream stream) throws IOException
{
InputStreamReader reader = new InputStreamReader(stream);
StringBuilder sb = new StringBuilder();
char[] buf = new char[100];
int len;
while ( (len = reader.read(buf)) != -1 ){
sb.append(buf, 0, len);
}
return sb.toString();
}
/**
* Parse a 'concatenated' date string, used in bank mutation exports:
* Example: parseConcatDateString("20090402") returns april 2nd, 2009
*/
public static Date parseConcatDateString(String dateStr)
{
String year = dateStr.substring(0, 4);
String month = dateStr.substring(4, 6);
String day = dateStr.substring(6, 8);
Calendar cal = Calendar.getInstance();
// Note that January has index 0
cal.set(Integer.parseInt(year), Integer.parseInt(month)-1, Integer.parseInt(day), 0, 0, 0);
return cal.getTime();
}
/**
* Produce a string in double quotes with backslash sequences in all the
* right places. A backslash will be inserted within </, allowing JSON
* text to be delivered in HTML. In JSON text, a string cannot contain a
* control character or an unescaped quote or backslash.
* @param string A String
* @return A String correctly formatted for insertion in a JSON text.
*/
public static String quoteJsonString(String string) {
if (string == null || string.length() == 0) {
return "\"\"";
}
char b;
char c = 0;
int i;
int len = string.length();
StringBuffer sb = new StringBuffer(len + 4);
String t;
sb.append('"');
for (i = 0; i < len; i += 1) {
b = c;
c = string.charAt(i);
switch (c) {
case '\\':
case '"':
sb.append('\\');
sb.append(c);
break;
case '/':
if (b == '<') {
sb.append('\\');
}
sb.append(c);
break;
case '\b':
sb.append("\\b");
break;
case '\t':
sb.append("\\t");
break;
case '\n':
sb.append("\\n");
break;
case '\f':
sb.append("\\f");
break;
case '\r':
sb.append("\\r");
break;
default:
if (c < ' ' || (c >= '\u0080' && c < '\u00a0') ||
(c >= '\u2000' && c < '\u2100')) {
t = "000" + Integer.toHexString(c);
sb.append("\\u" + t.substring(t.length() - 4));
} else {
sb.append(c);
}
}
}
sb.append('"');
return sb.toString();
}
public static String stringHashToJson(Set<String> set) {
if (set == null)
return "[]";
StringBuilder json = new StringBuilder();
boolean first = true;
json.append("[");
for(String k : set) {
if(!first) json.append(",");
first = false;
json.append(Util.quoteJsonString(k) + "\n");
}
json.append("]");
return json.toString();
}
}
| [
"[email protected]"
] | |
e8730b9c8dff1b12cd96d431f3b16d5d8b5a0871 | 30cf12e4016cc89018b554465406e8f9fa4ec3b3 | /javaEE/src/test_Practice/day03Test/test13.java | 852bdca5aed6de5741bcf553660a53a40ef47dde | [] | no_license | guangjianwei/ssm_sum | 9f9b3279ca35599a0495457ab6f9f9db3c9ad025 | 7545c1e7f4a8626f1a3d8f832bd73cc296523f19 | refs/heads/master | 2020-04-04T12:52:47.394638 | 2018-11-03T02:51:03 | 2018-11-03T02:51:03 | 155,940,658 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 425 | java | package test_Practice.day03Test;
/*
*/
public class test13 {
public static void main(String[] args) {
Student stu[]={new Student("liusan",20,90.0f),
new Student("lisi",22,90.0f),
new Student("wangwu",20,99.0f),
new Student("sunliu",22,100.0f)};
java.util.Arrays.sort(stu);
for(Student s:stu){
System.out.println(s);
}
}
}
| [
"[email protected]"
] | |
867b6366b3d85ec9157b62ca2f2f772235aa4525 | 3441de0b93c9bc4dc40e1a46abd7d36cafe51c2d | /passcloud-common/passcloud-security-core/src/main/java/com/passcloud/security/core/social/weixin/connect/WeixinConnectionFactory.java | 00c3e14d742bd3a8cee5fdf23d76312a27c279dd | [] | no_license | XinxiJiang/passcloud-master | 23baeb1c4360432585c07e49e7e2366dc2955398 | 212c2d7c2c173a788445c21de4775c4792a11242 | refs/heads/master | 2023-04-11T21:31:27.208057 | 2018-12-11T04:42:18 | 2018-12-11T04:44:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,500 | java | package com.passcloud.security.core.social.weixin.connect;
import com.passcloud.security.core.social.weixin.api.Weixin;
import org.springframework.social.connect.ApiAdapter;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.support.OAuth2Connection;
import org.springframework.social.connect.support.OAuth2ConnectionFactory;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2ServiceProvider;
/**
* 微信连接工厂
*
* @author liyuzhang
*/
public class WeixinConnectionFactory extends OAuth2ConnectionFactory<Weixin> {
/**
* Instantiates a new Weixin connection factory.
*
* @param providerId the provider id
* @param appId the app id
* @param appSecret the app secret
*/
public WeixinConnectionFactory(String providerId, String appId, String appSecret) {
super(providerId, new WeixinServiceProvider(appId, appSecret), new WeixinAdapter());
}
/**
* 由于微信的openId是和accessToken一起返回的,所以在这里直接根据accessToken设置providerUserId即可,不用像QQ那样通过QQAdapter来获取
*
* @param accessGrant the access grant
*
* @return the string
*/
@Override
protected String extractProviderUserId(AccessGrant accessGrant) {
if (accessGrant instanceof WeixinAccessGrant) {
return ((WeixinAccessGrant) accessGrant).getOpenId();
}
return null;
}
/**
* Create connection connection.
*
* @param accessGrant the access grant
*
* @return the connection
*/
@Override
public Connection<Weixin> createConnection(AccessGrant accessGrant) {
return new OAuth2Connection<>(getProviderId(), extractProviderUserId(accessGrant), accessGrant.getAccessToken(),
accessGrant.getRefreshToken(), accessGrant.getExpireTime(), getOAuth2ServiceProvider(), getApiAdapter(extractProviderUserId(accessGrant)));
}
/**
* Create connection connection.
*
* @param data the data
*
* @return the connection
*/
@Override
public Connection<Weixin> createConnection(ConnectionData data) {
return new OAuth2Connection<>(data, getOAuth2ServiceProvider(), getApiAdapter(data.getProviderUserId()));
}
private ApiAdapter<Weixin> getApiAdapter(String providerUserId) {
return new WeixinAdapter(providerUserId);
}
private OAuth2ServiceProvider<Weixin> getOAuth2ServiceProvider() {
return (OAuth2ServiceProvider<Weixin>) getServiceProvider();
}
}
| [
"[email protected]"
] | |
044bd6d3c35040ab20d0197ae38ad43dc7afac71 | a68d8a1ce4f442c6221e9465929cca5065c7d14c | /sed/sed-service/src/main/java/com/bsu/sed/model/dto/ContentDto.java | 4668f62a9c2a54783ce76b8d04a7839bdadc2b95 | [
"Apache-2.0"
] | permissive | GlebBondarchuk/SED | c803fcca7d22f7310c2d89697db62d71798eb576 | ccf00969bba690c1d1fc006d676a14aab65430d1 | refs/heads/master | 2021-01-10T18:59:54.417186 | 2015-05-25T14:56:42 | 2015-05-25T14:56:42 | 27,765,044 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,253 | java | package com.bsu.sed.model.dto;
import com.bsu.sed.model.Role;
import java.util.Date;
/**
* @author gbondarchuk
*/
public class ContentDto {
private static final long serialVersionUID = -2469204873901854757L;
private Long id;
private String html;
private String name;
private Date updateDate;
private Role role;
private boolean isStatic;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getHtml() {
return html;
}
public void setHtml(String html) {
this.html = html;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public boolean isStatic() {
return isStatic;
}
public void setStatic(boolean isStatic) {
this.isStatic = isStatic;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
| [
"[email protected]"
] | |
73cdef12920d0816068623cd6e965d3de95ca668 | c1a81500886719fee7b2cd4e178ba519ef4b946b | /reputationbox/dom/src/main/java/org/nic/isis/ri/SemanticSpace.java | 9dddbe148c6c2b19b16c048774fc6652e46224a6 | [] | no_license | dileepajayakody/isis-reputationbox | 6a7cca05fa392d14145456bd3d2985c0e019fbf1 | 1fe2a3426741c875d4fa5e39a60d509d93a31bb7 | refs/heads/master | 2016-09-06T16:51:57.547673 | 2015-12-08T11:15:07 | 2015-12-08T11:15:07 | 19,370,515 | 1 | 0 | null | 2014-07-01T08:41:39 | 2014-05-02T09:03:17 | Java | UTF-8 | Java | false | false | 4,638 | java | /*
* Copyright 2009 Keith Stevens
*
* This file is part of the S-Space package and is covered under the terms and
* conditions therein.
*
* The S-Space package is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation and distributed hereunder to you.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND NO REPRESENTATIONS OR WARRANTIES,
* EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE
* NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY
* PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION
* WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER
* RIGHTS.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.nic.isis.ri;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import edu.ucla.sspace.vector.TernaryVector;
/**
* A common interface for interacting with semantic space models of meaning.
* Implementations should expect the following sequence of processing.
*
* <ol>
* <li> {@link #processDocument(BufferedReader) processDocument} will be called
* one or more times with the text of the corpus.
*
* <li> {@link #processSpace(Properties) processSpace} will be called after all
* the documents have been used. Once this method has been called, no
* further calls to {@code processDocument} should be made
*
* <li> {@link #getVector(String) getVector} may be called after the space has
* been processed. Implementations may optionally support this method
* being called prior to {@code processSpace} but this is not required.
*
* </ol>
*
* In addition, {@link #getWords()} may be called at any time to determine which
* words are currently represented in the space. Implementations should specify
* in their class documentations what parameters are available as properties for
* the {@code processSpace} method, and what the default value of those
* parameters are.
*/
public interface SemanticSpace {
/**
* Processes the contents of the provided file as a document.
*
* @param document a reader that allows access to the text of the document
*
* @throws IOException if any error occurs while reading the document
*/
void processDocument(BufferedReader document) throws IOException;
/**
* mainly used for NLP keyword processing
* @param words
* @return the aggregated index vectors of the words
*/
double[] processWords(Map<String,Integer> words);
/**
* Returns the set of words that are represented in this semantic space.
*
* @return the set of words that are represented in this semantic space.
*/
Set<String> getWords();
//added by Dileepa for generalization purpose
Map<String, TernaryVector> getWordToIndexVector();
Map<String, double[]> getWordToMeaningVector();
/**
* Returns the semantic vector for the provided word.
*
* @param word a word that may be in the semantic space
*
* @return The vector for the provided word or {@code null} if the
* word was not in the space.
*/
double[] getVector(String word);
/**
* Once all the documents have been processed, performs any post-processing
* steps on the data. An algorithm should treat this as a no-op if no
* post-processing is required. Callers may specify the values for any
* exposed parameters using the {@code properties} argument.
*
* <p>
*
* By general contract, once this method has been called, {@code
* processDocument} will not be called again.
*
* @param properties a set of properties and values that may be used to
* configure any exposed parameters of the algorithm.
*/
void processSpace(Properties properties);
/**
* Returns a unique string describing the name and configuration of this
* algorithm. Any configurable parameters that would affect the resulting
* semantic space should be expressed as a part of this name.
*/
String getSpaceName();
/**
* Returns the length of vectors in this semantic space. Implementations
* are left free to define whether the returned value is valid before {@link
* #processSpace(Properties) processSpace} is called.
*/
int getVectorLength();
}
| [
"[email protected]"
] | |
91ae4e62888535ce269f10ae47d1f87fb4dc8a6f | c27967d936b9473c61f762ef3be3c9439c09c12b | /src/com/javarush/test/level04/lesson06/task04/Solution.java | 78eb65f80be08594f94d9c332b3122a06db062d7 | [] | no_license | AliNaffaa/JavaRushHomeWork | 26503564f89ef5dfcc1d7f9e30d88b350cc88fa3 | cb14644d5d254a3ede0cbb6cc5058fc6a439e1a4 | refs/heads/master | 2021-01-13T02:36:57.964666 | 2014-11-30T11:35:03 | 2014-11-30T11:35:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 974 | java | package com.javarush.test.level04.lesson06.task04;
/* Сравнить имена
Ввести с клавиатуры два имени, и если имена одинаковые вывести сообщение «Имена идентичны». Если имена разные, но их длины равны – вывести сообщение – «Длины имен равны».
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Solution
{
public static void main(String[] args) throws Exception
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String firstName = reader.readLine();
String secondName = reader.readLine();
if (firstName.equals(secondName))
System.out.println("Имена идентичны");
else if(firstName.length()==secondName.length())
System.out.println("Длины имен равны");
}
}
| [
"[email protected]"
] | |
94a8f2487f7d4eecae3cbf685cbb4f81b897f4fa | c10e5b8aa440755d2a9cbc1ee31f0d64d3fd05f3 | /Client/src/MClient/GameCards/Monsters/MonsterPrototype2.java | 9792d6b7cc00e741980ec2fd883b0f939f9105e7 | [] | no_license | DerutDan/MGamev2 | cf6b2f6214b7a2769ddba7b91cfcfcaefa0147cf | 48fae1c78e9bcf8eeb1d058dd582f89dac4aebb3 | refs/heads/master | 2021-01-21T07:20:18.605031 | 2017-05-17T19:04:22 | 2017-05-17T19:04:22 | 91,610,815 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 364 | java | package MClient.GameCards.Monsters;
/**
* Created by Danila on 15.02.17.
*/
public class MonsterPrototype2 extends Monster {
@Override
public void setDeathDescription() {
deathDescription = "Master takes 15 damage\n";
}
@Override
public void setPenaltyDescription() {
penaltyDescription = "Enemy takes 5 damage\n";
}
}
| [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.