text
stringlengths 10
2.72M
|
|---|
package com.earaya.voodoo.assets;
import org.eclipse.jetty.util.resource.Resource;
public class ClassPathAssetsComponent extends AssetsComponent {
public ClassPathAssetsComponent(String assetsPath) {
super(Resource.newClassPathResource(assetsPath));
}
}
|
/* 1: */ package com.kaldin.user.register.dao.impl;
/* 2: */
/* 3: */ import com.kaldin.common.util.PagingBean;
/* 4: */ import com.kaldin.user.register.dao.CandidateInterface;
/* 5: */ import com.kaldin.user.register.dto.CandidateDTO;
/* 6: */ import com.kaldin.user.register.dto.UnregisteredUsersDTO;
/* 7: */ import com.kaldin.user.register.hibernate.CandidateHibernate;
/* 8: */ import java.util.List;
/* 9: */
/* 10: */ public class CandidateImpl
/* 11: */ implements CandidateInterface
/* 12: */ {
/* 13: 12 */ CandidateHibernate candidateHibernate = new CandidateHibernate();
/* 14: */
/* 15: */ public List<?> show(int companyid)
/* 16: */ {
/* 17: 15 */ return this.candidateHibernate.show(companyid);
/* 18: */ }
/* 19: */
/* 20: */ public boolean save(CandidateDTO dtoObj)
/* 21: */ {
/* 22: 19 */ return this.candidateHibernate.save(dtoObj);
/* 23: */ }
/* 24: */
/* 25: */ public List<?> getUser(String email, int companyid)
/* 26: */ {
/* 27: 23 */ return this.candidateHibernate.getUser(email, companyid);
/* 28: */ }
/* 29: */
/* 30: */ public List<?> getUserTests(int id)
/* 31: */ {
/* 32: 27 */ return this.candidateHibernate.getUserTests(id);
/* 33: */ }
/* 34: */
/* 35: */ public String getEmail(int UserId)
/* 36: */ {
/* 37: 32 */ return this.candidateHibernate.getEmail(UserId);
/* 38: */ }
/* 39: */
/* 40: */ public List<?> show(PagingBean paggingBean, int totalRecord, int companyid)
/* 41: */ {
/* 42: 37 */ return this.candidateHibernate.show(paggingBean, totalRecord, companyid);
/* 43: */ }
/* 44: */
/* 45: */ public boolean checkProfile(int id)
/* 46: */ {
/* 47: 42 */ return this.candidateHibernate.checkProfile(id);
/* 48: */ }
/* 49: */
/* 50: */ public boolean checkAcademicInfo(int id)
/* 51: */ {
/* 52: 47 */ return this.candidateHibernate.checkAcademicInfo(id);
/* 53: */ }
/* 54: */
/* 55: */ public boolean checkTechInfo(int id)
/* 56: */ {
/* 57: 52 */ return this.candidateHibernate.checkTechInfo(id);
/* 58: */ }
/* 59: */
/* 60: */ public List<CandidateDTO> getUserList(int companyid, int status)
/* 61: */ {
/* 62: 57 */ return this.candidateHibernate.getUserList(companyid, status);
/* 63: */ }
/* 64: */
/* 65: */ public List<CandidateDTO> getCompanyUsers(int compid)
/* 66: */ {
/* 67: 61 */ return this.candidateHibernate.getCompanyUsers(compid);
/* 68: */ }
/* 69: */
/* 70: */ public List<?> getProfileDetails(String profile, int candidateId)
/* 71: */ {
/* 72: 65 */ return this.candidateHibernate.getProfileDetails(profile, candidateId);
/* 73: */ }
/* 74: */
/* 75: */ public String getUserPassword(int userId)
/* 76: */ {
/* 77: 70 */ return this.candidateHibernate.returnUserPassword(userId);
/* 78: */ }
/* 79: */
/* 80: */ public List<UnregisteredUsersDTO> getUnregisteredUserList(int companyid, int status)
/* 81: */ {
/* 82: 75 */ return this.candidateHibernate.getUnregisteredUserList(companyid, status);
/* 83: */ }
/* 84: */
/* 85: */ public boolean saveUnregisteredUser(String emailId, int companyId)
/* 86: */ {
/* 87: 80 */ return this.candidateHibernate.saveUnregisteredUser(emailId, companyId);
/* 88: */ }
/* 89: */
/* 90: */ public boolean changeStatusForUnregisteredUser(String emailId, int companyId)
/* 91: */ {
/* 92: 85 */ return this.candidateHibernate.updateStatusForUnregisteredUser(emailId, companyId);
/* 93: */ }
/* 94: */
/* 95: */ public boolean isExistingUser(String emailId, int companyId)
/* 96: */ {
/* 97: 90 */ return this.candidateHibernate.isUserAlreadyExists(emailId, companyId);
/* 98: */ }
/* 99: */
/* 100: */ public int getUserId(String email, int companyid)
/* 101: */ {
/* 102: 94 */ return this.candidateHibernate.getUserId(email, companyid);
/* 103: */ }
/* 104: */
/* 105: */ public boolean updateEmail(String email, int userid)
/* 106: */ {
/* 107: 98 */ return this.candidateHibernate.updateEmail(email, userid);
/* 108: */ }
/* 109: */
/* 110: */ public boolean deleteUser(CandidateDTO candidateObj, String email)
/* 111: */ {
/* 112:102 */ return this.candidateHibernate.deleteUser(candidateObj, email);
/* 113: */ }
public boolean deleteFromGroup(int groupId,int userId)
{
return this.candidateHibernate.deleteFromGroup(groupId, userId);
}
/* 114: */ }
/* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip
* Qualified Name: kaldin.user.register.dao.impl.CandidateImpl
* JD-Core Version: 0.7.0.1
*/
|
package com.aiyamamoto.transforemerapp.model;
/**
* Created by aiyamamoto on 2018-09-15.
*/
public class BattleResult {
private boolean isNameWin;
private boolean isCourageAndStrengthWin;
private boolean isSkillWin;
private boolean isOverallRatingWin;
public BattleResult() {
this.isNameWin = false;
this.isCourageAndStrengthWin = false;
this.isSkillWin = false;
this.isOverallRatingWin = false;
}
public void setNameWin(boolean nameWin) {
isNameWin = nameWin;
}
public void setCourageAndStrengthWin(boolean courageAndStrengthWin) {
isCourageAndStrengthWin = courageAndStrengthWin;
}
public void setSkillWin(boolean skillWin) {
isSkillWin = skillWin;
}
public void setOverallRatingWin(boolean overallRatingWin) {
isOverallRatingWin = overallRatingWin;
}
public boolean isNameWin() {
return isNameWin;
}
public boolean isCourageAndStrengthWin() {
return isCourageAndStrengthWin;
}
public boolean isSkillWin() {
return isSkillWin;
}
public boolean isOverallRatingWin() {
return isOverallRatingWin;
}
}
|
package net.halflite.resteasy.web.module;
import java.util.EnumSet;
import java.util.Map;
import javax.inject.Singleton;
import javax.servlet.DispatcherType;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.jboss.resteasy.plugins.guice.GuiceResteasyBootstrapServletContextListener;
import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher;
import org.webjars.servlet.WebjarsServlet;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.google.inject.servlet.GuiceFilter;
import com.google.inject.servlet.GuiceServletContextListener;
import com.google.inject.servlet.ServletModule;
import freemarker.ext.servlet.FreemarkerServlet;
public class AppServletModule extends ServletModule {
@Override
protected void configureServlets() {
install(new ResourceModule());
bind(GuiceResteasyBootstrapServletContextListener.class).in(Singleton.class);
bind(HttpServletDispatcher.class).in(Singleton.class);
bind(WebjarsServlet.class).in(Singleton.class);
bind(FreemarkerServlet.class).in(Singleton.class);
bind(GuiceFilter.class).in(Singleton.class);
serve("/webjars/*").with(WebjarsServlet.class);
Map<String, String> fmInitParam = ImmutableMap.<String, String> builder()
.put("TemplatePath", "classpath:views")
.put("NoCache", "true")
.put("ResponseCharacterEncoding", "fromTemplate")
.put("ExceptionOnMissingTemplate", "true")
.put("incompatible_improvements", "2.3.28")
.put("template_exception_handler", "rethrow")
.put("template_update_delay", "0")
.put("default_encoding", "UTF-8")
.put("output_encoding", "UTF-8")
.put("locale", "ja_JP")
.put("number_format", "0.##########")
.build();
serve("*.ftl").with(FreemarkerServlet.class, fmInitParam);
serve("/*").with(HttpServletDispatcher.class);
}
@Provides
@Singleton
public ServletContextHandler provideContextHandler(GuiceFilter guiceFilter,
GuiceResteasyBootstrapServletContextListener resteasyListener, GuiceServletContextListener guiceServletContextListener) {
final FilterHolder guiceFilterHolder = new FilterHolder(guiceFilter);
final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.addFilter(guiceFilterHolder, "/*", EnumSet.allOf(DispatcherType.class));
context.addEventListener(resteasyListener);
context.addEventListener(guiceServletContextListener);
return context;
}
@Provides
@Singleton
public GuiceServletContextListener provideContextListener(final Injector injector) {
return new GuiceServletContextListener() {
@Override
protected Injector getInjector() {
return injector;
}
};
}
}
|
package se.magmag.oauth.api.session.authentication;
import javax.interceptor.InterceptorBinding;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
/**
* Created by magnus.eriksson on 12/07/16.
*/
@InterceptorBinding
@Target({METHOD, TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Authenticated { }
|
package PoppyIlluminati;
/**
*
* @author leho9818
*/
public class Posts {
private String object_id;
private String name;
private String message;
private String type;
private String shares;
private String created_time;
public Posts(String inObject_id, String inName, String inMessage, String inType, String inShares, String inCreated_time) {
this.object_id = inObject_id;
this.name = inName;
this.message = inMessage;
this.type = inType;
this.shares = inShares;
this.created_time = inCreated_time;
}
public String getObject_id() {
return object_id;
}
public void setObject_id(String object_id) {
this.object_id = object_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getShares() {
return shares;
}
public void setShares(String shares) {
this.shares = shares;
}
public String getCreated_time() {
return created_time;
}
public void setCreated_time(String created_time) {
this.created_time = created_time;
}
}
|
package com.cfs.core.constants;
/**
* @author chopra
* 08/03/18
*/
public class PaymentConstants {
public static final String API_KEY_HEADER = "X-Api-Key";
public static final String AUTH_TOKEN_HEADER = "X-Auth-Token";
public static final String API_KEY = "777f5964fdadf64860acbddcf407969e";
public static final String AUTH_TOKEN = "ee4398c936bcda0e90459d39382aee4f";
public static final String CREATE_PAYMENT = "https://www.instamojo.com/api/1.1/payment-requests/";
public static final String GET_PAYMENT = "https://www.instamojo.com/api/1.1/payments/";
public static final String ERROR = "error";
public static final String CONTENT_TYPE = "application/json";
public static final String REDIRECT_URL = "http://cfs.com";
public static final String WEBHOOK_URL = "http://cfs.com";
}
|
package kr.ac.sogang.gtasubway.search;
import java.io.Serializable;
import android.text.format.Time;
public class StationInfo extends Station implements Serializable{
//String stationName=new String("");
String searchedMap;
int searchedLine=0, door=0, width=0, height=0;
int departure, arrival; //
public StationInfo(Station station,String searchedMap, int line, int door,int width, int height, int departure, int arrival){
// this.stationName=stationName;//될껄?
super(station);
this.searchedMap=searchedMap;
this.searchedLine=line;
this.door=door;
this.width=width;
this.height=height;
this.departure=departure;
this.arrival=arrival;
}
}
|
package de.zarncke.lib.id;
import de.zarncke.lib.value.Typed;
/**
* General form of Id types.
*
* @author Gunnar Zarncke
*/
public interface Id extends Typed {
String toUtf8String();
String toHexString();
}
|
package com.dataflow.analysis.dependency;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.expr.MethodCallExpr;
import com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration;
import java.util.Optional;
public class MethodCallVertex extends DependencyVertex {
private MethodCallExpr method;
private MethodDeclaration methodDeclaration;
public MethodCallVertex(MethodCallExpr method) {
this.method = method;
this.methodDeclaration = null;
try {
ResolvedMethodDeclaration resolvedMethodDeclaration = this.method.resolve();
Optional<MethodDeclaration> md = resolvedMethodDeclaration.toAst();
md.ifPresent(declaration -> this.methodDeclaration = declaration);
} catch (Exception e) {
System.out.println(e);
}
}
public boolean isResolvableMethod() {
return this.methodDeclaration != null && !this.methodDeclaration.getName().asString().equals("constructFeederAudit");
}
public MethodCallExpr getMethodCallExpr() {
return method;
}
public MethodDeclaration getMethodDeclaration() throws Exception {
if(this.methodDeclaration != null)
return this.methodDeclaration;
throw new Exception("Error");
}
@Override
public String toString() {
return this.method.toString();
}
}
|
package servlet;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.DaoFactory;
import dao.SectionDao;
import dao.dataAccess;
/**
* Servlet implementation class addprofessorsection
*/
@WebServlet("/updateProfessorSectionServlet")
public class updateProfessorSectionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public updateProfessorSectionServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
response.setCharacterEncoding("UTF-8");
String[] select = request.getParameterValues("select");
String[] professor = request.getParameterValues("professor");
for(int j=0;j<select.length;j++){
String select1 = select[j];
String professor1=professor[j];
SectionDao i = DaoFactory.createSectionDao();
i.updateProfessorSectionServlet(select1, professor1);
}
/*String professor = request.getParameter("professor");
String select="CMP101 - 1";
String professor="yu";
SectionDao sectionDao = DaoFactory.createSectioneDao();
sectionDao.updateProfessorSectionServlet(select,professor);*/
response.sendRedirect("pages/showallsection.jsp");
}
}
|
/**
*
*/
package com.bridgegap.profile;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.broadleafcommerce.common.presentation.AdminPresentation;
import org.broadleafcommerce.common.presentation.AdminPresentationCollection;
import org.broadleafcommerce.common.presentation.client.AddMethodType;
import org.broadleafcommerce.profile.core.domain.CustomerImpl;
import org.hibernate.annotations.Cascade;
import com.bridgegap.course.Program;
import com.bridgegap.course.ProgramImpl;
/**
* @author naveen.k.ganachari
*
*/
@Entity
@Table(name = "BRIDGE_CUSTOMER")
public class BridgeGapCustomer extends CustomerImpl {
/**
*
*/
private static final long serialVersionUID = 1L;
@Column(name = "COLLEGE_NAME")
@AdminPresentation(friendlyName = "CustomerImpl_College_Name",
group = GroupName.Customer, order = 5000,
prominent = true, gridOrder = 5000)
protected String collegeName;
@Column(name = "ACCOUNT_TYPE")
@AdminPresentation(friendlyName = "CustomerImpl_Account_Type",
group = GroupName.Customer, order = 6000,
prominent = true, gridOrder = 6000)
protected String accountType;
@Column(name = "BRANCH_NAME")
@AdminPresentation(friendlyName = "CustomerImpl_Branch_Name",
group = GroupName.Customer, order = 7000,
prominent = true, gridOrder = 7000)
protected String branchName;
@ElementCollection
@CollectionTable(name = "BG_SUBJECTS")
@Column(name = "SUBJECT_OF_INTEREST")
protected List<String> subjectsOfInterest = new ArrayList();
@Column(name = "CUSTOMER_NUMBER")
@AdminPresentation(friendlyName = "CustomerImpl_PhoneNumber",
group = GroupName.Customer, order = 8000,
prominent = true, gridOrder = 8000)
protected String customerPhoneNumber;
@OneToMany(mappedBy = "customer", targetEntity = ProgramImpl.class, cascade = { CascadeType.ALL })
@Cascade(value = { org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
@AdminPresentationCollection(friendlyName = "Programs", order = 9000, addType = AddMethodType.PERSIST)
protected List<Program> programs = new ArrayList<>();
public List<Program> getPrograms() {
return programs;
}
public void setPrograms(List<Program> programs) {
this.programs = programs;
}
public String getCustomerPhoneNumber() {
return customerPhoneNumber;
}
public void setCustomerPhoneNumber(String customerPhoneNumber) {
this.customerPhoneNumber = customerPhoneNumber;
}
public List<String> getSubjectsOfInterest() {
return subjectsOfInterest;
}
public void setSubjectsOfInterest(List<String> subjectsOfInterest) {
this.subjectsOfInterest = subjectsOfInterest;
}
public String getBranchName() {
return branchName;
}
public void setBranchName(String branchName) {
this.branchName = branchName;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public String getCollegeName() {
return collegeName;
}
public void setCollegeName(String collegeName) {
this.collegeName = collegeName;
}
}
|
package topics.multithread;
import java.util.LinkedList;
public class Storage {
// �ֿ����洢��
private final int MAX_SIZE = 100;
// �ֿ�洢������
private LinkedList<Object> list = new LinkedList<Object>();
// ����num����Ʒ
public void produce(int num) {
// ͬ�������
synchronized (list) {
// ����ֿ�ʣ����������
while (list.size() + num > MAX_SIZE) {
System.out.println("��Ҫ�����IJ�Ʒ������:" + num + "/t���������:"
+ list.size() + "/t��ʱ����ִ����������!");
try {
// �������������㣬��������
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// ����������������£�����num����Ʒ
for (int i = 1; i <= num; ++i) {
list.add(new Object());
}
System.out.println("���Ѿ�������Ʒ����:" + num + "/t���ֲִ���Ϊ��:" + list.size());
list.notifyAll();
}
}
// ����num����Ʒ
public void consume(int num) {
// ͬ�������
synchronized (list) {
// ����ֿ�洢������
while (list.size() < num) {
System.out.println("��Ҫ���ѵIJ�Ʒ������:" + num + "/t���������:"
+ list.size() + "/t��ʱ����ִ����������!");
try {
// �������������㣬��������
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// ����������������£�����num����Ʒ
for (int i = 1; i <= num; ++i) {
list.remove();
}
System.out.println("���Ѿ����Ѳ�Ʒ����:" + num + "/t���ֲִ���Ϊ��:" + list.size());
list.notifyAll();
}
}
// get/set����
public LinkedList<Object> getList() {
return list;
}
public void setList(LinkedList<Object> list) {
this.list = list;
}
public int getMAX_SIZE() {
return MAX_SIZE;
}
}
|
package com.smxknife.springdatajpa.model.grid;
import com.smxknife.springdatajpa.model.Item;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
/**
* @author smxknife
* 2020/11/19
*/
@Getter
@Setter
@Entity
@Table(name = "tb_grid")
public class Grid extends Item {
@Column(length = 20)
private String no;
@Column(length = 50)
private String name;
private String description;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private Grid parent;
}
|
/*
* Copyright (C) 2015 Miquel Sas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.qtplaf.library.trading.chart.parameters;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Stroke;
import com.qtplaf.library.trading.chart.CursorType;
/**
* Cursor plot parameters.
*
* @author Miquel Sas
*/
public class CursorPlotParameters {
/**
* ChartCross cursor circle radius.
*/
private int chartCrossCursorCircleRadius = 0;
/**
* Chart plotter: cross cursor color.
*/
private Color chartCrossCursorColor = Color.GRAY;
/**
* Chart plotter: cross cursor height.
*/
private int chartCrossCursorHeight = -1;
/**
* Chart plotter: cross cursor stroke.
*/
private Stroke chartCrossCursorStroke = new BasicStroke(
0.0f,
BasicStroke.CAP_ROUND,
BasicStroke.JOIN_MITER,
3.0f,
new float[] { 3.0f },
0.0f);
/**
* Chart plotter: cross cursor width.
*/
private int chartCrossCursorWidth = -1;
/**
* The cursot type to use.
*/
private CursorType chartCursorType = CursorType.ChartCross;
/**
* An integer that denotes the system cursor that applies, default is cross hair..
*/
private int chartCursorTypePredefined = Cursor.DEFAULT_CURSOR;
/**
* Constructor assigning the parent chart.
*/
public CursorPlotParameters() {
super();
}
/**
* Returns the cross cursor circle radius.
*
* @return The cross cursor circle radius.
*/
public int getChartCrossCursorCircleRadius() {
return chartCrossCursorCircleRadius;
}
/**
* Returns the cross cursor color.
*
* @return The cross cursor color.
*/
public Color getChartCrossCursorColor() {
return chartCrossCursorColor;
}
/**
* Returns the cross cursor height.
*
* @return The cross cursor height.
*/
public int getChartCrossCursorHeight() {
return chartCrossCursorHeight;
}
/**
* Returns the cross cursor stroke.
*
* @return The cross cursor stroke.
*/
public Stroke getChartCrossCursorStroke() {
return chartCrossCursorStroke;
}
/**
* Returns the cross cursor width.
*
* @return The cross cursor width.
*/
public int getChartCrossCursorWidth() {
return chartCrossCursorWidth;
}
/**
* Returns the default chart cursor type to use.
*
* @return The default chart cursor type to use.
*/
public CursorType getChartCursorType() {
return chartCursorType;
}
/**
* Returns the chart cursor type predefined.
*
* @return The chart cursor type predefined.
*/
public int getChartCursorTypePredefined() {
return chartCursorTypePredefined;
}
/**
* Sets the cross cursor circle radius, less or equal zero paints no circle.
*
* @param chartCrossCursorCircleRadius The cross cursor circle radius, less or equal zero paints no circle.
*/
public void setChartCrossCursorCircleRadius(int chartCrossCursorCircleRadius) {
this.chartCrossCursorCircleRadius = chartCrossCursorCircleRadius;
}
/**
* Sets the cross cursor color.
*
* @param chartCrossCursorColor The cross cursor color.
*/
public void setChartCrossCursorColor(Color chartCrossCursorColor) {
this.chartCrossCursorColor = chartCrossCursorColor;
}
/**
* Sets the cross cursor height.
*
* @param chartCrossCursorHeight The cross cursor height.
*/
public void setChartCrossCursorHeight(int chartCrossCursorHeight) {
this.chartCrossCursorHeight = chartCrossCursorHeight;
}
/**
* Sets the cross cursor stroke.
*
* @param chartCrossCursorStroke The cross cursor stroke.
*/
public void setChartCrossCursorStroke(Stroke chartCrossCursorStroke) {
this.chartCrossCursorStroke = chartCrossCursorStroke;
}
/**
* Sets the cross cursor width.
*
* @param chartCrossCursorWidth The cross cursor width.
*/
public void setChartCrossCursorWidth(int chartCrossCursorWidth) {
this.chartCrossCursorWidth = chartCrossCursorWidth;
}
/**
* Sets the default cursor type to use.
*
* @param chartCursorType The default cursor type to use.
*/
public void setChartCursorType(CursorType chartCursorType) {
this.chartCursorType = chartCursorType;
}
/**
* Sets the chart cursor type.
*
* @param chartCursorTypePredefined The chart cursor type.
*/
public void setChartCursorTypePredefined(int chartCursorTypePredefined) {
if (chartCursorTypePredefined < -1 || chartCursorTypePredefined > Cursor.MOVE_CURSOR) {
throw new IllegalArgumentException("Illegal cursor type");
}
this.chartCursorTypePredefined = chartCursorTypePredefined;
}
}
|
package it.polimi.ingsw.GC_21.CLIENT;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import it.polimi.ingsw.GC_21.VIEW.ActionInput;
import it.polimi.ingsw.GC_21.VIEW.InitGameInput;
import it.polimi.ingsw.GC_21.VIEW.InputForm;
public class CheckColorMessage extends MessageToClient implements Callable<InputForm> {
private boolean host;
private boolean possibleStartGame;
private Object LOCK;
private InitialTimerThread timerThread;
public CheckColorMessage(boolean result, String description, boolean host) {
super(result, false, description);
this.host = host;
this.possibleStartGame = false;
}
public CheckColorMessage(boolean result, boolean waiting, String description, boolean host, boolean possibleStartGame) {
super(result, waiting, description);
this.host = host;
this.possibleStartGame = possibleStartGame;
}
@Override
public InputForm executeCLI(Object LOCK) throws InterruptedException {
this.LOCK = LOCK;
if (result) {
if (host && possibleStartGame) {
ExecutorService poolExecutorService = Executors.newFixedThreadPool(1);
Future future = poolExecutorService.submit(this);
timerThread = new InitialTimerThread(client, future);
timerThread.start();
try {
return (InputForm) future.get();
} catch (InterruptedException | ExecutionException | CancellationException e) {
System.out.println("Time exceeded, Now starts the game");
return null;
}
}
System.out.println(description);
return null;
}
else {
System.out.println(description);
CheckLobbyMessage retryLobbyMessage = new CheckLobbyMessage(this, true, "Retry");
return retryLobbyMessage.executeCLI(LOCK);
}
}
@Override
public InputForm call() throws Exception {
inputForm = new InitGameInput();
inputForm = super.executeCLI(LOCK);
timerThread.interrupt();
return inputForm;
}
public boolean isHost() {
return host;
}
public void setHost(boolean host) {
this.host = host;
}
}
|
public class Main {
public static void main(String[] arg) {
// int dimension = 19;
// new GameWindow(dimension);
new StartingWindow();
}
}
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Map;
import java.util.TreeMap;
/**
* Creates a html file that generates a Tag Cloud containing given amount of
* words.
*
* @author Taha Topiwala
* @author Jacob Ruth
* @author Gautham Sivakumar
*
*/
public final class TagCloud {
/**
* Minimum frequency of the words.
*/
private static int minFrequency = 0;
/**
* Maximum frequency of the words.
*/
private static int maxFrequency = 0;
/**
* Maximum font size for displaying.
*/
public static final int MAX_FONT_SIZE = 48;
/**
* Minimum font size for displaying.
*/
public static final int MIN_FONT_SIZE = 11;
/**
* Integer Comparator.
*/
private static class MaxValueComparator implements Comparator<String> {
/**
*
*/
Map<String, Integer> base;
/**
*
*/
MaxValueComparator(Map<String, Integer> base) {
this.base = base;
}
@Override
public int compare(String one, String two) {
int firstDig = this.base.get(one);
int secondDig = this.base.get(two);
if (secondDig > firstDig) {
return 1;
} else if (firstDig > secondDig) {
return -1;
} else {
return two.compareTo(one);
}
}
}
/**
* .
*/
private TagCloud() {
}
/**
* Seperators.
*/
private static final String SEPERATORS = " \t\n\r =+-_)(*&^%$#@!/'\","
+ ".:;{}[]<>?|~`";
/**
*
* Creates the header for the HTML output file.
*
* @param inputFile
* name of the input file
*
* @param outputFile
* name of the output file
*
* @param outputHTML
* output stream
*
* @param numberOfWords
* number of words the user wants to search through
*
*/
private static void createHeaderHTML(PrintWriter outputHTML,
String inputFile, String outputFile, int numberOfWords) {
outputHTML.println("<html>");
outputHTML.println("<head>");
outputHTML.print("<title>");
outputHTML.print("Top " + numberOfWords + " words in " + inputFile);
outputHTML.println("</title>");
outputHTML.println("<link href=\"tagcloud.css\""
+ " rel=\"stylesheet\" type=\"text/css\">");
outputHTML.println("</head>");
outputHTML.println("<body>");
outputHTML.println("<h2>Top " + numberOfWords + " words in " + inputFile
+ "</h2>");
outputHTML.println("<hr>");
outputHTML.println("<div class=\"cdiv\">");
outputHTML.println("<p class=\"cbox\">");
}
/**
* Creates the body of the HTML file.
*
* @param fontDeque
* Deque containing font sizes
*
* @param wordCount
* Alphabetized map containing words and their counts
*
* @param outputHTML
* Output stream
*/
private static void createBodyHTML(Deque<Integer> fontDeque,
Map<String, Integer> wordCount, PrintWriter outputHTML) {
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
outputHTML.println("<span style=\"cursor:default;\" class=\"f"
+ fontDeque.removeFirst() + "\" title=\"count: "
+ entry.getValue() + "\">" + entry.getKey() + "</span>");
}
}
/**
* Creates the footer of the html document.
*
* @param outputHTML
* file output stream
* @requires outputHTML is open
*
* @ensures completed html file footer
*
*/
private static void createFooterHTML(PrintWriter outputHTML) {
outputHTML.println("</p>");
outputHTML.println("</div>");
outputHTML.println("</body>");
outputHTML.println("</html>");
}
/**
* Counts the number of times a word is used within the given text.
*
* @param in
* input stream
*
* @return map containing words and their counts
*
* @ensures {@code Returned map contains words and their counts provided
* by input file}
*
*/
private static Map<String, Integer> createMapOfWords(BufferedReader in) {
Map<String, Integer> countOfWords = new TreeMap<String, Integer>();
String inPart = "";
try {
inPart = in.readLine();
} catch (IOException e) {
System.err.println("Error reading input file: " + e);
return countOfWords;
}
int location = 0, counter;
try {
while (inPart != null) {
while (location < inPart.length()) {
String word = nextWordOrSeparator(inPart, location,
SEPERATORS);
if (!SEPERATORS
.contains(Character.toString(word.charAt(0)))) {
if (!countOfWords.containsKey(word)) {
countOfWords.put(word, 1);
} else {
counter = countOfWords.get(word);
counter++;
countOfWords.remove(word);
countOfWords.put(word, counter);
}
}
location += word.length();
}
location = 0;
inPart = in.readLine();
}
} catch (IOException e) {
System.err
.println("Error reading line from file input stream: " + e);
return countOfWords;
}
return countOfWords;
}
/**
* Returns the first "word" (maximal length string of characters not in
* {@code SEPARATORS}) or "separator string" (maximal length string of
* characters in {@code SEPARATORS}) in the given {@code text} starting at
* the given {@code position}.
*
* @param text
* the {@code String} from which to get the word or separator
* string
* @param position
* the starting index
* @return the first word or separator string found in {@code text} starting
* at index {@code position}
* @requires 0 <= position < |text|
* @ensures
*
* <pre>
* nextWordOrSeparator =
* text[position, position + |nextWordOrSeparator|) and
* if entries(text[position, position + 1)) intersection entries(SEPARATORS) = {}
* then
* entries(nextWordOrSeparator) intersection entries(SEPARATORS) = {} and
* (position + |nextWordOrSeparator| = |text| or
* entries(text[position, position + |nextWordOrSeparator| + 1))
* intersection entries(SEPARATORS) /= {})
* else
* entries(nextWordOrSeparator) is subset of entries(SEPARATORS) and
* (position + |nextWordOrSeparator| = |text| or
* entries(text[position, position + |nextWordOrSeparator| + 1))
* is not subset of entries(SEPARATORS))
* </pre>
*/
private static String nextWordOrSeparator(String text, int position,
String separators) {
assert text != null : "Violation of: text is not null";
assert separators != null : "Violation of: separators is not null";
assert 0 <= position : "Violation of: 0 <= position";
assert position < text.length() : "Violation of: position < |text|";
String ans = "";
int i = position;
if (!separators.contains(Character.toString(text.charAt(position)))) {
while (i < text.length() && !separators
.contains(Character.toString(text.charAt(i)))) {
i++;
}
ans = text.substring(position, i);
} else {
while (i < text.length() && separators
.contains(Character.toString(text.charAt(i)))) {
i++;
}
ans = text.substring(position, i);
}
return ans.toLowerCase();
}
/**
*
* Sorts the top n words in alphabetical order and creates a deque
* containing the font sizes for each word.
*
* @param wordCount
* map that contains the words and their respective count values
*
* @param numberOfWords
* The value that the user input at the beginning for how many
* words to look through from top
* @return wordFontDeque A deque containing the font sizes for the sorted
* word map
*
*/
private static Deque<Integer> getFontDeque(Map<String, Integer> wordCount,
int numberOfWords) {
TreeMap<String, Integer> comp = new TreeMap<String, Integer>(wordCount);
MaxValueComparator maxComp = new MaxValueComparator(comp);
Deque<Integer> wordFontDeque = new LinkedList<Integer>();
TreeMap<String, Integer> sortedMapByValue = new TreeMap<String, Integer>(
maxComp);
sortedMapByValue.putAll(wordCount);
wordCount.clear();
for (int i = 0; i < numberOfWords && !sortedMapByValue.isEmpty(); i++) {
if (maxFrequency == 0) {
maxFrequency = sortedMapByValue.firstEntry().getValue();
}
if (i == numberOfWords - 1) {
minFrequency = sortedMapByValue.firstEntry().getValue();
}
wordCount.put(sortedMapByValue.firstEntry().getKey(),
sortedMapByValue.firstEntry().getValue());
sortedMapByValue.remove(sortedMapByValue.firstKey());
}
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
wordFontDeque.add(calculateFontSize(entry.getValue()));
}
return wordFontDeque;
}
/**
* Calculate the font size given a count.
*
* @param count
* the frequency of the word
* @return the font size for the word of {@code frequency}.
*/
private static int calculateFontSize(int count) {
if (count == minFrequency) {
return MIN_FONT_SIZE;
} else if (count == maxFrequency) {
return MAX_FONT_SIZE;
} else {
return (int) ((MAX_FONT_SIZE - MIN_FONT_SIZE)
* (count - minFrequency)
/ (double) (maxFrequency - minFrequency)) + MIN_FONT_SIZE;
}
}
/**
* Main method.
*
* @param args
*/
public static void main(String[] args) {
BufferedReader inputFile = null;
PrintWriter outputHTML = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
//Ask for input file name
System.out.print("Enter a valid input file: ");
String directory = "";
try {
directory = in.readLine();
} catch (IOException out) {
System.err.println("Error with creating input stream : " + out);
return;
}
try {
inputFile = new BufferedReader(new FileReader(directory));
} catch (IOException out) {
System.err.println(
"Error with opening input stream from file: " + out);
return;
}
System.out.println();
//Ask for output file name
String outputFileName = "";
System.out.print("Enter a valid output file: ");
try {
outputFileName = in.readLine();
} catch (IOException out) {
System.err.println("Error with creating input stream: " + out);
return;
}
try {
outputHTML = new PrintWriter(
new BufferedWriter(new FileWriter(outputFileName)));
} catch (IOException out) {
System.err.println("Error creating output stream to file: " + out);
return;
}
System.out.println();
int numberOfWords = 0;
System.out.print("Number of words to generate: ");
try {
numberOfWords = Integer.parseInt(in.readLine());
} catch (NumberFormatException out) {
System.err.println("Error with int value " + out);
} catch (IOException out) {
System.err.println("Error with input: " + out);
return;
}
createHeaderHTML(outputHTML, directory, outputFileName, numberOfWords);
Map<String, Integer> wordCountInText = createMapOfWords(inputFile);
Deque<Integer> fontDeque = getFontDeque(wordCountInText, numberOfWords);
createBodyHTML(fontDeque, wordCountInText, outputHTML);
createFooterHTML(outputHTML);
try {
in.close();
inputFile.close();
System.out.close();
outputHTML.close();
} catch (IOException out) {
System.err.println("Error closing streams: " + out);
return;
}
}
}
|
package com.penzias.entity;
import java.math.BigDecimal;
import java.util.Date;
/**
* 描述:人群体格检查<br/>
* 作者:Bob <br/>
* 修改日期:2015年12月11日 - 上午11:35:34<br/>
* E-mail: sireezhang@163.com<br/>
*/
public class PhysiqueExamInfo {
private Integer physiqueexamid;
private Integer crowdid;
//检查时间
private Date examtime;
//身高(cm)
private BigDecimal height;
//体重(kg)
private BigDecimal weight;
//根据高和体重自动生成(kg/m2)
private BigDecimal bmi;
//腰围
private BigDecimal waist;
//第一次,收缩压SBP(mmHg)
private BigDecimal onesbp;
//第一次,舒张压SBP(mmHg)
private BigDecimal onedbp;
//第一次脉搏(次/分)
private Integer onepulse;
private BigDecimal twosbp;
private BigDecimal twodbp;
private Integer twopulse;
//心脏杂音(0:无;1:有)
private String cardiacsouffle;
//心律(0:整齐;1:不齐)
private String rhythm;
private String flag;
public Integer getPhysiqueexamid() {
return physiqueexamid;
}
public void setPhysiqueexamid(Integer physiqueexamid) {
this.physiqueexamid = physiqueexamid;
}
public Integer getCrowdid() {
return crowdid;
}
public void setCrowdid(Integer crowdid) {
this.crowdid = crowdid;
}
public Date getExamtime() {
return examtime;
}
public void setExamtime(Date examtime) {
this.examtime = examtime;
}
public BigDecimal getHeight() {
return height;
}
public void setHeight(BigDecimal height) {
this.height = height;
}
public BigDecimal getWeight() {
return weight;
}
public void setWeight(BigDecimal weight) {
this.weight = weight;
}
public BigDecimal getBmi() {
return bmi;
}
public void setBmi(BigDecimal bmi) {
this.bmi = bmi;
}
public BigDecimal getWaist() {
return waist;
}
public void setWaist(BigDecimal waist) {
this.waist = waist;
}
public BigDecimal getOnesbp() {
return onesbp;
}
public void setOnesbp(BigDecimal onesbp) {
this.onesbp = onesbp;
}
public BigDecimal getOnedbp() {
return onedbp;
}
public void setOnedbp(BigDecimal onedbp) {
this.onedbp = onedbp;
}
public Integer getOnepulse() {
return onepulse;
}
public void setOnepulse(Integer onepulse) {
this.onepulse = onepulse;
}
public BigDecimal getTwosbp() {
return twosbp;
}
public void setTwosbp(BigDecimal twosbp) {
this.twosbp = twosbp;
}
public BigDecimal getTwodbp() {
return twodbp;
}
public void setTwodbp(BigDecimal twodbp) {
this.twodbp = twodbp;
}
public Integer getTwopulse() {
return twopulse;
}
public void setTwopulse(Integer twopulse) {
this.twopulse = twopulse;
}
public String getCardiacsouffle() {
return cardiacsouffle;
}
public void setCardiacsouffle(String cardiacsouffle) {
this.cardiacsouffle = cardiacsouffle;
}
public String getRhythm() {
return rhythm;
}
public void setRhythm(String rhythm) {
this.rhythm = rhythm;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
}
|
package com.abhi.dao.user;
import java.util.List;
import com.abhi.entity.UserDetails;
public interface UserDAO
{
/**
* Add User
* @param user
*/
public void addUser(UserDetails user);
/**
* Delete User
* @param userId
*/
public void deleteUser(Integer userId);
/**
* Find by Id..
* @return
*/
public UserDetails findByUserId(Integer userId);
/**
* Find by Id..
* @return
*/
public List<UserDetails> findByEmailId(String emailId);
}
|
/*
final关键字
final标记的类不能被继承
final标记的方法不能被子类重写
final变量(成员变量+局部变量)即成为常量,名称大写,且只能被赋值一次
此常量在哪里赋值:①此常量不能使用默认初始化 ②可以显式的赋值、代码块、构造器。
练习:TestFinal.java
*/
package day3;
public class TestFinal {
public static void main(String[] args) {
}
}
class A1{
final int i1 = 90;
final double PI;
final String NAME;
// 代码块中初始化final常量
{
PI = 3.14;
}
// 构造器中初始化final常量(final常量只能被赋值一次)
public A1(double pI, String nAME) {
super();
// // The final field PI may already have been assigned
// PI = pI;
NAME = nAME;
}
final public void a1() {
}
}
//class B1 extends A1 {
// /*
// 子类中不能修改父类的final修饰的方法
// Multiple markers at this line
// - overrides day3.A1.a1
// - Cannot override the final method
// */
// public void a1() {
//
// }
//}
final class A{
}
//// he type B cannot subclass the final class A
//class B extends A{
//
//}
|
package com.tencent.mm.plugin.luckymoney.sns;
import android.view.View;
import android.view.View.OnClickListener;
class SnsLuckyMoneyPrepareUI$9 implements OnClickListener {
final /* synthetic */ SnsLuckyMoneyPrepareUI kTy;
SnsLuckyMoneyPrepareUI$9(SnsLuckyMoneyPrepareUI snsLuckyMoneyPrepareUI) {
this.kTy = snsLuckyMoneyPrepareUI;
}
public final void onClick(View view) {
SnsLuckyMoneyPrepareUI.l(this.kTy).setVisibility(8);
SnsLuckyMoneyPrepareUI.o(this.kTy);
}
}
|
package ru.mail.chatserver.server;
import org.reflections.Reflections;
import ru.mail.chatserver.server.handlers.AbstractHandler;
import ru.mail.chatserver.server.handlers.Handler;
import java.nio.channels.SelectionKey;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* User: v.kolosov
* Date: 11.09.12
* Time: 13:15
* Singleton
*/
public class ServerData {
private static ServerData ourInstance = new ServerData();
private Map<Integer ,SelectionKey> connectionsMap;
private Map<SelectionKey ,Integer> changeInterestOpsRequestsMap;
private Map<String, Class<? extends Handler>> commandsMap;
private ServerData() {
connectionsMap = new ConcurrentHashMap<Integer, SelectionKey>();
changeInterestOpsRequestsMap = new ConcurrentHashMap<SelectionKey, Integer>();
commandsMap = new ConcurrentHashMap<String, Class<? extends Handler>>();
}
/**
*
* Get all handlers classes using Reflections lib and register it in commands list
Must be called before any server activity, because scan for command handlers takes some time
*/
public void scanCommandHandlers() {
Reflections reflections = new Reflections("ru.mail.chatserver.server.handlers");
Set<Class<? extends AbstractHandler>> handlerClasses = reflections.getSubTypesOf(AbstractHandler.class);
for(Class<? extends Handler> handlerClass : handlerClasses) {
try {
handlerClass.newInstance().registerCommand();
} catch (InstantiationException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}
public void requestChangeOps(SelectionKey key, Integer ops) {
changeInterestOpsRequestsMap.put(key, ops);
}
public static ServerData getInstance() {
return ourInstance;
}
public Map<Integer, SelectionKey> getConnectionsMap() {
return connectionsMap;
}
public Map<SelectionKey, Integer> getChangeInterestOpsRequestsMap() {
return changeInterestOpsRequestsMap;
}
public Map<String, Class<? extends Handler>> getCommandsMap() {
return commandsMap;
}
}
|
package com.mikerussell.conjugation;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
/**
* Created by mrussell on 7/2/16.
*/
public class Conjugation {
public HashMap<Integer, String> persons = new HashMap<Integer, String>();
Logger log = Logger.getLogger(Conjugation.class);
String selectedPerson = "";
Verb verb;
public Conjugation(Verb verb) {
persons.put(1, "I");
persons.put(2, "You");
persons.put(3, "He");
persons.put(4, "She");
persons.put(5, "It");
persons.put(6, "We");
persons.put(7, "You guys");
persons.put(8, "They");
this.verb = verb;
Random rand = new Random();
Integer selectedPersonVal = rand.nextInt(8);
selectedPerson = persons.get(selectedPersonVal);
}
public HashMap<Integer, String> getPersons() {
return persons;
}
public void setPersons(HashMap<Integer, String> persons) {
this.persons = persons;
}
public String getPresentSimple() {
if(selectedPerson.toLowerCase().equals("He".toLowerCase()) || selectedPerson.toLowerCase().equals("She".toLowerCase()) || selectedPerson.toLowerCase().equals("It".toLowerCase())){
return selectedPerson + " " + getVerb().getThirdPersonSingular();
}
if(verb.getBaseForm().toLowerCase().equals("be")){
if(selectedPerson.toLowerCase().equals("i")){
return selectedPerson + " " + "am";
}
else{
return selectedPerson + " " + "are";
}
}
return selectedPerson + " " + getVerb().getBaseForm();
}
public String getPresentProgressive(){
Verb be = new Verb("be", "is", "was", "been", "being",true);
Conjugation auxiliaryVerb = new Conjugation(be);
auxiliaryVerb.setSelectedPerson(selectedPerson);
return auxiliaryVerb.getPresentSimple() + " " + verb.getPresentParticiple();
}
public String getSelectedPerson() {
return selectedPerson;
}
public void setSelectedPerson(String selectedPerson) {
this.selectedPerson = selectedPerson;
}
public void setSelectedPerson(int selectedPersonKey) {
this.selectedPerson = getPersons().get(selectedPersonKey);
}
public Verb getVerb() {
return verb;
}
public void setVerb(Verb verb) {
this.verb = verb;
}
public String getPastSimple() {
if(verb.getBaseForm().toLowerCase().equals("be") && (
getSelectedPerson().toLowerCase().equals("he") ||
getSelectedPerson().toLowerCase().equals("she") ||
getSelectedPerson().toLowerCase().equals("it") ||
getSelectedPerson().toLowerCase().equals("i")
)){
return selectedPerson + " " + "was";
}
return selectedPerson + " " + getVerb().getPastSimple();
}
public String getPastProgressive(){
Verb be = new Verb("be", "is", "were", "been", "being",true);
Conjugation auxiliaryVerb = new Conjugation(be);
auxiliaryVerb.setSelectedPerson(selectedPerson);
return auxiliaryVerb.getPastSimple() + " " + verb.getPresentParticiple();
}
public String getInfinitive(){
return "to " + verb.getBaseForm();
}
public String getFutureGoingTo() {
Verb go = new Verb("go", "goes", "went", "gone", "going",true);
Conjugation aux = new Conjugation(go);
aux.setSelectedPerson(selectedPerson);
return aux.getPresentProgressive() + " " + aux.getInfinitive();
}
public String getFutureWill() {
return selectedPerson + " will " + getVerb().getBaseForm();
}
public String getPresentPerfect() {
Verb have = new Verb("have", "has", "had", "had", "having",true);
Conjugation aux = new Conjugation(have);
aux.setSelectedPerson(selectedPerson);
return aux.getPresentSimple() + " " + verb.getPastParticiple();
}
public String getPastPerfect() {
Verb have = new Verb("have", "has", "had", "had", "having",true);
Conjugation aux = new Conjugation(have);
aux.setSelectedPerson(selectedPerson);
return aux.getPastSimple() + " " + verb.getPastParticiple();
}
public String getFuturePerfect() {
Verb have = new Verb("have", "has", "had", "had", "having",true);
Conjugation aux = new Conjugation(have);
aux.setSelectedPerson(selectedPerson);
return aux.getFutureWill() + " " + verb.getPastParticiple();
}
public String getFutureProgressive() {
Verb be = new Verb("be", "is", "were", "been", "being",true);
Conjugation auxiliaryVerb = new Conjugation(be);
auxiliaryVerb.setSelectedPerson(selectedPerson);
return auxiliaryVerb.getFutureWill() + " " + verb.getPresentParticiple();
}
public String getFuturePerfectProgressive() {
Verb be = new Verb("be", "is", "were", "been", "being",true);
Conjugation auxiliaryVerb = new Conjugation(be);
auxiliaryVerb.setSelectedPerson(selectedPerson);
return auxiliaryVerb.getFuturePerfect() + " " + verb.getPresentParticiple();
}
public String getPresentPerfectProgressive() {
Verb be = new Verb("be", "is", "were", "been", "being", true);
Conjugation auxiliaryVerb = new Conjugation(be);
auxiliaryVerb.setSelectedPerson(selectedPerson);
return auxiliaryVerb.getPresentPerfect() + " " + verb.getPresentParticiple();
}
public String getPastPerfectProgressive() {
Verb be = new Verb("be", "is", "were", "been", "being", true);
Conjugation auxiliaryVerb = new Conjugation(be);
auxiliaryVerb.setSelectedPerson(selectedPerson);
return auxiliaryVerb.getPastPerfect() + " " + verb.getPresentParticiple();
}
public List<String> getTenses() {
List<String> tensez = new ArrayList<String>();
for (Method method : this.getClass().getDeclaredMethods()) {
if (method.getName().startsWith("get")
&& (method.getName().toLowerCase().contains("past") ||
method.getName().toLowerCase().contains("present") ||
method.getName().toLowerCase().contains("future"))) {
String tenseInPascalCase = method.getName().substring(3);
String formattedString = StringUtils.join(
StringUtils.splitByCharacterTypeCamelCase(tenseInPascalCase),
' '
);
tenseInPascalCase = null;
log.debug(formattedString);
tensez.add(formattedString);
formattedString = null;
}
}
java.util.Collections.sort(tensez);
return tensez;
}
}
|
package fel_2;
public class Main {
public static void main(String[] args) {
StackAggregation stack1 = new StackAggregation(5);
for (int i = 0; i < 10; ++i) {
// boxing: int --> Integer
stack1.push(i);
}
System.out.print("StackAggregation : ");
while (!stack1.isEmpty()) {
System.out.print(stack1.top() + " ");
stack1.pop();
}
System.out.println();
StackInheritance stack2 = new StackInheritance(5);
for (int i = 0; i < 10; ++i) {
stack2.push(i);
}
stack2.remove(1);
System.out.print("StackInheritance : ");
while (!stack2.isEmpty()) {
System.out.print(stack2.top() + " ");
stack2.pop();
}
System.out.println();
}
}
|
package com.shiku.mianshi.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import cn.xyz.commons.utils.ReqUtil;
import cn.xyz.commons.utils.StringUtil;
import cn.xyz.commons.vo.JSONMessage;
import cn.xyz.commons.vo.ResultInfo;
import cn.xyz.mianshi.service.RoomManager;
import cn.xyz.mianshi.service.UserManager;
import cn.xyz.mianshi.vo.InviteListVo;
import cn.xyz.mianshi.vo.Room;
import cn.xyz.mianshi.vo.User;
import cn.xyz.mianshi.vo.Room.Member;
import net.spy.memcached.KeyUtil;
import com.alibaba.fastjson.JSON;
/**
* 群组接口
*
* @author Administrator
*
*/
@RestController
@RequestMapping("/room")
public class RoomController {
@Resource(name = RoomManager.BEAN_ID)
private RoomManager roomManager;
@Autowired
private UserManager userManager;
/**
* 新增房间
*
* @param room
* @param text
* @return
*/
@RequestMapping("/add")
public JSONMessage add(@ModelAttribute Room room, @RequestParam(defaultValue = "") String text) {
List<Integer> idList = StringUtil.isEmpty(text) ? null : JSON.parseArray(text, Integer.class);
if (roomManager.exisname(room.getName()) == null) {
Object data = roomManager.add(userManager.getUser(ReqUtil.getUserId()), room, idList);
return JSONMessage.success(null, data);
} else {
return JSONMessage.failure("房间名已经存在");
}
}
/**
* 删除房间
*
* @param roomId
* @return
*/
@RequestMapping("/delete")
public JSONMessage delete(@RequestParam String roomId) {
roomManager.delete(userManager.getUser(ReqUtil.getUserId()), new ObjectId(roomId));
return JSONMessage.success();
}
/**
* 更新房间
*
* @param roomId
* @param roomName
* @param notice
* @param desc
* @return
*/
@RequestMapping("/update")
public JSONMessage update(@RequestParam String roomId, @RequestParam(defaultValue = "") String roomName,
@RequestParam(defaultValue = "") String notice, @RequestParam(defaultValue = "") String desc,
@RequestParam(defaultValue = "-1") int showRead) {
// if (StringUtil.isEmpty(roomName) && StringUtil.isEmpty(notice)) {
//
// } else {
// User user = userManager.getUser(ReqUtil.getUserId());
// roomManager.update(user, new ObjectId(roomId), roomName, notice,
// desc);
// }
// if(roomManager.exisname(roomName)==null){
Map<String, Integer> data = new HashMap<>();
data.put("showRead", showRead);
User user = userManager.getUser(ReqUtil.getUserId());
boolean result = roomManager.update(user, new ObjectId(roomId), roomName, notice, desc, showRead);
if (result == false) {
return JSONMessage.failure("房间名已经存在");
} else {
return JSONMessage.success(null, data);
}
}
/**
* 根据房间Id获取房间
*
* @param roomId
* @return
*/
@RequestMapping("/get")
public JSONMessage get(@RequestParam String roomId) {
Object data = roomManager.get(new ObjectId(roomId));
return JSONMessage.success(null, data);
}
@GetMapping("/getRoom")
public JSONMessage getRoom(@RequestParam String roomId) {
Object data = roomManager.get(new ObjectId(roomId));
return JSONMessage.success(null, data);
}
/**
* 获取房间列表(按创建时间排序)
*
* @param pageIndex
* @param pageSize
* @return
*/
@RequestMapping("/list")
public JSONMessage list(@RequestParam(defaultValue = "0") int pageIndex,
@RequestParam(defaultValue = "10") int pageSize, @RequestParam(defaultValue = "") String roomName) {
Object data = roomManager.selectList(pageIndex, pageSize, roomName);
return JSONMessage.success(null, data);
}
/**
*
* <p>Title: updateMember</p>
* <p>Description: 添加群成员</p>
* @param roomId
* @param member
* @param text
* @return
*/
@RequestMapping("/member/update")
public JSONMessage updateMember(@RequestParam String roomId, @ModelAttribute Member member,
@RequestParam(defaultValue = "") String text) {
List<Integer> idList = StringUtil.isEmpty(text) ? null : JSON.parseArray(text, Integer.class);
User user = userManager.getUser(ReqUtil.getUserId());
if (null == idList)
roomManager.updateMember(user, new ObjectId(roomId), member);
else
roomManager.updateMember(user, new ObjectId(roomId), idList);
return JSONMessage.success();
}
// 退出群组
@RequestMapping("/member/delete")
public JSONMessage deleteMember(@RequestParam String roomId, @RequestParam int userId) {
User user = userManager.getUser(ReqUtil.getUserId());
roomManager.deleteMember(user, new ObjectId(roomId), userId);
return JSONMessage.success();
}
// 设置/取消群消息免打扰
@RequestMapping("/member/setOfflineNoPushMsg")
public JSONMessage setOfflineNoPushMsg(@RequestParam int offlineNoPushMsg, @RequestParam String roomId,
@RequestParam int userId) {
roomManager.Memberset(offlineNoPushMsg, new ObjectId(roomId), userId);
return JSONMessage.success();
}
@RequestMapping("/member/get")
public JSONMessage getMember(@RequestParam String roomId, @RequestParam int userId) {
Member data = roomManager.getMember(new ObjectId(roomId), userId);
if (data == null) {
return null;
}
if (StringUtil.isEmpty(data.getCall()))
data.setCall(roomManager.getCall(new ObjectId(roomId)));
if (StringUtil.isEmpty(data.getVideoMeetingNo()))
data.setVideoMeetingNo(roomManager.getVideoMeetingNo(new ObjectId(roomId)));
return JSONMessage.success(null, data);
}
@RequestMapping("/member/list")
public JSONMessage getMemberList(@RequestParam String roomId, @RequestParam(defaultValue = "") String keyword) {
Object data = roomManager.getMemberList(new ObjectId(roomId), keyword);
return JSONMessage.success(null, data);
}
// 获取房间
@RequestMapping("/get/call")
public JSONMessage getRoomCall(@RequestParam String roomId) {
Object data = roomManager.getCall(new ObjectId(roomId));
return JSONMessage.success(null, data);
}
//加入房间
@RequestMapping("/join")
public JSONMessage join(@RequestParam String roomId, @RequestParam(defaultValue = "2") int type) {
roomManager.join(ReqUtil.getUserId(), new ObjectId(roomId), type);
return JSONMessage.success();
}
@RequestMapping("/leave")
public JSONMessage leave(@RequestParam String roomId) {
roomManager.leave(ReqUtil.getUserId(), new ObjectId(roomId));
return JSONMessage.success();
}
@RequestMapping("/list/his")
public JSONMessage historyList(@RequestParam(defaultValue = "0") int type,
@RequestParam(defaultValue = "0") int pageIndex, @RequestParam(defaultValue = "10") int pageSize) {
// Object data = roomManager.selectHistoryList(ReqUtil.getUserId(),
// type);
Object data = roomManager.selectHistoryList(ReqUtil.getUserId(), type, pageIndex, pageSize);
return JSONMessage.success(null, data);
}
// 设置/取消管理员
@RequestMapping("/set/admin")
public JSONMessage setAdmin(@RequestParam String roomId, @RequestParam int touserId, @RequestParam int type) {
roomManager.setAdmin(new ObjectId(roomId), touserId, type, ReqUtil.getUserId());
return JSONMessage.success();
}
// 添加(群共享)
@RequestMapping("/add/share")
public JSONMessage Addshare(@RequestParam ObjectId roomId, @RequestParam int type, @RequestParam long size,
@RequestParam int userId, @RequestParam String url, @RequestParam String name) {
Object data = roomManager.Addshare(roomId, size, type, userId, url, name);
return JSONMessage.success(null, data);
}
// 查询(群共享)
@RequestMapping("/share/find")
public JSONMessage findShare(@RequestParam ObjectId roomId, @RequestParam(defaultValue = "0") int pageIndex,
@RequestParam(defaultValue = "0") long time, @RequestParam(defaultValue = "0") int userId,
@RequestParam(defaultValue = "10") int pageSize) {
Object data = roomManager.findShare(roomId, time, userId, pageIndex, pageSize);
return JSONMessage.success(null, data);
}
@RequestMapping("/share/get")
public JSONMessage getShare(@RequestParam ObjectId roomId, @RequestParam ObjectId shareId) {
Object data = roomManager.getShare(roomId, shareId);
return JSONMessage.success(null, data);
}
// 删除
@RequestMapping("/share/delete")
public JSONMessage deleteShare(@RequestParam String roomId, @RequestParam String shareId,
@RequestParam int userId) {
roomManager.deleteShare(new ObjectId(roomId), new ObjectId(shareId), userId);
return JSONMessage.success();
}
/**
*
* <p>
* Title: transfer
* </p>
* <p>
* Description:群主 转让
* </p>
*
* @param roomId
* @param touserId
* @param type
* @return
*/
@RequestMapping("/owner/transfer")
public JSONMessage transfer(@RequestParam ObjectId roomId, @RequestParam int userId, @RequestParam int toUserId) {
roomManager.transfer(roomId, userId, toUserId);
return JSONMessage.success();
}
/**
* Title: askOwner
* Description: 请求推送给群主消息,申请入群
* @param roomId
* @param member
* @param text
* @return
*/
@RequestMapping("/member/askOwner")
public JSONMessage askOwner(@RequestParam ObjectId roomId, @RequestParam(defaultValue = "") String userIds,@RequestParam(defaultValue = "")String msg) {
List<Integer> idList = StringUtil.isEmpty(userIds) ? null : JSON.parseArray(userIds, Integer.class);
User user = userManager.getUser(ReqUtil.getUserId());
if (null == idList)
return JSONMessage.failure("选择用户为空");
else
roomManager.askOwner(user, roomId, idList,msg);
return JSONMessage.success();
}
/**
*
* <p>Title: turnIsNeedVerification</p>
* <p>Description: 修改加群是否需要管理员认证</p>
* @param roomId
* @param isNeedVerification
* @return
*/
@RequestMapping("/turnIsNeedVerification")
public JSONMessage turnIsNeedVerification(@RequestParam ObjectId roomId, @RequestParam(defaultValue = "0") Integer isNeedVerification) {
roomManager.turnIsNeedVerification(roomId,isNeedVerification);
return JSONMessage.success();
}
@RequestMapping("/turnIsAllowAddFriend")
public JSONMessage turnIsAllowAddFriend(@RequestParam ObjectId roomId, @RequestParam(defaultValue = "0") Integer isAllowAddFriend) {
roomManager.turnIsAllowAddFriend(roomId,isAllowAddFriend);
return JSONMessage.success();
}
/**
*
* <p>Title: addMember</p>
* <p>Description: 由群主拉人进群</p>
* @param roomId
* @param addUserId
* @param Inviter
* @return
*/
@RequestMapping("/member/addMember")
public JSONMessage addMember(@RequestParam ObjectId roomId,@RequestParam(defaultValue = "") String userIds,@RequestParam Integer Inviter) {
/*List<Integer> idList = StringUtil.isEmpty(userIds) ? null : JSON.parseArray(userIds, Integer.class);
User user = userManager.getUser(ReqUtil.getUserId());
if (null == idList||idList.isEmpty())
return JSONMessage.failure("添加用户为空");
else //房主 //房间号 //被添加的用户 //邀请者
roomManager.addMember(user, roomId, idList,Inviter);
return JSONMessage.success();*/
List<Integer> idList = StringUtil.isEmpty(userIds) ? null : JSON.parseArray(userIds, Integer.class);
//User user = userManager.getUser(ReqUtil.getUserId());
User user =userManager.getUser(Inviter);
if (null == idList)
return JSONMessage.failure("添加用户为空");
else
roomManager.updateMember(user,roomId, idList);
return JSONMessage.success();
}
/**
*
* <p>Title: getUserInfo</p>
* <p>Description: 根据用户id列表获取用户的昵称列表</p>
* @param userId
* @param userIds
* @return
*/
@GetMapping("/member/getUserInfo")
public ResultInfo<InviteListVo> getUserInfo(Integer userId,@RequestParam(defaultValue = "") String userIds){
List<Integer> idList = StringUtil.isEmpty(userIds) ? null : JSON.parseArray(userIds, Integer.class);
ResultInfo<InviteListVo> result=userManager.getUserInfo(userId,idList);
return result;
}
}
|
package com.jhy.reduce;
import com.jhy.entity.ConsumptionLevel;
import com.jhy.util.HBaseUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.flink.api.common.functions.GroupReduceFunction;
import org.apache.flink.util.Collector;
import java.util.Iterator;
/**
* 消费水平Reduce
* [接收数据-->统计消费金额-->判断消费水平-->打标签]
*
* Created by JHy on 2019/5/17.
*/
public class ConsumptionLevelReduce implements GroupReduceFunction<ConsumptionLevel,ConsumptionLevel> {
@Override
public void reduce(Iterable<ConsumptionLevel> iterable, Collector<ConsumptionLevel> collector) throws Exception {
// 1-- 遍历输入输入,统计消费总金额
Iterator<ConsumptionLevel> iterator = iterable.iterator();
int sum = 0;
double totalamount = 0d;
String userid = "-1";
while(iterator.hasNext()){
ConsumptionLevel comsumptionLevel = iterator.next();
userid = comsumptionLevel.getUserid();
String amounttotal = comsumptionLevel.getAmounttotal();
double amountdouble = Double.valueOf(amounttotal);
totalamount += amountdouble;
sum++;
}
// 2-- 计算平均消费,判断消费水平
double avramout = totalamount/sum; // 高消费5000 中等消费 1000 低消费 小于1000
String flag = "low";
if(avramout >=1000 && avramout <5000){
flag = "middle";
}else if(avramout >= 5000){
flag = "high";
}
// 3-- 构造输出数据
String tablename = "userflaginfo";
String rowkey = userid+"";
String famliyname = "consumerinfo";
String colum = "consumptionlevel";
// 3--1 获取库里已有的消费水平标签值
String data = HBaseUtils.getdata(tablename,rowkey,famliyname,colum);
if(StringUtils.isBlank(data)){
// 3--2 HBase里消费水平为空,构造消费水平对象并返回
ConsumptionLevel consumptionLevel = new ConsumptionLevel();
consumptionLevel.setConsumptiontype(flag);
consumptionLevel.setCount(1L);
consumptionLevel.setGroupfield("==consumptionLevelfinal=="+flag);
collector.collect(consumptionLevel);
}else if(!data.equals(flag)){
// 3--3 判断HBase里之前的消费水平标签是否和现在的一致,不一致将之前的减掉,并设置新增的
ConsumptionLevel consumptionLevel1 = new ConsumptionLevel();
consumptionLevel1.setConsumptiontype(data);
consumptionLevel1.setCount(-1L);
consumptionLevel1.setGroupfield("==consumptionLevelfinal=="+data);
ConsumptionLevel consumptionLevel2 = new ConsumptionLevel();
consumptionLevel2.setConsumptiontype(flag);
consumptionLevel2.setCount(1L);
consumptionLevel2.setGroupfield("==consumptionLevelfinal=="+flag);
collector.collect(consumptionLevel1);
collector.collect(consumptionLevel2);
}
// 4-- 给用户打消费水平标签
HBaseUtils.putdata(tablename,rowkey,famliyname,colum,flag);
}
}
|
package com.paytechnologies.util;
import java.util.ArrayList;
import java.util.HashMap;
import com.paytechnologies.DTO.NavDrawerItems;
import com.paytechnologies.cloudacar.Benifits;
import com.paytechnologies.cloudacar.BookTrip;
import com.paytechnologies.cloudacar.CallToBook;
import com.paytechnologies.cloudacar.DashBoard;
import com.paytechnologies.cloudacar.Features;
import com.paytechnologies.cloudacar.LiveTripUsersList;
import com.paytechnologies.cloudacar.Login;
import com.paytechnologies.cloudacar.ManageTrip;
import com.paytechnologies.cloudacar.MyPlan;
import com.paytechnologies.cloudacar.MyTestActivity;
import com.paytechnologies.cloudacar.NewModifiedCacPlans;
import com.paytechnologies.cloudacar.R;
import com.paytechnologies.cloudacar.TripPendingRequest;
import com.paytechnologies.cloudacar.TripsDashboard;
import com.paytechnologies.cloudacar.adapters.AdapterListForNavGrid;
import com.paytechnologies.cloudacar.interfaces.INavigationHandler;
import com.paytechnologies.saveme.SaveMe;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.net.Uri;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class NavigationDrawerSetup implements OnItemClickListener {
private GridView mDrawerList;
private DrawerLayout mDrawer;
private CustomActionBarDrawerToggle mDrawerToggle;
private String[] menuItems;
private ActionBar actionBar;
private String title;
private Activity activity;
private INavigationHandler handler;
private AdapterListForNavGrid adapterPayout, adapterHowItWorks,
adapterTrips;
private ArrayList<NavDrawerItems> lstPayout, lstTrips, lstHowItWorks;
private NavDrawerItems prevDrawerSelected;
private String intentData;
private int currentCategory, categoryIndex;
private SessionManager session;
private Boolean isSubscribed;
private View drawerLayout;
private String TAG = "NavigationDrawerSetup";
public NavigationDrawerSetup(Activity activity, ActionBar actionBar,
GridView mDrawerList, DrawerLayout mDrawer, String title,
View drawerLayout, TextView txtView, ImageView imgView) {
this.activity = activity;
this.actionBar = actionBar;
this.mDrawerList = mDrawerList;
this.mDrawer = mDrawer;
this.title = title;
this.drawerLayout = drawerLayout;
session = new SessionManager(this.activity);
HashMap<String, String> user = session.getSubscribed();
isSubscribed = user.get(SessionManager.KEY_SUBSCRIBED)
.equalsIgnoreCase("true");
user = session.getUserDetails();
if (txtView != null) {
//LCH: txtView.setText(user.get("email").toUpperCase() + " " + user.get("lastname").toUpperCase());
String lastname = user.get(SessionManager.KEY_LASTNaME);
if(lastname==null) lastname="";
String email = user.get(SessionManager.KEY_EMAIL);
if (email==null) email = "";
txtView.setText(email.toUpperCase() + " " + lastname.toUpperCase());
}
}
public void setNavigationHandler(INavigationHandler handler) {
this.handler = handler;
}
public void setIntentExtra(String intentData) {
this.intentData = intentData;
}
public void setCurrentCategoryAndPosition(int category, int position) {
currentCategory = category;
categoryIndex = position;
}
public void InitializeDrawer() {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerToggle = new CustomActionBarDrawerToggle(activity, mDrawer);
mDrawer.setDrawerListener(mDrawerToggle);
mDrawerList.setOnItemClickListener(this);
}
public void CloseDrawer(View v) {
mDrawer.closeDrawer(v);
}
public void OpenDrawer(View v) {
mDrawer.openDrawer(v);
}
public CustomActionBarDrawerToggle getDrawerToggle() {
return mDrawerToggle;
}
public void LoadHowItWorks() {
Log.d (TAG, "######################## NavDrawerSetup: LoadHowItWorks ()");
if (adapterHowItWorks == null) {
IntializeAdapterHowItWorks();
}
mDrawerList.setAdapter(adapterHowItWorks);
}
public void LoadTrips() {
if (adapterTrips == null) {
IntializeAdapterTrips();
}
mDrawerList.setAdapter(adapterTrips);
}
public void LoadPayout() {
if (adapterPayout == null) {
IntializeAdapterPayout();
}
mDrawerList.setAdapter(adapterPayout);
}
private void IntializeAdapterPayout() {
String[] arrayItems = activity.getResources().getStringArray(
R.array.array_payout);
TypedArray arrayIconItems = activity.getResources().obtainTypedArray(
R.array.array_iconspayout);
TypedArray arraySelectedIconItems = activity.getResources()
.obtainTypedArray(R.array.array_selected_iconspayout);
lstPayout = new ArrayList<NavDrawerItems>();
for (int i = 0; i < arrayItems.length; i++) {
NavDrawerItems items = new NavDrawerItems();
items.setId(i);
items.setCategory(Constants.CATEGORY_PAYOUT);
items.setItemName(arrayItems[i]);
items.setItemName(arrayItems[i]);
items.setIcon(arrayIconItems.getResourceId(i, 0));
items.setSelectedIcon(arraySelectedIconItems.getResourceId(i, 0));
items.setPressesIcon(arraySelectedIconItems.getResourceId(i, 0));
lstPayout.add(items);
}
arrayIconItems.recycle();
arraySelectedIconItems.recycle();
adapterPayout = new AdapterListForNavGrid(activity, lstPayout);
}
private void IntializeAdapterTrips() {
String[] arrayItems = activity.getResources().getStringArray(
R.array.array_trips);
TypedArray arrayIconItems = activity.getResources().obtainTypedArray(
R.array.array_iconstrips);
TypedArray arraySelectedIconItems = activity.getResources()
.obtainTypedArray(R.array.array_selected_iconstrips);
lstTrips = new ArrayList<NavDrawerItems>();
for (int i = 0; i < arrayItems.length; i++) {
NavDrawerItems items = new NavDrawerItems();
items.setId(i);
items.setCategory(Constants.CATEGORY_TRIPS);
items.setItemName(arrayItems[i]);
items.setIcon(arrayIconItems.getResourceId(i, 0));
items.setSelectedIcon(arraySelectedIconItems.getResourceId(i, 0));
items.setPressesIcon(arraySelectedIconItems.getResourceId(i, 0));
lstTrips.add(items);
}
arrayIconItems.recycle();
arraySelectedIconItems.recycle();
adapterTrips = new AdapterListForNavGrid(activity, lstTrips);
}
private void IntializeAdapterHowItWorks() {
String[] arrayItems = activity.getResources().getStringArray(
R.array.array_howitworks);
TypedArray arrayIconItems = activity.getResources().obtainTypedArray(
R.array.array_iconshowitworks);
TypedArray arraySelectedIconItems = activity.getResources()
.obtainTypedArray(R.array.array_selected_iconshowitworks);
lstHowItWorks = new ArrayList<NavDrawerItems>();
for (int i = 0; i < arrayItems.length; i++) {
NavDrawerItems items = new NavDrawerItems();
items.setId(i);
items.setCategory(Constants.CATEGORY_HOWITWORKS);
items.setItemName(arrayItems[i]);
items.setIcon(arrayIconItems.getResourceId(i, 0));
items.setSelectedIcon(arraySelectedIconItems.getResourceId(i, 0));
items.setPressesIcon(arraySelectedIconItems.getResourceId(i, 0));
lstHowItWorks.add(items);
}
arrayIconItems.recycle();
arraySelectedIconItems.recycle();
adapterHowItWorks = new AdapterListForNavGrid(activity, lstHowItWorks);
//Log.d (TAG, "################## adapterHowItWorks.getcount="+adapterHowItWorks.getCount());
}
public class CustomActionBarDrawerToggle extends ActionBarDrawerToggle {
public CustomActionBarDrawerToggle(Activity mActivity,
DrawerLayout mDrawerLayout) {
super(mActivity, mDrawerLayout, R.drawable.ic_drawer,
R.string.ns_menu_open, R.string.ns_menu_close);
}
@Override
public void onDrawerClosed(View view) {
actionBar.setTitle(title);
// invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
handler.InvalidateMenu();
}
@Override
public void onDrawerOpened(View drawerView) {
actionBar.setTitle("Cloud A Car");
// invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
handler.InvalidateMenu();
}
}
@Override
public void onItemClick(AdapterView<?> parent, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
AdapterListForNavGrid adapter = (AdapterListForNavGrid) parent
.getAdapter();
if (prevDrawerSelected != null) {
prevDrawerSelected.setSelected(false);
}
adapter.getItem(position).setSelected(true);
adapter.notifyDataSetChanged();
prevDrawerSelected = (NavDrawerItems) adapter.getItem(position);
selectRespectiveDashboardPages(prevDrawerSelected.getCategory(),
position);
}
private void selectRespectiveDashboardPages(int category, int position) {
if (currentCategory == category && categoryIndex == position) {
AdapterListForNavGrid adapter = (AdapterListForNavGrid) mDrawerList
.getAdapter();
((NavDrawerItems) adapter.getItem(position)).setSelected(true);
adapter.notifyDataSetChanged();
CloseDrawer(drawerLayout);
return;
}
Log.d (TAG, "#################### selectRespectiveDashboardPages: category=["+category+"] position=["+position+"]");
switch (position) {
case 0:
if (category == Constants.CATEGORY_HOWITWORKS) {
Intent aboutUs = new Intent(activity, MyTestActivity.class);
if (intentData != null)
aboutUs.putExtra("fromIntent", intentData);
activity.startActivity(aboutUs);
activity.overridePendingTransition(R.anim.fade_in,
R.anim.fade_out);
} else if (category == Constants.CATEGORY_TRIPS) {
Intent inbox = new Intent(activity, TripsDashboard.class);
activity.startActivity(inbox);
activity.overridePendingTransition(R.anim.fade_in,
R.anim.fade_out);
} else if (category == Constants.CATEGORY_PAYOUT) {
Intent myPlans = new Intent(activity, NewModifiedCacPlans.class);
activity.startActivity(myPlans);
activity.overridePendingTransition(R.anim.fade_in,
R.anim.fade_out);
}
activity.finish();
break;
case 1:
if (category == Constants.CATEGORY_HOWITWORKS) {
Intent callToBook = new Intent(activity, CallToBook.class);
callToBook.putExtra("fromIntent", intentData);
if (intentData != null)
activity.startActivity(callToBook);
activity.overridePendingTransition(R.anim.fade_in,
R.anim.fade_out);
} else if (category == Constants.CATEGORY_TRIPS) {
Intent inbox = new Intent(activity, ManageTrip.class);
activity.startActivity(inbox);
activity.overridePendingTransition(R.anim.fade_in,
R.anim.fade_out);
} else if (category == Constants.CATEGORY_PAYOUT) {
Intent myPlans = new Intent(activity, MyPlan.class);
activity.startActivity(myPlans);
activity.overridePendingTransition(R.anim.fade_in,
R.anim.fade_out);
}
activity.finish();
break;
case 2:
if (category == Constants.CATEGORY_HOWITWORKS) {
Intent benifits = new Intent(activity, Benifits.class);
if (intentData != null)
benifits.putExtra("fromIntent", intentData);
activity.startActivity(benifits);
activity.overridePendingTransition(R.anim.fade_in,
R.anim.fade_out);
activity.finish();
} else if (category == Constants.CATEGORY_TRIPS) {
Intent inbox = new Intent(activity, BookTrip.class);
activity.startActivity(inbox);
activity.overridePendingTransition(R.anim.fade_in,
R.anim.fade_out);
activity.finish();
} else if (category == Constants.CATEGORY_PAYOUT) {
SaveMe saveme = new SaveMe(activity);
}
break;
case 3:
if (category == Constants.CATEGORY_HOWITWORKS) {
Intent features = new Intent(activity, Features.class);
if (intentData != null)
features.putExtra("fromIntent", intentData);
activity.startActivity(features);
activity.overridePendingTransition(R.anim.fade_in,
R.anim.fade_out);
} else if (category == Constants.CATEGORY_TRIPS) {
Intent inbox = new Intent(activity, TripPendingRequest.class);
activity.startActivity(inbox);
activity.overridePendingTransition(R.anim.fade_in,
R.anim.fade_out);
} else if (category == Constants.CATEGORY_PAYOUT) {
}
activity.finish();
break;
case 4:
if (category == Constants.CATEGORY_HOWITWORKS) {
String mailTo = "contact@cloudacar.com";
Intent email_intent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts("mailto", mailTo, null));
email_intent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"CAC Comments");
email_intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
activity.startActivity(Intent.createChooser(email_intent,
"Send email..."));
} else if (category == Constants.CATEGORY_TRIPS) {
Intent inbox = new Intent(activity, LiveTripUsersList.class);
activity.startActivity(inbox);
activity.overridePendingTransition(R.anim.fade_in,
R.anim.fade_out);
activity.finish();
} else if (category == Constants.CATEGORY_PAYOUT) {
}
break;
case 5:
if (category == Constants.CATEGORY_HOWITWORKS) {
Intent login = new Intent(activity, Login.class);
activity.startActivity(login);
activity.overridePendingTransition(R.anim.fade_in,
R.anim.fade_out);
session.ClearPreferences();
} else if (category == Constants.CATEGORY_TRIPS) {
Intent inbox = new Intent(activity, DashBoard.class);
activity.startActivity(inbox);
activity.overridePendingTransition(R.anim.fade_in,
R.anim.fade_out);
} else if (category == Constants.CATEGORY_PAYOUT) {
}
activity.finish();
break;
}
CloseDrawer(drawerLayout);
}
}
|
class QueueEmptyException extends Exception{
}
class Node <T>{
T data;
Node<T> next;
public Node(T data) {
this.data=data;
}
}
public class queueUsingLL<T> {
Node<T> front;
Node<T> rear;
int size;
public queueUsingLL() {
front=null;
rear=null;
size=0;
}
public void enqueue(T data) {
Node<T> newNode=new Node(data);
if(front==null&&rear==null) {
front=newNode;
rear=newNode;
}else {
rear.next=newNode;
rear=newNode;
}
size++;
}
public T dequeue() throws QueueEmptyException{
if(size==0) {
throw new QueueEmptyException();
}
T temp=front.data;
front=front.next;
size--;
return temp;
}
public boolean isEmpty(){
if(size==0)
return true;
else
return false;
}
public int size() {
return size;
}
public T front() throws QueueEmptyException{
if(size==0) {
throw new QueueEmptyException();
}
return front.data;
}
}
|
package com.oxycab.provider.ui.activity.regsiter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.accountkit.Account;
import com.facebook.accountkit.AccountKit;
import com.facebook.accountkit.AccountKitCallback;
import com.facebook.accountkit.AccountKitError;
import com.facebook.accountkit.AccountKitLoginResult;
import com.facebook.accountkit.PhoneNumber;
import com.facebook.accountkit.ui.AccountKitActivity;
import com.facebook.accountkit.ui.AccountKitConfiguration;
import com.facebook.accountkit.ui.LoginType;
import com.google.gson.Gson;
import com.hbb20.CountryCodePicker;
import com.oxycab.provider.BuildConfig;
import com.oxycab.provider.R;
import com.oxycab.provider.base.BaseActivity;
import com.oxycab.provider.common.CommonValidation;
import com.oxycab.provider.common.SharedHelper;
import com.oxycab.provider.data.network.model.MyOTP;
import com.oxycab.provider.ui.activity.otp.OTPActivity;
import com.oxycab.provider.ui.activity.regsiter.details.RegisterExtraDetailsActivity;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;
import okhttp3.RequestBody;
import retrofit2.HttpException;
import static com.oxycab.provider.common.Constants.APP_REQUEST_CODE;
public class RegisterActivity extends BaseActivity implements RegisterIView {
private static final String TAG = "RegisterActivity";
private static final int PICK_OTP_VERIFY = 222;
@BindView(R.id.back)
ImageView back;
@BindView(R.id.title)
TextView title;
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.txtFirstName)
EditText txtFirstName;
@BindView(R.id.txtLastName)
EditText txtLastName;
@BindView(R.id.txtPhoneNumber)
EditText txtPhoneNumber;
@BindView(R.id.mobile_layout)
LinearLayout mobile_layout;
@BindView(R.id.registration_layout)
LinearLayout registration_layout;
@BindView(R.id.dial_code)
CountryCodePicker dialCode;
RegisterPresenter<RegisterActivity> presenter = new RegisterPresenter<>();
@BindView(R.id.ll_name)
LinearLayout llName;
@BindView(R.id.ll_content)
LinearLayout llContent;
@Override
public int getLayoutId() {
return R.layout.activity_register;
}
@Override
public void initView() {
ButterKnife.bind(this);
presenter.attachView(this);
registration_layout.setVisibility(View.GONE);
}
void register() {
//All the String parameters, you have to put like
}
@OnClick({R.id.next, R.id.back})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.next:
if (mobile_layout.getVisibility() == View.VISIBLE) {
if (txtPhoneNumber.getText().toString().length() > 9 && CommonValidation.Validation(txtPhoneNumber.getText().toString().trim())) {
Toasty.error(this, getString(R.string.invalid_mobile), Toast.LENGTH_SHORT, true).show();
return;
} else if (CommonValidation.isValidPhone(txtPhoneNumber.getText().toString().trim())) {
Toasty.error(this, getString(R.string.validmobile), Toast.LENGTH_SHORT, true).show();
return;
}
presenter.verifyMobileAlreadyExits(txtPhoneNumber.getText().toString());
} else {
saveUser();
}
break;
case R.id.back:
onBackPressed();
break;
}
}
private void saveUser() {
if (registration_layout.getVisibility() == View.VISIBLE) {
if (CommonValidation.Validation(txtFirstName.getText().toString().trim())) {
Toasty.error(this, getString(R.string.invalid_first_name), Toast.LENGTH_SHORT, true).show();
txtFirstName.requestFocus();
return;
} else if (CommonValidation.Validation(txtLastName.getText().toString().trim())) {
Toasty.error(this, getString(R.string.invalid_last_name), Toast.LENGTH_SHORT, true).show();
txtLastName.requestFocus();
return;
} else {
Map<String, String> map = new HashMap<>();
map.put("first_name", txtFirstName.getText().toString());
map.put("last_name", txtLastName.getText().toString());
map.put("mobile", txtPhoneNumber.getText().toString().substring(txtPhoneNumber.getText().toString().length() - 10));
map.put("password", "123456");
map.put("password_confirmation", "123456");
map.put("device_token", SharedHelper.getKeyFCM(this, "device_token"));
map.put("device_id", SharedHelper.getKeyFCM(this, "device_id"));
map.put("device_type", BuildConfig.DEVICE_TYPE);
map.put("country_code", String.valueOf(dialCode.getSelectedCountryCodeWithPlus()));
Intent intent = new Intent(activity(), RegisterExtraDetailsActivity.class);
intent.putExtra("data", new Gson().toJson(map));
startActivity(intent);
// llName.setVisibility(View.GONE);
// llExtra.setVisibility(View.VISIBLE);
}
}
// else if (llExtra.getVisibility() == View.VISIBLE) {
// if (TextUtils.isEmpty(etAadhar.getText().toString())) {
// Toasty.error(this, getString(R.string.aadhar_validation), Toast.LENGTH_SHORT, true).show();
// return;
// } else {
// llExtra.setVisibility(View.GONE);
// llEmergency.setVisibility(View.VISIBLE);
// }
// } else if (llEmergency.getVisibility() == View.VISIBLE) {
// if (contact1.getText().toString().isEmpty()) {
// contact1.setError("Required");
// return;
// } else {
// register();
// }
// }
}
@Override
public void onSuccess(MyOTP otp) {
Intent intent = new Intent(activity(), OTPActivity.class);
intent.putExtra("mobile", txtPhoneNumber.getText().toString());
intent.putExtra("country_code", String.valueOf(dialCode.getSelectedCountryCodeWithPlus()));
intent.putExtra("otp", String.valueOf(otp.getOtp()));
startActivityForResult(intent, PICK_OTP_VERIFY);
}
@Override
public void onError(Throwable e) {
hideLoading();
HttpException error = (HttpException) e;
try {
String errorBody = error.response().errorBody().string();
JSONObject jObjError = new JSONObject(errorBody);
if (jObjError.has("email"))
Toast.makeText(getApplicationContext(), jObjError.optString("email"), Toast.LENGTH_LONG).show();
if (jObjError.has("error"))
Toast.makeText(getApplicationContext(), jObjError.optString("error"), Toast.LENGTH_LONG).show();
if (jObjError.has("message"))
Toast.makeText(getApplicationContext(), jObjError.optString("error"), Toast.LENGTH_LONG).show();
if (jObjError.has("mobile"))
Toast.makeText(activity(), jObjError.optString("mobile"), Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show();
} catch (Exception e1) {
Toast.makeText(getApplicationContext(), e1.getMessage(), Toast.LENGTH_LONG).show();
}
}
public void fbPhoneLogin() {
final Intent intent = new Intent(this, AccountKitActivity.class);
AccountKitConfiguration.AccountKitConfigurationBuilder configurationBuilder =
new AccountKitConfiguration.AccountKitConfigurationBuilder(
LoginType.PHONE,
AccountKitActivity.ResponseType.TOKEN);
configurationBuilder.setReadPhoneStateEnabled(true);
configurationBuilder.setReceiveSMS(true);
intent.putExtra(
AccountKitActivity.ACCOUNT_KIT_ACTIVITY_CONFIGURATION,
configurationBuilder.build());
startActivityForResult(intent, APP_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == APP_REQUEST_CODE && data != null) {
AccountKitLoginResult loginResult = data.getParcelableExtra(AccountKitLoginResult.RESULT_KEY);
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
@Override
public void onSuccess(Account account) {
Log.d("AccountKit", "onSuccess: Account Kit" + AccountKit.getCurrentAccessToken().getToken());
if (AccountKit.getCurrentAccessToken().getToken() != null) {
//SharedHelper.putKey(RegisterActivity.this, "account_kit_token", AccountKit.getCurrentAccessToken().getToken());
PhoneNumber phoneNumber = account.getPhoneNumber();
SharedHelper.putKey(RegisterActivity.this, "dial_code", phoneNumber.getCountryCode());
SharedHelper.putKey(RegisterActivity.this, "mobile", phoneNumber.getPhoneNumber());
txtPhoneNumber.setText(SharedHelper.getKey(RegisterActivity.this, "mobile"));
register();
}
}
@Override
public void onError(AccountKitError accountKitError) {
Log.e("AccountKit", "onError: Account Kit" + accountKitError);
}
});
} else if (requestCode == PICK_OTP_VERIFY && resultCode == Activity.RESULT_OK) {
registration_layout.setVisibility(View.VISIBLE);
mobile_layout.setVisibility(View.GONE);
Toast.makeText(this, "Thanks your Mobile is successfully verified, Please enter your First Name and Last Name to create your account", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: add setContentView(...) invocation
ButterKnife.bind(this);
}
}
|
package Übungsblatt2;
public class Transporter {
public void beam(String person, String from, String to, boolean urgent)throws TransporterMalfunctionException
{
if(urgent==true)
{
double zufall=Math.random()*100;
System.out.println(zufall);
if(zufall<70)
{
throw new TransporterMalfunctionException("beamen nix gut");
}
else
{
System.out.println("beamen von "+from+ " nach "+to+" erfogreich");
}
}
}
public void shutdown()
{
System.out.println("schalting ab");
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.webbeans.test.component.inject.parametrized;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class BoundedTypeVariableComponent<T extends Number,Y>
{
public Collection<T> field1;
public Collection<? extends Number> field2;
public Collection<Y> field3;
public Collection<List<?>> field4;
public Collection field5;
public Map<Y, Y> field6;
public Collection<Object> field7;
}
|
package com.dinu;
public class CeilingOfANumber {
public static void main(String[] args) {
int[] arr = {2, 4, 6, 7, 10, 30, 56, 102};
int target = 7;
int ans = search(arr, target);
System.out.println(ans);
}
static int search(int[] arr,int target)
{
int start=0;
int end=arr.length;
//what if the target number is greater than the greatest number
if(target>arr[end-1])
return -1;
while(start<=end) {
int mid=start+(end-start)/2;
if(target>arr[mid])
start=mid+1;
else if(target<arr[mid])
end=mid-1;
else if(target==arr[mid])
return mid;
}
return start;
}
}
|
package template.adapter;
import lombok.Data;
@Data
public class PlanetResponse {
private String planetId;
private String planetName;
}
|
package org.sweatshop.alphabet.health;
import com.codahale.metrics.health.HealthCheck;
import lombok.EqualsAndHashCode;
import lombok.Value;
@Value
@EqualsAndHashCode(callSuper=false)
public class AlphabetHealthCheck extends HealthCheck {
String template;
@Override
protected Result check() throws Exception {
final String saying = String.format(template, "TEST");
if (saying.indexOf("TEST") == -1) {
return Result.unhealthy("template doesn't include a name");
} else {
return Result.healthy();
}
}
}
|
package services.chat;
import model.chat.ChatMessage;
import javax.json.Json;
import javax.json.JsonObject;
import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;
import java.io.StringReader;
import java.sql.Timestamp;
public class ChatMessageDecoder implements Decoder.Text<ChatMessage> {
@Override
public void init(final EndpointConfig config) {
}
@Override
public void destroy() {
}
@Override
public ChatMessage decode(final String textMessage) throws DecodeException {
ChatMessage chatMessage = new ChatMessage();
JsonObject jsonMessage = Json.createReader(new StringReader(textMessage)).readObject();
chatMessage.setMessage(jsonMessage.getString("message"));
chatMessage.setSender(jsonMessage.getString("sender"));
chatMessage.setReceiver(jsonMessage.getString("receiver"));
chatMessage.setReceived(new Timestamp(System.currentTimeMillis()));
return chatMessage;
}
@Override
public boolean willDecode(final String s) {
return true;
}
}
|
package nbody_pap1314.simulator;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import nbody_pap1314.model.interfaces.IGalaxy;
import nbody_pap1314.view.interfaces.IGalaxyView;
/**
* The implementation of the graphics update phase.
*
* @author Michele Braccini
* @author Alessandro Fantini
*/
public class Galaxy2DUpdaterService {
protected final ExecutorService executor; /* fixed thread pool */
protected final IGalaxyView galaxy2D; /* graphical representation of the galaxy */
public Galaxy2DUpdaterService(ExecutorService executor, IGalaxyView galaxy2D) {
this.executor = executor;
this.galaxy2D = galaxy2D;
}
public long updateBodies2D(IGalaxy galaxy) {
long executionTime = System.currentTimeMillis();
CountDownLatch doneSignal = new CountDownLatch(galaxy.getNumBodies());
assert doneSignal.getCount() == galaxy.getNumBodies() : "error while initializing CountDownLatch"; /* JPF */
for(int bodyIndex = 0; bodyIndex < galaxy.getNumBodies(); bodyIndex++) {
try {
executor.submit(new UpdateBody2DTask(galaxy, bodyIndex, galaxy2D, doneSignal));
} catch (Exception e) {
log(e.getClass().getSimpleName() + ": " + bodyIndex);
continue;
}
}
try {
/* waits for previously submitted tasks to complete execution */
doneSignal.await();
} catch (InterruptedException e) {
log(e.getMessage());
}
assert doneSignal.getCount() == 0 : "CountDownLatch value must be zero"; /* JPF */
galaxy2D.update();
executionTime = System.currentTimeMillis() - executionTime;
return executionTime;
}
private void log(String msg) {
System.out.println("[" + this.getClass().getSimpleName() + "] " + msg);
}
}
|
/*---------------------------------------------------------------------------*/
/**
* @(#)$Id: ProcessUtil.java 7720 2013-07-10 02:46:00Z shiyongping $
* @(#) Implementation file of class ProcessUtil.
* @author sjyao
* (c) PIONEER SUNTEC CORPORATION 2013
* All Rights Reserved.
*/
/*---------------------------------------------------------------------------*/
package hhc.common.utils.stringUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author sjyao
*
*/
public class ProcessUtil {
private static List<Pattern> patterns;
/**
* 初始读取包含去除语义信息的模板文件
*
* @param file
* @throws IOException
* @throws UnsupportedEncodingException
*/
public static void init(String file) throws IOException {
patterns = new ArrayList<Pattern>();
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(file), "UTF-8"));
String line = null;
while ((line = in.readLine()) != null) {
if (line.matches("^$") || line.startsWith("#"))
continue;
String toks = line.trim();
Pattern patt = Pattern.compile(toks);
patterns.add(patt);
}
in.close();
}
/**
* 全角转半角(此函数在CharUtils中已存在)
*
* @param line
* @return line半角转换后的字符串
*/
public static String convertToHalfWidth(String line) {
char[] c = line.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == 12288) {
c[i] = (char) 32;
continue;
}
if (c[i] > 65280 && c[i] < 65375)
c[i] = (char) (c[i] - 65248);
}
String ret = new String(c);
return ret.replace("*", "");
}
private static char[] NUM_BIG = { '一', '二', '三', '四', '五', '六', '七', '八',
'九', '零' };
private static char[] NUM_SMALL = { '1', '2', '3', '4', '5', '6', '7', '8',
'9', '0' };
public static String numConvert(String str) {
for (int i = 0; i < NUM_SMALL.length; i++) {
str = str.replace(NUM_SMALL[i], NUM_BIG[i]);
}
return str;
}
private static char[] SINGS = { '+', '-', '!', ':', '?', '*', '~', '^',
'"', '\\', '(', ')', '[', ']', '{', '}', ' ' };
/**
* 判断字符是否需要转换
*
* @param c
* @return
*/
private static boolean needToConvert(char c) {
for (int i = 0; i < SINGS.length; i++) {
if (SINGS[i] == c)
return true;
}
return false;
}
/**
*
* @param user_query
* @return
*/
public static String normalizat(String user_query) {
String regex = " +";
user_query = user_query.replaceAll(regex, " ").trim();
char[] a = user_query.toCharArray();
char[] b = new char[500];
int i = 0;
for (char c : a) {
if (!needToConvert(c)) {
b[i++] = c;
}
}
String c = new String(b, 0, i);
return c;
}
/**
*
* @param user_query
* @return
*/
public static String preProcess(String user_query) {
String regex = " +";
user_query = user_query.replaceAll(regex, " ").trim();
user_query = user_query.replace("\\*|\\;|\\[|\\]", "");
char[] a = user_query.toCharArray();
char[] b = new char[500];
int i = 0;
for (char c : a) {
if (!needToConvert(c)) {
b[i++] = c;
} else {
b[i++] = '\\';
b[i++] = c;
}
}
String c = new String(b, 0, i);
return c;
}
/**
*
* @param user_query
* @return
*/
public static String preProcess(String user_query, String special_char) {
String regex = " +";
user_query = user_query.replaceAll(regex, " ").trim();
user_query = user_query.replace("\\*|\\;|\\[|\\]", "");
char[] a = user_query.toCharArray();
char[] b = new char[500];
int i = 0;
for (char c : a) {
if (!needToConvert(c) || special_char.contains(String.valueOf(c))) {
b[i++] = c;
} else {
b[i++] = '\\';
b[i++] = c;
}
}
String c = new String(b, 0, i);
return c;
}
public static String process(String query) {
if (null != query) {
if (!query.startsWith("(") && !query.endsWith(")")
&& query.contains(")")) {
query = query.replaceAll("\\(|\\)|(|)", " ").trim();
} else {
query = query.replaceAll("\\(|\\)|(|)", " ").trim();
}
query = query.replaceAll("\"|'|“|”|‘|’|\\[|\\]|\\;|\\*", "");
}
return query;
}
/**
* 计算query中最后一个字符是右括号时,是否为多余字符
*
* @param s
* @param c
* @return 字符串s中字符c的个数
*/
public static int counter(String s, char c) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) {
count++;
}
}
return count;
}
/**
* 去除语义信息
*
* @param query
* @return 返回去除语义信息后的query 注:在与模板中最后一个模板是用于去除query的最后一个不符合要求的字符的
* 对于最后一个字符是右括号并且前面没有与之匹配的左括号的情况做了单独处理
*/
public static String doDrop(String query) {
for (int j = 0; j < patterns.size(); j++) {
Pattern patt = patterns.get(j);
Matcher mat = patt.matcher(query);
if (mat.matches()) {
query = mat.group(1);
}
}
int leftParenthesesCount = counter(query, '(');
int rightParenthesesCount = counter(query, ')');
if (rightParenthesesCount == leftParenthesesCount + 1) {
int length = query.length();
if (query.charAt(length - 1) == ')')
query = query.substring(0, length - 1);
}
return query;
}
/**
* 判断first_string数组中是否包含second_string
*
* @param first_string
* @param second_string
* @return boolean
*/
public static boolean isHave(String[] first_string, String second_string) {
for (int i = 0; i < first_string.length; i++) {
if (first_string[i].equals(second_string)) {
return true;
}
}
return false;
}
}
|
package com.kitware.doc.service;
import java.util.List;
import com.kitware.doc.dao.DocDAO;
import com.kitware.doc.dao.DocDAOOracle;
import com.kitware.doc.vo.DocVO;
public class DocSelectService {
private DocDAO dao = new DocDAOOracle();
public List<DocVO> findIng(String emp_num) throws Exception{
return dao.selectIng(emp_num);
}
public List<DocVO> findOk(String emp_num) throws Exception{
return dao.selectOk(emp_num);
}
}
|
package com.lingnet.vocs.service.statistics;
import com.lingnet.common.service.BaseService;
import com.lingnet.vocs.entity.Annals;
public interface ProvincesArrService extends BaseService<Annals, String>{
}
|
package org.openuri.easypo;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class Main {
// This sample application demonstrates how to unmarshal an instance
// document into a Java content tree and access data contained within it.
public static void main( String[] args ) {
try {
// create a JAXBContext capable of handling classes generated into
// this package
JAXBContext jc = JAXBContext.newInstance( "org.openuri.easypo" );
// create an Unmarshaller
Unmarshaller u = jc.createUnmarshaller();
for( int i=0; i<args.length; i++ ){
// unmarshal a po instance document into a tree of Java content
// objects composed of classes from this package.
PurchaseOrder po = (PurchaseOrder)u.unmarshal(new File(args[i]));
// examine some of the content in the PurchaseOrder
System.out.println( "Ship the following items to: " );
// display the shipping address
Customer customer = po.getCustomer();
displayCustomer( customer );
// display the items
List items = po.getLineItem();
displayItems( items );
}
} catch( JAXBException je ) {
je.printStackTrace();
}
}
public static void displayCustomer( Customer cust ) {
System.out.println( "\t" + cust.getName() );
System.out.println( "\t" + cust.getAddress() + "\n");
}
public static void displayItems( List items ) {
for( Iterator iter = items.iterator(); iter.hasNext(); ) {
LineItem item = (LineItem)iter.next();
System.out.println( "\t" + item.getQuantity() +
" copies of \"" + item.getDescription() +
"\"" );
}
}
}
|
package com.momori.wepic.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.EditText;
import com.momori.wepic.R;
import com.momori.wepic.common.Func;
import com.momori.wepic.common.SFValue;
import com.momori.wepic.controller.post.UserController;
import com.momori.wepic.model.response.ResCommonModel;
import com.momori.wepic.model.response.ResLogInModel;
import com.momori.wepic.model.UserModel;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
public class UserRegActivity extends Activity {
@InjectView(R.id.reg_text_email) EditText textEmail ;
@InjectView(R.id.reg_text_password) EditText textPassword ;
@InjectView(R.id.reg_text_nickname) EditText textNickname ;
UserModel userVo ;
ResCommonModel resCommon ;
ResLogInModel resLogIn ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_reg);
ButterKnife.inject(this);
}
@OnClick(R.id.reg_button_reg)
public void regButtonOnclick() {
Log.i(this.getClass().toString(), "test");
/*
if(Func.checkEmailFormat(textEmail.getText().toString()) == false){
Log.i(this.getClass().toString(), "email format check error");
return;
}
// device 번호 추출
TelephonyManager systemService = (TelephonyManager)getSystemService (Context.TELEPHONY_SERVICE);
String PhoneNumber = systemService.getLine1Number();
PhoneNumber = "0" + PhoneNumber.substring(PhoneNumber.length()-10,PhoneNumber.length());
Log.i(this.getClass().toString(), "phone num : " + PhoneNumber);
// 회원가입
UserModel user = new UserModel(textEmail.getText().toString(), textPassword.getText().toString(), textNickname.getText().toString(), PhoneNumber, systemService.getDeviceId());
UserController usr = new UserController(user);
this.resCommon = usr.registUser();
if(Func.isPostSucc(this.resCommon.getResult()) == true ){ // 회원가입 성공시
Log.i(this.getClass().toString(), "user reg success");
// TODO : 회원 가입 후 정상 가입 여부 출력
// 일단은 회원가입 후 자동 로그인 시킨다!!
this.userVo = new UserModel(textEmail.getText().toString(), textPassword.getText().toString());
this.resLogIn = usr.loginUser();
if(Func.isPostSucc(this.resLogIn.getResult()) == true ){
SFValue pref = SFValue.getInstance();
if(pref.getValue(SFValue.PREF_AUTO_LOGIN, false) == false){
pref.put(SFValue.PREF_USER_EMAIL, this.userVo.getUserEmail());
pref.put(SFValue.PREF_USER_ID , this.userVo.getUserPw ());
pref.put(SFValue.PREF_AUTO_LOGIN, true );
}
Log.i(this.getClass().toString(), "login success");
finish();
Intent intentSubActivity = new Intent(UserRegActivity.this, MainActivity.class);
startActivity(intentSubActivity);
}
}
else {
// TODO : 오류 출력
Log.i(this.getClass().toString(), resCommon.getMsg());
}
*/
}
}
|
package com.example.java.reflect;
import com.example.java.reflect.clazz.GotClassDemo;
import org.junit.Test;
import java.io.Serializable;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
/**
* @date 2018/3/22
*/
public class GenericDemo {
/**
* java的Type接口有4个关于泛型的子接口
* <ul>
* <li>
* 1. {@link java.lang.reflect.GenericArrayType}
* 表示泛型数组类型
* <p>
* </li>
* <li>
* 2. {@link java.lang.reflect.TypeVariable}
* 表示泛型变量 T
* <p>
* </li>
* <li>
* 3. {@link java.lang.reflect.ParameterizedType}
* 表示参数化了的泛型类型 {@code List<String>}
* <p>
* </li>
* <li>
* 4. {@link java.lang.reflect.WildcardType}
* 表示泛型统配符类型 {@code ?}, {@code ? extends Number}, or {@code ? super Integer}
* <p>
* </li>
* </ul>
*
* @see GotClassDemo
*/
@Test
public void type() throws Exception {
//获取泛型参数类型
TypeVariable<? extends Class<? extends TypeVariableDemo>>[] typeParameters = TypeVariableDemo.class.getTypeParameters();
System.out.printf("TypeVariableDemo<T extends Number & Serializable>泛型参数个数:%d.%n", typeParameters.length);
TypeVariable t = typeParameters[0];
System.out.printf("TypeVariableDemo<T extends Number & Serializable>泛型参数名称:%s.%n", t.getTypeName());
System.out.printf("ParameterizedTypeDemo<T>泛型参数属于参数化类型:%b.%n", t instanceof java.lang.reflect.ParameterizedType);
System.out.printf("ParameterizedTypeDemo<T>泛型参数属于参数化类型:%b.%n", t instanceof TypeVariable);
//t.getBounds() 获取泛型上边界,如果没有声明就是Object
System.out.printf("TypeVariableDemo<T extends Number & Serializable>泛型边界个数:%d.%n", t.getBounds().length);
System.out.printf("TypeVariableDemo<T extends Number & Serializable>泛型边界参数:%s.%n", Arrays.toString(t.getBounds()));
//这里泛型边界类型属于Class对象
System.out.printf("TypeVariableDemo<T extends Number & Serializable>泛型边界参数为字节码对象:%b.%n", t.getBounds()[1] instanceof Class);
//参数化的泛型类型
TypeVariable<? extends Class<? extends ParameterizedTypeDemo>>[] typeParameters1 = ParameterizedTypeDemo.class.getTypeParameters();
System.out.printf("ParameterizedTypeDemo<Long>泛型参数个数:%d.%n", typeParameters1.length);
TypeVariable t1 = typeParameters1[0];
System.out.printf("ParameterizedTypeDemo<Long>泛型参数名称:%s.%n", t1.getTypeName());
System.out.printf("ParameterizedTypeDemo<Long>泛型参数属于参数化类型:%b.%n", t1 instanceof java.lang.reflect.ParameterizedType);
//t.getBounds() 获取泛型上边界,如果没有声明就是Object
System.out.printf("ParameterizedTypeDemo<Long>泛型边界个数:%d.%n", t1.getBounds().length);
System.out.printf("ParameterizedTypeDemo<Long>泛型边界参数:%s.%n", Arrays.toString(t1.getBounds()));
//这里泛型边界类型属于Class对象
System.out.printf("ParameterizedTypeDemo<Long>泛型边界参数为字节码对象:%b.%n", t1.getBounds()[0] instanceof Class);
//获取数组泛型
Type genericArrayType = GenericArrayTypeDemo.class.getMethod("create", Object[].class).getGenericReturnType();
System.out.printf("T[]属于GenericArrayType:%b.%n", genericArrayType instanceof GenericArrayType);
GenericArrayType arrayType = (GenericArrayType) genericArrayType;
System.out.printf("T[]的元素泛型类型属于泛型变量:%b.%n", arrayType.getGenericComponentType() instanceof TypeVariable);
//泛型通配符
Type type = WildcardTypeDemo.class.getMethod("createList").getGenericReturnType();
System.out.printf("List<?>的泛型类型属于统配符:%b.%n", ((ParameterizedType) type).getActualTypeArguments()[0] instanceof WildcardType);
}
@Test
public void genericArrayType() throws NoSuchMethodException {
Method createMethod = GenericArrayTypeDemo.class.getMethod("create", Object[].class);
//获取方法的泛型参数类型
Type[] genericParameterTypes = createMethod.getGenericParameterTypes();
for (Type genericParameterType : genericParameterTypes) {
assertTrue("(T[] t) 参数t的泛型类型属于GenericArrayType类型", genericParameterType instanceof GenericArrayType);
GenericArrayType type = (GenericArrayType) genericParameterType;
System.out.println("泛型类型名称:" + type.getTypeName() + "" + type.getGenericComponentType());
assertTrue("泛型数组的元素泛型类型为泛型变量TypeVariable",
type.getGenericComponentType() instanceof TypeVariable);
}
}
public static class GenericArrayTypeDemo {
public static <T> T[] create(T[] t) {
return t;
}
}
@Test
public void typeVariable() {
//泛型变量可以指定泛型边界,只能指定泛型上界
TypeVariable<Class<TypeVariableDemo>>[] typeParameters = TypeVariableDemo.class.getTypeParameters();
assertEquals("泛型变量个数", 2, typeParameters.length);
for (TypeVariable<Class<TypeVariableDemo>> typeParameter : typeParameters) {
System.out.println("泛型变量名称:" + typeParameter.getName());
}
Type[] bounds = typeParameters[0].getBounds();
Class<TypeVariableDemo> genericDeclaration = typeParameters[0].getGenericDeclaration();
assertEquals("GenericDeclaration为该泛型参数所在的类", TypeVariableDemo.class, genericDeclaration);
assertEquals("泛型边界个数", 2, bounds.length);
assertSame(bounds[0], Number.class);
assertSame(bounds[1], Serializable.class);
bounds = typeParameters[1].getBounds();
assertEquals(1, bounds.length);
assertTrue("T的泛型上界为泛型变量", bounds[0] instanceof TypeVariable);
assertSame("T的泛型上界为泛型变量D", bounds[0], typeParameters[0]);
}
public static class TypeVariableDemo
<D extends Number & Serializable,
T extends D> {
}
@Test
public void parameterizedType() throws NoSuchMethodException {
Method parameterized = ParameterizedTypeDemo.class.getMethod("parameterized", ParameterizedTypeDemo.class);
Type[] genericParameterTypes = parameterized.getGenericParameterTypes();
Type type = genericParameterTypes[0];
assertTrue(type instanceof ParameterizedType);
ParameterizedType parameterizedType = (ParameterizedType) type;
//获取实际参数类型
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
assertSame(actualTypeArguments[0], String.class);
//获取泛型类、接口
Type rawType = parameterizedType.getRawType();
assertSame(rawType, ParameterizedTypeDemo.class);
Type ownerType = parameterizedType.getOwnerType();
assertSame(ownerType, GenericDemo.class);
}
public static class ParameterizedTypeDemo<T> {
public void parameterized(ParameterizedTypeDemo<String> param) {
}
}
@Test
public void wildcardType() throws NoSuchMethodException {
Method createList = WildcardTypeDemo.class.getMethod("superType", List.class, Long.class);
Type[] types = createList.getGenericParameterTypes();
assertEquals("参数个数", 2, types.length);
ParameterizedType type = (ParameterizedType) types[0];
System.out.println(type.getTypeName());
Type[] actualTypeArguments = type.getActualTypeArguments();
assertTrue("", actualTypeArguments[0] instanceof WildcardType);
WildcardType tp = (WildcardType) actualTypeArguments[0];
Type[] lowerBounds = tp.getLowerBounds();
assertEquals(1, lowerBounds.length);
assertSame(Number.class, lowerBounds[0]);
}
public static class WildcardTypeDemo {
public static void superType(List<? super Number> list, Long id) {
}
public static List<?> createList() {
return new ArrayList<>();
}
}
}
|
package com.ace.easyteacher.Activity.AddActivitys;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.ace.easyteacher.DataBase.ClassInfo;
import com.ace.easyteacher.DataBase.DBUtils;
import com.ace.easyteacher.DataBase.StudentInfo;
import com.ace.easyteacher.Http.HttpUtils;
import com.ace.easyteacher.Http.MHttpClient;
import com.ace.easyteacher.R;
import com.ace.easyteacher.Upload.PutObjectSamples;
import com.ace.easyteacher.Utils.XToast;
import com.alibaba.fastjson.JSON;
import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.magicare.mutils.NetUtil;
import com.magicare.mutils.common.Callback;
import com.rengwuxian.materialedittext.MaterialEditText;
import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
public class AddStuActivity extends AppCompatActivity {
@Bind(R.id.name)
MaterialEditText mName;
@Bind(R.id.sid)
MaterialEditText mSid;
@Bind(R.id.sex)
MaterialEditText mSex;
@Bind(R.id.birth)
MaterialEditText birth;
@Bind(R.id.position)
MaterialEditText position;
@Bind(R.id.hobby)
MaterialEditText hobby;
@Bind(R.id.father_name)
MaterialEditText fatherName;
@Bind(R.id.father_number)
MaterialEditText fatherNumber;
@Bind(R.id.mother_name)
MaterialEditText motherName;
@Bind(R.id.mother_number)
MaterialEditText motherNumber;
@Bind(R.id.ok)
Button ok;
@Bind(R.id.sp_class_name)
Spinner mSp;
@Bind(R.id.tv_head)
TextView mTv_head;
@Bind(R.id.btn_stu_head)
Button mBtn_head;
@Bind(R.id.toolbar)
Toolbar toolbar;
private StudentInfo mStudent = new StudentInfo();
private String[] mClass_name;
private ArrayAdapter<String> mAdapter;
private Uri mUri;
private static final int CLASS_DONE = 1;
private final static int FILE_SELECT_CODE = 99;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case CLASS_DONE:
mAdapter = new ArrayAdapter<String>(AddStuActivity.this, android.R.layout.simple_spinner_item, mClass_name);
mAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
mSp.setAdapter(mAdapter);
mSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mStudent.setClass_name(mClass_name[position]);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
break;
default:
break;
}
}
};
private OSS oss;
private static final String endpoint = "oss-cn-shenzhen.aliyuncs.com";
private static final String accessKeyId = "tMs31AL2Z2IHa5q4";
private static final String accessKeySecret = "uz3ZW59qlkAGilPQvnp9yXmFmk1Gcu";
private static final String testBucket = "com-ace-teacher";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student);
ButterKnife.bind(this);
toolbar.setTitle("添加学生信息");
toolbar.setTitleTextColor(Color.WHITE);
setSupportActionBar(toolbar);
getAllClass();
mBtn_head.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openFile();
}
});
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mSid.getText().toString().trim().equals("")) {
mStudent.setSid(0);
} else {
mStudent.setSid(Long.parseLong(mSid.getText().toString().trim()));
}
mStudent.setName(mName.getText().toString());
mStudent.setSex(mSex.getText().toString());
mStudent.setBirthday(birth.getText().toString());
mStudent.setPosition(position.getText().toString());
mStudent.setHobby(hobby.getText().toString());
mStudent.setFather(fatherName.getText().toString());
mStudent.setFather_tel(fatherNumber.getText().toString());
mStudent.setMother(motherName.getText().toString());
mStudent.setMother_tel(motherNumber.getText().toString());
mStudent.setUrl("");
if (mStudent.getSid() == 0) {
XToast.showToast(AddStuActivity.this, "学号不能为空");
} else if (mStudent.getName().equals("")) {
XToast.showToast(AddStuActivity.this, "姓名不能为空");
} else {
makeHead();
addStudent(JSON.toJSONString(mStudent));
if (mUri != null) {
new Thread(new Runnable() {
@Override
public void run() {
new PutObjectSamples(oss, testBucket, mSid.getText().toString().trim(), getPath(AddStuActivity.this, mUri)).asyncPutObjectFromLocalFile();
}
}).start();
}
}
}
});
}
private void addStudent(String content) {
if (!NetUtil.isNetWorkConnected(AddStuActivity.this)) {
XToast.showToast(AddStuActivity.this, "请检查网络连接");
return;
}
HttpUtils.HttpCallback<String> callback = new HttpUtils.HttpCallback<String>() {
@Override
public void onError(Throwable ex, boolean isOnCallback) {
XToast.showToast(AddStuActivity.this, "上传失败");
}
@Override
public void onSuccess(String result) {
XToast.showToast(AddStuActivity.this, "上传成功");
finish();
}
@Override
public void onSuccess(List<String> result) {
}
@Override
public void onCancelled(Callback.CancelledException cex) {
}
@Override
public void onFinished() {
}
};
MHttpClient.addStudent(content, callback);
}
private void getAllClass() {
HttpUtils.HttpCallback<ClassInfo> callback = new HttpUtils.HttpCallback<ClassInfo>() {
@Override
public void onError(Throwable ex, boolean isOnCallback) {
DbManager db = x.getDb(DBUtils.getStutdentInfoDaoConfig());
try {
List<ClassInfo> result = db.selector(ClassInfo.class).findAll();
if (result != null && result.size() != 0) {
mClass_name = new String[result.size()];
for (int i = 0; i < result.size(); i++) {
mClass_name[i] = result.get(i).getClass_name();
}
}
} catch (DbException e) {
e.printStackTrace();
}
}
@Override
public void onSuccess(ClassInfo result) {
}
@Override
public void onSuccess(List<ClassInfo> result) {
mClass_name = new String[result.size()];
for (int i = 0; i < result.size(); i++) {
mClass_name[i] = result.get(i).getClass_name();
}
}
@Override
public void onCancelled(Callback.CancelledException cex) {
}
@Override
public void onFinished() {
mHandler.sendEmptyMessage(CLASS_DONE);
}
};
MHttpClient.getClassInfo(callback);
}
@Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
private void openFile() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent, "请选择一个要上传的文件"),
FILE_SELECT_CODE);
} catch (ActivityNotFoundException ex) {
XToast.showToast(this, "请安装文件管理器");
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
mUri = data.getData();
mTv_head.setText(getPath(this, mUri));
}
super.onActivityResult(requestCode, resultCode, data);
}
private void makeHead() {
OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
ClientConfiguration conf = new ClientConfiguration();
conf.setConnectionTimeout(15 * 1000); // 连接超时,默认15秒
conf.setSocketTimeout(15 * 1000); // socket超时,默认15秒
conf.setMaxConcurrentRequest(5); // 最大并发请求书,默认5个
conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次
OSSLog.enableLog();
oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
}
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
}
|
package boj10989;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
// 카운팅 정렬
public class Main3 {
private static BufferedReader br;
private static BufferedWriter bw;
private static StringBuilder sb;
private static int[] inputArr;
private static int[] countingArr;
public static void main(String[] args) throws NumberFormatException, IOException {
createObjects();
makeArr();
initializeArr();
doCountingSort();
printCountingArr();
closeBuffedIO();
}
public static void createObjects() {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
sb = new StringBuilder();
}
public static void makeArr() throws NumberFormatException, IOException {
int size = Integer.parseInt(br.readLine());
inputArr = new int[size];
}
public static void initializeArr() throws NumberFormatException, IOException {
for(int i =0; i< inputArr.length; i++) {
inputArr[i] = Integer.parseInt(br.readLine());
}
}
public static int getMaxOnInputArr() {
int max = 0;
for(int value : inputArr) {
if( value > max ) {
max = value;
}
}
return max;
}
public static void doCountingSort() {
int size = getMaxOnInputArr();
countingArr = new int[size+1];
for(int i =0; i< inputArr.length;i++) {
countingArr[inputArr[i]]++;
}
}
public static void printCountingArr() throws IOException {
for(int i=0; i<countingArr.length; i++) {
if(countingArr[i] != 0) {
for(int j =0; j< countingArr[i]; j++) {
sb.append(i).append("\n");
}
}
}
bw.write(sb.toString());
bw.flush();
}
public static void closeBuffedIO() throws IOException {
bw.close();
br.close();
}
}
|
package com.tencent.mm.ipcinvoker;
import android.os.HandlerThread;
import com.tencent.mm.ipcinvoker.a.b;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
class l$a implements b {
private int dmQ = 3;
HandlerThread mHandlerThread;
l$a() {
HandlerThread handlerThread = new HandlerThread("ThreadPool#InnerWorkerThread-" + hashCode());
handlerThread.start();
com.tencent.mm.ipcinvoker.h.b.i("IPC.ExecutorServiceCreatorImpl", "createHandlerThread(hash : %d)", new Object[]{Integer.valueOf(handlerThread.hashCode())});
this.mHandlerThread = handlerThread;
}
public final ExecutorService Cx() {
ExecutorService anonymousClass2 = new ScheduledThreadPoolExecutor(this.dmQ, new 1(this)) {
public final void execute(Runnable runnable) {
super.execute(new 1(this, runnable));
}
};
anonymousClass2.setMaximumPoolSize((int) (((double) this.dmQ) * 1.5d));
anonymousClass2.setRejectedExecutionHandler(new 3(this));
return anonymousClass2;
}
}
|
package com.hazelcast.map.mapstore.writebehind;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A bounded queue which throws {@link com.hazelcast.map.mapstore.writebehind.ReachedMaxSizeException}
* when it reaches max size.
*
* @param <T> Type of entry to be queued.
*/
class BoundedArrayWriteBehindQueue<T> extends ArrayWriteBehindQueue<T> {
/**
* Per node write behind queue item counter.
*/
private final AtomicInteger writeBehindQueueItemCounter;
/**
* Allowed max size per node which is used to provide back-pressure.
*/
private final int maxSize;
BoundedArrayWriteBehindQueue(int maxSize, AtomicInteger writeBehindQueueItemCounter) {
super();
this.maxSize = maxSize;
this.writeBehindQueueItemCounter = writeBehindQueueItemCounter;
}
BoundedArrayWriteBehindQueue(List<T> list, int maxSize, AtomicInteger writeBehindQueueItemCounter) {
super(list);
this.maxSize = maxSize;
this.writeBehindQueueItemCounter = writeBehindQueueItemCounter;
}
@Override
public boolean offer(T t) {
final int currentPerNodeCount = currentPerNodeCount();
if (hasReachedMaxSize(currentPerNodeCount)) {
throw new ReachedMaxSizeException("Queue already reached per node max capacity [" + maxSize + "]");
}
incrementPerNodeMaxSize();
return super.offer(t);
}
@Override
public void removeFirst() {
super.removeFirst();
decrementPerNodeMaxSize();
}
@Override
public T remove(int index) {
final T removed = super.remove(index);
decrementPerNodeMaxSize();
return removed;
}
@Override
public List<T> removeAll() {
final List<T> removes = super.removeAll();
final int size = removes.size();
decrementPerNodeMaxSize(size);
return removes;
}
@Override
public void clear() {
final int size = size();
super.clear();
decrementPerNodeMaxSize(size);
}
@Override
public WriteBehindQueue<T> getSnapShot() {
if (list == null || list.isEmpty()) {
return WriteBehindQueues.emptyWriteBehindQueue();
}
return new BoundedArrayWriteBehindQueue<T>(new ArrayList<T>(list), maxSize, writeBehindQueueItemCounter);
}
@Override
public void addFront(Collection<T> collection) {
if (collection == null || collection.isEmpty()) {
return;
}
final int currentPerNodeCount = currentPerNodeCount();
final int size = collection.size();
final int desiredSize = currentPerNodeCount + size;
if (hasReachedMaxSize(desiredSize)) {
throw new ReachedMaxSizeException("Remaining per node space is not enough for this collection."
+ " Remaining = [" + (maxSize - currentPerNodeCount) + "]");
}
incrementPerNodeMaxSize(size);
super.addFront(collection);
}
@Override
public void addEnd(Collection<T> collection) {
if (collection == null || collection.isEmpty()) {
return;
}
final int currentPerNodeCount = currentPerNodeCount();
final int size = collection.size();
final int desiredSize = currentPerNodeCount + size;
if (hasReachedMaxSize(desiredSize)) {
throw new ReachedMaxSizeException("Remaining per node space is not enough for this collection."
+ " Remaining = [" + (maxSize - currentPerNodeCount) + "]");
}
incrementPerNodeMaxSize(size);
super.addEnd(collection);
}
private boolean hasReachedMaxSize(int size) {
return size >= maxSize;
}
private int currentPerNodeCount() {
return writeBehindQueueItemCounter.intValue();
}
private void incrementPerNodeMaxSize() {
writeBehindQueueItemCounter.incrementAndGet();
}
private void incrementPerNodeMaxSize(int count) {
writeBehindQueueItemCounter.addAndGet(count);
}
private void decrementPerNodeMaxSize() {
writeBehindQueueItemCounter.decrementAndGet();
}
private void decrementPerNodeMaxSize(int size) {
writeBehindQueueItemCounter.addAndGet(-size);
}
}
|
package com.jlgproject.model.eventbusMode;
/**
* @author 王锋 on 2017/7/12.
*/
public class ResigerBean {
private int showIndex;
public ResigerBean(int showIndex) {
this.showIndex = showIndex;
}
public int getShowIndex() {
return showIndex;
}
public void setShowIndex(int showIndex) {
this.showIndex = showIndex;
}
}
|
/*
* Copyright 2019, E-Kohei
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.norana.numberplace.ui.activity;
import androidx.databinding.DataBindingUtil;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.Observer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageButton;
import java.util.ArrayDeque;
import java.util.NoSuchElementException;
import com.norana.numberplace.Constants;
import com.norana.numberplace.R;
import com.norana.numberplace.sudoku.Pair;
import com.norana.numberplace.sudoku.Sudoku;
import com.norana.numberplace.sudoku.Note;
import com.norana.numberplace.ui.dialog.ConfirmSolveDialogFragment;
import com.norana.numberplace.viewmodel.SudokuViewModel;
import com.norana.numberplace.database.SudokuItem;
import com.norana.numberplace.util.InputLog;
import com.norana.numberplace.databinding.ActivitySudokuBinding;
public class MakeActivity extends AppCompatActivity{
// what the user input: number, note
private int inputMode = Constants.MODE_NUMBER;
// ViewModel to store UI data
private SudokuViewModel viewModel;
// ViewDataBinding
private ActivitySudokuBinding mBinding;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
SudokuViewModel.Factory factory = new SudokuViewModel.Factory(
getApplication(), -1, null);
viewModel =
(new ViewModelProvider(this, factory)).get(SudokuViewModel.class);
// initialize view
mBinding
= DataBindingUtil.setContentView(this, R.layout.activity_sudoku);
setSupportActionBar(mBinding.toolbar);
mBinding.toolbarBackground.setImageResource(R.drawable.dripdrop_blue);
mBinding.sudokuview.setColorOnTouch(true);
viewModel.getBackgroundText().observe(this, new Observer<String>(){
@Override
public void onChanged(@Nullable final String newText){
// set the background text
mBinding.backgroundText.setText(newText);
// and clear the text later
if (!newText.endsWith("...")){
Handler handler = new Handler(getMainLooper());
handler.postDelayed(() -> {
mBinding.backgroundText.setText("");
}, 5000);
}
}
});
viewModel.getCurrentSudoku().observe(this, new Observer<Sudoku>(){
@Override
public void onChanged(@Nullable final Sudoku newCurrent){
// set the current sudoku to the sudokuView
mBinding.sudokuview.copySudoku(newCurrent);
}
});
viewModel.getCurrentNote().observe(this, new Observer<Note>(){
@Override
public void onChanged(@Nullable final Note newNote){
// set the current note to the sudokuView
mBinding.sudokuview.copyNote(newNote);
}
});
// if this is first creation, initialize sudoku the user make
if (savedInstanceState == null){
viewModel.setCurrentSudoku(new Sudoku(3));
viewModel.setCurrentNote(new Note(3));
viewModel.setLogStack(new ArrayDeque<InputLog>());
}
else{
inputMode = savedInstanceState.getInt("inputMode");
if (inputMode == Constants.MODE_NUMBER)
((ImageButton)findViewById(R.id.mode)).setImageResource(R.drawable.sudoku_icon_number);
else if (inputMode == Constants.MODE_NOTE)
((ImageButton)findViewById(R.id.mode)).setImageResource(R.drawable.sudoku_icon_note);
}
}
@Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putInt("inputMode", inputMode);
}
@Override
protected void onRestoreInstanceState( Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
inputMode = savedInstanceState.getInt("inputMode");
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_make_only, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
switch (id){
case R.id.action_save:
// save the current sudoku
saveSudoku();
finish();
return true;
case R.id.action_undo:
// undo
undoInput();
return true;
case R.id.action_clear_note:
// clear all notes
clearAllNotes();
return true;
case R.id.action_check_solvability:
// check whether the current sudoku is solvable
Sudoku current1 = viewModel.getCurrentSudoku().getValue();
viewModel.checkSudokuInBackground(current1);
return true;
case R.id.action_solve:
// solve the current sudoku
ConfirmSolveDialogFragment fragment = new ConfirmSolveDialogFragment();
fragment.show(getSupportFragmentManager(), "confirmSolveDialog");
return true;
}
return super.onOptionsItemSelected(item);
}
/** callback function for background text */
public void backgroundTextCallback(View v){
viewModel.setBackgroundText("");
}
/** callback function for change inputMode button */
public void changeModeCallback(View v){
// change input mode
if (inputMode == Constants.MODE_NUMBER){
inputMode = Constants.MODE_NOTE;
((ImageButton)findViewById(R.id.mode))
.setImageResource(R.drawable.sudoku_icon_note);
}
else{ // inputMode == MODE_NOTE
inputMode = Constants.MODE_NUMBER;
((ImageButton)findViewById(R.id.mode))
.setImageResource(R.drawable.sudoku_icon_number);
}
}
/** callback function for number buttton */
public void numberClickCallback(View v){
Pair<Integer, Integer> cell = mBinding.sudokuview.getSelectedCell();
if (cell != null){
Integer n = (Integer) v.getTag();
if (inputMode == Constants.MODE_NUMBER){
// store log object
int before = viewModel.getNumberInCurrentSudoku(cell);
InputLog log = new InputLog(before, n, cell,
Constants.MODE_NUMBER);
viewModel.getLogStack().addFirst(log);
// set number
viewModel.setNumberInCurrentSudoku(cell, n);
}
else if (inputMode == Constants.MODE_NOTE){
// store log object
int before = viewModel.getNumberInCurrentNote(cell);
int after = before ^ (1<<(n-1));
InputLog log = new InputLog(before, after, cell,
Constants.MODE_NOTE);
viewModel.getLogStack().addFirst(log);
// set note
viewModel.toggleNumberInCurrentNote(cell, n);
}
mBinding.sudokuview.setSelectedCell(getNextCell(cell));
}
}
private Pair<Integer, Integer> getNextCell(Pair<Integer, Integer> cell){
int number = cell.getFirst() * 9 + cell.getSecond() ;
int number_plus = (number + 1) % 81;
return new Pair<Integer, Integer>(number_plus/9, number_plus%9);
}
private void undoInput(){
try{
InputLog log = viewModel.getLogStack().removeFirst();
int mode = log.getInputMode();
Pair<Integer, Integer> cell = log.getCell();
int before = log.getBefore();
if (mode == Constants.MODE_NUMBER){
viewModel.setNumberInCurrentSudoku(cell, before);
}
else if (mode == Constants.MODE_NOTE){
viewModel.toggleNumberInCurrentNote(cell, before);
}
}
catch (NoSuchElementException e){}
}
// save the current sudoku
private void saveSudoku(){
Sudoku currentS = viewModel.getCurrentSudoku().getValue();
if (currentS != null){
SudokuItem sudokuItem =
new SudokuItem(-1, Constants.STATUS_MAKING, currentS.copy());
viewModel.insert(sudokuItem);
}
}
// clear all notes
private void clearAllNotes(){
viewModel.setCurrentNote(new Note(3));
}
// solve sudoku
public void solveSudoku(){
Sudoku current = viewModel.getCurrentSudoku().getValue();
viewModel.solveSudokuInBackground(current);
}
}
|
package com.yksoul.pay.utils;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* 操作类
*
* @author yksoul
* @version 1.0 Date: 2017-12-05
*/
public class ServerUtils {
/**
* 获取客户端真实ip
*
* @param request
* @return
*/
public static String getClientIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
public static String getServerIp(HttpServletRequest request) throws UnknownHostException {
InetAddress addr = InetAddress.getLocalHost();
return addr.getHostAddress();
}
}
|
package be.spring.app.controller;
import be.spring.app.data.MatchStatusEnum;
import be.spring.app.form.ChangeResultForm;
import be.spring.app.model.Account;
import be.spring.app.model.Match;
import be.spring.app.model.Season;
import be.spring.app.model.Team;
import be.spring.app.service.AccountService;
import be.spring.app.service.MatchesService;
import be.spring.app.service.SeasonService;
import be.spring.app.service.TeamService;
import be.spring.app.utils.Constants;
import be.spring.app.validators.ChangeMatchValidator;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.validation.Valid;
import java.rmi.AccessException;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
/**
* Created by u0090265 on 5/30/14.
*/
@Controller
@RequestMapping("/")
public class ChangeMatchController extends AbstractController {
private static final String DEFAULT_TEAM = "SVK";
@Autowired
ChangeMatchValidator validator;
@Autowired
private MatchesService matchesService;
@Autowired
private AccountService accountService;
@Autowired
private SeasonService seasonService;
@Autowired
private TeamService teamService;
@InitBinder("form")
protected void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
@ModelAttribute("players")
public List<Account> getPerson() {
List<Account> accounts = accountService.getAllActivateAccounts();
Collections.sort(accounts);
return accounts;
}
@ModelAttribute("matchStatus")
public List<String> getMatchStatus() {
return Lists.newArrayList(MatchStatusEnum.NOT_PLAYED.name(),
MatchStatusEnum.PLAYED.name(),
MatchStatusEnum.CANCELLED.name());
}
@ModelAttribute("defaultTeam")
public String getDefaultTeam() {
return DEFAULT_TEAM;
}
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value = "changeMatch", method = RequestMethod.POST)
public String postChangeMatchResult(@Valid @ModelAttribute("form") ChangeResultForm form, BindingResult result, Model model, Locale locale, final RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
//Add match, otherwise information is lost
model.addAttribute("match", matchesService.getMatch(form.getMatchId()));
return Constants.LANDING_MATCHES_CHANGE_MATCH;
}
Match m = matchesService.updateMatch(form);
setFlashSuccessMessage(redirectAttributes, locale, "text.match.result.update.success", new Object[]{m.getDescription()});
return Constants.REDIRECT_MATCHES_PAGE;
}
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value = "changeMatch", method = RequestMethod.GET)
public ModelAndView newMatchResult(ModelMap model, @RequestParam long matchId, @ModelAttribute("form") ChangeResultForm form) {
Match match = matchesService.getMatch(matchId);
model.addAttribute("match", match);
if (match != null) {
ChangeResultForm resultForm = new ChangeResultForm();
resultForm.setAtGoals(match.getAtGoals());
resultForm.setHtGoals(match.getHtGoals());
resultForm.setMatchId(match.getId());
resultForm.setDate(match.getDate());
resultForm.setStatus(match.getStatus());
resultForm.setSeason(match.getSeason().getId());
resultForm.setAwayTeam(match.getAwayTeam().getId());
resultForm.setHomeTeam(match.getHomeTeam().getId());
resultForm.setStatusText(match.getStatusText());
model.addAttribute("form", resultForm);
}
return new ModelAndView(Constants.LANDING_MATCHES_CHANGE_MATCH);
}
@ModelAttribute("teams")
public List<Team> getAllTeams() {
return teamService.getAll();
}
@ModelAttribute("seasons")
public List<Season> getAllSeasons() {
return seasonService.getSeasons();
}
@RequestMapping(value = "getError", method = RequestMethod.GET)
public void getError() throws AccessException {
try {
if (true) throw new AccessException("test");
} finally {
}
}
}
|
/**
*
*/
package biorimp.optmodel.mappings;
import biorimp.optmodel.mappings.metaphor.MetaphorCode;
import biorimp.optmodel.mappings.quantum.QubitRefactor;
import edu.wayne.cs.severe.redress2.entity.TypeDeclaration;
import edu.wayne.cs.severe.redress2.entity.refactoring.json.OBSERVRefParam;
import edu.wayne.cs.severe.redress2.entity.refactoring.json.OBSERVRefactoring;
import java.util.ArrayList;
import java.util.List;
/**
* @author Daavid
*/
public class MappingRefactorMF extends MappingRefactor {
/* (non-Javadoc)
* @see entity.MappingRefactor#mappingRefactor(java.lang.String, unalcol.types.collection.bitarray.BitArray, entity.MetaphorCode)
*/
protected Refactoring type = Refactoring.moveField;
@Override
public OBSERVRefactoring mappingRefactor(QubitRefactor genome) {
// TODO Auto-generated method stub
boolean feasible = true;
List<OBSERVRefParam> params = new ArrayList<OBSERVRefParam>();
int numSrcObs;
TypeDeclaration sysType_src;
//do{
//Creating the OBSERVRefParam for the src class
numSrcObs = genome.getNumberGenome(genome.getGenSRC());
sysType_src = MetaphorCode.getMapClass().get(numSrcObs %
MetaphorCode.getMapClass().size());
List<String> value_src = new ArrayList<String>();
value_src.add(sysType_src.getQualifiedName());
params.add(new OBSERVRefParam("src", value_src));
//Creating the OBSERVRefParam for the fld field
List<String> value_fld = new ArrayList<String>();
if (!MetaphorCode.getFieldsFromClass(sysType_src).isEmpty()) {
int numFldObs = genome.getNumberGenome(genome.getGenFLD());
value_fld.add((String) MetaphorCode.getFieldsFromClass(sysType_src).toArray()[numFldObs
% MetaphorCode.getFieldsFromClass(sysType_src).size()]);
params.add(new OBSERVRefParam("fld", value_fld));
} else {
value_fld.add("");
params.add(new OBSERVRefParam("fld", value_fld));
feasible = false;
}
//}while(code.getFieldsFromClass(sysType_src).isEmpty());
//Creating the OBSERVRefParam for the tgt
int numTgtObs = genome.getNumberGenome(genome.getGenTGT());
List<String> value_tgt = new ArrayList<String>();
TypeDeclaration sysType_tgt = MetaphorCode.getMapClass().get(numTgtObs %
MetaphorCode.getMapClass().size());
value_tgt.add(sysType_tgt.getQualifiedName());
params.add(new OBSERVRefParam("tgt", value_tgt));
return new OBSERVRefactoring(type.name(), params, feasible, new ArrayList<Double>());
}
/* (non-Javadoc)
* @see entity.MappingRefactor#mappingParams()
*/
@Override
public List<OBSERVRefParam> mappingParams() {
// TODO Auto-generated method stub
return null;
}
}
|
package todo.entity;
import java.sql.SQLException;
import javax.xml.bind.annotation.XmlRootElement;
import inventory.service.StatementManager;
import com.mysql.jdbc.Statement;
@XmlRootElement
public class Stock {
private Statement stmt;
private Item item;
private Branch branch;
private int quantity;
public Stock() {
stmt = StatementManager.getStatement();
}
public Stock(Item item, Branch branch, int quantity) {
this.item = item;
this.branch = branch;
this.quantity = quantity;
stmt = StatementManager.getStatement();
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
String query = "UPDATE Stock " + " SET itemID = '" + item.getItemID()
+ "' " + "WHERE branchID = '" + branch.getBranchID()
+ "' AND quantity = '" + quantity + "'";
try {
stmt.executeUpdate(query);
} catch (SQLException e) {
System.out.println("Cannot query");
e.printStackTrace();
}
this.item = item;
}
public Branch getBranch() {
return branch;
}
public void setBranch(Branch branch) {
String query = "UPDATE Stock " + " SET branchID = '"
+ branch.getBranchID() + "' " + "WHERE itemID = '"
+ item.getItemID() + "' AND quantity = '" + quantity + "'";
try {
stmt.executeUpdate(query);
} catch (SQLException e) {
System.out.println("Cannot query");
e.printStackTrace();
}
this.branch = branch;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
String query = "UPDATE Stock " + " SET quantity = '" + quantity + "' "
+ "WHERE itemID = '" + item.getItemID() + "' AND branchID = '"
+ branch.getBranchID() + "'";
try {
stmt.executeUpdate(query);
} catch (SQLException e) {
System.out.println("Cannot query");
e.printStackTrace();
}
this.quantity = quantity;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(item.toString() + "\n");
sb.append(branch.toString() + "\n");
sb.append("Quantity : " + quantity + "\n");
return sb.toString();
}
}
|
package com.mengdo.gameframework.utils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
@SuppressWarnings("unchecked")
public class DateConverter implements Converter{
@Override
public <T> T convert(Class<T> type, Object value) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return (T) dateFormat.parse(value.toString());
} catch (ParseException e) {
throw new ConversionException(e);
}
}
}
|
package com.Banks;
import com.Jsoup.BankFinancialProducts;
import com.Jsoup.BankFinancialProductsDao;
import com.Jsoup.util.MyBatisUtil;
import com.alibaba.fastjson.JSON;
import com.demo.other.Bank;
import com.demo.other.BankProduct;
import com.demo.other.Table;
import com.google.gson.Gson;
import net.sf.json.JSONArray;
import org.apache.ibatis.session.SqlSession;
import sun.net.www.protocol.http.Handler;
import sun.net.www.protocol.http.HttpURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
/**
* @Desc
* @Author 刘慧斌
* @CreateTime 2019-04-25 19:40
**/
//农业银行------json解析-----分页已解决
public class EwealthBank {
public static void main(String[] args) {
String url="http://ewealth.abchina.com/app/data/api/DataService/BoeProductV2?i=1&s=75&o=0&w=%25E5%258F%25AF%25E5%2594%25AE%257C%257C%257C%257C%257C%257C%257C1%257C%257C0%257C%257C0";
HttpURLConnection connection = null;
SqlSession sqlSession=MyBatisUtil.createSqlSession();
if(connection == null) {
try {
connection = (HttpURLConnection)new URL(null, url, new Handler()).openConnection();
// 添加请求头部
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36");
connection.setInstanceFollowRedirects(false);
System.out.println("----------");
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
reader.close();
inputStream.close();
//System.out.println(stringBuilder);
Gson gson=new Gson();
Bank bankProduct=gson.fromJson(stringBuilder.toString(),Bank.class);
String jsons = JSON.toJSONString(bankProduct.getData());
Table table=gson.fromJson(jsons,Table.class);
String jsons1= JSON.toJSONString(table.getTable());
System.out.println(jsons1);
JSONArray jsonArray=JSONArray.fromObject(jsons1);
BankProduct b1=null;
BankFinancialProducts products=null;
for (int i=0;i<jsonArray.size();i++){
Object o=jsonArray.get(i);
String json2 = JSON.toJSONString(o);
b1=gson.fromJson(json2,BankProduct.class);
products=new BankFinancialProducts("中国农业银行",b1.getProdName(),b1.getProdProfit(),b1.getProdSaleDate(),b1.getProdLimit(),b1.getPurStarAmo(),"暂无数据",b1.getProdYildType());
sqlSession.getMapper(BankFinancialProductsDao.class).insertSelective(products);
sqlSession.commit();
/*System.out.println("银行名称:"+"\t\t"+products.getBankName()+"\n"
+"产品名:" + "\t\t\t"+products.getProductName()+"\n"
+"链接:" + "\t\t\t"+products.getUrl()+"\n"
+"风险:" + "\t\t\t"+products.getRisk()+"\n"
+"收益:"+"\t\t\t"+products.getYieldRate()+"\n"
+"生效时间:"+"\t\t"+products.getTimeLimit()+"\n"
+"购买日期:"+"\t\t"+products.getDuring()+"\n"
+"起购金额:"+"\t\t"+products.getPurchaseAmount()+"\n");*/
}
} catch (IOException e) {
e.printStackTrace();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
}
}
}
|
package inter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by joetomjob on 3/6/18.
*/
class URLCount{
String urlS;
int count;
URLCount(String url, int count){
this.urlS = url;
this.count = count;
}
}
public class IntuitSan {
public Map<String, Integer> theFunction(ArrayList<URLCount> urlList){
Map<String,Integer> res = new HashMap<>();
for(URLCount u : urlList){
int cnt = u.count;
String[] spltUrl = u.urlS.split("\\.");
String ur = "";
for(int i = spltUrl.length-1; i>=0; i--){
if(spltUrl[i].trim().length() > 0) {
if (i == spltUrl.length - 1)
ur = spltUrl[i];
else
ur = spltUrl[i] + "." + ur;
if (res.containsKey(ur))
res.put(ur, res.get(ur) + cnt);
else
res.put(ur, cnt);
}
}
}
return res;
}
public static void main(String[] args) {
ArrayList<URLCount> inp= new ArrayList<>();
URLCount u1 = new URLCount ("google.com",50);
URLCount u2 = new URLCount ("sport.google.com",10);
URLCount u3 = new URLCount ("mobile.google.com",20);
URLCount u4 = new URLCount ("nexus.mobile.google.com",30);
URLCount u5 = new URLCount ("nexus5.nexus.google.com",80);
URLCount u6 = new URLCount ("yahoo.com",10);
URLCount u7 = new URLCount (".org",40);
URLCount u8 = new URLCount ("example.org",70);
inp.add(u1);
inp.add(u2);
inp.add(u3);
inp.add(u4);
inp.add(u5);
inp.add(u6);
inp.add(u7);
inp.add(u8);
// Object o = 'c'-'0';
// System.out.print(o);
//
// String ss = "";
// ss += 'e';
IntuitSan s = new IntuitSan();
Map<String, Integer> h = s.theFunction(inp);
for(Map.Entry<String, Integer> e: h.entrySet()) {
System.out.print(e.getKey());
System.out.print(": ");
System.out.print(e.getValue());
System.out.println();
}
}
}
|
package entity;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import db.DBConn;
public class Student {
long sid;
String password;
String sname;
int pnumber;
String college;
String classname;
public Student(long sid,String password,String sname,int pnumber,String college,String classname ){
this.classname=classname;
this.password=password;
this.college=college;
this.sid=sid;
this.sname=sname;
this.pnumber=pnumber;
}
public Student() {
}
public long getSid() {
return sid;
}
public void setSid(long sid) {
this.sid = sid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public int getPnumber() {
return pnumber;
}
public void setPnumber(int pnumber) {
this.pnumber = pnumber;
}
public String getCollege() {
return college;
}
public void setCollege(String college) {
this.college = college;
}
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
};
}
|
package com.zhkrb.eve_oauth2.bean;
public class ConfigBean {
private String authorizationUrl;
private String scopes;
public String getAuthorizationUrl() {
return authorizationUrl;
}
public void setAuthorizationUrl(String authorizationUrl) {
this.authorizationUrl = authorizationUrl;
}
public String getScopes() {
return scopes;
}
public void setScopes(String scopes) {
this.scopes = scopes;
}
}
|
package com.lfpapp.lfpapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LfpAppApplication {
public static void main(String[] args) {
SpringApplication.run(LfpAppApplication.class, args);
}
}
|
//check if a tree is balanced or not
import java.util.*;
class Node{
int data;
Node left,right;
public Node(int item){
data=item;
left=null;
right=null;
}
}
public class Balanced {
int find_height_of_node_in_binary_tree(int data,Node root,int level) {
Node B = root;
int h = 1;
if (B == null) {
return -1;
} else {
Queue<Node> queue = new LinkedList<Node>();
queue.add(B);
while (queue.size() > 0) {
int size = queue.size();
int flag = 0;
while (size > 0) {
Node C = queue.peek();
if(C.data==data){
return h;
}
if (C.left != null || C.right != null) {
flag=1;
if(C.left!=null) {
if (C.left.data == data) {
return h+1;
}
else {
queue.add(C.left);
}
}
if(C.right!=null) {
if (C.right.data == data) {
return h+1;
}
else {
queue.add(C.right);
}
}
}
queue.remove();
size--;
}
if(flag==1){
h=h+1;
}
}
}
return h;
}
int find_diference_between_min_and_max_height_of_nodes_in_Binary_tree(Node root) {
if(root==null){
return -1;
}
Queue<Node> q = new LinkedList<Node>();
Queue<Node> q1 = new LinkedList<Node>();
q.add(root);
//to get all leaf nodes into queue data structure
while(q.size()>0){
Node C=q.peek();
if(!(C.left==null&&C.right==null)){
q.remove();
if(C.left!=null){
q.add(C.left);
}
if(C.right!=null){
q.add(C.right);
}
}
else{
q1.add(q.remove());
}
}
int count=0;
int min_height=0;
int max_height=0;
int height=0;
while(q1.size()>0){
if(count==0){
Node D=q1.remove();
height= find_height_of_node_in_binary_tree(D.data,root,1);
min_height=height;
max_height=height;
count++;
}
else{
count++;
Node D=q1.remove();
height= find_height_of_node_in_binary_tree(D.data,root,1);
if(height<min_height){
min_height=height;
}
if(height>max_height){
max_height=height;
}
}
}
return max_height-min_height;
}
public static void main(String args[]){
Balanced b=new Balanced();
Node root=new Node(1);
root.left=new Node(2);
root.right=new Node(3);
root.left.left=new Node(4);
root.left.right=new Node(5);
root.right.left=new Node(6);
root.right.right=new Node(7);
root.left.left.left=new Node(8);
root.left.left.left.left=new Node(9);
root.left.left.left.left.left=new Node(10);
int c=b.find_diference_between_min_and_max_height_of_nodes_in_Binary_tree(root);
if(c>1){
System.out.println("Tree is unbalanced");
}
else{
System.out.println("Tree is balanced");
}
}
}
|
package FolhaDePagamento;
import java.util.Scanner;
public class IU {
private static int opcao;
private static Scanner ler = new Scanner(System.in);
public IU() {
menuGeral();
}
public static void menuGeral() {
System.out.println("\n******** Menu *********\n");
System.out.println("[1] - Menu Empregado");
System.out.println("[2] - Menu Gratificacao");
System.out.println("[3] - Folha de Pagamento");
System.out.println("[4] - Encerrar Programa\n");
System.out.println("Opcao: ");
setOpcao(Integer.valueOf(ler.nextLine()));
}
public static int getOpcao() {
return opcao;
}
public static void setOpcao(int opcao) {
IU.opcao = opcao;
}
}
|
package com.mycompany.talleralgoritmos;
public class Punto2 {
static int count = 1;
static int num = 1;
static double enl=1.0;
static double fact=1.0;
static double delta=1.0;
public static void main(String[] args) {
RecusiveWat();
System.out.println(enl);
}
static public void RecusiveWat() {
if (enl != enl + delta) {
enl += delta;
count += 1;
fact *= count;
delta = 1.0 / fact;
RecusiveWat();
}
}
}
|
package com.nefee.prawn.data.dao;
import com.nefee.prawn.data.entity.ArmorSet;
import org.springframework.data.repository.CrudRepository;
public interface ArmorSetRepository extends CrudRepository<ArmorSet, Long> {
}
|
package day23Arrays;
import java.util.Arrays;
public class aaa {
public static void main(String[] args) {
int number[];
number=new int [2];
number[0]=10;
number[1]=20;
number=new int[4];
number[2]=30;
number[3]=40;
System.out.println(Arrays.toString(number));
}
}
|
package com.diumotics.qms.qms;
import com.diumotics.qms.qms.controller.QueueController;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan("com.diumotics.qms.qms")
public class QmsApplication {
public static void main(String[] args) {
SpringApplication.run(QmsApplication.class, args);
}
}
|
package com.vilio.pcfs.pojo;
/**
* Created by dell on 2017/8/15.
*/
public class Messages {
private Integer id;
private Integer messageId;
private Integer userId;
private Integer messageTitle;
private Integer messageContent;
private Integer realitySendTime;
private Integer sendTime;
private Integer readFlag;
private Integer createTime;
private Integer updateTime;
private Integer status;
private Integer messageType;
private Integer sendStatus;
private Integer batchNo;
private Integer messageTicker;
private Integer messageSubtitle;
private Integer deviceToken;
private Integer channel;
public Integer getChannel() {
return channel;
}
public void setChannel(Integer channel) {
this.channel = channel;
}
public Integer getDeviceToken() {
return deviceToken;
}
public void setDeviceToken(Integer deviceToken) {
this.deviceToken = deviceToken;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getMessageId() {
return messageId;
}
public void setMessageId(Integer messageId) {
this.messageId = messageId;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getMessageTitle() {
return messageTitle;
}
public void setMessageTitle(Integer messageTitle) {
this.messageTitle = messageTitle;
}
public Integer getMessageContent() {
return messageContent;
}
public void setMessageContent(Integer messageContent) {
this.messageContent = messageContent;
}
public Integer getRealitySendTime() {
return realitySendTime;
}
public void setRealitySendTime(Integer realitySendTime) {
this.realitySendTime = realitySendTime;
}
public Integer getSendTime() {
return sendTime;
}
public void setSendTime(Integer sendTime) {
this.sendTime = sendTime;
}
public Integer getReadFlag() {
return readFlag;
}
public void setReadFlag(Integer readFlag) {
this.readFlag = readFlag;
}
public Integer getCreateTime() {
return createTime;
}
public void setCreateTime(Integer createTime) {
this.createTime = createTime;
}
public Integer getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Integer updateTime) {
this.updateTime = updateTime;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getMessageType() {
return messageType;
}
public void setMessageType(Integer messageType) {
this.messageType = messageType;
}
public Integer getSendStatus() {
return sendStatus;
}
public void setSendStatus(Integer sendStatus) {
this.sendStatus = sendStatus;
}
public Integer getBatchNo() {
return batchNo;
}
public void setBatchNo(Integer batchNo) {
this.batchNo = batchNo;
}
public Integer getMessageTicker() {
return messageTicker;
}
public void setMessageTicker(Integer messageTicker) {
this.messageTicker = messageTicker;
}
public Integer getMessageSubtitle() {
return messageSubtitle;
}
public void setMessageSubtitle(Integer messageSubtitle) {
this.messageSubtitle = messageSubtitle;
}
public Messages(Integer id, Integer messageId, Integer userId, Integer messageTitle, Integer messageContent, Integer realitySendTime, Integer sendTime, Integer readFlag, Integer createTime, Integer updateTime, Integer status, Integer messageType, Integer sendStatus, Integer batchNo, Integer messageTicker, Integer messageSubtitle, Integer deviceToken, Integer channel) {
this.id = id;
this.messageId = messageId;
this.userId = userId;
this.messageTitle = messageTitle;
this.messageContent = messageContent;
this.realitySendTime = realitySendTime;
this.sendTime = sendTime;
this.readFlag = readFlag;
this.createTime = createTime;
this.updateTime = updateTime;
this.status = status;
this.messageType = messageType;
this.sendStatus = sendStatus;
this.batchNo = batchNo;
this.messageTicker = messageTicker;
this.messageSubtitle = messageSubtitle;
this.deviceToken = deviceToken;
this.channel = channel;
}
public Messages() {
}
}
|
package com.duanxr.yith.midium;
import java.util.Arrays;
/**
* @author 段然 2021/3/8
*/
public class MagicSquaresInGrid {
/**
* A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
*
* Given a row x col grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).
*
*
*
* Example 1:
*
*
* Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]
* Output: 1
* Explanation:
* The following subgrid is a 3 x 3 magic square:
*
* while this one is not:
*
* In total, there is only one magic square inside the given grid.
* Example 2:
*
* Input: grid = [[8]]
* Output: 0
* Example 3:
*
* Input: grid = [[4,4],[3,3]]
* Output: 0
* Example 4:
*
* Input: grid = [[4,7,8],[9,5,1],[2,3,6]]
* Output: 0
*
*
* Constraints:
*
* row == grid.length
* col == grid[i].length
* 1 <= row, col <= 10
* 0 <= grid[i][j] <= 15
*
* 3 x 3 的幻方是一个填充有从 1 到 9 的不同数字的 3 x 3 矩阵,其中每行,每列以及两条对角线上的各数之和都相等。
*
* 给定一个由整数组成的 grid,其中有多少个 3 × 3 的 “幻方” 子矩阵?(每个子矩阵都是连续的)。
*
*
*
* 示例:
*
* 输入: [[4,3,8,4],
* [9,5,1,9],
* [2,7,6,2]]
* 输出: 1
* 解释:
* 下面的子矩阵是一个 3 x 3 的幻方:
* 438
* 951
* 276
*
* 而这一个不是:
* 384
* 519
* 762
*
* 总的来说,在本示例所给定的矩阵中只有一个 3 x 3 的幻方子矩阵。
* 提示:
*
* 1 <= grid.length <= 10
* 1 <= grid[0].length <= 10
* 0 <= grid[i][j] <= 15
*
*/
class Solution {
public int numMagicSquaresInside(int[][] grid) {
if (grid.length < 3 || grid[0].length < 3) {
return 0;
}
int sum = 0;
int[] bit = new int[16];
for (int i = 1; i <= 9; i++) {
bit[i] = 1;
}
int[] window = new int[16];
for (int x = 0; x < grid.length - 2; x++) {
if (x % 2 == 0) {
for (int y = 0; y < grid[0].length - 2; y++) {
if (y == 0) {
if (x == 0) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
window[grid[x + i][y + j]]++;
}
}
} else {
for (int i = 0; i < 3; i++) {
window[grid[x - 1][y + i]]--;
window[grid[x + 2][y + i]]++;
}
}
} else {
for (int i = 0; i < 3; i++) {
window[grid[x + i][y - 1]]--;
window[grid[x + i][y + 2]]++;
}
}
if (Arrays.equals(window, bit) && valid(grid, x, y)) {
sum++;
}
}
} else {
for (int y = grid[0].length - 3; y >= 0; y--) {
if (y == grid[0].length - 3) {
for (int i = 0; i < 3; i++) {
window[grid[x - 1][y + i]]--;
window[grid[x + 2][y + i]]++;
}
} else {
for (int i = 0; i < 3; i++) {
window[grid[x + i][y + 3]]--;
window[grid[x + i][y]]++;
}
}
if (Arrays.equals(window, bit) && valid(grid, x, y)) {
sum++;
}
}
}
}
return sum;
}
private boolean valid(int[][] grid, int x, int y) {
int diagonals = diagonals(grid, x, y);
if (diagonals == -1) {
return false;
}
int[] r = new int[3];
int[] c = new int[3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
r[i] += grid[x + i][y + j];
c[j] += grid[x + i][y + j];
}
}
for (int i = 1; i < r.length; i++) {
if (r[0] != r[i]) {
return false;
}
}
return diagonals == r[0] && Arrays.equals(r, c);
}
private int diagonals(int[][] grid, int x, int y) {
int diagonals0 = grid[x][y] + grid[x + 1][y + 1] + grid[x + 2][y + 2];
int diagonals1 = grid[x + 2][y] + grid[x + 1][y + 1] + grid[x][y + 2];
return diagonals0 == diagonals1 ? diagonals0 : -1;
}
}
}
|
package com.tencent.mm.ui.tools;
public interface MMGestureGallery$e {
void bDu();
}
|
package Hashmap;
public class array {
}
|
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Table;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Label;
import org.eclipse.wb.swt.SWTResourceManager;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
/**
* This class is used to represent the list users interface
* @author Refined Storage developers
*
*/
public class GuiListUsers extends Composite {
private Table table;
/**
* Object Super
*/
public Object Super;
/**
* This method represents the list users interface and his functionality
* @param parent the composite parent
* @param style the desired style
* @param name the current user name
* @param Rs the refined storage
* @param Db the database
* @throws Throwable error generating interface
*/
public GuiListUsers(Composite parent, int style, String name, Refined_storage Rs, DbFunctions Db) throws Throwable {
super(parent, style);
Super = this;
this.setVisible(false);
this.setVisible(true);
setLayout(null);
Composite composite_1 = new Composite(this, SWT.NONE);
composite_1.setForeground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
composite_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_DARK_SHADOW));
composite_1.setBounds(0, 504, 869, 80);
table = new Table(this, SWT.BORDER | SWT.FULL_SELECTION);
table.setBounds(208, 107, 461, 334);
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn tcId = new TableColumn(table, SWT.CENTER);
tcId.setWidth(75);
tcId.setText("ID");
TableColumn tcName = new TableColumn(table, SWT.CENTER);
tcName.setWidth(195);
tcName.setText("Name");
TableColumn tcPriority = new TableColumn(table, SWT.CENTER);
tcPriority.setWidth(187);
tcPriority.setText("Priority");
//Element that assures correct window size
Label labelSizing1 = new Label(this, SWT.NONE);
labelSizing1.setBounds(808, 564, 61, 20);
ResultSet result_set = Rs.get_admin().list_users(Db);
if(result_set != null) {
TableItem item;
try {
while (result_set.next()) {
item=new TableItem(table, SWT.NONE);
item.setText(new String[] { String.valueOf(result_set.getInt("id")),
result_set.getString("name") ,
result_set.getString("priority")});
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.err.println(e.getMessage());
}
}
this.pack();
this.setVisible(true);
Button btnAddRemove = new Button(this, SWT.NONE);
btnAddRemove.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
try {
((Control) Super).setVisible(false);
new GuiManageUsers(parent, style, name, Rs, Db);
} catch (Throwable e1) {
e1.printStackTrace();
}
}
});
btnAddRemove.setBounds(53, 107, 100, 30);
btnAddRemove.setText("Add/Remove");
Composite composite = new Composite(this, SWT.NONE);
composite.setForeground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_DARK_SHADOW));
composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_DARK_SHADOW));
composite.setBounds(0, 0, 869, 80);
Button btnBack = new Button(composite, SWT.NONE);
btnBack.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
try {
((Control) Super).dispose();
new GuiAdminMenu(parent, style, name, Rs, Db);
} catch (Throwable e1) {
e1.printStackTrace();
}
}
});
btnBack.setText("Back");
btnBack.setBounds(10, 10, 75, 25);
Label labelMain_1 = new Label(composite, SWT.NONE);
labelMain_1.setText("Users");
labelMain_1.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
labelMain_1.setFont(SWTResourceManager.getFont("Corbel", 20, SWT.NORMAL));
labelMain_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_DARK_SHADOW));
labelMain_1.setBounds(397, 23, 75, 47);
Label labelLine = new Label(this, SWT.NONE);
labelLine.setText("______________");
labelLine.setFont(SWTResourceManager.getFont("Corbel", 16, SWT.NORMAL));
labelLine.setBounds(361, 461, 147, 40);
}
@Override
protected void checkSubclass() {
// Disable the check that prevents subclassing of SWT components
}
}
|
package com.clay.claykey.view.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.clay.claykey.object.parse.DoorLogs;
import com.clay.claykey.presenter.BasePresenter;
import com.clay.claykey.view.activity.BaseActivity;
import java.util.ArrayList;
import butterknife.ButterKnife;
/**
* Created by Mina Fayek on 1/15/2016.
*/
public abstract class BaseFragment<P extends BasePresenter> extends Fragment {
protected P presenter;
View rootView;
public void showLoading() {
((BaseActivity) getActivity()).showLoading();
}
public void hideLoading() {
((BaseActivity) getActivity()).hideLoading();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(getLayoutId(), container, false);
ButterKnife.bind(this, rootView);
if(presenter == null)
{
presenter = createPresenter();
presenter.initView(this);
}
return rootView;
}
protected abstract P createPresenter();
protected abstract int getLayoutId();
}
|
package com.tencent.mm.plugin.fav.a;
class i$a {
String bVs;
String iVU;
long iWb;
int in;
private i$a() {
}
/* synthetic */ i$a(byte b) {
this();
}
}
|
package com.example.weatherapi_dynamicurl.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.example.weatherapi_dynamicurl.Model.WeatherResponse;
import com.example.weatherapi_dynamicurl.Retrofit.WeatherServiceApi;
import com.example.weatherapi_dynamicurl.R;
import com.example.weatherapi_dynamicurl.Retrofit.ApiClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
TextView textView;
private WeatherServiceApi weatherServiceApi;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.tvWeather);
weatherServiceApi = ApiClient.getRetrofitInstance().create(WeatherServiceApi.class);
//String urlString = String.format("weather?q=%s&units=%s&appid=%s", name, units, getString(R.string.weather_api));
Call<WeatherResponse> weatherResponseCall = weatherServiceApi.getCurrentWeatherResponse();
weatherResponseCall.enqueue(new Callback<WeatherResponse>() {
@Override
public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {
if (response.code() == 200) {
WeatherResponse weatherResponse = response.body();
if (weatherResponse != null) {
String city = weatherResponse.getName();
double temp = weatherResponse.getMain().getTemp();
int humidity = weatherResponse.getMain().getHumidity();
double speed = weatherResponse.getWind().getSpeed();
String description =weatherResponse.getSys().getCountry();
int sunrise =weatherResponse.getSys().getSunrise();
textView.setText("Country: "+description+"\n"+"City: "+city+"\n"+"Temp: "+temp+"\n"+"Humidity: "+humidity+"\n"+"Speed: "
+speed+"\n"+"Sunrise: "+sunrise);
Toast.makeText(MainActivity.this, "" + city + "\n" + temp, Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onFailure(Call<WeatherResponse> call, Throwable t) {
Toast.makeText(MainActivity.this, "" + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
|
package com.andy.weexlab.activity.nav;
import android.content.Intent;
import android.util.Log;
import com.andy.weexlab.activity.BaseWXActivity;
/**
* Created by Andy on 2017/9/18.
*/
public class NavStartActivity extends BaseWXActivity {
@Override
public boolean renderLocal() {
return false;
}
@Override
public String urlRend() {
return "http://192.168.31.212/nav-start.js";
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.e("NavStartActivity", "destroyed");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (mWXSDKInstance!=null) {
mWXSDKInstance.onActivityResult(requestCode, resultCode, data);
}
}
}
|
package com.tech.sims.form.stock;
import com.tech.sims.web.form.IForm;
/**
* StockForm Implementation
*
* @author salil.
* @version 1.0
*/
public class StockForm implements IForm {
/**
* @version
*/
private static final long serialVersionUID = -9021717831422394480L;
/**
* symbol - symbol
*/
private String symbol;
/**
* name - name
*/
private String name;
/**
* companyName - companyName
*/
private String companyName;
/**
* description - description
*/
private String description;
/**
* quantity - quantity
*/
private String quantity;
/**
* currentMktPrice - currentMktPrice
*/
private String currentMktPrice;
/**
* currentMktPriceMin - currentMktPriceMin
*/
private String currentMktPriceMin;
/**
* currentMktPriceMax - currentMktPriceMax
*/
private String currentMktPriceMax;
/**
* actionPerformed - actionPerformed
*/
private String actionPerformed;
/**
* @return the symbol
*/
public String getSymbol() {
return symbol;
}
/**
* @param symbol
* the symbol to set
*/
public void setSymbol(String symbol) {
this.symbol = symbol;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the companyName
*/
public String getCompanyName() {
return companyName;
}
/**
* @param companyName
* the companyName to set
*/
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description
* the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the quantity
*/
public String getQuantity() {
return quantity;
}
/**
* @param quantity
* the quantity to set
*/
public void setQuantity(String quantity) {
this.quantity = quantity;
}
/**
* @return the currentMktPrice
*/
public String getCurrentMktPrice() {
return currentMktPrice;
}
/**
* @param currentMktPrice
* the currentMktPrice to set
*/
public void setCurrentMktPrice(String currentMktPrice) {
this.currentMktPrice = currentMktPrice;
}
/**
* @return the currentMktPriceMin
*/
public String getCurrentMktPriceMin() {
return currentMktPriceMin;
}
/**
* @param currentMktPriceMin
* the currentMktPriceMin to set
*/
public void setCurrentMktPriceMin(String currentMktPriceMin) {
this.currentMktPriceMin = currentMktPriceMin;
}
/**
* @return the currentMktPriceMax
*/
public String getCurrentMktPriceMax() {
return currentMktPriceMax;
}
/**
* @param currentMktPriceMax
* the currentMktPriceMax to set
*/
public void setCurrentMktPriceMax(String currentMktPriceMax) {
this.currentMktPriceMax = currentMktPriceMax;
}
/**
* @return the actionPerformed
*/
public String getActionPerformed() {
return actionPerformed;
}
/**
* @param actionPerformed
* the actionPerformed to set
*/
public void setActionPerformed(String actionPerformed) {
this.actionPerformed = actionPerformed;
}
}
|
package com.tencent.tencentmap.mapsdk.a;
public class bc {
static bx<Integer, ao> a = new bx(4086);
public static void a(int i, ao aoVar, by<Integer, ao> byVar) {
a.a(Integer.valueOf(i), aoVar, byVar, aoVar.e());
}
}
|
package com.smartwerkz.bytecode.vm.methods;
import com.smartwerkz.bytecode.primitives.JavaArray;
import com.smartwerkz.bytecode.primitives.JavaInteger;
import com.smartwerkz.bytecode.vm.Frame;
import com.smartwerkz.bytecode.vm.OperandStack;
import com.smartwerkz.bytecode.vm.RuntimeDataArea;
public final class SystemArraycopyMethod implements NativeMethod {
@Override
public void execute(RuntimeDataArea rda, Frame frame, OperandStack operandStack) {
JavaInteger length = (JavaInteger) frame.getLocalVariables().getLocalVariable(4);
JavaInteger destpos = (JavaInteger) frame.getLocalVariables().getLocalVariable(3);
JavaArray dest = (JavaArray) frame.getLocalVariables().getLocalVariable(2);
JavaInteger srcpos = (JavaInteger) frame.getLocalVariables().getLocalVariable(1);
JavaArray src = (JavaArray) frame.getLocalVariables().getLocalVariable(0);
for (int i = 0; i < length.intValue(); i++) {
dest.set(destpos.intValue() + i, src.get(srcpos.intValue() + i));
}
}
}
|
package com.tencent.mm.protocal.c;
import com.tencent.mm.bk.a;
import com.tencent.mm.bk.b;
public final class fk extends a {
public int iwE;
public int otY;
public b rgr;
public b rgs;
public int rgt;
public b rgu;
protected final int a(int i, Object... objArr) {
int a;
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
if (this.rgr != null) {
aVar.b(1, this.rgr);
}
aVar.fT(2, this.iwE);
if (this.rgs != null) {
aVar.b(3, this.rgs);
}
aVar.fT(4, this.rgt);
if (this.rgu != null) {
aVar.b(5, this.rgu);
}
aVar.fT(6, this.otY);
return 0;
} else if (i == 1) {
if (this.rgr != null) {
a = f.a.a.a.a(1, this.rgr) + 0;
} else {
a = 0;
}
a += f.a.a.a.fQ(2, this.iwE);
if (this.rgs != null) {
a += f.a.a.a.a(3, this.rgs);
}
a += f.a.a.a.fQ(4, this.rgt);
if (this.rgu != null) {
a += f.a.a.a.a(5, this.rgu);
}
return a + f.a.a.a.fQ(6, this.otY);
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (a = a.a(aVar2); a > 0; a = a.a(aVar2)) {
if (!super.a(aVar2, this, a)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
fk fkVar = (fk) objArr[1];
switch (((Integer) objArr[2]).intValue()) {
case 1:
fkVar.rgr = aVar3.cJR();
return 0;
case 2:
fkVar.iwE = aVar3.vHC.rY();
return 0;
case 3:
fkVar.rgs = aVar3.cJR();
return 0;
case 4:
fkVar.rgt = aVar3.vHC.rY();
return 0;
case 5:
fkVar.rgu = aVar3.cJR();
return 0;
case 6:
fkVar.otY = aVar3.vHC.rY();
return 0;
default:
return -1;
}
}
}
}
|
package com.buiminhduc.controller.web.product;
import com.buiminhduc.autowire.BeanFactory;
import com.buiminhduc.model.entity.ProductEntity;
import com.buiminhduc.model.response.PageResponse;
import com.buiminhduc.model.response.ProductResponse;
import com.buiminhduc.paging.PageRequest;
import com.buiminhduc.repository.ProductRepository;
import com.buiminhduc.service.ProductService;
import com.buiminhduc.service.session.SessionUtil;
import com.buiminhduc.util.FormUtil;
import com.buiminhduc.util.HttpUtil;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/search")
public class SearchController extends HttpServlet {
private ProductService productService;
private PageResponse<ProductResponse> pageResponse;
public SearchController() {
productService= (ProductService) BeanFactory.getBeans().get("productService");
pageResponse= new PageResponse<>();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PageResponse pageResponse = FormUtil.toModel(PageResponse.class, request);
response.sendRedirect("/product?page=1&maxPageItem=5&sortName=null&sortBy=null&ten="+pageResponse.getTen()+"");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
public static void main(String[] args) throws Exception {
ProductService productService= (ProductService) BeanFactory.getBeans().get("productService");
ProductEntity productEntities = productService.findById(2);
System.out.println(productEntities.toString());
}
}
|
package com.forkjoin.example.task;
import java.math.BigInteger;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
/**
*
* Factorial using fork join.
*
* @author Bharat Savanur
*
*/
public class ForkJoinTaskExample {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ForkJoinPool pool = new ForkJoinPool(4);
int factNum = 1000;
ForkJoinTask task = new ForkJoinTask(1, factNum);
java.util.concurrent.ForkJoinTask<BigInteger> i = pool.submit(task);
System.out.println("Result===>" + i.get());
}
}
|
package com.tencent.map.lib;
public enum MapLanguage {
LAN_CHINESE,
LAN_ENGLISH
}
|
package com.lanhuawei.rongyunlhwtext;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
/**
* Created by Ivan.L on 2018/5/28 .
*
*/
public class ConversationActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversation);
}
}
|
package com.example.iutassistant.NewActivities;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.example.iutassistant.Extra.Constant;
import com.example.iutassistant.Model.ProjectInfo;
import com.example.iutassistant.R;
import com.google.firebase.database.FirebaseDatabase;
public class Teachers_Requested_Project_Details_Activity extends AppCompatActivity {
private CardView accept, reject;
private TextView projectName, courseName, studentId, description;
private static ProjectInfo project_list_info;
SharedPreferences userInfo;
String supervisor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new__project__details__after__click__to__list_view);
userInfo=getSharedPreferences(Constant.USER_INFO_SHARED_PREFERENCES,MODE_PRIVATE);
supervisor=userInfo.getString(Constant.user_email_preference,"NA");
supervisor=supervisor.substring(0,supervisor.indexOf("."));
accept = findViewById(R.id.acceptProjectId);
reject = findViewById(R.id.rejectProjectId);
projectName = findViewById(R.id.prjectNameID);
courseName = findViewById(R.id.courseNameId);
studentId = findViewById(R.id.studentIdforProject);
description = findViewById(R.id.descriptionOfProjectId);
projectName.setText(project_list_info.getProjectName());
courseName.setText(project_list_info.getCourse());
studentId.setText(project_list_info.getAllSid());
description.setText(project_list_info.getDescription());
}
public static void setProject_list_info(ProjectInfo project_list_info) {
Teachers_Requested_Project_Details_Activity.project_list_info = project_list_info;
}
public void Accept_Request(View view){
FirebaseDatabase.getInstance().getReference(Constant.Ref).child(Constant.Project_Structure_Root).child(Constant.Project_Supervisor_Node).child(supervisor).child(Constant.Project_Status_Requested_Node).child(project_list_info.getProject_Crs()).removeValue();
FirebaseDatabase.getInstance().getReference(Constant.Ref).child(Constant.Project_Structure_Root).child(Constant.Project_Supervisor_Node).child(supervisor).child(Constant.Project_Status_Accepted_Node).child(project_list_info.getProject_Crs()).setValue(project_list_info.getBatch_prog());
FirebaseDatabase.getInstance().getReference(Constant.Ref).child(Constant.Project_Structure_Root).child(Constant.Project_Course_Node).child(project_list_info.getCourse()).child(project_list_info.getProjectName()).setValue(Constant.Project_Status_Accepted_Node);
String[] teamMateList= project_list_info.getAllSid().split(",");
for(String sid : teamMateList){
FirebaseDatabase.getInstance().getReference(Constant.Ref).child(Constant.Project_Structure_Root).child(Constant.Project_Student_Node).child(sid).child(project_list_info.getProject_Crs()).setValue(supervisor);
}
//generate a notification
}
public void Reject_Request(View view){
FirebaseDatabase.getInstance().getReference(Constant.Ref).child(Constant.Project_Structure_Root).child(Constant.Project_Course_Node).child(project_list_info.getCourse()).child(project_list_info.getProjectName()).removeValue();
FirebaseDatabase.getInstance().getReference(Constant.Ref).child(Constant.Project_Structure_Root).child(Constant.Project_Supervisor_Node).child(supervisor).child(Constant.Project_Status_Requested_Node).child(project_list_info.getProject_Crs()).removeValue();
FirebaseDatabase.getInstance().getReference(Constant.Ref).child(Constant.Project_Structure_Root).child(Constant.Project_Node).child(project_list_info.getProject_Crs()).removeValue();
}
}
|
package kr.blogspot.ovsoce.allsearch.main.fragment;
import android.content.Context;
import android.os.Bundle;
/**
* Created by ovso on 2016. 2. 19..
*/
public class PlaceholderPresenterImpl implements PlaceholderPresenter {
PlaceholderPresenter.View mView;
PlaceholderModel mModel;
PlaceholderPresenterImpl(PlaceholderPresenter.View view) {
mView = view;
mModel = new PlaceholderModel();
}
@Override
public void onActivityCreate(Context context, Bundle bundle) {
mView.onInit();
mView.replaceUrl(mModel.getUrl(context, bundle.getInt(PlaceholderFragment.ARG_SECTION_NUMBER)));
}
@Override
public void onQueryTextSubmit(Context context, Bundle bundle) {
mView.replaceUrl(mModel.getUrl(context, bundle.getInt(PlaceholderFragment.ARG_SECTION_NUMBER)));
}
}
|
package q0076_hard;
public class MinimumWindowSubstring {
}
|
package com.research.collection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author shc
* @date 2020-01-11
*/
public class CollectionStream {
public List<Person> data() {
List<Person> listPerson = new ArrayList<>();
listPerson.add(new Person(200, "半人马行者"));
listPerson.add(new Person(50, "莉娜"));
listPerson.add(new Person(100, "斯达拉"));
listPerson.add(new Person(80, "熊战士"));
listPerson.add(new Person(500, "末日使者"));
listPerson.add(new Person(18, "米拉娜"));
return listPerson;
}
public void foreach() {
List<Person> data = data();
data.forEach(person -> person.name = "DOTA2:" + person.name);
System.out.println(data);
}
/**
* 过滤保留返回true的数据
*/
public void filter() {
List<Person> data = data();
data = data.stream().filter(person -> person.age > 20).collect(Collectors.toList());
System.out.println(data);
data = data.stream().filter(person -> {
if (person.age > 250) {
person.name = "古老的力量正在苏醒";
return true;
}
return false;
}).collect(Collectors.toList());
System.out.println(data);
}
public void map() {
List<Person> data = data();
data.stream().map(Person::getName).collect(Collectors.toList());
}
/**
* 集合的合并
*/
public void flatMap() {
List<Person> data = data();
List<List<Person>> lists = new ArrayList<>();
lists.add(data);
lists.add(data);
lists.add(data);
lists.add(data);
// 将所有集合合并成一个集合
data = lists.stream().flatMap(pList -> pList.stream()).collect(Collectors.toList());
System.out.println(data);
}
/**
* 将集合转换成map
*/
public void toMap() {
List<Person> personList = data();
Map<String, Person> personMap = personList.stream().collect(Collectors.toMap(Person::getName,
Function.identity(), (oldValue, newValue) -> newValue));
System.out.println(personMap);
}
/**
* 累积处理
*/
public void reduce() {
List<Person> data = data();
data.stream().map(Person::getAge).reduce((x, y) -> x + y);
Integer result = data.stream().map(Person::getAge).reduce(0, (x, y) -> x+y);
System.out.println(result);
}
public static void main(String[] args) {
}
}
|
package org.zacharylavallee.batch.tasklet;
import org.apache.commons.io.FileUtils;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.zacharylavallee.file.FileCompressUtil;
import java.io.File;
import java.io.IOException;
public class FileCompressTasklet implements Tasklet {
private String startFileName;
private String archiveFileName;
private boolean deleteStartFile;
private FileCompressUtil.CompressionType compressionType;
public FileCompressTasklet(String startFileName, String archiveFileName) {
this.startFileName = startFileName;
this.archiveFileName = archiveFileName;
compressionType = FileCompressUtil.CompressionType.ZIP;
deleteStartFile = true;
}
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext)
throws Exception {
File startFile = new File(startFileName);
File archiveFile = new File(archiveFileName);
validateInputFile(startFile);
compressionType.compress(startFile, archiveFile);
cleanUp(startFile);
return RepeatStatus.FINISHED;
}
public void setCompressionType(String compressionType) {
this.compressionType = FileCompressUtil.CompressionType.valueOf(compressionType);
}
public void setDeleteStartFile(Boolean deleteStartFile) {
this.deleteStartFile = deleteStartFile;
}
private void cleanUp(File cleanUp) throws IOException {
if (deleteStartFile)
FileUtils.forceDelete(cleanUp);
}
private void validateInputFile(File input) {
if (!input.exists())
throw new RuntimeException("Input file does not exist: " + input);
if (!input.canRead())
throw new RuntimeException("Input file does have the correct permissions: " + input);
if (deleteStartFile && !input.canWrite())
throw new RuntimeException("Input file does have the correct permissions: " + input);
}
}
|
package com.pangpang6.books.leecode.chain;
import com.pangpang6.books.offer.structure.ListNode;
/**
* 给定链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
*
* 迭代排序
*/
public class SortChain {
public static void main(String[] args) {
ListNode<Integer> head1 = new ListNode<>(7);
head1.next = new ListNode<>(1);
head1.next.next = new ListNode<>(5);
head1.next.next.next = new ListNode<>(3);
head1.next.next.next.next = new ListNode<>(2);
ListNode<Integer> head = sortList(head1);
System.out.println(head);
// int perSortLen = 2;
// perSortLen <<= 1;
// System.out.println(perSortLen);
}
public static ListNode<Integer> sortList(ListNode<Integer> head) {
if (head == null) {
return head;
}
int length = 0;
ListNode<Integer> node = head;
while (node != null) {
length++;
node = node.next;
}
ListNode<Integer> dummyHead = new ListNode<>(0, head);
for (int perSortLen = 1; perSortLen < length; perSortLen <<= 1) {
ListNode<Integer> prev = dummyHead, curr = dummyHead.next;
while (curr != null) {
// 拆分 perSortLen 长度的链表1
ListNode head1 = curr;
for (int i = 1; i < perSortLen && curr != null && curr.next != null; i++) {
curr = curr.next;
}
// 拆分 perSortLen 长度的链表2
ListNode head2 = curr.next;
curr.next = null; //断开第一个链表和第二个链表的链接
curr = head2; //第二个链表头 重新赋值给curr
for (int i = 1; i < perSortLen && curr != null && curr.next != null; i++) {
curr = curr.next;
}
//再次断开 第二个链表最后的next的链接
ListNode<Integer> next = null;
if (curr != null) {
next = curr.next;
curr.next = null;
}
curr = next;
ListNode merged = merge(head1, head2);
prev.next = merged;
while (prev.next != null) {
prev = prev.next;
}
}
}
return dummyHead.next;
}
public static ListNode<Integer> merge(ListNode<Integer> head1, ListNode<Integer> head2) {
if (head1 == null) {
return head2;
}
if (head2 == null) {
return head1;
}
ListNode<Integer> index1 = head1;
ListNode<Integer> index2 = head2;
ListNode<Integer> index;
if (index1.val < index2.val) {
index = index1;
index1 = index1.next;
} else {
index = index2;
index2 = index2.next;
}
while (index1 != null && index2 != null) {
if (index1.val < index2.val) {
index.next = index1;
index = index.next;
index1 = index1.next;
} else {
index.next = index2;
index = index.next;
index2 = index2.next;
}
}
if (index1 != null) {
index.next = index1;
} else {
index.next = index2;
}
return head1.val < head2.val ? head1 : head2;
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.acceleratorfacades.cart.action.populator;
import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNullStandardMessage;
import de.hybris.platform.acceleratorfacades.cart.action.CartEntryAction;
import de.hybris.platform.acceleratorfacades.cart.action.CartEntryActionHandler;
import de.hybris.platform.acceleratorfacades.cart.action.CartEntryActionHandlerRegistry;
import de.hybris.platform.commercefacades.order.data.OrderEntryData;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.core.model.order.AbstractOrderEntryModel;
import de.hybris.platform.core.model.order.CartEntryModel;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Required;
/**
* Populates supported actions for a cart entry
*/
public class AcceleratorCartEntryActionPopulator implements Populator<AbstractOrderEntryModel, OrderEntryData>
{
private CartEntryActionHandlerRegistry cartEntryActionHandlerRegistry;
@Override
public void populate(final AbstractOrderEntryModel source, final OrderEntryData target) throws ConversionException
{
validateParameterNotNullStandardMessage("source", source);
validateParameterNotNullStandardMessage("target", target);
if (source instanceof CartEntryModel)
{
final Set<String> supportedActions = new HashSet<>();
for (final CartEntryAction action : CartEntryAction.values())
{
final CartEntryActionHandler handler = getCartEntryActionHandlerRegistry().getHandler(action);
if (handler != null && handler.supports((CartEntryModel) source))
{
supportedActions.add(action.toString());
}
}
target.setSupportedActions(supportedActions);
}
}
protected CartEntryActionHandlerRegistry getCartEntryActionHandlerRegistry()
{
return cartEntryActionHandlerRegistry;
}
@Required
public void setCartEntryActionHandlerRegistry(final CartEntryActionHandlerRegistry cartEntryActionHandlerRegistry)
{
this.cartEntryActionHandlerRegistry = cartEntryActionHandlerRegistry;
}
}
|
package smart.authentication;
import smart.config.RedisConfig;
import smart.entity.UserEntity;
import smart.util.Helper;
import smart.lib.Json;
import smart.lib.session.Session;
import java.util.Set;
public class UserToken extends Token {
public final static String REDIS_USER_PREFIX = "user:";
public UserToken() {
}
public UserToken(UserEntity userEntity) {
super(userEntity);
}
public static void deleteToken(long uid, String redisKey) {
RedisConfig.getStringRedisTemplate().delete(redisKey);
RedisConfig.getStringRedisTemplate().opsForSet().remove(REDIS_USER_PREFIX + uid, redisKey);
}
/**
* @param session user session
* @return user token
*/
public static UserToken from(Session session) {
if (session == null || session.getId(false) == null) {
return null;
}
String redisKey = Session.REDIS_PREFIX + session.getId(false);
Object obj = session.get(Helper.camelCase(UserToken.class));
if (obj instanceof String) {
UserToken userToken = UserToken.from((String) obj);
if (userToken == null) {
return null;
}
Boolean exists = RedisConfig.getStringRedisTemplate().opsForSet().isMember(REDIS_USER_PREFIX + userToken.getId(), redisKey);
if (exists == null || !exists) {
session.destroy();
return null;
}
return userToken;
}
return null;
}
/**
* get toke by token, for api
*
* @param json String
* @return user token
*/
public static UserToken from(String json) {
var userToken = Json.decode(json, UserToken.class);
if (userToken != null && userToken.isEffective()) {
return userToken;
}
return null;
}
/**
* save token, for http request
*
* @param session session
*/
public void save(Session session) {
String redisKey = Session.REDIS_PREFIX + session.getId(true);
session.set(Helper.camelCase(UserToken.class), toString());
RedisConfig.getStringRedisTemplate().opsForSet().add(REDIS_USER_PREFIX + getId(), redisKey);
updateRedis(redisKey);
}
/**
* save and get token, for api
*
* @return token
*/
public String saveAndGetToken() {
return null;
}
/**
* update redis data
*
* @param excludeRedisKey 排除的redis key
*/
@SuppressWarnings("EmptyCatchBlock")
private void updateRedis(String excludeRedisKey) {
Set<String> set = RedisConfig.getStringRedisTemplate().opsForSet().members(REDIS_USER_PREFIX + getId());
assert set != null;
set.forEach(redisKey -> {
if (redisKey.equals(excludeRedisKey)) {
return;
}
UserToken userToken = null;
Object obj = RedisConfig.getStringObjectRedisTemplate().opsForHash().get(redisKey, Helper.camelCase(UserToken.class));
if (obj instanceof String) {
userToken = UserToken.from((String) obj);
}
if (userToken == null) {
deleteToken(getId(), redisKey);
return;
}
if (userToken.getId().equals(getId()) && userToken.getName().equals(getName()) && userToken.getPassword().equals(getPassword()) && userToken.getSalt().equals(getSalt())) {
if (!userToken.getAvatar().equals(getAvatar()) || !userToken.getPhone().equals(getPhone()) || userToken.getLevel() != getLevel()) {
userToken.setAvatar(getAvatar());
userToken.setLevel(getLevel());
userToken.setPhone(getPhone());
RedisConfig.getStringObjectRedisTemplate().opsForHash().put(redisKey, Helper.camelCase(UserToken.class), toString());
}
} else {
deleteToken(getId(), redisKey);
}
});
}
@Override
public String toString() {
return Json.encode(this);
}
}
|
import greenfoot.*;
/**
* Write a description of class VisibleActor here.
*
* @author (your name)
* @version (a version number or a date)
*/
public abstract class VisibleActor extends Actor
{
protected CameraViewableWorld world;
private int worldX;
private int worldY;
@Override
public void addedToWorld(World world)
{
this.world = (CameraViewableWorld) world;
this.worldX = super.getX();
this.worldY = super.getY();
}
public void moveCamera(int x, int y)
{
this.world.setCameraLocation(x, y);
}
@Override
public int getX()
{
return this.worldX;
}
@Override
public int getY()
{
return this.worldY;
}
@Override
public final void setLocation(int x, int y)
{
if (world != null)
{
super.setLocation(x - world.getCameraX() + world.getWidth()/2, y - world.getCameraY() + world.getHeight()/2);
}
else
{
super.setLocation(x, y);
}
this.worldX = x;
this.worldY = y;
}
}
|
package cn.omsfuk.library.web.model;
import lombok.Data;
import java.util.Date;
@Data
public class Reader {
private int id;
private String username;
private String password;
private int max_borrow;
private String email;
private String phone;
private String qq;
private Date reg_date;
}
|
package utp.edu.pe.almacenamientoarchivos.models;
import java.util.ArrayList;
/**
* Created by GrupoUTP on 24/06/2016.
*/
public class Message {
private String text;
public Message(String text ) {
this.text = text;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
|
public class Player {
String username;
int score;
boolean isDrawing;
boolean guessed;
/**
* default constructor
*/
public Player() {
isDrawing = false;
}
/**
* Makes a new Player given just a username
*
* @param username
*/
public Player(String username) {
this.username = username;
score = 0;
isDrawing = false;
guessed = false;
}
/**
* Initializes a new Player given username, score, status of drawing, and if
* player has guessed. Used for updating player values in server userList.
*
* @param username1
* @param score1
* @param isDrawing1
* @param guessed1
*/
public Player(String username1, int score1, boolean isDrawing1,
boolean guessed1) {
username = username1;
score = score1;
isDrawing = isDrawing1;
guessed = guessed1;
}
public boolean isDrawing() {
return isDrawing;
}
public void setDrawing(boolean isDrawing) {
this.isDrawing = isDrawing;
}
public String toString() {
return username;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public boolean isGuessed() {
return guessed;
}
public void setGuessed(boolean guessed) {
this.guessed = guessed;
}
}
|
package com.raiza.qrpay;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.zxing.Result;
import org.json.JSONObject;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class SimpleScannerActivity extends BaseActivity implements ZXingScannerView.ResultHandler {
private static final String FLASH_STATE = "FLASH_STATE";
private static final String AUTO_FOCUS_STATE = "AUTO_FOCUS_STATE";
private ZXingScannerView mScannerView;
private boolean mFlash;
private boolean mAutoFocus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null) {
mFlash = savedInstanceState.getBoolean(FLASH_STATE, false);
mAutoFocus = savedInstanceState.getBoolean(AUTO_FOCUS_STATE, true);
} else {
mFlash = false;
mAutoFocus = true;
}
setContentView(R.layout.activity_simple_scanner);
setupToolbar();
ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame);
mScannerView = new ZXingScannerView(this);
contentFrame.addView(mScannerView);
}
@Override
public void onPause() {
super.onPause();
if (mScannerView != null)
mScannerView.stopCamera(); // Stop camera on pause
}
@Override
public void onResume() {
super.onResume();
if (mScannerView != null) {
//mScannerView.resumeCameraPreview(this);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
mScannerView.setFlash(mFlash);
mScannerView.setAutoFocus(mAutoFocus);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(FLASH_STATE, mFlash);
outState.putBoolean(AUTO_FOCUS_STATE, mAutoFocus);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem menuItem;
if(mFlash) {
menuItem = menu.add(Menu.NONE, R.id.menu_flash, 0, R.string.flash_on);
} else {
menuItem = menu.add(Menu.NONE, R.id.menu_flash, 0, R.string.flash_off);
}
MenuItemCompat.setShowAsAction(menuItem, MenuItem.SHOW_AS_ACTION_NEVER);
if(mAutoFocus) {
menuItem = menu.add(Menu.NONE, R.id.menu_auto_focus, 0, R.string.auto_focus_on);
} else {
menuItem = menu.add(Menu.NONE, R.id.menu_auto_focus, 0, R.string.auto_focus_off);
}
MenuItemCompat.setShowAsAction(menuItem, MenuItem.SHOW_AS_ACTION_NEVER);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.action_logout).setVisible(false);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.menu_flash:
mFlash = !mFlash;
if(mFlash) {
item.setTitle(R.string.flash_on);
} else {
item.setTitle(R.string.flash_off);
}
mScannerView.setFlash(mFlash);
return true;
case R.id.menu_auto_focus:
mAutoFocus = !mAutoFocus;
if(mAutoFocus) {
item.setTitle(R.string.auto_focus_on);
} else {
item.setTitle(R.string.auto_focus_off);
}
mScannerView.setAutoFocus(mAutoFocus);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void handleResult(Result rawResult) {
// Do something with the result here
String resStr = rawResult.getText();
if (resStr.contains(getString(R.string.base_url_api))) {
volleyJsonUserRequest(resStr);
} else {
String msg = getString(R.string.url_not_found);
displayError(msg);
}
}
public void volleyJsonUserRequest(String url){
String REQUEST_TAG = url;
JsonObjectRequest jsonObjectReq = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
Long usr_id = response.getJSONArray("users").getJSONObject(0).getLong("user_id");
String usr_name = response.getJSONArray("users").getJSONObject(0).getString("user_name");
Intent intent = new Intent(SimpleScannerActivity.this, PayActivity.class);
intent.putExtra("rec_usr_id", usr_id);
intent.putExtra("rec_usr_name", usr_name);
startActivity(intent);
finish();
} catch (Exception e) {
Log.d("Exception", e.getMessage());
String msg = e.getMessage();
displayError(msg);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("JSONRequest", "Error: " + error.getMessage());
String msg = error.getMessage();
if (msg == null) msg = getString(R.string.unexpected_error);
displayError(msg);
}
});
// Adding JsonObject request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectReq,REQUEST_TAG);
}
private void displayError(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mScannerView.resumeCameraPreview(SimpleScannerActivity.this);
}
}, 2000);
}
}
|
package manju;
import java.util.*;
public class A {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while(t-- > 0) {
int n = scan.nextInt();
int k = scan.nextInt();
int l = scan.nextInt();
int flag = 0;
int[] b = new int[k];
for(int i = 0; i < k; i++) {
b[i] = i+1;
//System.out.print(b[i] + " ");
}
if(n>k*l || (n>1 && k==1))
System.out.println("-1");
else {
HashMap<Integer,Integer> map = new HashMap<>();
int[] a = new int[n];
for(int x : b) {
map.put(x,0);
}
int count = 0;
for(int i = 0; i < n; i++) {
if(map.containsKey(b[i % k]) && map.get(b[i % k]) < l) {
a[i] = b[i % k];
map.put(a[i],map.getOrDefault(a[i],0)+1);
}
else {
flag = 1;
break;
}
}
//System.out.println();
if(flag == 1) {
System.out.println("-1");
}
else {
for(int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
}
}
}
}
}
|
package com.issp.ispp.repository;
import com.issp.ispp.entity.SolicitudDatos;
import com.issp.ispp.entity.Usuario;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface SolicitudDatosRepository extends CrudRepository<SolicitudDatos,Long> {
Optional<SolicitudDatos> findTop1BySolicitanteOrderByFechaEnvioDesc(Usuario solicitante);
List<SolicitudDatos> findAllByOrderByEnviadaDesc();
}
|
package com.tencent.mm.plugin.traceroute.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
class NetworkDiagnoseAllInOneUI$5 implements OnClickListener {
final /* synthetic */ NetworkDiagnoseAllInOneUI oDK;
NetworkDiagnoseAllInOneUI$5(NetworkDiagnoseAllInOneUI networkDiagnoseAllInOneUI) {
this.oDK = networkDiagnoseAllInOneUI;
}
public final void onClick(DialogInterface dialogInterface, int i) {
this.oDK.startActivity(new Intent("android.settings.MANAGE_APPLICATIONS_SETTINGS"));
}
}
|
package com.example.wattson.main_fragments;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.SpannableString;
import android.text.style.TextAppearanceSpan;
import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.TextView;
import com.example.wattson.Adapter.UtilityAdapter;
import com.example.wattson.HomeActivity;
import com.example.wattson.InfoClasses.ApplianceInfo;
import com.example.wattson.R;
import com.example.wattson.utils.SpacingItemDecorator;
import com.google.android.material.textview.MaterialTextView;
import java.util.ArrayList;
public class UtilityInfoFragment extends Fragment {
private TextView m_backArrow;
private TextView txt_Day;
private TextView txt_Week;
private TextView txt_Month;
private TextView txt_Year;
private TextView txt_header;
private TextView on_OnIndicator;
private TextView m_currentTimePicked;
private MaterialTextView txt_sum;
private TextView img_symbol;
private StateTime m_StateTime;
private HomeActivity ac_HomeActivity;
private ApplianceInfo m_currentAppliance;
public UtilityInfoFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_utility_info, container, false);
ac_HomeActivity = (HomeActivity) getActivity();
// get the current appliance postition from bundle
Bundle bundle = getArguments();
int position = bundle.getInt("pos");
//save an instance of the current appliance
ArrayList<ApplianceInfo> ApplianceInfoList = ac_HomeActivity.getApplianceList();
m_currentAppliance = ApplianceInfoList.get(position);
return rootView;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
m_backArrow = (TextView) getView().findViewById(R.id.UtilBackArrow);
txt_Day = (TextView) getView().findViewById(R.id.textViewDay);
txt_Week = (TextView) getView().findViewById(R.id.textViewWeek);
txt_Month= (TextView) getView().findViewById(R.id.textViewMonth);
txt_Year = (TextView) getView().findViewById(R.id.textViewYear);
txt_header = (TextView) getView().findViewById(R.id.textViewUtilPageTitle);
txt_sum = (MaterialTextView) getView().findViewById(R.id.textViewUTodaysAmmount);
img_symbol = (TextView) getView().findViewById(R.id.textViewUtilityHeaderSymbol);
on_OnIndicator = (TextView) getView().findViewById(R.id.onIndicatorUtilInfo);
txt_header.setText(m_currentAppliance.getApplianceName());
img_symbol.setCompoundDrawablesWithIntrinsicBounds(m_currentAppliance.getItemSymbol(),0,0,0);
m_currentTimePicked = txt_Day;
m_StateTime = StateTime.DAY;
setCurrentTimePicked();
String[] labels = getResources().getStringArray(R.array.utility_header_list);
// num activation, total time on, avg cost per use
String[] values = {String.valueOf(m_currentAppliance.getNumActivations()),
m_currentAppliance.getTotalTimeOn(),
String.format("%.3f", m_currentAppliance.getDailyPrice()/m_currentAppliance.getNumActivations())};
RecyclerView rView = (RecyclerView)getView().findViewById(R.id.recycleViewUtility);
UtilityAdapter myAdapter = new UtilityAdapter(getContext(), labels, values);
rView.setAdapter(myAdapter);
rView.setLayoutManager(new LinearLayoutManager(getContext()));
// change this to create a larger margin between the items in recycle view
SpacingItemDecorator itemDecor = new SpacingItemDecorator(50);
rView.addItemDecoration(itemDecor);
// this controls the on indicator
on_OnIndicator.setVisibility(View.INVISIBLE);
//checks if on, if so starts blinking
if(m_currentAppliance.isCurrentlyOn()){
on_OnIndicator.setVisibility(View.VISIBLE);
Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(1000); //You can manage the blinking time with this parameter
anim.setStartOffset(100);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
on_OnIndicator.startAnimation(anim);
}
txt_sum.setText(String.format("%.3f", m_currentAppliance.getDailyPrice()));
// Go back to the Home Page
m_backArrow.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
Fragment someFragment = new HomeFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, someFragment ); // give your fragment container id in first parameter
transaction.addToBackStack(null); // if written, this transaction will be added to backstack
transaction.commit();
}
});
//change to day view
txt_Day.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
clearCurrentTime();
m_StateTime = StateTime.DAY;
m_currentTimePicked = txt_Day;
setCurrentTimePicked();
}
});
//change to week view
txt_Week.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
clearCurrentTime();
m_StateTime = StateTime.WEEK;
m_currentTimePicked = txt_Week;
setCurrentTimePicked();
}
});
//change to month view
txt_Month.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
clearCurrentTime();
m_StateTime = StateTime.MONTH;
m_currentTimePicked = txt_Month;
setCurrentTimePicked();
}
});
//change to year view
txt_Year.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
clearCurrentTime();
m_StateTime = StateTime.YEAR;
m_currentTimePicked = txt_Year;
setCurrentTimePicked();
}
});
}
/**
* this meths sets the time fram picked (day, week ...)
*/
private void setCurrentTimePicked(){
m_currentTimePicked.setClickable(false);
SpannableString content = new SpannableString(m_StateTime.getValue());
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
m_currentTimePicked.setText(content);
m_currentTimePicked.setTextColor(Color.BLACK);
}
/**
* This method clears the
*/
private void clearCurrentTime(){
m_currentTimePicked.setText(m_StateTime.getValue());
m_currentTimePicked.setTextColor(getResources().getColor(R.color.font_gray));
m_currentTimePicked.setClickable(true);
}
public enum StateTime {
DAY("Day"), WEEK("WK"), MONTH("MO"), YEAR("YR");
private final String value;
StateTime(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
}
|
package asus.ft.autoBrowsing;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
public class Webview_stream extends Activity{
public static Context Webview_context;
private WebView webView_1=null;
Context Webview_stream_context;
Bundle _bundle_webview;
public boolean GETHTML5_COMPLETE=false;
public String realPlayUrl="";
int[] count=new int[256];
Thread VideoPlay;
public static Webview_stream instance = null;
String ua = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36";
//Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36
//String ua1= "Mozilla/5.0 (iPhone; CPU iPhone OS 7_1 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D5145e Safari/9537.53";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview_2);
instance=this;
_bundle_webview =this.getIntent().getExtras();
DisplayMetrics monitorsize =new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(monitorsize);
webView_1 =(WebView) findViewById(R.id.webView_1);
WebSettings setting = webView_1.getSettings();
getWindow().setFlags(0x1000000, 0x1000000);
setting.setJavaScriptEnabled(true);
setting.setDomStorageEnabled(true);
setting.setJavaScriptCanOpenWindowsAutomatically(true);
setting.setDatabaseEnabled(true);
setting.setDefaultTextEncodingName("UTF-8");
setting.setUseWideViewPort(true);
setting.setAllowFileAccess(true);
setting.setAppCacheEnabled(true);
setting.setLoadWithOverviewMode(true);
setting.setUseWideViewPort(true);
setting.setCacheMode(WebSettings.LOAD_DEFAULT);
setting.setPluginsEnabled(true);
setting.setBuiltInZoomControls(true);
setting.setSupportZoom(true);
//webView_1.addJavascriptInterface(new DemoJavaScriptInterface(),"HTMLOUT");
class InJavaScriptLocalObj {
public void showSource(String GetId) {
/*if (html5url != null && !GETHTML5_COMPLETE) {
GETHTML5_COMPLETE = true;
realPlayUrl = html5url;
} */
// Log.i("conowen", "html5url=" + html5url);
Log.i(PathAndFlag.LogcatTAG, " GetId=" + GetId);
}
}
setting.setPluginState(WebSettings.PluginState.ON);
// webView_1.addJavascriptInterface(new InJavaScriptLocalObj(), "js_method");
//webView_1.setWebViewClient(mWebViewClient);
setting.setUserAgentString(ua);
webView_1.setWebChromeClient(new WebChromeClient());
webView_1.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//view.loadUrl("javascript:(alert(navigator.userAgent))()");
//SystemClock.sleep(10000);
/*try{
Runtime.getRuntime().exec(new String[]{"input", "tap", "293 241"});
Log.i("PathAndFlag.LogcatTAG", " input, tap, 293 241" );
}
catch(IOException e){
Log.i("PathAndFlag.LogcatTAG", " IOException=" + e.getMessage());
}*/
//view.loadUrl("javascript:(function() { document.getElementsByTagName('player_html5').play})()");
// view.loadUrl("javascript:(window.js_method.showSource( document.getElementById('movie_player')))");
//view.loadUrl("javascript:window.js_method.showSource(document.getElementsByTagName('video')[0].src);");
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
// view.loadUrl("javascript:(function(){document.getElementsByTagName('isAOUTD).innerHTML = \"true\"})();");
view.loadUrl(url);
return true;
}
});
String url= _bundle_webview.getString("loadUrl");
String s = "<html><head><meta charset=\"utf-8\" /><title>swf</title></head><body bgcolor=\"#000000\">"
+ "<embed src=\" "+url + "\" "
+ " width=\"100%\" height=\"100%\" align=\"middle\" allowScriptAccess=\"always\""
+ " allowFullScreen=\"true\" wmode=\"transparent\" "
+ "type=\"application/x-shockwave-flash\"> </embed></body></html>";
String s1 ="<html><body> <iframe height=100% width=100% src=\""+url+ "\" frameborder=0 allowfullscreen=\"true\" ></iframe></body></html>";
String S2="<video width=device-width height=device-height controls=\"controls\" poster=\"video.jpg\">"
+ " <iframe height=600 width=800 src=\""+url+ "\" frameborder=0 allowfullscreen></iframe> ></video>";
String s3 ="<embed src=\"http://player.youku.com/player.php/Type/Folder/Fid/23800841/Ob/1/sid/XMTMwOTYyNzgyOA==/v.swf\" quality=\"high\" width=\"480\" height=\"400\" align=\"middle\" allowScriptAccess=\"always\" allowFullScreen=\"true\" mode=\"transparent\" type=\"application/x-shockwave-flash\"></embed>";
Log.i(PathAndFlag.LogcatTAG, "Open Webview URL " + url);
webView_1.loadData(s1, "text/html; charset=UTF-8", null);
VideoPlay = new Thread(new VideoPlayClick());
VideoPlay.start();
// MediaController mc = new MediaController(this);
//videoView1.setMediaController(mc);
// videoView1.setVideoURI(Uri.parse(s));
// videoView1.start();
//webView_1.loadUrl(s1);
}
/*final class DemoJavaScriptInterface {
public void showHTML(String html) {
new AlertDialog.Builder(AppCt).setTitle("HTML codes")
.setMessage(html)
.setPositiveButton(android.R.string.ok, null)
.setCancelable(false).create().show();
}
}*/
/* WebViewClient mWebViewClient = new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
//view.loadUrl(url);
return true;
}
};*/
class VideoPlayClick implements Runnable {
Message message;
@Override
public void run() {
// TODO Auto-generated method stub
try
{
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
boolean stop = false;
Log.i("PathAndFlag.LogcatTAG", " Video now isMusicActive= " +stop);
int Count=0;
while(Count <= 10)
{
try
{
Runtime.getRuntime().exec(new String[]{"input", "tap", "293 241"});
Log.i(PathAndFlag.LogcatTAG, " input, tap, 293 241" );
Log.i(PathAndFlag.LogcatTAG, " webView_1.isShown()= " +webView_1.isShown());
}
catch(Exception e)
{
Log.i(PathAndFlag.LogcatTAG, "Input tap Exception=" + e.getMessage());
}
Thread.sleep(3000);
Count=Count+1;
}
/*boolean Flag=false;
while(!Flag)
{
if (stop)
{
System.out.println("true");
Log.i(PathAndFlag.LogcatTAG, " Video play is true" );
Log.i(PathAndFlag.LogcatTAG, " webView_1.isShown()= " +webView_1.isShown());
Flag=true;
break;
}
else
{
System.out.println("false");
Log.i(PathAndFlag.LogcatTAG, " Video is not play" );
try
{
Runtime.getRuntime().exec(new String[]{"input", "tap", "293 241"});
Log.i(PathAndFlag.LogcatTAG, " input, tap, 293 241" );
Log.i(PathAndFlag.LogcatTAG, " webView_1.isShown()= " +webView_1.isShown());
}
catch(Exception e)
{
Log.i(PathAndFlag.LogcatTAG, "Input tap Exception=" + e.getMessage());
}
}
Thread.sleep(5000);
stop = am.isMusicActive();
}*/
}
catch(Exception ee)
{
Log.i(PathAndFlag.LogcatTAG, " Threa Exception=" + ee.getMessage());
}
}
}
@Override
public void onPause()
{
super.onPause();
Log.i(PathAndFlag.LogcatTAG,"onPause()");
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
//this.finish();
Log.i(PathAndFlag.LogcatTAG,"onDestroy()");
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
//this.finish();
Log.i(PathAndFlag.LogcatTAG,"onStop()");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.