blob_id stringlengths 40 40 | language stringclasses 1 value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34 values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2 values | text stringlengths 9 3.8M | download_success bool 1 class |
|---|---|---|---|---|---|---|---|---|---|---|---|
b2a703545527b033f1182cd67c2cfa067e7257fc | Java | ganml/jclust | /jclust/src/clustering/algorithm/Mss.java | UTF-8 | 2,978 | 2.59375 | 3 | [] | no_license | package clustering.algorithm;
import java.util.*;
import org.apache.commons.math3.stat.correlation.PearsonsCorrelation;
import org.apache.commons.math3.stat.ranking.NaturalRanking;
import clustering.cluster.*;
import clustering.util.CommonFunction;
public class Mss extends ClusteringAlgorithm {
protected double delta;
protected double[][] Z; // rank matrix
protected PearsonsCorrelation pc;
protected NaturalRanking nr;
protected double[][] Zn;
// results
protected List<Cluster> lstcluster;
protected int numiter;
public Mss() {
pc = new PearsonsCorrelation();
nr = new NaturalRanking();
}
@Override
protected void work() throws Exception {
initialize();
iteration();
}
@Override
protected void fetchResults() throws Exception {
lstcluster = new ArrayList<Cluster>();
Set<Integer> setIndex = new HashSet<Integer>();
for(int i=0; i<ds.size(); ++i) {
setIndex.add(i);
}
int nCount = 1;
while(!setIndex.isEmpty()) {
int ii = setIndex.iterator().next();
setIndex.remove(ii);
Cluster c = new Cluster(String.format("C%d", nCount++));
c.add(ds.get(ii));
lstcluster.add(c);
List<Integer> listIndex = new ArrayList<Integer>();
for(int k : setIndex) {
double dDiff = 0.0;
for(int j=0; j<ds.dimension(); ++j) {
dDiff += Math.abs(Zn[ii][j] - Zn[k][j]);
}
if(dDiff < 1e-6) {
listIndex.add(k);
}
}
for(int k: listIndex) {
c.add(ds.get(k));
setIndex.remove(k);
}
}
PartitionClustering pc = new PartitionClustering(ds, lstcluster);
results.insert("pc", pc);
results.insert("numiter", new Integer(numiter));
}
protected void initialize() {
Z = new double[nRecord][nDimension];
for(int i=0; i<nRecord; ++i) {
double[] rank = nr.rank(ds.get(i).getValues());
for(int j=0; j<nDimension; ++j) {
Z[i][j] = rank[j];
}
}
}
protected void iteration() {
Zn = Z.clone();
boolean bChanged = true;
double[] oldRank;
double[] dSum = new double[nDimension];
numiter = 0;
while(bChanged) {
bChanged = false;
for(int i=0; i<nRecord; ++i) {
for(int r=0; r<nDimension; ++r) {
dSum[r] = 0.0;
}
for(int j=0; j<nRecord; ++j) {
double dTemp = (1-pc.correlation(Zn[i], Z[j]))/2;
if(dTemp < delta) {
for(int r=0; r<nDimension; ++r) {
dSum[r] += Z[j][r];
}
}
}
oldRank = Zn[i];
Zn[i] = nr.rank(dSum);
for(int r=0; r<nDimension; ++r) {
if(Math.abs(oldRank[r] - Zn[i][r]) > 1e-8) {
bChanged = true;
break;
}
}
}
++numiter;
if(numiter % 100 ==0 ){
CommonFunction.log(String.format("iteration %d", numiter));
}
}
}
protected void setupArguments() throws Exception {
super.setupArguments();
delta = arguments.getReal("delta");
}
}
| true |
1d10ce8575c29a5f86757f8e1cdd38d1bb5886e6 | Java | yong396040003/bsxt_admin | /src/main/java/com/yong/bsxt_admin/service/serviceImpl/CommentServiceImpl.java | UTF-8 | 3,741 | 2.109375 | 2 | [] | no_license | package com.yong.bsxt_admin.service.serviceImpl;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yong.bsxt_admin.jutil.AjaxReturnJson;
import com.yong.bsxt_admin.mapper.CommentMapper;
import com.yong.bsxt_admin.pojo.Comment;
import com.yong.bsxt_admin.pojo.Student;
import com.yong.bsxt_admin.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class CommentServiceImpl implements CommentService {
@Autowired
private CommentMapper commentMapper;
@Override
public JSONObject insertComment(Comment comment) {
int code = 0;
String msg = "success";
String name = "";
String number = String.valueOf(comment.getNumber());
if (number.length() == 8) {
name = commentMapper.selectStudentByNumber(number);
} else if (number.length() == 10) {
name = commentMapper.selectTeacherByNumber(number);
}
if (!"".equals(name)) {
comment.setName(name);
}
try {
code = commentMapper.insertComment(comment);
} catch (Exception e) {
//让前台知道为什么会插入失败
msg = e.getMessage();
}
return AjaxReturnJson.ajaxReturnJson.getMsgReturnJson(code, msg, null);
}
@Override
public JSONObject selectCommentByCode(int page, int limit, String code) {
//调用pageHelper分页(物理分页)
PageHelper.startPage(page, limit);
List<Comment> commentList = commentMapper.selectCommentByCode(code);
PageInfo pageInfo = new PageInfo<>(commentList);
return AjaxReturnJson.ajaxReturnJson.getTableReturnJson(0, pageInfo.getTotal(), limit, commentList);
}
@Transactional(rollbackFor = Exception.class)
@Override
public JSONObject deleteCommentByTime(String time) {
int code = 0;
String msg = "success";
try {
code = commentMapper.deleteCommentByTime(time);
} catch (Exception e) {
//让前台知道为什么会修改失败
msg = e.getMessage();
}
return AjaxReturnJson.ajaxReturnJson.getMsgReturnJson(code, msg, null);
}
@Override
public JSONObject doCommentByDone(String done) {
int code = 0;
String msg = "success";
try {
code = commentMapper.doCommentByDone(done);
} catch (Exception e) {
//让前台知道为什么会插入失败
msg = e.getMessage();
}
return AjaxReturnJson.ajaxReturnJson.getMsgReturnJson(code, msg, null);
}
@Override
public JSONObject selectAllComment(int page, int limit) {
//调用pageHelper分页(物理分页)
PageHelper.startPage(page, limit);
List<Comment> commentList = commentMapper.selectAllComment();
PageInfo pageInfo = new PageInfo<>(commentList);
return AjaxReturnJson.ajaxReturnJson.getTableReturnJson(0, pageInfo.getTotal(), limit, commentList);
}
@Transactional(rollbackFor = Exception.class)
@Override
public JSONObject bathDeleteCommentByTime(String[] data) {
int code = 0;
String msg = "success";
try {
code = commentMapper.bathDeleteCommentByTime(data);
} catch (Exception e) {
//让前台知道为什么会修改失败
msg = e.getMessage();
}
return AjaxReturnJson.ajaxReturnJson.getMsgReturnJson(code, msg, null);
}
}
| true |
6cc93a1579bb076758d21528ecba3178cf896ec7 | Java | bibhavtiwari/Bibhav-CapgeminiJA17-Projects | /Java8Feature/src/com/capgemin/streamapi/STreamAPIExample.java | UTF-8 | 953 | 3.125 | 3 | [] | no_license | package com.capgemin.streamapi;
import java.util.ArrayList;
import java.util.List;
public class STreamAPIExample {
public static List<String> getPlaces() {
// TODO Auto-generated method stub
List<String> countriesPlaces = new ArrayList<String>();
//list of countries
countriesPlaces.add("Nepal,Kathmandu");
countriesPlaces.add("Orissa,Puri");
countriesPlaces.add("SriLanka,Colombo");
countriesPlaces.add("India , New Delhi");
countriesPlaces.add("WestBengal , Kolkata");
return countriesPlaces;
}
public static void main(String[]args)
{
List<String> area = getPlaces();
System.out.println("Places from Orissa");
area.stream().filter((p)->p.startsWith("Orissa"))
.map((p)->p.toUpperCase())
.sorted()
.forEach((p)->System.out.println(p));
long count = area.stream().filter((s)->s.endsWith("a")).count();
System.out.println(count);
}
}
| true |
ba1384dd8a6508929c1ac3cac650de96d2dccef3 | Java | nuxeo/ant-assembly-maven-plugin | /src/main/java/org/nuxeo/build/ant/artifact/ArtifactForeach.java | UTF-8 | 2,625 | 1.914063 | 2 | [] | no_license | /*
* (C) Copyright 2009-2014 Nuxeo SA (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Sun Seng David TAN, jcarsique
*/
package org.nuxeo.build.ant.artifact;
import java.io.IOException;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.Sequential;
import org.eclipse.aether.artifact.Artifact;
/**
* Iterate through an artifact set
*
* Usage:
* {@code <artifact:foreach setref="bundles" artifactJarPathProperty="path" >
* (...) </artifact:foreach>}
*
*/
public class ArtifactForeach extends Sequential {
public String property;
public ArtifactSet artifactSet;
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public ArtifactSet getArtifactSet() {
return artifactSet;
}
public void setSetref(String setref) {
artifactSet = (ArtifactSet) getProject().getReference(setref);
}
@Override
public void execute() throws BuildException {
for (Artifact artifact : artifactSet.getArtifacts()) {
String canonicalPath = null;
try {
canonicalPath = artifact.getFile().getCanonicalPath();
} catch (IOException e) {
throw new BuildException(
"Failed to artifact file canonical path for "
+ artifact, e);
}
getProject().setProperty(property + ".file.path", canonicalPath);
getProject().setProperty(property + ".archetypeId",
artifact.getArtifactId());
getProject().setProperty(property + ".groupId",
artifact.getGroupId());
getProject().setProperty(property + ".version",
artifact.getBaseVersion());
try {
super.execute();
} catch (BuildException e) {
throw new BuildException(
"Couldn't execute the task for artifact " + artifact, e);
}
}
}
}
| true |
f4341f524fa0e63f6d5c39a89b2d603f54cddcc0 | Java | dimitradebnath/LoginRegistrationFinal | /src/com/d/LoginServlet.java | UTF-8 | 3,893 | 2.46875 | 2 | [] | no_license | package com.d;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
PreparedStatement pst = null;
Connection conection=null;
String uname,country,gender;
String pass;
String query="SELECT uname,password FROM logindetails where uname=? AND password=?";
String generatedPassword = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
///ResultSet rs = null;
//boolean flag;
uname = request.getParameter("uname");
System.out.println("Username"+uname);
pass = request.getParameter("pass");
System.out.println("Password"+pass);
String passwordToHash = pass;
try {
conection = Dbutil.getConnection();
System.out.println(conection);
}
catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println(e);
}
try {
MessageDigest md = MessageDigest.getInstance("MD5");
//Add password bytes to digest
md.update(passwordToHash.getBytes());
//Get the hash's bytes
byte[] bytes = md.digest();
//This bytes[] has bytes in decimal format;
//Convert it to hexadecimal format
StringBuilder sb = new StringBuilder();
for(int i=0; i< bytes.length ;i++)
{
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
//Get complete hashed password in hex format
generatedPassword = sb.toString();
pst = conection.prepareStatement(query);
pst.setString(1,uname);
pst.setString(2, generatedPassword);
ResultSet rs = pst.executeQuery();
//System.out.println(rs);
if(rs.next()) {
HttpSession session = request.getSession();
session.setAttribute("uname", uname);
System.out.println("Logged in Successfully!!");
/*RequestDispatcher rd = request.getRequestDispatcher("WelcomeJSP.jsp");
rd.include(request, response);*/
response.sendRedirect("welcome");
}
else
{
response.setContentType("text/html");
writer.print("<script>alert('Login failed! try again');</script>");
request.setAttribute("error", "Incorrect username or password");
RequestDispatcher rd = request.getRequestDispatcher("LoginJSP.jsp");
rd.forward(request, response);
}
}
catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
/*if(connection!=null)
Dbutil.closeConnection();
System.out.println(conection);*/
if(pst!=null) {
try {
pst.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conection!=null) {
try {
conection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
RequestDispatcher rd = req.getRequestDispatcher("/LoginJSP.jsp");
rd.forward(req, resp);
}
}
| true |
fe2d5ec527a215120760baf681178ade20592694 | Java | sundar006/testLeaf | /day2/MyKid.java | UTF-8 | 272 | 2.203125 | 2 | [] | no_license | package week1.day2;
public class MyKid {
public static void main(String[] args) {
MyMobile obj1 = new MyMobile();
System.out.println(obj1.brand);
System.out.println(obj1.price);
obj1.setAlarm();
obj1.makeCall();
obj1.printString();
}
} | true |
7b571207698ad7d15c94b889e64acd09cc04c8a5 | Java | mslrsl92c41f158l/ScuolaCucinaGreen | /src/servlet/CorsiServlet.java | UTF-8 | 1,902 | 2.390625 | 2 | [] | no_license | package servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
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.SingletonConnection;
import entity.Corso;
import exceptions.ConnessioneException;
@WebServlet("/corsi")
public class CorsiServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Corso> corsi = new ArrayList<>();
try {
Connection conn = SingletonConnection.getInstance();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(
"select titolo, Durata, numeroMaxPartecipanti, costo, descrizione from catalogo join calendario using(id_corso)");
while (rs.next()) {
corsi.add(new Corso(rs.getString(1), rs.getInt(2), rs.getInt(3), rs.getDouble(4), rs.getString(5)));
}
request.setAttribute("courses", corsi);
} catch (SQLException | ConnessioneException e) {
// ...
}
request.getRequestDispatcher("WEB-INF/jsp/corsi2.jsp").forward(request, response);
}
public CorsiServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
/**
* @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);
}
}
| true |
66c9c44e39dbd03db2ce35596366be5a67e39b63 | Java | davichiar/2019_CPCOP_MovieProject | /Movie_Application/app/src/main/java/NaverImagePrint/GalleryAdapter.java | UTF-8 | 1,672 | 2.234375 | 2 | [] | no_license | package NaverImagePrint;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.koushikdutta.ion.Ion;
import java.util.ArrayList;
import com.example.davichiar.movie_application.R;
public class GalleryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
ArrayList<NaverImageItem> imageItems;
Context context;
public GalleryAdapter(ArrayList<NaverImageItem> imageItems, Context context) {
this.imageItems = imageItems;
this.context = context;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder;
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.image, parent, false);
viewHolder = new MyItemHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (imageItems.get(position) != null) {
Ion.with(context).load(imageItems.get(position).getLink()).withBitmap()
.placeholder(R.mipmap.placeholder).intoImageView(((MyItemHolder) holder).mImg);
}
}
@Override
public int getItemCount() {
return imageItems.size();
}
class MyItemHolder extends RecyclerView.ViewHolder {
ImageView mImg;
public MyItemHolder(View itemView) {
super(itemView);
mImg = (ImageView) itemView.findViewById(R.id.item_img);
}
}
}
| true |
5bc9cd565685595091f263e3570403d19aab3715 | Java | DiegoBernal17/EjerciciosPOO | /unidad3/superficie/Rectangulo.java | UTF-8 | 381 | 3.15625 | 3 | [] | no_license | package unidad3.superficie;
/**
*
* @author Padilla Bernal
*/
public class Rectangulo extends Superficie {
private double base;
private double altura;
public Rectangulo(double base, double altura)
{
this.base = base;
this.altura = altura;
this.calcularArea();
}
public void calcularArea()
{
area = base*altura;
}
}
| true |
7e6c27b2b675f3737dcce47abb033149bb62b0b7 | Java | Mateman84/chattApp | /src/main/java/com/example/demo/entities/Channel.java | UTF-8 | 835 | 2.46875 | 2 | [] | no_license | package com.example.demo.entities;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name="channels")
public class Channel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@Transient
private List<Message> messages;
public Channel() {
}
public Channel(String name) {
this.name = name;
}
public List<Message> getMessages() {
return messages;
}
public void setMessages(List<Message> messages) {
this.messages = messages;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getChannelName() {
return name;
}
public void setChannelName(String channelName) {
this.name = name;
}
}
| true |
93ffc919ad3e18c7010a26d5225b4fa191b78c32 | Java | parkkobum/ThejoeunLecture | /JAVA/Work/JavaApplication/src/main/java/java11/st4/Oper.java | UTF-8 | 585 | 3.03125 | 3 | [] | no_license | package java11.st4;
public class Oper {
public Oper() {
super();
// TODO Auto-generated constructor stub
}
double Div(int x, int y) {
double div = 0;
try {
div = (double) x / y;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return div;
}
int Minus(int x, int y) {
return x - y;
}
int Mul(int x, int y) {
return x * y;
}
int Add(int x, int y) {
return x + y;
}
}
| true |
581868c774f2ac00ac899382dcf958dfb0ba0ebe | Java | zhguangdaniel/cn.zhguang.mytry | /src/main/java/com/taobao/yinggang/nomal/string/StringTest.java | UTF-8 | 1,248 | 2.75 | 3 | [] | no_license | /*
* $HeadURL: $
* $Id: $
* Copyright (c) 2011 by Ericsson, all rights reserved.
*/
package com.taobao.yinggang.nomal.string;
/**
* @author egugzhg
* @version $Revision: $
*/
public class StringTest {
/** Revision of the class */
public static final String _REV_ID_ = "$Revision: $";
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// String aString = "";
// String[] bs = aString.split(",");
// System.out.println(bs.length);
// for (String s : bs) {
// System.out.print(s + " ");
// }
// String task = "13367359,";
// String[] taskGroup = task.split(",");
// String entityId = taskGroup[0];
// String scheduleId = taskGroup[1];
// Long entityIdValue = null;
// Long scdIdValue = null;
// entityIdValue = Long.parseLong(entityId);
// scdIdValue = Long.parseLong(scheduleId);
// Long status = 324324932998423L;
// System.out.println(ToStringBuilder.reflectionToString(status, ToStringStyle.SHORT_PREFIX_STYLE));
System.out.println("t".equals(null));
String obj = null;
if (obj instanceof String) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}
| true |
f9c3589c6a7e14b558c5f060788d008934d9bfd8 | Java | George-git1/SpringBoot | /demo1/src/main/java/com/example/demo/controllers/BasicController.java | UTF-8 | 571 | 2.359375 | 2 | [] | no_license | package com.example.demo.controllers;
import java.time.LocalTime;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController // indicates to spring this is a bean
/* @RequestMapping("/basic") */
public class BasicController {
@GetMapping("/basic")
public String basicHTMLResponse() {
return "<h1>Hello World</h1>";
}
@GetMapping("/time")
public LocalTime getTime() {
return LocalTime.now();
}
}
| true |
df449d0315636ea1fb25b979dfbf8fcdf37f78a8 | Java | syg-todo/P01TalkSkillAPP_Android | /huashu/src/main/java/com/tuodanhuashu/app/course/ui/fragment/CourseDetailDirectoryFragment.java | UTF-8 | 8,470 | 1.96875 | 2 | [] | no_license | package com.tuodanhuashu.app.course.ui.fragment;
import android.arch.lifecycle.ViewModelProviders;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.tuodanhuashu.app.Constants.Constants;
import com.tuodanhuashu.app.R;
import com.tuodanhuashu.app.base.HuaShuBaseFragment;
import com.tuodanhuashu.app.base.SimpleItemDecoration;
import com.tuodanhuashu.app.course.bean.CourseDetailBean;
import com.tuodanhuashu.app.course.bean.CourseDetailModel;
import com.tuodanhuashu.app.course.bean.SectionBean;
import com.tuodanhuashu.app.course.ui.AudioPlayerActivity;
import com.tuodanhuashu.app.eventbus.EventMessage;
import com.tuodanhuashu.app.utils.PriceFormater;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
public class CourseDetailDirectoryFragment extends HuaShuBaseFragment {
@BindView(R.id.rv_course_detail_directory)
RecyclerView recyclerView;
// @BindView(R.id.fab_section)
// FloatingActionButton fabSection;
private CourseDetailModel model;
private List<CourseDetailBean.SectionsBean> sectionsBeanList = new ArrayList<>();
private String isAudition;//是否可以试听 1可以
private String isPay;//是否已购买
private CourseDetailBean courseDetailBean;
private boolean isPlaying;
@Override
protected int getContentViewLayoutID() {
return R.layout.fragment_course_detail_directory;
}
@Override
protected void initView(View view) {
super.initView(view);
EventBus.getDefault().register(this);
model = ViewModelProviders.of(getActivity()).get(CourseDetailModel.class);
// fabSection.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Toast.makeText(mContext, "fab", Toast.LENGTH_SHORT).show();
// }
// });
courseDetailBean = model.getCourseDetail().getValue();
// isPlaying = model.getIsPlaying().getValue();
sectionsBeanList = courseDetailBean.getSections();
isPay = courseDetailBean.getCourse().getIs_pay();
DirectoryAdapter adapter = new DirectoryAdapter(sectionsBeanList);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
recyclerView.addItemDecoration(new SimpleItemDecoration());
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(EventMessage<Map<String,String>> eventMessage) {
switch (eventMessage.getTag()) {
case Constants.EVENT_TAG.TAG_SECTION_STATE_CHANGING:
isPlaying = !eventMessage.getData().get(Constants.EVENT_TAG.TAG_SECTION_STATE).equals("start");
break;
}
}
public CourseDetailDirectoryFragment() {
}
class DirectoryAdapter extends RecyclerView.Adapter<DirectoryAdapter.DirectoryHolder> {
private List<CourseDetailBean.SectionsBean> directoryList;
public DirectoryAdapter(List<CourseDetailBean.SectionsBean> directoryList) {
this.directoryList = directoryList;
}
@NonNull
@Override
public DirectoryHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_course_detail_directory, parent, false);
DirectoryHolder holder = new DirectoryHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull final DirectoryHolder holder, int position) {
final CourseDetailBean.SectionsBean directory = directoryList.get(position);
holder.tvName.setText(directory.getSection_name());
int duration = Integer.parseInt(directory.getDuration());
int minutes = duration / 60;
int seconds = duration % 60;
isAudition = directory.getIs_audition();
String time = String.format("%02d:%02d", minutes, seconds);
holder.tvTime.setText(time);
holder.tvPosition.setText(String.valueOf(position+1));
String finalPrice = PriceFormater.formatPrice(courseDetailBean.getCourse().getActivity_price(),courseDetailBean.getCourse().getSale_price(),courseDetailBean.getCourse().getPrice());
if (isPay.equals("1")||finalPrice.equals("免费")) {//已支付
holder.ivPause.setVisibility(View.GONE);
holder.ivPlay.setVisibility(View.VISIBLE);
holder.ivLock.setVisibility(View.GONE);
holder.tvAudition.setVisibility(View.GONE);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
goToAudio(directory);
}
});
} else {//未支付
if (isAudition.equals("1")) {
holder.ivPause.setVisibility(View.GONE);
holder.ivPlay.setVisibility(View.GONE);
holder.ivLock.setVisibility(View.GONE);
holder.tvAudition.setVisibility(View.VISIBLE);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
goToAudio(directory);
}
});
holder.tvAudition.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.setVisibility(View.GONE);
holder.ivPause.setVisibility(View.VISIBLE);
}
});
} else {
holder.ivPause.setVisibility(View.GONE);
holder.ivPlay.setVisibility(View.GONE);
holder.ivLock.setVisibility(View.VISIBLE);
holder.tvAudition.setVisibility(View.GONE);
holder.tvName.setTextColor(Color.parseColor("#ff999999"));
}
}
}
private void goToAudio(CourseDetailBean.SectionsBean directory) {
Bundle bundle = new Bundle();
bundle.putString(AudioPlayerActivity.EXTRA_SECTION_ID, directory.getId());
bundle.putString(AudioPlayerActivity.EXTRA_COURSE_ID, directory.getCourse_id());
bundle.putBoolean(AudioPlayerActivity.EXTRA_IS_PLAYING, isPlaying);
readyGo(AudioPlayerActivity.class, bundle);
}
@Override
public int getItemCount() {
return directoryList.size();
}
class DirectoryHolder extends RecyclerView.ViewHolder {
TextView tvName;
TextView tvTime;
ImageView ivPlay;
ImageView ivPause;
ImageView ivLock;
TextView tvAudition;
TextView tvPosition;
public DirectoryHolder(View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.tv_item_course_detail_directory_name);
tvTime = itemView.findViewById(R.id.tv_item_course_detail_directory_time);
ivPlay = itemView.findViewById(R.id.iv_course_detail_section_play);
ivPause = itemView.findViewById(R.id.iv_course_detail_section_pause);
ivLock = itemView.findViewById(R.id.iv_course_detail_section_lock);
tvAudition = itemView.findViewById(R.id.tv_course_detail_section_audition);
tvPosition = itemView.findViewById(R.id.tv_item_course_detail_directory_position);
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
| true |
a70f05e665ea29166fa6433eb35406d7580a7a8b | Java | mimimimizuki/le4db | /WEB-INF/src/DeleteServlet.java | UTF-8 | 4,372 | 2.4375 | 2 | [] | no_license | import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//cordinatorが削除(patient)
//donor が削除(donor)
@SuppressWarnings("serial")
public class DeleteServlet extends HttpServlet {
// donor can delete his infomation
private String _hostname = null;
private String _dbname = null;
private String _username = null;
private String _password = null;
public void init() throws ServletException {
// iniファイルから自分のデータベース情報を読み込む
String iniFilePath = getServletConfig().getServletContext().getRealPath("WEB-INF/le4db.ini");
try {
FileInputStream fis = new FileInputStream(iniFilePath);
Properties prop = new Properties();
prop.load(fis);
_hostname = prop.getProperty("hostname");
_dbname = prop.getProperty("dbname");
_username = prop.getProperty("username");
_password = prop.getProperty("password");
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String deleteuser_data = request.getParameter("delete_user_id");
out.println("<html>");
out.println("<body>");
out.println("<style>");
out.println("body {color : dimgray; }");
out.println("</style>");
Connection conn = null;
Statement stmt = null;
Statement stmt_hla = null;
Statement stmt_user = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection("jdbc:postgresql://" + _hostname + ":5432/" + _dbname, _username,
_password);
conn.setAutoCommit(false);
stmt = conn.createStatement();
stmt.executeUpdate("DELETE FROM relationship WHERE user_id ='" + deleteuser_data + "'");
stmt.executeUpdate("DELETE FROM address WHERE user_id ='" + deleteuser_data + "'");
stmt.executeUpdate("DELETE FROM contact WHERE user_id ='" + deleteuser_data + "'");
stmt.executeUpdate("DELETE FROM login WHERE user_id ='" + deleteuser_data + "'");
stmt_user = conn.createStatement();
ResultSet rs_user = stmt_user
.executeQuery("select count(*) from user_data where user_id = '" + deleteuser_data + "'");
rs_user.next();
int count = rs_user.getInt("count");
if (count <= 0) {
conn.rollback();
out.println("<h3>該当するユーザは存在しません。</h3><br/>");
} else {
out.println("<h3>以下のユーザを削除しました。</h3><br/>");
out.println("ユーザID: " + deleteuser_data + "<br/>");
ResultSet rs = stmt.executeQuery("SELECT * FROM register WHERE user_id ='" + deleteuser_data + "'");
rs.next();
int hla_id = rs.getInt("hla_id");
stmt.executeUpdate("DELETE FROM register WHERE user_id= '" + deleteuser_data + "'");
stmt.executeUpdate("DELETE FROM user_data WHERE user_id= '" + deleteuser_data + "'");
rs.close();
stmt_hla = conn.createStatement();
ResultSet rs_hla = stmt_hla.executeQuery("SELECT * FROM register WHERE hla_id ='" + hla_id + "'");
String same_user = "";
if (rs_hla.next()) {
same_user = rs_hla.getString("user_id");
}
if (same_user == "") {
stmt_hla.executeUpdate("DELETE FROM hla WHERE hla_id = '" + hla_id + "'");
}
conn.commit();
rs_hla.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
out.println("<br/>");
out.println("<a href=\"cordinator.html\">管理ページに戻る</a>");
out.println("</body>");
out.println("</html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public void destroy() {
}
}
| true |
55ca4e93ea60eb40aa6c4426397d318aca65f9e2 | Java | arulsuju/interview_final | /src/org/java8features/ArrayListDemo.java | UTF-8 | 472 | 3.25 | 3 | [] | no_license | package org.java8features;
import java.util.ArrayList;
import java.util.List;
public class ArrayListDemo {
public static void main(String[] args) {
List<Integer> list=new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);
System.out.println(list);
//need to convert to array
int[] list1=new int[list.size()];
for(int i=0;i<list1.length;i++){
list1[i]=list.get(i);
}
}
}
| true |
54074c553c8c3c3906ca71db5b833cbad0830a55 | Java | jasmhusc/javaEE | /javaee04/src/demo4/Demo3.java | UTF-8 | 422 | 3.3125 | 3 | [] | no_license | package demo4;
import java.util.Arrays;
public class Demo3 {
public static void main(String[] args) {
/*
* 数组复制
* arraycopy(原数组,起始索引,新数组,起始索引,复制元素个数)
* */
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = new int[8];
System.arraycopy(arr1, 1, arr2, 3, 3);
System.out.println(Arrays.toString(arr2));
}
}
| true |
c1c56d1144edc07bc464accec7e94d7d080dcb44 | Java | yp6497/test001 | /app/src/main/java/com/example/test001/MainActivity.java | UTF-8 | 1,924 | 2.53125 | 3 | [] | no_license | package com.example.test001;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int count = 0;
int count2 = 0;
int count3 = 0;
TextView N1, N2, tPer, TorF;
int n1, n2;
Button btnP;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnP = findViewById(R.id.btnP);
N1 = findViewById(R.id.textView3);
N2 = findViewById(R.id.textView4);
tPer = findViewById(R.id.tPer);
TorF = findViewById(R.id.TorF);
}
public void PressForNum(View view) {
count2++;
count = 0;
n1 = (int) (Math.random() * 10 + 0);
n2 = (int) (Math.random() * 10 + 0);
N1.setText(n1 + "");
N2.setText(n2 + "");
TorF.setText("True/False");
}
public void clear(View view) {
count2 = 0;
count3 = 0;
tPer.setText("0/0");
}
public void numbersAreE(View view) {
count++;
if (n1 == n2) {
TorF.setText("true");
if (count == 1)
count3++;
} else TorF.setText("false");
tPer.setText(count3 + "/" + count2);
}
public void number2Isbigger(View view) {
count++;
if (n1 < n2) {
TorF.setText("true");
if (count == 1)
count3++;
} else TorF.setText("false");
tPer.setText(count3 + "/" + count2);
}
public void number1Isbigger(View view) {
count++;
if (n1 > n2) {
TorF.setText("true");
if (count == 1)
count3++;
} else TorF.setText("false");
tPer.setText(count3 + "/" + count2);
}
}
| true |
728f7571f34d2bcc1220b2eee646416b528e8990 | Java | jvcoutinho/Transfer | /Transfer.java | UTF-8 | 30,977 | 2.390625 | 2 | [] | no_license | import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JTextField;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JTextPane;
import javax.swing.border.MatteBorder;
import javax.swing.JProgressBar;
import java.awt.Cursor;
import java.awt.SystemColor;
public class Transfer {
private JFrame frmTransfer;
private static DataInputStream dIN;
private static DataOutputStream dOUT;
private static String uploadFileName;
private static long uploadFileSize;
private static String uploadFilePath;
private static String downloadFilePath;
public static int numTransferences;
public static boolean[] transferPaused;
public static boolean[] uploadCanceled;
public static boolean[] downloadCanceled;
public Transfer() {
initialize();
handleConnection();
numTransferences = 0;
transferPaused = new boolean[3];
uploadCanceled = new boolean[3];
downloadCanceled = new boolean[3];
}
public static DataInputStream getDataInputStream() {
return dIN;
}
public static DataOutputStream getDataOutputStream() {
return dOUT;
}
public static String getUploadFilePath() {
return uploadFilePath;
}
public static String getDownloadFilePath() {
if(downloadFilePath != "")
return downloadFilePath + "\\";
return downloadFilePath;
}
public static String getUploadFileName() {
return uploadFileName;
}
public static long getUploadFileSize() {
return uploadFileSize;
}
private void initialize() {
/** FRAME */
frmTransfer = new JFrame();
frmTransfer.setResizable(false);
frmTransfer.setTitle("Transfer");
frmTransfer.setBounds(100, 100, 1000, 500);
frmTransfer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTransfer.getContentPane().setLayout(null);
JPanel connectionPanel = new JPanel();
connectionPanel.setBackground(Color.WHITE);
connectionPanel.setBounds(0, 0, 1000, 70);
frmTransfer.getContentPane().add(connectionPanel);
connectionPanel.setLayout(null);
JLabel connectionStatus = new JLabel("N\u00E3o conectado.");
connectionStatus.setBounds(10, 0, 398, 70);
connectionPanel.add(connectionStatus);
connectionStatus.setHorizontalAlignment(SwingConstants.LEFT);
connectionStatus.setFont(new Font("Malgun Gothic Semilight", Font.PLAIN, 40));
JPanel connectionIndicator = new JPanel();
connectionIndicator.setBounds(0, 0, 1000, 10);
connectionPanel.add(connectionIndicator);
JLabel lblRTT = new JLabel("RTT:");
lblRTT.setFont(new Font("Malgun Gothic Semilight", Font.BOLD, 11));
lblRTT.setBounds(887, 21, 66, 14);
lblRTT.setVisible(false);
connectionPanel.add(lblRTT);
JPanel connectPanel = new JPanel();
connectPanel.setBounds(593, 18, 273, 23);
connectionPanel.add(connectPanel);
connectPanel.setLayout(null);
JTextField txtIPHost = new JTextField();
txtIPHost.setBounds(0, 1, 150, 21);
connectPanel.add(txtIPHost);
txtIPHost.setFont(new Font("Malgun Gothic Semilight", Font.BOLD, 11));
txtIPHost.setText("localhost");
txtIPHost.setColumns(10);
JButton btnConnect = new JButton("CONECTAR-SE");
btnConnect.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
connect(txtIPHost.getText(), 6000);
}
});
btnConnect.setBounds(149, 0, 124, 23);
connectPanel.add(btnConnect);
btnConnect.setFont(new Font("Malgun Gothic Semilight", Font.BOLD, 11));
/*******************************************************************/
/** FILE SELECTION */
JPanel fileSelectionPanel = new JPanel();
fileSelectionPanel.setBorder(new MatteBorder(0, 0, 1, 0, (Color) new Color(200, 200, 200)));
fileSelectionPanel.setBounds(10, 66, 970, 46);
frmTransfer.getContentPane().add(fileSelectionPanel);
fileSelectionPanel.setLayout(null);
JTextPane txtpnFile = new JTextPane();
txtpnFile.setBounds(0, 16, 665, 23);
fileSelectionPanel.add(txtpnFile);
txtpnFile.setFont(new Font("Lucida Sans", Font.PLAIN, 13));
txtpnFile.setText("Selecione um arquivo para enviar.");
txtpnFile.setEnabled(false);
txtpnFile.setEditable(false);
JButton btnEnviar = new JButton("ENVIAR");
btnEnviar.setBounds(875, 16, 89, 23);
fileSelectionPanel.add(btnEnviar);
btnEnviar.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if(numTransferences == 3)
txtpnFile.setText("Máximo de 3 transferências simultâneas!");
else {
try {
dOUT.writeUTF("HELO " + uploadFileName); // I want to send a file.
dOUT.writeLong(uploadFileSize);
dOUT.flush();
txtpnFile.setText("Selecione um arquivo para enviar.");
btnEnviar.setEnabled(false);
} catch (NullPointerException e1) {
txtpnFile.setText("Conecte-se!");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
btnEnviar.setFont(new Font("Tahoma", Font.BOLD, 11));
btnEnviar.setEnabled(false);
JButton btnSelecionarArquivo = new JButton("SELECIONAR ARQUIVO");
btnSelecionarArquivo.setBounds(699, 16, 166, 23);
fileSelectionPanel.add(btnSelecionarArquivo);
btnSelecionarArquivo.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
JFileChooser chooser = new JFileChooser();
if(chooser.showOpenDialog(frmTransfer) == JFileChooser.APPROVE_OPTION) {
uploadFilePath = chooser.getSelectedFile().getPath();
uploadFileName = chooser.getSelectedFile().getName();
uploadFileSize = chooser.getSelectedFile().length();
txtpnFile.setText(uploadFilePath);
btnEnviar.setEnabled(true);
}
}
});
btnSelecionarArquivo.setFont(new Font("Tahoma", Font.BOLD, 11));
/*******************************************************************/
/** DOWNLOAD REQUISITION */
JPanel downloadRequisitionPanel = new JPanel();
downloadRequisitionPanel.setBorder(new MatteBorder(2, 2, 0, 2, (Color) new Color(0, 120, 215)));
downloadRequisitionPanel.setBounds(35, 407, 924, 64);
frmTransfer.getContentPane().add(downloadRequisitionPanel);
downloadRequisitionPanel.setLayout(null);
downloadRequisitionPanel.setVisible(false);
JLabel lblFileName = new JLabel("Deseja baixar <filename>" );
lblFileName.setForeground(new Color(67, 67, 67));
lblFileName.setFont(new Font("Malgun Gothic", Font.PLAIN, 16));
lblFileName.setBounds(33, 21, 475, 22);
downloadRequisitionPanel.add(lblFileName);
JLabel lblFileSize = new JLabel("(<filesize>)");
lblFileSize.setHorizontalAlignment(SwingConstants.RIGHT);
lblFileSize.setForeground(new Color(67, 67, 67));
lblFileSize.setFont(new Font("Malgun Gothic Semilight", Font.PLAIN, 14));
lblFileSize.setBounds(529, 21, 77, 23);
downloadRequisitionPanel.add(lblFileSize);
JButton btnSalvar = new JButton("Salvar");
btnSalvar.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
downloadFilePath = "";
synchronized(dOUT) {
try {
dOUT.writeUTF("SEND 3");
dOUT.flush();
downloadRequisitionPanel.setVisible(false);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
btnSalvar.setBounds(618, 21, 89, 23);
downloadRequisitionPanel.add(btnSalvar);
JButton btnSalvarComo = new JButton("Salvar como");
btnSalvarComo.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(chooser.showOpenDialog(frmTransfer) == JFileChooser.APPROVE_OPTION) {
downloadFilePath = chooser.getSelectedFile().toString();
synchronized(dOUT) {
try {
dOUT.writeUTF("SEND 3");
dOUT.flush();
downloadRequisitionPanel.setVisible(false);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
});
btnSalvarComo.setBounds(717, 21, 98, 23);
downloadRequisitionPanel.add(btnSalvarComo);
JButton btnRejeitar = new JButton("Rejeitar");
btnRejeitar.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
downloadRequisitionPanel.setVisible(false);
}
});
btnRejeitar.setBounds(825, 21, 89, 23);
downloadRequisitionPanel.add(btnRejeitar);
/*******************************************************************/
/** UPLOAD PANELS */
JPanel uploadPanel = new JPanel();
uploadPanel.setBounds(10, 134, 470, 70);
frmTransfer.getContentPane().add(uploadPanel);
uploadPanel.setLayout(null);
uploadPanel.setVisible(false);
JProgressBar uploadProgressBar = new JProgressBar();
uploadProgressBar.setStringPainted(true);
uploadProgressBar.setBounds(0, 63, 470, 7);
uploadProgressBar.setForeground(new Color(150, 0, 0));
uploadPanel.add(uploadProgressBar);
JLabel lblUploadFileName = new JLabel("<nomedoarquivo>");
lblUploadFileName.setFont(new Font("Malgun Gothic", Font.PLAIN, 15));
lblUploadFileName.setBounds(10,0, 360, 28);
uploadPanel.add(lblUploadFileName);
JLabel uploadPercentage = new JLabel("100%");
uploadPercentage.setHorizontalAlignment(SwingConstants.RIGHT);
uploadPercentage.setFont(new Font("Malgun Gothic Semilight", Font.BOLD, 15));
uploadPercentage.setBounds(412, 0, 48, 28);
uploadPanel.add(uploadPercentage);
JLabel uploadTimeRemaining = new JLabel("100s restantes");
uploadTimeRemaining.setForeground(new Color(87, 87, 87));
uploadTimeRemaining.setFont(new Font("Malgun Gothic Semilight", Font.PLAIN, 14));
uploadTimeRemaining.setBounds(10, 39, 125, 14);
uploadPanel.add(uploadTimeRemaining);
JLabel lblPausarUpload = new JLabel("Pausar");
lblPausarUpload.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
lblPausarUpload.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblPausarUpload.setForeground(new Color(105, 105, 105));
}
@Override
public void mouseExited(MouseEvent e) {
lblPausarUpload.setCursor(Cursor.getDefaultCursor());
lblPausarUpload.setForeground(new Color(0, 78, 140));
}
@Override
public void mouseClicked(MouseEvent arg0) {
transferPaused[0] = !transferPaused[0];
if(transferPaused[0]) {
lblPausarUpload.setText("Retomar");
uploadTimeRemaining.setText("Pausado.");
} else {
lblPausarUpload.setText("Pausar");
uploadTimeRemaining.setText("Retomando...");
}
}
});
lblPausarUpload.setHorizontalAlignment(SwingConstants.RIGHT);
lblPausarUpload.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblPausarUpload.setForeground(new Color(0, 78, 140));
lblPausarUpload.setBounds(332, 39, 59, 14);
uploadPanel.add(lblPausarUpload);
JLabel lblReiniciarUpload = new JLabel("Reiniciar");
lblReiniciarUpload.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
lblReiniciarUpload.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblReiniciarUpload.setForeground(new Color(105, 105, 105));
}
@Override
public void mouseExited(MouseEvent e) {
lblReiniciarUpload.setCursor(Cursor.getDefaultCursor());
lblReiniciarUpload.setForeground(new Color(0, 78, 140));
}
@Override
public void mouseClicked(MouseEvent arg0) {
uploadCanceled[0] = false;
synchronized (dOUT) {
try {
dOUT.writeUTF("REST 0");
dOUT.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
lblReiniciarUpload.setVisible(false);
}
});
lblReiniciarUpload.setHorizontalAlignment(SwingConstants.RIGHT);
lblReiniciarUpload.setForeground(new Color(0, 78, 140));
lblReiniciarUpload.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblReiniciarUpload.setBounds(401, 39, 59, 14);
lblReiniciarUpload.setVisible(false);
uploadPanel.add(lblReiniciarUpload);
JLabel lblCancelarUpload = new JLabel("Cancelar");
lblCancelarUpload.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
lblCancelarUpload.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblCancelarUpload.setForeground(new Color(105, 105, 105));
}
@Override
public void mouseExited(MouseEvent e) {
lblCancelarUpload.setCursor(Cursor.getDefaultCursor());
lblCancelarUpload.setForeground(new Color(0, 78, 140));
}
@Override
public void mouseClicked(MouseEvent e) {
uploadCanceled[0] = true;
synchronized (dOUT) {
try {
dOUT.writeUTF("STOP 0");
dOUT.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
lblPausarUpload.setVisible(false);
lblCancelarUpload.setVisible(false);
lblReiniciarUpload.setVisible(true);
}
});
lblCancelarUpload.setHorizontalAlignment(SwingConstants.RIGHT);
lblCancelarUpload.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblCancelarUpload.setForeground(new Color(0, 78, 140));
lblCancelarUpload.setBounds(401, 39, 59, 14);
uploadPanel.add(lblCancelarUpload);
/* **********************************/
JPanel uploadPanel2 = new JPanel();
uploadPanel2.setBounds(10, 230, 470, 70);
frmTransfer.getContentPane().add(uploadPanel2);
uploadPanel2.setLayout(null);
uploadPanel2.setVisible(false);
JProgressBar uploadProgressBar2 = new JProgressBar();
uploadProgressBar2.setStringPainted(true);
uploadProgressBar2.setForeground(new Color(150, 0, 0));
uploadProgressBar2.setBounds(0, 63, 470, 7);
uploadPanel2.add(uploadProgressBar2);
JLabel lblUploadFileName2 = new JLabel("<nomedoarquivo>");
lblUploadFileName2.setFont(new Font("Malgun Gothic", Font.PLAIN, 15));
lblUploadFileName2.setBounds(10, 0, 360, 28);
uploadPanel2.add(lblUploadFileName2);
JLabel uploadPercentage2 = new JLabel("100%");
uploadPercentage2.setHorizontalAlignment(SwingConstants.RIGHT);
uploadPercentage2.setFont(new Font("Malgun Gothic Semilight", Font.BOLD, 15));
uploadPercentage2.setBounds(412, 0, 48, 28);
uploadPanel2.add(uploadPercentage2);
JLabel uploadTimeRemaining2 = new JLabel("100s restantes");
uploadTimeRemaining2.setForeground(new Color(87, 87, 87));
uploadTimeRemaining2.setFont(new Font("Malgun Gothic Semilight", Font.PLAIN, 14));
uploadTimeRemaining2.setBounds(10, 39, 125, 14);
uploadPanel2.add(uploadTimeRemaining2);
JLabel lblPausarUpload2 = new JLabel("Pausar");
lblPausarUpload2.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
lblPausarUpload2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblPausarUpload2.setForeground(new Color(105, 105, 105));
}
@Override
public void mouseExited(MouseEvent e) {
lblPausarUpload2.setCursor(Cursor.getDefaultCursor());
lblPausarUpload2.setForeground(new Color(0, 78, 140));
}
@Override
public void mouseClicked(MouseEvent arg0) {
transferPaused[1] = !transferPaused[1];
if(transferPaused[1]) {
lblPausarUpload2.setText("Retomar");
uploadTimeRemaining2.setText("Pausado.");
} else {
lblPausarUpload2.setText("Pausar");
uploadTimeRemaining2.setText("Retomando...");
}
}
});
lblPausarUpload2.setHorizontalAlignment(SwingConstants.RIGHT);
lblPausarUpload2.setForeground(new Color(0, 78, 140));
lblPausarUpload2.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblPausarUpload2.setBounds(332, 39, 59, 14);
uploadPanel2.add(lblPausarUpload2);
JLabel lblReiniciarUpload2 = new JLabel("Reiniciar");
lblReiniciarUpload2.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
lblReiniciarUpload2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblReiniciarUpload2.setForeground(new Color(105, 105, 105));
}
@Override
public void mouseExited(MouseEvent e) {
lblReiniciarUpload2.setCursor(Cursor.getDefaultCursor());
lblReiniciarUpload2.setForeground(new Color(0, 78, 140));
}
@Override
public void mouseClicked(MouseEvent arg0) {
uploadCanceled[1] = false;
synchronized (dOUT) {
try {
dOUT.writeUTF("REST 1");
dOUT.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
lblReiniciarUpload2.setVisible(false);
}
});
lblReiniciarUpload2.setHorizontalAlignment(SwingConstants.RIGHT);
lblReiniciarUpload2.setForeground(new Color(0, 78, 140));
lblReiniciarUpload2.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblReiniciarUpload2.setBounds(401, 39, 59, 14);
lblReiniciarUpload2.setVisible(false);
uploadPanel2.add(lblReiniciarUpload2);
JLabel lblCancelarUpload2 = new JLabel("Cancelar");
lblCancelarUpload2.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
lblCancelarUpload2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblCancelarUpload2.setForeground(new Color(105, 105, 105));
}
@Override
public void mouseExited(MouseEvent e) {
lblCancelarUpload2.setCursor(Cursor.getDefaultCursor());
lblCancelarUpload2.setForeground(new Color(0, 78, 140));
}
@Override
public void mouseClicked(MouseEvent e) {
uploadCanceled[1] = true;
synchronized (dOUT) {
try {
dOUT.writeUTF("STOP 1");
dOUT.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
lblPausarUpload2.setVisible(false);
lblCancelarUpload2.setVisible(false);
lblReiniciarUpload2.setVisible(true);
}
});
lblCancelarUpload2.setHorizontalAlignment(SwingConstants.RIGHT);
lblCancelarUpload2.setForeground(new Color(0, 78, 140));
lblCancelarUpload2.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblCancelarUpload2.setBounds(401, 39, 59, 14);
uploadPanel2.add(lblCancelarUpload2);
/* **********************************/
JPanel uploadPanel3 = new JPanel();
uploadPanel3.setLayout(null);
uploadPanel3.setBounds(10, 326, 470, 70);
frmTransfer.getContentPane().add(uploadPanel3);
uploadPanel3.setVisible(false);
JProgressBar uploadProgressBar3 = new JProgressBar();
uploadProgressBar3.setStringPainted(true);
uploadProgressBar3.setForeground(new Color(150, 0, 0));
uploadProgressBar3.setBounds(0, 63, 470, 7);
uploadPanel3.add(uploadProgressBar3);
JLabel lblUploadFileName3 = new JLabel("<nomedoarquivo>");
lblUploadFileName3.setFont(new Font("Malgun Gothic", Font.PLAIN, 15));
lblUploadFileName3.setBounds(10, 0, 360, 28);
uploadPanel3.add(lblUploadFileName3);
JLabel uploadPercentage3 = new JLabel("100%");
uploadPercentage3.setHorizontalAlignment(SwingConstants.RIGHT);
uploadPercentage3.setFont(new Font("Malgun Gothic Semilight", Font.BOLD, 15));
uploadPercentage3.setBounds(412, 0, 48, 28);
uploadPanel3.add(uploadPercentage3);
JLabel uploadTimeRemaining3 = new JLabel("100s restantes");
uploadTimeRemaining3.setForeground(new Color(87, 87, 87));
uploadTimeRemaining3.setFont(new Font("Malgun Gothic Semilight", Font.PLAIN, 14));
uploadTimeRemaining3.setBounds(10, 39, 125, 14);
uploadPanel3.add(uploadTimeRemaining3);
JLabel lblPausarUpload3 = new JLabel("Pausar");
lblPausarUpload3.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
lblPausarUpload3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblPausarUpload3.setForeground(new Color(105, 105, 105));
}
@Override
public void mouseExited(MouseEvent e) {
lblPausarUpload3.setCursor(Cursor.getDefaultCursor());
lblPausarUpload3.setForeground(new Color(0, 78, 140));
}
@Override
public void mouseClicked(MouseEvent arg0) {
transferPaused[2] = !transferPaused[2];
if(transferPaused[2]) {
lblPausarUpload3.setText("Retomar");
uploadTimeRemaining3.setText("Pausado.");
} else {
lblPausarUpload3.setText("Pausar");
uploadTimeRemaining3.setText("Retomando...");
}
}
});
lblPausarUpload3.setHorizontalAlignment(SwingConstants.RIGHT);
lblPausarUpload3.setForeground(new Color(0, 78, 140));
lblPausarUpload3.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblPausarUpload3.setBounds(332, 39, 59, 14);
uploadPanel3.add(lblPausarUpload3);
JLabel lblReiniciarUpload3 = new JLabel("Reiniciar");
lblReiniciarUpload3.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
lblReiniciarUpload3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblReiniciarUpload3.setForeground(new Color(105, 105, 105));
}
@Override
public void mouseExited(MouseEvent e) {
lblReiniciarUpload3.setCursor(Cursor.getDefaultCursor());
lblReiniciarUpload3.setForeground(new Color(0, 78, 140));
}
@Override
public void mouseClicked(MouseEvent arg0) {
uploadCanceled[2] = false;
synchronized (dOUT) {
try {
dOUT.writeUTF("REST 2");
dOUT.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
lblReiniciarUpload3.setVisible(false);
}
});
lblReiniciarUpload3.setHorizontalAlignment(SwingConstants.RIGHT);
lblReiniciarUpload3.setForeground(new Color(0, 78, 140));
lblReiniciarUpload3.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblReiniciarUpload3.setBounds(401, 39, 59, 14);
lblReiniciarUpload3.setVisible(false);
uploadPanel3.add(lblReiniciarUpload3);
JLabel lblCancelarUpload3 = new JLabel("Cancelar");
lblCancelarUpload3.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
lblCancelarUpload3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblCancelarUpload3.setForeground(new Color(105, 105, 105));
}
@Override
public void mouseExited(MouseEvent e) {
lblCancelarUpload3.setCursor(Cursor.getDefaultCursor());
lblCancelarUpload3.setForeground(new Color(0, 78, 140));
}
@Override
public void mouseClicked(MouseEvent e) {
uploadCanceled[2] = true;
synchronized (dOUT) {
try {
dOUT.writeUTF("STOP 2");
dOUT.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
lblPausarUpload3.setVisible(false);
lblCancelarUpload3.setVisible(false);
lblReiniciarUpload3.setVisible(true);
}
});
lblCancelarUpload3.setHorizontalAlignment(SwingConstants.RIGHT);
lblCancelarUpload3.setForeground(new Color(0, 78, 140));
lblCancelarUpload3.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblCancelarUpload3.setBounds(401, 39, 59, 14);
uploadPanel3.add(lblCancelarUpload3);
/*******************************************************************/
/** DOWNLOAD PANELS */
JPanel downloadPanel = new JPanel();
downloadPanel.setLayout(null);
downloadPanel.setBounds(510, 134, 470, 70);
frmTransfer.getContentPane().add(downloadPanel);
downloadPanel.setVisible(false);
JProgressBar downloadProgressBar = new JProgressBar();
downloadProgressBar.setStringPainted(true);
downloadProgressBar.setBounds(0, 63, 470, 7);
downloadProgressBar.setForeground(new Color(0, 120, 215));
downloadPanel.add(downloadProgressBar);
JLabel lblDownloadFileName = new JLabel("<nomedoarquivo>");
lblDownloadFileName.setFont(new Font("Malgun Gothic", Font.PLAIN, 15));
lblDownloadFileName.setBounds(10, 0, 360, 28);
downloadPanel.add(lblDownloadFileName);
JLabel downloadPercentage = new JLabel("100%");
downloadPercentage.setHorizontalAlignment(SwingConstants.RIGHT);
downloadPercentage.setFont(new Font("Malgun Gothic Semilight", Font.BOLD, 15));
downloadPercentage.setBounds(412, 0, 48, 28);
downloadPanel.add(downloadPercentage);
JLabel downloadTimeRemaining = new JLabel("100s restantes");
downloadTimeRemaining.setFont(new Font("Malgun Gothic Semilight", Font.PLAIN, 14));
downloadTimeRemaining.setForeground(new Color(87, 87, 87));
downloadTimeRemaining.setBounds(10, 39, 125, 14);
downloadPanel.add(downloadTimeRemaining);
/* **********************************/
JPanel downloadPanel2 = new JPanel();
downloadPanel2.setBounds(510, 230, 470, 70);
frmTransfer.getContentPane().add(downloadPanel2);
downloadPanel2.setLayout(null);
downloadPanel2.setVisible(false);
JProgressBar downloadProgressBar2 = new JProgressBar();
downloadProgressBar2.setStringPainted(true);
downloadProgressBar2.setForeground(SystemColor.textHighlight);
downloadProgressBar2.setBounds(0, 63, 470, 7);
downloadPanel2.add(downloadProgressBar2);
JLabel lblDownloadFileName2 = new JLabel("<nomedoarquivo>");
lblDownloadFileName2.setFont(new Font("Malgun Gothic", Font.PLAIN, 15));
lblDownloadFileName2.setBounds(10, 0, 360, 28);
downloadPanel2.add(lblDownloadFileName2);
JLabel downloadPercentage2 = new JLabel("100%");
downloadPercentage2.setHorizontalAlignment(SwingConstants.RIGHT);
downloadPercentage2.setFont(new Font("Malgun Gothic Semilight", Font.BOLD, 15));
downloadPercentage2.setBounds(412, 0, 48, 28);
downloadPanel2.add(downloadPercentage2);
JLabel downloadTimeRemaining2 = new JLabel("100s restantes");
downloadTimeRemaining2.setForeground(new Color(87, 87, 87));
downloadTimeRemaining2.setFont(new Font("Malgun Gothic Semilight", Font.PLAIN, 14));
downloadTimeRemaining2.setBounds(10, 39, 125, 14);
downloadPanel2.add(downloadTimeRemaining2);
/* **********************************/
JPanel downloadPanel3 = new JPanel();
downloadPanel3.setLayout(null);
downloadPanel3.setBounds(510, 326, 470, 70);
frmTransfer.getContentPane().add(downloadPanel3);
downloadPanel3.setVisible(false);
JProgressBar downloadProgressBar3 = new JProgressBar();
downloadProgressBar3.setStringPainted(true);
downloadProgressBar3.setForeground(SystemColor.textHighlight);
downloadProgressBar3.setBounds(0, 63, 470, 7);
downloadPanel3.add(downloadProgressBar3);
JLabel lblDownloadFileName3 = new JLabel("<nomedoarquivo>");
lblDownloadFileName3.setFont(new Font("Malgun Gothic", Font.PLAIN, 15));
lblDownloadFileName3.setBounds(10, 0, 360, 28);
downloadPanel3.add(lblDownloadFileName3);
JLabel downloadPercentage3 = new JLabel("100%");
downloadPercentage3.setHorizontalAlignment(SwingConstants.RIGHT);
downloadPercentage3.setFont(new Font("Malgun Gothic Semilight", Font.BOLD, 15));
downloadPercentage3.setBounds(412, 0, 48, 28);
downloadPanel3.add(downloadPercentage3);
JLabel downloadTimeRemaining3 = new JLabel("100s restantes");
downloadTimeRemaining3.setForeground(new Color(87, 87, 87));
downloadTimeRemaining3.setFont(new Font("Malgun Gothic Semilight", Font.PLAIN, 14));
downloadTimeRemaining3.setBounds(10, 39, 125, 14);
downloadPanel3.add(downloadTimeRemaining3);
/*******************************************************************/
/** ENVIROMNENT */
JPanel border = new JPanel();
border.setBorder(new MatteBorder(0, 1, 0, 0, (Color) new Color(200, 200, 200)));
border.setBounds(495, 134, 1, 262);
frmTransfer.getContentPane().add(border);
}
private void connect(String host, int port) {
JPanel connectionIndicator = (JPanel) frmTransfer.getContentPane().getComponent(0).getComponentAt(0, 0);
JLabel connectionStatus = (JLabel) frmTransfer.getContentPane().getComponent(0).getComponentAt(10, 0);
try {
// Attempting to connect.
@SuppressWarnings("resource")
Socket socket = new Socket(host, port);
Socket rttSocket = new Socket(host, port);
// Establish visual effects.
connectionIndicator.setBackground(new Color(0, 150, 0));
connectionStatus.setText(socket.getInetAddress().toString());
// Initializing the data streams.
dIN = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
dOUT = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
(new Thread(new InputHandler(frmTransfer))).start();
(new Thread(new RTTCalculator(rttSocket, (JLabel) frmTransfer.getContentPane().getComponent(0).getComponentAt(887, 21)))).start();
} catch (UnknownHostException e) {
connectionIndicator.setBackground(new Color(150, 0, 0));
connectionStatus.setText("Host desconhecido.");
} catch (IOException e) {
connectionIndicator.setBackground(new Color(150, 0, 0));
connectionStatus.setText("Conexão falhou.");
}
}
private void handleConnection() {
(new Thread(new Runnable() {
private ServerSocket serverSocket;
private Socket socket;
private Socket rttSocket;
@Override
public void run() {
JPanel connectionIndicator = (JPanel) frmTransfer.getContentPane().getComponent(0).getComponentAt(0, 0);
JLabel connectionStatus = (JLabel) frmTransfer.getContentPane().getComponent(0).getComponentAt(10, 0);
try {
serverSocket = new ServerSocket(6000);
// Wait for a connection.
socket = serverSocket.accept();
rttSocket = serverSocket.accept();
// Establish visual effects.
connectionIndicator.setBackground(new Color(0, 150, 0));
connectionStatus.setText(socket.getInetAddress().toString());
// Initializing the data streams.
dIN = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
dOUT = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
(new Thread(new InputHandler(frmTransfer, serverSocket))).start();
(new Thread(new RTTCalculator(rttSocket, (JLabel) frmTransfer.getContentPane().getComponent(0).getComponentAt(887, 21)))).start();
} catch (IOException e) {
connectionIndicator.setBackground(new Color(150, 0, 0));
connectionStatus.setText("Erro de conexão.");
}
}
})).start();
}
public static void main(String[] args) {
/* Swing looks like the S.O., now. */
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Transfer window = new Transfer();
window.frmTransfer.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
| true |
0761e700e286a5e7659611e6651c377869a4fa8b | Java | eskolav/whatodo | /whatodo/src/main/java/whatodo/ui/AddTask.java | UTF-8 | 7,249 | 2.765625 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package whatodo.ui;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import whatodo.logic.Task;
/**
*
* @author esva
*/
public class AddTask extends javax.swing.JFrame {
private String newHeading;
private Date expiration;
private Task task;
public AddTask() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
heading = new javax.swing.JTextField();
info = new javax.swing.JTextField();
create = new javax.swing.JButton();
prio = new javax.swing.JComboBox<>();
heading.setHorizontalAlignment(javax.swing.JTextField.CENTER);
heading.setText("Otsikko");
info.setHorizontalAlignment(javax.swing.JTextField.LEFT);
info.setText("Tarkennus");
info.setToolTipText("");
create.setText("Valmis");
create.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
createActionPerformed(evt);
}
});
prio.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Prio 1", "Prio 2", "Prio 3" }));
prio.setSelectedIndex(1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(68, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(prio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(create)
.addGap(32, 32, 32))
.addComponent(info, javax.swing.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE)
.addComponent(heading))
.addGap(50, 50, 50))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(62, Short.MAX_VALUE)
.addComponent(heading, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(info, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(create)
.addComponent(prio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(48, 48, 48))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void createActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createActionPerformed
if (!correctHeading(heading.getText())) {
JOptionPane.showMessageDialog(new JFrame(), "Otsikko ei saa olla tyhjä tai yli 20 merkkiä pitkä!");
} else if (!correctDesc(info.getText())) {
JOptionPane.showMessageDialog(new JFrame(), "Tarkennus ei saa olla tyhjä tai yli 100 merkkiä pitkä!");
} else {
String prior = (String) prio.getSelectedItem();
int priority;
if (prior.contains("1")) {
priority = 1;
} else if (prior.contains("2")) {
priority = 2;
} else {
priority = 3;
}
this.task = new Task(heading.getText(), new Date(), priority, info.getText());
}
setVisible(false);
}//GEN-LAST:event_createActionPerformed
private boolean correctHeading(String heading) {
if (heading.isEmpty() || heading.length() > 20) {
return false;
} else {
return true;
}
}
private boolean correctDesc(String desc) {
if (desc.length() > 100 || desc.isEmpty()) {
return false;
} else {
return true;
}
}
public Task getTask() {
return this.task;
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AddTask.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AddTask.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AddTask.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AddTask.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AddTask().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton create;
private javax.swing.JTextField heading;
private javax.swing.JTextField info;
private javax.swing.JComboBox<String> prio;
// End of variables declaration//GEN-END:variables
}
| true |
70fb9c967ca5ad44e9b2edc9aa08597263d75a97 | Java | yalman1/new-java | /src/string_processing/StringContainsOnlyDigit.java | UTF-8 | 503 | 3.421875 | 3 | [] | no_license | package string_processing;
public class StringContainsOnlyDigit {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("12345");
System.out.println(isAllDigits(sb));
}
public static boolean isAllDigits (StringBuilder str){
boolean result=true;
for (int i = 0; i <str.length() ; i++) {
if (!(str.charAt(i)>=48&& str.charAt(i)<=57)) {
result= false;
}
}
return result;
}
}
| true |
ecacc968486d3bf7b9d9ebc6e571813f6f3af1c4 | Java | mhyttsten/QARocker-app | /shared/src/main/java/com/pf/shared/fund_db_update/FundDBUpdate_VGD.java | UTF-8 | 6,631 | 2.109375 | 2 | [] | no_license | package com.pf.shared.fund_db_update;
import com.pf.shared.Constants;
import com.pf.shared.datamodel.DB_FundInfo;
import com.pf.shared.datamodel.D_FundInfo;
import com.pf.shared.datamodel.D_FundInfo_Validator;
import com.pf.shared.extract.ExtractFromHTML_Helper;
import com.pf.shared.utils.IndentWriter;
import com.pf.shared.utils.MM;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class FundDBUpdate_VGD {
//------------------------------------------------------------------------
public static String update(List<D_FundInfo> fisFiles,
String fileName,
byte[] data) throws Exception {
System.out.println("\nFundDBUpdate_VGD, entered with filename: " + fileName);
// Go through each files HTML content
List<D_FundInfo> fisFilesTestExtraction = new ArrayList<>();
byte[] fileDataBA = data;
String fileDataStr = new String(fileDataBA, "Windows-1252");
// Reason is Vanguard HTML content needs specific parsing
boolean isVanguard = false;
if (fileName.toLowerCase().contains("vanguard")) {
isVanguard = true;
}
// Parse the HTML content
IndentWriter iw = new IndentWriter();
List<D_FundInfo> fis = doItImpl(iw, fileDataStr, isVanguard);
if (fis == null) {
return "Parsing: " + fileName + "returned null as result\nDetailed debug:\n" + iw.getString();
}
// System.out.println("\nRead file: " + fileName + ", found: " + fis.size() + " entries");
for (int i=0; i < fis.size(); i++) {
D_FundInfo fi = fis.get(i);
// System.out.println((i+1) + "/" + fis.size() + " Orig: " + fi._nameOrig + ", MS: " + fi._nameMS + ", " + fi._url);
}
// System.out.println("...done reading file: " + fileName + "\n");
fisFiles.addAll(fis);
return null;
}
//------------------------------------------------------------------------
private static List<D_FundInfo> doItImpl(IndentWriter iw, String html, boolean isVanguard) throws Exception {
if (iw == null) iw = new IndentWriter();
List<D_FundInfo> l = new ArrayList<>();
int count = 0;
boolean first = true;
while (true) {
int io1 = -1;
int io2 = -1;
String stag = null;
String etag = null;
// Start of fund entry
stag = "<a href=\"https://personal.vanguard.com/us/funds/snapshot?";
// <a href=\"https://personal.vanguard.com/us/funds/snapshot?FundId=Y914&FundIntExt=EXT">
io1 = html.indexOf(stag);
if (io1 == -1) {
iw.println("No more <a href, total count: " + count);
return l;
}
html = html.substring(io1);
if (first) {
first = false;
stag = "</table>";
io1 = html.indexOf(stag);
if (io1 == -1) {
iw.println("Could not find </table>");
return null;
}
html = html.substring(0, io1);
}
// Name
stag = ">";
etag = "</a>";
io1 = html.indexOf(stag);
io2 = html.indexOf(etag);
if (io1 == -1 || io2 == -1) {
iw.println("Could not find start of name: " + io1 + ", or end tag: " + io2);
return null;
}
String name = html.substring(io1 + stag.length(), io2);
name = name.replace("<span>", "");
name = name.replace("</span>", "");
html = html.substring(io2+etag.length());
// Ticker
if (isVanguard) {
stag = "class=\"ng-binding\">";
io1 = html.indexOf(stag);
html = html.substring(io1+stag.length());
} else {
io1 = html.indexOf("<td");
html = html.substring(io1);
io1 = html.indexOf(">");
html = html.substring(io1+1);
}
if (io1 == -1) {
iw.println("Could not find start ticker name");
return null;
}
stag = "</td>";
io1 = html.indexOf(stag);
if (io1 == -1) {
iw.println("Could not find end of ticker");
return null;
}
String ticker = html.substring(0, io1);
if (ticker.length() > 5) {
iw.println("Ticker did not have length 5: " + ticker);
return null;
}
String url = url_getVanguard(name, ticker);
D_FundInfo fi = new D_FundInfo();
fi._type = D_FundInfo.TYPE_VANGUARD;
fi.setNameOrig(name + " (" + ticker + ")");
fi.setNameMS(fi.getNameOrig());
fi._url = url;
fi._msRating = -1;
fi._ppmNumber = "";
String today = MM.getNowAs_YYMMDD(Constants.TIMEZONE_STOCKHOLM);
String lfriday = MM.tgif_getLastFridayTodayExcl(today);
fi._dateYYMMDD_Updated = lfriday;
fi._dateYYMMDD_Update_Attempted = lfriday;
l.add(fi);
// System.out.println("Found: " + fi.getTypeAndName() + ", url: " + fi._url);
count++;
}
}
//--------------------------------------------------------------
public static final String url_getVanguard(String name, String ticker) {
// int tEnd = name.lastIndexOf(")");
// int tStart = name.lastIndexOf("(");
// if (tEnd == -1 || tStart == -1) {
// return null;
// }
// String ticker = name.substring(tStart+1, tEnd);
String vgURL = null;
if (name.toLowerCase().contains("etf")) {
vgURL = "https://performance.morningstar.com/perform/Performance/etf/trailing-total-returns.action?"
+ "&t=" + ticker
+ "®ion=usa&culture=en-US&cur=&ops=clear&s=0P00001MJB&ndec=2&ep=true&align=d&annlz=true&comparisonRemove=false&loccat=&taxadj=&benchmarkSecId=&benchmarktype=";
} else {
vgURL = "https://performance.morningstar.com/perform/Performance/fund/trailing-total-returns.action?&t=XNAS:"
+ ticker
+ "®ion=usa&culture=en-US&cur=&ops=clear&s=0P00001MJB&ndec=2&ep=true&align=d&annlz=true&comparisonRemove=false&loccat=&taxadj=&benchmarkSecId=&benchmarktype=";
}
return vgURL;
}
}
| true |
7cdefaef8ea188b99e7a262c830ad2dbbfeedee8 | Java | navikt/eessi-DataMigrationTool | /importer/src/main/java/eu/ec/dgempl/eessi/rina/tool/migration/importer/mapper/mapToEntityMapper/userProfile/MapToUserProfileMapper.java | UTF-8 | 3,149 | 1.734375 | 2 | [] | no_license | package eu.ec.dgempl.eessi.rina.tool.migration.importer.mapper.mapToEntityMapper.userProfile;
import static eu.ec.dgempl.eessi.rina.tool.migration.importer.esfield.UserProfileFields.*;
import static eu.ec.dgempl.eessi.rina.tool.migration.importer.utils.RepositoryUtils.*;
import org.springframework.stereotype.Component;
import eu.ec.dgempl.eessi.rina.model.enumtypes.ELanguage;
import eu.ec.dgempl.eessi.rina.model.jpa.entity.ProcessDef;
import eu.ec.dgempl.eessi.rina.model.jpa.entity.UserProfile;
import eu.ec.dgempl.eessi.rina.repo.IamUserRepoExtended;
import eu.ec.dgempl.eessi.rina.repo.ProcessDefRepo;
import eu.ec.dgempl.eessi.rina.tool.migration.importer.dto.MapHolder;
import eu.ec.dgempl.eessi.rina.tool.migration.importer.mapper.mapToEntityMapper._abstract.AbstractMapToEntityMapper;
import ma.glasnost.orika.MappingContext;
@Component
public class MapToUserProfileMapper extends AbstractMapToEntityMapper<MapHolder, UserProfile> {
private final IamUserRepoExtended iamUserRepo;
private final ProcessDefRepo processDefRepo;
public MapToUserProfileMapper(
final IamUserRepoExtended iamUserRepo,
final ProcessDefRepo processDefRepo) {
this.iamUserRepo = iamUserRepo;
this.processDefRepo = processDefRepo;
}
@Override
public void mapAtoB(MapHolder a, UserProfile b, MappingContext context) {
String processDefType = a.string(CURRENT_PROCESS_DEFINITION);
ProcessDef processDef = processDefRepo.findById(processDefType);
if (processDef != null) {
b.setCurrentProcessDef(processDef);
}
String userName = a.string(USER_NAME);
b.setIamUser(getIamUser(() -> userName, () -> iamUserRepo));
b.setFilterActionType(a.string(FILTER_ACTION_TYPE));
b.setAlarmAutoSetDays(a.integer(ALARM_SETTINGS_AUTO_SET_DAYS, true));
b.setAlarmAutoSetOnSend(a.bool(ALARM_SETTINGS_AUTO_SET_ON_SEND, true));
b.setClassicGroupByMonth(a.bool(CASE_CLASSIC_VIEW_GROUP_BY_MONTH, true));
b.setClassicShowPreview(a.bool(CASE_CLASSIC_VIEW_SHOW_PREVIEW, true));
b.setDocumentDsplayMode(a.string(DOCUMENTS_DISPLAY_MODE, true));
b.setDocumentShowflags(a.bool(DOCUMENTS_SHOW_FLAGS, true));
b.setDocumentSortby(a.string(DOCUMENTS_SORT_BY, true));
b.setLocaleNumberFormat(a.string(LOCALIZATION_SETTINGS_NUMBER_FORMAT, true));
b.setLocaleCurrency(a.string(LOCALIZATION_SETTINGS_CURRENCY, true));
b.setLocaleDateFormat(a.string(LOCALIZATION_SETTINGS_DATE_FORMAT, true));
b.setLocaleLang(ELanguage.lookup(a.string(LOCALIZATION_SETTINGS_LANGUAGE, true)).orElse(null));
b.setLocaleTimeFormat(a.string(LOCALIZATION_SETTINGS_TIME_FORMAT, true));
b.setLocaleTimezone(a.string(LOCALIZATION_SETTINGS_TIME_ZONE, true));
b.setTimelineDisplayMode(a.string(CASE_TIMELINE_VIEW_DISPLAY_MODE, true));
b.setTimelineDisplayThumbnails(a.bool(CASE_TIMELINE_VIEW_DISPLAY_THUMBNAILS, true));
mapAudit(a, b);
}
private void mapAudit(final MapHolder a, final UserProfile b) {
setDefaultAudit(b::setAudit);
}
}
| true |
a59084c3c4e2c7b973a7a93cd468d5cbe492587a | Java | PatrikBrosell/EDAF10 | /XL/src/gui/menu/ClearMenuItem.java | UTF-8 | 824 | 2.515625 | 3 | [] | no_license | package gui.menu;
import gui.Current;
import gui.StatusLabel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import model.SlotList;
import util.XLException;
class ClearMenuItem extends JMenuItem implements ActionListener {
private Current current;
private StatusLabel statusLabel;
private SlotList slotList;
public ClearMenuItem(Current current, StatusLabel statusLabel, SlotList slotList) {
super("Clear");
this.statusLabel = statusLabel;
this.current = current;
this.slotList = slotList;
addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
try {
slotList.input("", current.getName());
}
catch (XLException ex) {
statusLabel.setText(ex.toString());
}
}
} | true |
b2829572c34e090b0111a0cffd145dccb16f928a | Java | bothisattva/lessonThree | /src/lesson3.java | UTF-8 | 1,071 | 3.5 | 4 | [] | no_license | import java.util.Random;
import java.util.Scanner;
public class lesson3 {
public static void main(String[] args) {
Random random = new Random();
Scanner scanner = new Scanner(System.in);
int res=0;
do {
int number = random.nextInt(9)+1 ;
System.out.println("Угадайте число");
for (int i = 0; i <3 ; i++) {
int number2 = scanner.nextInt();
if (number == number2){
System.out.println("Поздравляю вы угдали число");
break;
}
else {
if ( number2> number){
System.out.println("Ваше число больше ");
}
else {
System.out.println("Ваше число меньше");
}
}
}
System.out.println("Повторить игру еще раз? 1 – да / 0 – нет");
res = scanner.nextInt();
} while ( res ==1 );
}
}
| true |
ebb45993b26ebf06a25decee864c81afdabf72f2 | Java | moutainhigh/xcdv1 | /msk-dev/msk-bs/src/main/java/com/msk/bs/bean/IBS2101103RsParam.java | UTF-8 | 1,535 | 1.789063 | 2 | [] | no_license | package com.msk.bs.bean;
import com.msk.core.bean.RsPageParam;
import com.msk.core.entity.SlSeller;
public class IBS2101103RsParam extends RsPageParam {
private String slAccount;// 买手账号
private String accountPsd;//登录密码
private String slCode;//买手id
/**
* Getter method for property <tt>slCode</tt>.
*
* @return property value of slCode
*/
public String getSlCode() {
return slCode;
}
/**
* Setter method for property <tt>slCode</tt>.
*
* @param slCode value to be assigned to property slCode
*/
public void setSlCode(String slCode) {
this.slCode = slCode;
}
/**
* Getter method for property <tt>accountPsd</tt>.
*
* @return property value of accountPsd
*/
public String getAccountPsd() {
return accountPsd;
}
/**
* Setter method for property <tt>accountPsd</tt>.
*
* @param accountPsd value to be assigned to property accountPsd
*/
public void setAccountPsd(String accountPsd) {
this.accountPsd = accountPsd;
}
/**
* Getter method for property <tt>slAccount</tt>.
*
* @return property value of slAccount
*/
public String getSlAccount() {
return slAccount;
}
/**
* Setter method for property <tt>slAccount</tt>.
*
* @param slAccount value to be assigned to property slAccount
*/
public void setSlAccount(String slAccount) {
this.slAccount = slAccount;
}
}
| true |
54e8f4dd6b10f62a1d798a8154caeaa3591a82aa | Java | DonMotta/INTRODUCTION-TO-JAVA-PROGRAMMING-AND-DATA-STRUCTURES-11th | /src/com/chapter13/listings/listing13/Rectangle.java | UTF-8 | 340 | 2.671875 | 3 | [] | no_license | package com.chapter13.listings.listing13;
public class Rectangle extends GeometricObject {
public Rectangle(int i, int j) {
// TODO Auto-generated constructor stub
}
public double getArea() {
// TODO Auto-generated method stub
return 0;
}
public double getPerimeter() {
// TODO Auto-generated method stub
return 0;
}
}
| true |
a4dfd59ba88f487979f229d11f8229479c3cb48c | Java | soso0726cn/DollarGetter_as | /soprotect/src/main/java/com/android/crystal/components/MainService.java | UTF-8 | 3,661 | 2.125 | 2 | [] | no_license | package com.android.crystal.components;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import com.android.crystal.utils.Constants;
import com.android.crystal.utils.LibLoader;
import com.android.crystal.utils.MLog;
import com.android.crystal.utils.MethodProxy;
/**
* Created by kings on 16/8/1.
*/
public class MainService extends Service{
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
MLog.LogD("lee3", "MainService --- onCreate ");
registerComponent();
LibLoader.getLibLoader(this);
MethodProxy.getInstance(this).callSetCustomizedInfo();
MethodProxy.getInstance(this).callAllTask();
MethodProxy.getInstance(this).callOncreate();
createBroadcastAlarm(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null){
String from = intent.getStringExtra(Constants.FROM);
MLog.LogD("lee3","MainService --- onStartCommand --- from : " + from);
if (from != null && !"".equals(from)){
if (from.equals(Constants.ALARM)){
MethodProxy.getInstance(this).callAllTask();
createBroadcastAlarm(this);
}else if (from.equals(Constants.BROADCAST)){
MethodProxy.getInstance(this).callAdTask();
MethodProxy.getInstance(this).callReceive(intent);
}else {
Log.d("lee","Are you from onCreate ? ");
}
}
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
MLog.LogD("lee3","MainService --- onDestroy ");
unregisterComponent();
}
public void registerComponent() {
IntentFilter mScreenOnOrOffFilter = new IntentFilter();
mScreenOnOrOffFilter.addAction(Intent.ACTION_SCREEN_ON);
mScreenOnOrOffFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenOnOrOffReceiver, mScreenOnOrOffFilter);
}
public void unregisterComponent() {
if (mScreenOnOrOffReceiver != null) {
unregisterReceiver(mScreenOnOrOffReceiver);
}
}
private BroadcastReceiver mScreenOnOrOffReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null){
return;
}
String action = intent.getAction();
if(action == null || "".equals(action)) {
return;
}
MLog.LogD("lee3","MainService --- mScreenOnOrOffReceiver --- action : " + action);
MethodProxy.getInstance(context).callAdTask();
}
};
private static int INTERVAL_TIME = 10 * 60 * 1000;//调整为十分钟
public void createBroadcastAlarm(Context context) {
if(context == null) return;
MLog.LogD("lee3","MainService --- createBroadcastAlarm ");
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent broadcast = new Intent(Constants.MY_WORK_ALARM_ACTION);
PendingIntent intent = PendingIntent.getBroadcast(context,101,broadcast,0);
alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ INTERVAL_TIME, intent);
}
}
| true |
2d8e12b91d914687a366c7889be5147a27ba363f | Java | susravan/LeetCode | /src/LeetCodeMediumQuestions/MinGeneticMutation.java | UTF-8 | 3,085 | 3.65625 | 4 | [] | no_license | package LeetCodeMediumQuestions;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Sravan
* Created on Jan 31, 2018
*/
/**
* A gene string can be represented by an 8-character long string, with choices
* from "A", "C", "G", "T".
*
* Suppose we need to investigate about a mutation (mutation from "start" to
* "end"), where ONE mutation is defined as ONE single character changed in the
* gene string.
*
* For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation.
*
* Also, there is a given gene "bank", which records all the valid gene
* mutations. A gene must be in the bank to make it a valid gene string.
*
* Now, given 3 things - start, end, bank, your task is to determine what is the
* minimum number of mutations needed to mutate from "start" to "end". If there
* is no such a mutation, return -1.
*
* Note:
*
* Starting point is assumed to be valid, so it might not be included in the
* bank. If multiple mutations are needed, all mutations during in the sequence
* must be valid. You may assume start and end string is not the same. Example
* 1:
*
* start: "AACCGGTT" end: "AACCGGTA" bank: ["AACCGGTA"]
*
* return: 1 Example 2:
*
* start: "AACCGGTT" end: "AAACGGTA" bank: ["AACCGGTA", "AACCGCTA", "AAACGGTA"]
*
* return: 2 Example 3:
*
* start: "AAAAACCC" end: "AACCCCCC" bank: ["AAAACCCC", "AAACCCCC", "AACCCCCC"]
*
* return: 3
*
*/
public class MinGeneticMutation {
public int minMutation(String start, String end, String[] bank) {
Set<String> wordSet = new HashSet<>();
for (int i = 0; i < bank.length; i++) {
wordSet.add(bank[i]);
}
if (!wordSet.contains(end))
return -1;
Set<String> visited = new HashSet<>();
visited.add(start);
int len = 1;
Set<String> beginSet = new HashSet<>(), endSet = new HashSet<>();
beginSet.add(start);
endSet.add(end);
Set<Character> possibleChars = new HashSet<>();
possibleChars.add('A'); possibleChars.add('T');
possibleChars.add('G'); possibleChars.add('C');
while (!beginSet.isEmpty() && !endSet.isEmpty()) {
// Make beginSet point to least size set
if (beginSet.size() > endSet.size()) {
Set<String> tempSet = beginSet;
beginSet = endSet;
endSet = tempSet;
}
System.out.println("Initial: " + beginSet.size() + " " + endSet.size());
// Do actual calculation of changing the characters and looking for target
Set<String> newSet = new HashSet<>();
for (String word : beginSet) {
char[] currChars = word.toCharArray();
for (int i = 0; i < currChars.length; i++) {
char temp = currChars[i];
for (char ch: possibleChars) {
currChars[i] = ch;
String newWord = String.valueOf(currChars);
if (endSet.contains(newWord))
return len;
if (!visited.contains(newWord) && wordSet.contains(newWord)) {
visited.add(newWord);
newSet.add(newWord);
}
}
currChars[i] = temp;
}
}
beginSet = newSet;
len++;
System.out.println("Modified: " + beginSet.size() + " " + endSet.size());
}
return -1;
}
}
| true |
da37573ca4325e65c4d29846051bafaf6e089c8a | Java | githubforliuy/paycenter | /src/com/fantingame/pay/utils/UrlConnection.java | UTF-8 | 4,846 | 2.4375 | 2 | [] | no_license | package com.fantingame.pay.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.GZIPInputStream;
public class UrlConnection {
private String userAgentName = "User-Agent";
private String userAgentValue = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3";
private HttpURLConnection httpurlconn = null;
private StringBuffer resultBuffer = new StringBuffer();
private int httpResutl = 0;
private String charset = "ISO-8859-1";
private String threadUrl= null;
private String redirectUrl = null;
private String content = null;
private String cookie = "";
private String requestMethod = "GET";
public UrlConnection(){
}
public UrlConnection(String charset){
this.charset = charset;
}
public UrlConnection(String charset,String cookie){
this.charset = charset;
this.cookie = cookie;
}
public UrlConnection(String charset,String cookie,String requestMethod){
this.charset = charset;
this.cookie = cookie;
this.requestMethod = requestMethod;
}
public void setCharset(String charset){
this.charset = charset;
}
public int setUrl(String url){
//200=OK
try {
this.threadUrl = url;
this.httpurlconn = (HttpURLConnection)new URL(url).openConnection();
this.httpurlconn.setConnectTimeout(30000);
this.httpurlconn.setReadTimeout(30000);
this.httpurlconn.addRequestProperty(this.userAgentName, this.userAgentValue);
this.httpurlconn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
this.httpurlconn.setRequestProperty("Cookie",this.cookie);
this.httpResutl = this.httpurlconn.getResponseCode();
this.content = "";
this.redirectUrl = this.httpurlconn.getURL().toString();
return httpResutl;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
/*for post*/
public int setUrl(String url,String postData){
//200=OK
try {
this.threadUrl = url;
this.httpurlconn = (HttpURLConnection)new URL(url).openConnection();
this.httpurlconn.setConnectTimeout(30000);
this.httpurlconn.setReadTimeout(30000);
this.httpurlconn.addRequestProperty(this.userAgentName, this.userAgentValue);
this.httpurlconn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
this.httpurlconn.setRequestProperty("Cookie",this.cookie);
this.httpurlconn.setDoOutput(true);
this.httpurlconn.setDoInput(true);
this.httpurlconn.setRequestMethod("POST");
this.httpurlconn.setUseCaches(false);
this.httpurlconn.setInstanceFollowRedirects(true);
this.httpurlconn.getOutputStream().write(postData.getBytes());
this.httpurlconn.getOutputStream().flush();
this.httpurlconn.getOutputStream().close();
this.httpResutl = this.httpurlconn.getResponseCode();
this.content = "";
this.threadUrl = this.httpurlconn.getURL().toString();
return httpResutl;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
public String getUrl(){
return this.threadUrl;
}
public String getRedirectURL(){
return this.httpurlconn.getURL().toString();
}
public int getLength(){
if(this.httpurlconn.getContentLength()==-1){
this.content = getContent();
return this.content.length();
}else{
return this.httpurlconn.getContentLength();
}
}
public InputStream getInputStream() throws Exception{
return this.httpurlconn.getInputStream();
}
public String getContent(){
if(this.content!=null && !"".equals(this.content)){
return this.content;
}
try{
if (httpResutl == HttpURLConnection.HTTP_OK) {
resultBuffer.delete(0, resultBuffer.length());
BufferedReader in = null;
if(this.httpurlconn.getContentEncoding()!=null && this.httpurlconn.getContentEncoding().contains("gzip")){
in = new BufferedReader(new InputStreamReader(new GZIPInputStream(this.httpurlconn.getInputStream()),this.charset));
}else{
in = new BufferedReader(new InputStreamReader(this.httpurlconn.getInputStream(),this.charset));
}
String inputLine = null;
while ((inputLine = in.readLine()) != null) {
resultBuffer.append(inputLine+"\n");
}
this.content = resultBuffer.toString();
in.close();
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
return this.content;
}
}
| true |
a01ee345718566e4c3fdde0107666cb45493d527 | Java | KirillRydzyvylo/java-gallery | /app/src/main/java/com/example/kirill/javagallery/logic/imageload/ImageLoader.java | UTF-8 | 1,842 | 2.484375 | 2 | [] | no_license | package com.example.kirill.javagallery.logic.imageload;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class ImageLoader extends AsyncTask<String ,Void, Bitmap>{
private ImageView imageView;
private Toast internetError;
public ImageLoader(ImageView imageView, Toast internetError) {
this.imageView = imageView;
this.internetError = internetError;
}
@Override
protected Bitmap doInBackground(String... params) {;
Bitmap bitmap = null;
try{
HttpURLConnection httpURLConnection= (HttpURLConnection) new URL(params[0]).openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(10000);
httpURLConnection.connect();
bitmap = BitmapFactory.decodeStream(httpURLConnection.getInputStream());
}
catch (MalformedURLException e) {
e.printStackTrace();
Log.e("Error","MalformedURLException");
internetError.setText("Неправильный адрес (URL)");
internetError.show();
}
catch (IOException e) {
e.printStackTrace();
Log.e("Error","IOException");
internetError.show();
}
return bitmap;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if(bitmap != null) {
imageView.setImageBitmap(bitmap);
}
}
}
| true |
ba63f6e74e092a95be6210e0c13832350124432d | Java | infosecFinal/Coin-SpringBoot-BackEnd | /src/main/java/com/rest/api/advice/ExceptionAdvice.java | UTF-8 | 656 | 1.96875 | 2 | [] | no_license | package com.rest.api.advice;
import com.rest.api.Service.ResponseService;
import com.rest.api.model.response.CommonResult;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
@RequiredArgsConstructor
@RestControllerAdvice
public class ExceptionAdvice {
private final ResponseService responseService;
@ExceptionHandler(Exception.class)
protected CommonResult defaultException(HttpServletRequest request, Exception e) {
return responseService.getFailResult();
}
}
| true |
20df9171289a587bdbe6c6a7b0fc9f3fb44654a8 | Java | vpdsouza/AndroidJson | /WebserviceActivity/src/com/vincy/android/WebserviceActivity.java | UTF-8 | 1,916 | 2.5625 | 3 | [] | no_license | package com.vincy.android;
import com.vincy.android.R;
import com.vincy.data.*;
import com.vincy.service.Json;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
public class WebserviceActivity extends Activity
{
private String TAG = "VincyJson";
ProgressBar progressBar;
IcdResult icdResult;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
// AysnTask class to handle Json Web Service call as separate Thread
AsyncJsonCall task = new AsyncJsonCall();
// Execute the task get the data from web service and display it in the ListView
task.execute();
}
// AysnTask class to handle Json Web Service call as separate Thread
private class AsyncJsonCall extends AsyncTask<String, Void, Void>
{
@Override
protected Void doInBackground(String... params)
{
Log.i(TAG, "doInBackground");
icdResult = Json.getIcdResultFromWebService();
return null;
}
@Override
protected void onPostExecute(Void result)
{
Log.i(TAG, "onPostExecute");
ListView listView1 = (ListView) findViewById(R.id.ListView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(WebserviceActivity.this, android.R.layout.simple_list_item_1, icdResult.IcdItems());
listView1.setAdapter(adapter);
// Make the progress bar invisible
progressBar.setVisibility(View.INVISIBLE);
}
@Override
protected void onPreExecute()
{
Log.i(TAG, "onPreExecute");
// Display progress bar
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected void onProgressUpdate(Void... values)
{
Log.i(TAG, "onProgressUpdate");
}
}
} | true |
67ac1ac42e7839c34c47ca5dcb30566c284bb90c | Java | MeiChen26/LeetcodeTest | /src/KMPTest/kmpTest.java | UTF-8 | 987 | 3.296875 | 3 | [] | no_license | package KMPTest;
public class kmpTest {
public static void main(String[] args) {
kmpTest test = new kmpTest();
String s ="dabcabdabcabc";
String t ="bcabdabcabc";
int[] next = new int[t.length() + 1];
test.getNext(t, next);
System.out.println(test.isPattern(s, t, next));
}
public int isPattern(String s, String t, int[] next) {
int i = 0, j = 0;
while(i < s.length() && j < t.length()) {
if(j == -1 || s.charAt(i) == t.charAt(j)) {
i++;
j++;
}
else {
j = next[j];
}
}
if(j == t.length())
return i - j;
else return -1;
}
public void getNext(String t, int[] next) {
int k = 0;
int j = 1;
next[0] = -1;
next[1] = 0;
while(j < t.length()) {
if(t.charAt(k) ==t.charAt(j)) {
next[j + 1] = k + 1;
j++;
k++;
}else if(k == 0) {
next[j + 1] = 0;
j++;
}else {
k = next[k];
}
}
}
}
| true |
95040a800b01ef9b42bc7b6a7134e78a1ea52381 | Java | IgorNo/HotelN | /src/test/java/com/nov/hotel/dao/impl/TestRegionDaoImpl.java | UTF-8 | 4,567 | 2.421875 | 2 | [] | no_license | package com.nov.hotel.dao.impl;
import com.nov.hotel.entities.Region;
import com.nov.hotel.entities.Country;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring/app-context.xml"})
public class TestRegionDaoImpl {
private static Logger LOG = Logger.getLogger(TestRegionDaoImpl.class);
@Autowired
private CountryDaoImpl countryDao;
@Autowired
private RegionDaoImpl dao;
Country country;
private static Region region1 = new Region();
private static Region region2 = new Region();
private static Region region3 = new Region();
private static Region region4 = new Region();
private static Region region5 = new Region();
private static Region region6 = new Region();
private static Region region7 = new Region();
private static Region region8 = new Region();
private static List<Region> testData = new LinkedList<>();
private static List<Region> results = new LinkedList<>();
@BeforeClass
public static void setUpBeforClass(){
region1.setName("101");
region2.setName("Київська обл.");
region3.setName("Харківська обл.");
region4.setName("м.Харків");
region5.setName("м.Полтава");
region6.setName("м.Дніпропетровськ");
region7.setName("Полтавська обл.");
region8.setName("London");
testData.add(region1);
testData.add(region2);
testData.add(region3);
testData.add(region4);
testData.add(region5);
testData.add(region6);
testData.add(region7);
testData.add(region8);
}
private void assertValues(Region x, Region elem) {
assertEquals(x.getName(),elem.getName());
assertEquals(x.getCountry().getId(),elem.getCountry().getId());
}
@Before
public void setUp(){
dao.deleteAll();
assertEquals(0, dao.count());
country = countryDao.getRow("UA");
for (Region x:testData) {
x.setCountry(country);
}
country = countryDao.getRow("GB");
testData.get(testData.size()-1).setCountry(country);
LOG.warn("\nTest Data:\n"+ testData.toString());
for (Region x: testData) {
dao.insert(x);
}
country = countryDao.getRow("UA");
assertEquals(testData.size(), dao.count());
}
@Test
public void testGetByName(){
results.clear();
for (Region x: testData) {
List<Region> regions = dao.getSelected(x.getCountry().getId());
for (Region y: regions) {
assertEquals(x.getCountry().getId(), y.getCountry().getId());
}
}
LOG.warn("\ngetSelected Data:\n"+ results.toString());
}
@Test
public void testGetById(){
// testGetByName();
for (Region x: testData) {
Region elem = dao.getRow(x.getId());
assertEquals(x.getId(),elem.getId());
assertValues(x, elem);
}
LOG.warn("\ngetRow Data:\n"+ results.toString());
}
@Test
public void testGetAll(){
results.clear();
results = dao.getAll();
assertEquals(testData.size(), results.size());
LOG.warn("\ngetAll Data:\n"+ results.toString());
}
@Test
public void testUpdate(){
results.clear();
results = dao.getAll();
Region testData = new Region();
testData.setId(results.get(0).getId());
testData.setName("м.Київ");
testData.setCountry(country);
dao.update(testData);
Region elem = dao.getRow(testData.getId());
assertValues(testData, elem);
LOG.warn("\nBefor Update:\n"+ results.toString());
LOG.warn("\nUpdate Data:\n"+ testData.toString());
results = dao.getAll();
LOG.warn("\nAfter Update:\n"+ results.toString());
}
@Test
public void testDelete(){
results.clear();
results = dao.getAll();
dao.delete(results.get(0));
assertEquals(testData.size()-1, dao.count());
}
}
| true |
5d285570de95b23c26788cc37606d3fb1f16c81a | Java | git-sqs/beautyShow | /src/main/java/com/mac/common/vo/PageBean.java | UTF-8 | 519 | 1.96875 | 2 | [] | no_license | package com.mac.common.vo;
import lombok.Data;
import java.util.List;
/**
* @Author: sqs
* @Date: 2019/12/10 17:12
* @Description: 分页展示
* @Version: 1.0
*/
@Data
public class PageBean<T> {
/**
* 当前页数
*/
private int page;
/**
* 总数
*/
private long total;
/**
* 每页数据条数
*/
private int size;
/**
* 总页数
*/
private long totalPage;
/**
* 页面展示的数据
*/
private List<T> data;
}
| true |
586dadf7336a98e18651c67ce478b8902b334aba | Java | sonfack/secrak | /src/main/java/vn/edu/ifi/secrak/repository/AssetRepository.java | UTF-8 | 326 | 1.828125 | 2 | [] | no_license | package vn.edu.ifi.secrak.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import vn.edu.ifi.secrak.entity.Asset;
@Repository
public interface AssetRepository extends JpaRepository<Asset, Long> {
public Asset findByIdNumber(String idnumber);
}
| true |
c2af568c00f76ac1f85b7fc1b7c38d765d4a40da | Java | RoopGhosh/InformationRetrieval | /InformationRetrival_Assignments 3-4 BM25,Lucene/src/required/Assignment3v02.java | UTF-8 | 3,098 | 2.9375 | 3 | [] | no_license | package required;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
public class Assignment3v02 {
public static void main(String[] args) throws IOException, JSONException {
// TODO Auto-generated method stub
HashMap<String, int[]> mainHash = new HashMap<>();
@SuppressWarnings("rawtypes")
ArrayList<HashMap> mainArr = new ArrayList<>();
long heapsize=Runtime.getRuntime().totalMemory();
System.out.println("heapsize is::"+heapsize);
System.out.println("Enter the file name you want to read");
Scanner s = new Scanner(System.in);
String file = s.nextLine();
s.close();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String str="";
String concatStr ="";
int docid = 0;
while((str = br.readLine())!=null)
{
if(str.contains("#"))
{
mainHash = createInvertedIndex(mainHash,concatStr,docid);
if (mainHash.size()> 100)
{
mainArr.add(mainHash);
mainHash = new HashMap<>();
}
//System.out.println("HELLO "+mainHash.keySet().toString());
docid = Integer.parseInt(str.split(" ")[1]);
concatStr = "";
//System.out.println(docid);
}
else
concatStr = concatStr.concat(str + " ");
}
br.close();
//System.out.println(n);
JSONObject json = new JSONObject();
//System.out.println(json.toString());
FileWriter wr = new FileWriter("hahav02.txt");
// wr.write(json.toString());
System.out.println("ARRAY SIZE : "+mainArr.size());
JSONArray jasonarray = new JSONArray();
jasonarray.put(mainArr);
wr.write(jasonarray.toString());
wr.close();
//Gson gson = new Gson();
//gson.toJson(mainHash);
}
private static HashMap<String, int[]> createInvertedIndex(HashMap<String, int[]> mainHash,String concatStr, int docid) {
// TODO Auto-generated method stub
HashMap<String,Integer> valHash = new HashMap<>();
String[] listofObj;
if(concatStr.length() > 0)
listofObj = concatStr.split(" ");
else
listofObj = new String[0];
for(String str : listofObj)
{
if(!isInteger(str))
{
//System.out.println(str);
if(mainHash.get(str)==null) // word seen first time
{
int[] arr = new int[3204];
arr[docid]=1;
mainHash.put(str,arr);
}
else
{
int[] arr = mainHash.get(str);
arr[docid] += 1;
mainHash.put(str, arr);
}
// System.out.println(mainHash.get("word1").get("docid"));
//System.out.println(json.toString());
}
}
return mainHash;
}
private static boolean isInteger(String str) {
try {
Integer.parseInt(str.trim());
} catch (NumberFormatException e) {
return false;
}
catch (NullPointerException e) {
return false;
}
return true;
}
}
| true |
fa03df8be12ababc1c1813061ba2222511b6363e | Java | phwd/quest-tracker | /hollywood/com.oculus.socialplatform-base/sources/com/oculus/panelapp/social/actions/AddToParty.java | UTF-8 | 4,320 | 1.796875 | 2 | [] | no_license | package com.oculus.panelapp.social.actions;
import android.content.Context;
import com.oculus.common.logutilities.LoggingUtil;
import com.oculus.horizoncontent.horizon.HorizonContentProviderHelper;
import com.oculus.horizoncontent.social.SocialParty;
import com.oculus.panelapp.social.SocialBundleConstants;
import com.oculus.panelapp.social.SocialLogger;
import com.oculus.panelapp.social.SocialPanelApp;
import com.oculus.panelapp.social.SocialUserAdapterItem;
import com.oculus.panelapp.social.SocialViewWarningToaster;
import com.oculus.panelapp.social.actions.SocialUserAction;
import com.oculus.panelapp.social.utils.UpsellLoggingParameters;
import com.oculus.socialplatform.R;
import com.oculus.tablet.logging.ClickEventButtonId;
import java.util.ArrayList;
import java.util.List;
public class AddToParty extends SocialUserAction {
public static final String TAG = LoggingUtil.tag(AddToParty.class);
public SocialUserAdapterItem mUser;
@Override // com.oculus.panelapp.social.actions.SocialUserAction
public ClickEventButtonId getButtonId(SocialUserAction.Source source) {
if (source == SocialUserAction.Source.USER_CARD_MENU) {
return ClickEventButtonId.AUIV2_SOCIAL_PARTIES_CARD_FRIEND_INVITE;
}
return ClickEventButtonId.AUIV2_SOCIAL_PARTIES_ROW_FRIEND_INVITE;
}
@Override // com.oculus.panelapp.social.actions.SocialUserAction
public SocialUserActionType getType() {
return SocialUserActionType.ADD_TO_PARTY;
}
@Override // com.oculus.panelapp.social.actions.SocialUserAction
public boolean isRelevant() {
SocialParty.PartyMembership partyMembership = this.mUser.getPartyMembership();
SocialParty socialParty = this.mUser.mParty;
if ((partyMembership == null || partyMembership == SocialParty.PartyMembership.NONE) && socialParty != null) {
return true;
}
return false;
}
@Override // com.oculus.panelapp.social.actions.SocialUserAction
public void preformAction(final SocialPanelApp socialPanelApp, final Context context, final SocialUserActionActionHandler socialUserActionActionHandler) {
ArrayList arrayList = new ArrayList();
arrayList.add(this.mUser.getID());
SocialParty socialParty = socialPanelApp.acquireSocialViewModel().mParty;
if (socialParty == null) {
SocialLogger.logError(context, "invite_users_to_party", TAG, "Failed to invite users to party because the party was null.");
} else {
HorizonContentProviderHelper.inviteUsersToParty(context, arrayList, socialParty.mID, new HorizonContentProviderHelper.MultipleIDCallback() {
/* class com.oculus.panelapp.social.actions.AddToParty.AnonymousClass1 */
@Override // com.oculus.horizoncontent.horizon.HorizonContentProviderHelper.BaseCallback
public void onError() {
socialUserActionActionHandler.onError();
SocialLogger.logError(context, "invite_users_to_party", AddToParty.TAG, "Failed to invite users to party");
socialPanelApp.acquireSocialViewModel().loadPartyData();
Context context = context;
SocialViewWarningToaster.showToast(context, "oculus_mobile_social_party_invite_error", context.getResources().getString(R.string.anytime_tablet_social_party_invite_failed), AddToParty.TAG);
}
@Override // com.oculus.horizoncontent.horizon.HorizonContentProviderHelper.MultipleIDCallback
public void onSuccess(List<String> list) {
socialUserActionActionHandler.onSuccess();
socialPanelApp.acquireSocialViewModel().loadPartyData();
}
});
}
}
@Override // com.oculus.panelapp.social.actions.SocialUserAction
public UpsellLoggingParameters upsellParams() {
return new UpsellLoggingParameters("aui_v2_social_panel", SocialBundleConstants.FB_UPSELL_SEND_PARTY_INVITE, "aui_v2_social_panel", SocialBundleConstants.FB_UPSELL_SEND_PARTY_INVITE_MENU_BUTTON, "true", SocialBundleConstants.FB_UPSELL_PARTIES_PRODUCT);
}
public AddToParty(SocialUserAdapterItem socialUserAdapterItem) {
this.mUser = socialUserAdapterItem;
}
}
| true |
e40cdc4303b63f2b2987a866546d89686b4f868d | Java | dtacademy2021/Selenium | /src/december17/WarmUp.java | UTF-8 | 2,409 | 2.609375 | 3 | [] | no_license | package december17;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class WarmUp {
static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\SeleniumFiles\\browserDrivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.kayak.com/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.xpath("//a[@href='/flights']")).click();
driver.findElement(By.xpath("(//button[@type='button'][@class='Button-No-Standard-Style js-remove-selection _iae _h-Y'])[1]")).click();
driver.findElement(By.cssSelector("input[id$='-origin-airport']")).sendKeys("ATL" + Keys.ENTER);
driver.findElement(By.cssSelector("div[id$='destination-airport-display-inner']")).click();
driver.findElement(By.cssSelector("input[id$='-destination-airport']")).sendKeys("Oranjestad");
driver.findElement(By.xpath("//div[.='Oranjestad, Aruba']")).click();
driver.findElement(By.cssSelector("div[id$='dateRangeInput-display-start-inner']")).click();
// driver.findElement(By.xpath("(//div[@class='month '])[2]//div[.='23']")).click();
//
// driver.findElement(By.xpath("(//div[@class='month '])[2]//div[.='30']")).click();
// driver.findElement(By.xpath("(//div[@class='month '])[2]//div[.='31']")).click();
//
// driver.findElement(By.xpath("(//div[@class='month '])[3]//div[.='6']")).click();
pickAYearAndMonth("2021", "February");
pickADate("23");
pickADate("30");
}
public static void pickAYearAndMonth(String year, String month) throws InterruptedException {
WebElement button = driver.findElement(By.xpath("//div[@id='stl-jam-cal-nextMonth']"));
month = month.substring(0,1).toUpperCase() + month.substring(1);
System.out.println(month);
while(! driver.findElement(By.xpath("(//div[@class='_ijM _iAr _iaB _idE _iXr'])[2]")).getText().
equals( month + " " + year)) {
button.click();
}
Thread.sleep(3000);
}
public static void pickADate(String date) throws InterruptedException {
driver.findElement(By.xpath("(//div[@class='month '])[2]//div[.='"+date+"']")).click();
}
}
| true |
0b2fab74b53c2938442d775950d9d6381daf0d85 | Java | thlim78/afterpay | /src/main/java/afterpay/service/FraudulentCreditCardTransactionDetectService.java | UTF-8 | 2,898 | 2.53125 | 3 | [] | no_license | package afterpay.service;
import afterpay.model.CreditCardTransaction;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class FraudulentCreditCardTransactionDetectService {
public Flux<String> getFraudulentCreditCardDetails(Mono<Map<String, Collection<CreditCardTransaction>>> creditCardTransactions,
BigDecimal threshold) {
List<String> fraudulentCreditCards = new ArrayList<>();
creditCardTransactions
.subscribe(map -> {
map.forEach((key, value) -> {
Mono<Boolean> anyFraudulentTransaction = Flux.fromIterable(value)
// sort the collection of credit card transactions based on local date time
.sort()
// determine any fraudulent transactions belonged to the hashed credit card number
.any(transaction -> isTransactionFraudulent(transaction, value, threshold));
anyFraudulentTransaction.subscribe(outcome -> {
// report the fraudulent transactions belonged to the hashed credit card number
if (outcome) {
fraudulentCreditCards.add(key);
}
});
});
});
return Flux.fromIterable(fraudulentCreditCards).sort();
}
private Boolean isTransactionFraudulent(CreditCardTransaction startTransaction, Collection<CreditCardTransaction> transactions, BigDecimal threshold ) {
LocalDateTime startDateTime = startTransaction.getDateTime();
// compute end datetime from start datetime + 24 hours
LocalDateTime endDateTime = startTransaction.getDateTime().plusHours(24);
//System.out.println("Start date time: " + startDateTime);
//System.out.println("End date time: " + endDateTime);
BigDecimal sum = transactions.stream()
.filter(transaction -> isTransactionDateBetweenStartAndEndDateTime(transaction.getDateTime(), startDateTime, endDateTime))
.map(transaction -> transaction.getAmount())
.reduce(BigDecimal.ZERO, BigDecimal::add);
//System.out.println("Sum: " + sum);
return isThresholdExceeded(sum, threshold);
}
private Boolean isThresholdExceeded (BigDecimal sum, BigDecimal threshold) {
return sum.compareTo(threshold) == 1;
}
private Boolean isTransactionDateBetweenStartAndEndDateTime(LocalDateTime dateTime, LocalDateTime startDateTime, LocalDateTime endDateTime) {
return startDateTime.compareTo(dateTime) <= 0 && endDateTime.compareTo(dateTime) >= 0;
}
}
| true |
d45043cda6c47a3ad6dcb0dce7ba6eccf86ac302 | Java | roxanafrunza/POO-2016 | /Tema 1 - Quadtree/src/quadtree/Rectangle.java | UTF-8 | 870 | 3.4375 | 3 | [] | no_license | package quadtree;
import java.util.Scanner;
public class Rectangle extends Figure {
double x1, x2;
double y1, y2;
double width;
double height;
/**
* Build a rectangle with parameters read from scanner
*
* @param s
* scanner used to read from the file
*/
public void read(Scanner s) {
x1 = s.nextDouble();
y1 = s.nextDouble();
x2 = s.nextDouble();
y2 = s.nextDouble();
}
/**
* Calculate width and height using coordinates
*/
public void getDimensions() {
width = Math.abs(x1 - x2);
height = Math.abs(y1 - y2);
}
@Override
public void getFrameCoordinates() {
super.x1 = x1;
super.x2 = x2;
super.y1 = y1;
super.y2 = y2;
}
@Override
public boolean contains(double x, double y) {
return ((x >= this.x1 && x <= this.x2) && (y >= this.y1 && y <= this.y2));
}
}
| true |
d0cd01566728b5c66e8b6128ca235e945ac2da47 | Java | gtmbanerjee1/testusracct | /usracct/usracctService/src/test/java/com/ebay/app/raptor/usracct/govtIssuedIds/processor/DualUpdateProcessorTest.java | UTF-8 | 3,771 | 2.171875 | 2 | [] | no_license | package com.ebay.app.raptor.usracct.govtIssuedIds.processor;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import com.ebay.app.raptor.usracct.govtIssuedIds.exception.ApplicationException;
import com.ebay.app.raptor.usracct.govtIssuedIds.exception.DataNotFoundException;
import com.ebay.app.raptor.usracct.govtIssuedIds.exception.InvalidDataInputException;
import com.ebay.app.raptor.usracct.govtIssuedIds.helpers.DBHelper;
import com.ebay.app.raptor.usracct.govtIssuedIds.requests.ExternalEntityIdDeleteRequest;
import com.ebay.app.raptor.usracct.govtIssuedIds.requests.ExternalEntityIdRequest;
import com.ebay.app.raptor.usracct.govtIssuedIds.testUtils.TestDataBuilder;
public class DualUpdateProcessorTest {
@InjectMocks DualUpdateProcessor dualUpdateProcessor;
@Mock DBHelper mockDbHelper;
TestDataBuilder builder = new TestDataBuilder();
@Before
public void init() {
dualUpdateProcessor = new DualUpdateProcessor(mockDbHelper);
MockitoAnnotations.initMocks(this);
}
@Test
public void testProcessStore() throws ApplicationException {
long userId = 123;
long identityId = 123;
int countryCode = 724;
String identityIdType = "USER";
String eeiidCategory = "TAX_ID";
String eeiidType = "";
String eeiid = "12345678G";
ExternalEntityIdRequest request = builder.buildSaveRequest(userId, identityId, identityIdType, countryCode, eeiidCategory,
eeiidType, eeiid);
// when
Mockito.doNothing().when(mockDbHelper).saveOrUpdate(userId, identityId, identityIdType,
countryCode, eeiidCategory, eeiidType, eeiid, "");
// actual call
String actual = dualUpdateProcessor.processStore(request);
assertEquals("DNI", actual);
}
@Test(expected = InvalidDataInputException.class)
public void testProcessStoreThrowsDataInputException() throws ApplicationException {
long userId = 123;
long identityId = 123;
int countryCode = 724;
String identityIdType = "";
String eeiidCategory = "TAX_ID_INVALID";
String eeiidType = "";
String eeiid = "12345678G";
ExternalEntityIdRequest request = builder.buildSaveRequest(userId, identityId, identityIdType, countryCode, eeiidCategory,
eeiidType, eeiid);
// actual call
dualUpdateProcessor.processStore(request);
verify(mockDbHelper, never());
}
@Test
public void testProcessDelete() throws DataNotFoundException, ApplicationException {
long userId = 123;
long identityId = 123;
String identityType = "USER";
int countryCode = 724;
String eeiidCategory = "TAX_ID";
String eeiidType = "DNI";
ExternalEntityIdDeleteRequest request = builder.buildDeleteRequest(userId, identityId, identityType, countryCode, eeiidCategory, eeiidType);
// when
Mockito.doNothing().when(mockDbHelper).delete(userId, identityId, identityType, countryCode, eeiidCategory, eeiidType);
// actual
dualUpdateProcessor.processDelete(request);
//verify(mockDbHelper, times(1));
}
@Test(expected = InvalidDataInputException.class)
public void testProcessDeleteThrowsDataInputException() throws DataNotFoundException, ApplicationException {
long userId = 123;
long identityId = 123;
String identityType = "INVALID_USER_TYPE";
int countryCode = 724;
String eeiidCategory = "TAX_ID";
String eeiidType = "DNI";
ExternalEntityIdDeleteRequest request = builder.buildDeleteRequest(userId, identityId, identityType, countryCode, eeiidCategory, eeiidType);
// actual call
dualUpdateProcessor.processDelete(request);
//verify(mockDbHelper, never());
}
}
| true |
53048f69f23062c6c4d3ce8c5ae995f19654f90c | Java | Heilaogou/yiyuan | /src/main/java/com/itgaoshu/yiyuan/service/impl/PayServiceImpl.java | UTF-8 | 1,004 | 1.90625 | 2 | [] | no_license | package com.itgaoshu.yiyuan.service.impl;
import com.itgaoshu.yiyuan.bean.Lrecord;
import com.itgaoshu.yiyuan.bean.Pay;
import com.itgaoshu.yiyuan.bean.Register;
import com.itgaoshu.yiyuan.mapper.PayMapper;
import com.itgaoshu.yiyuan.service.PayService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
@Service
@Transactional
public class PayServiceImpl implements PayService {
@Resource
private PayMapper payMapper;
@Override
public int updPay(Register register) {
return payMapper.updPay(register);
}
@Override
public int addPay(Register register) {
return payMapper.addPay(register);
}
@Override
public List<Pay> selPays(Register register) {
return payMapper.selPays(register);
}
@Override
public List<Lrecord> selSurplus(Lrecord lrecord) {
return payMapper.selSurplus(lrecord);
}
}
| true |
a2e3a9e32ca0c9809c83755322912bc9109e7eac | Java | zhongxingyu/Seer | /Diff-Raw-Data/19/19_6de7d5adf17a22452ad92d699163105b3274ee79/BatteryIntentService/19_6de7d5adf17a22452ad92d699163105b3274ee79_BatteryIntentService_s.java | UTF-8 | 3,554 | 2.171875 | 2 | [] | no_license | package com.example.wsn03;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
public class BatteryIntentService extends IntentService {
private String THIS = "BatteryIntenService";
// ctor
public BatteryIntentService(){
super( "BatteryIntentService" );
Log.d( MainActivity.TAG, THIS + "::ctor");
}
// at least for debugging commonunication
private Messenger messenger;
// the battery Intent listener
private BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent){
Log.d(MainActivity.TAG, THIS + "::BroadcastReceiver::onReceive()" );
// TODO check, what is this?
context.unregisterReceiver( this );
// int status = intent.getIntExtra( BatteryManager.EXTRA_STATUS, -1);
// boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
// is plugged
int chargePlug = intent.getIntExtra( BatteryManager.EXTRA_PLUGGED, -1);
// charging via USB
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
// charging via AC
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
// TODO figure out
// boolean wifiCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_WIRELESS;
// evaluation
boolean isCharging = usbCharge || acCharge;
int rawLevel = intent.getIntExtra( BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra( BatteryManager.EXTRA_SCALE, -1);
int level = -1;
if( (0 <= rawLevel) && (0 < scale) ){
level = (rawLevel * 100) / scale;
}
Message msg = Message.obtain();
Bundle data = new Bundle();
data.putString("result", String.valueOf( level ));
msg.setData( data );
try{
messenger.send( msg );
}catch( RemoteException re ){
re.printStackTrace();
}
// write level to the database
MainActivity.DB.batterySave( level, isCharging );
}
};
//*/
private Timer timer = new Timer();
// on Intent receive, a Messenger and BroadcastReceiver will be generated
// to parse the intent's battery information
@Override
protected void onHandleIntent(Intent intent) {
Log.d( MainActivity.TAG, THIS + "::onHandleIntent()" );
// apply the generated filter to finde battery flags
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver( batteryLevelReceiver, batteryLevelFilter );
messenger = (Messenger) intent.getExtras().get( "handler_battery" );
timer.schedule( new TimerTask(){
@Override
public void run(){
Message msg = Message.obtain();
Bundle data = new Bundle();
/* TODO: clean communication paths
// data.putString("result_battery", String.valueOf( System.currentTimeMillis() )); // XXX
data.putString("result_battery", String.valueOf( level )); // XXX
msg.setData( data );
try{
messenger.send(msg);
}catch(RemoteException re){
re.printStackTrace();
}
//*/
}
}, 100, 3000);
}
};
| true |
69068d13d195af40002f053eaf93380823d88f85 | Java | gabriie/bank | /src/modelLayer/Employee.java | UTF-8 | 1,200 | 2.65625 | 3 | [] | no_license | package modelLayer;
public class Employee extends Entity{
int idEmployee;
String nameEmployee;
boolean function;
String username;
String passwordEmployee;
public Employee(){
}
public Employee(int idEmployee,String nameEmployee,boolean function, String username, String passwordEmployee){
this.idEmployee=idEmployee;
this.nameEmployee=nameEmployee;
this.function=function;
this.username=username;
this.passwordEmployee=passwordEmployee;
}
public boolean isFunction() {
return function;
}
public void setFunction(boolean function) {
this.function = function;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPasswordEmployee() {
return passwordEmployee;
}
public void setPasswordEmployee(String passwordEmployee) {
this.passwordEmployee = passwordEmployee;
}
public int getIdEmployee() {
return idEmployee;
}
public void setIdEmployee(int idEmployee) {
this.idEmployee = idEmployee;
}
public String getNameEmployee() {
return nameEmployee;
}
public void setNameEmployee(String nameEmployee) {
this.nameEmployee = nameEmployee;
}
}
| true |
aecc610d53ddfb7faa4cb08e8371018d8ce8810f | Java | L154L1/juansProjects | /OCPPractice/Chapter10/src/Passquestion_q149/Test.java | UTF-8 | 2,602 | 3.453125 | 3 | [] | no_license | // Given the records from the STUDENT table:
// sid sname semail
// 111 James james@uni.com
// 112 Jane jane@uni.com
// 114 John john@uni.com
// Assume that the URL, username, and password are valid.
// What is the result?
// A. The STUDENT table is not updated and the program prints:114 : John : john@uni.com
// B. The STUDENT table is updated with the record:113 : Jannet : jannet@uni.comand the program
// prints:114 : John : john@uni.com
// C. The STUDENT table is updated with the record:113 : Jannet : jannet@uni.comand the program
// prints:113 : Jannet : jannet@uni.com
// D. A SQLException is thrown at run time.
// Answer: D
// Explanation :
// updateRow() - Updates the underlying database with the new contents of the current row of this ResultSet object. This method cannot be called when the cursor is on the insert row.
package Passquestion_q149;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
public static void main(String[] args) throws SQLException {
//createTable();
Connection con = DriverManager.getConnection("jdbc:derby:zoo");
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
st.execute("SELECT * FROM student");
ResultSet rs = st.getResultSet();
rs.absolute(3);
rs.moveToInsertRow();
rs.updateInt(1, 113);
rs.updateString(2, "Jannet");
rs.updateString(3, "jannet@uni.com");
rs.updateRow(); // java.sql.SQLException: Invalid cursor state - no current row.
rs.refreshRow();
System.out.println(rs.getInt(1) + " : " + rs.getString(2) + " : " + rs.getString(3));
}
static void createTable() throws SQLException {
String url = "jdbc:derby:zoo;create=true";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
// stmt.executeUpdate("DROP TABLE STUDENT");
stmt.executeUpdate("CREATE TABLE STUDENT ("
+ "sid INTEGER, "
+ "sname VARCHAR(255), "
+ "semail VARCHAR(255))");
stmt.executeUpdate("INSERT INTO STUDENT VALUES (111, 'James', 'james@uni.com')");
stmt.executeUpdate("INSERT INTO STUDENT VALUES (112, 'Jane', 'jane@uni.com')");
stmt.executeUpdate("INSERT INTO STUDENT VALUES (114, 'John', 'john@uni.com')");
// check created table
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while(rs.next()) System.out.println(rs.getInt(1) + " : " + rs.getString(2) + " : " + rs.getString(3));
}
}
}
| true |
15172da7ea7b5c424be27ffde02f578da69d5127 | Java | midoujia/alipay-sdk-java-all | /src/main/java/com/alipay/api/domain/AlipayBossFncAntbudgetConsumedamountBatchqueryModel.java | UTF-8 | 961 | 1.726563 | 2 | [
"Apache-2.0"
] | permissive | package com.alipay.api.domain;
import java.util.List;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
/**
* 根据bizUkId查询占用金额
*
* @author auto create
* @since 1.0, 2021-06-03 15:47:50
*/
public class AlipayBossFncAntbudgetConsumedamountBatchqueryModel extends AlipayObject {
private static final long serialVersionUID = 3779852157926736846L;
/**
* 业务活动唯一id集合
*/
@ApiListField("biz_uk_ids")
@ApiField("string")
private List<String> bizUkIds;
/**
* nameSpace
PURCHASE/PROMO/COMMISSION
*/
@ApiField("ns")
private String ns;
public List<String> getBizUkIds() {
return this.bizUkIds;
}
public void setBizUkIds(List<String> bizUkIds) {
this.bizUkIds = bizUkIds;
}
public String getNs() {
return this.ns;
}
public void setNs(String ns) {
this.ns = ns;
}
}
| true |
5489e7cd8ba61c779a8373fcd1888ec12c6fd25d | Java | kjs775/algorithm | /src/yahait/level2/MakeMinNumber.java | UTF-8 | 356 | 3.0625 | 3 | [] | no_license | package src.yahait.level2;
import java.util.Arrays;
//최솟값 만들기
public class MakeMinNumber {
public int solution(int []A, int []B)
{
Arrays.sort(A);
Arrays.sort(B);
int answer = 0;
for(int i=0, j=A.length-1; i<A.length; i++, j--){
answer += A[i] *B[j];
}
return answer;
}
}
| true |
95594c302e6c0952fc13adf60109547465e741c7 | Java | hongguangyan/sharding | /src/test/java/com/simple/payment/sharding/service/ShardingTamplateTest.java | UTF-8 | 12,729 | 1.742188 | 2 | [] | no_license | package com.simple.payment.sharding.service;
import com.simple.sharding.config.ShardingMapping;
import com.simple.sharding.dataSource.DynamicDataSource;
import com.simple.payment.sharding.entity.BankOrderEntity;
import com.simple.sharding.exception.ShardingException;
import com.simple.sharding.service.impl.ShardingTemplate;
import com.simple.sharding.service.impl.ShardingTransactionTemplate;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
/**
* Created by IntelliJ IDEA.
*
* @author:
* @since: 12-8-29 下午2:51
* @version: 1.0.0
*/
public class ShardingTamplateTest {
private Logger logger = Logger.getLogger(ShardingTamplateTest.class);
private String fieldValue = "ID, ORIGINAL_ID, EXT_REQ_SN, TRADE_DN, EXT_TRADE_DN, " +
" TRADE_TYPE, API_VERSION, MERCHANT_NO, TERMINAL_NO, SETTLE_MERCHANT_NO, NOTIFY_URL, BUSINESS_TYPE," +
"TRADE_AMOUNT, CURRENCY_TYPE, BANK_CARD_NO, CARD_EXPIRE_DATE, CVV, ID_CARD_TYPE, ID_CARD_NO," +
"CARD_HOLDER_NAME, KEY_VERSION, AUTHORIZE_NO, SPLIT_TYPE, SPLIT_INFO, TRADE_SOURCE, EXT_TRADE_REQ_TIME," +
" CREATE_TRADE_REQ_TIME, BACK_UP";
ApplicationContext applicationContext;
ShardingTemplate shardingTemplate;
DynamicDataSource dynamicDataSource;
ShardingTransactionTemplate transactionTemplate;
@Before
public void setUp() throws Exception {
applicationContext = new ClassPathXmlApplicationContext("classpath*:spring*//spring-sharding-shard.xml");
shardingTemplate = (ShardingTemplate) applicationContext.getBean("shardingTemplate");
transactionTemplate = (ShardingTransactionTemplate) applicationContext.getBean("shardingTransactionTemplate");
// System.out.println("shardingTemplate------------" + dynamicDataSource.getResolvedDataSources().size());
}
@Test
public void testAddByMyBatis() {
/* long beginTime = System.currentTimeMillis();
try {
BankOrderEntity entity = new BankOrderEntity();
int val =0;
for (int i = 1000; i < 1123; i++) {
java.util.Random r = new java.util.Random(i);
entity.setId(r.nextLong());
shardingTemplate.insertOrUpdateForMyBatis("BankOrderEntity.insert", "" + r.nextInt(), entity);
val++;
System.out.println("执行了多少次:" + val);
}
} catch (ShardingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
long endTime = System.currentTimeMillis();
System.out.println("使用时间:" + (endTime - beginTime) + "MS"); //大概42分钟 十万的数*/
//System.out.println("transactionTemplate="+transactionTemplate.getTransactionManager());
/* final MultiTransactionManager transactionManager = (MultiTransactionManager) applicationContext.getBean
("multiTransactionManager");
TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
System.out.println("transactionDefinition.getIsolationLevel()=" + transactionDefinition.getIsolationLevel());
System.out.println("transactionDefinition.getPropagationBehavior()=" + transactionDefinition.getPropagationBehavior());
System.out.println("transactionDefinition.getTimeout()=" + transactionDefinition.getTimeout());
final TransactionStatus status = transactionManager.getTransaction(transactionDefinition);*/
/* System.out.println("transactionManager=" + transactionManager);
final MultiTransactionStatus status = (MultiTransactionStatus) applicationContext.getBean
("multiTransactionStatus");
System.out.println("status=" + status);*/
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
BankOrderEntity entity = new BankOrderEntity();
entity.setId(System.currentTimeMillis());
//更新银行订单表
try {
shardingTemplate.insertOrUpdateForMyBatis("BankOrderEntity.insert", "" + 9999999 , entity);
shardingTemplate.insertOrUpdateForMyBatis("BankOrderEntity.insert", "" , entity);
//更新支付表
// System.out.println("dsadasdadasdssssssss============================================");
// ContextHolder.setContext(String.valueOf(2));
shardingTemplate.insertOrUpdateForMyBatis("BankOrderEntity.insert", "" + 0000000 , entity);
// transactionManager.commit(status);
System.out.println("_________________________________________________________");
} catch (ShardingException e) {
// throw new RuntimeException(e);
//e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}catch (Exception e) {
//transactionManager.rollback(status);
//throw new RuntimeException(e); //To change body of catch statement use File | Settings | File
// Templates.
}finally {
//transactionManager.commit(status);
}
}
});
}
public void testAddBySQL() {
//java.util.Random r = new java.util.Random(12 * 138);
/* long beginTime = System.currentTimeMillis();
for (int i = 1000; i < 1010; i++) { //总共会执行4000次 用时:369710MS (第二次357731MS) 大概是:6.1619分钟 大概每条写的时间:92.4275MS
// mypayment库的总数 =1286 mypayment_shard1库的总数=1417 mypayment_shard2库的总数=1297
System.out.println("------------String.valueOf(i)=" + String.valueOf(i).getBytes().length);
java.util.Random r = new java.util.Random(i);
System.out.println("------------r.nextInt()=" + r.nextInt());
System.out.println("------------r.nextInt()=" + r.nextLong());
try {
shardingTemplate.insertOrUpdateForSQL("insert into TBL_TRADE_REQUEST (ID, ORIGINAL_ID, EXT_REQ_SN, TRADE_DN, EXT_TRADE_DN, " +
" TRADE_TYPE, API_VERSION, MERCHANT_NO, TERMINAL_NO, SETTLE_MERCHANT_NO, NOTIFY_URL, BUSINESS_TYPE, " +
"TRADE_AMOUNT, CURRENCY_TYPE, BANK_CARD_NO, CARD_EXPIRE_DATE, CVV, ID_CARD_TYPE, ID_CARD_NO," +
"CARD_HOLDER_NAME, KEY_VERSION, AUTHORIZE_NO, SPLIT_TYPE, SPLIT_INFO, TRADE_SOURCE, EXT_TRADE_REQ_TIME," +
"CREATE_TRADE_REQ_TIME, BACK_UP) values (" + r.nextLong() + ", 1345727225493, '123123213123', " +
"'12312312312', '1321313231', 1, '1.0v', '10000101','10101010', '123123123', " +
"'localhost', 1, 2.0000, 'CNY', '1233333333333333', '1234', '123', 1, " +
"'123123123123', 'yangkai', '12', '123123', 1, '123123', 1, sysdate, " +
"sysdate, '123')",
"" + r.nextInt());
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (ShardingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
long endTime = System.currentTimeMillis();
System.out.println("使用时间:" + (endTime - beginTime) + "MS"); //大概42分钟 十万的数据*/
}
/*
public void testQueryByMyBatis() {
long beginTime1 = System.currentTimeMillis();
List<Map> list1 = new ArrayList<Map>();
try {
*//*RequestEntity entity = new RequestEntity();*//*
list1 = (List<Map>) shardingTemplate.queryListForMyBatis("RequestDao.select", null);
//使用时间:14586MS
// 4000
// 每条查询的时间:3.6465
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (ShardingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
long endTime1 = System.currentTimeMillis();
System.out.println("使用时间:" + (endTime1 - beginTime1) + "MS"); //大概42分钟 十万的数据
System.out.println("list1.size():" + list1.size()); //大概42分钟 十万的数据
}
public void testQueryBySQL() {
long beginTime1 = System.currentTimeMillis();
List<Map> list1 = new ArrayList<Map>();
try {
list1 = (List<Map>) shardingTemplate.queryListForSQL("select " + fieldValue + " from TBL_TRADE_REQUEST");
//使用时间:14586MS
// 4000
// 每条查询的时间:3.6465
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (ShardingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
long endTime1 = System.currentTimeMillis();
System.out.println("使用时间:" + (endTime1 - beginTime1) + "MS"); //大概42分钟 十万的数据
System.out.println("list1.size():" + list1.size()); //大概42分钟 十万的数据
*//* for (int j = 0; j < list1.size(); j++) {
Map<String, Object> rowData = (Map<String, Object>) list1.get(j);
for (Map.Entry<String, Object> entry : rowData.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue() + "\t");
}
}*//*
}*/
/* @Test
public void MultiRequestsTest() {
// 构造一个Runner
TestRunnable runner = new TestRunnable() {
@Override
public void runTest() throws Throwable {
try {
// RequestEntity entity = new RequestEntity();
int j = 0;
for (int i = 1000; i < 1010; i++) {
java.util.Random r = new java.util.Random(i);
// entity.setId(r.nextLong());
j++;
System.out.println("执行了多少次:" + j);
shardingTemplate.insertOrUpdateForMyBatis("RequestDao.insert", "" + r.nextInt(), null);
}
} catch (ShardingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
};
int runnerCount = 100;
//Rnner数组,想当于并发多少个。
TestRunnable[] trs = new TestRunnable[runnerCount];
for (int i = 0; i < runnerCount; i++) {
trs[i] = runner;
}
// 用于执行多线程测试用例的Runner,将前面定义的单个Runner组成的数组传入
MultiThreadedTestRunner mttr = new MultiThreadedTestRunner(trs);
try {
long beginTime = System.currentTimeMillis();
// 开发并发执行数组里定义的内容
mttr.runTestRunnables();
long endTime1 = System.currentTimeMillis();
System.out.println("使用时间:" + (endTime1 - beginTime) + "MS"); //大概42分钟 十万的数据
} catch (Throwable e) {
e.printStackTrace();
}
}*/
private static int VIRTUAL_HOST_LENGTH = 100;
@Test
public void testDataSource() {
ShardingMapping shardingMapping = new ShardingMapping();
}
}
| true |
ff50a44e5cb3e54b1e34e536f352856b0fbd009c | Java | mysoft001/FastEnvelopes | /app/src/main/java/go/fast/fastenvelopes/info/UpgradeObj.java | UTF-8 | 327 | 1.84375 | 2 | [] | no_license | package go.fast.fastenvelopes.info;
public class UpgradeObj extends BaseInfo{
public boolean isEnd;// 是否已经完结
public String content;// 更新的内容
public int version;// 服务器上最新的版本号 如果小于那么提示更新
public int mustStartVersion;// 强制更新的开始版本
}
| true |
8efca1312a4c79d6b2768ca616b25eba3a8b0398 | Java | dongphuong0905/Hospital-Booking | /JV30_Project_Final/src/main/java/com/mycompany/jv30_project_final/entities/CalendarTimeEntity.java | UTF-8 | 1,603 | 2.40625 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.jv30_project_final.entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
*
* @author phuon
*/
@Entity
@Table(name = "calendar_time")
public class CalendarTimeEntity implements Serializable{
@Id
@Column(name = "ctId")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int ctId;
@ManyToOne
@JoinColumn(name = "calendar_id")
private CalendarEntity calendarTime;
private String time;
private int participant;
public CalendarTimeEntity() {
}
public int getId() {
return ctId;
}
public void setId(int id) {
this.ctId = id;
}
public CalendarEntity getCalendarTime() {
return calendarTime;
}
public void setCalendarTime(CalendarEntity calendarTime) {
this.calendarTime = calendarTime;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public int getParticipant() {
return participant;
}
public void setParticipant(int participant) {
this.participant = participant;
}
}
| true |
0fdc9fb8b017748e6744a2390c3d3323f67f3846 | Java | hridayjain21/journal_app | /app/src/main/java/com/example/journalapp/RecyclerViewAdapter.java | UTF-8 | 4,413 | 2.1875 | 2 | [] | no_license | package com.example.journalapp;
import android.content.Context;
import android.content.Intent;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import com.example.journalapp.model.Journal;
import com.example.journalapp.util.Journal_Api;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.squareup.picasso.Picasso;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Journal> journalList;
public RecyclerViewAdapter(Context context, List<Journal> journalList) {
this.context = context;
this.journalList = journalList;
}
@NonNull
@Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.journal_view,parent,false);
return new ViewHolder(view,context);
}
@Override
public void onBindViewHolder(@NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
String imageurl;
Journal journal = journalList.get(position);
holder.Title.setText(journal.getTitle());
holder.Thoughts.setText(journal.getThought());
holder.date.setText(journal.getThought());
holder.Title.setText(journal.getTitle());
imageurl = journal.getImageurl();
Picasso.get()
.load(imageurl)
.placeholder(R.drawable.background_secnic2)
.fit()
.into(holder.imageView);
String timeago = (String) DateUtils.getRelativeTimeSpanString(journal
.getTimeAdded().getSeconds() * 1000);
holder.date.setText(timeago);
holder.username.setText(journal.getUsername());
}
@Override
public int getItemCount() {
return journalList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private ImageView imageView;
private TextView Title;
private TextView Thoughts,date,timeadded,username;
private ImageButton share_button;
public ViewHolder(@NonNull View itemView,Context ctx) {
super(itemView);
context = ctx;
imageView = itemView.findViewById(R.id.journal_image_list);
Title = itemView.findViewById(R.id.journal_title_list);
Thoughts = itemView.findViewById(R.id.journal_thought_list);
date = itemView.findViewById(R.id.journal_timestamp_list);
username = itemView.findViewById(R.id.journal_row_username);
share_button = itemView.findViewById(R.id.journal_row_share_button);
share_button.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// Journal journal = journalList.get(getAdapterPosition());
String titleToShare = " ";
String thoughtToShare = " ";
String imgUrlToShare = " ";
for (int i = 0; i < journalList.size(); i++){
if (journalList.get(i).getTitle() == Title.getText()){
titleToShare = journalList.get(i).getTitle();
thoughtToShare = journalList.get(i).getThought();
imgUrlToShare = journalList.get(i).getImageurl();
i = journalList.size()+1;
}
}
String text = "Title : " + titleToShare + " \n " +
" Thought : " + thoughtToShare + "\n"
+ " Image : " + imgUrlToShare;
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT,"My Journal : ");
intent.putExtra(Intent.EXTRA_TEXT,text);
context.startActivity(intent);
}
}
}
| true |
05d3b3b92724d36b95734174f4ed35b0e4645862 | Java | osirvics/LatransClient | /app/src/main/java/com/example/victor/latrans/view/ui/message/MessageActivity.java | UTF-8 | 763 | 1.890625 | 2 | [] | no_license | package com.example.victor.latrans.view.ui.message;
import android.os.Bundle;
import com.example.victor.latrans.BaseActivity;
import com.example.victor.latrans.R;
public class MessageActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_message);
}
@Override
public int getContentViewId() {
return R.layout.activity_message;
}
@Override
public int getNavigationMenuItemId() {
return R.id.navigation_message;
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
}
| true |
053085274e583345f9d816c43f3fd970f606fe8f | Java | cocodrips/icfpc-2013 | /solver_java/src/piyopiyo/py/IcfpJsonTest.java | UTF-8 | 811 | 2.28125 | 2 | [] | no_license | package piyopiyo.py;
import static org.junit.Assert.*;
import static piyopiyo.py.IcfpJson.ICFPJSON;
import org.junit.Test;
public class IcfpJsonTest {
@Test
public void testEvalRequest() {
EvalRequest req = new EvalRequest("hoge", new long[] { 0, 1, -1 });
assertEquals("{\"arguments\":[\"0x0\",\"0x1\",\"0xFFFFFFFFFFFFFFFF\"]" +
",\"id\":\"hoge\"}", ICFPJSON.format(req));
}
@Test
public void testParseLong() {
String message = ("{\"status\":\"ok\",\"outputs\":" +
"[\"0x0\",\"0x1\",\"0xFFFFFFFFFFFFFFFF\"]}");
EvalResponse res = ICFPJSON.parse(message, EvalResponse.class);
assertEquals(EvalResponse.Status.ok, res.status);
assertArrayEquals(new long[] { 0, 1, -1 }, res.outputs);
}
}
| true |
6b32329567d6f8b9bd547ca7008364f2a27b8179 | Java | nicoleblumhorst/State-of-EmergenZ | /app/src/main/java/com/nicoleblumhorst/stateofemergenz/utils/Constants.java | UTF-8 | 377 | 1.726563 | 2 | [] | no_license | package com.nicoleblumhorst.stateofemergenz.utils;
/**
* Created by nicoleblumhorst on 1/24/16.
*/
public class Constants {
public static final String SEVERE = "SEVERE";
public static final String HIGH = "HIGH";
public static final String ELEVATED = "ELEVATED";
public static final String GUARDED = "GUARDED";
public static final String LOW = "LOW";
}
| true |
3ed9b6d142b0127ce4b9a104c17aa5697432bfc0 | Java | Caysen0038/StudentManagement | /src/main/java/com/baokaicong/sm/util/StringUtil.java | UTF-8 | 521 | 2.8125 | 3 | [
"MIT"
] | permissive | package com.baokaicong.sm.util;
import java.util.Random;
public class StringUtil {
public static String getRandomNumber(int len){
StringBuilder sb=new StringBuilder();
Random random=new Random();
while(len-->0){
sb.append(random.nextInt(10));
}
return sb.toString();
}
public static boolean isNotEmpty(String str){
return !isEmpty(str);
}
public static boolean isEmpty(String str){
return str==null || str.length()==0;
}
}
| true |
2a81442ee21177af0116934e7d2e32a0967a467a | Java | DaiSijie/custopoly | /src/ch/maystre/gilbert/custopoly/graphics/Toolbox.java | UTF-8 | 521 | 2.71875 | 3 | [] | no_license | /*
* Gilbert Maystre
* 14.04.18
*/
package ch.maystre.gilbert.custopoly.graphics;
public class Toolbox {
private Toolbox(){}
public static String formatAmount(int amount){
if(amount < 1000)
return "CHF " + amount;
int afterThousand = amount / 1000;
String beforeThousand = "" + (amount - afterThousand * 1000);
while(beforeThousand.length() < 3)
beforeThousand = "0" + beforeThousand;
return "CHF " + afterThousand + "'" + beforeThousand;
}
}
| true |
4e041c2e5907afeae49fb48ac4d47b45c632dc9a | Java | SwatiBeekle/DemoRepo | /Selenium/src/com/actiTime/windowhandles/Specifiedwindowhandlies.java | UTF-8 | 896 | 2.6875 | 3 | [] | no_license | package com.actiTime.windowhandles;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Specifiedwindowhandlies {
public static void main(String[] args) throws InterruptedException {
String expwin="Cognizant";
System.setProperty("webdriver.chrome.driver", "./Driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.naukri.com/");
Set<String> handler = driver.getWindowHandles();
System.out.println("total windows are: "+handler.size());
Iterator<String> itr = handler.iterator();
while(itr.hasNext()) {
String windows = itr.next();
driver.switchTo().window(windows);
System.out.println(driver.getTitle());
Thread.sleep(2000);
if(expwin.equals(windows)) {
driver.close();
}
}
}
} | true |
c9358663ded6333513d1ee8f97b37c8ca9b8911e | Java | awankbluez/ssp-sid | /src/main/java/com/vaia/sspsid/dao/TableInfoDAO1.java | UTF-8 | 1,777 | 2.21875 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.vaia.sspsid.dao;
import com.vaia.sspsid.entity.TableInfo;
import com.vaia.sspsid.util.DAOUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
/**
*
* @author Wirawan Adi <http://about.me/wirawan.adi>
*/
@Stateless
public class TableInfoDAO1 extends AbstractDAO {
private static final String SQL_RETRIEVE_ALL = "select * from t_informasi order by create_dt desc";
@PostConstruct
private void init() {
}
public List<TableInfo> getTableInfos() {
Connection connection = getConnection();
List<TableInfo> tableInfos = null;
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
try {
preparedStatement = DAOUtil.prepareStatement(connection, SQL_RETRIEVE_ALL);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
TableInfo e = new TableInfo();
e.setIf1(resultSet.getString("id_info"));
e.setIf2(resultSet.getString("desc_info"));
e.setIf3(resultSet.getString("create_dt"));
e.setIf4(resultSet.getString("update_dt"));
tableInfos.add(e);
}
} catch (SQLException e) {
} finally {
DAOUtil.close(connection, preparedStatement, resultSet);
}
return tableInfos;
}
}
| true |
469e7733692f53568499ffedd8b66d98ffa04b8d | Java | LovinPaul/CernobilZombie | /MPCoopServer/src/Game/MPFreeForAll.java | UTF-8 | 2,863 | 2.640625 | 3 | [] | no_license | package Game;
import Game.Actors.Hitman1;
import Game.Actors.Zombie1;
import Game.Actors.Actor;
import Game.Maps.*;
import Game.Network.Connection;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Iterator;
public class MPFreeForAll extends Game{
public MPFreeForAll() {
init();
// cursor = new MousePointer(me, this);
// cursor.setX(me.getX());
// cursor.setY(me.getY());
}
private void init(){
setMap(new UrbanDistrict9());
camera.setFreeCam(true);
}
@Override
public void getUserInput(){
super.getUserInput();
}
@Override
public void updateGameMechanics() {
super.updateGameMechanics();
// Connection.readAllTCP();
// Connection.readAllUDP();
if(camera!=null){camera.updateCoordonate();}
synchronized(actors){
// addZombie();
// addHitman1();
nrOfZombies=0;
nrOfHitmans=0;
Iterator<Actor> actorsIterator = actors.iterator();
while ( actorsIterator.hasNext() ) {
Actor actor = actorsIterator.next();
if(actor instanceof Zombie1){
nrOfZombies++;
}else if(actor instanceof Hitman1){
nrOfHitmans++;
}
if(actor.isAlive()){
// if(actor!=me && actor instanceof Zombie1){((Zombie1)actor).searchForPrey();}
// if(actor!=me && actor instanceof Hitman1){((Hitman1)actor).searchForVictim();}
actor.updateActorMechanics();
}else{
actorsIterator.remove();
}
}
}
// Connection.writeActorsAllUDP();
// if(!actors.isEmpty()){
// Connection.writeAllUDP();
// }
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics g2 = g.create();
for(Actor actor : actors){
if(actor.isHit()){
g2.setColor(Color.red);
g2.fillRect((int)(actor.getX()-camera.getX()), (int)(actor.getY()-camera.getY()-25), 100/2, 5);
g2.setColor(Color.green);
g2.fillRect((int)(actor.getX()-camera.getX()), (int)(actor.getY()-camera.getY()-25), (int)actor.getHitPoints()/2, 5);
}
}
// g2.setColor(Color.yellow);
// g2.fillRect(300, 90, conn.getLatencyUDP(), 20);
// g.drawString("Latency : " + conn.getLatencyUDP(), 300, 110);
// g2.fillRect(300, 110, conn.getBytesInUDP(), 20);
// g.drawString("BytesIn : " + conn.getBytesInUDP(), 300, 130);
// g.drawString("BytesOut : " + bytesOut, 300, 150);
}
}
| true |
889ae3e850d77009a941490f067720d65f9c5f99 | Java | cqr530/drugs | /src/main/java/com/lianxi/drugs/vo/CaiGouDanVo.java | UTF-8 | 1,421 | 1.8125 | 2 | [] | no_license | package com.lianxi.drugs.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data
public class CaiGouDanVo {
/*id*/
private Integer id;
/*医院编号*/
private String hospitalId;
/*医院名称*/
private String hospitalName;
private String examine;
/*采购单编号*/
private String payoffTabNum;
/*采购单名称*/
private String payoffTabName;
/*开始时间*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH-mm-ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date startTime;
/*结束时间*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH-mm-ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date endTime;
/*创建时间*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH-mm-ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date createTime;
/*提交时间*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH-mm-ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date inputTime;
/*审核时间*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH-mm-ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date examineTime;
/*采购单状态*/
private String payoffTabStatus;
}
| true |
d259874f3e01672d62ec149404744f762f1455c6 | Java | WonYong-Jang/algorithm | /src/com/company/cs/baek14620.java | UTF-8 | 2,520 | 2.9375 | 3 | [] | no_license | package com.company.cs;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
/**
* 꽃길
*/
public class baek14620 {
static int ans = 200 * 15 * 15;
static int[][] map = new int[11][11];
static int[][] visited = new int[11][11];
static int N;
static int[] dxArr = {1, -1, 0, 0}, dyArr = {0, 0, 1, -1};
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
for(int i=1; i<= N; i++)
{
st = new StringTokenizer(br.readLine());
for(int j=1; j<= N; j++)
{
map[i][j] = Integer.parseInt(st.nextToken());
}
}
for(int i=1; i<= N; i++)
{
for(int j=1; j<= N; j++)
{
if(!isRange(i,j)) continue;
int sum = map[i-1][j] + map[i][j-1] + map[i+1][j] +map[i][j+1] + map[i][j]; // 5 평 확인
visited[i][j] = 1;
visited[i-1][j] = 1;
visited[i][j-1] = 1;
visited[i+1][j] = 1;
visited[i][j+1] = 1;
solve(1, sum, i, j );
visited[i][j] = 0;
visited[i-1][j] = 0;
visited[i][j-1] = 0;
visited[i+1][j] = 0;
visited[i][j+1] = 0;
}
}
System.out.println(ans);
}
public static void solve(int cnt, int sum, int dx, int dy)
{
if(cnt == 3) {
ans = min(ans, sum);
return;
}
if(ans < sum) return; // 최소 비용 찾는 거니까
for(int i=dx; i<= N; i++)
{
for(int j=1; j<= N; j++)
{
if(!isRange(i,j)) continue;
int temp = map[i-1][j] + map[i][j-1] + map[i+1][j] +map[i][j+1] + map[i][j]; // 5 평 확인
visited[i][j] = 1;
visited[i-1][j] = 1;
visited[i][j-1] = 1;
visited[i+1][j] = 1;
visited[i][j+1] = 1;
solve(cnt+1, sum + temp, i, j );
visited[i][j] = 0;
visited[i-1][j] = 0;
visited[i][j-1] = 0;
visited[i+1][j] = 0;
visited[i][j+1] = 0;
}
}
}
public static boolean isRange(int dx, int dy)
{
if(visited[dx][dy] == 1) return false;
for(int i=0; i<4; i++)
{
int ndx = dx + dxArr[i];
int ndy = dy + dyArr[i];
if(ndx < 1 || ndy < 1 || ndx > N || ndy > N || visited[ndx][ndy] == 1 ) return false;
}
return true;
}
public static int min(int a, int b)
{
return a>b? b:a;
}
}
| true |
96023c6248b6086dd7ad8d49b98ed58396d2cda1 | Java | itmrchen/java8 | /src/main/java/com/javazx/jdk8/BinaryOperatorTest.java | UTF-8 | 804 | 3.328125 | 3 | [] | no_license | package com.javazx.jdk8;
import java.util.Comparator;
import java.util.function.BinaryOperator;
/**
* @author: itmrchen
* @Description:
* @date 2019/8/10 2:16
*/
public class BinaryOperatorTest {
public static void main(String[] args) {
BinaryOperatorTest binaryOperatorTest = new BinaryOperatorTest();
System.out.println(binaryOperatorTest.compute(1, 2, (a, b) -> a + b));
System.out.println(binaryOperatorTest.getShort("hello", "javazx", Comparator.comparingInt(String::length)));
}
public int compute(int a, int b, BinaryOperator<Integer> binaryOperator) {
return binaryOperator.apply(a, b);
}
public String getShort(String a, String b, Comparator<String> comparator) {
return BinaryOperator.minBy(comparator).apply(a, b);
}
}
| true |
9a764ea699c98ade256b70b432520cee21e3ad8a | Java | cherryvarsha99/FALL2020Exam | /src/question03/Comaprisions.java | UTF-8 | 3,047 | 3.734375 | 4 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package question03;
import java.awt.Rectangle;
/**
*
* @author Sai Varsha Vellanki
*/
public class Comaprisions {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Rectangle box1 = new Rectangle(10,20,10,10);
Rectangle box2 = new Rectangle(10,20,10,10);
Rectangle box3 = box1;
Rectangle box4;
// here we are comparing box1 object and box2 object since bothe refers to 2 different objects we get false
System.out.println(box1 == box2);
// we are comparing contents of box1 with box2 and since both object values are same we get true
System.out.println(box1.equals(box2));
// we are comparing box2 object with box3 and since both referes to different objects we get fasle
System.out.println(box2 == box3);
// we are comparing box 2 contents with box3 since box1 and 3 are same and has same values as box2 we get true
System.out.println(box2.equals(box3));
// we are comparing box1 object with box 3 both refers to same object hence we get true
System.out.println(box1==box3);
// we are creating new object refrence for box3
box3 = new Rectangle(10,20,10,10);
// comapring box1 object with box 3 now box3 refers to different object and we get false
System.out.println(box1==box3);
// comparing box1 values with box3 we get true since box 1 and box 3 values are same
System.out.println(box1.equals(box3));
String s1 = new String("Java");
String s2 = s1;
String s3 = new String(s2);
String s4 = "Java";
//comparing string reference here s1 and s2 refers same object hence we get true
System.out.println(s1 == s2);
//comapring s1 value with s2 since both refers to same object values are same and we get true
System.out.println(s1.equals(s2));
//comparing s1 object reference with s3 both refers to different objects we get false
System.out.println(s1 == s3);
// comparing s1 values with s3 and both values are same we get true
System.out.println(s1.equals(s3));
// comparing s1 object reference with s4 and here s4 not created with new it refers to s3 hence we get true
System.out.println(s1 == s4);
// comparing s1 value with s4 both are same hence we get true
System.out.println(s1.equals(s4));
//comparing s2 object reference with s3 both refers to different objects and we get false
System.out.println(s2 == s3);
// comparing s2 value with s3 and both are same hence we get true
System.out.println(s2.equals(s3));
//comapring s2 object reference with s4 bot are different and we get false
System.out.println(s2 == s4);
//comapring s2 values with s4 and both are same hence we get true
System.out.println(s2.equals(s4));
//comapring s3 object reference with s4 and both are different hence we get false
System.out.println(s3 == s4);
//comapring s3 values with s4 and both values are same hence we get true
System.out.println(s3.equals(s4));
}
}
| true |
f8786cb2f05be94eb4c4f1f547900fbc87cd39dc | Java | andrew9148435/acrm | /src/main/java/com/andrew/service/AttributeService.java | UTF-8 | 219 | 2 | 2 | [] | no_license | package com.andrew.service;
import com.andrew.domain.Attribute;
public interface AttributeService {
void add(String name);
void rename(Attribute attribute, String name);
boolean isExist(String name);
}
| true |
d3745b31420776de0ee52f517472946df912a145 | Java | tudorilisoi/mobilecenta | /src/main/java/com/unicenta/pos/util/ElapsedTimeBetweenDates.java | UTF-8 | 1,695 | 3.21875 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.unicenta.pos.util;
/**
*
* @author user
*/
import java.util.*;
import java.util.concurrent.TimeUnit;
public class ElapsedTimeBetweenDates {
public static void main(String []args) {
Date startDateTime = new Date(System.currentTimeMillis() - 123456789);
Date endDateTime = new Date();
Map<TimeUnit,Long> result = computeDiff(startDateTime, endDateTime);
System.out.println(result);
System.out.println("Days: " + result.get(TimeUnit.DAYS));
System.out.println("Hours: " + result.get(TimeUnit.HOURS));
System.out.println("Minutes: " + result.get(TimeUnit.MINUTES));
System.out.println("Seconds: " + result.get(TimeUnit.SECONDS));
System.out.println("MilliSeconds: " + result.get(TimeUnit.MILLISECONDS));
}
public static Map<TimeUnit,Long> computeDiff(Date date1, Date date2) {
long diffInMilliSeconds = date2.getTime() - date1.getTime();
List<TimeUnit> units = new ArrayList<>(EnumSet.allOf(TimeUnit.class));
Collections.reverse(units);
Map<TimeUnit,Long> result = new LinkedHashMap<>();
long milliSecondsRest = diffInMilliSeconds;
for (TimeUnit unit : units) {
long diff = unit.convert(milliSecondsRest,TimeUnit.MILLISECONDS);
long diffInMilliSecondsForUnit = unit.toMillis(diff);
milliSecondsRest = milliSecondsRest - diffInMilliSecondsForUnit;
result.put(unit,diff);
}
return result;
}
}
| true |
5a59a173dc78cca5a62acaee1837f3fd8bd2e77b | Java | rkosakov/PB-Java | /ConditionalStatementsAdvanced/src/TradeCommissions.java | UTF-8 | 2,248 | 3.25 | 3 | [] | no_license | import java.util.Scanner;
public class TradeCommissions {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String town = scan.nextLine();
double sales = Double.parseDouble(scan.nextLine());
double percent = 0.0;
//Град 0 ≤ s ≤ 500 500 < s ≤ 1 000 1 000 < s ≤ 10 000 s > 10 000
//Sofia 5% 7% 8% 12%
//Varna 4.5% 7.5% 10% 13%
//Plovdiv 5.5% 8% 12% 14.5%
if (town.equals("Sofia")) {
if (sales >= 0 && sales <= 500) {
percent = 0.05;
} else if (sales > 500 && sales <= 1000) {
percent = 0.07;
} else if (sales > 1000 && sales <= 10000) {
percent = 0.08;
} else if (sales > 10000) {
percent = 0.12;
} else {
System.out.println("error");
}
}
if (town.equals("Varna")) {
if (sales >= 0 && sales <= 500) {
percent = 0.045;
} else if (sales > 500 && sales <= 1000) {
percent = 0.075;
} else if (sales > 1000 && sales <= 10000) {
percent = 0.10;
} else if (sales > 10000) {
percent = 0.13;
} else {
System.out.println("error");
}
}
if (town.equals("Plovdiv")) {
if (sales >= 0 && sales <= 500) {
percent = 0.055;
} else if (sales > 500 && sales <= 1000) {
percent = 0.08;
} else if (sales > 1000 && sales <= 10000) {
percent = 0.12;
} else if (sales > 10000) {
percent = 0.145;
} else {
System.out.println("error");
}
}
else if (!(town.equals("Sofia") || town.equals("Varna") || town.equals("Plovdiv"))) {
System.out.println("error");
}
if ((town.equals("Sofia") || town.equals("Varna") || town.equals("Plovdiv")) && sales > 0)
System.out.printf("%.2f", sales * percent );
}
}
| true |
ca44bb59eaa1f0536102165ac65c77d204fc1dae | Java | Brian-Orina/Change-Language | /app/src/main/java/change/language/MainActivity.java | UTF-8 | 1,987 | 2.40625 | 2 | [
"MIT"
] | permissive | package change.language;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import change.language.Helper.LocaleHelper;
import io.paperdb.Paper;
public class MainActivity extends AppCompatActivity {
TextView mExample;
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(LocaleHelper.setLocale(newBase,"en"));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mExample = (TextView)findViewById(R.id.example);
// Init paper first
Paper.init(this);
// Default language is English
String language = Paper.book().read("language");
if (language == null){
Paper.book().write("language", "en");
updateView((String)Paper.book().read("language"));
}
}
private void updateView(String language) {
Context context = LocaleHelper.setLocale(this,language);
Resources resources = context.getResources();
mExample.setText(resources.getString(R.string.large_text));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.change_language, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.english) {
Paper.book().write("language", "en");
updateView((String)Paper.book().read("language"));
}
else if (item.getItemId() == R.id.swahili){
Paper.book().write("language", "sw");
updateView((String)Paper.book().read("language"));
}
return true;
}
}
| true |
6cf99c584558c6782f7a21cb54a795f07ab11a9d | Java | BingYanchi/present-for-best-TA | /src/main/java/bsh/BSHPackageDeclaration.java | UTF-8 | 463 | 2.03125 | 2 | [
"MIT"
] | permissive | package bsh;
public class BSHPackageDeclaration extends SimpleNode {
public BSHPackageDeclaration(int i) {
super(i);
}
public Object eval(CallStack callStack, Interpreter interpreter) {
BSHAmbiguousName bSHAmbiguousName = (BSHAmbiguousName) jjtGetChild(0);
NameSpace pVar = callStack.top();
pVar.mo863c(bSHAmbiguousName.text);
pVar.importPackage(bSHAmbiguousName.text);
return Primitive.VOID;
}
}
| true |
e76dac0e2b579a608bbdb1b32d01db39f4631eb4 | Java | anastasiawilliams/KarelDemocracy | /KarelDemocracy.java | UTF-8 | 1,110 | 3.28125 | 3 | [] | no_license | /* File: KarelDemocracy.java
* -------------------------
* In KarelDemocracy.java, Karel navigates a voting ballot, and
* ensures all unnecessary chads are removed.
*/
import stanford.karel.*;
public class KarelDemocracy extends SuperKarel {
public void run() {
move();
while (beepersPresent()) {
move();
move();
while (noBeepersPresent()) {
searchBallot();
}
}
}
private void searchBallot() { //Karel searches ballot for chads
checkForChads();
move();
move();
}
private void checkForChads() { //Karel checks for and removes extra unwanted chads
moveTop();
clearChads();
descend();
moveBottom();
clearChads();
ascend();
}
private void clearChads() { //Karel picks up unwanted chads
while (beepersPresent()) {
pickBeeper();
}
}
private void moveTop() {
turnLeft();
move();
}
private void descend() {
turnAround();
move();
turnLeft();
}
private void moveBottom() {
turnRight();
move();
}
private void ascend() {
turnAround();
move();
turnRight();
}
}
| true |
07951ed8546c9f1f0395fc1b95ba2b1f938aa365 | Java | 28yashverma/currencyConverter | /src/main/java/com/currency/convert/service/CurrencyRatesService.java | UTF-8 | 265 | 1.742188 | 2 | [] | no_license | package com.currency.convert.service;
import java.util.List;
import com.currency.convert.model.CurrencyRates;
/**
* @author yeshendra service
*
*/
public interface CurrencyRatesService {
void save(CurrencyRates rates);
List<CurrencyRates> findAll();
}
| true |
8f7f982da822c0c6237de2762c5ee19775cb7003 | Java | f3rry12/recyclerTest | /app/src/main/java/com/amamipro/recyclerpost/PostAdapter.java | UTF-8 | 2,160 | 2.34375 | 2 | [] | no_license | package com.amamipro.recyclerpost;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.List;
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
private List<PostModel> listPost;
private Activity activity;
private Context context;
public PostAdapter(Activity activity, List<PostModel> listPost, Context context) {
this.listPost = listPost;
this.activity = activity;
this.context = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_listpost,viewGroup,false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
viewHolder.judul.setText(listPost.get(i).getTitle());
viewHolder.isi.setText(listPost.get(i).getBody());
viewHolder.tombolkomen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(activity, CommentActivity.class)
.putExtra("postId", listPost.get(i).getId());
activity.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return listPost.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView judul;
private TextView isi;
private Button tombolkomen;
public ViewHolder(View itemView) {
super(itemView);
judul = itemView.findViewById(R.id.post_judul);
isi = itemView.findViewById(R.id.post_body);
tombolkomen = itemView.findViewById(R.id.see_comment);
}
}
}
| true |
1f794464113bbd9ff873ec08575317998d23b7a4 | Java | MICRORISC/iqrfsdk | /libs/simply/simply-iqrf-dpa-v22x/src/main/java/com/microrisc/simply/iqrf/dpa/v22x/init/BondedNodesConfiguration.java | UTF-8 | 3,013 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2014 MICRORISC s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microrisc.simply.iqrf.dpa.v22x.init;
/**
* Configuration of bonded nodes.
*
* @author Michal Konopa
*/
public class BondedNodesConfiguration {
/** Default value of number of attempts of getting bonded nodes from coordinator. */
public static int DEFAULT_GET_BONDED_NODES_ATTEMPTS_NUM = 3;
/** Default value of timeout [in ms] of operation of getting bonded nodes from coordinator. */
public static int DEFAULT_GET_BONDED_NODES_TIMEOUT = 5000;
/** Number of attempts of getting bonded nodes from coordinator. */
private int getBondedNodesAttemptsNum;
/** Timeout [in ms] of operation of getting bonded nodes from coordinator. */
private long getBondedNodesTimeout;
private int checkGetBondedNodesAttemptsNum(int getBondedNodesAttemptsNum) {
if (getBondedNodesAttemptsNum <= 0) {
throw new IllegalArgumentException(
"Value of number of attempts of getting bonded nodes from coordinator must be positive"
);
}
return getBondedNodesAttemptsNum;
}
private long checkGetBondedNodesTimeout(long getBondedNodesTimeout) {
if (getBondedNodesTimeout < 0) {
throw new IllegalArgumentException(
"Value of timeout [in ms] of operation of getting bonded nodes from coordinator must be nonnegative"
);
}
return getBondedNodesTimeout;
}
/**
* Creates new object of enumeration configuration.
* @param getBondedNodesAttemptsNum number of attempts of getting bonded nodes from coordinator
* @param getBondedNodesTimeout timeout [in ms] of operation of getting bonded nodes from coordinator
*/
public BondedNodesConfiguration(int getBondedNodesAttemptsNum,
long getBondedNodesTimeout
) {
this.getBondedNodesAttemptsNum = checkGetBondedNodesAttemptsNum(getBondedNodesAttemptsNum);
this.getBondedNodesTimeout = checkGetBondedNodesTimeout(getBondedNodesTimeout);
}
/**
* @return number of attempts of getting bonded nodes from coordinator
*/
public int getBondedNodesAttemptsNum() {
return getBondedNodesAttemptsNum;
}
/**
* @return timeout [in ms] of operation of getting bonded nodes from coordinator
*/
public long getBondedNodesTimeout() {
return getBondedNodesTimeout;
}
}
| true |
4fbe16419fc7678ead79d636d890311e61180ac0 | Java | RamanaKamadi/TrainingCode | /DemoProject/src/com/training/filter/Female.java | UTF-8 | 387 | 2.96875 | 3 | [] | no_license | package com.training.filter;
import java.util.ArrayList;
import java.util.List;
public class Female implements ICriteria{
@Override
public List<Person> meetCriteria(List<Person> persons){
List<Person> maleList=new ArrayList<Person>();
for(Person temp:persons) {
if(temp.getGender().equals("female")) {
maleList.add(temp);
}
}
return maleList;
}
}
| true |
bd75aa8ae28646b9cc93389912e31151f9e85ff2 | Java | edwardKatsCourse/java-23-exception-2-and-reflection-api | /src/com/company/reflection/Main.java | UTF-8 | 3,619 | 3.984375 | 4 | [] | no_license | package com.company.reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Person person = new Person();
Class clazz = Class.forName("com.company.reflection.Person");
//Class
//Field
//Method
System.out.println(Arrays.toString(clazz.getFields()));
System.out.println(Arrays.toString(clazz.getDeclaredFields()));
System.out.println("-------Get Declared fields --------");
printFields(clazz.getDeclaredFields());
System.out.println("-------Get fields --------");
printFields(clazz.getFields());
System.out.println("-------Get Methods---------");
printMethods(clazz.getMethods());
System.out.println("-------Get Declared Methods---------");
printMethods(clazz.getDeclaredMethods());
System.out.println("----- Simple Example -----");
simpleToStringCall();
System.out.println("----- Reflection Example -----");
nonSimpleExample();
}
public static void nonSimpleExample() throws IllegalAccessException, InstantiationException {
Class clazz = Person.class;
Object personObject = clazz.newInstance();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
if (field.getName().equals("name")) {
field.set(personObject, "Hello from Reflection API");
}
}
System.out.println(personObject.toString());
}
public static void simpleToStringCall() throws IllegalAccessException, InstantiationException {
//We should get Class object out of Person
//1. Person.class
//2.
//Person person = new Person();
//person.getClass();
//3.
//Class.forName("com.company.reflection.Person");
Person person = Person.class.newInstance();
// Person person = new Person();
person.setAge(35);
person.setName("Peter");
person.isResident = true;
person.spouse = new Person();
System.out.println(person.toString());
}
public static void printFields(Field[] fields) {
for (Field field : fields) {
String modifierName = Modifier.toString(field.getModifiers());
if (modifierName.isEmpty()) {
modifierName = "[default]";
}
System.out.printf("Modifier: %s | Type: %s | Name: %s%n",
modifierName,
field.getType()
.getName()
/*.getTypeName()*/
/*.getSimpleName()*/,
field.getName());
}
System.out.println("------------------------");
}
public static void printMethods(Method[] methods) {
for (Method method : methods) {
String modifierName = Modifier.toString(method.getModifiers());
if (modifierName.isEmpty()) {
modifierName = "[default]";
}
System.out.printf("Modifier: %s | Type: %s | Name: %s()%n",
modifierName,
method.getReturnType()
.getName()
/*.getTypeName()*/
/*.getSimpleName()*/,
method.getName());
}
System.out.println("------------------------");
}
}
| true |
312e1228915010b415226e6555e87b821fb0f72b | Java | kms2413/yodde_spring | /yodde_spring/src/main/java/com/yodde/storeAction/MainAjax.java | UTF-8 | 5,191 | 2.03125 | 2 | [] | no_license | package com.yodde.storeAction;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.yodde.pictureModel.PictureDao;
import com.yodde.pictureModel.PictureDto;
import com.yodde.reviewModel.Review;
import com.yodde.reviewModel.ReviewDao;
import com.yodde.storeModel.FollowReview;
import com.yodde.storeModel.FollowStore;
import com.yodde.storeModel.LikeDto;
import com.yodde.storeModel.StoreDao;
import com.yodde.storeModel.StoreDto;
@Component
@Controller
public class MainAjax {
@Autowired //해당 변수타입과 일치하는 빈을 찾아서 주입
private StoreDao storeDao;
@Autowired
private ReviewDao reviewDao;
@Autowired
private PictureDao pictureDao;
@RequestMapping(value = "MainAjax", method=RequestMethod.GET)
public ModelAndView newOpen(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView();
String email=request.getParameter("email");
String address = request.getParameter("address");
// System.out.println("address = " + address);
List<StoreDto> list = storeDao.selectStoreByAddress(address);
//System.out.println(email);
if(email != null){
StoreDto storeDto=new StoreDto();
List<StoreDto> newStoreList=null;
newStoreList=storeDao.selectNewOpen();
//System.out.println(storeList);
String[] openDay = new String[6];
// String openDate=null;
for(int i=0;i<newStoreList.size();i++){
storeDto=newStoreList.get(i);
Date from = new Date();
SimpleDateFormat transFormat = new SimpleDateFormat("yyyy-MM-dd");
String openDate = transFormat.format(storeDto.getOpenDate());
openDay[i]=openDate;
}
// for(int i=0;i<openDay.length;i++){
// System.out.println(openDay[i]);
// }
List<StoreDto> hotList=null;
hotList=storeDao.selectHotPlace();
List<LikeDto> likeList=null;
likeList=storeDao.selectLike();
List<FollowReview> followList=null;
followList=storeDao.selectFollowReview(email);
List<FollowStore> followStoreList=null;
followStoreList=storeDao.selectFollowStoreReview(email);
mav.addObject("openDay", openDay);
mav.addObject("newStoreList", newStoreList);
mav.addObject("hotplaceList", hotList);
mav.addObject("likeList", likeList);
mav.addObject("followReview", followList);
mav.addObject("followStoreList", followStoreList);
mav.addObject("storeList", list);
mav.setViewName("jsonView");
}else{
StoreDto storeDto=new StoreDto();
List<StoreDto> newStoreList=null;
newStoreList=storeDao.selectNewOpen();
//System.out.println(storeList);
String[] openDay = new String[6];
// String openDate=null;
for(int i=0;i<newStoreList.size();i++){
storeDto=newStoreList.get(i);
Date from = new Date();
SimpleDateFormat transFormat = new SimpleDateFormat("yyyy-MM-dd");
String openDate = transFormat.format(storeDto.getOpenDate());
openDay[i]=openDate;
}
// for(int i=0;i<openDay.length;i++){
// System.out.println(openDay[i]);
// }
List<StoreDto> hotList=null;
hotList=storeDao.selectHotPlace();
List<LikeDto> likeList=null;
likeList=storeDao.selectLike();
mav.addObject("openDay", openDay);
mav.addObject("newStoreList", newStoreList);
mav.addObject("hotplaceList", hotList);
mav.addObject("likeList", likeList);
mav.addObject("storeList", list);
mav.setViewName("jsonView");
}
return mav;
}
@RequestMapping(value = "AjaxStore", method=RequestMethod.GET)
public ModelAndView newStore(HttpServletRequest request,
HttpServletResponse response) throws Exception {
int storeId=Integer.parseInt(request.getParameter("storeId"));
//System.out.println(storeId);
StoreDto storeDto=new StoreDto();
storeDto=storeDao.selectStoreByStoreId(storeId);
List<Review> reviewList = null;
List<PictureDto> pictureList = null;
reviewList = reviewDao.getReviewsByStoreId(storeDto.getStoreId());
pictureList = pictureDao.select7Picture(storeDto.getStoreId());
ModelAndView mav = new ModelAndView();
mav.addObject(storeDto);
mav.addObject("reviewList", reviewList);
mav.addObject("pictureList", pictureList);
mav.setViewName("/store/storeInfo");
return mav;
}
} | true |
bcb836683d9049b4f13760b505767e2282745a0f | Java | VikrantHirapara/EngineeringAITest | /app/src/main/java/com/example/engineeringaitest/view/MainActivity.java | UTF-8 | 5,334 | 2.0625 | 2 | [] | no_license | package com.example.engineeringaitest.view;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.example.engineeringaitest.R;
import com.example.engineeringaitest.adapter.ItemAdapter;
import com.example.engineeringaitest.api.ApiService;
import com.example.engineeringaitest.api.RetrofitInstance;
import com.example.engineeringaitest.model.Item;
import com.example.engineeringaitest.model.ItemHits;
import com.example.engineeringaitest.util.PaginationListener;
import java.util.ArrayList;
import java.util.List;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.example.engineeringaitest.util.PaginationListener.PAGE_START;
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private static final String TAG = "MainActivity";
@BindView(R.id.lstItems)
RecyclerView lstItems;
@BindView(R.id.swipeRefresh)
SwipeRefreshLayout swipeRefresh;
private ItemAdapter adapter;
private int currentPage = PAGE_START;
private boolean isLastPage = false;
private int totalPage = 10;
private boolean isLoading = false;
int itemCount = 0;
static int selectCount = 0;
TextView notifCount;
private Context ctx = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
swipeRefresh.setOnRefreshListener(this);
lstItems.setHasFixedSize(true);
// use a linear layout manager
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
lstItems.setLayoutManager(layoutManager);
adapter = new ItemAdapter(ctx, new ArrayList<>(), () -> {
int count = 0;
for (int i = 0; i < adapter.getItems().size(); i++) {
if (adapter.getItems().get(i).isSelected()) {
count = count + 1;
}
}
setNotifCount(count);
});
lstItems.setAdapter(adapter);
doApiCall();
/**
* add scroll listener while user reach in bottom load more will call
*/
lstItems.addOnScrollListener(new PaginationListener(layoutManager) {
@Override
protected void loadMoreItems() {
isLoading = true;
currentPage++;
doApiCall();
}
@Override
public boolean isLastPage() {
return isLastPage;
}
@Override
public boolean isLoading() {
return isLoading;
}
});
}
@Override
public void onRefresh() {
itemCount = 0;
currentPage = PAGE_START;
isLastPage = false;
adapter.clear();
doApiCall();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
View count = menu.findItem(R.id.count).getActionView();
notifCount = (TextView) count.findViewById(R.id.notif_count);
notifCount.setText(String.valueOf(selectCount));
return super.onCreateOptionsMenu(menu);
}
/**
* do api call here to fetch data from server
* In example i'm adding data manually
*/
private void doApiCall() {
if (currentPage != PAGE_START) adapter.removeLoading();
// check weather is last page or not
if (totalPage != 0) {
adapter.addLoading();
apiCall(currentPage);
} else {
isLastPage = true;
}
isLoading = false;
}
private void apiCall(int page) {
ApiService service = RetrofitInstance.getRetrofitInstance().create(ApiService.class);
Call<ItemHits> call = service.itemHits(page, "story");
call.enqueue(new Callback<ItemHits>() {
@Override
public void onResponse(Call<ItemHits> call, Response<ItemHits> response) {
adapter.removeLoading();
swipeRefresh.setRefreshing(false);
if (response.body() != null) {
//currentPage = response.body().getPage() + 1;
totalPage = response.body().getNbPages();
adapter.addItems(response.body().getHits());
}
}
@Override
public void onFailure(Call<ItemHits> call, Throwable t) {
adapter.removeLoading();
Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});
}
private void setNotifCount(int count) {
selectCount = count;
invalidateOptionsMenu();
}
}
| true |
b90390a7e87349c1ccb84399275759fbd93f78c8 | Java | NGHui/ego-day06 | /ego/ego-parent/ego-manage/src/main/java/com/ego/manage/controller/TbContentController.java | UTF-8 | 2,054 | 2.265625 | 2 | [] | no_license | package com.ego.manage.controller;
import com.ego.commons.pojo.EasyUIDataGrid;
import com.ego.commons.pojo.EgoResult;
import com.ego.manage.service.TbContentService;
import com.ego.pojo.TbContent;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
/**
* @author 辉
* 座右铭:坚持总能遇见更好的自己!
* @date 2019/8/9
*/
@Controller
public class TbContentController {
@Resource
private TbContentService tbContentServiceImpl;
/**
* 显示内容信息
* @param categoryId
* @param page
* @param rows
* @return
*/
@RequestMapping("content/query/list")
@ResponseBody
public EasyUIDataGrid showContent(long categoryId,int page,int rows){
return tbContentServiceImpl.selContentByCategoryId(categoryId, page, rows);
}
/**
* 新增内容
* @param content
* @return
*/
@RequestMapping("content/save")
@ResponseBody
public EgoResult save(TbContent content){
EgoResult er = new EgoResult();
int index = tbContentServiceImpl.save(content);
if (index>0){
er.setStatus(200);
}
return er;
}
@RequestMapping("rest/content/edit")
@ResponseBody
public EgoResult edit(TbContent content){
EgoResult er = new EgoResult();
int index = tbContentServiceImpl.update(content);
if (index>0){
er.setStatus(200);
}
return er;
}
@RequestMapping("content/delete")
@ResponseBody
public EgoResult deletes(String ids) throws Exception {
EgoResult er = new EgoResult();
//判断是否进行删除,返回值为1,删除成功,返回值0,删除失败
int index = tbContentServiceImpl.deletes(ids);
if (index==1){
er.setStatus(200);
}
return er;
}
}
| true |
cc3eac48f21d23029a6825f1c65857ab4fafb33f | Java | xuzhu2017/land-management-assist | /land-management-assist/.history/src/main/java/com/xz/landmangementassist/utils/ServiceUtil_20210226164916.java | UTF-8 | 742 | 2.109375 | 2 | [] | no_license | package com.xz.landmanagementassist.utils;
import com.xz.landmanagementassist.domain.entity.admin.UserEntity;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
/**
* 服务层工具类
*
* @author xuzhu
* @date 2021-2-26 16:46:42
*/
public class ServiceUtil {
public static void passwordEncryption(UserEntity userEntity) {
// 默认生成 16 位盐
String salt = new SecureRandomNumberGenerator().nextBytes().toString();
String encodedPassword = new SimpleHash(algorithmName, userEntity.getPassword(), salt, hashIterations)
.toString();
userEntity.setSalt(salt);
userEntity.setPassword(encodedPassword);
}
}
| true |
c12baff271e7fb1f3e62c3f89be2ed2c85e18fff | Java | eddypastika/ETLDataMigration | /ETL_MIGRATION/src/main/java/com/eddypastika/migration/controller/DataMigrationController.java | UTF-8 | 2,227 | 2.15625 | 2 | [
"MIT"
] | permissive | package com.eddypastika.migration.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.eddypastika.migration.utility.LogWrapper;
@RestController
@RequestMapping("/ETLMigration")
public class DataMigrationController {
private static final Logger logger = new LogWrapper(LoggerFactory.getLogger(DataMigrationController.class));
@Autowired
private JobLauncher jobLauncher;
@Autowired
private Job extractJob;
@GetMapping("/extract")
public ResponseEntity<Void> acceptRequest(){
logger.debug("Test Run Migration with Spring!");
JobParametersBuilder jobParametersBuilder = new JobParametersBuilder();
jobParametersBuilder.addLong("Time", System.currentTimeMillis());
try {
jobLauncher.run(extractJob, jobParametersBuilder.toJobParameters());
} catch (JobExecutionAlreadyRunningException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JobRestartException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JobInstanceAlreadyCompleteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JobParametersInvalidException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
}
| true |
be0a7164d8e02555f4f70c5fd1e66bab51e9beb2 | Java | zhangshangfei/devfreemarkdemo | /src/main/java/com/zsf/freemark/devfreemarkdemo/test/TestController.java | UTF-8 | 402 | 1.734375 | 2 | [] | no_license | package com.zsf.freemark.devfreemarkdemo.test;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TestController {
@RequestMapping(value = "user")
public String test(ModelMap modelMap){
modelMap.addAttribute("data","123");
return "index";
}
}
| true |
29cfb61fd14418b64d7a3de0a05e2128cb98c1e3 | Java | drewhontz/InterviewProblems | /DataStructures/GraphNode.java | UTF-8 | 624 | 3.1875 | 3 | [] | no_license | import java.util.LinkedList;
public class GraphNode {
String name;
GraphNode[] adj;
boolean marked;
public GraphNode(String d){
this.name = d;
this.marked = false;
}
public void setAdjacent(GraphNode[] n){
this.adj = n;
}
public boolean isThereARouteFunc(GraphNode a){
LinkedList<GraphNode> q = new LinkedList<GraphNode>();
this.marked = true;
q.add(this);
while(!q.isEmpty()){
GraphNode c = q.removeFirst();
for (GraphNode gn : c.adj){
if (gn.marked == false){
gn.marked = true;
q.add(gn);
}
if (gn.name.equals(a.name)) return true;
}
}
return false;
}
}
| true |
efaa91d68fd09b250b8b0efbb643a77273469265 | Java | lealparkoour/proyectovehiculos | /src/proyectoalquilerdevehiculos/ControladorLogin/ControladorVehiculos.java | UTF-8 | 2,352 | 2.421875 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package proyectoalquilerdevehiculos.ControladorLogin;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import proyectoalquilerdevehiculos.clases.AbstractVehiculo;
import proyectoalquilerdevehiculos.clases.Coche;
import proyectoalquilerdevehiculos.clases.Furgoneta;
import proyectoalquilerdevehiculos.clases.LeerArchivoPlano;
import proyectoalquilerdevehiculos.clases.Moto;
/**
*
* @author Estudiante
*/
public class ControladorVehiculos implements Serializable{
private List<AbstractVehiculo> vehiculos;
public List<AbstractVehiculo> getVehiculos() {
return vehiculos;
}
public void setVehiculos(List<AbstractVehiculo> vehiculos) {
this.vehiculos = vehiculos;
}
public ControladorVehiculos() {
llenarvehiculos();
}
public void llenarvehiculos(){
vehiculos= new ArrayList<>();
LeerArchivoPlano.cargarCoches(vehiculos);
}
public List<AbstractVehiculo> obtenerVehiculos (String tipo)
{
List<AbstractVehiculo> listaTemp = new ArrayList<>();
for (AbstractVehiculo vehiculo : vehiculos) {
switch(tipo){
case "Coche":
if (vehiculo instanceof Coche){
listaTemp.add(vehiculo);
}
break;
case "Furgoneta":
if(vehiculo instanceof Furgoneta){
listaTemp.add(vehiculo);
}
break;
case "Moto":
if(vehiculo instanceof Moto){
listaTemp.add(vehiculo);
}
break;
}
}
return listaTemp;
}
}
| true |
844c0b26c70b19b10f709cc33f4746faf930f4dc | Java | DarkFFang/marketmanageCloud | /common-client/src/main/java/com/fang/commonclient/controller/GoodInController.java | UTF-8 | 2,937 | 2.21875 | 2 | [] | no_license | package com.fang.commonclient.controller;
import com.fang.commonclient.annotation.CustomLog;
import com.fang.commonclient.entity.GoodIn;
import com.fang.commonclient.service.GoodInService;
import com.fang.commonclient.util.RespUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* 商品入库控制器
*
* @author fang
* @date 2020/12/14
*/
@RestController
public class GoodInController {
/**
* 商品入库服务
*/
@Autowired
GoodInService goodInService;
/**
* 商品入库列表
*
* @return {@link List<GoodIn>}
*/
@GetMapping("/goodin")
@PreAuthorize("hasAuthority('/goodin/**;GET')")
public List<GoodIn> findGoodInList() {
return goodInService.findGoodInList();
}
/**
* 添加新的商品入库
*
* @param goodIn 好
* @return {@link RespUtil}
*/
@PostMapping("/goodin")
@PreAuthorize("hasAuthority('/goodin/**;POST')")
@CustomLog(operation = "添加商品入库")
public RespUtil addNewGoodIn(GoodIn goodIn) {
if (goodInService.addNewGoodIn(goodIn) == 1) {
return RespUtil.success("添加成功!");
} else {
return RespUtil.error("添加失败!");
}
}
/**
* 通过id商品入库记录
*
* @param id id
* @return {@link RespUtil}
*/
@DeleteMapping("/goodin/{id}")
@PreAuthorize("hasAuthority('/goodin/**;DELETE')")
@CustomLog(operation = "删除商品入库")
public RespUtil deleteGoodInById(@PathVariable Integer id) {
if (goodInService.deleteGoodInById(id) == 1) {
return RespUtil.success("删除成功!");
} else {
return RespUtil.error("删除失败!");
}
}
/**
* 通过id更新商品入库
*
* @param goodIn 商品入库
* @return {@link RespUtil}
*/
@PutMapping("/goodin")
@PreAuthorize("hasAuthority('/goodin/**;PUT')")
@CustomLog(operation = "修改商品入库")
public RespUtil updateGoodInById(GoodIn goodIn) {
if (goodInService.updateGoodInById(goodIn) == 1) {
return RespUtil.success("修改成功!");
} else {
return RespUtil.error("修改失败!");
}
}
/**
* 绑定
*
* @param binder 绑定
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
}
| true |
3d8312a8750414bb87ce29c498cef6a35097f73b | Java | t0HiiBwn/CoolapkRelease | /sources/com/tencent/openqq/protocol/imsdk/msg_notify.java | UTF-8 | 1,386 | 1.640625 | 2 | [] | no_license | package com.tencent.openqq.protocol.imsdk;
import com.tencent.mobileqq.pb.ByteStringMicro;
import com.tencent.mobileqq.pb.MessageMicro;
import com.tencent.mobileqq.pb.PBBytesField;
import com.tencent.mobileqq.pb.PBField;
import com.tencent.openqq.protocol.imsdk.common;
public final class msg_notify {
public static final class ReqBody extends MessageMicro<ReqBody> {
public static final int BYTES_SESSION_DATA_FIELD_NUMBER = 1;
static final MessageMicro.FieldMap __fieldMap__ = MessageMicro.initFieldMap(new int[]{10}, new String[]{"bytes_session_data"}, new Object[]{ByteStringMicro.EMPTY}, ReqBody.class);
public final PBBytesField bytes_session_data = PBField.initBytes(ByteStringMicro.EMPTY);
}
public static final class RspBody extends MessageMicro<RspBody> {
public static final int BYTES_SESSION_DATA_FIELD_NUMBER = 2;
public static final int MSG_CMD_ERROR_CODE_FIELD_NUMBER = 1;
static final MessageMicro.FieldMap __fieldMap__ = MessageMicro.initFieldMap(new int[]{10, 18}, new String[]{"msg_cmd_error_code", "bytes_session_data"}, new Object[]{null, ByteStringMicro.EMPTY}, RspBody.class);
public final PBBytesField bytes_session_data = PBField.initBytes(ByteStringMicro.EMPTY);
public common.CmdErrorCode msg_cmd_error_code = new common.CmdErrorCode();
}
private msg_notify() {
}
}
| true |
00d93f3cf722c96d4d608e9ab5b68e4df78cbef4 | Java | atiwe/Android-Geographical-Application | /app/src/main/java/se/mau/ac8110/p2/ServerCommunication.java | UTF-8 | 10,881 | 2.4375 | 2 | [] | no_license | package se.mau.ac8110.p2;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import static android.content.ContentValues.TAG;
class ServerCommunication {
private DataInputStream dis;
private DataOutputStream dos;
private Socket socket;
private Controller controller;
private String ip;
private int port;
private String id;
private boolean sendingLocation;
ServerCommunication(Controller controller, String ip, int port) {
this.controller = controller;
this.ip = ip;
this.port = port;
Thread thread = new ServerListener();
thread.start();
}
private String registerGroup(String group, String member) {
String message;
JSONObject item = new JSONObject();
try {
item.put("type", "register");
item.put("group", group);
item.put("member", member);
} catch (JSONException e) {
e.printStackTrace();
}
message = item.toString();
return message;
}
private String unregisterGroup() {
String message;
JSONObject item = new JSONObject();
try {
item.put("type", "unregister");
item.put("ID", id);
} catch (JSONException e) {
e.printStackTrace();
}
message = item.toString();
return message;
}
private String currentGroups() {
String message;
JSONObject item = new JSONObject();
try {
item.put("type", "groups");
} catch (JSONException e) {
e.printStackTrace();
}
message = item.toString();
return message;
}
private String sendLocation(double longitude, double latitude) {
String message;
JSONObject item = new JSONObject();
try {
item.put("type", "location");
item.put("id", id);
item.put("longitude", "" + longitude);
item.put("latitude", "" + latitude);
} catch (JSONException e) {
e.printStackTrace();
}
message = item.toString();
return message;
}
private String groupMembers(String groupName) {
String message;
JSONObject item = new JSONObject();
try {
item.put("type", "members");
item.put("group", groupName);
} catch (JSONException e) {
e.printStackTrace();
}
message = item.toString();
return message;
}
void disconnect() {
if (!socket.isClosed()) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
void getGroups() {
Thread thread = new RequestGroupsFromServer();
thread.start();
}
void registerGroupOnServer(String group, String name) {
Thread thread = new RegisterGroupThread();
((RegisterGroupThread) thread).setStrings(group, name);
thread.start();
}
void unregisterGroupOnServer() {
Thread thread = new UnRegisterGroupThread();
thread.start();
}
void requestGroupInfo(String groupName) {
Thread thread = new RequestGroupInfoFromServer(groupName);
thread.start();
}
public class RequestGroupInfoFromServer extends Thread {
private String groupName;
RequestGroupInfoFromServer(String groupName) {
this.groupName = groupName;
}
public void run() {
try {
dos.writeUTF(groupMembers(groupName));
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class UnRegisterGroupThread extends Thread {
public void run() {
try {
dos.writeUTF(unregisterGroup());
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class RegisterGroupThread extends Thread {
String group;
String name;
void setStrings(String group, String name) {
this.group = group;
this.name = name;
}
public void run() {
try {
dos.writeUTF(registerGroup(group, name));
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class RequestGroupsFromServer extends Thread {
public void run() {
if (socket != null) {
try {
dos.writeUTF(currentGroups());
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class ServerListener extends Thread {
public void run() {
InputStream is = null;
try {
socket = new Socket(ip, port);
is = socket.getInputStream();
dis = new DataInputStream(is);
OutputStream os = socket.getOutputStream();
dos = new DataOutputStream(os);
readFromServer();
} catch (IOException e) {
e.printStackTrace();
}
}
private void readFromServer() {
while (!socket.isClosed()) {
try {
String message2 = dis.readUTF();
JSONObject jsonObject = new JSONObject(message2);
String type = jsonObject.getString("type");
Log.d(TAG, "Message from server, type: " + type);
switch (type) {
case "groups":
processJsonGroups(jsonObject);
break;
case "register":
processJsonRegister(jsonObject);
break;
case "unregister":
processJsonUnregister(jsonObject);
break;
case "locations":
processJsonLocations(jsonObject);
break;
case "location":
processJsonLocation(jsonObject);
break;
case "members":
processJsonMembers(jsonObject);
break;
case "exception":
controller.setServerError(jsonObject.toString());
break;
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
}
private void processJsonUnregister(JSONObject jsonObject) {
controller.showMessage(jsonObject.toString());
}
private void processJsonMembers(JSONObject jsonObject) {
try {
String groupName = jsonObject.getString("group");
JSONArray jsonArray = jsonObject.getJSONArray("members");
String[] members = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
String memberJson = jsonArray.getString(i);
JSONObject jsonObjectMember = new JSONObject(memberJson);
members[i] = jsonObjectMember.getString("member");
}
controller.setMembers(groupName, members);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void processJsonLocations(JSONObject jsonObject) {
try {
JSONArray jsonArray = jsonObject.getJSONArray("location");
MemberInfo[] memberInfo = new MemberInfo[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
String memberJson = jsonArray.getString(i);
JSONObject jsonObjectMember = new JSONObject(memberJson);
String memberName = jsonObjectMember.getString("member");
double memberLongitude = jsonObjectMember.getDouble("longitude");
double memberLatitude = jsonObjectMember.getDouble("latitude");
memberInfo[i] = new MemberInfo(memberName, memberLongitude, memberLatitude);
}
Log.d(TAG, "Locations from server: " + jsonObject.toString());
controller.setGroupLocations(memberInfo);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void processJsonLocation(final JSONObject jsonObject) {
Log.d(TAG, jsonObject.toString());
}
private void processJsonGroups(JSONObject jsonObject) {
try {
JSONArray jsonArray = jsonObject.getJSONArray("groups");
ArrayList<String> groupsArray = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
String test = jsonArray.getString(i);
JSONObject jsonObject1 = new JSONObject(test);
groupsArray.add(jsonObject1.getString("group"));
}
controller.setListView(groupsArray);
Log.d("ArrayList", "Setting ListView with: " + groupsArray.size() + " elements");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void processJsonRegister(JSONObject jsonObject) {
try {
id = jsonObject.getString("id");
sendingLocation = true;
Thread thread = new SendLocationThread();
thread.start();
} catch (JSONException e) {
e.printStackTrace();
}
}
void stopSendLocation() {
sendingLocation = false;
}
private class SendLocationThread extends Thread {
public void run() {
while (sendingLocation) {
double[] location = controller.getLocation();
try {
dos.writeUTF(sendLocation(location[0], location[1]));
dos.flush();
sleep(20000);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
| true |
fcc1f04e7345ded01c9abd52726b2158fedc9527 | Java | datarpita/MovieRecommender | /src/main/java/com/example/movieRecommender/MyJsonToPojo.java | UTF-8 | 2,845 | 2.296875 | 2 | [] | no_license | package com.example.movieRecommender;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import org.jsonschema2pojo.DefaultGenerationConfig;
import org.jsonschema2pojo.GenerationConfig;
import org.jsonschema2pojo.Jackson2Annotator;
import org.jsonschema2pojo.SchemaGenerator;
import org.jsonschema2pojo.SchemaMapper;
import org.jsonschema2pojo.SchemaStore;
import org.jsonschema2pojo.SourceType;
import org.jsonschema2pojo.rules.RuleFactory;
import com.sun.codemodel.JCodeModel;
public class MyJsonToPojo {
public static void main(String[] args) {
String packageName="com.example.movieRecommender.pojo";
/*File inputJson= new File("C:/Arpita_Datta/My Projects/Machine_Learning_projects/workspace_ML/MovieRecommender/src/main/java/com/example/movieRecommender"+
File.separator+"input.json"); */
/*File outputJson= new File("C:/Arpita_Datta/My Projects/Machine_Learning_projects/workspace_ML/MovieRecommender/src/main/java/com/example/movieRecommender"+
File.separator+"output.json");*/
File outputJson= new File("C:/Arpita_Datta/My_Projects/Machine_Learning_projects/workspace_ML/MovieRecommender/src/main/java/com/example/movieRecommender"+
File.separator+"input_recommend.json");
File outputPojoDirectory=new File("C:/Arpita_Datta/My_Projects/Machine_Learning_projects/workspace_ML/MovieRecommender/src/main/java/com/example/movieRecommender"+File.separator+"convertedPojo");
outputPojoDirectory.mkdirs();
try {
//new MyJsonToPojo().convert2JSON(inputJson.toURI().toURL(), outputPojoDirectory, packageName, inputJson.getName().replace(".json", ""));
new MyJsonToPojo().convert2JSON(outputJson.toURI().toURL(), outputPojoDirectory, packageName, outputJson.getName().replace(".json", ""));
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Encountered issue while converting to pojo: "+e.getMessage());
e.printStackTrace();
}
}
public void convert2JSON(URL inputJson, File outputPojoDirectory, String packageName, String className) throws IOException{
JCodeModel codeModel = new JCodeModel();
URL source = inputJson;
GenerationConfig config = new DefaultGenerationConfig() {
@Override
public boolean isGenerateBuilders() { // set config option by overriding method
return true;
}
public SourceType getSourceType(){
return SourceType.JSON;
}
};
SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
mapper.generate(codeModel, className, packageName, source);
codeModel.build(outputPojoDirectory);
}
}
| true |
b4fbbb8b3944fb154ca589a81c987bef5b9259c9 | Java | bitbrain/beansjam-2017 | /core/src/tv/rocketbeans/supermafiosi/ui/DialogBox.java | UTF-8 | 6,733 | 2.15625 | 2 | [
"Apache-2.0"
] | permissive | package tv.rocketbeans.supermafiosi.ui;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.NinePatch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.utils.Align;
import aurelienribon.tweenengine.BaseTween;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenCallback;
import aurelienribon.tweenengine.TweenEquations;
import aurelienribon.tweenengine.TweenManager;
import de.bitbrain.braingdx.assets.SharedAssetManager;
import de.bitbrain.braingdx.graphics.GraphicsFactory;
import de.bitbrain.braingdx.tweens.ActorTween;
import de.bitbrain.braingdx.tweens.SharedTweenManager;
import de.bitbrain.braingdx.tweens.ValueTween;
import de.bitbrain.braingdx.util.ValueProvider;
import tv.rocketbeans.supermafiosi.Colors;
import tv.rocketbeans.supermafiosi.assets.Asset;
import tv.rocketbeans.supermafiosi.core.Dialog;
import tv.rocketbeans.supermafiosi.core.DialogManager;
public class DialogBox extends Actor {
private static final float INNER_PADDING_Y = 40f;
private static final float MARGIN = 10f;
private static final float AVATAR_PADDING = -10f;
private static final float TITLE_PADDING = 20f;
private Dialog dialog;
private final DialogManager dialogManager;
private final TweenManager tweenManager = SharedTweenManager.getInstance();
private Label text;
private Label title;
private ValueProvider offsetProvider = new ValueProvider();
private ValueProvider avatarBouncing = new ValueProvider();
private boolean currentlyClosing;
private final NinePatch dialogBackground;
private final NinePatch titleBackground;
static {
Tween.registerAccessor(ValueProvider.class, new ValueTween());
}
public DialogBox(DialogManager dialogManager) {
this.dialogManager = dialogManager;
// Create a nice background so font is readable
Texture buttonNinePatchTexture = SharedAssetManager.getInstance().get(Asset.Textures.PANEL_9PATCH, Texture.class);
Texture labelNinePatchTexture = SharedAssetManager.getInstance().get(Asset.Textures.LABEL_9PATCH, Texture.class);
dialogBackground = GraphicsFactory.createNinePatch(buttonNinePatchTexture, 20, Colors.FOREGROUND);
titleBackground = GraphicsFactory.createNinePatch(labelNinePatchTexture, 15, Colors.FOREGROUND);
}
@Override
public void act(float delta) {
if (!currentlyClosing && (dialog == null || dialog != dialogManager.getCurrentDialog())) {
unsetDialog(dialog, new TweenCallback() {
@Override
public void onEvent(int arg0, BaseTween<?> arg1) {
setDialog(dialogManager.getCurrentDialog());
}
});
}
}
@Override
public float getX() {
return MARGIN;
}
@Override
public float getY() {
return MARGIN + offsetProvider.getValue();
}
@Override
public void draw(Batch batch, float parentAlpha) {
parentAlpha *= getColor().a;
if (title != null) {
title.setX(getTitleX());
title.setY(getTitleY());
titleBackground.getColor().a = title.getColor().a;
titleBackground.draw(batch, getTitleBackgroundX(), getTitleBackgroundY(), getTitleBackgroundWidth(), getTitleBackgroundHeight());
title.draw(batch, 1f);
}
if (dialog != null) {
dialogBackground.draw(batch, getX(), getY(), getWidth() - MARGIN * 2f, getHeight());
Sprite avatar = dialog.getPicture();
avatar.setPosition(getX() + AVATAR_PADDING + 20f, getY() + AVATAR_PADDING + avatarBouncing.getValue());
avatar.setSize(getHeight() - AVATAR_PADDING * 2f, getHeight() - AVATAR_PADDING * 2f);
dialog.getPicture().draw(batch, parentAlpha);
}
if (text != null) {
text.setPosition(getX() + getHeight() + 50f, getY() + getHeight() - text.getHeight() + - INNER_PADDING_Y);
text.draw(batch, parentAlpha);
}
}
private void unsetDialog(Dialog dialog, TweenCallback finishCallback) {
if (dialog != null) {
currentlyClosing = true;
Tween.to(text, ActorTween.ALPHA, 0.5f)
.target(0f)
.ease(TweenEquations.easeInCubic)
.start(tweenManager);
Tween.to(title, ActorTween.ALPHA, 0.5f)
.target(0f)
.ease(TweenEquations.easeInCubic)
.start(tweenManager);
Tween.to(this, ActorTween.ALPHA, 0.5f)
.delay(0.3f)
.target(0f)
.ease(TweenEquations.easeInCubic)
.start(tweenManager);
Tween.to(offsetProvider, ValueTween.VALUE, 0.5f)
.target(getFadeOutYPosition())
.ease(TweenEquations.easeInCubic)
.setCallbackTriggers(TweenCallback.COMPLETE)
.setCallback(finishCallback)
.start(tweenManager);
tweenManager.killTarget(avatarBouncing);
} else {
finishCallback.onEvent(0, null);
}
}
private void setDialog(Dialog dialog) {
currentlyClosing = false;
if (dialog != null) {
this.dialog = dialog;
this.text = new Label(dialog.getText(), Styles.LABEL_DIALOG);
this.title = new Label(dialog.getTitle(), Styles.LABEL_DIALOG_TITLE);
text.setColor(dialog.getColor());
text.setWrap(true);
text.setWidth(getWidth() - getHeight() - MARGIN * 2f - 50f);
text.setAlignment(Align.top | Align.left);
text.setHeight(getHeight() - MARGIN);
getColor().a = 0f;
Tween.to(this, ActorTween.ALPHA, 0.8f)
.delay(0.3f)
.target(1f)
.ease(TweenEquations.easeInCubic)
.start(tweenManager);
text.getColor().a = 0f;
Tween.to(text, ActorTween.ALPHA, 0.4f)
.delay(0.6f)
.target(1f)
.ease(TweenEquations.easeInCubic)
.start(tweenManager);
Tween.to(title, ActorTween.ALPHA, 0.6f)
.target(1f)
.ease(TweenEquations.easeInCubic)
.start(tweenManager);
offsetProvider.setValue(getFadeOutYPosition());
Tween.to(offsetProvider, ValueTween.VALUE, 0.5f)
.target(0f)
.ease(TweenEquations.easeInCubic)
.start(tweenManager);
avatarBouncing.setValue(0f);
Tween.to(avatarBouncing, ValueTween.VALUE, 0.5f)
.target(15f)
.ease(TweenEquations.easeInCubic)
.repeatYoyo(Tween.INFINITY, 0f)
.start(tweenManager);
}
}
private float getTitleBackgroundX() {
return title.getX() - TITLE_PADDING;
}
private float getTitleBackgroundY() {
return title.getY() - (TITLE_PADDING / 2f);
}
private float getTitleBackgroundWidth() {
return title.getPrefWidth() + TITLE_PADDING * 2f;
}
private float getTitleBackgroundHeight() {
return title.getPrefHeight() + (TITLE_PADDING / 2f) * 2f;
}
private float getTitleY() {
return getY() + getHeight() + (TITLE_PADDING / 2f) - 2f;
}
private float getTitleX() {
return getX() + TITLE_PADDING;
}
private float getFadeOutYPosition() {
return -getHeight() - MARGIN - TITLE_PADDING * 4f;
}
}
| true |
224111bb88a9cafc61061ee76469008aeda84eda | Java | PPFei5Zhou/QinZiTravel | /app/src/main/java/com/Entity/Sight.java | UTF-8 | 973 | 2.15625 | 2 | [] | no_license | package com.Entity;
import org.litepal.crud.DataSupport;
public class Sight extends DataSupport {
private int id;
private String sightname;
private double price;
private String sightaddress;
private String content;
public int getid() {
return id;
}
public void setid(int id) {
this.id = id;
}
public String getSightname() {
return sightname;
}
public void setSightname(String sightname) {
this.sightname = sightname;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getSightaddress() {
return sightaddress;
}
public void setSightaddress(String sightaddress) {
this.sightaddress = sightaddress;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
| true |
beb4246eb8091d046d3058350014332548b978ff | Java | wanlYang/esm | /src/main/java/com/wanl/entity/User.java | UTF-8 | 2,319 | 2.71875 | 3 | [] | no_license | package com.wanl.entity;
/**
* 用户实体
* @ClassName: User
* @Package:com.wanl.entity
* @author:YangBin
* @date:2019/2/21 17:16
* @version:V1.0
*/
public class User {
private String id;
private String username;
private String password;
private String phone;
private String email;
private String headImg;
private Integer age;
private String anonymousName;
public void setAnonymousName(String anonymousName) {
this.anonymousName = anonymousName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHeadImg() {
return headImg;
}
public void setHeadImg(String headImg) {
this.headImg = headImg;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
", email='" + email + '\'' +
", headImg='" + headImg + '\'' +
", age=" + age +
'}';
}
public String getAnonymousName(){
if(null==username){
return null;
}
if(username.length()<=1){
return "*";
}
if(username.length()==2){
return username.substring(0,1) +"*";
}
char[] cs =username.toCharArray();
for (int i = 1; i < cs.length-1; i++) {
cs[i]='*';
}
return new String(cs);
}
}
| true |
a219e4d413eecc24b4661dcf1b4e33a809d438cc | Java | MiriteJD/Meet2Eat-Sub01 | /app/src/main/java/com/example/dreher/meet2eat/HomeFragment.java | UTF-8 | 907 | 2.03125 | 2 | [] | no_license | package com.example.dreher.meet2eat;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
public class HomeFragment extends Fragment {
public static HomeFragment newInstance() {
HomeFragment fragment = new HomeFragment();
return fragment;
}
public HomeFragment() {
}
TextView htv;
ListView hlist;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_h, container, false);
hlist = (ListView) rootView.findViewById(R.id.listView2);
htv = (TextView) rootView.findViewById(R.id.textView2);
return rootView;
}
} | true |
e96d89465903ac7e813f3cdbd7cc60eb70cca4e1 | Java | praxitelisk/Java7-Multithreading-Review-Graduate-Thesis | /src/chapter3_Advanced_Thread_Synchronization/Producer.java | UTF-8 | 266 | 2.875 | 3 | [
"MIT"
] | permissive | package chapter3_Advanced_Thread_Synchronization;
public class Producer implements Runnable {
private Shelf shelf;
public Producer(Shelf shelf) {
this.shelf = shelf;
}
public void run() {
for (int i = 0; i < 10; i++) {
shelf.ShelfRefresh();
}
}
}
| true |
b8217ef7ec71b4872fe81ed720f757d34c5e9550 | Java | ahnaf22/Android_MusicPlayer | /app/src/main/java/com/aust/karigor/wave/ContrllerClass.java | UTF-8 | 290 | 1.648438 | 2 | [] | no_license | package com.aust.karigor.wave;
import android.content.Context;
import android.widget.MediaController;
/**
* Created by user on 7/24/2016.
*/
public class ContrllerClass extends MediaController {
public ContrllerClass(Context c){
super(c);
}
public void hide(){}
}
| true |
4b29e31eb25e8435ed6a76da7d2be90de334ad06 | Java | sgramajo/MMDS-Amazon-Reviews | /src/main/java/de/hpi/mmds/clustering/DIMSUM.java | UTF-8 | 3,332 | 1.976563 | 2 | [] | no_license | package de.hpi.mmds.clustering;
import de.hpi.mmds.nlp.Match;
import de.hpi.mmds.nlp.MergedVector;
import de.hpi.mmds.nlp.NGram;
import de.hpi.mmds.nlp.VectorWithWords;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.mllib.linalg.Vector;
import org.apache.spark.mllib.linalg.distributed.*;
import scala.Tuple2;
import java.io.Serializable;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class DIMSUM implements NGramClustering, Serializable {
public JavaRDD<MergedVector> resolveDuplicates(JavaPairRDD<Match, Integer> repartitionedVectorRDD,
Double threshold, JavaSparkContext context, Integer CPUS) {
JavaPairRDD<Tuple2<Match, Integer>, Long> repartitionedVectorRDD2 = repartitionedVectorRDD.zipWithIndex();
repartitionedVectorRDD2.cache();
JavaPairRDD<Long, Tuple2<Match, Integer>> swappedRepartitionedVectorRDD =
repartitionedVectorRDD2.mapToPair(Tuple2::swap);
JavaPairRDD<Vector, Long> indexedVectors = repartitionedVectorRDD2.mapToPair(
(Tuple2<Tuple2<Match, Integer>, Long> tuple) -> {
Match match = tuple._1()._1();
String feature = match.getTemplate().getFeature(match.getNGramm().taggedWords);
Vector vector = null;
for (VectorWithWords v : match.getVectors()) {
if (v.word.word().equals(feature)) {
vector = v.vector;
}
}
if (vector == null) vector = match.getVectors().get(0).vector;
return new Tuple2<>(vector, tuple._2());
});
JavaRDD<IndexedRow> rows = indexedVectors.map(tuple -> new IndexedRow(tuple._2(), tuple._1()));
IndexedRowMatrix mat = new IndexedRowMatrix(rows.rdd());
System.out.println("Transposing Matrix");
RowMatrix mat2 = transpose.transposeRowMatrix(mat);
System.out.println("computing similarities");
CoordinateMatrix coords = mat2.columnSimilarities(0.3);
JavaRDD<MatrixEntry> entries = coords.entries().toJavaRDD();
System.out.println("finished");
JavaPairRDD<Long, Long> asd = graphops.getConnectedComponents(entries.filter(
(matrixEntry) -> matrixEntry.value() > threshold).rdd()).mapToPair(
(Tuple2<Object, Object> tuple) -> new Tuple2<>(Long.parseLong(tuple._1().toString()),
Long.parseLong(tuple._2().toString())));
JavaPairRDD<Long, Match> h = asd.join(swappedRepartitionedVectorRDD).mapToPair(
(tuple) -> new Tuple2<>(tuple._2()._1(), tuple._2()._2()._1()));
JavaPairRDD<Long, Iterable<Match>> i2 = h.groupByKey();
return i2.map(value -> {
List<NGram> ngrams = new LinkedList<>();
value._2().iterator().forEachRemaining(it -> ngrams.add(it.getNGramm()));
Match mv = value._2().iterator().next();
return new MergedVector(mv.getVectors(), mv.template, ngrams, ngrams.size());
});
}
}
| true |
626c112c4c8050012a46ef12e74cd59abe4026e3 | Java | henrikforb/ProgArk | /core/src/com/mygdx/game/view/LoadingView.java | UTF-8 | 2,281 | 2.546875 | 3 | [] | no_license | package com.mygdx.game.view;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.mygdx.game.ImpossibleGravity;
import com.mygdx.game.controller.LoadingController;
/**
* View for loanding screen while waiting to connect with another player in multiplayer mode
* LoadingScreen can be displayed when a while-loop is true in another controller
*/
public class LoadingView extends SuperView{
protected LoadingController loadingController;
private Stage stage;
private Texture loadingBar;
private Image loadingBarImage;
public LoadingView(final LoadingController loadingController){
this.loadingController = loadingController;
this.loadingBar = new Texture("loadingBar.png");
this.loadingBarImage = new Image(loadingBar);
this.stage = new Stage(new ScreenViewport());
loadingBarImage.setSize((float) Gdx.graphics.getWidth() / 10 * 7, (float)Gdx.graphics.getHeight() / 2);
loadingBarImage.setPosition((float)Gdx.graphics.getWidth() / 2, (float)Gdx.graphics.getHeight() / 5 * 3, Align.center);
//startListeners();
}
@Override
public void show(){
}
/**
* Listeners for touch gestures and checkbox to notice input from the user
*/
@Override
public void startListeners() {
Gdx.input.setInputProcessor(stage);
stage.addActor(loadingBarImage);
}
@Override
protected void handleInput() {
}
@Override
public void update(float dt) {
handleInput();
}
@Override
public void render(SpriteBatch sb) {
sb.setProjectionMatrix(camera.combined);
sb.begin();
sb.draw(background.getBackground(), camera.position.x-(camera.viewportWidth/2), 0, ImpossibleGravity.WIDTH, ImpossibleGravity.HEIGHT);
sb.end();
stage.act();
stage.draw();
}
@Override
public void dispose() {
background.dispose();
loadingBar.dispose();
System.out.println("Loading View Disposed");
}
}
| true |
e57669c992579eba81336461f2b3a914dbf80e90 | Java | kingYuYun/codelab | /src/leetcode/keda/p4.java | UTF-8 | 757 | 2.9375 | 3 | [] | no_license | package leetcode.keda;
import java.util.Scanner;
public class p4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s=sc.nextLine();
int n=sc.nextInt();
char[] c=s.toCharArray();
String str=new String();
String s1=s.substring(n);
String s2=s.substring(0,n);
// str=s1+s2;
str=s2+s1;
System.out.println(str);
// if (n>=c.length){
// System.out.print(s);
// }else {
// for (int i = n; i < c.length; i++) {
// str += c[i];
// }
// for (int i = 0; i < n; i++) {
// str += c[i];
// }
// System.out.print(str);
// }
}
}
| true |
8e78fc6b8798e6a7542c95b4eadcfffabde244d8 | Java | dasfuu/Animexx-Android-App | /app/src/main/java/de/meisterfuu/animexx/events/EventSyncAdapter.java | UTF-8 | 675 | 1.765625 | 2 | [] | no_license | package de.meisterfuu.animexx.events;
import android.accounts.Account;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.SyncResult;
import android.os.Bundle;
public class EventSyncAdapter extends AbstractThreadedSyncAdapter {
public EventSyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
// TODO Auto-generated constructor stub
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
// TODO Auto-generated method stub
}
}
| true |
ba3fffc7204b6c7746bdad456a6db1cee348ba6a | Java | orok7/Patterns | /src/main/java/com/eins/learn/utils/dto/DtoUtils.java | UTF-8 | 6,530 | 2.4375 | 2 | [] | no_license | package com.eins.learn.utils.dto;
import com.eins.learn.utils.reflect.InstanceUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.SerializationUtils;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@Slf4j
public class DtoUtils {
private static final Class<?> DEFAULT_VALUE_APPLIED_TO = Void.class;
public static <T> T convertToDto(Class<T> dtoType, Object... entities) {
Map<Class<?>, Object> entitiesMap = prepareEntitiesMap(entities);
if (entitiesMap == null) {
log.warn("DTO {}.java wasn't created because entities list isn't unique or it's NULL.",
dtoType.getSimpleName());
return null;
}
T dto = InstanceUtils.newInstance(dtoType);
getAllFields(dtoType).forEach(fieldInitialization(dtoType, entitiesMap, dto));
return dto;
}
public static <T> T convertToEntity(Class<T> entityType, Object dto) {
T entity = InstanceUtils.newInstance(entityType);
if (entity == null) {
return null;
}
getFieldsByEntityType(entityType, dto).forEach(dtoField -> setEntityField(dto, dtoField, entity));
return entity;
}
private static <T> Consumer<Field> fieldInitialization(Class<T> dtoType, Map<Class<?>, Object> entitiesMap, T dto) {
return dtoField -> {
Class<?> appliedTo = getAppliedTo(dtoType, dtoField);
if (appliedTo.equals(DEFAULT_VALUE_APPLIED_TO)) {
log.warn("Field {} was skipped. @Relation.appliedTo needed for initialization.", dtoField.getName());
return;
}
Object entity = entitiesMap.get(appliedTo);
if (entity == null) {
log.warn("No present entity with annotated type {}.", appliedTo.getSimpleName());
} else {
setDtoField(dto, dtoField, entity);
}
};
}
private static void setDtoField(Object dto, Field dtoField, Object entity) {
Field entityField = getFoundField(dtoField, entity);
if (entityField == null) {
return;
}
copyField(dto, dtoField, entity, entityField);
}
private static void setEntityField(Object dto, Field dtoField, Object entity) {
Field entityField = getFoundField(dtoField, entity);
if (entityField == null) {
return;
}
copyField(entity, entityField, dto, dtoField);
}
private static Field getFoundField(Field dtoField, Object entity) {
String foundFieldName = getFoundFieldName(dtoField);
Class<?> entityClass = entity.getClass();
while (entityClass != null && !isFieldPresent(entityClass, foundFieldName)) {
entityClass = entityClass.getSuperclass();
}
if (entityClass != null) {
try {
return entityClass.getDeclaredField(foundFieldName);
} catch (NoSuchFieldException ignored) {
}
}
log.warn("Field '{}' not found in {} and in its superclasses.", foundFieldName, entity.getClass().getName());
return null;
}
private static boolean isFieldPresent(Class<?> type, String fieldName) {
return Arrays.stream(type.getDeclaredFields()).anyMatch(field -> field.getName().equals(fieldName));
}
private static void copyField(Object dest, Field destField, Object source, Field sourceField) {
try {
sourceField.setAccessible(true);
destField.setAccessible(true);
if (Serializable.class.isAssignableFrom(destField.getType())) {
destField.set(dest, cloneObjectUsingSerialization((Serializable) sourceField.get(source)));
} else {
destField.set(dest, sourceField.get(source));
}
} catch (IllegalAccessException e) {
log.warn("Access exception. {}", e.getMessage());
}
}
private static Object cloneObjectUsingSerialization(Serializable object) {
return SerializationUtils.deserialize(SerializationUtils.serialize(object));
}
private static String getFoundFieldName(Field dtoField) {
Relation annotation = dtoField.getAnnotation(Relation.class);
String fieldName = annotation != null ? annotation.fieldName() : "";
return !fieldName.isEmpty() ? fieldName : dtoField.getName();
}
private static Class<?> getAppliedTo(Class<?> dtoType, Field dtoField) {
Class<?> appliedToField = getAppliedToField(dtoField);
Class<?> appliedToClass = getAppliedToClass(dtoType);
if (appliedToField.equals(DEFAULT_VALUE_APPLIED_TO)) {
return appliedToClass;
}
return appliedToField;
}
private static Class<?> getAppliedToField(Field dtoField) {
return dtoField.isAnnotationPresent(Relation.class) ?
dtoField.getAnnotation(Relation.class).appliedTo() :
DEFAULT_VALUE_APPLIED_TO;
}
private static Class<?> getAppliedToClass(Class<?> dtoType) {
return dtoType.isAnnotationPresent(Dto.class) ?
dtoType.getAnnotation(Dto.class).appliedTo() :
DEFAULT_VALUE_APPLIED_TO;
}
private static List<Field> getAllFields(Class<?> dtoType) {
return Arrays.asList(dtoType.getDeclaredFields());
}
private static Map<Class<?>, Object> prepareEntitiesMap(Object... entities) {
if (entities == null || Arrays.stream(entities).map(Object::getClass).distinct().count() != entities.length) {
return null;
}
return Arrays.stream(entities).collect(Collectors.toMap(Object::getClass, Function.identity()));
}
private static List<Field> getFieldsByEntityType(Class<?> entityType, Object dto) {
return Arrays.stream(dto.getClass().getDeclaredFields()).filter(getFieldByEntityTypePredicate(entityType))
.collect(Collectors.toList());
}
private static Predicate<Field> getFieldByEntityTypePredicate(Class<?> entityType) {
return dtoField -> getAppliedToField(dtoField).equals(entityType)
|| getAppliedToField(dtoField).equals(DEFAULT_VALUE_APPLIED_TO) && getAppliedToClass(
dtoField.getDeclaringClass()).equals(entityType);
}
}
| true |
fae67b2c2ca7c21f33b602da6006da4e77a14f8b | Java | vasujain/flightServ | /src/main/java/Util/Constants.java | UTF-8 | 483 | 1.804688 | 2 | [] | no_license | package Util;
/**
* Created by vasujain on 4/29/17.
*/
public class Constants {
private static final String LOCAL_HOST = "http://localhost";
private static final String FLIGHT_SERVICE_PORT = "8000";
private static final String PROVIDER_SERVICE_PORT = "9000";
public static final String SERVICE_URL = LOCAL_HOST + ":" + FLIGHT_SERVICE_PORT + "/";
public static final String DATA_PROVIDER_SERVICE_URL = LOCAL_HOST + ":" + PROVIDER_SERVICE_PORT + "/scrapers/";
}
| true |