text
stringlengths
10
2.72M
package com.dto; public class MemberDTO { private String userid; private String passwd; private String ssn; private String username; private String post; private String addr; private String phone; private String email; private String email1; private String email2; private char agent; private String ssn1; private String ssn2; private String phone1; private String phone2; private String phone3; public MemberDTO() { super(); // TODO Auto-generated constructor stub } public MemberDTO(String userid, String passwd, String phone) { super(); this.userid = userid; this.passwd = passwd; this.phone = phone; } public MemberDTO(String userid, String passwd, String ssn, String username, String post, String addr, String phone, String email, String email1, String email2, char agent, String ssn1, String ssn2, String phone1, String phone2, String phone3) { super(); this.userid = userid; this.passwd = passwd; this.ssn = ssn; this.username = username; this.post = post; this.addr = addr; this.phone = phone; this.email = email; this.email1 = email1; this.email2 = email2; this.agent = agent; this.ssn1 = ssn1; this.ssn2 = ssn2; this.phone1 = phone1; this.phone2 = phone2; this.phone3 = phone3; } public MemberDTO(String userid, String passwd, String ssn, String username, String post, String addr, String phone, String email, char agent) { super(); this.userid = userid; this.passwd = passwd; this.ssn = ssn; this.username = username; this.post = post; this.addr = addr; this.phone = phone; this.email = email; this.agent = agent; } public MemberDTO(String userid, String passwd, String ssn, String username, String post, String addr, String phone, String email) { super(); this.userid = userid; this.passwd = passwd; this.ssn = ssn; this.username = username; this.post = post; this.addr = addr; this.phone = phone; this.email = email; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } public String getSsn() { return ssn; } public void setSsn(String ssn) { this.ssn = ssn; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPost() { return post; } public void setPost(String post) { this.post = post; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public char getAgent() { return agent; } public void setAgent(char agent) { this.agent = agent; } @Override public String toString() { return "MemberDTO [userid=" + userid + ", passwd=" + passwd + ", ssn=" + ssn + ", username=" + username + ", post=" + post + ", addr=" + addr + ", phone=" + phone + ", email=" + email + ", email1=" + email1 + ", email2=" + email2 + ", agent=" + agent + ", ssn1=" + ssn1 + ", ssn2=" + ssn2 + ", phone1=" + phone1 + ", phone2=" + phone2 + ", phone3=" + phone3 + "]"; } public String getEmail1() { return email1; } public void setEmail1(String email1) { this.email1 = email1; } public String getEmail2() { return email2; } public void setEmail2(String email2) { this.email2 = email2; } public String getSsn1() { return ssn1; } public void setSsn1(String ssn1) { this.ssn1 = ssn1; } public String getSsn2() { return ssn2; } public void setSsn2(String ssn2) { this.ssn2 = ssn2; } public String getPhone1() { return phone1; } public void setPhone1(String phone1) { this.phone1 = phone1; } public String getPhone2() { return phone2; } public void setPhone2(String phone2) { this.phone2 = phone2; } public String getPhone3() { return phone3; } public void setPhone3(String phone3) { this.phone3 = phone3; } }
package com.company; public class Birou extends Mobila { boolean areSertare; boolean suport; public Birou(int anAparitie, boolean calitate, String nume, String tip, float lungime, float latime, float inaltime, String tipModel, String brand, boolean areSertare, boolean suport) { super(anAparitie, calitate, nume, tip, lungime, latime, inaltime, tipModel,brand); this.areSertare = areSertare; this.suport = suport; } void showBirou(){ System.out.println("Are/nu are sertare: "+areSertare); System.out.println("Are/ nu are suport: "+suport); } }
package com.example.simpledashcam; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; public class FlickrLoginProvider extends ContentProvider { static final String _ID = "_id"; static final String NSID = "nsid"; static final String API_KEY = "api_key"; static final String API_KEY_SECRET = "api_key_secret"; static final String ACCESS_TOKEN = "access_token"; static final String TOKEN_SECRET = "token_secret"; static final String USERNAME = "username"; static final String DATABASE_NAME = "SimpleDashCam"; static final String TABLE_NAME_FLICKR_LOGIN = "FlickrLogin"; static final int DATABASE_VERSION = 1; static final String CREATE_DB_TABLE = " CREATE TABLE " + TABLE_NAME_FLICKR_LOGIN + " (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + " " + NSID + " TEXT NOT NULL, " + " " + API_KEY + " TEXT NOT NULL, " + " " + API_KEY_SECRET + " TEXT NOT NULL, " + " " + ACCESS_TOKEN + " TEXT NOT NULL, " + " " + TOKEN_SECRET + " TEXT NOT NULL, " + " " + USERNAME + " TEXT NOT NULL);"; static final String PROVIDER_NAME = "com.example.simpledashcam.provider"; static final String URL = "content://" + PROVIDER_NAME + "/" + TABLE_NAME_FLICKR_LOGIN; static final Uri CONTENT_URI = Uri.parse(URL); private SQLiteDatabase db; /** * Helper class that actually creates and manages * the provider's underlying data repository. */ private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context){ super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_DB_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_FLICKR_LOGIN); onCreate(db); } } public FlickrLoginProvider() { } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { int count = db.delete(TABLE_NAME_FLICKR_LOGIN, selection, selectionArgs); getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public String getType(Uri uri) { return "vnd.android.cursor.dir/vnd.example.FlickrLoginProvider"; } @Override public Uri insert(Uri uri, ContentValues values) { long rowID = db.insert(TABLE_NAME_FLICKR_LOGIN, "", values); if (rowID > 0) { Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID); getContext().getContentResolver().notifyChange(_uri, null); return _uri; } throw new SQLException("Failed to add a record into " + uri); } @Override public boolean onCreate() { Context context = getContext(); DatabaseHelper dbHelper = new DatabaseHelper(context); db = dbHelper.getWritableDatabase(); return (db != null); } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(TABLE_NAME_FLICKR_LOGIN); Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int count = db.update(TABLE_NAME_FLICKR_LOGIN, values, selection, selectionArgs); getContext().getContentResolver().notifyChange(uri, null); return count; } }
package utilities; import domain.Rule; import domain.rulesImplementation.TakeMoreForLess; import domain.rulesImplementation.TakeTwoForOne; import java.io.FileNotFoundException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; public class PricingRules { public static List<Rule> importRules(String file) throws FileNotFoundException, ParseException { List<String> importRules = FilesReader.leituradeCsvFile(file); List<Rule> rules = new ArrayList<Rule>(); for (String item : importRules) { String[] aux = item.split(";"); switch (Integer.parseInt(aux[0])) { case 1: Rule ruleOne = new TakeTwoForOne(Integer.parseInt(aux[0]), (aux[1]), aux[2], Integer.parseInt(aux[3])); rules.add(ruleOne); break; case 2: Rule ruleTwo = new TakeMoreForLess(Integer.parseInt(aux[0]), (aux[1]), aux[2], Integer.parseInt(aux[3])); rules.add(ruleTwo); break; default: break; } } return rules; } }
package edu.mit.cci.simulation.util; import com.Ostermiller.util.CSVParser; import org.apache.commons.io.IOUtils; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * User: jintrone * Date: 3/20/11 * Time: 4:47 PM */ public class CSVReader implements Iterable<Map<String,String>>{ List<String> headers = new ArrayList<String>(); Reader reader = null; String[][] lines; public CSVReader(String s) throws IOException { reader = new FileReader(s); lines = CSVParser.parse(reader); for (String str:lines[0]) { headers.add(str); } } public Map<String,String> readLine(int idx) { if (idx < lines.length) { Map<String,String> result = new HashMap<String,String>(); int i = 0; for (String s:lines[idx]) { result.put(headers.get(i++),s); } return result; } else return Collections.emptyMap(); } @Override public Iterator<Map<String, String>> iterator() { return new Iterator<Map<String,String>>() { int currLine = 1; @Override public boolean hasNext() { return currLine < lines.length; } @Override public Map<String, String> next() { return readLine(currLine++); } @Override public void remove() { throw new UnsupportedOperationException("This iterator does not support the removal of items"); } }; } }
+--------------------+ | STATIC MODIFIER | +--------------------+ "STATIC KEYWORD IS MODIFIER APPLICABLE FOR METHOD AND VARIABLES BUT NOT FOR CLASSES WE CAN'T DECLARE TOP "LEVEL CLASS WITH STATIC MODIFIER BUT WE CAN DECLARE INNER CLASS AS STATIC' [SUCH TYPE OF INNER CLASSARE "CALLED STATIC NESTED CLASSES]. **************************************************************************************************** "IN THE CASE OF INSTANCE VARIABLES FOR EVERY OBJECT A SEPRATE COPY WILL CREATED BUT IN THE CASE OF STATIC "VARIABLE A SINGLE COPY WILL BE CREATED AT CLASS LEVEL AND SHARED BY EVERY OBJECT OF THAT CLASS. "static class inside attribute not automatically becomes static like variable method.:refer:staticlass.java "we can not access instance method from static method using instance class name but reference can access. Example:- -------- class Test { static int i = 10; int y = 20; public static void main(String[]args) { Test t1 = new Test(); t1.x = 888; t1.y = 999; Test t2 = new Test(); System.out.println(t2.x+"-----"+t2.y)==>888.20; } | | } +--Because of static variable only one copy for ever -y object.- "WE CAN'T ACCESS INSTANCE MEMBER DIRECTLY FROM STATIC AREA BUT WE CAN ACCESS FROM INSTANCE AREA DIRECTLY, "WE CAN ACCESS STATIC MEMBERS FROM BOTH INSTANCE AND STATIC AREA DIRECTLY. **************************************************************************************************** CONSIDER THE FOLLOWING DECLARATION. ================================= 1:int x = 10; 2:static int x = 10; 3:public void m1() { Sop(x); } 4:public static void m1() { Sop(x); }; Within the same class which of the above declaration we can take simultaneously 1 and 3 allowed 2 and 3 allowed +---------------------------------------------------------------------+ 1 and 4 not allowed |Error:non static variable cannot be references from a static method | 2 and 4 allwed +---------------------------------------------------------------------+ +--------------------------------------------+ 1 and 2 invalied |Error:variable x is already define in Test | +--------------------------------------------+ +--------------------------------------+ 3 and 4 invalid |Error:m1() is already defined in Test | +--------------------------------------+ Example:- public class Parent { int x = 10; public void m1() { System.out.println(x); } } class child extends Parent { public static void m2() { System.out.println(x);//errorBecause of can't access instance member from static method. } } note1: Overloading concept applicable for static method including main method But JVM always call String[]arg main method only Example:- -------- class Test { public static void main(String[]args) { System.out.println("String[]"); } public static void m1() { System.out.println("i+[]"); } } other overloaded method we have to call just like a normal method call note2: "INHERITANCE CONCEPT APPLICABLE FOR STATIC METHOD INCLUDING MAIN METHOD HENCE WHILE EXECUTING CHILD CLASS "IF CHILD DOSEN'T CONTAIN MAIN METHOD THEN PARENT CLASS MAIN METHOD WILL BE EXECUTED. Example:- -------- class P { public static void main(String[]args) { System.out.println("Parent main"); } } class C extends P { $>javac P.java } | +--+-----------| | | P.class C.class $>java P==>parent main $>java C==>Parent main note3: class P { public static void main(String[]args)<---------------+ { | System.out.println("Parent main"); | } | } | ----->it is method hidding but not overriding. class C extends P | { | public static void main(String[]args)<---------------+ { super("child main"); } } $>javac P.java $>java P==>Parent main $>javac C.java $>java C==>child main +---------------------------------------------------------------------------------------------------------+ |IT SEEMS OVERIDING CONCEPT APPLICABLE FOR STATIC METHOD BUT IT IS NOT OVERRIDING AND IT IS METHOD HIDDING| +---------------------------------------------------------------------------------------------------------+ note: ===== "FOR STATIC METHOD OVERLOADING AND INHERITANCE CONCEPT ARE APPLICALBE BUT OVERRIDING CONCEPT ARE NOT "APPLICABLE BUT INSTEAD OF OVERRIDING METHOD HIDDING CONCEPT IS APPLICABLE. Inside method implementation if we are using at least one instance variable then that method talks about' particular object hence we should declare method as instannce method' Inside method implemenation if we are not using any instance variable then this method no ware related to particular object hence we have to declare such type of method as static method irrespective of whether we are using static variable or not | | class Thunderbird Example:- | { | String Brand; class Student | static Price; { | String name; | // public String GetInfo1() public static GetInfo1();//error non-static int rollno; | { // variable brand int marks; | return Brand; // cannot be refe static String cname; | } +-------------------+ | public int GetInfo2() |getStudentInfo() | | { |{ | --->instance method | return Price; |return name+-+marks| | } +-------------------+ | public static void main(String[]args) +----------------------+ | { | getCollegeInfo() | | Thunderbird t = new Thunderbird(); | { | | t.Brand = "ROYAL"; | return cname; | --->static method | t.Price = 165000; | } | | System.out.println(t.GetInfo1()); +-------------------------+ | System.out.println(t.GetInfo2()); | getAverage() | | } | { | | | return x+y/2; | --->static method | | } | | +-------------------------------------------------------+ | getCompleteInfo() | | { | --->instance method | return name+"----"+rollno+---"+marks+---"+cname; | +-------------------------------------------------------+ "FOR STATIC METHOD IMPLEMENTATION SHOULD BE AVAILABLE WHERE AS FOR ABSTRACT METHOD IMPLEMENTATION IS NOT "AVAILABLE HENCE ABSTRACT STATIC COMBINATION IS ILLEGAL FOR METHOD. SYNCHRONIZED MODIFIER:- ====================== synchronized IS THE MODIFIER APPLICABLE FOR METHOD AND BLOCKS BUT NOT FOR CLASSES AND VARIABLE.' IF MULTIPLE THREAD TRYING TO OPERATE SIMULTANEOUSLY ON THE SAME JAVA OBJECT THEN THERE MAY BE CHANCE OF' , DATA INCONSISTANCE PROBLEM' THIS IS CALLED RACE CONDITION WE CAN OVERCOME THIS PROBLEM BY USING SYNCHRONIZED KEYWORD' IF A METHOD OR BLOCK DECLARE AS SYNORONIZED THEN AT A TIME ONLY ONE THREAD IS ALLOWED TO EXECUTE' THAT METHOD OR BLOCK ON THE GIVEN OBJECT SO THAT DATA INCONSISTANCE PROBLEM WILL BE RESOLVED. BUT MAIN DISADVANTAGE SYNCRONIZED KEYWORD IS IT INCREASEING WAITING TIME OF THREAD' AND CREATE PERFORMANCE, PROBLEM HENCE IF THERE NO SPACIFIC REQUIRMENT THEN IT IS NOT RECOMMENDED TO USE SYNCRONIZED . SYNCRONIZED METHOD SHOULD COMPULSORY CONTAIN IMPLEMENTATION WHERE AS ABSTRACT METHOD DOSEN'T CONTAIN ANY, IMPLEMENTATION HENCE ABSTRACT SYNCRONIZED IS ILLEGAL COMBINATION OF MODIFIERS FOR METHODS.
import java.util.*; public class ArrayListLoopExample { public static void main(String args[]) { // initialize ArrayList ArrayList<Integer> al = new ArrayList<Integer>(); // add elements to ArrayList object al.add(3); al.add(17); al.add(6); al.add(9); al.add(7); System.out.println("Using Advanced For Loop"); // printing ArrayList for (Integer num : al) { System.out.println(num); } } }
package com.hello.suripu.service.resources; import com.hello.suripu.core.ObjectGraphRoot; import com.hello.suripu.core.flipper.FeatureFlipper; import com.librato.rollout.RolloutClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; public abstract class BaseResource { private static final List<String> EMPTY = new ArrayList<>(); private static final Logger LOGGER = LoggerFactory.getLogger(BaseResource.class); @Inject RolloutClient featureFlipper; protected BaseResource() { ObjectGraphRoot.getInstance().inject(this); } /** * Use this method to return plain text errors (to Sense) * It returns byte[] just to match the signature of most methods interacting with Sense * @param status * @param message * @return */ protected byte[] plainTextError(final Response.Status status, final String message) { LOGGER.error("{} : {} ", status, (message.isEmpty()) ? "-" : message); throw new WebApplicationException(Response.status(status) .entity(message) .type(MediaType.TEXT_PLAIN_TYPE).build() ); } public void throwPlainTextError(final Response.Status status, final String message) throws WebApplicationException { plainTextError(status, message); } // TODO: add similar method for JSON Error /** * Returns the first IP address specified in headers or empty string * @param request * @return */ public static String getIpAddress(final HttpServletRequest request) { final String ipAddress = (request.getHeader("X-Forwarded-For") == null) ? request.getRemoteAddr() : request.getHeader("X-Forwarded-For"); if (ipAddress == null) { return ""; } final String[] ipAddresses = ipAddress.split(","); return ipAddresses[0]; // always return first one? } // Calibration is enabled on a per device basis protected Boolean hasCalibrationEnabled(final String senseId) { return featureFlipper.deviceFeatureActive(FeatureFlipper.CALIBRATION, senseId, EMPTY); } }
package com.esum.framework.core.component.listener; public abstract class DummyListener extends AbstractListener { private static final long serialVersionUID = 1L; }
public class Player extends Unit implements Loggable { private MessageLogger logger; private int age; private String nationality; private String position; private float height; private Condition condition = null; private int skill; public Player(String name, long salary, int age, String nationality, String position, float height, int skill) { super(name, salary); this.age = age; this.nationality = nationality; this.position = position; this.height = height; this.skill = skill; } public int getTotalSkill() { // 선수의 능력치(condition.healthiness, condition.psychological, skill)를 합하여 반환 return (this.getCondition().getHealthiness() + this.getCondition().getPsychological() + this.skill); } public int shoot(boolean verbose) { int point = (int)RandomGenerator.getRangedRandomInt(2, 3); // 2점 혹은 3점 (랜덤) Math.random() // getTotalSkill 값을 0~1.0사이의 값으로 스케일링 하여(x 0.01) + 0.5 를 더하고 (point / 2 x 0.1) 을 더해서 // TrueFalse 로 득점 유무 - 득점시 point 못하면 point = 0 if(!RandomGenerator.TrueFalse((this.getTotalSkill() * 0.01) + 0.65 - (point * 0.01))) { point = 0; } else { if(verbose) this.sendMessage(this.getName() + " got " + String.valueOf(point) + " point shot."); } return point; } public void setLogger(Object o) { if(o instanceof MessageLogger) { this.logger = (MessageLogger) o; } } @Override public void sendMessage(String msg) { this.logger.addMessage(msg); } public void setCondition(Condition condition) { this.condition = condition; } public String getNationality() { return nationality; } public String getPosition() { return position; } public float getHeight() { return height; } public Condition getCondition() { return condition; } public int getSkill() { return skill; } }
package view; import controller.OperationFailedException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; public class ErrorMessageHandler { /** * Prints error message for user. * @param msg */ void showErrorMsg(String msg) { StringBuilder errorMsgBuilder = new StringBuilder(); errorMsgBuilder.append(createTime()); errorMsgBuilder.append(", ERROR: "); errorMsgBuilder.append(msg); System.out.println(errorMsgBuilder); } /** * Prints error message to Dev. * @param e */ public void logErrorMsg(OperationFailedException e) { StringBuilder logMsgBuilder = new StringBuilder(); logMsgBuilder.append(createTime()); logMsgBuilder.append(", ERROR: "); logMsgBuilder.append(e.getMessage()); System.out.println(logMsgBuilder); e.printStackTrace(); } /** * Get and format current time. * @return */ private String createTime() { LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM); return now.format(formatter); } }
package com.vopt.fleetapp.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class EmployeeTypeController { @GetMapping("/employeeType") public String getEmployeeType(){ return "employeeType"; } }
package com.fehead.community.service; import com.baomidou.mybatisplus.extension.service.IService; import com.fehead.community.entities.ClubUser; import com.fehead.community.error.BusinessException; import java.util.List; /** * <p> * 服务类 * </p> * * @author ktoking * @since 2020-04-03 */ public interface IClubUserService extends IService<ClubUser> { //加入社团 void addClub(Integer userId,Integer clubId) throws BusinessException; //获取我加入的所有社团id List<ClubUser> clubs(Integer userId); //获取所有社团下的用户 List<ClubUser> getClubUser(Integer clubId) throws BusinessException; //分页查找所有社团下的用户 List<ClubUser> getAllUserByPage(Integer page,Integer clubId) throws BusinessException; //退出社团 Integer quiteClub(Integer userId,Integer clubId) throws BusinessException; Integer getNumbers(Integer clubId); }
package com.sun.xml.bind.v2.runtime.unmarshaller; import com.sun.xml.bind.DatatypeConverterImpl; import com.sun.xml.bind.api.AccessorException; import com.sun.xml.bind.v2.WellKnownNamespace; import com.sun.xml.bind.v2.runtime.reflect.Accessor; import org.xml.sax.SAXException; /** * Looks for xsi:nil='true' and sets the target to null. * Otherwise delegate to another handler. * * @author Kohsuke Kawaguchi */ public class XsiNilLoader extends ProxyLoader { private final Loader defaultLoader; public XsiNilLoader(Loader defaultLoader) { this.defaultLoader = defaultLoader; assert defaultLoader!=null; } protected Loader selectLoader(UnmarshallingContext.State state, TagName ea) throws SAXException { int idx = ea.atts.getIndex(WellKnownNamespace.XML_SCHEMA_INSTANCE,"nil"); if(idx!=-1) { String value = ea.atts.getValue(idx); if(DatatypeConverterImpl._parseBoolean(value)) { onNil(state); return Discarder.INSTANCE; } } return defaultLoader; } /** * Called when xsi:nil='true' was found. */ protected void onNil(UnmarshallingContext.State state) throws SAXException { } public static final class Single extends XsiNilLoader { private final Accessor acc; public Single(Loader l, Accessor acc) { super(l); this.acc = acc; } protected void onNil(UnmarshallingContext.State state) throws SAXException { try { acc.set(state.prev.target,null); } catch (AccessorException e) { handleGenericException(e,true); } } } public static final class Array extends XsiNilLoader { public Array(Loader core) { super(core); } protected void onNil(UnmarshallingContext.State state) { // let the receiver add this to the lister state.target = null; } } }
package br.com.raiox.model; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import br.com.raiox.generic.IGenericEntity; import br.com.raiox.util.StringUtil; /** * Pojo Cargo * * @author daniel alencar barros tavares * @version 1.0 * * @since 07/03/2016 */ @Entity @NamedQueries(value = { @NamedQuery(name = "Cargo.findByID", query = "SELECT c FROM Cargo c " + "WHERE c.id = ?1 ") }) @Table(name = "cargo") public class Cargo extends AbstractEntity implements IGenericEntity<Cargo> { /** * */ private static final long serialVersionUID = 1L; @Transient public static final String FIND_BY_ID = "Cargo.findByID"; @Id @Column(name = "id_cargo") @GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY) private Integer id; @Column(name = "ds_cargo") private String dsCargo; @OneToMany(mappedBy = "cargo", fetch = FetchType.LAZY) private List<Servidor> servidor; public List<Servidor> getServidor() { return servidor; } public void setServidor(List<Servidor> servidor) { this.servidor = servidor; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getDsCargo() { return dsCargo; } public void setDsCargo(String dsCargo) { this.dsCargo = dsCargo; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Cargo other = (Cargo) obj; if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 89 * hash + (this.id != null ? this.id.hashCode() : 0); return hash; } @Override public String toString() { return id + "-" + dsCargo; } /* * Validar entidade */ public String validate() { String validate = ""; if (StringUtil.isNullOrEmpty(dsCargo)) { validate += "Descrição é Obrigatório!"; } return validate; } }
package edu.harvard.hms.dbmi.avillach.auth.data.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import org.hibernate.annotations.Type; import com.fasterxml.jackson.annotation.JsonInclude; import edu.harvard.dbmi.avillach.data.entity.BaseEntity; @JsonInclude(JsonInclude.Include.NON_EMPTY) @Entity(name = "credential") public class Credential extends BaseEntity implements Serializable { /** * generated */ private static final long serialVersionUID = -4652918137080056344L; /** * should be stored as a salted hash */ @Column(name = "password") @Type(type = "text") private String password; @Column(name = "created_on") @Type(type = "date") private Date createdOn; @Column(name = "salt", columnDefinition = "BINARY(16)") private byte[] salt; @Column(name = "is_expired") private Boolean isExpired; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getCreatedOn() { return createdOn; } public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } public byte[] getSalt() { return salt; } public void setSalt(byte[] salt) { this.salt = salt; } public Boolean isExpired() { return isExpired; } public void setExpired(Boolean isExpired) { this.isExpired = isExpired; } }
/* * $Id$ * $Name$ */ package org.usd.csci.person.personrest; import java.net.URI; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import javax.ejb.Singleton; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import static javax.ws.rs.HttpMethod.DELETE; import static javax.ws.rs.HttpMethod.POST; import javax.ws.rs.NotFoundException; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.usd.csci.person.data.Person; import static org.usd.csci.person.data.Person.BIRTH_DATE_FORMAT; import static org.usd.csci.person.data.Person.BIRTH_DATE_KEY; import static org.usd.csci.person.data.Person.FIRST_NAME_KEY; import static org.usd.csci.person.data.Person.LAST_NAME_KEY; /** * REST Web Service * * @author Mike Benton CSC470 */ @Singleton @Path("/persons") public class PersonResource { Map<Integer, Person> persons = new ConcurrentHashMap<Integer, Person>(); AtomicInteger id = new AtomicInteger(); //-------------------------------------------------------------------------- @Context private UriInfo context; //-------------------------------------------------------------------------- public PersonResource() { loadPersons(); } /** * readPerson receives a JSON string and returns a Person object * * @param json String representing a JSON object * * @return Person with all fields set from JSON String * * @throws JSONException if problem with JSON processing * @throws ParseException if Date object in wrong format */ public Person readPerson(String json)throws JSONException, ParseException{ Person personToReturn = new Person(); JSONObject obj = new JSONObject(json); id.incrementAndGet(); personToReturn.setId(id.get()); personToReturn.setFirstname(obj.getString(FIRST_NAME_KEY)); personToReturn.setLastname(obj.getString(LAST_NAME_KEY)); String birthdateString = obj.getString(BIRTH_DATE_KEY); Date dateObject = new SimpleDateFormat("MM/dd/yyyy").parse(birthdateString); personToReturn.setBirthdate(dateObject); return personToReturn; } private void loadPersons(){ //THIS WAS ONLY TO LOAD IN A PERSON FOR TESTING id.incrementAndGet(); Person aPerson = new Person(); aPerson.setFirstname("Carol"); aPerson.setLastname("Smith"); aPerson.setBirthdate(new Date()); aPerson.setId(id.get()); persons.put(id.get(), aPerson); id.incrementAndGet(); aPerson = new Person(); aPerson.setFirstname("Jack"); aPerson.setLastname("Jackson"); aPerson.setBirthdate(new Date()); aPerson.setId(id.get()); persons.put(id.get(), aPerson); } /** * persons receives parameter(s) from the user and returns a String with * the desired query results * * @param start the starting position ID * @param size the amount of results(Persons) to return * @param name the last name specified as a search query * * @return String representing the JSON Person objects that were searched * by the user */ @GET @Produces("application/json") public String persons(@QueryParam("start") int start, @QueryParam("size") int size, @QueryParam("name") String name){ if(size == 0){ //BLOCK FOR NO PARAMETERS ENTERED BY USER IN ANY OF THE SEARCH FIELDS (RETRIEVE ALL RECORDS) if(name==null || name.isEmpty()){ try{ JSONObject jPersons = new JSONObject(); JSONArray jlist = new JSONArray(); Collection<Person> list = persons.values(); for(Person aPerson : list){ JSONObject obj = new JSONObject(aPerson.toJSON()); jlist.put(obj); } jPersons.put("persons", jlist); return jPersons.toString(); } catch(JSONException e){ throw new WebApplicationException(Response.Status.BAD_REQUEST); } } //BLOCK FOR FINDING THE NAME PARAMETER ONLY (RETRIEVE BY NAME) else if(!name.isEmpty()){ try{ JSONObject jPersons = new JSONObject(); JSONArray jlist = new JSONArray(); Collection<Person> list = persons.values(); for(Person aPerson : list){ if( aPerson.getLastname().equals(name) ){ JSONObject obj = new JSONObject(aPerson.toJSON()); jlist.put(obj); } } jPersons.put("persons", jlist); return jPersons.toString(); } catch(JSONException e){ throw new WebApplicationException(Response.Status.BAD_REQUEST); } } } //BLOCK FOR FINDING ALL PARAMETERS ENTERED BY USER (NAME, START, SIZE) else if (size != 0 && !name.isEmpty()){ try{ JSONObject jPersons = new JSONObject(); JSONArray jlist = new JSONArray(); Collection<Person> list = persons.values(); Person[] personArray; personArray =(Person[])persons.values().toArray(new Person[persons.size()]); int listSize = persons.size(); if( (size+start-1) > (listSize) ){ throw new ArrayIndexOutOfBoundsException(); } for(int i = (start-1) ; i < (size+(start-1)) ; i++){ Person aPerson = personArray[i]; if( aPerson.getLastname().equals(name) ){ JSONObject obj = new JSONObject(aPerson.toJSON()); jlist.put(obj); } } jPersons.put("persons", jlist); return jPersons.toString(); }catch(JSONException e){ throw new WebApplicationException(Response.Status.BAD_REQUEST); } } //BLOCK FOR FINDING THE SIZE & START PARAMETER ONLY - NOTHING ENTERED IN NAME PARAMETER(RETRIEVE RANGE OF RECORDS) //else (size != 0) ELSE STATEMENT COMMENTED OUT SO METHOD RECOGNIZED A RETURN STATEMENT try{ JSONObject jPersons = new JSONObject(); JSONArray jlist = new JSONArray(); Collection<Person> list = persons.values(); Person[] personArray = (Person[])persons.values().toArray(new Person[persons.size()]); int listSize = persons.size(); if( (size+start-1) > (listSize) ){ throw new ArrayIndexOutOfBoundsException(); } //REMEMBER int i IS ALWAYS CHANGING IN THE LOOP, YOU NEEDED A CONSISTENT VARIABLE (start-1) not (i-1) for(int i = (start-1) ; i < (size+(start-1)) ; i++){ Person aPerson = personArray[i]; JSONObject obj = new JSONObject(aPerson.toJSON()); jlist.put(obj); } jPersons.put("persons", jlist); return jPersons.toString(); }catch(JSONException e){ throw new WebApplicationException(Response.Status.BAD_REQUEST); } //} }//END OF PERSONS @QUERYPARAM @GET @Path("{id}") @Produces("application/json") public String persons(@PathParam("id") int id){ try{ Person aPerson = persons.get(id); if(aPerson != null){ return aPerson.toJSON(); }else{ throw new NotFoundException("not located"); } }catch(Exception e){ //DIRECTIONS SAY JSONEXCEPTION throw new WebApplicationException(Response.Status.BAD_REQUEST); } } @POST @Consumes("application/json") public Response createPerson(String is){ try{ Person person = readPerson(is); persons.put(person.getId(), person); return Response.created(URI.create("/persons/" + person.getId())).build(); }catch(JSONException e){ return Response.status(Response.Status.BAD_REQUEST).build(); }catch(ParseException e){ return Response.status(Response.Status.BAD_REQUEST).build(); } } @PUT @Path("{id}") @Consumes("application/json") public Response updatePerson(@PathParam("id") int id, String is){ try{ Person person = readPerson(is); person.setId(id); Person locPerson = persons.get(id); if(locPerson == null){ throw new WebApplicationException(Response.Status.NOT_FOUND); } persons.put(person.getId(), person); return Response.status(Response.Status.OK).build(); }catch(JSONException e){ return Response.status(Response.Status.BAD_REQUEST).build(); }catch(ParseException e){ return Response.status(Response.Status.BAD_REQUEST).build(); } } @DELETE @Path("{id}") public Response deletePerson(@PathParam("id") int id, String is){ try{ persons.remove(id); }catch(Exception e){ throw new WebApplicationException(Response.Status.NOT_FOUND); } return Response.status(Response.Status.OK).build(); } }//END CLASS
package handin07; public abstract class AbstractPerson { private String name, street, zip, city; public AbstractPerson(String name, String street, String zip, String city) { super(); this.name = name; this.street = street; this.zip = zip; this.city = city; } /** * * @return the name */ public String getName() { return name; } /** * * @return the street */ public String getStreet() { return street; } /** * * @return the zip code */ public String getZip() { return zip; } /** * * @return the city */ public String getCity() { return city; } /** * * @return the person's address as one string */ public String getAddress() { return street + "\n" + zip + " " + city; } }
package com.coder.service; public class HomeService { }
package com.davivienda.sara.tablas.usuarioaplicacion.servicio; import com.davivienda.sara.base.BaseEntityServicio; import com.davivienda.sara.base.exception.EntityServicioExcepcion; import com.davivienda.sara.entitys.seguridad.ConfAccesoAplicacion; import com.davivienda.sara.entitys.seguridad.UsuarioAplicacion; import java.util.Collection; import java.util.logging.Level; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.persistence.TransactionRequiredException; /** * ControlUsuarioAplicacionServicio - 24/05/2008 Descripción : Clase encargada * de todos los procesos de administración de la información de * UsuarioAplicacion Versión : 1.0 * * @author jjvargas Davivienda 2008 */ public class UsuarioAplicacionServicio extends BaseEntityServicio<UsuarioAplicacion> { public UsuarioAplicacionServicio(EntityManager em) { super(em, UsuarioAplicacion.class); } public Collection<ConfAccesoAplicacion> getConfAccesoAplicacion(String idUsuario) { UsuarioAplicacion usuario = null; Collection<ConfAccesoAplicacion> respuesta = null; try { usuario = buscar(idUsuario); if (idUsuario != null) { usuario.getConfAccesoAplicacionCollection().size(); respuesta = usuario.getConfAccesoAplicacionCollection(); } } catch (EntityServicioExcepcion ex) { configApp.loggerApp.log(Level.SEVERE, null, ex); } return respuesta; } @Override public UsuarioAplicacion actualizar(UsuarioAplicacion objetoModificado) throws EntityServicioExcepcion { UsuarioAplicacion objetoActual = super.buscar(objetoModificado.getUsuario()); if (objetoActual == null) { super.adicionar(objetoModificado); objetoActual = super.buscar(objetoModificado.getUsuario()); } else { objetoActual.actualizarEntity(objetoModificado); objetoActual = super.actualizar(objetoActual); } return objetoActual; } @Override public void borrar(UsuarioAplicacion entity) throws EntityServicioExcepcion { UsuarioAplicacion objetoActual = super.buscar(entity.getUsuario()); super.borrar(objetoActual); } public int borrarPorUsuario(String usuario) throws EntityServicioExcepcion { int respuesta = 0; String strQuery = "DELETE FROM UsuarioAplicacion u WHERE u.usuario = :usuario"; try { //se revisa que halla registros para el usuario Query query = null; query = em.createNamedQuery("UsuarioAplicacion.deleteByUsuario"); query.setParameter("usuario", usuario); respuesta = query.executeUpdate(); //si hay borra if (respuesta > 0) { query = null; query = em.createQuery(strQuery); query.setParameter("usuario", usuario); respuesta = query.executeUpdate(); } } catch (IllegalStateException ex) { configApp.loggerApp.log(java.util.logging.Level.SEVERE, "No se tiene acceso a la unidad de persistencia ", ex); throw new EntityServicioExcepcion(ex); } catch (TransactionRequiredException ex) { configApp.loggerApp.log(java.util.logging.Level.SEVERE, "no es una transaccion ", ex); throw new EntityServicioExcepcion(ex); } return respuesta; } }
package de.codecentric.cvgenerator; import static org.junit.Assert.*; import java.util.Collection; import org.junit.Test; import de.codecentric.cvgenerator.Employee; import de.codecentric.cvgenerator.Job; import de.codecentric.cvgenerator.Part; import de.codecentric.cvgenerator.Project; public class EmployeeTest { @Test public void testProjectsWithPart() { Employee employee = new Employee(); Part part = new Part(); Project project = new Project(); Job job = new Job(); job.setEmployee(employee); job.setPart(part); job.setProject(project); employee.add(job); Collection<Project> projects = employee.getProjectsWithPart(part); assertTrue(projects.contains(project)); } @Test public final void testGetID() { Integer testValue = 123456; Employee emp = new Employee(); emp.setID(testValue); Integer emp_id = emp.getID(); assertEquals(emp_id, testValue); } @Test(expected = RuntimeException.class) public final void testGetIDNullException() throws Exception { Employee emp = new Employee(); emp.setID(0); } }
/* * Copyright (c) 2013-2014, Neuro4j.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neuro4j.studio.debug.ui.views; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Widget; /** * This class is not part of the public API of JFace. See bug 267722. * * @since 3.5 * @noextend This class is not intended to be subclassed by clients. * @noinstantiate This class is not intended to be instantiated by clients. */ public class StructuredViewerInternals { /** * Nothing to see here. * * @since 3.5 * @noextend This interface is not intended to be extended by clients. * @noimplement This interface is not intended to be implemented by clients. */ protected static interface AssociateListener { /** * Call when an element is associated with an Item * * @param element * @param item */ void associate(Object element, Item item); /** * Called when an Item is no longer associated * * @param item */ void disassociate(Item item); /** * Called when an element has been filtered out. * * @since 3.6 * @param element */ void filteredOut(Object element); } /** * Nothing to see here. Sets or resets the AssociateListener for the given * Viewer. * * @param viewer * the viewer * @param listener * the {@link AssociateListener} * @noreference This method is not intended to be referenced by clients. */ protected static void setAssociateListener(StructuredViewer viewer, AssociateListener listener) { viewer.setAssociateListener(listener); } /** * Nothing to see here. Returns the items for the given element. * * @param viewer * @param element * @return the Widgets corresponding to the element * * @noreference This method is not intended to be referenced by clients. */ protected static Widget[] getItems(StructuredViewer viewer, Object element) { return viewer.findItems(element); } }
package com.raj; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Date; @RestController public class DemoController { @RequestMapping("/") public String hello() { return "Hello from Spring security at " + new Date(System.currentTimeMillis()); } }
package ge.softgen.nikosspringproject.clientservices; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ClientservicesApplication { public static void main(String[] args) { SpringApplication.run(ClientservicesApplication.class, args); } }
package com.newbig.im.app.controller.admin.v1; import com.github.pagehelper.PageSerializable; import com.newbig.im.common.constant.AppConstant; import com.newbig.im.dal.model.SysUser; import com.newbig.im.model.dto.SysUserAddDto; import com.newbig.im.model.dto.SysUserDeleteDto; import com.newbig.im.model.dto.SysUserUpdateDto; import com.newbig.im.model.vo.ResponseVo; import com.newbig.im.service.SysUserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.validation.Valid; /** * User: Haibo * Date: 2018-05-01 10:05:30 * Desc: */ @RestController @Slf4j @RequestMapping(value = AppConstant.API_PREFIX_V1+"/sysUser") @Api(value = "sysUser相关api.") public class SysUserController { @Resource private SysUserService sysUserService; @ApiOperation(value = "获取列表") @GetMapping(value = "/list") public ResponseVo<PageSerializable<SysUser>> getList( @RequestParam(required = false) String name, @RequestParam(required = false) String mobile, @RequestParam(required = false,defaultValue = "1") int pageNum, @RequestParam(required = false,defaultValue = "20") int pageSize ){ return ResponseVo.success(sysUserService.getList(name,mobile,pageSize,pageNum)); } @ApiOperation(value = "获取详情") @GetMapping(value = "/get") public ResponseVo<SysUser> getDetail( @RequestParam(required = false) Integer id ){ return ResponseVo.success(sysUserService.getDetailById(id)); } @ApiOperation(value = "增加") @PostMapping(value = "/add") public ResponseVo add(@Valid @RequestBody SysUserAddDto sysUserAddDto){ sysUserService.addSysUser(sysUserAddDto); return ResponseVo.success("保存成功"); } @ApiOperation(value = "更新") @PostMapping(value = "/update") public ResponseVo update(@Valid @RequestBody SysUserUpdateDto sysUserUpdateDto){ sysUserService.updateSysUser(sysUserUpdateDto); return ResponseVo.success("更新成功"); } @ApiOperation(value = "删除") @PostMapping(value = "/delete") public ResponseVo delete(@Valid @RequestBody SysUserDeleteDto sysUserDeleteDto){ sysUserService.deleteSysUser(sysUserDeleteDto.getId()); return ResponseVo.success("删除成功"); } }
package Problem_2268; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { static int N, M; static long[] arr; static long[] tree; static long query(int start, int end, int node, int left, int right) { if(left > end || right < start) return 0; if(left <= start && end <= right) return tree[node]; int mid = (start+end)/2; return query(start, mid, node*2, left, right) + query(mid+1, end, node*2+1, left,right); } static void update(int start, int end, int node, int index, long dif) { if(index < start || index > end) return; tree[node]+= dif; if(start==end) return; int mid = (start+end)/2; update(start, mid, node*2, index, dif); update(mid+1, end, node*2+1, index, dif); } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String buf = br.readLine(); N = Integer.parseInt(buf.split(" ")[0]); M = Integer.parseInt(buf.split(" ")[1]); arr = new long[N+1]; tree = new long[arr.length*4+4]; StringBuilder sb = new StringBuilder(); for(int i = 0; i<M; i++) { buf = br.readLine(); int a = Integer.parseInt(buf.split(" ")[1]); int b = Integer.parseInt(buf.split(" ")[2]); if(buf.split(" ")[0].equals("0")) { // sum result if(a > b) { // i,j no condition. so, always do i<j to swap. int temp = a; a = b; b = temp; } sb.append(query(1,N,1,a,b)).append("\n"); } else { // update : modify long dif = (long)b-arr[a]; arr[a] = b; update(1,N,1,a,dif); } } System.out.println(sb.toString()); } }
import java.util.*; import java.io.*; class powern { public static void main(String[] args) { Scanner kb=new Scanner(System.in); int m,n; m=kb.nextInt(); n=kb.nextInt(); System.out.println((int)Math.pow(m,n)); } }
package com.salesianostriana.dam; import javax.annotation.PostConstruct; import org.springframework.stereotype.Component; import com.salesianostriana.dam.modal.Cachimba; import com.salesianostriana.dam.modal.Marca; import com.salesianostriana.dam.servicios.CachimbaServicio; import com.salesianostriana.dam.servicios.MarcaServicio; import lombok.RequiredArgsConstructor; @Component @RequiredArgsConstructor public class InitData { private final CachimbaServicio caServicio; private final MarcaServicio marServicio; @PostConstruct public void init () { Marca a = new Marca ("Aladyn","Una cachimba aladin, es la prueba de que los buenos materiales y los precios baratos no son incompatibles. Por eso, nos trae todos sus modelos fabricados de acero inoxidable V2A y con un difusor regulable de tres niveles que nos proporciona un tiro desde cerrado hasta abierto pasando por niveles intermedios en función de la posición del difusor.\n" + "\n" + "Su fundación es de 1986 y su fabricación es en Egipto, siendo una cachimba de nacionalidad alemana. Todas sus purgas están fabricadas con una bola de vidrio y en función del modelo tienen una estética diferente (vertical hacia arriba, de tres salidas, una salida…), asegurándose en todas una purga completa de la base con un suave soplido."); Marca b = new Marca ("Mr.Shisha","Mr Shisha, fue fundada en 2016. Se caracteriza por su rediseño constante dentro del mundo de la cachimba además de aportar novedades como el sistema de purga vertical hacia arriba y/o hacia abajo dependiendo del modelo. La exclusividad en sus productos y sobre todo la calidad de sus materiales unido a sus bajos precios hacen de esta marca, una de las mejores del mercado."); Marca c = new Marca ("VZ Hookah", "La marca Cachimbas VZ Hookah apuesta por la fabricación a mano de todos sus productos, convirtiéndolos así en más exclusivos si cabe y de una preparación con más cautela. Teniendo así, un producto único de cada unidad que es fabricada.\n" + "\n" + "De esta forma, podemos adquirir productos de todo tipo de diseños y alturas, teniendo modelos de apenas 35 centímetros hasta modelos más altos de unos 58 centímetros. De la misma forma, al tener un tipo de cámara tradicional y una conexión con la base mediante arandelas en unos modelos y con goma a presión otros, esta marca nos ofrece la posibilidad de combinar el mástil con cualquier tipo de base que más se acople a nuestras exigencias. Obteniendo un modelo con un diseño propio y único, uniéndolo a la ya exclusividad propia de cada unidad."); marServicio.save(a); marServicio.save(b); marServicio.save(c); Cachimba ca = new Cachimba ("MVP 360","Acero","Acero inoxidable", "La cachimba MVP 360 es una cachimba de acero inoxidable de 36 cm provista de un equipamiento completo ya que se entrega con una manguera de silicona con mango de metal y un muelle, una cazoleta de terracota además de un difusor integrado regulable ",80.0,36,1,"https://www.hispacachimba.es/image/cache/catalog/aladin/cachimba-aladin-mvp-360-rainbow-550x550h.jpg"); caServicio.save(ca); Cachimba cb = new Cachimba ("MVP 460","Acero","Acero inoxidable", "La cachimba Aladin MVP 460 es uno de los nuevos modelos sacados por la marca Aladin. Tiene una altura aproximada de 46 cm y todas sus piezas son de acero inoxidable resistentes al agua.",100.70,46,1,"https://www.hispacachimba.es/image/cache/catalog/aladin/cachimba-aladin-mvp-460-model-2-glass-1-clear-550x550h.jpg"); caServicio.save(cb); Cachimba cc = new Cachimba ("Rocket 2.0","azul","Acero inoxidable", "Shisha Rocket 2.0 Deadpool, una cachimba de tamaño pequeño con base de cristal transparente con 1cm de grosor de fondo, cámara tradicional y purga completamente renovada.",100.50,1,1,"https://www.hispacachimba.es/image/cache/catalog/mrshisha/cachimba-mrshisha-megatron-20-blue-matte-resin-550x550.jpg"); caServicio.save(cc); Cachimba cd = new Cachimba ("Khalifa Gold","Oro","Acero inoxidable", "Una cachimba fabricada totalmente de acero inoxidable V2A, con una cámara tradicional que te permitirá acoplar tu cachimba a cualquier base y garantizando su purga efectiva y completa con un simple soplido.",155.95,55,1,"https://www.hispacachimba.es/image/cache/catalog/mrshisha/cachimba-mrshisha-khalifa-bronze-sin-base-550x550.jpg"); caServicio.save(cd); Cachimba ce = new Cachimba ("2 GO","Acero","Acero inoxidable", "La marca alemana aladin presento, este año 2019 su cachimba mas pequeña y manejable. (Aladin 2 GO) Fabricada y diseñada con los mejores materiales (acero inoxidable) nos traen este modelo considerado calidad precio la mejor opción como cachimba de transporte. Su tiro a diferencia de los otros modelos si que es a difusor sin regular. La cámara encaja a rosca con la lase permitiendo un sellado perfecto.",44.95,20,1,"https://www.hispacachimba.es/image/cache/catalog/aladin/cachimba-aladin-2go-550x550h.jpg"); caServicio.save(ce); Cachimba cf = new Cachimba ("MVP 670 Flower","Acero","Acero inoxidable", "La marca aladin, nos sorprende con este maravilloso modelo moderno que llama la atención por su tamaño (67cm aprox) y su estética. El modelo ms grande de la marca con bases talladas y materiales de acero inoxidable como en todos sus modelos. Esta al igual que el resto contiene el difusor regulable que permite adaptar la restricción de la fumada al gusto de cada uno. A diferencia del resto de modelos de mvp est no permite adaptar el recoge melaza característico alemán dado que el pato va conectado al mástil.",139.95,67,3,"https://www.hispacachimba.es/image/cache/catalog/aladin/cachimba-aladin-mvp-480-bottom-blue-550x550.jpg"); caServicio.save(cf); Cachimba cg = new Cachimba ("Brass","Cobre","Acero inoxidable con recubrimiento de latón", "La marca rusa VZ Hookah nos trae una de las cachimbas más elegantes del mercado, su modelo Brass. Está fabricado completamente de acero inoxidable V2A con un recubrimiento de latón que le da esa imagen de elegancia y exclusividad. Una cachimba con una bola de purga de vidrio y un difusor regulable de tres niveles. Su conexión con la base es a presión con una goma de silicona, igual que el modelo Custom y/o Minimal. Si tu objetivo es hacerte con una de las cachimbas más codiciadas del mercado, la VZ Hookah Brass es la cachimba que buscas.",439.95,60,1,"https://www.hispacachimba.es/image/cache/catalog/rusia/cachimba-vz-hookah-copper-550x550w.jpg"); caServicio.save(cg); a.addCachimba(cb); a.addCachimba(ca); b.addCachimba(cc); b.addCachimba(cd); a.addCachimba(ce); a.addCachimba(cf); c.addCachimba(cg); caServicio.edit(ca); caServicio.edit(cc); caServicio.edit(cb); caServicio.edit(cd); caServicio.edit(ce); caServicio.edit(cf); caServicio.edit(cg); } }
package api.valorevaluacion; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @AllArgsConstructor @NoArgsConstructor @Data @Entity @Table(name = "tbvalorevaluacion") public class EntidadValorEvaluacion { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String valor; private boolean habilitado; //Borrar desde aqui public String getValor() { return valor; } public void setValor(String valor) { this.valor = valor; } public boolean isHabilitado() { return habilitado; } public void setHabilitado(boolean habilitado) { this.habilitado = habilitado; } }
package mb.amazul.webservice.db.oraclerh.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import mb.amazul.webservice.db.oraclerh.model.Ta_estadoscivis; @Repository public interface Ta_estadoscivisRepository extends JpaRepository<Ta_estadoscivis, Long>{ List<Ta_estadoscivis> findAllByOrderByNome(); }
public interface TestInterface { String myvar="hello"; public abstract void read(); public abstract void write(); }
import java.util.Comparator; public enum Algorithm { FCFS(SchedulerAlgorithm.fcfs, "First Come First Serve"), SJF(SchedulerAlgorithm.sjf, "Shortest Job First"), FCFS_PRIORITY(SchedulerAlgorithm.fcfs_priority, "Priority + First Come First Serve"), SJF_PRIORITY(SchedulerAlgorithm.sjf_priority, "Priority + Shortest Job First"); private Comparator<ServiceProcess> comparator; private String value; Algorithm(Comparator<ServiceProcess> comparator, String value) { setComparator(comparator); setValue(value); } public Comparator<ServiceProcess> getComparator() { return comparator; } public String getValue() { return value; } private void setComparator(Comparator<ServiceProcess> comparator) { this.comparator = comparator; } private void setValue(String value) { this.value = value; } }
package net.admin.system; import be.mxs.common.util.db.MedwanQuery; import be.mxs.common.util.system.ScreenHelper; import java.sql.Connection; import java.sql.Timestamp; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Vector; import java.util.List; import java.util.LinkedList; public class AccessLog { private int accessid; private int userid; private Timestamp accesstime; private String lastname; private String firstname; //--- GETTERS & SETTERS ----------------------------------------------------------------------- public int getAccessid(){ return accessid; } public void setAccessid(int accessid){ this.accessid = accessid; } public int getUserid(){ return userid; } public void setUserid(int userid){ this.userid = userid; } public Timestamp getAccesstime(){ return accesstime; } public void setAccesstime(Timestamp accesstime){ this.accesstime = accesstime; } public String getLastname(){ return lastname; } public void setLastname(String lastname){ this.lastname = lastname; } public String getFirstname(){ return firstname; } public void setFirstname(String firstname){ this.firstname = firstname; } //--- SEARCH ACCESS LOGS ---------------------------------------------------------------------- public static Vector searchAccessLogs(String sFindBegin, String sFindEnd){ PreparedStatement ps = null; ResultSet rs = null; Vector vAL = new Vector(); String sSelect; String sSelect1 = "SELECT a.accessid, a.accesstime, b.lastname, b.firstname"+ " FROM AccessLogs a, Users u, Admin b"+ " WHERE a.accesstime BETWEEN ? AND ?"+ " AND u.userid = a.userid"+ " AND b.personid = u.personid"+ " ORDER BY a.accesstime, b.searchname"; String sSelect2 = "SELECT a.accessid, a.accesstime, b.lastname, b.firstname"+ " FROM AccessLogs a, Users u, Admin b"+ " WHERE a.accesstime >= ?"+ " AND u.userid = a.userid"+ " AND b.personid = u.personid"+ " ORDER BY a.accesstime, b.searchname"; String sSelect3 = "SELECT a.accessid, a.accesstime, b.lastname, b.firstname"+ " FROM AccessLogs a, Users u, Admin b"+ " WHERE a.accesstime <= ?"+ " AND u.userid = a.userid"+ " AND b.personid = u.personid"+ " ORDER BY a.accesstime, b.searchname"; Connection ad_conn = MedwanQuery.getInstance().getAdminConnection(); try{ if((sFindBegin.trim().length()>0)&&(sFindEnd.trim().length()>0)){ sSelect = sSelect1; ps = ad_conn.prepareStatement(sSelect); ps.setDate(1,ScreenHelper.getSQLDate(sFindBegin)); ps.setDate(2,ScreenHelper.getSQLDate(ScreenHelper.getDateAdd(sFindEnd, "1"))); } else if(sFindBegin.trim().length()>0){ sSelect = sSelect2; ps = ad_conn.prepareStatement(sSelect); ps.setDate(1,ScreenHelper.getSQLDate(sFindBegin)); } else if(sFindEnd.trim().length()>0){ sSelect = sSelect3; ps = ad_conn.prepareStatement(sSelect); ps.setDate(1,ScreenHelper.getSQLDate(ScreenHelper.getDateAdd(sFindEnd, "1"))); } rs = ps.executeQuery(); AccessLog objAL; while(rs.next()){ objAL = new AccessLog(); objAL.setAccessid(rs.getInt("accessid")); objAL.setLastname(ScreenHelper.checkString(rs.getString("lastname"))); objAL.setFirstname(ScreenHelper.checkString(rs.getString("firstname"))); objAL.setAccesstime(rs.getTimestamp("accesstime")); vAL.addElement(objAL); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); ad_conn.close(); } catch(Exception e){ e.printStackTrace(); } } return vAL; } //--- LOG ACCESS ------------------------------------------------------------------------------ public static void logAccess(AccessLog objAL){ PreparedStatement ps = null; String sInsert = "INSERT INTO AccessLogs (accessid,userid,accesstime)"+ " VALUES (?,?,?)"; Connection ad_conn = MedwanQuery.getInstance().getAdminConnection(); try{ ps = ad_conn.prepareStatement(sInsert); ps.setInt(1,MedwanQuery.getInstance().getOpenclinicCounter("AccessLogs")); ps.setInt(2,objAL.getUserid()); ps.setTimestamp(3,objAL.getAccesstime()); ps.execute(); } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(ps!=null) ps.close(); ad_conn.close(); } catch(Exception e){ e.printStackTrace(); } } } //--- INSERT (1) ------------------------------------------------------------------------------ public static void insert(String sUserID){ PreparedStatement ps = null; String sInsert = "INSERT INTO AccessLogs (accessid,userid,accesstime)"+ " VALUES (?,?,?)"; Connection ad_conn = MedwanQuery.getInstance().getAdminConnection(); try{ ps = ad_conn.prepareStatement(sInsert); ps.setInt(1,MedwanQuery.getInstance().getOpenclinicCounter("AccessLogs")); ps.setInt(2,Integer.parseInt(sUserID)); ps.setTimestamp(3,ScreenHelper.getSQLTime()); ps.executeUpdate(); } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(ps!=null) ps.close(); ad_conn.close(); } catch(Exception e){ e.printStackTrace(); } } } //--- INSERT (2) ------------------------------------------------------------------------------ public static void insert(String sUserID,String accessCode){ PreparedStatement ps = null; String sInsert = "INSERT INTO AccessLogs(accessid,userid,accesstime,accesscode)"+ " VALUES (?,?,?,?)"; Connection ad_conn = MedwanQuery.getInstance().getAdminConnection(); try{ ps = ad_conn.prepareStatement(sInsert); ps.setInt(1,MedwanQuery.getInstance().getOpenclinicCounter("AccessLogs")); ps.setInt(2,Integer.parseInt(sUserID)); ps.setTimestamp(3,ScreenHelper.getSQLTime()); ps.setString(4,accessCode); ps.executeUpdate(); } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(ps!=null) ps.close(); ad_conn.close(); } catch(Exception e){ e.printStackTrace(); } } } //--- INSERT (3) ------------------------------------------------------------------------------ public static void insert(String sUserID,String accessCode, java.util.Date accessTime){ PreparedStatement ps = null; String sInsert = "INSERT INTO AccessLogs(accessid,userid,accesstime,accesscode)"+ " VALUES (?,?,?,?)"; Connection ad_conn = MedwanQuery.getInstance().getAdminConnection(); try{ ps = ad_conn.prepareStatement(sInsert); ps.setInt(1,MedwanQuery.getInstance().getOpenclinicCounter("AccessLogs")); ps.setInt(2,Integer.parseInt(sUserID)); ps.setTimestamp(3,new java.sql.Timestamp(accessTime.getTime())); ps.setString(4,accessCode); ps.executeUpdate(); } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(ps!=null) ps.close(); ad_conn.close(); } catch(Exception e){ e.printStackTrace(); } } } //--- GET LAST ACCESS ------------------------------------------------------------------------- public static List getLastAccess(String patientId, int nb){ PreparedStatement ps = null; ResultSet rs = null; List l = new LinkedList(); String sSelect = "SELECT * FROM AccessLogs"+ " WHERE accesscode = ?"+ " ORDER BY accessid DESC"; Connection ad_conn = MedwanQuery.getInstance().getAdminConnection(); try{ ps = ad_conn.prepareStatement(sSelect); ps.setString(1,patientId); rs = ps.executeQuery(); int i = 0; while(rs.next()){ if(nb==0 || i<=nb){ Object sReturn[] = {rs.getTimestamp("accesstime"),rs.getString("userid")}; l.add(sReturn); } i++; } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); ad_conn.close(); } catch(Exception e){ e.printStackTrace(); } } return l; } public static java.util.Date getFirstAccess(String id){ java.util.Date d = null; PreparedStatement ps = null; ResultSet rs = null; String sSelect = "SELECT * FROM AccessLogs"+ " WHERE accesscode = ?"+ " ORDER BY accessid"; Connection ad_conn = MedwanQuery.getInstance().getAdminConnection(); try{ ps = ad_conn.prepareStatement(sSelect); ps.setString(1,id); rs = ps.executeQuery(); if(rs.next()){ d=rs.getDate("accesstime"); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); ad_conn.close(); } catch(Exception e){ e.printStackTrace(); } } return d; } public static void setFirstAccess(String id,java.util.Date d){ PreparedStatement ps = null; ResultSet rs = null; String sSelect = "SELECT * FROM AccessLogs WHERE accesscode = ? ORDER BY accessid"; Connection ad_conn = MedwanQuery.getInstance().getAdminConnection(); try{ ps = ad_conn.prepareStatement(sSelect); ps.setString(1,id); rs = ps.executeQuery(); if(rs.next()){ int i = rs.getInt("accessid"); rs.close(); ps.close(); ps=ad_conn.prepareStatement("update AccessLogs set accesstime=? where accessid=?"); ps.setTimestamp(1, new java.sql.Timestamp(d.getTime())); ps.setInt(2, i); ps.execute(); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); ad_conn.close(); } catch(Exception e){ e.printStackTrace(); } } } //--- GET ACCESS TIMES ------------------------------------------------------------------------ public static Vector getAccessTimes(java.sql.Date dBegin, java.sql.Date dEnd, int iUserId){ PreparedStatement ps = null; ResultSet rs = null; Vector vAccessTimes = new Vector(); String sSelect = "SELECT a.accesstime FROM AccessLogs a"+ " WHERE a.accesstime BETWEEN ? AND ?"+ " AND userid = ?"; Connection ad_conn = MedwanQuery.getInstance().getAdminConnection(); try{ ps = ad_conn.prepareStatement(sSelect); ps.setDate(1,dBegin); ps.setDate(2,dEnd); ps.setInt(3,iUserId); rs = ps.executeQuery(); while(rs.next()){ vAccessTimes.addElement(rs.getDate("accesstime")); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); ad_conn.close(); } catch(Exception e){ e.printStackTrace(); } } return vAccessTimes; } //--- DELETE (1) ------------------------------------------------------------------------------ public static void delete(String sAccessId){ PreparedStatement ps = null; Connection ad_conn = MedwanQuery.getInstance().getAdminConnection(); try{ String sQuery = "DELETE FROM AccessLogs WHERE accessid = ?"; ps = ad_conn.prepareStatement(sQuery); ps.setString(1,sAccessId); ps.executeUpdate(); } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(ps!=null) ps.close(); ad_conn.close(); } catch(Exception e){ e.printStackTrace(); } } } //--- DELETE (2) ------------------------------------------------------------------------------ public static void delete(java.util.Date delFromDate, java.util.Date delUntilDate){ PreparedStatement ps = null; ResultSet rs = null; // compose query to retreive accessIds in interval String sQuery = "SELECT accessid FROM AccessLogs l, UsersView u, AdminView a "; if(delFromDate!=null && delUntilDate!=null){ sQuery+= "WHERE l.accesstime BETWEEN ? AND ? "; } else if(delFromDate!=null){ sQuery+= "WHERE l.accesstime >= ? "; } else if(delUntilDate!=null){ sQuery+= "WHERE l.accesstime < ? "; } int questionMarkIdx = 1; sQuery+= "AND u.userid = l.userid "+ "AND a.personid = u.personid"; StringBuffer accessIds = new StringBuffer(); Connection ad_conn = MedwanQuery.getInstance().getAdminConnection(); try{ ps = ad_conn.prepareStatement(sQuery); if(delFromDate!=null) ps.setDate(questionMarkIdx++,new java.sql.Date(delFromDate.getTime())); if(delUntilDate!=null) ps.setDate(questionMarkIdx,new java.sql.Date(delUntilDate.getTime())); int id; rs = ps.executeQuery(); while(rs.next()){ id = rs.getInt("accessid"); if(id > 0){ accessIds.append("'").append(id).append("',"); } } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(ps!=null) ps.close(); if(rs!=null) rs.close(); } catch(Exception e){ e.printStackTrace(); } } //*** delete accesss specified by accessIds-string *** try{ if(accessIds.length() > 0){ // remove last comma if(accessIds.toString().indexOf(",") > 0){ accessIds = accessIds.deleteCharAt(accessIds.length()-1); } // delete records sQuery = "DELETE FROM AccessLogs WHERE accessid IN ("+accessIds+")"; ps = ad_conn.prepareStatement(sQuery); ps.executeUpdate(); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(ps!=null) ps.close(); ad_conn.close(); } catch(Exception e){ e.printStackTrace(); } } } }
package com.acewill.ordermachine.model; public class BaseModelSz { /** * 0:成功;其他值为错误码 */ public int result; public String errmsg; }
package com.aaa.house.service; import com.aaa.house.dao.HouseDao; import com.aaa.house.entity.House; import com.aaa.house.entity.Staff; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; import java.util.Map; /** * fileName:HouseServiceImpl * description: * author:guoxiaoxuan * createTime:2019/7/26 22:10 * versoin:1.0.0 */ @Service public class HouseServiceImpl implements HouseService{ @Autowired private HouseDao houseDao; @Override /** * 查询房屋信息 */ public List<House> queryHouseAll(Map map) { List<House> houses = houseDao.queryHouseAll(map); Map<String,Object> maps=new HashMap<>(); for (House hou : houses) { Integer houseId = hou.getHouseId(); if (houseId!=null){ List<String> lab = houseDao.selectLable(houseId); hou.setHouseLabel(lab); } } return houses; } @Override /** * 查询发布房屋数量 */ public Integer queryHousePageCount(Map map) { Integer i=houseDao.queryHousePageCount(map); System.out.println(i); return i; } @Override /** * 获取房屋布局 */ public List<Map> selectLayout() { return houseDao.selectLayout(); } @Override /** * 根据id获取房屋的信息 */ public Map<String,Object> housedetail(Map map) { House houses=houseDao.houseDetail(map); Map<String,Object> maps=new HashMap<>(); Integer hid=houses.getHouseId(); List<String> lab = houseDao.selectLable(hid); houses.setHouseLabel(lab); List<String> img = houseDao.selectImgs(hid); houses.setHouseImgs(img); String staff = houses.getHouseStaffid(); Staff sta=houseDao.selectStaff(staff); maps.put("obj",houses); maps.put("staff",sta); return maps; } @Override /** * 关注房源 */ public Integer insertAtteition (Map map){ return houseDao.insertAtteition(map); } @Override /** * 判断是否关注过房源 */ public List<Map> selectAtteition(Map map){ return houseDao.selectAtteition(map); } @Override /** * 预约看房 */ public Integer insertLookHouse (Map map){ return houseDao.insertLookHouse(map); } }
package com.example.elevatorrestservice.service.impl; import java.util.List; import javax.annotation.PostConstruct; import org.springframework.stereotype.Service; import com.example.elevatorrestservice.model.Elevator; import com.example.elevatorrestservice.model.ElevatorState; import com.example.elevatorrestservice.model.Floor; import com.example.elevatorrestservice.model.MultiElevatorScheduler; import com.example.elevatorrestservice.model.Passenger; import com.example.elevatorrestservice.service.ElevatorService; @Service public class ElevatorServiceImpl implements ElevatorService { private Elevator elevatorGroup[]; private Floor floors[]; private MultiElevatorScheduler elevatorScheduler; @PostConstruct public void init() { this.elevatorGroup = new Elevator[TOTAL_ELEVATORS]; this.floors = new Floor[TOTAL_FLOORS]; this.createFloors(); this.createElevators(); this.elevatorScheduler = new MultiElevatorScheduler(this.elevatorGroup, this.floors); new Thread(this.elevatorScheduler).start(); // Activates the GroupElevatorController to scan the floors array } /** * Creates Elevator objects in the elevatorGroup array. */ private void createElevators() { for (int i = 0; i < TOTAL_ELEVATORS; ++i) { this.elevatorGroup[i] = new Elevator(i); this.elevatorGroup[i].setCurrentFloor(1); // Start from 1 this.elevatorGroup[i].setDirection(Elevator.DIRECTION.UP); } // Create elevator threads for (int i = 0; i < TOTAL_ELEVATORS; ++i) { this.elevatorGroup[i].startRequestMonitor(); this.elevatorGroup[i].startElevatorWorker(); } } /** * Creates Floor objects in the floors array. */ private void createFloors() { for (int i = 0; i < TOTAL_FLOORS; ++i) { this.floors[i] = new Floor(i); } } /** * Randomly selects a floor from the floors array and * calls the generatePassenger method on the Floor(randFloor) object. */ private void generatePassenger(List<Passenger> passengers) throws InterruptedException { for (Passenger passenger : passengers) { System.out.println("passenger:" + passenger.getUser() + " start:" + passenger.getStartFloor() + " end:" + passenger.getEndFloor()); floors[passenger.getStartFloor() - 1].generatePassenger(passenger); } } @Override public List<ElevatorState> lowCostSchedule(List<Passenger> passengers) { try { this.generatePassenger(passengers); } catch (InterruptedException e) { e.printStackTrace(); } return this.elevatorScheduler.getElevatorStates(); } @Override public List<ElevatorState> reset() { return this.elevatorScheduler.reset(); } }
package com.unimelb.comp90015.Server; import com.unimelb.comp90015.Server.Dictionary.DictionaryFactory; import com.unimelb.comp90015.Server.Dictionary.IDictionary; import com.unimelb.comp90015.Server.GUI.ServerGUI; import com.unimelb.comp90015.Server.ThreadPool.HandleConnectionThread; import com.unimelb.comp90015.Server.ThreadPool.PriorityTaskThread; import com.unimelb.comp90015.Server.ThreadPool.ThreadPool; import com.unimelb.comp90015.Util.ClientSocket; import com.unimelb.comp90015.Util.InvalidMessageException; import com.unimelb.comp90015.Util.InvalidVIPPriorityException; import javax.net.ServerSocketFactory; import java.io.IOException; import java.net.ServerSocket; import java.util.Date; import java.util.concurrent.TimeUnit; import static com.unimelb.comp90015.Util.Constant.ERROR_INVALID_SERVER_ARGS_CODE; import static com.unimelb.comp90015.Util.Constant.ERROR_INVALID_SERVER_ARGS_CONTENT; import static com.unimelb.comp90015.Util.Util.*; import static com.unimelb.comp90015.Util.Util.serverPortError; /** * Xulin Yang, 904904 * * @create 2020-03-23 15:19 * description: the multi-threaded server with thread-pool architecture, thread * per connection with a period of inactive time **/ public class DictionaryServer { /** * the server's port number */ private static int serverPort; /** * dictionary file's path on disk */ private static String dictionaryFilePath; /** * thread pool's size */ private static int threadPoolSize; /** * client's connection's inactive waiting time; unit: second */ private static int inactiveWaitTime; /** * the limit of number of tasks to be queued in the thread pool */ private static int threadPoolQueueLimit; public static void main(String[] args) { // check inputs checkArgs(args); // create thread pool ThreadPool threadPool = new ThreadPool(threadPoolSize, threadPoolQueueLimit); System.out.println("Thread pool created."); // create dictionary from disk IDictionary dictionary = DictionaryFactory.getInstance() .createSimpleDictionary(dictionaryFilePath); System.out.println("Dictionary read."); // create server ServerSocketFactory factory = ServerSocketFactory.getDefault(); // create GUI ServerGUI serverGUI = new ServerGUI(threadPool, dictionary); System.out.println("GUI created"); try(ServerSocket server = factory.createServerSocket(serverPort)) { System.out.println("Server created."); while (true) { // accept client's connection and receive VIP number ClientSocket clientSocket = new ClientSocket(server.accept(), (int) TimeUnit.SECONDS.toMillis(inactiveWaitTime)); // queue in thread pool full, drop the task if (threadPool.isQueueFull()) { clientSocket.sendConnectionDropedResponse(); clientSocket.close(); } else { // create thread HandleConnectionThread connectionThread = new HandleConnectionThread(clientSocket, dictionary, threadPool); // add thread to thread pool PriorityTaskThread connectionPriorityTaskThread = new PriorityTaskThread(connectionThread, clientSocket.getVipPriority(), new Date()); threadPool.execute(connectionPriorityTaskThread); } } } catch (IOException e) { System.out.println("IOException."); } catch (InvalidMessageException e) { System.out.println(getError(e.getCode(), e.getMessage())); } catch (InvalidVIPPriorityException e) { System.out.println(getError(e.getCode(), e.getMessage())); } // close thread pool threadPool.shutdown(); } /** * check whether server's inputs are correct * @param args command line arguments */ private static void checkArgs(String[] args) { if (args.length < 5) { popupErrorDialog(ERROR_INVALID_SERVER_ARGS_CODE, ERROR_INVALID_SERVER_ARGS_CONTENT); } try { serverPort = Integer.parseInt(args[0]); if (checkWrongServerPort(serverPort)) { serverPortError(); } } catch (NumberFormatException e) { serverPortError(); } dictionaryFilePath = args[1]; try { threadPoolSize = Integer.parseInt(args[2]); if (checkWrongThreadPoolSize(threadPoolSize)) { threadPoolSizeError(); } } catch (NumberFormatException e) { threadPoolSizeError(); } try { inactiveWaitTime = Integer.parseInt(args[3]); if (checkWrongInactiveTime(inactiveWaitTime)) { inactiveTimeError(); } } catch (NumberFormatException e) { inactiveTimeError(); } try { threadPoolQueueLimit = Integer.parseInt(args[4]); if (checkWrongThreadPoolQueueLimit(threadPoolQueueLimit, threadPoolSize)) { threadPoolQueueLimitError(); } } catch (NumberFormatException e) { threadPoolQueueLimitError(); } } }
package com.capstone.videoeffect; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Toast; import com.gowtham.library.utils.LogMessage; import com.gowtham.library.utils.TrimVideo; import java.util.ArrayList; import java.util.List; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; public class VideoHomeActivity extends AppCompatActivity { private static final int REQUEST_TAKE_GALLERY_VIDEO = 100; private static final int REQUEST_VIDEO_RECORD = 101; LinearLayout uploadVideo, recordvideo, myvideo; ImageView ivback; public static final String FILEPATH = "filepath"; Intent intent = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video_home); uploadVideo = (LinearLayout) findViewById(R.id.uploadVideo); recordvideo = (LinearLayout) findViewById(R.id.recordvideo); myvideo = (LinearLayout) findViewById(R.id.myvideo); ivback = findViewById(R.id.ivback); ivback.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(VideoHomeActivity.this, HomeActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }); recordvideo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openVideoCapture(); } }); uploadVideo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Build.VERSION.SDK_INT >= 23) getPermission(); else uploadVideoget(); } }); myvideo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { intent = new Intent(VideoHomeActivity.this, MyVideosActivity.class); startActivity(intent); } }); } private void openVideoCapture() { try { Intent intent = new Intent("android.media.action.VIDEO_CAPTURE"); intent.putExtra("android.intent.extra.durationLimit", 30); startActivityForResult(intent, REQUEST_VIDEO_RECORD); } catch (Exception e) { e.printStackTrace(); } } private void getPermission() { String[] params = null; String writeExternalStorage = Manifest.permission.WRITE_EXTERNAL_STORAGE; String readExternalStorage = Manifest.permission.READ_EXTERNAL_STORAGE; int hasWriteExternalStoragePermission = ActivityCompat.checkSelfPermission(this, writeExternalStorage); int hasReadExternalStoragePermission = ActivityCompat.checkSelfPermission(this, readExternalStorage); List<String> permissions = new ArrayList<String>(); if (hasWriteExternalStoragePermission != PackageManager.PERMISSION_GRANTED) permissions.add(writeExternalStorage); if (hasReadExternalStoragePermission != PackageManager.PERMISSION_GRANTED) permissions.add(readExternalStorage); if (!permissions.isEmpty()) { params = permissions.toArray(new String[permissions.size()]); } if (params != null && params.length > 0) { ActivityCompat.requestPermissions(VideoHomeActivity.this, params, 100); } else uploadVideoget(); } private void uploadVideoget() { try { Intent intent = new Intent(); intent.setType("video/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Video"), REQUEST_TAKE_GALLERY_VIDEO); } catch (Exception e) { e.printStackTrace(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == REQUEST_TAKE_GALLERY_VIDEO) { if (data.getData() != null) { LogMessage.v("Video path:: " + data.getData()); openTrimActivity(String.valueOf(data.getData())); } else { Toast.makeText(this, "video uri is null", Toast.LENGTH_SHORT).show(); } } else if (requestCode == REQUEST_VIDEO_RECORD) { if (data.getData() != null) { LogMessage.v("Video path:: " + data.getData()); openTrimActivity(String.valueOf(data.getData())); } else { Toast.makeText(this, "video uri is null", Toast.LENGTH_SHORT).show(); } } // } else { // Toast.makeText(VideoHomeActivity.this, R.string.toast_cannot_retrieve_selected_video, Toast.LENGTH_SHORT).show(); // } } if (requestCode == TrimVideo.VIDEO_TRIMMER_REQ_CODE && data != null) { Uri uri = Uri.parse(TrimVideo.getTrimmedVideoPath(data)); Log.d("TAG", "Trimmed path:: " + uri); intent = new Intent(VideoHomeActivity.this, MainActivity.class); intent.putExtra(VideoHomeActivity.FILEPATH, String.valueOf(uri)); startActivity(intent); } } private void openTrimActivity(String data) { TrimVideo.activity(data) // .setCompressOption(new CompressOption()) //pass empty constructor for default compress option .setDestination("/storage/emulated/0/DCIM/VideoEffect") .start(this); } }
package com.muyh.zouzou.service.impl; import com.muyh.zouzou.dao.VerificationcodeMapper; import com.muyh.zouzou.model.Verificationcode; import com.muyh.zouzou.service.iface.VerificationcodeService; import com.muyh.zouzou.utils.ResultUtil; import com.muyh.zouzou.utils.TokenUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Map; @Service public class VerificationcodeServiceImpl implements VerificationcodeService { @Autowired VerificationcodeMapper verificationcodeMapper; @Override public Object[] createToken(String userId) { return new Object[0]; } @Override public Object[] checkToken(String token) { Map<String, Object> tokenMap = TokenUtil.parserJavaWebToken(token); if (null == tokenMap){ return ResultUtil.put(false,"解析失败",null); } Verificationcode code = verificationcodeMapper.selectByUID((String) tokenMap.get("uid")); if (null == code){ return ResultUtil.put(false,"不存在该用户",null); } if (!token.equals(code.getToken())){ return ResultUtil.put(false,"验证失败,请重新登陆!",null); } return ResultUtil.put(true,"验证成功", null); } @Override public Object[] getToken(String userId) { return new Object[0]; } @Override public Object[] deleteToken(String userId) { return new Object[0]; } }
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations; import org.giddap.dreamfactory.leetcode.onlinejudge.SearchForARange; public class SearchForARangeImpl implements SearchForARange { @Override public int[] searchRange(int[] A, int target) { int[] ret = new int[]{-1, -1}; // find lower bound int l = -1; int r = A.length; while (r - l > 1) { int m = l + (r - l) / 2; if (A[m] < target) { l = m; } else { r = m; } } if (r < A.length && A[r] == target) { ret[0] = r; } // find upper bound l = -1; r = A.length; while (r - l > 1) { int m = l + (r - l) / 2; if (A[m] > target) { r = m; } else { l = m; } } if (l > -1 && A[l] == target) { ret[1] = l; } return ret; } }
package oops; public class Toyota extends Car1 { void speed(int a) { System.out.println("Speed=>"+a); } }
package com.oxymore.practice.controller; import com.mongodb.MongoConfigurationException; import com.mongodb.client.*; import com.mongodb.client.model.*; import com.oxymore.practice.LocaleController; import com.oxymore.practice.Practice; import com.oxymore.practice.documents.EloDocument; import com.oxymore.practice.documents.KitDocument; import com.oxymore.practice.documents.PlayerDocument; import lombok.Getter; import lombok.RequiredArgsConstructor; import org.bson.BsonDocument; import org.bson.BsonString; import org.bson.Document; import org.bson.codecs.configuration.CodecRegistries; import org.bson.codecs.configuration.CodecRegistry; import org.bson.codecs.pojo.PojoCodecProvider; import org.bson.conversions.Bson; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; @Getter public final class DatabaseController { private final Practice plugin; private final MongoClient mongoClient; private final Database database; private final Map<UUID, PlayerDocument> playerCache; private final Map<UUID, Integer> eloCache; public DatabaseController(Practice plugin) throws ControllerInitException { this.plugin = plugin; Logger.getLogger("org.mongodb.driver").setLevel(Level.SEVERE); Logger.getLogger("org.bson").setLevel(Level.SEVERE); try { this.mongoClient = MongoClients.create(plugin.getConfiguration().mongoDBConnectionUrl); } catch (MongoConfigurationException e) { throw new ControllerInitException("database", "Unable to connect to MongoDB. Check your connection url."); } final CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(com.mongodb.MongoClient.getDefaultCodecRegistry(), CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build())); final MongoDatabase mongo = mongoClient.getDatabase("practice") .withCodecRegistry(pojoCodecRegistry); final MongoCollection<KitDocument> kits = mongo.getCollection("kits", KitDocument.class); final MongoCollection<PlayerDocument> players = mongo.getCollection("players", PlayerDocument.class); final MongoCollection<EloDocument> elo = mongo.getCollection("elo", EloDocument.class); this.database = new Database(plugin, mongo, kits, players, elo); this.playerCache = new ConcurrentHashMap<>(); this.eloCache = new ConcurrentHashMap<>(); } public void queryCacheUpdate(OfflinePlayer player, boolean moveAsync) { final AsyncExecutor op = db -> { final Bson query = Filters.eq("playerId", player.getUniqueId()); final PlayerDocument playerDocument = db.players.find(query).first(); final int elo = db.getAverageElo(query); playerCache.put(player.getUniqueId(), playerDocument); eloCache.put(player.getUniqueId(), elo); }; if (moveAsync) { async(op); } else { op.execute(database); } } public void removeFromCache(Player player) { playerCache.remove(player.getUniqueId()); eloCache.remove(player.getUniqueId()); } @RequiredArgsConstructor public static class Database { private final Practice plugin; public final MongoDatabase mongo; public final MongoCollection<KitDocument> kits; public final MongoCollection<PlayerDocument> players; public final MongoCollection<EloDocument> elo; public void sync(Runnable runnable) { plugin.getServer().getScheduler().runTask(plugin, runnable); } public void syncIfOnline(OfflinePlayer target, Runnable runnable) { if (target == null) { return; } sync(() -> { if (target.isOnline()) { runnable.run(); } }); } public int getAverageElo(Bson query) { final Document eloDoc = mongo.getCollection("elo").aggregate(Arrays.asList( Aggregates.match(query), Aggregates.group("_id", new BsonField("averageElo", new BsonDocument("$avg", new BsonString("$elo")))) )).first(); int elo = eloDoc != null ? eloDoc.getDouble("averageElo").intValue() : 0; if (elo == 0) { elo = 1000; } return elo; } public Collection<LocaleController.ExpansionElement> fetchTop(Bson filter) { if (filter == null) { filter = new Document(); } final Collection<LocaleController.ExpansionElement> entries = new ArrayList<>(); final AggregateIterable<Document> aggregate = mongo.getCollection("elo").aggregate(Arrays.asList( Aggregates.match(filter), Aggregates.group("$playerId", Accumulators.avg("averageElo", "$elo")), Aggregates.sort(Sorts.descending("averageElo")), Aggregates.limit(10) )); int j = 0; for (Document eloDocument : aggregate) { final int rank = ++j; final String playerName = Bukkit.getOfflinePlayer((UUID) eloDocument.get("_id")).getName(); final int elo = eloDocument.getDouble("averageElo").intValue(); entries.add(e -> e .var("rank", String.valueOf(rank)) .var("player", playerName) .var("elo", String.valueOf(elo))); } return entries; } public void saveKit(KitDocument kitDocument) { final Bson filter = kitDocument.getFilter(); if (kits.find(filter).first() != null) { kits.updateOne(filter, Updates.combine( Updates.set("name", kitDocument.getName()), Updates.set("kit", kitDocument.getKit()) )); } else { kits.insertOne(kitDocument); } } public void deleteKit(KitDocument kitDocument) { kits.deleteOne(kitDocument.getFilter()); } } public void async(AsyncExecutor asyncExecutor) { if (asyncExecutor == null) { return; } plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> asyncExecutor.execute(database)); } public interface AsyncExecutor { void execute(Database database); } }
package com.eussi._01_jca_jce.certpkg; import java.io.FileInputStream; import java.security.KeyStore; import java.security.Signature; import java.security.cert.X509Certificate; /** * demo 待完善 * Created by wangxueming on 2019/4/1. */ public class _03_X509Certificate { public static void main(String[] args) { try { //加载秘钥库文件 FileInputStream fileInputStream = new FileInputStream(""); //实例化KeyStore KeyStore keyStore = KeyStore.getInstance("JKS"); //加载秘钥库 keyStore.load(fileInputStream, "passwd".toCharArray()); //关闭输入流 fileInputStream.close(); //获得X509证书 X509Certificate x509Certificate = (X509Certificate) keyStore.getCertificate("alias"); //通过证书标明的签名算法构建Signtrue Signature signature = Signature.getInstance(x509Certificate.getSigAlgName()); } catch (Exception e) { e.printStackTrace(); } } }
package no.uninett.adc.neo.domain; public class RelationshipType { public static final String INCLUDES_CHANGE = "INCLUDES_CHANGE"; public static final String CHANGESET_FOR_OBJECT = "CHANGESET_FOR_OBJECT"; public static final String HAS_STATE = "HAS_STATE"; public static final String IS_ENTITLET = "IS_ENTITLET"; public static final String HAS_ATTRIBUTE = "HAS_ATTRIBUTE"; public static final String HAS_KEY = "HAS_KEY"; public static final String SYSTEM_FOR_ENTITLEMENT = "SYSTEM_FOR_ENTITLEMENT"; public static final String SYSTEM_FOR_ORG = "SYSTEM_FOR_ORG"; public static final String SYSTEM_URN = "SYSTEM_URN"; public static final String WORKS_FOR_ORG = "WORKS_FOR_ORG"; }
package logic; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * This scheduling algorithm is a greedy algorithm that will greedily produce * schedules. Due to the nature of this algorithm it can produce schedules that * don't have all classes, but it will still return them. */ public class GreedyQuickScheduleMaker { /** * Stores all course object that the wants */ private static ArrayList<Course> currentCourse = new ArrayList<>(); /** * Since the class is static for all intents and purposes there is no need to * allow instantiation */ private GreedyQuickScheduleMaker() { throw new UnsupportedOperationException("This is a static class and cannot be instantiated!"); } /** * This method will retrieve the course from the given name and semester and add * it to the global ArrayList * * @param courseName - The name of the course to be searched for * @param semesterID - Semester to search in */ public static void findCC(String courseName, String semesterID) { try { currentCourse.addAll(Scraper.getAllClasses(semesterID).get(courseName)); } catch (IOException e) { Globals.popupException().writeError(e); } } /** * Returns a list of lists of courses that are valid possible schedules * * @param desiredCourses The courses that the user desires * @param semesterID The semester ID to make a schedule of * @return Returns all possible sets of schedules */ public static ArrayList<ArrayList<Course>> build(List<String> desiredCourses, String semesterID) { currentCourse.clear(); ArrayList<Course> firstCourseList = new ArrayList<>(); ArrayList<Course> secondCourseList = new ArrayList<>(); ArrayList<ArrayList<Course>> out = new ArrayList<>(); ArrayList<Course> copyList = new ArrayList<>(); // Create the arraylist of selected courses for (int j = 0; j < desiredCourses.size(); j++) { findCC(desiredCourses.get(j), Scraper.getAllSemesters().get(semesterID)); } Collections.sort(currentCourse); for (int i = 0; i < currentCourse.size(); i++) { copyList.add(currentCourse.get(i)); } int numberOfCourses = 0; for (int i = 0; i < currentCourse.size(); i++) { if (i + 1 < currentCourse.size()) { if (!(currentCourse.get(i).toString().equals(currentCourse.get(i + 1).toString()))) { // If the next course doesn't equal the current course numberOfCourses++; } } else { numberOfCourses++; } } // This array will store the number of course repeats in order of sorted appearance // i.e. Systems has two offerings int[] arr = new int[numberOfCourses]; int ind = 0; for (int i = 0; i < numberOfCourses; i++) { arr[i] = 1; // At least one // Check for repeats and increase count accordingly if (ind + 1 < currentCourse.size() && ind < currentCourse.size()) { while (currentCourse.get(ind).toString().equals(currentCourse.get(ind + 1).toString())) { arr[i]++; ind++; if (ind + 1 >= currentCourse.size()) { break; } } } ind++; } int courseIndex = 0; // Build schedule // Go through the number of courses to have for (int i = 0; i < numberOfCourses; i++) { // Go through the multiple times of that class for (int j = 0; j < arr[i]; j++) { // Skip if the class is already in the schedule boolean skip = false; boolean skipConflict = false; for (int k = 0; k < firstCourseList.size(); k++) { if (firstCourseList.get(k).toString().equals(currentCourse.get(courseIndex).toString())) { // Class exists skip skip = true; } } if (skip) { break; } // Add the first class if (i == 0) { firstCourseList.add(currentCourse.get(courseIndex)); courseIndex++; } else if (arr[i] == 1) { for (int k = 0; k < firstCourseList.size(); k++) { if (firstCourseList.get(k).conflicts(currentCourse.get(courseIndex))) { skipConflict = true; } } if (skipConflict) { courseIndex++; continue; } firstCourseList.add(currentCourse.get(courseIndex)); courseIndex++; } else { // Add other classes for (int k = 0; k < firstCourseList.size(); k++) { if (firstCourseList.get(k).conflicts(currentCourse.get(courseIndex))) { skipConflict = true; } } if (skipConflict) { courseIndex++; continue; } try { if (!firstCourseList.get(i - 1).conflicts(currentCourse.get(courseIndex))) { firstCourseList.add(currentCourse.get(courseIndex)); courseIndex += arr[i]; break; } } catch (IndexOutOfBoundsException e) { // If we go out of bounds we skip this course numberOfCourses--; } } } } out.add(firstCourseList); courseIndex = 0; // Make a second schedule if there are enough courses if (numberOfCourses < currentCourse.size()) { // Multiple courses, go through each course. Single courses first for (int i = 0; i < numberOfCourses; i++) { // Go through the multiple times of that course started from the latest courses for (int j = (arr[i] - 1); j >= 0; j--) { // Skip if the class is already in the schedule boolean skip = false; boolean skipConflict = false; for (int k = 0; k < secondCourseList.size(); k++) { if (secondCourseList.get(k).toString().equals(currentCourse.get(courseIndex).toString())) { // Class exists skip skip = true; } } if (skip) { break; } // Add the first class if (i == 0) { secondCourseList.add(currentCourse.get(courseIndex)); courseIndex++; } else if (arr[i] == 1) { for (int k = 0; k < secondCourseList.size(); k++) { if (secondCourseList.get(k).conflicts(currentCourse.get(courseIndex))) { skipConflict = true; } } if (skipConflict) { courseIndex++; continue; } secondCourseList.add(currentCourse.get(courseIndex)); courseIndex++; } else { // Add other classes for (int k = 0; k < secondCourseList.size(); k++) { if (secondCourseList.get(k).conflicts(currentCourse.get(courseIndex + j))) { skipConflict = true; } } if (skipConflict) { if (j == 0) { courseIndex += arr[i]; } continue; } if (!secondCourseList.get(i - 1).conflicts(currentCourse.get(courseIndex + j))) { secondCourseList.add(currentCourse.get(courseIndex + j)); courseIndex += arr[i]; break; } } } } out.add(secondCourseList); } return out; } }
package be.mxs.common.util.pdf.official.chuk.examinations; import be.mxs.common.util.pdf.official.PDFOfficialBasic; import be.mxs.common.util.system.ScreenHelper; import com.itextpdf.text.Font; import com.itextpdf.text.FontFactory; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import net.admin.AdminPrivateContact; import java.text.SimpleDateFormat; public class chukPDFOfficialPhysioReport extends PDFOfficialBasic { // declarations private int pageWidth = 100; //--- ADD HEADER ------------------------------------------------------------------------------ protected void addHeader(){ try{ //*** HEADER ****************************************************** PdfPTable headerTable = new PdfPTable(5); headerTable.setWidthPercentage(pageWidth); // address PdfPTable addressTable = new PdfPTable(1); addressTable.addCell(createTitle("ADEPR",Font.BOLD,12,1)); addressTable.addCell(createTitle("NYAMATA HOSPITAL",Font.NORMAL,10,1)); addressTable.addCell(createTitle("POBOX. 7112",Font.NORMAL,10,1)); addressTable.addCell(createTitle("TEL: 561101",Font.NORMAL,10,1)); cell = createTitle("PHYSIOTHERAPY DPT",Font.UNDERLINE,10,1); cell.setNoWrap(true); addressTable.addCell(cell); headerTable.addCell(createCell(new PdfPCell(addressTable),1,PdfPCell.ALIGN_LEFT,PdfPCell.NO_BORDER)); // date SimpleDateFormat stdDateFormat = ScreenHelper.stdDateFormat; cell = createValueCell(getTran("web","date")+": "+stdDateFormat.format(new java.util.Date()),Font.NORMAL,9,4,false); cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); cell.setVerticalAlignment(PdfPCell.ALIGN_TOP); headerTable.addCell(cell); // add headertable to document doc.add(headerTable); //*** TITLE ****************************************************** PdfPTable titleTable = new PdfPTable(1); titleTable.setWidthPercentage(pageWidth); // title cell = createTitle(getTran("physioreportpdftitle"),Font.UNDERLINE,13,1); cell.setPaddingTop(30); cell.setPaddingBottom(30); titleTable.addCell(cell); // add headertable to document doc.add(titleTable); //*** PATIENT DATA ************************************************ // get required data AdminPrivateContact apc = ScreenHelper.getActivePrivate(patient); String patientAddress = ""; if(apc!=null){ patientAddress = apc.address+", "+apc.zipcode+" "+apc.city; } // put patient-data in tables.. PdfPTable patientTable = new PdfPTable(6); patientTable.setWidthPercentage(pageWidth); // row 1 : name and nationality patientTable.addCell(subTitleCell(getTran("web","identity"),6)); String patientFullName = patient.lastname+" "+patient.firstname; patientTable.addCell(createValueCell(getTran("web","name")+": ",Font.NORMAL,9,1,false)); patientTable.addCell(createValueCell(patientFullName,Font.BOLD,9,2,false)); patientTable.addCell(createValueCell(getTran("web.admin","nationality")+": ",Font.NORMAL,9,1,false)); patientTable.addCell(createValueCell(patient.getID("nationality"),Font.NORMAL,9,2,false)); // row 2 : age & gender and residence patientTable.addCell(createValueCell(getTran("web","dateofbirth")+" & "+getTran("web","gender")+": ",Font.NORMAL,9,1,false)); patientTable.addCell(createValueCell(patient.dateOfBirth+", "+patient.gender,Font.NORMAL,9,2,false)); patientTable.addCell(createValueCell(getTran("web","residence")+": ",Font.NORMAL,9,1,false)); patientTable.addCell(createValueCell(patientAddress,Font.NORMAL,9,2,false)); // row 3 : others patientTable.addCell(createValueCell(getTran("web","other")+": ",Font.NORMAL,9,6,false)); // spacer below page-header patientTable.addCell(createBorderlessCell("",10,6)); // add headertable to document doc.add(patientTable); } catch(Exception e){ e.printStackTrace(); } } //--- ADD CONTENT ----------------------------------------------------------------------------- protected void addContent(){ try{ //*** CONTENT ***************************************************** table = new PdfPTable(1); table.setWidthPercentage(pageWidth); // REPORT itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_REP_REPORT"); table.addCell(subTitleCell(getTran(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_REP_REPORT"),1)); cell = textCell(itemValue,1); cell.setFixedHeight(220); cell.setVerticalAlignment(PdfPCell.ALIGN_TOP); table.addCell(cell); // spacer table.addCell(emptyCell(10,1)); // CONCLUSION itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_REP_CONCLUSION"); table.addCell(subTitleCell(getTran(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_REP_CONCLUSION"),1)); cell = textCell(itemValue,1); cell.setFixedHeight(220); cell.setVerticalAlignment(PdfPCell.ALIGN_TOP); table.addCell(cell); doc.add(table); //*** FOOTER ****************************************************** String sUnit = "", sUnitAddress = ""; table = new PdfPTable(3); table.setWidthPercentage(pageWidth); table.addCell(emptyCell(2)); table.addCell(createValueCell(sUnit,Font.NORMAL,10,1,false)); table.addCell(emptyCell(2)); table.addCell(createValueCell(sUnitAddress,Font.NORMAL,10,1,false)); doc.add(table); } catch(Exception e){ e.printStackTrace(); } } //************************************* PRIVATE METHODS *************************************** //--- SUBTITLE CELL --------------------------------------------------------------------------- private PdfPCell subTitleCell(String title, int colspan){ cell = new PdfPCell(new Paragraph(title,FontFactory.getFont(FontFactory.HELVETICA,10,Font.UNDERLINE))); cell.setColspan(colspan); cell.setBorder(PdfPCell.NO_BORDER); cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); return cell; } //--- TEXT CELL ------------------------------------------------------------------------------- private PdfPCell textCell(String text, int colspan){ cell = new PdfPCell(new Paragraph(text,FontFactory.getFont(FontFactory.HELVETICA,9,Font.NORMAL))); cell.setColspan(colspan); cell.setBorder(PdfPCell.NO_BORDER); cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); return cell; } }
//package com.varunmutalik; //import java.util.Locale; import java.util.Scanner; public class Calculator { public static void main(String[] args) { float num1, num2; System.out.println("Enter first number"); Scanner scan= new Scanner(System.in); num1= scan.nextFloat(); System.out.println("Enter second number"); Scanner scan1 = new Scanner(System.in); num2= scan.nextFloat(); System.out.print("You have entered "); System.out.print(num1); System.out.print(" and "); System.out.println(num2); String prompt = "Enter 0 for addition, 1 for Subtraction, 2 for multiplication, 3 for division "; System.out.println(prompt); int input = scan.nextInt(); switch (input){ case 0: System.out.println("Adding these numbers"); System.out.println("The result is: "); System.out.println(num1+num2); break; case 1: System.out.println("Subtracting these numbers"); System.out.println("The result is: "); System.out.println(num1-num2); break; case 2: System.out.println("Multiplying these numbers"); System.out.println("The result is: "); System.out.println(num1*num2); break; case 3: System.out.println("Dividing these numbers"); System.out.println("The result is: "); System.out.println(num1/num2); break; default: System.out.println("Invalid input"); } } }
package com.company; import java.util.List; public class SelectionSort { int select; int access; public void go(List<Integer> arr, int time) { try { for (int i = 0; i < arr.size() - 1; i++) { int index = i; for (int j = i + 1; j < arr.size(); j++) { if (arr.get(j) < arr.get(index)) { //searching for lowest index this.access++; index = j; } } int smallerNumber = arr.get(index); this.access++; arr.set(index, arr.get(i)); this.select++; arr.set(i, smallerNumber); this.select++; System.out.println(arr); Thread.sleep(time); } } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("It took " + this.select + " swaps to sort this array. The array was accessed " + this.access + " times."); } }
package com.trump.auction.pals.api.impl; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.dubbo.config.annotation.Service; import com.trump.auction.pals.api.AlipayStubService; import com.trump.auction.pals.api.model.alipay.AliPayQueryResponse; import com.trump.auction.pals.api.model.alipay.AlipayBackRequest; import com.trump.auction.pals.api.model.alipay.AlipayBackResponse; import com.trump.auction.pals.api.model.alipay.AlipayPayRequest; import com.trump.auction.pals.api.model.alipay.AlipayPayResponse; import com.trump.auction.pals.api.model.alipay.AlipayQueryRequest; import com.trump.auction.pals.service.AlipayService; @Service(version = "1.0.0") public class AlipayStubServiceImpl implements AlipayStubService { @Autowired private AlipayService alipayService; @Override public AlipayPayResponse toAlipayPay(AlipayPayRequest apr) { return alipayService.toAlipayPay(apr); } @Override public AlipayBackResponse toAlipayBack(AlipayBackRequest abr) { return alipayService.toAlipayBack(abr); } @Override public AliPayQueryResponse toAlipayQuery(AlipayQueryRequest aqr){ return alipayService.toAlipayQuery(aqr); } @Override public String queryBatchNoByOrderNo(String orderNo) { return alipayService.queryBatchNoByOrderNo(orderNo); } }
package ru.job4j.cinema; import org.junit.Test; import java.util.Arrays; import java.util.Calendar; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; public class CinemaTest { @Test public void add() { Cinema cinema = new Cinema3D(); Session session3D = new Session3D(); cinema.add(session3D); List<Session> sessions = cinema.find(session -> true); assertThat(sessions, is(Arrays.asList(session3D))); } @Test(expected = TicketException.class) public void notBuy() { Account account = new AccountCinema(); Cinema cinema = new Cinema3D(); Calendar date = Calendar.getInstance(); date.set(2020, 10, 10, 23, 00); Ticket ticket = cinema.buy(account, 1, 1, date); } @Test public void buy() { Account account = new AccountCinema(); Cinema cinema = new Cinema3D(); Calendar date = Calendar.getInstance(); date.set(2020, 10, 10, 23, 00); Ticket ticket = cinema.buy(account, 1, 1, date); assertThat(ticket, is(new Ticket3D())); } @Test public void find() { Cinema cinema = new Cinema3D(); cinema.add(new Session3D()); List<Session> sessions = cinema.find(session -> true); assertThat(sessions, is(Arrays.asList(new Session3D()))); } @Test(expected = SessionException.class) public void notFind() { Cinema cinema = new Cinema3D(); List<Session> sessions = cinema.find(session -> true); } }
package Interview; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.junit.Test; public class FailFast_FailSafe { @Test public void failFast(){ Map<String,String> provinceCode=new HashMap<String,String>(); provinceCode.put("FJ", "fujian"); provinceCode.put("SH", "shanghai"); provinceCode.put("HN", "henan") ; Iterator it=provinceCode.keySet().iterator(); while(it.hasNext()){ System.out.println(provinceCode.get(it.next())); provinceCode.put("XJ","xinjiang"); } } @Test public void faitFast2(){ ArrayList<Integer> aList=new ArrayList<>(); aList.add(1); aList.add(2); aList.add(3); aList.add(4); aList.add(5); Iterator<Integer> it=aList.iterator(); // while(it.hasNext()){ // System.out.println(it.next()); // if(it.next()==2) // { // it.remove();} // } System.out.println(aList); it=aList.iterator(); try { while(it.hasNext()){ if(it.next()==3){ aList.remove(3); } } } catch (Exception e) { System.out.println(e.getCause().getMessage()); System.out.println(e.getLocalizedMessage()); assertEquals(true,e.getMessage().contains("Concurrent"), "exception"); } } }
/** * Copyright 2016 JustWayward Team * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.szhrnet.taoqiapp.mvp.api.response; import com.szhrnet.taoqiapp.config.URLConfig; import com.szhrnet.taoqiapp.mvp.api.factory.BookApiService; import com.szhrnet.taoqiapp.mvp.api.support.HeaderInterceptor; import com.szhrnet.taoqiapp.mvp.api.support.Logger; import com.szhrnet.taoqiapp.mvp.api.support.LoggingInterceptor; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * <pre> * author: MakeCodeFly * desc : ProfitApi类 * email:15695947865@139.com * </pre> */ public class ProfitApi { public static ProfitApi instance; private Retrofit retrofit; private OkHttpClient client; public static ProfitApi getInstance() { synchronized (ProfitApi.class) { if (instance == null) { instance = new ProfitApi(); } return instance; } } private static OkHttpClient getClient() { if (instance.client != null) return instance.client; LoggingInterceptor logging = new LoggingInterceptor(new Logger()); logging.setLevel(LoggingInterceptor.Level.BODY); instance.client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS) .connectTimeout(20 * 1000, TimeUnit.MILLISECONDS) .readTimeout(20 * 1000, TimeUnit.MILLISECONDS) .retryOnConnectionFailure(true) // 失败重发 .addInterceptor(new HeaderInterceptor()) .addInterceptor(logging) .build(); return instance.client; } // 构建一个Retrofit private static Retrofit getRetrofit() { if (instance.retrofit != null) return instance.retrofit; OkHttpClient client = getClient(); instance.retrofit = new Retrofit.Builder() .baseUrl(URLConfig.URL_BASE) .addConverterFactory(GsonConverterFactory.create()) // 添加Gson转换器 .client(client) .build(); return instance.retrofit; } /** * 返回一个请求代理 * * @return RemoteBookApiService */ public static BookApiService remoteBookApiService() { return getInstance().getRetrofit().create(BookApiService.class); } /** * 进行错误Code的解析, * 把网络返回的Code值进行统一的规划并返回为一个String资源 * @param model RspModel * @param callback DataSource.FailedCallback 用于返回一个错误的资源Id */ public static void decodeRspCode(RspModel model, DataSource.FailedCallback callback) { if (model == null) return; switch (model.getCode()){ // case 101: break; default: break; } } }
package br.com.wmomodas; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AutorizadorInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object controller) throws Exception { String uri = request.getRequestURI(); if( uri.endsWith("loginForm") || uri.endsWith("efetuaLogin") || uri.contains("resources")) { return true; } if(request.getSession() .getAttribute("usuarioLogado") != null) { return true; } response.sendRedirect("loginForm"); return false; } }
package edu.cricket.api.cricketscores.rest.source.model; public class Ref { private String $ref; public String get$ref() { return $ref; } public void set$ref(String $ref) { this.$ref = $ref; } @Override public String toString() { return "Ref{" + "$ref='" + $ref + '\'' + '}'; } }
package com.junzhao.shanfen.activity; import android.content.Intent; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import com.junzhao.base.base.APPCache; import com.junzhao.base.base.BaseAct; import com.junzhao.base.http.IHttpResultError; import com.junzhao.base.http.IHttpResultSuccess; import com.junzhao.base.http.MLHttpError; import com.junzhao.base.http.MLHttpRequestMessage; import com.junzhao.base.http.MLHttpType; import com.junzhao.base.http.MLRequestParams; import com.junzhao.base.utils.MLStrUtil; import com.junzhao.shanfen.R; import com.junzhao.shanfen.model.LZCompanyData; import com.junzhao.shanfen.model.LoginIpData; import com.junzhao.shanfen.model.PHUserData; import com.junzhao.shanfen.service.CommService; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import com.lidroid.xutils.view.annotation.event.OnClick; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Administrator on 2018/3/26. */ public class LZWanshanAty extends BaseAct implements Handler.Callback { public List<LZCompanyData> lzCompanyData; MyCountDownTimer downTimer = null; boolean isTimerFinished = true; Handler mHandler; @ViewInject(R.id.tv_com_zong) public TextView tv_com_zong; @ViewInject(R.id.tv_com_fen) public TextView tv_com_fen; @ViewInject(R.id.tv_getcode) public TextView tv_getcode; @ViewInject(R.id.regist_phone) public EditText regist_phone; @ViewInject(R.id.regist_code) public EditText regist_code; @ViewInject(R.id.regist_usename) public EditText regist_usename; @ViewInject(R.id.regist_password) public EditText regist_password; @ViewInject(R.id.ln_gongsi) public LinearLayout ln_gongsi; @ViewInject(R.id.regist_idcard) public EditText regist_idcard; private String branchCompanyId = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.aty_wanshan); ViewUtils.inject(this); mHandler = new Handler(LZWanshanAty.this); downTimer = new MyCountDownTimer(); tv_getcode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (v == tv_getcode) { if (MLStrUtil.isFastClick()) { return; } if (MLStrUtil.isEmpty(regist_phone.getText().toString().trim())) { showMessage(LZWanshanAty.this, "手机号码不能为空"); return; } if (isTimerFinished) { downTimer.start(); sendcode(); isTimerFinished = false; } } } }); getCompanyData(); } boolean isbangding = false; @OnClick(R.id.regist_sub) public void registClick(View view) { if (MLStrUtil.isEmpty(regist_phone.getText().toString().trim())) { showMessage(LZWanshanAty.this, "手机号码不能为空"); return; } if (MLStrUtil.isEmpty(regist_code.getText().toString().trim())) { showMessage(LZWanshanAty.this, "验证码不能为空"); return; } if (!isbangding) { if (MLStrUtil.isEmpty(regist_usename.getText().toString().trim())) { showMessage(LZWanshanAty.this, "姓名不能为空"); return; } if (MLStrUtil.isEmpty(regist_idcard.getText().toString().trim())) { showMessage(LZWanshanAty.this, "身份证不能为空"); return; } if (!MLStrUtil.IDCardValidate(regist_idcard.getText().toString())) { showMessage(LZWanshanAty.this, "身份证号码不正确"); return; } if (TextUtils.isEmpty(companyID)) { showMessage(LZWanshanAty.this, "选择公司"); return; } if (TextUtils.isEmpty(regist_password.getText().toString())) { showMessage(LZWanshanAty.this, "请输入密码"); return; } } registerIp(); } //6.微信、QQ、微博注册(tang) private void register() { Map<String, String> map = new HashMap(); MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("openId", APPCache.getOpenid()); mlHttpParam.put("type", "1"); mlHttpParam.put("userName", regist_usename.getText().toString()); mlHttpParam.put("idNumber", regist_idcard.getText().toString()); mlHttpParam.put("tel", regist_phone.getText().toString().trim()); mlHttpParam.put("branchCompanyId", branchCompanyId); mlHttpParam.put("photoPath", APPCache.getWeiPhoto()); mlHttpParam.put("address", "君兆"); mlHttpParam.put("mobileBrand", "oneplus"); mlHttpParam.put("loginGid", MLStrUtil.getMyUUID()); mlHttpParam.put("password", regist_password.getText().toString()); mlHttpParam.put("vCode", regist_code.getText().toString().trim()); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.REGISTERBYOTHER, mlHttpParam, PHUserData.class, CommService.getInstance(), true); loadData(LZWanshanAty.this, message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { PHUserData lzRegistData = (PHUserData) obj; APPCache.setUseData(lzRegistData); APPCache.setToken(lzRegistData.token); APPCache.setYouKe(false); showMessage(LZWanshanAty.this, "绑定成功"); startAct(LZWanshanAty.this, MainActivity.class); finish(); } } // , new IHttpResultError() { // @Override // public void error(MLHttpType.RequestType type, Object obj) { // // } // } ); } //短信验证码 private void sendcode() { Map<String, String> map = new HashMap(); MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("tel", regist_phone.getText().toString().trim()); mlHttpParam.put("flag", "4"); mlHttpParam.put("thirdPartyType", "1"); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.CREATEVCODEFOUR, mlHttpParam, String.class, CommService.getInstance(), true); loadData(LZWanshanAty.this, message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { String message = (String) obj; showMessage(LZWanshanAty.this, message); isbangding = true; } } , new IHttpResultError() { @Override public void error(MLHttpType.RequestType type, Object obj) { MLHttpError message = (MLHttpError) obj; if (MLStrUtil.compare(message.errorCode, "103")) { ln_gongsi.setVisibility(View.VISIBLE); isbangding = false; } } } ); } //会员注册 private void registerIp() { Map<String, String> map = new HashMap(); MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("openId", APPCache.getOpenid()); mlHttpParam.put("companyId", companyID); mlHttpParam.put("loginType", "1"); mlHttpParam.put("tel", regist_phone.getText().toString().trim()); mlHttpParam.put("vCode", regist_code.getText().toString().trim()); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.ANOTHERREGIST, mlHttpParam, LoginIpData.class, CommService.getInstance(), true); loadData(LZWanshanAty.this, message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { LoginIpData companyIp = (LoginIpData) obj; APPCache.setIPAddress(companyIp.companyIp); register(); // loginIP(APPCache.getOpenid(), "1"); // LZRegistData lzRegistData = (LZRegistData) obj; // APPCache.setToken(lzRegistData.token); // APPCache.setUse(regist_phone.getText().toString().trim()); // APPCache.setPwd(regist_pwd.getText().toString().trim()); // showMessage(LZRegistAty.this, "注册成功"); // finish(); } } // , new IHttpResultError() { // @Override // public void error(MLHttpType.RequestType type, Object obj) { // // } // } ); } public void getCompanyData() { Map<String, String> map = new HashMap(); MLRequestParams mlHttpParam = new MLRequestParams(); // mlHttpParam.put("tel", regist_phone.getText().toString().trim()); // mlHttpParam.put("password", regist_pwd.getText().toString().trim()); // mlHttpParam.put("vCode", regist_code.getText().toString().trim()); // mlHttpParam.put("userName", regist_usename.getText().toString().trim()); // mlHttpParam.put("confirmPass", regist_repwd.getText().toString().trim()); // mlHttpParam.put("flag", "1"); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.GETCOMPANY, mlHttpParam, LZCompanyData.class, CommService.getInstance(), true); message.setResList(true); loadData(LZWanshanAty.this, message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { lzCompanyData = (List<LZCompanyData>) obj; } } // , new IHttpResultError() { // @Override // public void error(MLHttpType.RequestType type, Object obj) { // // } // } ); } //获取该用户所在的服务器ip public void loginIP(String openid, String loginType) { Map<String, String> map = new HashMap(); MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("telOrOpenId", openid); mlHttpParam.put("loginType", loginType); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.GETUSERIP, mlHttpParam, LoginIpData.class, CommService.getInstance(), true); loadData(LZWanshanAty.this, message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { LoginIpData companyIp = (LoginIpData) obj; APPCache.setIPAddress(companyIp.companyIp); register(); } } , new IHttpResultError() { @Override public void error(MLHttpType.RequestType type, Object obj) { } } ); } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case 0: tv_getcode.setText("" + msg.obj); break; case 1: isTimerFinished = true; tv_getcode.setText("重新发送"); break; } return false; } class MyCountDownTimer extends CountDownTimer { public MyCountDownTimer() { super(60 * 1000, 1000); } @Override public void onTick(long millisUntilFinished) { Message msg = mHandler.obtainMessage(0); msg.obj = millisUntilFinished / 1000; mHandler.sendMessage(msg); } @Override public void onFinish() { mHandler.sendEmptyMessage(1); } } public int COMPANYCODE = 100; public int COMPANYCODEFEN = 200; public int pos = 0; public int fenpos = 0; public String companyID = ""; @OnClick(R.id.tv_com_zong) public void tv_com_zong(View view) { startAct(LZWanshanAty.this, LZRegistCompanyAty.class, lzCompanyData, COMPANYCODE); } @OnClick(R.id.tv_com_fen) public void tv_com_fen(View view) { if (lzCompanyData.get(pos).branchCompanyList != null && lzCompanyData.get(pos).branchCompanyList.size() > 0) { startAct(LZWanshanAty.this, LZRegistFenCompanyAty.class, lzCompanyData.get(pos).branchCompanyList, COMPANYCODEFEN); } else { showMessage(LZWanshanAty.this, "暂无分公司"); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == COMPANYCODE && resultCode == COMPANYCODE) { pos = data.getIntExtra("pos", 0); tv_com_zong.setText(lzCompanyData.get(pos).companyName); companyID = lzCompanyData.get(pos).companyId; if (lzCompanyData.get(pos).branchCompanyList != null && lzCompanyData.get(pos).branchCompanyList.size() > 0) { tv_com_fen.setText(lzCompanyData.get(pos).branchCompanyList.get(0).branchCompanyName); branchCompanyId = lzCompanyData.get(pos).branchCompanyList.get(0).branchCompanyId; } else { tv_com_fen.setText("暂无分公司"); } } if (requestCode == COMPANYCODEFEN && resultCode == COMPANYCODEFEN) { fenpos = data.getIntExtra("pos", 0); tv_com_fen.setText(lzCompanyData.get(pos).branchCompanyList.get(fenpos).branchCompanyName); branchCompanyId = lzCompanyData.get(pos).branchCompanyList.get(fenpos).branchCompanyId; } } @OnClick(R.id.titlebar_tv_left) public void leftClick(View view) { finish(); } @Override protected void onDestroy() { super.onDestroy(); APPCache.setYouKe(false); } }
package instruments; public class Guitar extends Instrument{ private int noOfStrings; public Guitar(String material, String type, String colour, double buyingPrice, double sellingPrice, int noOfStrings) { super(material, type, colour, buyingPrice, sellingPrice); this.noOfStrings = noOfStrings; } public int getNoOfStrings() { return noOfStrings; } public String play() { return "twang twang twang"; } }
package ch.puzzle.http.util; import java.net.http.HttpHeaders; import java.net.http.HttpResponse; import java.util.stream.Collectors; public class ResponseHelper { public static String toShortString(final HttpResponse<?> response) { return toString(response, 100, 3, "|"); } public static String toString(final HttpResponse<String> response) { return toString(response, 1000, 1000, "\n"); } private static String toString(final HttpResponse<?> response, int maxChar, int maxHeader, String separator) { StringBuilder sb = new StringBuilder(); sb.append("Url : " + response.uri()).append("\n"); sb.append("Status : " + response.statusCode()).append("\n"); sb.append("Version: " + response.version()).append("\n"); sb.append("Body : " + firstNChars(response.body().toString(), maxChar)).append("\n"); sb.append("Headers: " + firstNHeaders(response.headers(), maxHeader, separator)).append("\n"); return sb.toString(); } private static String firstNChars(String s, int n) { if (s == null || s.length() <= n) { return s; } return s.trim().substring(0, n) + "... \n\nTotal " + s.length() + " bytes"; } private static String firstNHeaders(HttpHeaders headers, int n, String separator) { return headers.map() // .entrySet() // .stream() // .limit(n) // .map(e -> String.format("\"%s\":\"%s\"", e.getKey(), e.getValue())) // .collect(Collectors.joining(" " + separator + " ")); } }
package vista.Cartas; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.WindowConstants; import controlador.*; public class FormEliminarPlatoBebida extends javax.swing.JFrame { private JButton btnEliminar; private JComboBox cmbCarta; private JTextField txtItem; private JLabel lblCarta; private AbstractAction eliminarAccion; public FormEliminarPlatoBebida() { super(); initGUI(); } private void initGUI() { try { getContentPane().setLayout(null); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); this.setTitle("Eliminar Plato/Bebida"); { btnEliminar = new JButton(); getContentPane().add(btnEliminar); btnEliminar.setText("ELIMINAR"); btnEliminar.setBounds(86, 108, 118, 34); btnEliminar.setAction(eliminarAccion()); } { lblCarta = new JLabel(); getContentPane().add(lblCarta); lblCarta.setText("Dia de Carta:"); lblCarta.setBounds(10, 15, 90, 35); } { lblCarta = new JLabel(); getContentPane().add(lblCarta); lblCarta.setText("Plato/Bebida:"); lblCarta.setBounds(10, 60, 90, 35); } { String[] n = { "", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado", "domingo"}; cmbCarta = new JComboBox(n); getContentPane().add(cmbCarta); cmbCarta.setBounds(120, 15, 90, 35); } { txtItem = new JTextField(); getContentPane().add(txtItem); txtItem.setBounds(120, 60, 150, 35); } pack(); setSize(300, 180); } catch (Exception e) { e.printStackTrace(); } } private AbstractAction eliminarAccion() { if(eliminarAccion == null) { eliminarAccion = new AbstractAction("ELIMINAR", null) { public void actionPerformed(ActionEvent evt) { if( Restaurante.getRestaurante().descargarCarta( (cmbCarta.getSelectedItem().toString()) , (txtItem.getText()) ) ){ JOptionPane.showMessageDialog(null, "Plato/Bebida eliminado de la carta", "MENSAJE", JOptionPane.WARNING_MESSAGE); }else{ JOptionPane.showMessageDialog(null, "El dia NO posee carta asignada o NO existe el Plato/Bebida", "Prohibido", JOptionPane.WARNING_MESSAGE); } } }; } return eliminarAccion; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.inbio.commons.dublincore.facade.ara; import java.util.List; import java.util.Set; import javax.ejb.Remote; import org.inbio.commons.dublincore.dto.DublinCoreDTO; import org.inbio.commons.dublincore.dto.ara.InterfaceDublinCoreDTO; import org.inbio.commons.dublincore.dto.ara.ReferenceDTO; import org.inbio.commons.dublincore.manager.DublinCoreMetadataManager; /** * * @author gsulca */ @Remote public interface DublinCoreFacadeRemote extends DublinCoreMetadataManager { public Long countSimpleSearch(String query); public List<DublinCoreDTO> getReferenceSimpleSearch(String query, int firstResult, int maxResult); public Long countDublinCoreAdvancedSearch(DublinCoreDTO dublinCoreDTO); public Set<Integer> getDublinCoreByCriteria(DublinCoreDTO dublinCoreDTO); public List<DublinCoreDTO> getDublinCoreAdvancedSearch(DublinCoreDTO dublinCoreDTO, int firstResult, int maxResult); public List<ReferenceDTO> dublinCoreDTOsToReferenceDTOs (List<DublinCoreDTO> list); public ReferenceDTO dublinCoreDTOToReferenceDTO (DublinCoreDTO element); public Long countResourceByTypeId(int typeId); public List<DublinCoreDTO> getAllDublinCorePaginated(int firstResult, int maxResult); public void saveDublinCore(InterfaceDublinCoreDTO interfaceDublinCoreDTO); public void updateDublinCore(InterfaceDublinCoreDTO interfaceDublinCoreDTO); public InterfaceDublinCoreDTO findInterfaceDublincoreById(Long resourceId); public List<DublinCoreDTO> findAllDublinCorePaginated(int resourceTypeId, int firstResult, int maxResult); public List<ReferenceDTO> dublinCoreDTOsToFullReferenceDTOs (List<DublinCoreDTO> list); }
package model.character.constants; /** * This package contains all racial modifiers as constants. * @author Daradics Levente */
package com.android.example.myapplication; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class existing extends AppCompatActivity { SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_existing); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); db = openOrCreateDatabase("USERDB", Context.MODE_PRIVATE, null); db.execSQL("CREATE TABLE IF NOT EXISTS user10(user_id VARCHAR PRIMARY KEY , name VARCHAR , password VARCHAR); "); } public void login(View view) { EditText t1 = (EditText) findViewById(R.id.edit5); EditText t2 = (EditText) findViewById(R.id.edit4); String name = t1.getText().toString(); String pass = t2.getText().toString(); Cursor c = db.rawQuery("SELECT * FROM user10", null); if (c.getCount() == 0) { Toast.makeText(this, "No record found !!!!", Toast.LENGTH_LONG).show(); } else { int f = 0; while (c.moveToNext()) { String yo1 = c.getString(0); String yo2 = c.getString(2); if ((name.equals(yo1)) && (pass.equals(yo2))) { f = 1; break; } } if (f == 1) { Toast.makeText(this, "Logging In", Toast.LENGTH_LONG).show(); Intent i = new Intent(this, coffee.class); startActivity(i); } else { Toast.makeText(this, "No record found", Toast.LENGTH_LONG).show(); } } } }
package com.dio.citydestroyer.Database; import org.postgresql.Driver; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.SimpleDriverDataSource; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.TransactionManagementConfigurer; import javax.sql.DataSource; import java.util.Properties; @Configuration @EnableTransactionManagement @ComponentScan public class HibernateConfiguration implements TransactionManagementConfigurer { @Value("${spring.datasource.url}") private String url; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; @Value("${spring.datasource.driver-class-name}") private Class<Driver> driverClass; @Bean public DataSource dataSource() { SimpleDriverDataSource dataSource = new SimpleDriverDataSource(); dataSource.setDriverClass(driverClass); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setConnectionProperties(hibernateProperties()); return dataSource; } @Bean public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); sessionFactory.setPackagesToScan("com.dio.citydestroyer"); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; } @Bean public Properties hibernateProperties() { Properties properties = new Properties(); properties.put("hibernate.hbm2ddl.auto", "update"); return properties; } @Bean public PlatformTransactionManager transactionManager() { return new DataSourceTransactionManager(dataSource()); } @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return transactionManager(); } }
package com.vicutu.cache.impl; import java.util.Iterator; import java.util.Map; import com.vicutu.cache.Cache; import com.vicutu.cache.CacheManager; public class MapCacheManagerImpl implements CacheManager { private Map<String, Cache> caches; public void setCaches(Map<String, Cache> caches) { this.caches = caches; } public Cache get(String name) { return caches.get(name); } public Iterator<String> keySet() { return caches.keySet().iterator(); } public void remove(String name) { Cache cache = caches.get(name); if (cache != null) { caches.remove(name); } } public void destroy() throws Throwable { caches.clear(); } public void removeAll() { caches.clear(); } }
/* * (C) Mississippi State University 2009 * * The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is * a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries * and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in * http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in * all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html. */ //PlanarScripter.java //Declares a class for automating WSL scripting with ScalarWidgets. //Davis Herring //Created November 10 2002 //Updated March 31 2004 //Version 0.11 package org.webtop.util.script; import org.webtop.util.WTString; import org.webtop.x3d.widget.PlanarWidget; import org.webtop.wsl.client.WSLPlayer; public class PlanarScripter extends WidgetScripter implements PlanarWidget.Listener { private final float defaultXValue,defaultYValue; public PlanarScripter(PlanarWidget widget,WSLPlayer player,String id,String param,float defX,float defY) { super(widget,player,id,param); defaultXValue=defX; defaultYValue=defY; widget.addListener((PlanarWidget.Listener)this); } protected void setValue(String value) { int split = value.indexOf(','); if(split==-1) ((PlanarWidget)widget).setValue(defaultXValue,defaultYValue); else ((PlanarWidget)widget).setValue(WTString.toFloat(value.substring(0,split),defaultXValue), WTString.toFloat(value.substring(split+1),defaultYValue)); } protected void destroy() { ((PlanarWidget)widget).removeListener((PlanarWidget.Listener)this); super.destroy(); } public void valueChanged(PlanarWidget src, float x,float y) { if(src==widget) { if(src.isActive()) recordMouseDragged(String.valueOf(x)+','+y); } else System.err.println("PlanarScripter: unexpected valueChanged from "+src); } }
package solutions; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.IntStream; import java.util.stream.Stream; public class test { public static void main(String[] args) throws IOException { long y = 88888888888L; } }
package com.project.smart6.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import com.project.smart6.model.IPLPlayer; import com.project.smart6.model.IPLSchedule; @Repository public interface IPLRepository extends JpaRepository <IPLPlayer, Long> { @Query("select u from IPLPlayer u where u.player_team = ?1 OR u.player_team = ?2 ORDER BY u.player_credit DESC") public List<IPLPlayer> findAllPlayersByTeam(String iplTeam1, String iplTeam2); @Query("select u from IPLSchedule u") public List<IPLSchedule> getIplSchedule(String todayDate); }
package Java三.正则表达式; public class regex1 { public static void main(String[] args) { String str = "abc" ; String regex = "\\w{3,}" ; System.out.println(str.matches(regex)); } }
package ch.erp.management.mvp.model.http; /** * 公共的请求回调监听器 */ public interface MHttpCallBack<T> { /*成功时回调-返回请求数据*/void onSuccess(T t); /*失败时回调-返回错误信息*/void onFaild(String errorMsg); }
/* * Copyright (c) 2021. <plusmancn@gmail.com> All Rights Reversed. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. */ package cn.plusman.poc.mybatis.plus.explore.mapper; import cn.plusman.poc.mybatis.plus.explore.entity.User; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * @author plusman * @since 2021/3/13 3:05 PM */ public interface UserMapper { User selectByid3(Integer id); /** * $ 号示例 * @return */ User selectUserWithDollar(String name); /** * # 号示例 * @return */ User selectUserWithPound(String name); }
package com.nextLevel.hero.mngSalary.model.dto; import java.math.BigDecimal; import java.sql.Date; public class FourInsRateDTO { private String searchDate; private int companyNo; private int divNo; private java.sql.Date insRateStartDate; private BigDecimal workersPensionRate; private BigDecimal workersHealthRate; private BigDecimal workersLongTermCareRate; private BigDecimal workersUnempRate; private BigDecimal under150EmpRate; private BigDecimal industryRate; public FourInsRateDTO() {} public FourInsRateDTO(String searchDate, int companyNo, int divNo, Date insRateStartDate, BigDecimal workersPensionRate, BigDecimal workersHealthRate, BigDecimal workersLongTermCareRate, BigDecimal workersUnempRate, BigDecimal under150EmpRate, BigDecimal industryRate) { super(); this.searchDate = searchDate; this.companyNo = companyNo; this.divNo = divNo; this.insRateStartDate = insRateStartDate; this.workersPensionRate = workersPensionRate; this.workersHealthRate = workersHealthRate; this.workersLongTermCareRate = workersLongTermCareRate; this.workersUnempRate = workersUnempRate; this.under150EmpRate = under150EmpRate; this.industryRate = industryRate; } public String getSearchDate() { return searchDate; } public void setSearchDate(String searchDate) { this.searchDate = searchDate; } public int getCompanyNo() { return companyNo; } public void setCompanyNo(int companyNo) { this.companyNo = companyNo; } public int getDivNo() { return divNo; } public void setDivNo(int divNo) { this.divNo = divNo; } public java.sql.Date getInsRateStartDate() { return insRateStartDate; } public void setInsRateStartDate(java.sql.Date insRateStartDate) { this.insRateStartDate = insRateStartDate; } public BigDecimal getWorkersPensionRate() { return workersPensionRate; } public void setWorkersPensionRate(BigDecimal workersPensionRate) { this.workersPensionRate = workersPensionRate; } public BigDecimal getWorkersHealthRate() { return workersHealthRate; } public void setWorkersHealthRate(BigDecimal workersHealthRate) { this.workersHealthRate = workersHealthRate; } public BigDecimal getWorkersLongTermCareRate() { return workersLongTermCareRate; } public void setWorkersLongTermCareRate(BigDecimal workersLongTermCareRate) { this.workersLongTermCareRate = workersLongTermCareRate; } public BigDecimal getWorkersUnempRate() { return workersUnempRate; } public void setWorkersUnempRate(BigDecimal workersUnempRate) { this.workersUnempRate = workersUnempRate; } public BigDecimal getUnder150EmpRate() { return under150EmpRate; } public void setUnder150EmpRate(BigDecimal under150EmpRate) { this.under150EmpRate = under150EmpRate; } public BigDecimal getIndustryRate() { return industryRate; } public void setIndustryRate(BigDecimal industryRate) { this.industryRate = industryRate; } @Override public String toString() { return "FourInsRateDTO [searchDate=" + searchDate + ", companyNo=" + companyNo + ", divNo=" + divNo + ", insRateStartDate=" + insRateStartDate + ", workersPensionRate=" + workersPensionRate + ", workersHealthRate=" + workersHealthRate + ", workersLongTermCareRate=" + workersLongTermCareRate + ", workersUnempRate=" + workersUnempRate + ", under150EmpRate=" + under150EmpRate + ", industryRate=" + industryRate + "]"; } }
/** * Class to represent a vertex of a graph * @author : pgr150030- Panchami Rudrakshi * reference : rbk code */ import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Vertex implements Iterable<Edge> { int name; // name of the vertex boolean seen; // flag to check if the vertex has already been visited int d; // duration of task corresponding to vertex List<Edge> adj, revAdj; // adjacency list; use LinkedList or ArrayList public Vertex parent; //parent of the vertex public int indegree; public int cno; public int outdegree; public int slack; int ec; int lc; int n; /** * Constructor for the vertex * * @param n * : int - name of the vertex */ Vertex(int n) { name = n; seen = false; d = Integer.MAX_VALUE; adj = new ArrayList<Edge>(); revAdj = new ArrayList<Edge>(); /* only for directed graphs */ cno = 0; parent = null; } public Iterator<Edge> iterator() { return adj.iterator(); } /** * Method to represent a vertex by its name */ public String toString() { return Integer.toString(name); } }
package expansion.neto.com.mx.jefeapp.ui.autoriza; import android.app.Activity; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.view.WindowManager; import expansion.neto.com.mx.jefeapp.R; import expansion.neto.com.mx.jefeapp.databinding.ActivityAutorizaCalificaBinding; /** * Created by marcosmarroquin on 23/03/18. */ public class ActivityCalificarAutoriza extends AppCompatActivity { private ActivityAutorizaCalificaBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_NO_TITLE); this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); initDataBinding(); binding.enviar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); } /** * Método que setea la vista con el binding */ private void initDataBinding() { binding = DataBindingUtil.setContentView(this, R.layout.activity_autoriza_califica); } }
package org.juxtasoftware.service.importer.jxt; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Given a global list of typeless revision occurrences, convert it into * a list of typed revision occurrence that can be used to generate single * exclusion entries in the xslt file. * @author loufoster * */ final class JxtRevisionExtractor extends DefaultHandler{ private Set<Integer> includedRevisions; private Integer revisionCount = 0; private Set<RevisionOccurrence> excludedRevisonsInfo = new HashSet<RevisionOccurrence>(); private Map<String, Integer> tagCounts = new HashMap<String, Integer>(); public void extract( final Reader srcReader, final List<Integer> includedRevisions ) throws SAXException, IOException { // juxta revision lists are zero based. Make them one based this.includedRevisions = new HashSet<Integer>(); for ( Integer rev : includedRevisions ) { this.includedRevisions.add( (rev+1) ); } this.tagCounts.put("add", 0); this.tagCounts.put("addSpan", 0); this.tagCounts.put("del", 0); this.tagCounts.put("delSpan", 0); Util.saxParser().parse( new InputSource( srcReader), this ); } public Set<RevisionOccurrence> getExcludedRevisions() { return this.excludedRevisonsInfo; } public int getTotalRevisionCount() { return this.revisionCount; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ( isRevision(qName) ) { // increment total revsion count and individual revision type count this.revisionCount++; Integer cnt = this.tagCounts.get(qName) + 1; this.tagCounts.put(qName, cnt); // add revisions that are not part of the inclusion list are excluded if ( isAdd(qName) ) { if ( this.includedRevisions.contains( this.revisionCount ) == false ) { this.excludedRevisonsInfo.add( new RevisionOccurrence(qName, cnt) ); } } else { // delete revsions are excluded unless they are part of the list if ( this.includedRevisions.contains( this.revisionCount ) ) { this.excludedRevisonsInfo.add( new RevisionOccurrence(qName, cnt) ); } } } } private boolean isRevision(final String qName ) { return ( isAdd(qName) || isDelete(qName) ); } private boolean isAdd(final String qName ) { return ( qName.equals("add") || qName.equals("addSpan")); } private boolean isDelete(final String qName ) { return ( qName.equals("del") || qName.equals("delSpan")); } /** * @author loufoster */ static class RevisionOccurrence { private final String tagName; private final int occurrence; public RevisionOccurrence( final String tagName, final int occurrence) { this.tagName = tagName; this.occurrence = occurrence; } public String getTagName() { return tagName; } public int getOccurrence() { return occurrence; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + occurrence; result = prime * result + ((tagName == null) ? 0 : tagName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RevisionOccurrence other = (RevisionOccurrence) obj; if (occurrence != other.occurrence) return false; if (tagName == null) { if (other.tagName != null) return false; } else if (!tagName.equals(other.tagName)) return false; return true; } } }
package ffm.slc.model.enums; /** * A code categorizing the attendance event (e.g., excused absence, unexcused absence) */ public enum AttendanceEventCategoryType { IN_ATTENDANCE("In Attendance"), EXCUSED_ABSENCE("Excused Absence"), UNEXCUSED_ABSENCE("Unexcused Absence"), TARDY("Tardy"), EARLY_DEPARTURE("Early departure"); private String prettyName; AttendanceEventCategoryType(String prettyName) { this.prettyName = prettyName; } @Override public String toString() { return prettyName; } }
package cmput301f17t26.smores; import android.graphics.Bitmap; import android.location.Location; import android.test.ActivityInstrumentationTestCase2; import android.util.Base64; import com.google.android.gms.maps.model.LatLng; import junit.framework.Assert; import java.io.ByteArrayOutputStream; import java.util.UUID; import cmput301f17t26.smores.all_exceptions.CommentNotSetException; import cmput301f17t26.smores.all_exceptions.CommentTooLongException; import cmput301f17t26.smores.all_exceptions.ImageNotSetException; import cmput301f17t26.smores.all_exceptions.ImageTooBigException; import cmput301f17t26.smores.all_exceptions.LocationNotSetException; import cmput301f17t26.smores.all_models.HabitEvent; /** * Created by Luke on 2017-10-21. */ public class HabitEventTest extends ActivityInstrumentationTestCase2 { public HabitEventTest() { super(cmput301f17t26.smores.all_models.HabitEvent.class); } public void testHabitEvent() { //Includes coverage of getUserID() and getHabitID() UUID userID = UUID.randomUUID(); UUID habitID = UUID.randomUUID(); HabitEvent habitEvent = new HabitEvent(userID, habitID); assertEquals(userID, habitEvent.getUserID()); assertEquals(habitID, habitEvent.getHabitID()); } public void testHabitEventRandomUUID() { //Includes coverage of getID() UUID userID = UUID.randomUUID(); UUID habitID = UUID.randomUUID(); HabitEvent habitEvent1 = new HabitEvent(userID, habitID); HabitEvent habitEvent2 = new HabitEvent(userID, habitID); HabitEvent habitEvent3 = new HabitEvent(userID, habitID); assertTrue(habitEvent1.getID() != habitEvent2.getID()); assertTrue(habitEvent1.getID() != habitEvent3.getID()); assertTrue(habitEvent2.getID() != habitEvent3.getID()); } public void testSetComment() { //Includes coverage of getComment() UUID userID = UUID.randomUUID(); UUID habitID = UUID.randomUUID(); HabitEvent habitEvent = new HabitEvent(userID, habitID); String comment = "short comment"; try { habitEvent.setComment(comment); assertEquals(comment, habitEvent.getComment()); } catch (CommentTooLongException e) { Assert.fail("Comment too long"); } catch (CommentNotSetException e) { Assert.fail("Comment not set"); } } public void testSetCommentLongComment() { UUID userID = UUID.randomUUID(); UUID habitID = UUID.randomUUID(); HabitEvent habitEvent = new HabitEvent(userID, habitID); String comment = "It is a long comment."; try { habitEvent.setComment(comment); Assert.fail("Should have thrown CommentTooLongException"); } catch (CommentTooLongException e) { //success } } public void testSetLocation() { //Includes coverage of getLocation() UUID userID = UUID.randomUUID(); UUID habitID = UUID.randomUUID(); HabitEvent habitEvent = new HabitEvent(userID, habitID); Location location = new Location(""); location.setLatitude(14.852071d); location.setLongitude(-91.530547d); habitEvent.setLocation(location); try { assertEquals(location, habitEvent.getLocation()); } catch (LocationNotSetException e) { Assert.fail("Location not set"); } } public void testSetLatitude() { //Includes coverage of getLocation() UUID userID = UUID.randomUUID(); UUID habitID = UUID.randomUUID(); HabitEvent habitEvent = new HabitEvent(userID, habitID); Location location = new Location(""); location.setLatitude(14.852071d); location.setLongitude(-91.530547d); habitEvent.setLocation(location); Location gotLocation = new Location(""); gotLocation.setLatitude(location.getLatitude()); gotLocation.setLongitude(location.getLongitude()); try { assertEquals(location.getLatitude(), gotLocation.getLatitude()); } catch (NullPointerException e) { Assert.fail("Latitude not set"); } } public void testSetLongitude() { //Includes coverage of getLocation() UUID userID = UUID.randomUUID(); UUID habitID = UUID.randomUUID(); HabitEvent habitEvent = new HabitEvent(userID, habitID); Location location = new Location(""); location.setLatitude(14.852071d); location.setLongitude(-91.530547d); habitEvent.setLocation(location); Location gotLocation = new Location(""); gotLocation.setLatitude(location.getLatitude()); gotLocation.setLongitude(location.getLongitude()); try { assertEquals(location.getLongitude(), gotLocation.getLongitude()); } catch (NullPointerException e) { Assert.fail("Longitude not set"); } } public void testSetImage() { //Includes coverage of getImage() UUID userID = UUID.randomUUID(); UUID habitID = UUID.randomUUID(); HabitEvent habitEvent = new HabitEvent(userID, habitID); Bitmap bitmap = Bitmap.createBitmap(5, 5, Bitmap.Config.ARGB_8888); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); byte[] b = byteArrayOutputStream.toByteArray(); String thumbnailBase64 = Base64.encodeToString(b, Base64.DEFAULT); try { habitEvent.setImage(bitmap); Bitmap gotBitmap = habitEvent.getImage(); ByteArrayOutputStream gotByteArrayOutputStream = new ByteArrayOutputStream(); gotBitmap.compress(Bitmap.CompressFormat.PNG, 100, gotByteArrayOutputStream); String gotThumbnailBase64 = Base64.encodeToString(gotByteArrayOutputStream.toByteArray(), Base64.DEFAULT); assertEquals(thumbnailBase64, gotThumbnailBase64); } catch (ImageTooBigException e) { Assert.fail("small image was considered too big."); } catch (ImageNotSetException e) { Assert.fail("Image not set"); } } public void testSetImageTooBig() { UUID userID = UUID.randomUUID(); UUID habitID = UUID.randomUUID(); HabitEvent habitEvent = new HabitEvent(userID, habitID); Bitmap bitmap = Bitmap.createBitmap(129, 129, Bitmap.Config.ARGB_8888); try { habitEvent.setImage(bitmap); Assert.fail("Should have thrown ImageTooBigException"); } catch (ImageTooBigException e) { //success } } public void testRemoveLocation() { //Includes coverage of getLocation UUID userID = UUID.randomUUID(); UUID habitID = UUID.randomUUID(); HabitEvent habitEvent = new HabitEvent(userID, habitID); Location location = new Location(""); location.setLatitude(14.852071d); location.setLongitude(-91.530547d); habitEvent.setLocation(location); habitEvent.removeLocation(); try { habitEvent.getLocation(); Assert.fail("Should have thrown LocationNotSetException"); } catch (LocationNotSetException e) { //success } } public void testRemoveImage() { //Includes coverage of getImage UUID userID = UUID.randomUUID(); UUID habitID = UUID.randomUUID(); HabitEvent habitEvent = new HabitEvent(userID, habitID); Bitmap bitmap = Bitmap.createBitmap(5, 5, Bitmap.Config.ARGB_8888); try { habitEvent.setImage(bitmap); } catch (ImageTooBigException e) { Assert.fail("Could not set image"); } habitEvent.removeImage(); try { habitEvent.getImage(); Assert.fail("Should have thrown ImageNotSetException"); } catch (ImageNotSetException e) { //success } } public void testRemoveComment() { //Includes coverage of getComment UUID userID = UUID.randomUUID(); UUID habitID = UUID.randomUUID(); HabitEvent habitEvent = new HabitEvent(userID, habitID); String comment = "Cool comment."; try { habitEvent.setComment(comment); } catch (CommentTooLongException e) { Assert.fail("Could not set comment"); } habitEvent.removeComment(); try { habitEvent.getComment(); Assert.fail("Should have thrown CommentNotSetException"); } catch (CommentNotSetException e) { //success } } public void testGetLatLng() { UUID userID = UUID.randomUUID(); UUID habitID = UUID.randomUUID(); HabitEvent habitEvent = new HabitEvent(userID, habitID); LatLng latLng = new LatLng(14.852071d, -91.530547d); Location location = new Location(""); location.setLatitude(latLng.latitude); location.setLongitude(latLng.longitude); habitEvent.setLocation(location); try { assertEquals(latLng, habitEvent.getLatLng()); } catch (LocationNotSetException e) { Assert.fail("Location not set"); } } }
package ex0417; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; public class GradeDAO { //데이터접속 public Connection con() throws Exception{ String driver = "oracle.jdbc.driver.OracleDriver"; String url = "jdbc:oracle:thin:@localhost:1521:xe"; String user = "system"; String password = "1234"; Class.forName(driver); Connection con=DriverManager.getConnection(url, user, password); return con; } //데이터 목록 출력하기 public ArrayList<GradeVO> list() throws Exception{ ArrayList<GradeVO> list=new ArrayList<GradeVO>(); String sql="select * from tbl_grade"; PreparedStatement ps=con().prepareStatement(sql); ResultSet rs=ps.executeQuery(); while(rs.next()) { GradeVO vo=new GradeVO(); vo.setGno(rs.getInt("gno")); vo.setGname(rs.getString("gname")); vo.setKor(rs.getInt("kor")); vo.setEng(rs.getInt("eng")); vo.setMat(rs.getInt("mat")); list.add(vo); //자주 까먹는 부분. vo를 list에 넣어주어야함! 누락되면 출력안됨! } return list; } //데이터입력 메소드 public void insert(GradeVO vo)throws Exception{ String sql="insert into tbl_grade(gno, gname, kor, eng, mat) values(SEQ_GNO.nextval,?,?,?,?)"; PreparedStatement ps=con().prepareStatement(sql); ps.setString(1, vo.getGname()); ps.setInt(2, vo.getKor()); ps.setInt(3, vo.getEng()); ps.setInt(4, vo.getMat()); ps.execute(); //쿼리도 상관없음. } //데이터삭제 메소드 public void delete(int gno)throws Exception{ String sql="delete from tbl_grade where gno=?"; PreparedStatement ps=con().prepareStatement(sql); ps.setInt(1, gno); ps.execute(); } //데이터 수정 메서드 public void update(GradeVO vo)throws Exception{ String sql="update tbl_grade set kor=?, eng=?, mat=? where gno=?"; PreparedStatement ps=con().prepareStatement(sql); ps.setInt(1, vo.getKor()); ps.setInt(2, vo.getEng()); ps.setInt(3, vo.getMat()); ps.setInt(4, vo.getGno()); ps.execute(); } }
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Random; public class Radix_sort { public static void printArray(int[] list, int size, BufferedWriter bw) throws IOException { int i; bw.write((System.getProperty("line.separator"))); bw.write("[ "); System.out.print("[ "); for (i = 0; i < size; i++) { System.out.print(list[i] + " "); bw.write(list[i] + " "); } System.out.println("]\n"); bw.write("]\n"); } public static int findLargestNum(int[] array, int size) { int i; int largestNum = -1; for (i = 0; i < size; i++) { if (array[i] > largestNum) largestNum = array[i]; } return largestNum; } // Radix Sort public static void radixSort(int[] array, int size, BufferedWriter bw) throws IOException { System.out.println("\n\nRunning Radix Sort on Unsorted List!\n\n"); bw.write((System.getProperty("line.separator"))); bw.write("\n\nRunning Radix Sort on Unsorted List!\n\n"); bw.write((System.getProperty("line.separator"))); // Base 10 is used int i; int[] semiSorted = new int[size]; int significantDigit = 1; int largestNum = findLargestNum(array, size); // Loop until we reach the largest significant digit while (largestNum / significantDigit > 0) { System.out.println("\n\n\tNow considering " + significantDigit + "'s place for putting into buckets\n"); bw.write((System.getProperty("line.separator"))); bw.write((System.getProperty("line.separator"))); bw.write("\n\n\tNow considering " + significantDigit + "'s place for putting into buckets\n"); bw.write((System.getProperty("line.separator"))); System.out.print("\tSorting :" + significantDigit + "'s place "); bw.write("\tSorting :" + significantDigit + "'s place "); bw.write((System.getProperty("line.separator"))); printArray(array, size, bw); int[] bucket = new int[10]; for (i = 0; i < 10; i++) { bucket[i] = 0; } // Counts the number of "keys" or digits that will go into each // bucket for (i = 0; i < size; i++) bucket[(array[i] / significantDigit) % 10]++; /** * Add the count of the previous buckets, Acquires the indexes after * the end of each bucket location in the array Works similar to the * count sort algorithm **/ for (i = 1; i < 10; i++) bucket[i] += bucket[i - 1]; // Use the bucket to fill a "semiSorted" array // for (i = size - 1; i >= 0; i--) for (i = 0; i <= size - 1; i++) { semiSorted[--bucket[(array[i] / significantDigit) % 10]] = array[i]; int pos = (array[i] / significantDigit) % 10; System.out.println("Putting \t " + array[i] + "\t in bucket " + pos); bw.write((System.getProperty("line.separator"))); bw.write("Putting \t " + array[i] + "\t in bucket " + pos + "\n"); bw.write((System.getProperty("line.separator"))); } bw.write((System.getProperty("line.separator"))); bw.write("Now collect the numbers from the buckets back starting from 0\n\n"); bw.write((System.getProperty("line.separator"))); System.out .println("Now collect the numbers from the buckets back starting from 0\n"); bw.write((System.getProperty("line.separator"))); bw.write("After collecting the numbers now our array looks like"); bw.write((System.getProperty("line.separator"))); bw.write("[ "); System.out .print("After collecting the numbers now our array looks like [ "); for (i = 0; i < size; i++) { array[i] = semiSorted[i]; System.out.print(" " + array[i]); bw.write(" " + array[i]); } System.out.println(" ]\n\n"); bw.write(" ]\n\n\n"); // Move to next significant digit significantDigit *= 10; } } public static void main(String[] args) throws IOException { File file = new File("answer.txt"); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); System.out.print("\n\nRunning Radix Sort\n"); System.out.print("----------------------------------\n"); bw.write("\n\nRunning Radix Sort\n"); bw.write((System.getProperty("line.separator"))); bw.write("----------------------------------------------------------------------\n"); bw.write((System.getProperty("line.separator"))); int size = 12; int list[]= new int[12]; Random rnd = new Random(System.currentTimeMillis()); for (int index = 0; index < 12; index++) { list[index] = rnd.nextInt(900) + 100; } //int list[] = { 10, 2, 303, 4021, 293, 1, 0, 429, 480, 92, 2999, 14 }; System.out.print("\nUnsorted List: "); bw.write("\nUnsorted List: "); printArray(list, size, bw); double startTimeProgram = System.currentTimeMillis(); radixSort(list, size, bw); double endTimeProgram = System.currentTimeMillis(); double time = endTimeProgram- startTimeProgram; bw.write((System.getProperty("line.separator"))); System.out.print("\nSorted List:"); bw.write((System.getProperty("line.separator"))); bw.write("\nSorted List:"); printArray(list, size, bw); bw.write((System.getProperty("line.separator"))); System.out.print("\n"); bw.write((System.getProperty("line.separator"))); bw.write("Total Running time for the program is "+ time + "ms"); bw.flush(); bw.close(); } }
package com.cyhz_common_component_activity; public interface CCA_Camera_CallBack { public final static int CAMERA = 1; public final static int ALBUM = 2; public void back(String paramString,int fromType); }
package com.larryhsiao.nyx.core.jots; import com.silverhetch.clotho.Source; import java.sql.Connection; /** * Db connection source with initial sql. */ public class JotsDb implements Source<Connection> { private final Source<Connection> connSource; public JotsDb(Source<Connection> connSource) { this.connSource = connSource; } @Override public Connection value() { try { final Connection conn = connSource.value(); conn.createStatement().executeUpdate( // language=H2 "CREATE TABLE IF NOT EXISTS jots(" + "id integer not null auto_increment," + "content text not null, " + "createdTime timestamp with time zone not null, " + "location geometry, " + "mood varchar not null default '', " + "version integer not null default 1, " + "delete integer not null default 0" + ");" ); return conn; } catch (Exception e) { throw new IllegalArgumentException(e); } } }
package com.pce.BookMeTutor.Model.Dao; import java.io.Serializable; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; 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.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @Table(name = "booking") public class Booking implements Serializable { private static final long serialVersionUID = 8958089464653520081L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "booking_id", unique = true, nullable = false) private long id; @ManyToOne private UserEntity user; @ManyToOne(optional = true) @JoinColumn(nullable = true) private Tutor handler; @Column(nullable = false) private String subject; @Column(nullable = false) private String topic; @Column(name = "class_number", nullable = false) private String classNumber; @Column(name = "board", nullable = false) private String board; @Column(name = "line_1", nullable = false) private String line1; @Column(name = "line_2", nullable = false) private String line2; @Column(name = "city", nullable = false) private String city; @Column(name = "pincode", nullable = false) private String pincode; @Column(name = "scheduled_time", nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date schedule; @Column(name = "deadline_time", nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date deadline; @Column(name = "rescheduled", nullable = false, columnDefinition = "boolean default false") private boolean rescheduled; @Column(name = "secret", nullable = false, length = 4) private String secret; @Column(name = "score") private int score; @Column(name = "user_comment") private String comment; @Column(name = "reason") private String reason; @Column(name = "booking_status", nullable = false) private String status = "unAssigned"; @OneToOne(cascade = CascadeType.ALL) private Invoice invoice; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public long getId() { return id; } public void setId(long id) { this.id = id; } public UserEntity getUser() { return user; } public void setUser(UserEntity user) { this.user = user; } public Tutor getHandler() { return handler; } public void setHandler(Tutor handler) { this.handler = handler; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public String getClassNumber() { return classNumber; } public void setClassNumber(String classNumber) { this.classNumber = classNumber; } public String getBoard() { return board; } public void setBoard(String board) { this.board = board; } public String getLine1() { return line1; } public void setLine1(String line1) { this.line1 = line1; } public String getLine2() { return line2; } public void setLine2(String line2) { this.line2 = line2; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getPincode() { return pincode; } public void setPincode(String pincode) { this.pincode = pincode; } public Date getSchedule() { return schedule; } public void setSchedule(Date schedule) { this.schedule = schedule; } public Date getDeadline() { return deadline; } public void setDeadline(Date deadline) { this.deadline = deadline; } public boolean isRescheduled() { return rescheduled; } public void setRescheduled(boolean rescheduled) { this.rescheduled = rescheduled; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public Invoice getInvoice() { return invoice; } public void setInvoice(Invoice invoice) { this.invoice = invoice; } public static long getSerialversionuid() { return serialVersionUID; } @Override public String toString() { return "Booking [id=" + id + ", user=" + user + ", handler=" + handler + ", subject=" + subject + ", topic=" + topic + ", classNumber=" + classNumber + ", board=" + board + ", line1=" + line1 + ", line2=" + line2 + ", city=" + city + ", pincode=" + pincode + ", schedule=" + schedule + ", deadline=" + deadline + ", rescheduled=" + rescheduled + ", secret=" + secret + ", score=" + score + ", comment=" + comment + ", reason=" + reason + ", status=" + status + ", invoice=" + invoice + "]"; } public Booking(long id, UserEntity user, Tutor handler, String subject, String topic, String classNumber, String board, String line1, String line2, String city, String pincode, Date schedule, Date deadline, boolean rescheduled, String secret, int score, String comment, String reason, String status, Invoice invoice) { super(); this.id = id; this.user = user; this.handler = handler; this.subject = subject; this.topic = topic; this.classNumber = classNumber; this.board = board; this.line1 = line1; this.line2 = line2; this.city = city; this.pincode = pincode; this.schedule = schedule; this.deadline = deadline; this.rescheduled = rescheduled; this.secret = secret; this.score = score; this.comment = comment; this.reason = reason; this.status = status; this.invoice = invoice; } public Booking() { super(); } }
package com.arjun.repositories; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.arjun.models.Users; import com.arjun.util.MyConnectionFactory; public class UserDAO { private Statement st; private PreparedStatement pst; private MyConnectionFactory mcf = MyConnectionFactory.getConnectionFactory(); Connection conn = mcf.getConnection(); // this method chekes if the user user name and password are valid or not // if valid returns true else false public Boolean checkLogin(String uname, String upass) { Boolean isRight = false; //int uid = -1; // login is not successfull try { String sql = "select * from ers_users " + "where ers_username = ? and ers_password = ?"; pst = conn.prepareStatement(sql); pst.setString(1, uname); pst.setString(2, upass); ResultSet res = pst.executeQuery(); if(res.next()) { isRight = true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return isRight; } // this method get the all the user details on the basis of username and password public Users getUser(String uname, String upass) throws SQLException { Users user = new Users(); String sql = "select * from ers_users " + "where ers_username = ? and ers_password = ?"; pst = conn.prepareStatement(sql); pst.setString(1, uname); pst.setString(2, upass); ResultSet res = pst.executeQuery(); if(res.next()) { user.setUser_ID(res.getInt(1)); user.setUserName(res.getString(2)); user.setFirstName(res.getString(4)); user.setLastName(res.getString(5)); user.setEmail(res.getString(6)); user.setRoleID(res.getInt(7)); } return user; } // this will check if the user values are already in the data base if so return true else false // takes arguemt of user public Boolean isUserUnique(Users user) { boolean userIsUnique = true; String sql = "select * from ers_users where ers_username = ? or user_email = ? "; try { pst = conn.prepareStatement(sql); pst.setString(1, user.getUserName()); pst.setString(2, user.getEmail()); ResultSet res = pst.executeQuery(); if(res.next()) { userIsUnique = false; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); userIsUnique = false; } System.out.println("DAO "+ userIsUnique); return userIsUnique; } // this will add the user in the data base if success returns true else false // takes in user object as argument public Boolean addUser(Users user) { boolean userAdded = false; String sql = "insert into ers_users (user_first_name, user_last_name, user_email, ers_username, ers_password, user_role_id )" + "values(?, ?, ?, ?, ?, ?)" ; try { pst = conn.prepareStatement(sql); pst.setString(1, user.getFirstName()); pst.setString(2, user.getLastName()); pst.setString(3, user.getEmail()); pst.setString(4, user.getUserName()); pst.setString(5, user.getUserPassword()); pst.setInt(6, 1); int res = pst.executeUpdate(); if(res != 0) { userAdded = true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); userAdded = false; } return userAdded; } }
package org.jdownloader.api.myjdownloader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.URL; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import jd.controlling.proxy.ProxyController; import jd.http.SocketConnectionFactory; import org.appwork.utils.NullsafeAtomicReference; import org.appwork.utils.net.httpconnection.HTTPConnectionImpl; import org.appwork.utils.net.httpconnection.HTTPProxy; import org.appwork.utils.net.httpconnection.HTTPProxyException; import org.appwork.utils.net.httpconnection.SocketStreamInterface; import org.appwork.utils.net.socketconnection.SocketConnection; import org.jdownloader.api.myjdownloader.MyJDownloaderConnectThread.DeviceConnectionHelper; import org.jdownloader.api.myjdownloader.MyJDownloaderConnectThread.SessionInfoWrapper; import org.jdownloader.myjdownloader.client.json.DeviceConnectionStatus; public class MyJDownloaderWaitingConnectionThread extends Thread { protected static class MyJDownloaderConnectionRequest { public final SessionInfoWrapper getSession() { return session; } private final SessionInfoWrapper session; private final DeviceConnectionHelper connectionHelper; public final DeviceConnectionHelper getConnectionHelper() { return connectionHelper; } protected MyJDownloaderConnectionRequest(SessionInfoWrapper session, DeviceConnectionHelper connectionHelper) { this.session = session; this.connectionHelper = connectionHelper; } } protected static class MyJDownloaderConnectionResponse { public final DeviceConnectionStatus getStatus() { return status; } public final SocketStreamInterface getSocketStream() { return socket; } public final Throwable getThrowable() { return throwable; } private final DeviceConnectionStatus status; private final SocketStreamInterface socket; private final Throwable throwable; private final MyJDownloaderWaitingConnectionThread thread; private final MyJDownloaderConnectionRequest request; public final MyJDownloaderConnectionRequest getRequest() { return request; } protected MyJDownloaderConnectionResponse(MyJDownloaderWaitingConnectionThread thread, MyJDownloaderConnectionRequest request, DeviceConnectionStatus connectionStatus, SocketStreamInterface connectionSocket, Throwable e) { this.request = request; this.status = connectionStatus; this.socket = connectionSocket; this.throwable = e; this.thread = thread; } /** * @return the thread */ public final MyJDownloaderWaitingConnectionThread getThread() { return thread; } } protected final AtomicBoolean running = new AtomicBoolean(true); protected final NullsafeAtomicReference<MyJDownloaderConnectionRequest> connectionRequest = new NullsafeAtomicReference<MyJDownloaderConnectionRequest>(); protected final MyJDownloaderConnectThread connectThread; private final static AtomicInteger THREADID = new AtomicInteger(0); public MyJDownloaderWaitingConnectionThread(MyJDownloaderConnectThread connectThread) { this.setDaemon(true); this.setName("MyJDownloaderWaitingConnectionThread:" + THREADID.incrementAndGet()); this.connectThread = connectThread; } @Override public void run() { try { while (running.get()) { MyJDownloaderConnectionRequest request = null; synchronized (connectionRequest) { if ((request = connectionRequest.getAndSet(null)) == null) { if (running.get() == false) { return; } connectionRequest.wait(); request = connectionRequest.getAndSet(null); } } if (request != null) { Throwable e = null; DeviceConnectionStatus status = null; request.getConnectionHelper().backoff(); HTTPProxy proxy = null; final InetSocketAddress addr = request.getConnectionHelper().getAddr(); final URL url = new URL(null, "socket://" + SocketConnection.getHostName(addr) + ":" + addr.getPort(), ProxyController.SOCKETURLSTREAMHANDLER); Socket socket = null; SocketStreamInterface socketStream = null; try { connectThread.log("Connect " + addr); final List<HTTPProxy> list = ProxyController.getInstance().getProxiesByURL(url, false, false); if (list != null && list.size() > 0) { proxy = list.get(0); socket = SocketConnectionFactory.createSocket(proxy); socket.setReuseAddress(true); socket.setSoTimeout(180000); socket.setTcpNoDelay(true); socket.connect(addr, 30000); final Socket finalSocket = socket; socketStream = new SocketStreamInterface() { @Override public Socket getSocket() { return finalSocket; } @Override public OutputStream getOutputStream() throws IOException { return finalSocket.getOutputStream(); } @Override public InputStream getInputStream() throws IOException { return finalSocket.getInputStream(); } @Override public void close() throws IOException { finalSocket.close(); } }; if (addr.getPort() == 443) { socketStream = HTTPConnectionImpl.getDefaultSSLSocketStreamFactory().create(socketStream, SocketConnection.getHostName(addr), 443, true, true); } socketStream.getOutputStream().write(("DEVICE" + request.getSession().getSessionToken()).getBytes("ISO-8859-1")); socketStream.getOutputStream().flush(); final int validToken = socketStream.getInputStream().read(); status = DeviceConnectionStatus.parse(validToken); } else { synchronized (connectionRequest) { try { connectionRequest.wait(5000); } catch (final InterruptedException ignore) { } throw new ConnectException("No available connection for: " + url); } } } catch (Throwable throwable) { try { connectThread.log(throwable); e = throwable; if (proxy != null && !proxy.isNone() && throwable instanceof HTTPProxyException) { ProxyController.getInstance().reportHTTPProxyException(proxy, url, (IOException) throwable); } } finally { try { if (socket != null) { socket.close(); socket = null; } } catch (final Throwable ignore) { } } } final MyJDownloaderConnectionResponse response = new MyJDownloaderConnectionResponse(this, request, status, socketStream, e); if (connectThread.putResponse(response) == false) { connectThread.log("putResponse failed, maybe connectThread is closed/interrupted."); try { if (socket != null) { socket.close(); } } catch (final Throwable ignore) { } } } } } catch (final Throwable e) { connectThread.log(e); } finally { abort(); } } public boolean isRunning() { return running.get(); } public boolean putRequest(MyJDownloaderConnectionRequest request) { synchronized (connectionRequest) { if (running.get() == false) { return false; } if (connectionRequest.compareAndSet(null, request)) { connectionRequest.notifyAll(); return true; } return false; } } public void abort() { synchronized (connectionRequest) { running.set(false); connectionRequest.notifyAll(); } } }
package com.apap.igd.service; import com.apap.igd.model.JenisPenangananModel; public interface JenisPenangananService { JenisPenangananModel getJenisPenangananById(long idPenanganan); JenisPenangananModel addJenisPenanganan(JenisPenangananModel jenisPenanganan); }
package com.kieferlam.battlelan.settings; import org.lwjgl.glfw.GLFW; import java.io.BufferedWriter; import java.io.FileWriter; import java.lang.reflect.Field; /** * Created by Kiefer on 21/03/2015. */ public class Settings { public int bind_Left, bind_Right, bind_Jump, bind_Primary, bind_Secondary, res_Width, res_Height; public Settings(){ } @Override public String toString(){ StringBuilder builder = new StringBuilder(); for (Field field : getClass().getFields()) { try { String value = field.get(this).toString(); builder.append(field.getName() + ":" + value); builder.append(System.lineSeparator()); } catch (IllegalAccessException e) { e.printStackTrace(); } } return builder.toString(); } public static Settings getDefaultSettings(){ Settings defaultSettings = new Settings(); defaultSettings.bind_Left = GLFW.GLFW_KEY_A; defaultSettings.bind_Right = GLFW.GLFW_KEY_D; defaultSettings.bind_Jump = GLFW.GLFW_KEY_SPACE; defaultSettings.bind_Primary = GLFW.GLFW_MOUSE_BUTTON_1; defaultSettings.bind_Secondary = GLFW.GLFW_MOUSE_BUTTON_2; defaultSettings.res_Width = 854; defaultSettings.res_Height = 480; return defaultSettings; } }
package com.propertycross.mgwt.properties; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class OrderedPropertiesManagerTest { private OrderedPropertiesManager cache; @Mock private PropertiesStorage storage; @Before public void cache() throws Throwable { List<Property> queue = new ArrayList<Property>(); queue.add(new Property("0", "t0", "p0", "bd0", "bt0", "ty0", "i0", "s0")); queue.add(new Property("1", "t1", "p1", "bd1", "bt1", "ty1", "i1", "s1")); when(storage.favourites()).thenReturn(queue); cache = new OrderedPropertiesManager(storage); } @Test public void loadsFromStorage() throws Throwable { verify(storage).favourites(); } @Test public void checksIfFavourite() throws Throwable { assertTrue("is favourite", cache.isFavourite(new Property( "0", "t0", "p0", "bd0", "bt0", "ty0", "i0", "s0"))); assertFalse("isn't favourite", cache.isFavourite(new Property( "X", "t0", "p0", "bd0", "bt0", "ty0", "i0", "s0"))); } @Test public void removesFavourite() throws Throwable { cache.removeFavourite(new Property("0", "t0", "p0", "bd0", "bt0", "ty0", "i0", "s0")); List<Property> expected = new ArrayList<Property>(); expected.add(new Property("1", "t1", "p1", "bd1", "bt1", "ty1", "i1", "s1")); verify(storage).saveFavourites(expected); } @Test public void caseSameSearchMovedToHeadOfTheQueue() { Property prop0 = new Property("0", "t0", "p0", "bd0", "bt0", "ty0", "i0", "s0"); cache.addFavourite(prop0); List<Property> expected = new ArrayList<Property>(); expected.add(new Property("1", "t1", "p1", "bd1", "bt1", "ty1", "i1", "s1")); expected.add(prop0); verify(storage).saveFavourites(expected); } @Test public void addsNewSearch() throws Throwable { Property newProp = new Property("2", "t2", "p2", "bd2", "bt2", "ty2", "i2", "s2"); cache.addFavourite(newProp); List<Property> expected = new ArrayList<Property>(); expected.add(new Property("0", "t0", "p0", "bd0", "bt0", "ty0", "i0", "s0")); expected.add(new Property("1", "t1", "p1", "bd1", "bt1", "ty1", "i1", "s1")); expected.add(newProp); verify(storage).saveFavourites(expected); } }
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyExample_01 { public static void main(String[] args) { InvocationHandler invocationHandler = new ReaderInvocationHandler(); Object proxyInstance = Proxy.newProxyInstance(ProxyExample_01.class.getClassLoader(), new Class[] {Reader.class}, invocationHandler); String result = (((Reader) proxyInstance)).read("Hello Proxy!"); System.out.println(result); } } interface Reader { String read(String str); } class MyReader implements Reader { @Override public String read(String str) { return str; } } class ReaderInvocationHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { for (Object arg : args) { System.out.println("Argument: " + arg); } final Object result = method.invoke(new MyReader(), args); System.out.println("Result: " + result); return result; } }
package com.robin.springbootlearn.common.aspect; import com.robin.springbootlearn.app.service.UserOptLogService; import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.PostConstruct; /** * @author robin * @version v0.0.1 * @depiction 用户操作日志切面 * @create 2019-11-27 23:22 **/ public class UserOptLogAspect { @Autowired private UserOptLogService userOptLogService; private static UserOptLogAspect userOptLogAspect; @PostConstruct public void init() { userOptLogAspect = this; userOptLogAspect.userOptLogService = this.userOptLogService; } }
/* Copyright (C) 2013-2014, Securifera, Inc All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of Securifera, Inc 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 OWNER 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. ================================================================================ Pwnbrew is provided under the 3-clause BSD license above. The copyright on this package is held by Securifera, Inc */ package pwnbrew.misc; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Enumeration; import java.util.Properties; /** * * @author Securifera */ public class ManifestProperties extends Properties { //=================================================================== /** * Constructor */ public ManifestProperties() { super(); } //========================================================================= /** * * After the entries have been written, the output stream is flushed. * The output stream remains open after this method returns. * <p> * @param out an output stream. * @exception IOException if writing this property list to the specified * output stream throws an <tt>IOException</tt>. * @exception ClassCastException if this <code>Properties</code> object * contains any keys or values that are not <code>Strings</code>. * @exception NullPointerException if <code>out</code> is null. * @since 1.2 */ public void store(OutputStream out ) throws IOException { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, "8859_1")); synchronized (this) { for (Enumeration e = keys(); e.hasMoreElements();) { String key = (String)e.nextElement(); String val = (String)get(key); bw.write(key + ": " + val); bw.newLine(); } } bw.flush(); } }
package debug; import java.util.ArrayList; public class CompanyName { public static void main(String[] args) { Company company = new Company(new ArrayList<>()); company.addEmployee(new Employee("Sanyi",10)); company.addEmployee(new Employee("Sanyi 2" ,15)); company.addEmployee(new Employee("Sanyi 3",20)); System.out.println("Béla nevű alakalmazott:"+ company.findEmployeeByName("Béla")); System.out.println("Sanyi nevű alakalmazott:"+ company.findEmployeeByName("Sanyi").getName()); System.out.println("Alakalmazottak:"+ company.listEmployeeNames()); } }
package controller; import entity.EquiScrap_insert; import entity.EquiScrap_select; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import service.EquiScrapService; import java.util.List; import java.util.Map; @Controller @RequestMapping("/Scrap") public class equiScrapController { @Autowired EquiScrapService equiScrapService; //引入的xml文件 String xmlPath = "EquiScrapSQL.xml"; //查询 @RequestMapping("/select") public String equi_scrap_select(EquiScrap_select equiScrap_select, Model model){ List result = equiScrapService.select(xmlPath,equiScrap_select); //System.out.println(result.toString()); //将list转为二维数组 String[][] form = new String[result.size()][6]; //System.out.println(result.toString()); //将查询到的数据赋给二维数组 for (int i=0;i<result.size();i++) { Map map = (Map) result.get(i); form[i][0] = String.valueOf(map.get("scrap_no")); form[i][1] = String.valueOf(map.get("create_emp")); form[i][2] = String.valueOf(map.get("create_date").toString().substring(0, 10)); form[i][3] = String.valueOf(map.get("state")); form[i][4] = String.valueOf(map.get("audit_emp")); form[i][5] = String.valueOf(map.get("maker")); } model.addAttribute("result",form); return "scrap/main"; } //添加 @RequestMapping("/insert") public String scrap_insert(EquiScrap_insert equiScrap_insert,Model model){ int success = equiScrapService.insert(xmlPath,equiScrap_insert); String state = "添加失败!"; if (success == 1){ state = "添加成功!"; } model.addAttribute("state",state); return "scrap/insert"; } //删除 @RequestMapping("/delete") public @ResponseBody int scrap_delete(String id,String src){ return equiScrapService.delete(xmlPath,id,src); } //审核 @RequestMapping("/audit") public @ResponseBody int audit(String id,String src,String user){ int result = equiScrapService.audit(xmlPath,src,id,user); //System.out.println(result); return result; } //消审 @RequestMapping("remove") public @ResponseBody int remove(String id,String src){ return equiScrapService.remove(xmlPath,src,id); } //详情页查询 @RequestMapping("detail_select") public @ResponseBody String[][] depot_out_detail_select(String scrap_no, String src){ List result = equiScrapService.detail_select(xmlPath,scrap_no,src); //System.out.println(result.toString()); String[][] form = new String[result.size()][5]; //将查询到的数据赋给二维数组 for (int i=0;i<result.size();i++){ Map map = (Map) result.get(i); form[i][0]= String.valueOf(map.get("card_no")); form[i][1]= String.valueOf(map.get("equi_name")); form[i][2]= String.valueOf(map.get("unit")); form[i][3]= String.valueOf(map.get("store")); form[i][4]= String.valueOf(map.get("ven_name")); } //System.out.println(form[0][0]); return form; } //详情页添加 @RequestMapping("/detail_insert") public @ResponseBody int scrap_detail_insert(String scrap_no,String card_no,String src){ return equiScrapService.detail_insert(xmlPath,scrap_no,card_no,src); //System.out.println(out_no+card_no+src); } //详情页删除 @RequestMapping("/detail_delete") public @ResponseBody int depot_out_detail_delete(String id,String src){ return equiScrapService.detail_delete(xmlPath,id,src); } //详情页添加页面查询 @RequestMapping("/detail_insert_select") public @ResponseBody String[][] scrap_detail_insert_select(String scrap_no,String card_no, String src){ List result = equiScrapService.detail_insert_select(xmlPath,scrap_no,card_no,src); String[][] form = new String[result.size()][4]; //将查询到的数据赋给二维数组 for (int i=0;i<result.size();i++){ Map map = (Map) result.get(i); form[i][0]= String.valueOf(map.get("card_no")); form[i][1]= String.valueOf(map.get("equi_name")); form[i][2]= String.valueOf(map.get("ven_name")); form[i][3]= String.valueOf(map.get("store_name")); } return form; } }
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Main { final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); final String LINE_SPR = System.getProperty("line.separator"); final int BIG_MOD = 1000000007; class Pair { int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } public String toString() { return a + ":" + b; } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair p = (Pair) o; return this.b == p.b && this.a == p.a; } public int hashCode() { return a + b * 100000; } } void run() throws Exception { String[] nums = ns().split(" "); int n = Integer.parseInt(nums[0]); int c = Integer.parseInt(nums[1]); String str = ""; for(String tmp : ns().split(" ")) { str += tmp; } for(int i = 1; i <= c; i++) { Set<Pair> res = new HashSet<Pair>(); int index = 0; while(index < n && index >= 0) { index = str.indexOf(Integer.toString(i), index); if(index == -1) break; for(int j = 0; j <= index; j++) { for(int k = index; k < n; k++) { res.add(new Pair(j, k)); } } index++; } System.out.println(res.size()); } } int code(int i, int j, int c) { return i + j * c; } /* * Templates */ void dumpObjArr(Object[] arr, int n) { for(int i = 0; i < n; i++) { System.out.print(arr[i]); if(i < n - 1) System.out.print(" "); } System.out.println(""); } void dumpObjArr2(Object[][] arr, int m, int n) { for(int j = 0; j < m; j++) dumpObjArr(arr[j], n); } int ni() throws Exception { return Integer.parseInt(br.readLine().trim()); } long nl() throws Exception { return Long.parseLong(br.readLine().trim()); } String ns() throws Exception { return br.readLine(); } boolean isPrime(int n) { for(int i=2;i<n;i++) { if(n%i==0) return false; } return true; } int getPrime(int n) { List<Integer> primes = new ArrayList<Integer>(); primes.add(2); int count = 1; int x = 1; while(primes.size() < n) { x+=2; int m = (int)Math.sqrt(x); for(int p : primes) { if(p > m) { primes.add(x); break; } if(x % p == 0) break; } } return primes.get(primes.size() - 1); } public static void main(String[] args) throws Exception { new Main().run(); } }
package com.example.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.AdditionalAnswers.returnsFirstArg; import static org.mockito.ArgumentMatchers.any; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; import com.example.dao.PostRepository; import com.example.exception.PostNotFoundException; import com.example.mapper.PostMapper; import com.example.model.Post; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; import javax.persistence.EntityNotFoundException; import java.util.ArrayList; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class PostServiceTest { @Autowired private PostService postService; @MockBean private PostRepository postRepository; @Autowired private PostMapper postMapper; @Test public void getAllPostsTest() { List<Post> list = new ArrayList<>(); Post post = new Post(); post.setTitle("First post"); post.setDescription("DMy first post"); post.setContent("My first content"); list.add(post); Mockito.when(postRepository.findAll()).thenReturn(list); List<Post> posts = postMapper.toPosts(postService.getAllPosts()); assertEquals(list.size(), posts.size()); verify(postRepository, Mockito.times(1)).findAll(); } @Test public void getOnePostTest() { long id = 1; when(postRepository.getOne(id)) .thenReturn(new Post("First post", "My first post", "My first content")); Post post = postMapper.toPost(postService.getOnePost(id)); assertThat(post).isNotNull(); } @Test(expected = PostNotFoundException.class) public void getOnePostNotFoundTest(){ long id = 1; when(postRepository.getOne(id)).thenThrow(EntityNotFoundException.class); postService.getOnePost(id); } @Test public void addPostTest() { long id = 1; Post newPost = new Post("First post", "My first post", "My first content"); newPost.setId(id); when(postRepository.saveAndFlush(any(Post.class))).then(returnsFirstArg()); Post post = postMapper.toPost(postService.addPost(postMapper.toPostDTO(newPost))); assertThat(post.getTitle()).isNotNull(); } @Test public void updatePost() { long id = 1; Post newPost = new Post("First post", "My first post", "My first content"); newPost.setId(id); when(postRepository.getOne(id)).thenReturn(newPost); when(postRepository.save(any(Post.class))).then(returnsFirstArg()); Post post = postMapper.toPost(postService.updatePost(postMapper.toPostDTO(newPost), id)); assertEquals(post.getTitle(), newPost.getTitle()); } @Test public void deletePost() { long id = 1; when(postRepository.getOne(id)). thenReturn(new Post("First post", "My first post", "My first content")); postService.deletePost(id); verify(postRepository, times(1)).delete(any(Post.class)); } }
package pwnbrew.socks; import java.io.IOException; import java.io.InterruptedIOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import pwnbrew.MaltegoStub; import pwnbrew.manager.DataManager; import pwnbrew.misc.Constants; import pwnbrew.misc.DebugPrinter; import pwnbrew.misc.ManagedRunnable; import pwnbrew.network.control.messages.SocksOperation; import pwnbrew.utilities.SocketUtilities; public class SocksServer extends ManagedRunnable { private static final String NAME_Class = SocksServer.class.getSimpleName(); protected Thread m_TheThread = null; protected ServerSocket theServerSocket = null; protected final int theListenPort; private final int theHostId; private final int theChannelId; private final Map<Integer, SocksHandler> handlerMap = new HashMap<>(); public static final int LISTEN_TIMEOUT = 200; public static final int DEFAULT_SERVER_TIMEOUT = 200; //========================================================================== /** * * @param listenPort * @param passedHostId * @param passedChannelId */ public SocksServer( int listenPort, int passedHostId, int passedChannelId ) { super( Constants.Executor); theListenPort = listenPort; theHostId = passedHostId; theChannelId = passedChannelId; } //========================================================================== /** * * @return */ public int getPort() { return theListenPort; } //========================================================================== /** * */ @Override public void go(){ listen(); close(); } //========================================================================== /** * */ public void close() { if( theServerSocket != null ) { try { theServerSocket.close(); } catch( IOException e ) { } } theServerSocket = null; //Kill all the threads synchronized( handlerMap ){ for( Iterator<Map.Entry<Integer, SocksHandler>> anIter = handlerMap.entrySet().iterator(); anIter.hasNext(); ){ //Add each entry Map.Entry<Integer, SocksHandler> anEntry = anIter.next(); anEntry.getValue().shutdown(); } } //Send message to create channel for socks proxy SocksOperation aSocksMsg = new SocksOperation( theHostId, SocksOperation.SOCKS_STOP ); DataManager.send(MaltegoStub.getMaltegoStub(), aSocksMsg); } //========================================================================== /** * * @throws java.net.BindException * @throws IOException */ private void prepareToListen() throws java.net.BindException, IOException { theServerSocket = new ServerSocket( theListenPort ); theServerSocket.setSoTimeout( LISTEN_TIMEOUT ); } //========================================================================== /** * */ protected void listen() { try { prepareToListen(); } catch( java.net.BindException ex ){ DebugPrinter.printMessage( NAME_Class, "listen", "The Port "+theListenPort+" is in use !", null ); DebugPrinter.printMessage( NAME_Class, "listen", ex.getMessage(), ex ); return; } catch( IOException ex) { DebugPrinter.printMessage( NAME_Class, "listen", ex.getMessage(), ex ); return; } //Main accept loop while( theServerSocket != null && !finished() ) checkClientConnection(); } //========================================================================= /** * */ public void checkClientConnection() { //Close() method was probably called. if( theServerSocket == null ) return; try { Socket clientSocket = theServerSocket.accept(); clientSocket.setSoTimeout( DEFAULT_SERVER_TIMEOUT ); DebugPrinter.printMessage( NAME_Class, "SocksServer", "Connection from : " + getSocketInfo( clientSocket ), null ); //register the socks handler registerSocksHandler(clientSocket); } catch( InterruptedIOException | SocketException e ) { } catch( Exception ex ) { DebugPrinter.printMessage( NAME_Class, "checkClientConnection", ex.getMessage(), ex ); } } //========================================================================= /** * * @param clientSocket */ public void registerSocksHandler( Socket clientSocket ){ //Create new handler, register it, and start it int handlerId = SocketUtilities.getNextId(); synchronized( handlerMap ){ while( true ){ SocksHandler aHandler = handlerMap.get(handlerId); if( aHandler != null ) handlerId = SocketUtilities.getNextId(); else break; } } //Create the socks handler and register it SocksHandler aHandler; synchronized( handlerMap ){ aHandler = new SocksHandler( handlerId, clientSocket, theHostId, theChannelId ); handlerMap.put(handlerId, aHandler); } aHandler.start(); } //========================================================================= /** * * @param sock * @return */ public String getSocketInfo( Socket sock ) { if( sock == null ) return "<NA/NA:0>"; return "<"+iP2Str( sock.getInetAddress() )+":"+ sock.getPort() + ">"; } //========================================================================== /** * * @param IP * @return */ public String iP2Str( InetAddress IP ) { if( IP == null ) return "NA/NA"; return IP.getHostName()+"/"+IP.getHostAddress(); } //========================================================================== /** * * @param theHandlerId * @return */ public SocksHandler getSocksHandler(int theHandlerId) { SocksHandler retHandler; synchronized(handlerMap){ retHandler = handlerMap.get(theHandlerId); } return retHandler; } //========================================================================== /** * * @param theHandlerId * @return */ public SocksHandler removeSocksHandler(int theHandlerId) { SocksHandler retHandler; synchronized(handlerMap){ retHandler = handlerMap.remove(theHandlerId); } return retHandler; } }
package com.xixiwan.platform.sys.entity; import com.xixiwan.platform.base.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * 角色和菜单关联表 * </p> * * @author Sente * @since 2018-09-14 */ @Data @EqualsAndHashCode(callSuper = true) @Accessors(chain = true) public class SysRoleMenu extends BaseEntity<SysRoleMenu> { private static final long serialVersionUID = 1L; /** * 角色id */ private Integer roleid; /** * 菜单id */ private Integer menuid; }
package br.com.furb.repository; import br.com.furb.domain.NotaFiscal; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface NotaFiscalRepository extends JpaRepository<NotaFiscal, Long> { }
package HeMaSeaFoodSystem; /** * TODO: SERVICE-3375:Implement SeaFoodService */ public class ISeaFoodServiceImplement { //TO DO }
package de.blb; import org.h2.jdbc.JdbcSQLNonTransientConnectionException; import org.junit.Test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import static org.junit.Assert.*; public class InsertTRMTest { //Testing VWIM 0013-0017, 0021 and 0025 insertions //Again with some real Data expected in each table //Test commented out because it was for development purposes only and as there is no connection to the db anymore //This test will always fail and lead to our pipeline to fail. @Test public void InsertTRMTest() throws SQLException, JdbcSQLNonTransientConnectionException { try { Connection conn = Connector.connect("jdbc:h2:tcp://40.68.207.131/~/BayernLB", "sa", "pqJxjm!D4b97?4Mz8h"); ResultSet rs13 = getRows(conn, "VWIM0013SERVICE_CLUSTER"); ResultSet rs14 = getRows(conn, "VWIM0014SERVICE_CATEGORY"); ResultSet rs15 = getRows(conn, "VWIM0015SERVICE_CAPABILITY"); ResultSet rs16 = getRows(conn, "VWIM0016TECHNOLOGY_FUNCTIONALITY"); ResultSet rs17 = getRows(conn, "VWIM0017TECHNOLOGY_PRODUCT"); ResultSet rs21 = getRows(conn, "VWIM0021APPLICATION_TECHNOLOGY_PRODUCT"); ResultSet rs25 = getRows(conn, "VWIM0025KOMP_TECHNOLOGY_PRODUCT"); finder(rs13, 1,new String[]{"Platform Services", "General Services", "Business Services"}); finder(rs14, 1,new String[]{"IT-Infrastructure Services", "Data Interchange Services", "User Interface Services"}); finder(rs15, 1,new String[]{"Visual Analytics", "Unified Communications (UC)", "Software Development Security"}); finder(rs16,1, new String[]{"Business Services", "Infrastructure Services", "Software Services"}); finder(rs17,1, new String[]{"12", "28", "144"}); finder(rs21, 2,new String[]{"SP-021", "SP-033", "SP-034"}); finder(rs25, 2,new String[]{"APP-0921_K_DATA_Compliance DB-DB", "APP-34_K_SW_C5_FatClient", "APP-204_K_SW_G2-Host-Konverter"}); } catch (Exception e) { } } public static void finder(ResultSet rs, int column, String[] whereCondition1) throws SQLException { boolean foundFlag = false; while (rs.next()) { for (String toFind : whereCondition1) { if (rs.getString(column).equals(toFind)) { System.out.println("found " + toFind); foundFlag = true; //Pass this test case } } } if (!foundFlag) fail(); //if not found, gail this test case } public static ResultSet getRows(Connection conn, String tableName) throws SQLException { PreparedStatement tableSelector = conn.prepareStatement("select * from " + tableName); //Iterates over tables and selects data //tableSelector.setString(1, tableName); ResultSet rs = tableSelector.executeQuery(); return rs; } }
package com.zheng.thread.producerconsumer; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * 面包箱 * @Author zhenglian * @Date 2018/6/24 23:21 */ public class BreadBox { /** * 装馒头的箱子 */ private BlockingQueue box = new ArrayBlockingQueue(50); public void put(Bread bread) { try { box.put(bread); } catch (InterruptedException e) { e.printStackTrace(); } } public Bread get() { try { return (Bread) box.take(); } catch (InterruptedException e) { e.printStackTrace(); } return null; } }
package no.nav.vedtak.sikkerhet.oidc.config; /** * Standard navn på environment injisert av NAIS når tokenX er enabled */ public enum TokenXProperty { TOKEN_X_WELL_KNOWN_URL, TOKEN_X_CLIENT_ID, TOKEN_X_PRIVATE_JWK, TOKEN_X_ISSUER, TOKEN_X_JWKS_URI, TOKEN_X_TOKEN_ENDPOINT; }
/** * Check mirror tree logic and check identical tree logic is same. it's just we need to flip left and right * Reference: https://www.geeksforgeeks.org/check-if-two-trees-are-mirror-of-each-other-using-level-order-traversal/ */ public class CheckMirrorTree { // main method }