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 |
---|---|---|---|---|---|---|---|---|---|---|---|
400aa9c11c4f5624d7c19e70e90ee89fb568fd33
|
Java
|
Sushma-M/BasicSanity_27Aug
|
/services/TestingDB_SQL/src/com/basicsanity/testingdb_sql/UserDetails.java
|
UTF-8
| 3,466 | 2.046875 | 2 |
[] |
no_license
|
/*Copyright (c) 2018-2019 wavemaker.com All Rights Reserved.
This software is the confidential and proprietary information of wavemaker.com You shall not disclose such Confidential Information and shall use it only in accordance
with the terms of the source code license agreement you entered into with wavemaker.com*/
package com.basicsanity.testingdb_sql;
/*This is a Studio Managed File. DO NOT EDIT THIS FILE. Your changes may be reverted by Studio.*/
import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ForeignKey;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonProperty.Access;
/**
* UserDetails generated by WaveMaker Studio.
*/
@Entity
@Table(name = "`User Details`")
public class UserDetails implements Serializable {
private String userDataId;
private String userAddress;
private Integer users;
@JsonProperty(access = Access.READ_ONLY)
private byte[] userDisplayPic;
private Boolean isEmployee;
private Users usersByUsers;
@Id
@Column(name = "`UserData Id`", nullable = false, length = 255)
public String getUserDataId() {
return this.userDataId;
}
public void setUserDataId(String userDataId) {
this.userDataId = userDataId;
}
@Column(name = "`User Address`", nullable = false, length = 2147483647)
public String getUserAddress() {
return this.userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
@Column(name = "`Users`", nullable = true, scale = 0, precision = 10)
public Integer getUsers() {
return this.users;
}
public void setUsers(Integer users) {
this.users = users;
}
@Column(name = "`User Display Pic`", nullable = true)
public byte[] getUserDisplayPic() {
return this.userDisplayPic;
}
public void setUserDisplayPic(byte[] userDisplayPic) {
this.userDisplayPic = userDisplayPic;
}
@Column(name = "`Is Employee`", nullable = true)
public Boolean getIsEmployee() {
return this.isEmployee;
}
public void setIsEmployee(Boolean isEmployee) {
this.isEmployee = isEmployee;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "`Users`", referencedColumnName = "`Users`", insertable = false, updatable = false, foreignKey = @ForeignKey(name = "`FK_Users_TO_User_DetailsV6UrW`"))
@Fetch(FetchMode.JOIN)
public Users getUsersByUsers() {
return this.usersByUsers;
}
public void setUsersByUsers(Users usersByUsers) {
if(usersByUsers != null) {
this.users = usersByUsers.getUsers();
}
this.usersByUsers = usersByUsers;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof UserDetails)) return false;
final UserDetails userDetails = (UserDetails) o;
return Objects.equals(getUserDataId(), userDetails.getUserDataId());
}
@Override
public int hashCode() {
return Objects.hash(getUserDataId());
}
}
| true |
c8db8541c82bdded030889fb12f2fc6b89b7e26f
|
Java
|
PursueMxy/zhiqu
|
/zhiquwang/src/main/java/com/icarexm/zhiquwang/presenter/InviteAwardPresenter.java
|
UTF-8
| 1,025 | 2.109375 | 2 |
[] |
no_license
|
package com.icarexm.zhiquwang.presenter;
import com.google.gson.GsonBuilder;
import com.icarexm.zhiquwang.bean.SeeFundBean;
import com.icarexm.zhiquwang.contract.InviteAwardContract;
import com.icarexm.zhiquwang.contract.InviteAwardContract;
import com.icarexm.zhiquwang.model.InviteAwardModel;
public class InviteAwardPresenter implements InviteAwardContract.Presenter {
//获取提现列表
public InviteAwardContract.View mView;
public InviteAwardModel InviteAwardModel;
public InviteAwardPresenter(InviteAwardContract.View view){
this.mView=view;
InviteAwardModel=new InviteAwardModel();
}
public void GetSeeFund(String token,String type){
InviteAwardModel.PostSeeFund(this,token,type);
}
//数据返回
public void SetSeeFund(String content,String type){
SeeFundBean seeFundBean = new GsonBuilder().create().fromJson(content, SeeFundBean.class);
mView.Update(seeFundBean.getCode(), seeFundBean.getMsg(), seeFundBean.getData());
}
}
| true |
228d202f418cc39c56f2a745106eb557a50832b9
|
Java
|
VDSteven/tmt
|
/src/main/java/com/steven/tmt/repository/AuthorityRepository.java
|
UTF-8
| 286 | 1.742188 | 2 |
[] |
no_license
|
package com.steven.tmt.repository;
import com.steven.tmt.domain.Authority;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Spring Data JPA repository for the Authority entity.
*/
public interface AuthorityRepository extends JpaRepository<Authority, String> {
}
| true |
7d54dcf98075e138fbee0c025ccb28801680659d
|
Java
|
mhiver/ACO_MiniEditor
|
/src/fr/istic/aco/minieditor/v2/tests/MemCopyTest.java
|
UTF-8
| 643 | 2.03125 | 2 |
[
"MIT"
] |
permissive
|
/**
*
*/
package fr.istic.aco.minieditor.v2.tests;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import fr.istic.aco.minieditor.v2.MemCopy;
import fr.istic.aco.minieditor.v2.Memento;
/**
* @author Baptiste Tessiau
* @author Matthieu Hiver
* @version 1.1
*
*/
public class MemCopyTest {
private Memento memento;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
memento = new MemCopy();
}
/**
* Test method for {@link fr.istic.aco.minieditor.v2.MemCopy#getSavedState()}.
*/
@Test
public void testGetSavedState() {
assertNull(memento.getSavedState());
}
}
| true |
a8dba3b8c7a938d478888db15e44b17b9583af0e
|
Java
|
jtap60/com.estr
|
/src/com/estrongs/android/pop/utils/cv.java
|
UTF-8
| 3,276 | 1.992188 | 2 |
[] |
no_license
|
package com.estrongs.android.pop.utils;
import com.estrongs.android.util.bk;
import java.util.LinkedList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class cv
{
BlockingQueue<Runnable> a;
ThreadPoolExecutor b;
ct<dc> c = new ct(3);
Runnable d = new cx(this);
private LinkedList<LinkedList<cz>> e = new LinkedList();
private int f;
private int g = 0;
private int h = 0;
private boolean i = false;
private ct<db> j = new ct(3);
private da k = new cw(this);
public cv()
{
this(0, Runtime.getRuntime().availableProcessors(), 3);
}
public cv(int paramInt)
{
this(0, paramInt, 3);
}
public cv(int paramInt1, int paramInt2, int paramInt3)
{
a(paramInt1, paramInt2, paramInt3);
}
private cz a()
{
LinkedList localLinkedList = (LinkedList)e.getLast();
cz localcz = (cz)localLinkedList.poll();
if (localcz != null)
{
if ((localLinkedList.isEmpty()) && (e.size() > 1)) {
e.remove(localLinkedList);
}
return localcz;
}
if (e.size() > 1)
{
e.remove(localLinkedList);
return a();
}
return null;
}
private void a(db paramdb)
{
try
{
g -= 1;
j.a(paramdb);
if ((g < 0) || (g >= f)) {
g = 0;
}
if (g == 0) {
bk.a(d);
}
return;
}
finally {}
}
private cz b()
{
try
{
cz localcz = a();
if (localcz != null) {
h -= 1;
}
return localcz;
}
finally {}
}
private void c()
{
try
{
e();
return;
}
finally
{
localObject = finally;
throw ((Throwable)localObject);
}
}
private db d()
{
db localdb2 = (db)j.a();
db localdb1 = localdb2;
if (localdb2 == null) {
localdb1 = new db(this);
}
return localdb1;
}
private void e()
{
try
{
while ((g < f) && (h > 0))
{
g += 1;
Object localObject1 = null;
try
{
db localdb = d();
localObject1 = localdb;
b.execute(localdb);
}
catch (RejectedExecutionException localRejectedExecutionException)
{
a((db)localObject1);
}
}
}
finally {}
}
private dc f()
{
Object localObject;
if (c == null) {
localObject = null;
}
dc localdc;
do
{
return (dc)localObject;
localdc = (dc)c.a();
localObject = localdc;
} while (localdc != null);
return new dc(this, null);
}
void a(int paramInt1, int paramInt2, int paramInt3)
{
f = paramInt2;
e.add(new LinkedList());
a = new SynchronousQueue();
b = new ThreadPoolExecutor(paramInt1, f, 60L, TimeUnit.SECONDS, a, new cy(paramInt3));
}
public void a(cz paramcz)
{
try
{
((LinkedList)e.getLast()).add(paramcz);
h += 1;
c();
return;
}
finally {}
}
}
/* Location:
* Qualified Name: com.estrongs.android.pop.utils.cv
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| true |
f3da163acaf8dd919d1771a840267d463effd646
|
Java
|
zengbo0710/sharepointdemo
|
/Maintenance/java_src/com/maintenance/demo/vo/query/TbUserInfoQuery.java
|
UTF-8
| 2,282 | 1.953125 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Powered By [rapid-framework]
* Web Site: http://www.rapid-framework.org.cn
* Google Code: http://code.google.com/p/rapid-framework/
* Since 2008 - 2012
*/
package com.maintenance.demo.vo.query;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import java.io.Serializable;
import java.util.*;
import javacommon.base.*;
import javacommon.util.*;
import cn.org.rapid_framework.util.*;
import cn.org.rapid_framework.web.util.*;
import cn.org.rapid_framework.page.*;
import cn.org.rapid_framework.page.impl.*;
import com.maintenance.demo.model.*;
import com.maintenance.demo.dao.*;
import com.maintenance.demo.service.*;
import com.maintenance.demo.vo.query.*;
/**
* @author badqiu email:badqiu(a)gmail.com
* @version 1.0
* @since 1.0
*/
public class TbUserInfoQuery extends BaseQuery implements Serializable {
private static final long serialVersionUID = 3148176768559230877L;
/** id */
private java.lang.Integer id;
/** userName */
private java.lang.String userName;
/** password */
private java.lang.String password;
/** description */
private java.lang.String description;
/** role */
private java.lang.Integer role;
public java.lang.Integer getId() {
return this.id;
}
public void setId(java.lang.Integer value) {
this.id = value;
}
public java.lang.String getUserName() {
return this.userName;
}
public void setUserName(java.lang.String value) {
this.userName = value;
}
public java.lang.String getPassword() {
return this.password;
}
public void setPassword(java.lang.String value) {
this.password = value;
}
public java.lang.String getDescription() {
return this.description;
}
public void setDescription(java.lang.String value) {
this.description = value;
}
public java.lang.Integer getRole() {
return this.role;
}
public void setRole(java.lang.Integer value) {
this.role = value;
}
public String toString() {
return ToStringBuilder.reflectionToString(this,ToStringStyle.MULTI_LINE_STYLE);
}
}
| true |
74d5033198a17afedd0719e842d0ef4290181c38
|
Java
|
jchampemont/dependency_injection
|
/src/main/java/com/jeanchampemont/demo/dependency_injection/service/impl/StringJoinerServiceImpl.java
|
UTF-8
| 285 | 2.15625 | 2 |
[] |
no_license
|
package com.jeanchampemont.demo.dependency_injection.service.impl;
import com.jeanchampemont.demo.dependency_injection.service.StringJoinerService;
public class StringJoinerServiceImpl implements StringJoinerService {
public String join(String a, String b) {
return a + b;
}
}
| true |
ba76c0f20d4095079e6f4d1f9ae915d5565b7f59
|
Java
|
marijaciri/Java-CRUD-MySql
|
/PIT24/src/gui/JTableRacunar.java
|
UTF-8
| 1,811 | 2.734375 | 3 |
[] |
no_license
|
package gui;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import baza.DAO;
import domen.Racunar;
public class JTableRacunar extends AbstractTableModel{
ArrayList<Racunar> lista;
public JTableRacunar(ArrayList<Racunar> lista) {
this.lista = lista;
}
@Override
public int getColumnCount() {
return 4;
}
@Override
public int getRowCount() {
return lista.size();
}
@Override
public Object getValueAt(int r, int c) {
Racunar pom = lista.get(r);
switch (c) {
case 0:
return pom.getId_racunara();
case 1:
return pom.getVrsta();
case 2:
return pom.getCena();
case 3:
return pom.isNov();
default:
return "Greska!";
}
}
@Override
public String getColumnName(int c) {
switch (c) {
case 0:
return "ID racunara";
case 1:
return "Vrsta";
case 2:
return "Cena";
case 3:
return "Status";
default:
return "Greska!";
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:return false;
case 1:return true;
case 2:return true;
case 3:return false;
default:return false;
}
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
try{
Racunar pom = lista.get(rowIndex);
switch (columnIndex) {
case 1: pom.setVrsta(aValue.toString()); break;
case 2: pom.setCena(Integer.parseInt(aValue.toString())); break;
case 3: pom.setNov(Boolean.parseBoolean(aValue.toString()));
}
DAO dao = new DAO();
dao.updateRacunar(pom);
}catch (Exception e) {
JOptionPane.showMessageDialog(null, "Greska "+e.getMessage());
}
fireTableRowsUpdated(rowIndex, columnIndex);
}
public ArrayList<Racunar> getLista() {
return lista;
}
}
| true |
0a306b09e3637741b09f77de000cc41908491a85
|
Java
|
lionsola/deadlock
|
/src/editor/ToolBar.java
|
UTF-8
| 18,961 | 2.09375 | 2 |
[] |
no_license
|
package editor;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.ListCellRenderer;
import javax.swing.SwingConstants;
import client.graphics.Sprite;
import client.gui.GUIFactory;
import editor.dialogs.ListDialog;
import editor.dialogs.ParticleSourceDialog;
import editor.dialogs.SpawnDialog;
import editor.dialogs.TerrainDialog;
import editor.dialogs.ThingDialog;
import editor.dialogs.TileSwitchDialog;
import editor.tools.Tool;
import editor.tools.Tool.*;
import server.world.Thing;
import server.world.trigger.TileSwitchPreset;
import server.world.Terrain;
public class ToolBar extends JPanel {
private static final long serialVersionUID = 5669888117742429060L;
final Editor editor;
JToggleButton activeButton;
public ToolBar(final Editor editor) {
this.editor = editor;
this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
final JButton move = new JButton();
stylizeToolButton(move);
try {
move.setIcon(new ImageIcon(ImageIO.read(new File("resource/editor/hand.png"))));
} catch (IOException e1) {
move.setText("H");
}
move.setToolTipText("Hand Tool - drag to move map.");
move.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
editor.setTool(new MoveTool(editor.getArenaPanel()));
}});
this.add(move);
final JToggleButton tilePaint = new JToggleButton();
stylizeToolButton(tilePaint);
try {
tilePaint.setIcon(new ImageIcon(ImageIO.read(new File("resource/editor/terrain.png"))));
} catch (IOException e1) {
tilePaint.setText("Terrain");
}
tilePaint.setToolTipText("Terrain Paint - left to paint, right to remove");
tilePaint.addItemListener(new ItemListener() {
ListDialog<Terrain> list = null;
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange()==ItemEvent.SELECTED) {
if (list==null) {
final CustomListModel<Terrain> tlm = new CustomListModel<Terrain>(new ArrayList<Terrain>(editor.tileTable.values()));
JButton add = new JButton("Add");
JButton edit = new JButton("Edit");
JButton delete = new JButton("Delete");
JButton[] buttons = {edit,add,delete};
list = new ListDialog<Terrain>(editor, tilePaint, "Terrain", buttons, tlm);
list.getList().setCellRenderer(cellRenderer);
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
TerrainDialog dialog = new TerrainDialog(editor,null);
dialog.setVisible(true);
Terrain t = dialog.getTile();
if (t!=null) {
editor.getTerrainTable().put(t.getId(), t);
editor.tileDataChanged = true;
tlm.getList().add(t);
tlm.invalidate();
}
}
});
edit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
new TerrainDialog(editor,list.getList().getSelectedValue()).setVisible(true);
editor.tileDataChanged = true;
tlm.invalidate();
}
});
delete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showConfirmDialog(editor,
"Deleting an object will affect all maps that use it."
+ "\nRemove this object from those maps first."
+ "\nProceed?",
"WARNING", JOptionPane.OK_CANCEL_OPTION);
if (result==JOptionPane.OK_OPTION) {
String s = JOptionPane.showInputDialog(editor,
"Just to double check, are you sure?");
if (s.equals("yup")) {
Terrain t = list.getList().getSelectedValue();
//editor.tiles.remove(t);
editor.tileTable.remove(t.getId());
editor.tileDataChanged = true;
tlm.getList().remove(t);
tlm.invalidate();
}
}
}
});
}
list.setVisible(true);
editor.setTool(new Tool.TilePaint(editor.getArenaPanel(), list.getList()));
} else if (e.getStateChange()==ItemEvent.DESELECTED) {
list.setVisible(false);
editor.setTool(new Tool.MoveTool(editor.getArenaPanel()));
}
}
});
tilePaint.addItemListener(toggleButtonSwitch);
this.add(tilePaint);
final JToggleButton objectPaint = new JToggleButton();
stylizeToolButton(objectPaint);
try {
objectPaint.setIcon(new ImageIcon(ImageIO.read(new File("resource/editor/thing.png"))));
} catch (IOException e1) {
objectPaint.setText("Thing");
}
objectPaint.setToolTipText("Thing Paint - left to paint, right to remove");
objectPaint.addItemListener(new ItemListener() {
ListDialog<Thing> list = null;
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange()==ItemEvent.SELECTED) {
if (list==null) {
final CustomListModel<Thing> tlm = new CustomListModel<Thing>(new ArrayList<Thing>(editor.objectTable.values()));
JButton add = new JButton("Add");
JButton edit = new JButton("Edit");
JButton delete = new JButton("Delete");
JButton[] buttons = {edit,add,delete};
list = new ListDialog<Thing>(editor, objectPaint, "Thing", buttons, tlm);
list.getList().setCellRenderer(cellRenderer);
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ThingDialog dialog = new ThingDialog(editor,null);
dialog.setVisible(true);
Thing t = dialog.getThing();
if (t!=null) {
editor.getObjectTable().put(t.getId(), t);
editor.tileDataChanged = true;
tlm.getList().add(t);
tlm.invalidate();
}
}
});
edit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
new ThingDialog(editor,list.getList().getSelectedValue()).setVisible(true);
tlm.invalidate();
}
});
delete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showConfirmDialog(editor,
"Deleting an object will affect all maps that use it."
+ "\nRemove this object from those maps first."
+ "\nProceed?",
"WARNING", JOptionPane.OK_CANCEL_OPTION);
if (result==JOptionPane.OK_OPTION) {
String s = JOptionPane.showInputDialog(editor,
"Just to double check, are you sure?");
if (s.equals("yup")) {
Thing t = list.getList().getSelectedValue();
editor.objectTable.remove(t.getId());
editor.tileDataChanged = true;
tlm.getList().remove(t);
tlm.invalidate();
}
}
}
});
}
list.setVisible(true);
editor.setTool(new Tool.ObjectPaint(editor.getArenaPanel(), list.getList()));
} else if (e.getStateChange()==ItemEvent.DESELECTED) {
list.setVisible(false);
editor.setTool(new Tool.MoveTool(editor.getArenaPanel()));
}
}
});
objectPaint.addItemListener(toggleButtonSwitch);
this.add(objectPaint);
final JToggleButton editSprite = new JToggleButton();
stylizeToolButton(editSprite);
try {
editSprite.setIcon(new ImageIcon(ImageIO.read(new File("resource/editor/rotate.png"))));
} catch (IOException e1) {
editSprite.setText("Sprite");
}
editSprite.setToolTipText("Edit Sprite - left to switch sprite, scroll to rotate, mid to flip, right to clear");
editSprite.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange()==ItemEvent.SELECTED) {
editor.setTool(new Tool.SpriteSwitcher(editor.getArenaPanel()));
} else if (e.getStateChange()==ItemEvent.DESELECTED) {
editor.setTool(new Tool.MoveTool(editor.getArenaPanel()));
}
}
});
editSprite.addItemListener(toggleButtonSwitch);
this.add(editSprite);
final JToggleButton trigger = new JToggleButton();
stylizeToolButton(trigger);
try {
trigger.setIcon(new ImageIcon(ImageIO.read(new File("resource/editor/switch.png"))));
} catch (IOException e1) {
trigger.setText("Trigger");
}
trigger.setToolTipText("Trigger - left to add / select / set target tile, right to remove");
trigger.addItemListener(new ItemListener() {
ListDialog<TileSwitchPreset> list = null;
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange()==ItemEvent.SELECTED) {
if (list==null) {
final CustomListModel<TileSwitchPreset> tlm = new CustomListModel<TileSwitchPreset>(new ArrayList<TileSwitchPreset>(editor.getTriggerTable().values()));
JButton add = new JButton("Add");
JButton edit = new JButton("Edit");
JButton delete = new JButton("Delete");
JButton[] buttons = {edit,add,delete};
list = new ListDialog<TileSwitchPreset>(editor, trigger, "Trigger", buttons, tlm);
list.getList().setCellRenderer(triggerRenderer);
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
TileSwitchDialog dialog = new TileSwitchDialog(editor,null);
dialog.setVisible(true);
TileSwitchPreset t = dialog.getTriggerPreset();
if (t!=null) {
editor.getTriggerTable().put(t.getId(), t);
editor.tileDataChanged = true;
tlm.getList().add(t);
tlm.invalidate();
}
}
});
edit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
new TileSwitchDialog(editor,list.getList().getSelectedValue()).setVisible(true);
editor.tileDataChanged = true;
tlm.invalidate();
}
});
delete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showConfirmDialog(editor,
"Deleting a trigger will affect all maps that use it."
+ "\nRemove this trigger from those maps first."
+ "\nProceed?",
"WARNING", JOptionPane.OK_CANCEL_OPTION);
if (result==JOptionPane.OK_OPTION) {
String s = JOptionPane.showInputDialog(editor,
"Just to double check, are you sure?");
if (s.equals("yup")) {
TileSwitchPreset t = list.getList().getSelectedValue();
editor.triggerTable.remove(t.getId());
editor.tileDataChanged = true;
tlm.getList().remove(t);
tlm.invalidate();
}
}
}
});
}
list.setVisible(true);
editor.setTool(new Tool.TriggerPaint(editor.getArenaPanel(), list.getList()));
editor.getArenaPanel().renderTileSwitchTrigger = true;
} else if (e.getStateChange()==ItemEvent.DESELECTED) {
list.setVisible(false);
editor.setTool(new Tool.MoveTool(editor.getArenaPanel()));
editor.getArenaPanel().renderTileSwitchTrigger = false;
}
}
});
trigger.addItemListener(toggleButtonSwitch);
this.add(trigger);
final JToggleButton spawn = new JToggleButton();
stylizeToolButton(spawn);
try {
spawn.setIcon(new ImageIcon(ImageIO.read(new File("resource/editor/spawn.png"))));
} catch (IOException e1) {
spawn.setText("NPC");
}
spawn.setToolTipText("Add spawn points");
spawn.addItemListener(new ItemListener() {
SpawnDialog dialog = null;
@Override
public void itemStateChanged(ItemEvent arg0) {
if (arg0.getStateChange()==ItemEvent.SELECTED) {
if (dialog==null) {
dialog = new SpawnDialog(editor,spawn);
}
dialog.setVisible(true);
editor.setTool(new Tool.SpawnPaint(editor.getArenaPanel(), dialog));
} else if (arg0.getStateChange()==ItemEvent.DESELECTED) {
dialog.setVisible(false);
editor.setTool(new Tool.MoveTool(editor.getArenaPanel()));
}
}
});
spawn.addItemListener(toggleButtonSwitch);
this.add(spawn);
final JToggleButton particle = new JToggleButton();
stylizeToolButton(particle);
try {
particle.setIcon(new ImageIcon(ImageIO.read(new File("resource/editor/particle.png"))));
} catch (IOException e1) {
particle.setText("Particle");
}
particle.setToolTipText("Edit particle sources");
particle.addItemListener(new ItemListener() {
ParticleSourceDialog dialog = null;
@Override
public void itemStateChanged(ItemEvent arg0) {
if (arg0.getStateChange()==ItemEvent.SELECTED) {
if (dialog==null) {
dialog = new ParticleSourceDialog(editor,editor, particle, null);
}
dialog.setVisible(true);
editor.setTool(new Tool.ParticleSourcePaint(editor.getArenaPanel(), dialog));
editor.getArenaPanel().renderParticleSource = true;
} else if (arg0.getStateChange()==ItemEvent.DESELECTED) {
dialog.setVisible(false);
editor.setTool(new Tool.MoveTool(editor.getArenaPanel()));
editor.getArenaPanel().renderParticleSource = false;
}
}
});
particle.addItemListener(toggleButtonSwitch);
this.add(particle);
final JToggleButton data = new JToggleButton();
stylizeToolButton(data);
try {
data.setIcon(new ImageIcon(ImageIO.read(new File("resource/editor/particle.png"))));
} catch (IOException e1) {
data.setText("?");
}
data.setToolTipText("Edit particle sources");
data.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent arg0) {
if (arg0.getStateChange()==ItemEvent.SELECTED) {
editor.setTool(new Tool.DataPaint(editor.getArenaPanel()));
editor.getArenaPanel().renderData = true;
} else if (arg0.getStateChange()==ItemEvent.DESELECTED) {
editor.setTool(new Tool.MoveTool(editor.getArenaPanel()));
editor.getArenaPanel().renderData = false;
}
}
});
data.addItemListener(toggleButtonSwitch);
this.add(data);
}
private static void stylizeToolButton(AbstractButton button) {
//button.setOpaque(true);
button.setFocusable(false);
//button.setBackground(Color.BLACK);
button.setBorderPainted(false);
button.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
}
private ItemListener toggleButtonSwitch = new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange()==ItemEvent.SELECTED) {
if (e.getSource()!=activeButton) {
// deactivate the current active button & dialog first
if (activeButton!=null)
activeButton.doClick();
// set this one to be the one
activeButton = (JToggleButton) e.getSource();
}
} else if (e.getStateChange()==ItemEvent.DESELECTED) {
if (e.getSource()==activeButton) {
activeButton = null;
}
}
}};
private ListCellRenderer<CellRenderable> cellRenderer = new ListCellRenderer<CellRenderable>() {
@Override
public Component getListCellRendererComponent(JList<? extends CellRenderable> list,
final CellRenderable value, int index, boolean isSelected, boolean cellHasFocus) {
BufferedImage iconImage = value.getImage();
if (iconImage.getHeight() > Sprite.TILE_SPRITE_SIZE ||
iconImage.getWidth() > Sprite.TILE_SPRITE_SIZE) {
iconImage = iconImage.getSubimage(0, 0, Sprite.TILE_SPRITE_SIZE, Sprite.TILE_SPRITE_SIZE);
}
ImageIcon icon = new ImageIcon(iconImage);
JLabel tile = new JLabel(icon, SwingConstants.LEFT);
tile.setOpaque(true);
tile.setFont(GUIFactory.font_s);
tile.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
if (isSelected) {
tile.setBackground(list.getSelectionBackground());
tile.setForeground(list.getSelectionForeground());
}
else {
tile.setBackground(list.getBackground());
tile.setForeground(list.getForeground());
}
tile.setToolTipText(value.getName());
return tile;
}
};
private ListCellRenderer<TileSwitchPreset> triggerRenderer = new ListCellRenderer<TileSwitchPreset>() {
@Override
public Component getListCellRendererComponent(JList<? extends TileSwitchPreset> list,
final TileSwitchPreset value, int index, boolean isSelected, boolean cellHasFocus) {
try {
BufferedImage oriImage = null;
oriImage = value.getOriginalThing().getImage();
if (oriImage.getHeight() > Sprite.TILE_SPRITE_SIZE ||
oriImage.getWidth() > Sprite.TILE_SPRITE_SIZE) {
oriImage = oriImage.getSubimage(0, 0, Sprite.TILE_SPRITE_SIZE, Sprite.TILE_SPRITE_SIZE);
}
BufferedImage switchImage = null;
switchImage = value.getSwitchThing().getImage();
if (switchImage.getHeight() > Sprite.TILE_SPRITE_SIZE ||
switchImage.getWidth() > Sprite.TILE_SPRITE_SIZE) {
switchImage = switchImage.getSubimage(0, 0, Sprite.TILE_SPRITE_SIZE, Sprite.TILE_SPRITE_SIZE);
}
ImageIcon icon = new ImageIcon(oriImage);
JLabel tile = new JLabel(icon, SwingConstants.LEFT);
tile.setOpaque(true);
tile.setFont(GUIFactory.font_s);
tile.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
tile.setToolTipText(value.getOriginalThing().getName());
ImageIcon sicon = new ImageIcon(switchImage);
JLabel stile = new JLabel(sicon, SwingConstants.LEFT);
stile.setOpaque(true);
stile.setFont(GUIFactory.font_s);
stile.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
stile.setToolTipText(value.getSwitchThing().getName());
JLabel triggerName = new JLabel(value.getName());
triggerName.setFont(GUIFactory.font_s);
JPanel panel = new JPanel();
panel.add(tile);
panel.add(stile);
panel.add(triggerName);
if (isSelected) {
panel.setBackground(list.getSelectionBackground());
panel.setForeground(list.getSelectionForeground());
}
else {
panel.setBackground(list.getBackground());
panel.setForeground(list.getForeground());
}
return panel;
}
catch (Exception e) {
return new JPanel();
}
}
};
}
| true |
05e352aeeb70681bf60eec54fa4485b940c95fa3
|
Java
|
RIMEL-UCA/RIMEL-UCA.github.io
|
/chapters/2020/assets/MavenProfileInProjectTimeline/code/event-search-tools/src/main/java/fr/unice/polytech/si5/rimel/eventprofile/model/Docker.java
|
UTF-8
| 231 | 1.898438 | 2 |
[] |
no_license
|
package fr.unice.polytech.si5.rimel.eventprofile.model;
public enum Docker {
DOCKERFILE("dockerfile"),
DOCKERCOMPOSE("docker-compose"),
;
public final String name;
Docker(String s) {
name = s;
}
}
| true |
10f1b9a67eba221815ee38e9f830de569d32c1e2
|
Java
|
prentent/TextDemo
|
/udp/src/main/java/com/example/udp/Demo1Sender.java
|
UTF-8
| 1,230 | 2.984375 | 3 |
[] |
no_license
|
package com.example.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import com.sun.org.apache.bcel.internal.classfile.InnerClass;
/**
研究下UDP通讯
UDP数据传输的特点
1:因为无连接所以速度快
2:无连接
3:每次能够发送的数据最大是64k
4:因为无连接所以不安全、
5:UDP的传输是依靠数据包进行传输的
生活中的运输货物
1:把货物装入集装箱放到码头等货运船
2:把集装箱装入船上
3:船运输货物
4:开着车去码头取货物
5:拿到货物
*/
public class Demo1Sender {
public static void main(String[] args) {
try {
DatagramSocket socket=new DatagramSocket(); //码头
String data="哈哈哈哈!!!!"; //货物
DatagramPacket packet=new DatagramPacket(data.getBytes(),data.getBytes().length,InetAddress.getLocalHost(),9000); //装货物贴标签
socket.send(packet);
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
a2bcff9e64c0dbf8cea81443bb273af3e6b2e325
|
Java
|
pravinkumarm/SelbotTestLeaf
|
/src/main/java/com/selbot/pages/FindLeads.java
|
UTF-8
| 1,361 | 2.125 | 2 |
[] |
no_license
|
package com.selbot.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import com.selbot.testng.api.base.Annotations;
public class FindLeads extends Annotations {
public FindLeads() {
PageFactory.initElements(driver, this);
}
@FindBy(how=How.LINK_TEXT, using="Find Leads") WebElement eleClickFindLeads;
@FindBy(how=How.XPATH, using="//input[@name='id']") WebElement eleEnterMyLeads;
@FindBy(how=How.XPATH,using="//Button[text()='Find Leads']") WebElement eleClickFindLeadButton;
@FindBy(how=How.XPATH, using="//div[@class='x-grid3-cell-inner x-grid3-col-partyId']/a") WebElement eleSelectGrid;
public FindLeads clickFindLeads() throws InterruptedException{
click (eleClickFindLeads);
Thread.sleep(3000);
return this;
}
public FindLeads enterLeadID(String LeadID) throws InterruptedException {
clearAndType(eleEnterMyLeads,LeadID);
Thread.sleep(3000);
return this;
}
public FindLeads clickFindButton() throws InterruptedException {
click(eleClickFindLeadButton);
Thread.sleep(3000);
return this;
}
public ViewLead selectLeadList() throws InterruptedException {
click (eleSelectGrid);
Thread.sleep(3000);
return new ViewLead();
}
}
| true |
97817b7717234bc0520eafd150c68117013f71b2
|
Java
|
reverseengineeringer/com.yelp.android
|
/src/com/bumptech/glide/k.java
|
UTF-8
| 293 | 1.507813 | 2 |
[] |
no_license
|
package com.bumptech.glide;
import com.bumptech.glide.manager.h;
class k
implements Runnable
{
k(j paramj, h paramh) {}
public void run()
{
a.a(b);
}
}
/* Location:
* Qualified Name: com.bumptech.glide.k
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| true |
c273e9241df92373d9f8a6cbd69d0d68955a0c56
|
Java
|
vener91/cs577
|
/p2/main.java
|
UTF-8
| 3,618 | 3.390625 | 3 |
[] |
no_license
|
import java.util.*;
class GraphTest {
public static void main(String[] args) {
//System.out.print(args[0] + " nodes ");
//System.out.print(args[1] + " edges ");
//If it passed here that means it has the variables
//Generate agency matrix
int nodeCount = Integer.parseInt(args[0]);
int edgeCount = Integer.parseInt(args[1]);
int repeatCount = Integer.parseInt(args[2]);
int mode = Integer.parseInt(args[3]);
int connectedCount = 0;
int graphLimit = 0;
Random diceRoller = new Random();
while(repeatCount > 0){
ArrayList<Node> nodeList = new ArrayList<Node>();
boolean[][] edgeList = new boolean[nodeCount][nodeCount];
int i,k;
//Create nodes
for (i = 0; i < nodeCount; i++){
//Default to false for the edgeList
for(k = 0; k < nodeCount; k++){
edgeList[i][k] = false;
}
nodeList.add(new Node(i));
}
int vertexA = 0;
int vertexB = 0;
//Create edges
for (i = 0; i < edgeCount; i++) {
while(true){
vertexA = diceRoller.nextInt(nodeCount);
vertexB = diceRoller.nextInt(nodeCount);
if(edgeList[vertexA][vertexB] || vertexA == vertexB){
continue;
}
edgeList[vertexA][vertexB] = true;
edgeList[vertexB][vertexA] = true;
nodeList.get(vertexA).addNode(nodeList.get(vertexB));
nodeList.get(vertexB).addNode(nodeList.get(vertexA));
break;
}
}
//Verify if bidirectional
for(Node n: nodeList ){
for(Node n2: n.outBound ){
if(n2.outBound.indexOf(n) == -1){
System.exit(1);
}
}
}
switch(mode){
case 0: //Check of connectedness
if(!checkConnected(nodeList)){
//connectedCount++;
//System.out.print("Disconnected \n");
}else{
connectedCount++;
//System.out.print("Connected \n");
}
break;
case 1:
if(checkConnected(nodeList)){
System.out.print(Walk(diceRoller, nodeList) + ",");
graphLimit++;
}
break;
}
if(graphLimit == 5){
break;
}
repeatCount--;
}
switch(mode){
case 0:
System.out.print(connectedCount);
break;
}
}
public static boolean checkConnected(ArrayList<Node> nodeList){
boolean isDisconnect = false;
//Clear visitcount
for(Node n: nodeList){
n.visitCount = 0;
}
DFStraverse(nodeList.get(0));
//See if any nodes din't get visited
for (Node n : nodeList){
if(n.visitCount == 0){
isDisconnect = true;
break;
}
}
return !isDisconnect;
}
public static void DFStraverse(Node startNode){
startNode.visitCount++;
for (Node node : startNode.outBound){
if(node.visitCount == 0){
DFStraverse(node);
}
}
}
public static int Walk(Random r, ArrayList<Node> nodeList){
int zeroCount = 0;
int size = 0;
int nodeSize = nodeList.size();
//Clear visitcount
for(Node n: nodeList){
n.visitCount = 0;
}
Node currNode = nodeList.get(r.nextInt(nodeSize - 1));
currNode.visitCount++;
zeroCount++;
while(zeroCount < nodeSize){
size = currNode.outBound.size();
if(size > 1){
currNode = currNode.outBound.get(r.nextInt(size)); //Pick one node
}else{
currNode = currNode.outBound.get(0);
}
if(currNode.visitCount == 0){
zeroCount++;
//System.out.println(zeroCount + " "+ nodeList.size());
}
/*
for(Node n: nodeList){
if(n.visitCount == 0){
System.out.print("Node - " + n.number);
for(Node node: n.outBound){
System.out.print( " - " + node.number);
}
System.out.println();
}
}
*/
currNode.visitCount++;
}
int sum = 0;
for(Node n: nodeList){
sum += n.visitCount;
}
return sum;
}
}
| true |
01e5cb5541c0b0ec3ed8226ecba4d6976ecf8b98
|
Java
|
YuliyaKhilko/pvt_course
|
/Task25/TestDataDAO.java
|
UTF-8
| 1,555 | 2.5625 | 3 |
[] |
no_license
|
package core;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
public class TestDataDAO {
Connection connection = null;
public Connection getConnection() {
String url = "jdbc:mysql://localhost:3306/sys?useSSL=false";
String user = "root";
String password = "qwerty123";
try {
// Class.forName("com.mysql.jdbc.Driver");
if (connection == null)
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public List<TestData> select() {
List<TestData> data = new LinkedList<TestData>();
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM test_automation.test_data");
TestData testData = null;
while (resultSet.next()) {
testData = new TestData();
testData.setLogin(resultSet.getString("login"));
testData.setPassword(resultSet.getString("password"));
testData.setEmail(resultSet.getString("email"));
testData.setEmailSubject(resultSet.getString("email_subject"));
testData.setEmailBody(resultSet.getString("email_body"));
testData.setGroupName(resultSet.getString("group_name"));
testData.setName(resultSet.getString("name"));
data.add(testData);
}
resultSet.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return data;
}
}
| true |
4a96c03a714abd2ee3bcd6c364e2ab94e49d164d
|
Java
|
TasneemAlaa/Bus-managment-system
|
/bus/DriverFile.java
|
UTF-8
| 8,328 | 2.359375 | 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 bus;
import java.awt.FileDialog;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
import java.util.*;
/**
*
* @author pc
*/
public class DriverFile extends javax.swing.JFrame {
ArrayList<Driver> dr ;
/**
* Creates new form demo
*/
public DriverFile() {
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() {
panel1 = new java.awt.Panel();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
panel1.setBackground(new java.awt.Color(44, 62, 80));
jButton1.setBackground(new java.awt.Color(248, 148, 6));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton1.setForeground(new java.awt.Color(255, 255, 255));
jButton1.setText("Open File");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTable1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(248, 148, 6)));
jTable1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null},
{null, null, null},
{null, null, null}
},
new String [] {
"Driver ID", "Salary", "Working Hours"
}
));
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
panel1.setLayout(panel1Layout);
panel1Layout.setHorizontalGroup(
panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel1Layout.createSequentialGroup()
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel1Layout.createSequentialGroup()
.addGap(54, 54, 54)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 424, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panel1Layout.createSequentialGroup()
.addGap(214, 214, 214)
.addComponent(jButton1)))
.addContainerGap(54, Short.MAX_VALUE))
);
panel1Layout.setVerticalGroup(
panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 329, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(44, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 1, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
try {
FileDialog fc = new FileDialog(this, "Choose a file", FileDialog.LOAD);
fc.setVisible(true);
String file = fc.getFile();
if (file != null) {
FileInputStream f = new FileInputStream(file);
ObjectInputStream o = new ObjectInputStream(f);
dr= (ArrayList<Driver>) o.readObject();
f.close();
o.close();
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(dr.size());
int row = 0;
int col;
double total = 0;
for (Driver d : dr) {
col = 0;
model.setValueAt(d.getD_id(), row, col++);
model.setValueAt(d.getSalary(), row, col++);
model.setValueAt(d.getWorkingHrs(), row, col);
row++;
}
}
} catch (Exception x) {
}
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @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(DriverFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DriverFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DriverFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DriverFile.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 DriverFile().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private java.awt.Panel panel1;
// End of variables declaration//GEN-END:variables
}
| true |
2e4cd68a31d106c7d95a9849d5d5a71dff790d7b
|
Java
|
carecon/fabric3-core
|
/kernel/api/fabric3-host-api/src/main/java/org/fabric3/api/host/os/OperatingSystem.java
|
UTF-8
| 1,724 | 2.140625 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Fabric3
* Copyright (c) 2009-2015 Metaform Systems
*
* 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.
*
* Portions originally based on Apache Tuscany 2007
* licensed under the Apache 2.0 license.
*/
package org.fabric3.api.host.os;
import org.fabric3.api.host.Version;
/**
* The current runtime operating system in normalized form.
*/
public class OperatingSystem {
private String name;
private String processor;
private Version version;
public OperatingSystem(String name, String processor, Version version) {
this.name = name;
this.processor = processor;
this.version = version;
}
/**
* Returns the normalized operating system name.
*
* @return the normalized operating system name
*/
public String getName() {
return name;
}
/**
* Returns the normalized operating system processor.
*
* @return the normalized operating system processor
*/
public String getProcessor() {
return processor;
}
/**
* Returns the operating system version.
*
* @return the operating system version
*/
public Version getVersion() {
return version;
}
}
| true |
c03035a0318bfdb89d4b7fc1046cf390672690ca
|
Java
|
Evolveum/midpoint-studio
|
/studio-idea-plugin/src/main/java/com/evolveum/midpoint/studio/ui/trace/overview/OverviewProviderRegistry.java
|
UTF-8
| 2,356 | 1.960938 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.evolveum.midpoint.studio.ui.trace.overview;
import com.evolveum.midpoint.schema.traces.OpNode;
import com.evolveum.midpoint.schema.traces.RepositoryCacheOpNode;
import com.evolveum.midpoint.schema.traces.operations.*;
import org.jetbrains.annotations.NotNull;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Supplier;
/**
*
*/
public class OverviewProviderRegistry {
private static final Map<Class<? extends OpNode>, Supplier<OverviewProvider<?>>> PROVIDERS = new LinkedHashMap<>();
static {
PROVIDERS.put(RepositoryCacheOpNode.class, RepositoryCacheOperationOverviewProvider::new);
PROVIDERS.put(FocusRepositoryLoadOpNode.class, FocusRepositoryLoadOverviewProvider::new);
PROVIDERS.put(FullProjectionLoadOpNode.class, FullProjectionLoadOverviewProvider::new);
PROVIDERS.put(ClockworkRunOpNode.class, ClockworkRunOverviewProvider::new);
PROVIDERS.put(ClockworkClickOpNode.class, ClockworkClickOverviewProvider::new);
PROVIDERS.put(ProjectorProjectionOpNode.class, ProjectorProjectionOverviewProvider::new);
PROVIDERS.put(ProjectorComponentOpNode.class, ProjectorComponentOverviewProvider::new);
PROVIDERS.put(FocusChangeExecutionOpNode.class, FocusChangeExecutionOverviewProvider::new);
PROVIDERS.put(ProjectionChangeExecutionOpNode.class, ProjectionChangeExecutionOverviewProvider::new);
PROVIDERS.put(ResourceObjectConstructionEvaluationOpNode.class, ResourceObjectConstructionEvaluationOverviewProvider::new);
PROVIDERS.put(MappingEvaluationOpNode.class, MappingEvaluationOverviewProvider::new);
PROVIDERS.put(TransformationExpressionEvaluationOpNode.class, TransformationExpressionEvaluationOverviewProvider::new);
PROVIDERS.put(ItemConsolidationOpNode.class, ItemConsolidationOverviewProvider::new);
}
@SuppressWarnings("unchecked")
@NotNull
public static <O extends OpNode> OverviewProvider<O> getProvider(@NotNull O node) {
for (Map.Entry<Class<? extends OpNode>, Supplier<OverviewProvider<?>>> entry : PROVIDERS.entrySet()) {
if (entry.getKey().isAssignableFrom(node.getClass())) {
return (OverviewProvider<O>) entry.getValue().get();
}
}
return (OverviewProvider<O>) new NullOverviewProvider();
}
}
| true |
f81960321dd91dadfe0c68cb542427a80381456d
|
Java
|
Azure/azure-sdk-for-java
|
/sdk/datadog/azure-resourcemanager-datadog/src/samples/java/com/azure/resourcemanager/datadog/generated/MonitorsGetByResourceGroupSamples.java
|
UTF-8
| 840 | 1.976563 | 2 |
[
"LicenseRef-scancode-generic-cla",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"CC0-1.0",
"BSD-3-Clause",
"UPL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] |
permissive
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.datadog.generated;
/** Samples for Monitors GetByResourceGroup. */
public final class MonitorsGetByResourceGroupSamples {
/*
* x-ms-original-file: specification/datadog/resource-manager/Microsoft.Datadog/stable/2021-03-01/examples/Monitors_Get.json
*/
/**
* Sample code: Monitors_Get.
*
* @param manager Entry point to MicrosoftDatadogManager.
*/
public static void monitorsGet(com.azure.resourcemanager.datadog.MicrosoftDatadogManager manager) {
manager
.monitors()
.getByResourceGroupWithResponse("myResourceGroup", "myMonitor", com.azure.core.util.Context.NONE);
}
}
| true |
d790f58a78488afa6c76da9dc23d5df86a8602ee
|
Java
|
arnavbagad/Java-Class-Notes
|
/Student/jrJava/graphics4_ourOwnDesign/MyJPanel.java
|
UTF-8
| 494 | 2.921875 | 3 |
[] |
no_license
|
package jrJava.graphics4_ourOwnDesign;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class MyJPanel extends JPanel {
public void paintComponent(Graphics g){
System.out.println("MyJPanel begin: TID=" + Thread.currentThread().getId());
g.setColor(Color.white);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.cyan);
g.drawRect(20, 20, 300, 300);
g.setColor(Color.orange);
g.drawRect(30, 100, 150, 150);
}
}
| true |
11f3be78cc916b90b0ca4bdccf450716ece0278a
|
Java
|
Thester113/SW2-Global-Consulting-Scheduler
|
/src/Controllers/ContactsReportController.java
|
UTF-8
| 4,687 | 2.640625 | 3 |
[] |
no_license
|
package Controllers;
import Model.Appointments;
import Model.Contacts;
import DAO.DBConnection;
import DAO.ReportDB;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ResourceBundle;
import java.util.logging.Logger;
/**
* Combo Box is used to select a contact this will set a table view with the contact's appointments.
*/
public class ContactsReportController implements Initializable {
@FXML
private ComboBox<Contacts> contactCB;
@FXML
private TableView<Appointments> contactAppointmentTbl;
@FXML
private TableColumn<Appointments, Integer> appointmentID;
@FXML
private TableColumn<Appointments, String> aptTitle;
@FXML
private TableColumn<Appointments, String> aptType;
@FXML
private TableColumn<Appointments, String> aptDescription;
@FXML
private TableColumn<Appointments, LocalDateTime> aptStart;
@FXML
private TableColumn<Appointments, LocalDateTime> aptEnd;
@FXML
private TableColumn<Appointments, Integer> aptCustID;
@FXML
private Button exitBtn;
@FXML
private Button mainBtn;
/**
* Opens main screen from reports
*
* @param event
* @throws IOException
*/
@FXML
void backToMain(ActionEvent event) throws IOException {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/Views/MainScreen.fxml"));
loader.load();
Stage stage = (Stage) ((Button) event.getSource()).getScene().getWindow();
Parent scene = loader.getRoot();
stage.setScene(new Scene(scene));
stage.show();
}
/**
* Shows contacts report. Display appointments for contact using a lambda.
* Lambda Expression reduces code and makes getting appointments easier.
*
* @param event
* @throws IOException
*/
@FXML
void displayContactSchedule(ActionEvent event) throws IOException {
try {
//Gets the contact to send as a query to the DB
Contacts contactSchedule = contactCB.getSelectionModel().getSelectedItem();
ReportDB.sendContactSelection(contactSchedule);
//Checks the appointments from the DB and populates the tableview
contactAppointmentTbl.setItems(ReportDB.getContactSchedule());
for (Appointments appointments : ReportDB.contactSchedule) {
System.out.println(appointments.getStart());
}
appointmentID.setCellValueFactory(new PropertyValueFactory<>("appointmentID"));
aptTitle.setCellValueFactory(new PropertyValueFactory<>("title"));
aptType.setCellValueFactory(new PropertyValueFactory<>("type"));
aptDescription.setCellValueFactory(new PropertyValueFactory<>("description"));
aptStart.setCellValueFactory(new PropertyValueFactory<>("start"));
aptEnd.setCellValueFactory(new PropertyValueFactory<>("end"));
aptCustID.setCellValueFactory(new PropertyValueFactory<>("customerID"));
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Exits the application
*
* @param event
*/
@FXML
void exitToApp(ActionEvent event) {
Button sourceButton = (Button) event.getSource();
exitBtn.setText(sourceButton.getText());
DBConnection.closeConnection();
System.exit(0);
}
ObservableList<Contacts> contactList = FXCollections.observableArrayList();
/**
* Gets all contacts and displays in Combo Box Contact Name and ID.
*
* @param url
* @param resourceBundle
*/
@FXML
public void initialize(URL url, ResourceBundle resourceBundle) {
try {
Connection conn = DBConnection.startConnection();
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM contacts");
//Creates Country Objects using Strings for Country selection
//columnLabel corresponds to Column value and not the attribute of the object
if (rs.next()) {
do {
contactList.add(new Contacts(rs.getInt("Contact_ID"), rs.getString("Contact_Name"), rs.getString("Email")));
} while (rs.next());
}
contactCB.setItems(contactList);
} catch (SQLException ce) {
Logger.getLogger(ce.toString());
}
}
}
| true |
c76602419d6b577c73bd22cddf4a05b0e713ea86
|
Java
|
Karivtan/ImageJ-Diffusion_simulator
|
/Diffusion_Generator.java
|
UTF-8
| 6,550 | 2.1875 | 2 |
[] |
no_license
|
import ij.*;
import ij.process.*;
import ij.gui.*;
import java.awt.*;
import ij.plugin.*;
import ij.plugin.frame.*;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import ij.WindowManager;
import java.util.Random;
import ij.ImagePlus;
import ij.text.*; // import ImageJ text package
public class Image_generator3 implements PlugIn {
static public int[][][] Imageray;
static public String[] Imagetext;
static public String Singleimageline;
public ImageStack stack;
static public double x;
static ImagePlus imp;
static public double y;
static public double y2;
static public double x2;
static public double directionx;
static public double directiony;
static public String v;
static public double angle;
static public double remain;
static public double xold;
static public double yold;
static public double y2old;
static public double x2old;
public int nF;
public int nB;
public int nW;
public int nH;
public int nZ;
public int switchT;
public int radius;
public double Dconst;
public double vconst;
String[] moChoice={"Brownian", "Constrained", "Active+Brownian", "Active", "Still","brown+con"};
public void run(String arg) {//1
IJ.run("Close All", "");
nB=5;
nH=100;
nW=100;
nB=100;
nZ=100;
switchT=50;
radius=10;
Dconst=4;
vconst=4;
GenericDialog gd = new GenericDialog("Stack Averaging");
gd.addNumericField("Number of foci=", nF, 0);//50
gd.addNumericField("Heigth", nH, 0);//50
gd.addNumericField("Width", nW, 0);//50
gd.addNumericField("Time frames", nW, 0);//50
gd.addNumericField("Border", nB,0);//50
gd.addNumericField("Switch (if applicable)", switchT,0);//50
gd.addNumericField("Radius of confinement", radius,0);//50
gd.addNumericField("Diffusion Constant", Dconst,1);//50
gd.addNumericField("speed of active diffusion", vconst,0);//50
gd.addChoice("Type of movement: ", moChoice, moChoice[0]);
gd.showDialog();
nF=(int)gd.getNextNumber();
nH=(int)gd.getNextNumber();
nW=(int)gd.getNextNumber();
nZ=(int)gd.getNextNumber();
nB=(int)gd.getNextNumber();
switchT=(int)gd.getNextNumber();
radius=(int)gd.getNextNumber();
Dconst=gd.getNextNumber();
vconst=gd.getNextNumber();
String moSet=gd.getNextChoice();
Random rG = new Random();
imp = IJ.createImage("Untitled", "8-bit Black", nH+nB+nB, nW+nB+nB, nZ);
IJ.showMessage("Random Image generator","Starting generation!");
Imageray= new int[nH+nB+nB][nW+nB+nB][nZ];
v="";
for (int g=0; g<nF;g++){ //2
x2old=100;
y2old=100;
xold=50;
yold=50;
x2=(int)(rG.nextDouble()*nW+nB);
y2=(int)(rG.nextDouble()*nH+nB);
xold=x2;
yold=y2;
if (moSet=="Brownian"){
for (int z=1;z<nZ+1;z++){ //z, 3
angle=rG.nextDouble()*2*Math.PI-Math.PI;
x=(Math.cos(angle)*Math.sqrt(4*Dconst)+xold);
y=(Math.sin(angle)*Math.sqrt(4*Dconst)+yold);
xold=x;
yold=y;
IJ.run(imp, "Specify...", "width=7 height=7 x="+x+" y="+y+" slice="+z+" oval");
// IJ.showMessage("My_Plugin","Hello world!\n"+x+"\n"+y);
IJ.run(imp, "Fill", "slice");
IJ.showProgress((double)z/nZ);
}
} else if (moSet=="brown+con") {
for (int z=1;z<switchT;z++){ //z, 3
angle=rG.nextDouble()*2*Math.PI-Math.PI;
x=(Math.cos(angle)*Math.sqrt(4*Dconst)+xold);
y=(Math.sin(angle)*Math.sqrt(4*Dconst)+yold);
xold=x;
yold=y;
IJ.run(imp, "Specify...", "width=3 height=3 x="+x+" y="+y+" slice="+z+" oval");
IJ.run(imp, "Fill", "slice");
IJ.showProgress((double)z/nZ);
x2=xold;
y2=yold;
}
for (int z=switchT;z<nZ+1;z++){ //z, 3
angle=rG.nextDouble()*2*Math.PI-Math.PI;
x=(Math.cos(angle)*Math.sqrt(4*Dconst)+xold);
y=(Math.sin(angle)*Math.sqrt(4*Dconst)+yold);
while (((x-x2)*(x-x2)+(y-y2)*(y-y2))>radius*radius){
//x<(x2-5)||x>(x2+5)||y<(y2-5)||y>(y2+5)){
angle=rG.nextDouble()*2*Math.PI-Math.PI;
x=(Math.cos(angle)*Math.sqrt(4*Dconst)+xold);
y=(Math.sin(angle)*Math.sqrt(4*Dconst)+yold);
}
xold=x;
yold=y;
IJ.run(imp, "Specify...", "width=3 height=3 x="+x+" y="+y+" slice="+z+" oval");
IJ.run(imp, "Fill", "slice");
IJ.showProgress((double)z/nZ);
}//3
} else if (moSet=="Constrained") {
for (int z=1;z<nZ+1;z++){ //z, 3
angle=rG.nextDouble()*2*Math.PI-Math.PI;
x=(Math.cos(angle)*Math.sqrt(4*Dconst)+xold);
y=(Math.sin(angle)*Math.sqrt(4*Dconst)+yold);
while (((x-x2)*(x-x2)+(y-y2)*(y-y2))>radius*radius){
// while (x<(x2-10)||x>(x2+10)||y<(y2-10)||y>(y2+10)){
angle=rG.nextDouble()*2*Math.PI-Math.PI;
x=(Math.cos(angle)*Math.sqrt(4*Dconst)+xold);
y=(Math.sin(angle)*Math.sqrt(4*Dconst)+yold);
}
xold=x;
yold=y;
IJ.run(imp, "Specify...", "width=3 height=3 x="+x+" y="+y+" slice="+z+" oval");
IJ.run(imp, "Fill", "slice");
IJ.showProgress((double)z/nZ);
}//3
} else if (moSet=="Active"){
directionx = (Math.random()*2-1)*Math.sqrt(vconst);
if (Math.random()>0.5){
directiony = Math.sqrt(vconst-directionx*directionx);
} else {
directiony = -Math.sqrt(vconst-directionx*directionx);
}
for (int z=1;z<nZ+1;z++){ //z, 3
x=(xold+directionx);
y=(yold+directiony);
xold=x;
yold=y;
IJ.run(imp, "Specify...", "width=3 height=3 x="+x+" y="+y+" slice="+z+" oval");
IJ.run(imp, "Fill", "slice");
IJ.showProgress((double)z/nZ);
}
} else if (moSet=="Still") {
x=(x2+rG.nextGaussian());
y=(y2+rG.nextGaussian());
for (int z=1;z<nZ+1;z++){
IJ.run(imp, "Specify...", "width=3 height=3 x="+x+" y="+y+" slice="+z+" oval");
IJ.run(imp, "Fill", "slice");
IJ.showProgress((double)z/nZ);
}
} else {
directionx = (Math.random()*2-1)*Math.sqrt(vconst);
if (Math.random()>0.5){
directiony = Math.sqrt(vconst-directionx*directionx);
} else {
directiony = 0-Math.sqrt(vconst-directionx*directionx);
}
// IJ.showMessage("Random Image generator","Starting generation!\n"+directionx+";"+directiony);
for (int z=1;z<nZ+1;z++){ //z, 3
angle=rG.nextDouble()*2*Math.PI-Math.PI;
x=(Math.cos(angle)*Math.sqrt(4*Dconst)+xold+directionx);
y=(Math.sin(angle)*Math.sqrt(4*Dconst)+yold+directiony);
xold=x;
yold=y;
IJ.run(imp, "Specify...", "width=3 height=3 x="+x+" y="+y+" slice="+z+" oval");
IJ.run(imp, "Fill", "slice");
IJ.showProgress((double)z/nZ);
}
}
}//1
IJ.run(imp, "Select None", "");
// IJ.run(imp, "Gaussian Blur...", "sigma=1 stack");
imp.show();
}
}
| true |
e5b1295b346199b25b92946d9d791cd23134961b
|
Java
|
davojuve/mapR
|
/app/src/main/java/com/example/davit/mapreminder/DetailActivity.java
|
UTF-8
| 8,625 | 2.046875 | 2 |
[] |
no_license
|
package com.example.davit.mapreminder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.davit.mapreminder.data.MapReminderConstants;
import com.example.davit.mapreminder.data.Reminder;
import com.example.davit.mapreminder.database.ReminderDataSource;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
/**
* class Detail Activity
*/
public class DetailActivity extends AppCompatActivity implements OnMapReadyCallback {
GoogleMap mMapDetail;
Reminder reminder;
private static final int ERROR_DIALOG_REQUEST = 9001;
protected double targetCordLat = 0.0;
protected double targetCordLng = 0.0;
private String reminderName;
private String reminderImageName;
ReminderDataSource dataSource;
private Long reminderId;
protected static final String REMINDER_ID = "reminderId";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_reminder);
/** Back button on detail page */
Button detailBtnBack = (Button) findViewById(R.id.detailBtnBack);
detailBtnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
// Intent intent = new Intent(DetailActivity.this, MainActivity.class);
// startActivity(intent);
}
});
/** Open connection to the database */
dataSource = new ReminderDataSource(this);
dataSource.open();
/**
* get reminder by id (from database)
* id from intent (MainActivity)
* set reminders Name, Image, Description, coordinates
*/
reminderId = getIntent().getLongExtra(MapReminderConstants.REMINDER_ID, 0);
reminder = dataSource.findById( reminderId );
// set name
reminderName = reminder.getReminderName();
TextView detailReminderName = (TextView) findViewById(R.id.detailReminderName);
detailReminderName.setText(reminderName);
// set image
ImageView detailImage = (ImageView) findViewById(R.id.detailReminderImage);
reminderImageName = reminder.getType();
setImageResource( detailImage, reminderImageName );
// Set description
TextView detailDescription = (TextView) findViewById(R.id.detailReminderDescription);
detailDescription.setText(reminder.getDescription());
// set map coordinates
targetCordLat = reminder.getTargetCordLat();
targetCordLng = reminder.getTargetCordLng();
/** Check google map service */
if (googleMapServicesOK()) {
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.detailMap);
mapFragment.getMapAsync(this);
}else{
Toast.makeText(this, "Problem with mapping service", Toast.LENGTH_SHORT).show();
}
} // End of onCreate
@Override
protected void onResume() {
super.onResume();
dataSource.open();
}
@Override
protected void onPause() {
super.onPause();
dataSource.close();
}
/** when map is ready */
@Override
public void onMapReady(GoogleMap map) {
if (mMapDetail == null) {
mMapDetail = map;
}
goToLocation(targetCordLat, targetCordLng, 15);
if (mMapDetail != null) {
/** add custom info window on marker */
mMapDetail.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker marker) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
View v = getLayoutInflater().inflate(R.layout.marker_info_window, null);
/** add custom info on marker info window */
ImageView markerImageView = (ImageView) v.findViewById(R.id.markerImageView);
TextView markerReminderName = (TextView) v.findViewById(R.id.markerReminderName);
setImageResource(markerImageView, reminderImageName);
markerReminderName.setText(reminderName);
return v;
}
});
} // End of if mMapDetail != null
} // End of onMapReady
/**
* for checking if google mapping service is available
* @return bool
*/
public boolean googleMapServicesOK() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int isAvailable = googleAPI.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
} else if (googleAPI.isUserResolvableError(isAvailable)) {
googleAPI.getErrorDialog(this, isAvailable, ERROR_DIALOG_REQUEST).show();
} else {
Toast.makeText(this, "Can't connect to mapping service", Toast.LENGTH_SHORT).show();
}
return false;
}
/**
* set map location and zoom level
* @param lat double
* @param lng double
* @param zoom float
*/
private void goToLocation(double lat, double lng, float zoom){
LatLng latLng = new LatLng(lat, lng);
// CameraUpdate update = CameraUpdateFactory.newLatLng(latLng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, zoom);
mMapDetail.moveCamera(update);
// if you want to see transition use animateCamera()
// add marker to map on detail activity
addMarker(mMapDetail, lat, lng);
// Toast.makeText(this, "Location of "+reminder.getType(), Toast.LENGTH_SHORT).show();
}
/**
* Add marker on map method
* @param map GoogleMap
* @param lat double
* @param lng double
*/
private void addMarker(GoogleMap map, double lat, double lng){
map.addMarker(new MarkerOptions()
.position(new LatLng(lat, lng))
.title(reminder.getType())
);
}
/**
* Set image
* @param iv ImageView
* @param imageName String (reminder.getType() )
*/
private void setImageResource( ImageView iv, String imageName ){
int resID = getResources().getIdentifier(imageName, "drawable", getPackageName());
iv.setImageResource(resID);
}
/** remove Reminder Click Listener*/
public void detailReminderBtnRemoveClickListener(View view) {
/** display alert are you sure? */
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to delete?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dataSource.deleteById(reminderId);
// todo cancel notification if active
// if (isNotificationActive) {
// notificationManager.cancel(notificationId);
// isNotificationActive = false;
// }
DetailActivity.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
/** detailReminder Btn Edit Click Listener */
public void detailReminderBtnEditClickListener(View view) {
Intent intent = new Intent(this, AddReminder.class);
if (reminderId != null) {
intent.putExtra(REMINDER_ID, reminderId);
}
startActivity(intent);
finish();
}
}
| true |
b5bac780d8c3e5437ace3d6492274b39a9b09998
|
Java
|
qiangshuifish/tiny-spring-annotation
|
/src/test/java/xin/qiangshuidiyu/spring/context/AnnotationApplicationContextTest.java
|
UTF-8
| 1,871 | 2.453125 | 2 |
[] |
no_license
|
package xin.qiangshuidiyu.spring.context;
import org.junit.Test;
import xin.qiangshuidiyu.spring.test.app.HelloWorldService;
import xin.qiangshuidiyu.spring.test.app.OutputService;
import xin.qiangshuidiyu.spring.test.app.impl.HelloWorldServiceImpl;
import xin.qiangshuidiyu.spring.test.app.impl.OutputServiceImpl;
public class AnnotationApplicationContextTest {
@Test
public void test() throws Exception {
AbstractApplicationContext applicationContext = new AnnotationApplicationContext("xin");
HelloWorldServiceImpl helloWorldServiceImpl = applicationContext.getBean("helloWorldServiceImpl");
OutputServiceImpl outputServiceImpl = applicationContext.getBean("outputServiceImpl");
HelloWorldServiceImpl helloWorldServiceImpl1 = applicationContext.getBean(HelloWorldServiceImpl.class);
OutputServiceImpl outputServiceImpl1 = applicationContext.getBean(OutputServiceImpl.class);
helloWorldServiceImpl.helloWorld();
outputServiceImpl.output();
helloWorldServiceImpl.output();
helloWorldServiceImpl1.helloWorld();
helloWorldServiceImpl.output();
outputServiceImpl1.output();
}
@Test
public void testScope() throws Exception {
AbstractApplicationContext applicationContext = new AnnotationApplicationContext("xin");
HelloWorldService helloWorldService1 = applicationContext.getBean(HelloWorldServiceImpl.class);
HelloWorldService helloWorldService2 = applicationContext.getBean(HelloWorldServiceImpl.class);
System.out.println(helloWorldService1 == helloWorldService2);
OutputService outputService1 = applicationContext.getBean(OutputServiceImpl.class);
OutputService outputService2 = applicationContext.getBean(OutputServiceImpl.class);
System.out.println(outputService1 == outputService2);
}
}
| true |
2649d560be9b75262d911a2c13dfbf598dccf33f
|
Java
|
bazelbuild/bazel
|
/src/main/java/com/google/devtools/build/lib/vfs/AbstractFileSystemWithCustomStat.java
|
UTF-8
| 2,017 | 2.203125 | 2 |
[
"Apache-2.0"
] |
permissive
|
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// 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.google.devtools.build.lib.vfs;
import java.io.IOException;
/**
* An {@link AbstractFileSystem} that provides default implementations of {@link FileSystem#isFile}
* et al. in terms of {@link FileSystem#stat} (rather than the other way around, which is what
* {@link FileSystem} does).
*/
public abstract class AbstractFileSystemWithCustomStat extends AbstractFileSystem {
public AbstractFileSystemWithCustomStat(DigestHashFunction hashFunction) {
super(hashFunction);
}
@Override
protected boolean isFile(PathFragment path, boolean followSymlinks) {
FileStatus stat = statNullable(path, followSymlinks);
return stat != null ? stat.isFile() : false;
}
@Override
protected boolean isSpecialFile(PathFragment path, boolean followSymlinks) {
FileStatus stat = statNullable(path, followSymlinks);
return stat != null ? stat.isSpecialFile() : false;
}
@Override
protected boolean isSymbolicLink(PathFragment path) {
FileStatus stat = statNullable(path, false);
return stat != null ? stat.isSymbolicLink() : false;
}
@Override
protected boolean isDirectory(PathFragment path, boolean followSymlinks) {
FileStatus stat = statNullable(path, followSymlinks);
return stat != null ? stat.isDirectory() : false;
}
@Override
protected abstract FileStatus stat(PathFragment path, boolean followSymlinks) throws IOException;
}
| true |
e76bf99ce0858df05bb22715d93878323a92efc5
|
Java
|
jvadi/Java
|
/Day 16/Temperature Averages/src/TemperatureAverage.java
|
UTF-8
| 1,444 | 3.171875 | 3 |
[] |
no_license
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class TemperatureAverage {
final String DELIMITER = ",";
//Reader - gets line (String)
//ReadLine(String
//Split tokens
//Parse tokens as ints
//Average and count tokens
//returns int[av][num]
//Adds to int[][]
public void launch(String filename){
String line;
String[] tokens;
List temperatureRecords = new ArrayList();
BufferedReader reader = null;
try{
FileReader in = new FileReader(filename);
reader = new BufferedReader(in);
while (((line = reader.readLine()) != null)){
temperatureRecords.add(this.parseLine(line));
}
this.printRecords(temperatureRecords);
}catch (FileNotFoundException ex){
System.out.println("No such file '"+filename+"'");
} catch (IOException ex) {
ex.printStackTrace();
}finally{
try{
if (reader != null)
reader.close();
}catch (IOException ex){
ex.printStackTrace();
}
}
}
private void printRecords(List temperatureRecords) {
// TODO Auto-generated method stub
}
private int[] parseLine(String line) {
int[] result = new int[2];
String[] tokens = line.split(DELIMITER);
//TODO - Add in a splitter here
return result;
}
}
| true |
7ce4f331467cf32e33c997778ddced2d0177eef6
|
Java
|
changyupahn/NeoPlatech
|
/NeoPlatech/src/main/java/boassoft/service/impl/ApprRqstServiceImpl.java
|
UTF-8
| 1,789 | 1.632813 | 2 |
[] |
no_license
|
package boassoft.service.impl;
import javax.annotation.Resource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.stereotype.Service;
import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;
import boassoft.mapper.ApprRqstMapper;
import boassoft.mapper.BatchMapper;
import boassoft.service.ApprRqstService;
import boassoft.util.CommonList;
import boassoft.util.CommonMap;
@Service("apprRqstService")
public class ApprRqstServiceImpl extends EgovAbstractServiceImpl implements ApprRqstService {
@Resource(name="ApprRqstMapper")
private ApprRqstMapper apprRqstMapper;
@Resource(name="BatchMapper")
private BatchMapper batchMapper;
@Override
public CommonList getApprRqstList(CommonMap cmap) throws Exception {
// TODO Auto-generated method stub
CommonList list = apprRqstMapper.getApprRqstList(cmap);
list.totalRow = apprRqstMapper.getApprRqstListCnt(cmap);
return list;
}
@Override
public CommonMap getApprRqstView(CommonMap cmap) throws Exception {
// TODO Auto-generated method stub
return apprRqstMapper.getApprRqstView(cmap);
}
@Override
public void insertApprRqst(CommonMap cmap) throws Exception {
// TODO Auto-generated method stub
apprRqstMapper.insertApprRqst(cmap);
}
@Override
public void updateApprRqst(CommonMap cmap) throws Exception {
// TODO Auto-generated method stub
apprRqstMapper.updateApprRqst(cmap);
}
@Override
public void deleteApprRqst(CommonMap cmap) throws Exception {
// TODO Auto-generated method stub
apprRqstMapper.deleteApprRqst(cmap);
}
@Override
public int updateApprRqstStatusCd(CommonMap cmap) throws Exception {
// TODO Auto-generated method stub
return batchMapper.updateApprRqst(cmap);
}
}
| true |
7f02d223b88233a7910a1875660153a5b8df6659
|
Java
|
wgd0813/jdbc-for-rdf3x
|
/src/cn/edu/ruc/iir/jdbc43x/Statement.java
|
UTF-8
| 6,376 | 2.546875 | 3 |
[] |
no_license
|
/*
* Connection.java 0.0.1 2013/04/04
* Copyright(C) 2013 db-iir RUC. All rights reserved.
*/
package cn.edu.ruc.iir.jdbc43x;
import java.sql.*;
/**
* This <code>Statement</code> implements the java.sql.Statement interface. It
* opens an input stream from rdf3xembedded and pass the stream as a parameter
* to the constructor of cn.edu.ruc.iir.ResultSet. So it does not load all the
* data into memory and does not cause a OutOfMemory error.
*
* @author Hank Bian ([email protected])
* @version 0.0.1, 2013/04/04
* @see java.sql.Statement
*/
// This work is licensed under the Creative Commons
// Attribution-Noncommercial-Share Alike 3.0 Unported License. To view a copy
// of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/
// or send a letter to Creative Commons, 171 Second Street, Suite 300,
// San Francisco, California, 94105, USA.
public final class Statement implements java.sql.Statement
{
// The connection
private Connection connection;
// Constructor
Statement(Connection connection)
{
this.connection = connection;
}
// Add to batch
public void addBatch(String sql) throws SQLException
{
throw new SQLException();
}
// Cancel the statment
public void cancel() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
// Clear the batch
public void clearBatch()
{
}
// Clear all warnings
public void clearWarnings()
{
}
// Release resources
public void close()
{
connection = null;
}
// Execute a statement
public boolean execute(String sql) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
// Execute a statment
public boolean execute(String sql, int autoGeneratedKeys)
throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
// Execute a statement
public boolean execute(String sql, int[] columnIndexes) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
// Execute a statement
public boolean execute(String sql, String[] columnNames)
throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
// Execute a batch
public int[] executeBatch() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
// Execute a query
private java.sql.ResultSet executeQueryInternal(String query,
FunctionCallback callback) throws SQLException
{
synchronized (connection)
{
// Send the query
connection.assertOpen();
connection.writeLine(query);
// Check the answer
String response = connection.readLine();
if (!("ok".equals(response)))
throw new SQLException(response);
// Header
String[] header = connection.readResultLine();
return new ResultSet(header, connection, callback);
}
}
// Execute a query
public java.sql.ResultSet executeQuery(String query) throws SQLException
{
return executeQueryInternal(query, null);
}
// Execute a query
public java.sql.ResultSet executeQueryWithFunctions(String query,
FunctionCallback functions) throws SQLException
{
return executeQueryInternal(query, functions);
}
// Execute a statement
public int executeUpdate(String sql) throws SQLException
{
executeQuery(sql);
return 0;
}
// Execute a statement
public int executeUpdate(String sql, int autoGeneratedKeys)
throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
// Execute a statment
public int executeUpdate(String sql, int[] columnIndexes)
throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
// Execute a statement
public int executeUpdate(String sql, String[] columnNames)
throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
// Get the connection
public java.sql.Connection getConnection()
{
return connection;
}
// Get the fetch direction
public int getFetchDirection()
{
return ResultSet.FETCH_FORWARD;
}
// Get the fetch size
public int getFetchSize()
{
return 0;
}
// Generated keys
public ResultSet getGeneratedKeys() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
// Maximum field size
public int getMaxFieldSize()
{
return 0;
}
// Maximum number of rows
public int getMaxRows()
{
return 0;
}
// Get more results
public boolean getMoreResults()
{
return false;
}
// Get mmore result
public boolean getMoreResults(int current)
{
return false;
}
// Query timeout
public int getQueryTimeout()
{
return 0;
}
// Results
public ResultSet getResultSet()
{
return null;
}
// Concurrency
public int getResultSetConcurrency()
{
return ResultSet.CONCUR_READ_ONLY;
}
// Holdability
public int getResultSetHoldability()
{
return ResultSet.CLOSE_CURSORS_AT_COMMIT;
}
// Scroll behavior
public int getResultSetType()
{
return ResultSet.TYPE_FORWARD_ONLY;
}
// Update count
public int getUpdateCount()
{
return 0;
}
// Warnings
public SQLWarning getWarnings()
{
return null;
}
// Closed
public boolean isClosed()
{
return connection == null;
}
// Poolable
public boolean isPoolable()
{
return false;
}
// Cursor name
public void setCursorName(String name) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
// Escape processing
public void setEscapeProcessing(boolean enable) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
// Fetch direction
public void setFetchDirection(int direction) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
// Fetch size
public void setFetchSize(int rows)
{
}
// Maximum field size
public void setMaxFieldSize(int max)
{
}
// Maximum number of rows
public void setMaxRows(int max)
{
}
// Poolable?
public void setPoolable(boolean poolable) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
// Query timeout
public void setQueryTimeout(int seconds) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
// Wrapper?
public boolean isWrapperFor(Class<?> iface)
{
return false;
}
// Unwrap
public <T> T unwrap(Class<T> iface) throws SQLException
{
throw new SQLException();
}
@Override
public void closeOnCompletion() throws SQLException
{
// TODO Auto-generated method stub
}
@Override
public boolean isCloseOnCompletion() throws SQLException
{
// TODO Auto-generated method stub
return false;
}
}
| true |
474ec47eb5a40017c3b3438f15c6d85f7b8febe3
|
Java
|
myuyang/MinaMaster
|
/ShootBallScreen/app/src/main/java/vitaliqp/shootballscreen/enums/CollectBallArea.java
|
UTF-8
| 338 | 1.703125 | 2 |
[] |
no_license
|
package vitaliqp.shootballscreen.enums;
/**
* 类名:vitaliqp.shootballscreen.enums
* 时间:2019/3/13 15:10
* 描述:
* 修改人:
* 修改时间:
* 修改备注:
*
* @author QP
*/
public enum CollectBallArea {
OUT_RIGHT,
OUT_LEFT,
OUT_UP_LEFT,
OUT_UP_RIGHT,
OUT_DOWN_LEFT,
OUT_DOWN_RIGHT
}
| true |
0ce8590e38235a7e96e572dd97c6e6f82a4ec6e8
|
Java
|
jrhenriquerf/PadroesDeProjetos
|
/FactoryMethod/src/FactoryMethod/FabricaDeAnimais.java
|
UTF-8
| 194 | 2.765625 | 3 |
[] |
no_license
|
package FactoryMethod;
public abstract class FabricaDeAnimais {
protected Animal animal;
public abstract void escolherAnimal(String tipo);
public Animal comprar() {
return animal;
}
}
| true |
77d3b341bd055b699f1512c74a6542592457c6f2
|
Java
|
qiangzh/easyDemo
|
/src/com/readline/ReadLineTest.java
|
UTF-8
| 1,466 | 2.8125 | 3 |
[] |
no_license
|
package com.readline;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.sf.cglib.core.CollectionUtils;
public class ReadLineTest {
public static void main(String[] args) throws Exception {
String filePath = "L:/workspace/Test/src/com/readline/Test.txt";
FileInputStream fileInputStream = new FileInputStream(filePath);
BufferedReader dr = new BufferedReader(new InputStreamReader(fileInputStream));
String str;
Map<String,String> map = new HashMap();
while ((str = dr.readLine()) != null) {
int start = "L:\\workspace\\tb_jituan\\".length();
int end = str.indexOf(".java(") + 5;
str = str.substring(start, end);
str = str.replace('\\', '/');
map.put(str, str);
}
List list = new ArrayList();
for(Iterator iter =map.entrySet().iterator();iter.hasNext();){
Entry entry = (Entry) iter.next();
list.add((String)entry.getKey());
}
Collections.sort(list);
for(Iterator iter =list.iterator();iter.hasNext();){
System.out.println(iter.next());
}
}
}
| true |
1f9ea82df55310fb392e30201f3cfbd5cd01338c
|
Java
|
SannikovDmitry/tower-defence-09-2016
|
/src/main/java/ru/agrage/project/Configurations/SecurityConfig.java
|
UTF-8
| 3,474 | 1.929688 | 2 |
[] |
no_license
|
package ru.agrage.project.Configurations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import ru.agrage.project.Service.CustomUserDetailsService;
@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = {"ru.agrage.project.Service"})
@EnableRedisHttpSession
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("customUserDetailsService")
CustomUserDetailsService customUserDetailsService;
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/admin/**").access("hasRole('admin')")
.antMatchers("/api/user/login/").permitAll()
.antMatchers("/api/user/registration/").permitAll()
.antMatchers("/api/user/logout/").access("hasRole('user') or hasRole('admin')")
.antMatchers("/api/user/rating/").access("hasRole('user') or hasRole('admin')")
.antMatchers("/api/user/session/").access("hasRole('user') or hasRole('admin')");
http.csrf().disable();
http
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/api/user/**"
).permitAll();
http
.headers().disable();
http
.sessionManagement();
}
@Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
// Cors
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("https://towerdefensepvp.herokuapp.com", "https://91.78.137.174:3000", "https://127.0.0.1:3000");
}
};
}
}
| true |
7bfb3760dc486ea70150e617377a9db9d0ae957d
|
Java
|
kHRYSTAL/CameraDemo
|
/app/src/main/java/me/khrystal/camerademo/MainActivity.java
|
UTF-8
| 9,789 | 2.328125 | 2 |
[] |
no_license
|
package me.khrystal.camerademo;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, SurfaceHolder.Callback, Camera.ShutterCallback, Camera.PictureCallback {
SurfaceView sfcPreview;
Button btnWrite;
Button btnShutter;
Button btnFlash;
/** 睡眠时间 */
protected static final long SLEEP_TIME = 50;
/** 初始化相机 */
protected static final int MSG_ID_CAMERA_START = 0x01;
/** 释放相机资源 */
protected static final int MSG_ID_CAMERA_STOP = 0x2;
boolean mIsActivityTeady = false;
boolean mIsSurfaceTeady = false;
SurfaceHolder mHolder;
Camera.Parameters mParameters;
Camera mCamera;
/** 支持的闪光灯模式 */
List<String> mSupportFlash;
int mIndexFlash;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
uiInit();
}
private void uiInit() {
btnWrite = (Button)findViewById(R.id.btn_write);
btnFlash = (Button)findViewById(R.id.btn_flash);
btnShutter = (Button)findViewById(R.id.btn_shutter);
sfcPreview = (SurfaceView)findViewById(R.id.sfc_preview);
btnWrite.setOnClickListener(this);
btnShutter.setOnClickListener(this);
btnFlash.setOnClickListener(this);
sfcPreview.getHolder().addCallback(this);
sfcPreview.setOnClickListener(this);
mHolder = sfcPreview.getHolder();
}
/**
* 相机为SurfaceView 要跟随生命周期
*/
@Override
protected void onStart() {
super.onStart();
mIsActivityTeady = true;
mHandler.sendEmptyMessage(MSG_ID_CAMERA_START);
}
@Override
protected void onStop() {
super.onStop();
mIsActivityTeady = false;
mHandler.sendEmptyMessage(MSG_ID_CAMERA_STOP);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_flash:
int index = (mIndexFlash + 1) % mSupportFlash.size();
String mode = mSupportFlash.get(index);
// 将新的闪光灯模式设置到参数中
mParameters.setFlashMode(mode);
// 设置参数到照相机上
mCamera.setParameters(mParameters);
refreshFlashMode();
break;
case R.id.btn_shutter:
/*
* shutter:快门回调,在按下快门的瞬间会调用此接口中的方法, 常用于播放自定义的快门
* raw:照片回调,将未经处理的最原始的照片数据信息传递给此接口
* postview:照片回调,将经过一定处理的照片数据信息传递给此接口 此处理一般是经过硬件处理,所以部分手机可能不支持。
* jpeq 照片回调 :将经过较大压缩的照片数据传递给此接口。最常用的接口
*/
mCamera.takePicture(this, null, null, this);
break;
case R.id.btn_write:
//TODO 跳转至其他页面
Toast.makeText(this, "跳转至其他页面", Toast.LENGTH_SHORT).show();
break;
case R.id.sfc_preview:
//调用autoFocus方法可以进行自动对焦
//参数是个回调,用于确认对焦是否成功,如果无需知道对焦是否成功,设置为null
mCamera.autoFocus(null);
break;
default:
break;
}
}
// SurfaceView callback method start---->
@Override
public void surfaceCreated(SurfaceHolder holder) {
mIsSurfaceTeady = true;
mHandler.sendEmptyMessage(MSG_ID_CAMERA_START);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mIsSurfaceTeady = false;
mHandler.sendEmptyMessage(MSG_ID_CAMERA_STOP);
}
// SurfaceView callback method end --->
// Camera implements method callback start----->
/**
* @param data
* 字节数组,包含照片的数据
* @param camera
* 刚进行拍照的相机
* */
@Override
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream fos = null;
// 用于创建临时文件
try {
File file = File.createTempFile("DCIM", ".tmp");
fos = new FileOutputStream(file);
fos.write(data);
// TODO 页面跳转
Intent intent = new Intent(this, BitmapTransformActivity.class);
intent.putExtra("path", file.getAbsolutePath());
startActivity(intent);
finish();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 快门按下回调
*/
@Override
public void onShutter() {
}
// Camera implements method callback end------>
private void startCamera() {
// 如果相机在短时间内重复打开,先关闭一下就不会出错了;
stopCamera();
// 可以得到摄像头的个数;此方法的返回值-1是Open方法的最大值;
// Camera.getNumberOfCameras();
// 不带参数 打开默认摄像头;如果带int参数表示打开指定的摄像头
// 一般0表示的后置摄像头,1表示前置后置摄像头
mCamera = Camera.open();
mCamera.setDisplayOrientation(90);
mParameters = mCamera.getParameters();
// getMaxZoom得到最大的比例
mSupportFlash = mParameters.getSupportedFlashModes();
//adapteration
List<Camera.Size> supportedPreviewSizes = mParameters.getSupportedPreviewSizes();
Camera.Size previewSize = supportedPreviewSizes.get(getPictureSize(supportedPreviewSizes));
mParameters.setPreviewSize(previewSize.width, previewSize.height);
List<Camera.Size> supportedPictureSizes = mParameters.getSupportedPictureSizes();
Camera.Size pictureSize = supportedPictureSizes.get(getPictureSize(supportedPictureSizes));
mParameters.setPictureSize(pictureSize.width, pictureSize.height);
mCamera.setParameters(mParameters);
//
refreshFlashMode();
try {
mCamera.setPreviewDisplay(mHolder);
} catch (IOException ex) {
ex.printStackTrace();
}
// 开始捕获图像进行预览
mCamera.startPreview();
}
/** 刷新闪光灯按钮上的图片状态 */
private void refreshFlashMode() {
// 得到当前的闪光灯状态
String mode = mParameters.getFlashMode();
// 得到当前闪光灯模式在列表中的下标;
mIndexFlash = mSupportFlash.indexOf(mode);
if ("off".equals(mode)) {
Toast.makeText(this,"关闭闪关灯",Toast.LENGTH_SHORT).show();
} else if ("on".equals(mode)) {
Toast.makeText(this,"开启闪关灯",Toast.LENGTH_SHORT).show();
} else if ("auto".equals(mode)) {
Toast.makeText(this,"自动",Toast.LENGTH_SHORT).show();
}
}
private void stopCamera() {
if (mCamera != null) {
// 停止预览
mCamera.stopPreview();
// 释放相机资源
mCamera.release();
}
mCamera = null;
}
Handler mHandler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case MSG_ID_CAMERA_START: {
if (mIsActivityTeady && mIsSurfaceTeady) {
startCamera();
} else if (mIsActivityTeady || mIsSurfaceTeady) {
// 移除其他正在等待的消息,即同时只能有一个消息在等待;
removeMessages(MSG_ID_CAMERA_START);
sendEmptyMessageDelayed(MSG_ID_CAMERA_START, SLEEP_TIME);
}
break;
}
case MSG_ID_CAMERA_STOP: {
removeMessages(MSG_ID_CAMERA_START);
removeMessages(MSG_ID_CAMERA_STOP);
stopCamera();
break;
}
default:
break;
}
}
};
private int getPictureSize(List<Camera.Size> sizes) {
WindowManager wm = this.getWindowManager();
int screenWidth = wm.getDefaultDisplay().getWidth();
// 屏幕的宽度
int index = -1;
for (int i = 0; i < sizes.size(); i++) {
if (Math.abs(screenWidth - sizes.get(i).width) == 0) {
index = i;
break;
}
}
// 当未找到与手机分辨率相等的数值,取列表中间的分辨率
if (index == -1) {
index = sizes.size() / 2;
}
return index;
}
}
| true |
4686714d78d2f1354c0af31858f673b720343275
|
Java
|
georgeYanch/Bank
|
/src/main/java/Clerk.java
|
WINDOWS-1251
| 2,944 | 3.359375 | 3 |
[] |
no_license
|
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import java.io.FileWriter;
import java.io.IOException;
/** {@link Client},
* - Department.
* {@link Thread}
* run() .
* <pre>
* {@code public void run(){
synchronized(field){
//...
* }
* }
*</pre>
*
* @author George Luckyanchikov
* @version 1.0
* @see Department
* @see Client
* @see Thread
* @throws IOEcxeption
* @throws InterruptedException
*
*/
public class Clerk extends Thread {
private static final Logger log = LogManager.getLogger(Clerk.class);
private Client client;
private FileWriter fw;
private int number;
private int income;
public final int salary = 300;
public Clerk(int number, Client client, int income, FileWriter fw){
this.number = number;
this.client = client;
this.income = income;
this.fw = fw;
log.info(" ");
}
public ThreadGroup getThreads(){
return this.getThreadGroup();
}
public void setIncome(int income){
this.income = income;
}
public int getIncome(){
return income;
}
public int getNumber(){
return number;
}
@Override
public void run(){
log.warn("[ ] ...");
synchronized(client){
synchronized(Time.class){
synchronized(fw){
if(Time.hours >= 16){
log.warn(" !");
return;
}
if(!Thread.currentThread().isInterrupted()){
log.info("...");
Time.addLocalTime(client.getRequest().getInTime());
String s = "| " + this.getNumber() + "| " + client.toString() + " " + this.getIncome() + ".";
try{
fw.write("\r\n : " + Time.getTime());
fw.write("\r\n" + s);
Time.addLocalTime(client.getRequest().getOutTime());
fw.write("\r\n : " + Time.getTime());
fw.write("\r\n_______________________________________________________________________________________________________________________");
}catch (IOException e){
log.error("Troubles with I/O processing![X]");
e.printStackTrace();
}
log.info(s);
log.warn(" " + this.getNumber() + " \n");
}else try {
log.error("Clerk's tread was interrupted![X]");
throw new InterruptedException();
} catch (InterruptedException e) {
log.fatal("Thread crushed![X]");
e.printStackTrace();
}
}
}
}
}
}
| true |
c3313e0c01d5441693ef3047977d455cf42088c5
|
Java
|
imuqshid/giira-final
|
/app/src/main/java/gira/cdap/com/giira/Task/TaskgetReviews.java
|
UTF-8
| 3,588 | 1.96875 | 2 |
[] |
no_license
|
package gira.cdap.com.giira.Task;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import gira.cdap.com.giira.Service.JSONParser;
import gira.cdap.com.giira.Service.ServiceHandler;
import gira.cdap.com.giira.one_place;
/**
* Created by Perceptor on 6/13/2016.
*/
public class TaskgetReviews extends AsyncTask<String, Void, String> {
ServiceHandler serviceHandler;
InputStream is;
JSONParser parsing;
Context context;
JSONObject json;
one_place one;
String placeid;
String comment;
ProgressDialog prgDialog;
ArrayList<reviews> reviewsArrayList;
// TextView allcomments;
String allcomm;
public TaskgetReviews(Context context, String placeid, one_place one)
{
this.one=one;
this.context = context;
this.placeid=placeid;
}
@Override
protected void onPreExecute(){
super.onPreExecute();
prgDialog = new ProgressDialog(one);
prgDialog.setMessage("Please Wait, Fetching Details..");
prgDialog.setIndeterminate(false);
prgDialog.setCancelable(false);
prgDialog.show();
}
@Override
protected String doInBackground(String... params) {
String result = null;
List<NameValuePair> value = new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("place_id",null));
serviceHandler = new ServiceHandler();
is = serviceHandler.makeServiceCall(serverURL.local_host_url+"giira/index.php/places/getcomments?place_id="+placeid,1,value);
parsing = new JSONParser();
try {
json = parsing.getJSONFromResponse(is);
result = String.valueOf(json.getBoolean("response"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
prgDialog.hide();
JSONArray reviews;
JSONArray Serviceid;
List<String> servicesL = new ArrayList<String>();
String[] servicesA = null;
List<String> serviceidsL = new ArrayList<String>();
String[] serviceidsA = null;
try {
reviewsArrayList = new ArrayList<reviews>();
reviews = json.getJSONArray("Reviews");
for (int i = 0; i < reviews.length(); i++) {
JSONObject object=reviews.getJSONObject(i);
reviews reviews1=new reviews();
reviews1.setName(object.getString("user"));
reviews1.setDate(object.getString("Commentdate"));
reviews1.setRating((float)object.getDouble("starsRating"));
reviews1.setComment(object.getString("comment"));
reviews1.setUserimage(object.getString("thumb"));
reviewsArrayList.add(reviews1);
}
one.setreviews(reviewsArrayList);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true |
aa40f487579065430f37744da0412b87f3804cad
|
Java
|
islonik/VFS
|
/client/src/test/java/org/vfs/client/network/UserManagerTest.java
|
UTF-8
| 1,045 | 2.359375 | 2 |
[] |
no_license
|
package org.vfs.client.network;
import org.junit.Assert;
import org.junit.Test;
import org.vfs.core.VFSConstants;
import org.vfs.core.network.protocol.Protocol;
/**
* @author Lipatov Nikita
*/
public class UserManagerTest {
@Test
public void testSetUser() {
UserManager userManager = new UserManager();
Protocol.User user1 = Protocol.User.newBuilder()
.setId(VFSConstants.NEW_USER)
.setLogin("nikita")
.build();
userManager.setUser(user1);
Assert.assertTrue(userManager.isAuthorized());
Assert.assertEquals("nikita", user1.getLogin());
Protocol.User user2 = Protocol.User.newBuilder()
.setId(VFSConstants.NEW_USER)
.setLogin("r2d2")
.build();
userManager.setUser(user2);
Assert.assertTrue(userManager.isAuthorized());
Assert.assertEquals("r2d2", user2.getLogin());
userManager.setUser(null);
Assert.assertFalse(userManager.isAuthorized());
}
}
| true |
bcc857af1a37d532d2609b2ae817837d37bf04c6
|
Java
|
pavneet3/coding-practice
|
/src/tst/khabri/FirstNonRepeatingInStream.java
|
UTF-8
| 582 | 3.1875 | 3 |
[] |
no_license
|
package tst.khabri;
import java.util.LinkedHashMap;
public class FirstNonRepeatingInStream {
static void nonRepeatingInStream(char a[]) {
LinkedHashMap<Character, Integer> m = new LinkedHashMap<>();
for (int i = 0; i < a.length; i++) {
if (m.containsKey(a[i])) {
m.remove(a[i]);
} else {
m.put(a[i], null);
}
char r = '\t';
for (Character k : m.keySet()) {
r = k;
break;
}
System.out.print(r == '\t' ? -1 : r + " ");
}
}
public static void main(String[] args) {
nonRepeatingInStream(new char[] { 'a', 'a', 'b', 'c', 'b' });
}
}
| true |
4a9cc616456bf00988d535b96e996670a50a2002
|
Java
|
Xuinaga/Program20-21
|
/UD-3/Buscaminas/BuscaminasV3/src/model/Hasiera.java
|
UTF-8
| 8,035 | 2.46875 | 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 model;
import exekutagarriak.Puntuazioak;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* Jokua irekitzean agertzen den menua eta bere akzioak sortzen ditu
*
* @author peralta.laura
*/
public class Hasiera extends JFrame implements ActionListener {
private JPanel menua;
private int tamaina = 8;
private JButton hasiJolasten;
private JButton tamainaAldatu;
private JButton irten;
private JLabel titulua;
private JTextField tamainaBerria;
private JButton aldatu;
private JFrame frame;
private JLabel baloreaGaizki;
private JLabel zelaiTamaina;
private JFrame jokalaria;
private JButton izenaSartu;
private JButton jokalarienDenbora;
private JTextField izenaHartu;
private Puntuazioak ireki;
;
/**
* Hasiera konstruktorea, initPanel() eta initMenua() metodoei deitzen die
*/
public Hasiera() {
this.ireki = new Puntuazioak();
initPanel();
initMenua();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public Hasiera(int tamaina) {
this.ireki = new Puntuazioak();
this.tamaina = tamaina;
initPanel();
initMenua();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
/**
* jokuaren menuko panela sortzen duen metodoa
*/
public void initPanel() {
menua = new JPanel();
add(menua);
menua.setLayout(null);
setTitle("MENUA");
setSize(500, 500);
setLocationRelativeTo(null);
setAlwaysOnTop(true);
setVisible(true);
}
/**
* menuko panelaren barruan egongo diren elementuak sortzen dituen metodoa
*/
public void initMenua() {
Color darkGreen = new Color(0, 102, 0);
titulua = new JLabel();
titulua.setText("COVID-19 BILATU");
titulua.setFont(new Font("Arial", Font.BOLD, 22));
titulua.setForeground(darkGreen);
titulua.setBounds(150, 25, 300, 50);
menua.add(titulua);
hasiJolasten = new JButton("JOLASTU");
hasiJolasten.setFont(new Font("Arial", Font.BOLD, 14));
hasiJolasten.setSize(100, 50);
hasiJolasten.setLocation(200, 100);
hasiJolasten.addActionListener(this);
menua.add(hasiJolasten);
tamainaAldatu = new JButton("TAMAINA ALDATU");
tamainaAldatu.setFont(new Font("Arial", Font.BOLD, 14));
tamainaAldatu.setSize(200, 50);
tamainaAldatu.setLocation(150, 175);
tamainaAldatu.addActionListener(this);
menua.add(tamainaAldatu);
jokalarienDenbora = new JButton("JOKALARIEN DENBORA");
jokalarienDenbora.setFont(new Font("Arial", Font.BOLD, 14));
jokalarienDenbora.setSize(200, 50);
jokalarienDenbora.setLocation(150, 250);
jokalarienDenbora.addActionListener(this);
menua.add(jokalarienDenbora);
irten = new JButton("IRTEN");
irten.setFont(new Font("Arial", Font.BOLD, 14));
irten.setSize(100, 50);
irten.setLocation(200, 325);
irten.addActionListener(this);
menua.add(irten);
JLabel aukeratutakoTamaina = new JLabel("JOLASAREN TAMAINA: ");
aukeratutakoTamaina.setFont(new Font("Arial", Font.BOLD, 14));
aukeratutakoTamaina.setBounds(150, 375, 175, 50);
menua.add(aukeratutakoTamaina);
zelaiTamaina = new JLabel("" + tamaina);
zelaiTamaina.setFont(new Font("Arial", Font.BOLD, 14));
zelaiTamaina.setBounds(310, 375, 100, 50);
menua.add(zelaiTamaina);
}
/**
* Aldatu botoian klikatzean irekitzen den menua sortzen du
*/
public void tamainaAldatu() {
frame = new JFrame();
frame.setSize(500, 250);
frame.setLayout(null);
baloreaGaizki = new JLabel("TAMAINAREN BALIOA 8-25 IZAN BEHAR DA!");
baloreaGaizki.setFont(new Font("Arial", Font.BOLD, 14));
baloreaGaizki.setForeground(Color.red);
baloreaGaizki.setBounds(100, 15, 300, 50);
baloreaGaizki.setVisible(false);
frame.add(baloreaGaizki);
JLabel testua = new JLabel("SARTU TAMAINA: ");
testua.setFont(new Font("Arial", Font.BOLD, 14));
testua.setBounds(125, 50, 150, 50);
frame.add(testua);
tamainaBerria = new JTextField();
tamainaBerria.setFont(new Font("Arial", Font.PLAIN, 14));
tamainaBerria.setSize(50, 25);
tamainaBerria.setLocation(260, 65);
frame.add(tamainaBerria);
aldatu = new JButton("ALDATU");
aldatu.setFont(new Font("Arial", Font.BOLD, 14));
aldatu.addActionListener(this);
aldatu.setSize(100, 30);
aldatu.setLocation(200, 125);
frame.add(aldatu);
frame.setLocationRelativeTo(null);
frame.setAlwaysOnTop(true);
frame.setVisible(true);
}
public void izenaSartu() {
jokalaria = new JFrame();
jokalaria.setSize(500, 250);
jokalaria.setLayout(null);
JLabel testua = new JLabel("SARTU ZURE IZENA: ");
testua.setFont(new Font("Arial", Font.BOLD, 14));
testua.setBounds(125, 50, 150, 50);
jokalaria.add(testua);
izenaHartu = new JTextField();
izenaHartu.setFont(new Font("Arial", Font.PLAIN, 14));
izenaHartu.setSize(100, 25);
izenaHartu.setLocation(260, 65);
jokalaria.add(izenaHartu);
izenaSartu = new JButton("SARTU");
izenaSartu.setFont(new Font("Arial", Font.BOLD, 14));
izenaSartu.addActionListener(this);
izenaSartu.setSize(100, 30);
izenaSartu.setLocation(200, 125);
jokalaria.add(izenaSartu);
jokalaria.setLocationRelativeTo(null);
jokalaria.setAlwaysOnTop(true);
jokalaria.setVisible(true);
}
/**
* botoiei klikatzean gertatzen diren akzioak
*
* @param e klikatzen den elementua hartzen du
*/
@Override
public void actionPerformed(ActionEvent e) {
Object eventSource = e.getSource();
JButton klikatutakoBotoia = (JButton) eventSource;
if (klikatutakoBotoia == hasiJolasten && !(ireki.isVisible())) {
izenaSartu();//Eskatu erabiltzaileari bere izena
this.setVisible(false);
} else if (ireki.isVisible() && klikatutakoBotoia == hasiJolasten) {
JOptionPane.showMessageDialog(menua, "Lehioak itxi behar dituzu!");
} else if (klikatutakoBotoia == izenaSartu) {
Jokua j = new Jokua(tamaina); //joku berri bat sortzen du emandako tamainarekin
j.setIzena(izenaHartu.getText());
jokalaria.setVisible(false);
} else if (klikatutakoBotoia == tamainaAldatu && (frame == null || frame.isVisible() == false)) {
this.setVisible(false);
tamainaAldatu();
} else if (klikatutakoBotoia == aldatu) {
try {
if (!(Integer.parseInt(tamainaBerria.getText()) >= 8 && Integer.parseInt(tamainaBerria.getText()) <= 25)) {
baloreaGaizki.setVisible(true);
} else {
tamaina = Integer.parseInt(tamainaBerria.getText());
zelaiTamaina.setText("" + tamaina);
frame.setVisible(false);
this.setVisible(true);
}
} catch (NumberFormatException x) {
baloreaGaizki.setVisible(true);
}
} else if (klikatutakoBotoia == jokalarienDenbora && !(ireki.isVisible())) {
ireki.setVisible(true);
} else if (klikatutakoBotoia == irten) {
System.exit(0);
}
}
}
| true |
e27acfc803993f213a9ce3c0bcef0fef0bdf3c68
|
Java
|
mitsumizo/collectingNews
|
/src/main/java/jp/co/etc/benesse/db/ConnectionManager.java
|
UTF-8
| 1,590 | 2.875 | 3 |
[] |
no_license
|
package jp.co.etc.benesse.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManager {
private Connection connection;
static {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException("ドライバのロードに失敗しました。", e);
}
}
public Connection getConnection() {
if(this.connection == null) {
try {
String url = "jdbc:postgresql://localhost:5432/news_scrayping";
String user = "mitsumizo_news";
String password = "Yamaguchi.eiji5752";
this.connection = DriverManager.getConnection(url, user, password);
this.connection.setAutoCommit(false);
} catch (SQLException e) {
throw new RuntimeException("データベースの接続に失敗しました。", e);
}
}
return connection;
}
public void closeConnection() {
try {
if (this.connection != null) {
this.connection.close();
}
} catch (SQLException e) {
throw new RuntimeException("データベースの切断に失敗しました。", e);
}
}
public void commit() {
try {
if(this.connection != null) {
this.connection.commit();
}
} catch (SQLException e) {
throw new RuntimeException("トランザクションのコミットに失敗しました。", e);
}
}
public void rollback() {
try {
if(this.connection != null) {
this.connection.rollback();
}
} catch (SQLException e) {
throw new RuntimeException("トランザクションのロールバックに失敗しました。", e);
}
}
}
| true |
81d78cd5f8a85c3252e6a4ce7880257fb8aaeb9f
|
Java
|
amargeu/DataStructure
|
/practice/src/practice/countEO.java
|
UTF-8
| 298 | 2.890625 | 3 |
[] |
no_license
|
package practice;
public class countEO
{
public static void main(String[] args)
{
int n=8795243;
int ce=0,co=0;
while(n>0)
{
int rem=n%10;
if(rem%2==0)
ce++;
else
co++;
n=n/10;
}
System.out.println(ce);
System.out.println(co);
}
}
| true |
7c853dccac11b9c1d0e8a294fed3dc03942a0b19
|
Java
|
hinnn012/3343_13
|
/Exception/CannotPassYourOwnLoopException.java
|
UTF-8
| 425 | 2.578125 | 3 |
[] |
no_license
|
package Exception;
public class CannotPassYourOwnLoopException extends Exception {
private String lastValidPlayer;
public CannotPassYourOwnLoopException(String lastValidPlayer){
this.lastValidPlayer = lastValidPlayer;
}
public String getLastValidPlayer(){
return lastValidPlayer;
}
}
/*
InputMoreThanHands
InputCannotBeNull
InputNotValid
InvalidPattern
InvalidRank
CannotPassYourOwnLoop
*/
| true |
212ff770b084c76c580d706d1c2f527d086fc608
|
Java
|
amr-rabbie/baghdadmunicipality
|
/app/src/main/java/com/unicomg/baghdadmunicipality/Views/login/LoginActivity.java
|
UTF-8
| 8,393 | 1.820313 | 2 |
[] |
no_license
|
package com.unicomg.baghdadmunicipality.Views.login;
import android.app.Dialog;
import android.content.ClipData.Item;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.material.textfield.TextInputEditText;
import com.unicomg.baghdadmunicipality.R;
import com.unicomg.baghdadmunicipality.Views.froget_password.ForgetPasswordActivity;
import com.unicomg.baghdadmunicipality.Views.mainscreen.MainActivity;
import com.unicomg.baghdadmunicipality.di.DaggerApplication;
import com.unicomg.baghdadmunicipality.helper.ConnectivityReceiver;
import com.unicomg.baghdadmunicipality.helper.Constants;
import java.util.ArrayList;
import javax.inject.Inject;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
public class LoginActivity extends AppCompatActivity implements LoginView, ConnectivityReceiver.ConnectivityReceiverListener {
@Inject
LoginPresenter loginPresenter;
TextInputEditText edit_user_name,edtPass;
Button btn_login;
ProgressBar pbar;
LinearLayout ll;
private static final int PERMISSION_REQUEST_CODE = 200;
private Dialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
edit_user_name=findViewById(R.id.edt_un);
edtPass=findViewById(R.id.edt_pw);
btn_login=findViewById(R.id.btn_login);
pbar=findViewById(R.id.pbar);
ll=findViewById(R.id.ll);
dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setTitle("تحميل البيانات .....");
dialog.setContentView(R.layout.custom_dialog);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
((DaggerApplication)getApplication()).getAppComponent().inject(this);
loginPresenter.onAttach(this);
DaggerApplication.getDaggerApplication().setConnectivityListener(this);
if (!checkPermission()) {
requestPermission();
}
if(! Constants.getuserId(this).isEmpty()){
Intent i=new Intent(this,MainActivity.class);
startActivity(i);
}
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email,pw;
email=edit_user_name.getText().toString();
pw=edtPass.getText().toString();
if(email.isEmpty() && pw.isEmpty()){
Toast.makeText(LoginActivity.this, "لابد من ادخال جميع الحقول ", Toast.LENGTH_SHORT).show();
}
else if(email.isEmpty()){
Toast.makeText(LoginActivity.this, "لابد من ادخال بريدك الالكترونى ", Toast.LENGTH_SHORT).show();
edit_user_name.setError("لابد من ادخال بريدك الالكترونى ");
}else if(pw.isEmpty()){
Toast.makeText(LoginActivity.this, "لابد من ادخال كلمة السر ", Toast.LENGTH_SHORT).show();
edtPass.setError("لابد من ادخال كلمة السر");
}else{
loginPresenter.getLogin(email,pw,ll,dialog);
}
}
});
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(LoginActivity.this)
.setMessage(message)
.setPositiveButton("تم", okListener)
.setNegativeButton("الغاء", null)
.create()
.show();
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0) {
boolean locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean cameraAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean readStorageAccepted = grantResults[2] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[3] == PackageManager.PERMISSION_GRANTED;
if (locationAccepted && cameraAccepted && readStorageAccepted && writeStorageAccepted)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION)) {
showMessageOKCancel("التطبيق يحتاج بعض الصلاحيات",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{ACCESS_FINE_LOCATION, CAMERA, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE},
PERMISSION_REQUEST_CODE);
}
}
});
return;
}
}
}
break;
}
}
@Override
public void showLoading() {
}
@Override
public void hideLoading() {
}
@Override
public void showMessage(String message, int mColor) {
Toast.makeText(LoginActivity.this, ""+message, Toast.LENGTH_SHORT).show();
}
@Override
public void updateList(ArrayList<Item> items) {
}
@Override
public void openProjectsActivity() {
Intent i=new Intent(this, MainActivity.class);
startActivity(i);
}
@Override
public void onAttache() {
}
@Override
public void onDetach() {
}
@Override
public void onNetworkConnectionChanged(boolean isConnected) {
loginPresenter.checkConnection(isConnected);
}
@Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_FINE_LOCATION);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA);
int result2 = ContextCompat.checkSelfPermission(getApplicationContext(), READ_EXTERNAL_STORAGE);
int result3 = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED &&
result2 == PackageManager.PERMISSION_GRANTED &&
result3 == PackageManager.PERMISSION_GRANTED;
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION, CAMERA, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
public void openForgetPasswordActivity(View view) {
startActivity(new Intent(LoginActivity.this, ForgetPasswordActivity.class));
}
}
| true |
422c0fe68c91b540a0d40b8fa8a54a9fdf5350cf
|
Java
|
yuhuangbin/lease
|
/src/main/java/com/lease/controller/ProductController.java
|
UTF-8
| 1,506 | 1.976563 | 2 |
[] |
no_license
|
package com.lease.controller;
import com.lease.api.ApiResponse;
import com.lease.domain.LeaseInfo;
import com.lease.domain.ProductInfo;
import com.lease.service.IProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* Description:
* author: yu.hb
* Date: 2018-12-01
*/
@RestController
@RequestMapping("/api/product")
public class ProductController {
@Autowired
private IProductService productService;
@RequestMapping("/buyList")
public ApiResponse buyList(@RequestBody ProductInfo productInfo) {
return ApiResponse.getInstance(productService.selectList(productInfo));
}
@RequestMapping("/save")
public ApiResponse save(@RequestBody ProductInfo productInfo) {
return productService.save(productInfo);
}
@RequestMapping("/del")
public ApiResponse del(Integer id) {
return productService.del(id);
}
@RequestMapping("/getByid")
public ApiResponse get(Integer id) {
ProductInfo productInfo = productService.getByid(id);
return ApiResponse.getInstance(productInfo);
}
@RequestMapping("/verify")
public ApiResponse verify(@RequestBody LeaseInfo leaseInfo) {
return productService.verify(leaseInfo);
}
}
| true |
b724b1fdb55e85c5f95a9fd2a6a08281c6ec0e11
|
Java
|
DevSunbo/hufs2021
|
/src/main/java/hufs2021/jeongbo/controller/apiXXXXXXX/TeamProjectController.java
|
UTF-8
| 7,354 | 2.265625 | 2 |
[] |
no_license
|
package hufs2021.jeongbo.controller.apiXXXXXXX;
import hufs2021.jeongbo.model.entity.TeamProject;
import hufs2021.jeongbo.network.Header;
import hufs2021.jeongbo.network.request.TeamProjectRequest;
import hufs2021.jeongbo.network.response.TeamProjectResponse;
import hufs2021.jeongbo.service.TeamProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/team-project")
public class TeamProjectController {
/*@Autowired
private TeamProjectRepository teamProjectRepository;*/
@Autowired
private TeamProjectService teamProjectService;
@PostMapping("/create")
@ResponseBody
public Header<TeamProjectResponse> create(@RequestBody TeamProjectRequest teamProjectRequest) {
/*TeamProject teamProject = TeamProject.builder()
.pField(teamProjectRequest.getPField())
.pName(teamProjectRequest.getPName())
.pMin(teamProjectRequest.getPMin())
.pMax(teamProjectRequest.getPMax())
.pDeadline(teamProjectRequest.getPDeadline())
.pMainLanguage(teamProjectRequest.getPMainLanguage())
.pLocation(teamProjectRequest.getPLocation())
.pContent(teamProjectRequest.getPContent())
.fId(teamProjectRequest.getFId())
.createdAt(LocalDateTime.now())
.createdBy(teamProjectRequest.getCreatedBy())
.studentId(teamProjectRequest.getStudentId())
.build();
TeamProject newTeamProject = teamProjectRepository.save(teamProject);
if(newTeamProject!=null)
return Header.OK();
else
return Header.ERROR();*/
return teamProjectService.create(teamProjectRequest);
}
@GetMapping("/readall")
@ResponseBody
public Header<TeamProjectResponse> readAll() {
/*List<TeamProject> teamProjectList = teamProjectRepository.findAll();
if (teamProjectList != null) {
teamProjectList.stream().forEach(teamProject -> {
System.out.println(teamProject.getPNumber());
System.out.println(teamProject.getPName());
System.out.println(teamProject.getPMin());
System.out.println(teamProject.getPMax());
System.out.println(teamProject.getPDeadline());
System.out.println(teamProject.getPMainLanguage());
System.out.println(teamProject.getPLocation());
System.out.println(teamProject.getPContent());
System.out.println(teamProject.getFId());
System.out.println(teamProject.getCreatedAt());
System.out.println(teamProject.getCreatedBy());
System.out.println(teamProject.getUpdatedAt());
System.out.println(teamProject.getUpdatedBy());
System.out.println(teamProject.getStudentId());
System.out.println("----------------------------------");
});
return Header.OK();
}
else
return Header.ERROR();*/
return teamProjectService.readAll();
}
@GetMapping("/read")
@ResponseBody
public Header<TeamProjectResponse> read(@RequestParam Integer number) {
/*return teamProjectRepository.findById(number)
.map(teamProject -> {
System.out.println(teamProject.getPNumber());
System.out.println(teamProject.getPName());
System.out.println(teamProject.getPMin());
System.out.println(teamProject.getPMax());
System.out.println(teamProject.getPDeadline());
System.out.println(teamProject.getPMainLanguage());
System.out.println(teamProject.getPLocation());
System.out.println(teamProject.getPContent());
System.out.println(teamProject.getFId());
System.out.println(teamProject.getCreatedAt());
System.out.println(teamProject.getCreatedBy());
System.out.println(teamProject.getUpdatedAt());
System.out.println(teamProject.getUpdatedBy());
System.out.println(teamProject.getStudentId());
return teamProject;
}).map(teamProject -> Header.OK(response(teamProject)))
.orElseGet(Header::ERROR);*/
return teamProjectService.read(number);
}
@PutMapping("/update")
@ResponseBody
public Header<TeamProjectResponse> update(@RequestBody TeamProjectRequest teamProjectRequest) {
/*return teamProjectRepository.findById(teamProjectRequest.getPNumber())
.map(teamProject -> {
teamProject.setPName(teamProjectRequest.getPName());
teamProject.setPMin(teamProjectRequest.getPMin());
teamProject.setPMax(teamProjectRequest.getPMax());
teamProject.setPDeadline(teamProjectRequest.getPDeadline());
teamProject.setPMainLanguage(teamProjectRequest.getPMainLanguage());
teamProject.setPLocation(teamProjectRequest.getPLocation());
teamProject.setPContent(teamProjectRequest.getPContent());
teamProject.setFId(teamProjectRequest.getFId());
teamProject.setUpdatedAt(LocalDateTime.now());
teamProject.setUpdatedBy(teamProjectRequest.getUpdatedBy());
return teamProject;
}).map(teamProject -> teamProjectRepository.save(teamProject))
.map(teamProject -> Header.OK(response(teamProject)))
.orElseGet(Header::ERROR);*/
return teamProjectService.update(teamProjectRequest);
}
@DeleteMapping("/delete")
@ResponseBody
public Header<TeamProjectResponse> delete(@RequestParam Integer number) {
/*Optional<TeamProject> teamProjectOptional = teamProjectRepository.findById(number);
teamProjectOptional.ifPresent(teamProject -> teamProjectRepository.delete(teamProject));
Optional<TeamProject> deletedTeamProject = teamProjectRepository.findById(number);
return Header.OK();*/
return teamProjectService.delete(number);
}
private TeamProjectResponse response(TeamProject teamProject) {
return TeamProjectResponse.builder()
.pNumber(teamProject.getProjectNumber())
.pField(teamProject.getPField())
.pName(teamProject.getPName())
.pMin(teamProject.getPMin())
.pMax(teamProject.getPMax())
.pDeadline(teamProject.getPDeadline())
.pMainLanguage(teamProject.getPMainLanguage())
.pLocation(teamProject.getPLocation())
.pContent(teamProject.getPContent())
.fId(teamProject.getFId())
.createdAt(teamProject.getCreatedAt())
.createdBy(teamProject.getCreatedBy())
.updatedAt(teamProject.getUpdatedAt())
.updatedBy(teamProject.getUpdatedBy())
.studentId(teamProject.getStudentId())
.build();
}
}
| true |
f11f2b99c455c2494d2918ded7d8f15a175d8985
|
Java
|
fabjj77/taurus
|
/taurus-integration/src/main/java/com/whitelabelled/service/delegate/impl/RetrieveCustomerDetailsImpl.java
|
UTF-8
| 3,807 | 1.84375 | 2 |
[] |
no_license
|
package com.whitelabelled.service.delegate.impl;
import static com.whitelabelled.util.QanSecurityConstants.QANTAS_COMPANY_CODE;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ibsplc.iloyal.common.type.WebServiceTransactionHeader;
import com.ibsplc.iloyal.customer.retrievecustomerprofile.type.RetrieveCustomerRequest;
import com.ibsplc.iloyal.customer.retrievecustomerprofile.type.RetrieveCustomerResponse;
import com.ibsplc.iloyal.customer.retrievecustomerprofile.wsdl.CustomerWebServiceException;
import com.ibsplc.iloyal.customer.retrievecustomerprofile.wsdl.RetrieveCustomer;
import com.ibsplc.iloyal.member.memberprofiledetail.v2_7.wsdl.MemberWebServiceException;
import com.whitelabelled.exception.CustomAquireException;
import com.whitelabelled.service.delegate.IFlyIntegrationService;
import com.whitelabelled.service.delegate.RetrieveCustomerDetails;
import com.whitelabelled.util.IFlyLoyaltyWSException;
import com.whitelabelled.util.QantasTaurusDateProvider;
@Service
public class RetrieveCustomerDetailsImpl implements RetrieveCustomerDetails {
private static final Logger LOGGER = Logger.getLogger(CreateServiceRequestServiceImpl.class);
@Autowired
private IFlyIntegrationService iFlyIntegrationService;
@Override
public RetrieveCustomerResponse retrieveCustomerDetailsForEmail(String email) throws CustomAquireException {
RetrieveCustomerRequest retrieveCustReq = new RetrieveCustomerRequest();
RetrieveCustomerResponse retrCustResponse = null;
retrieveCustReq = (RetrieveCustomerRequest) prepareRequestForEmail(retrieveCustReq, email);
try {
retrCustResponse = (RetrieveCustomerResponse) invokeIFlyService("retrieveCustomer", retrieveCustReq);
} catch (IFlyLoyaltyWSException e) {
LOGGER.error(" IFlyLoyaltyWSException in retrieveCustomerDetailsForEmail : "+e.getMessage());
throw new CustomAquireException(e.getErrorCode(), e.getErrorMessage(), e.getErrorCode());
} catch (MemberWebServiceException e) {
LOGGER.error(" MemberWebServiceException in retrieveCustomerDetailsForEmail : "+e.getMessage());
throw new CustomAquireException(e.getFaultInfo().getFaultcode(), e.getFaultInfo().getFaultstring(), e.getFaultInfo().getFaultcode());
} catch (CustomerWebServiceException e) {
LOGGER.error(" CustomerWebServiceException in retrieveCustomerDetailsForEmail : "+e.getMessage());
throw new CustomAquireException(e.getFaultInfo().getFaultcode(), e.getFaultInfo().getFaultstring(), e.getFaultInfo().getFaultcode());
}
return retrCustResponse;
}
public Object invokeIFlyService(String operation, Object request) throws IFlyLoyaltyWSException, MemberWebServiceException, CustomerWebServiceException {
RetrieveCustomerResponse retriveCustomerResponse = null;
RetrieveCustomer retriveCustomer = (RetrieveCustomer)(iFlyIntegrationService.getContext().getBean(operation));
retriveCustomer = (RetrieveCustomer)(iFlyIntegrationService.setClientSecurity(retriveCustomer));
retriveCustomerResponse = retriveCustomer.retrieveCustomer((RetrieveCustomerRequest)request);
return retriveCustomerResponse;
}
private RetrieveCustomerRequest prepareRequestForEmail(RetrieveCustomerRequest retrieveCustReq, String email)
{
retrieveCustReq.setCompanyCode(QANTAS_COMPANY_CODE);
retrieveCustReq.setCustomerNumber("");
retrieveCustReq.setMembershipNumber("");
retrieveCustReq.setPrefferedEmail(email);
WebServiceTransactionHeader txnHeader = new WebServiceTransactionHeader();
txnHeader.setTransactionID("");
txnHeader.setUserName("");
txnHeader.setTimeStamp(QantasTaurusDateProvider
.getXMLGregorianCalendarTimeStamp());
retrieveCustReq.setTxnHeader(txnHeader);
return retrieveCustReq;
}
}
| true |
e046be31ad1528391a3095b50332aa56267e3c2b
|
Java
|
zhangxuan999/androidlearning
|
/javatest/src/main/java/designmode/TestBuilder.java
|
GB18030
| 2,660 | 4.125 | 4 |
[] |
no_license
|
package designmode;
/**
* 1.buildģʽһι죬ΪһЩĬֵ
* 2.buildbuildһnew һproductbuilderIJ
*
* Աproductഴ캯ʣҵproductһι죬Ȼÿһsetͺˣʹ߲֪ЩDZشġnew productΪ
* product Ĺ캯˽еģbuilderǾ̬ڲ
*/
public class TestBuilder {
public static void main(String[] args) {
Product jocy = new Product.ProductBuilder().setData("1990-06-08").setId(1).setName("jocy").build();
System.out.println(jocy.toString());
Product build = new Product.ProductBuilder(jocy).build();
System.out.println(build.toString());
Product build1 = jocy.newBuilder().build();
System.out.println(build1.toString());
}
}
class Product{
int id;
String name;
String Data;
//ι
private Product(){
this(new ProductBuilder());
}
// builderΪĹ
private Product(ProductBuilder productBuilder) {
this.id = productBuilder.id;
this.name = productBuilder.name;
this.Data = productBuilder.Data;
}
//һproductbuilderԵǰIJ
public ProductBuilder newBuilder(){
return new ProductBuilder(this);
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getData() {
return Data;
}
@Override
public String toString() {
return "name:" + name + "data:" + Data +"id:"+id
;
}
static class ProductBuilder{
//Ĭϲ
public ProductBuilder(){
this.id = 0;
this.Data = "default";
this.name = "default";
}
//һprodtctĹ
public ProductBuilder(Product product){
this.id = product.id;
this.name = product.name;
this.Data = product.Data;
}
public ProductBuilder setId(int id) {
this.id = id;
return this;
}
public ProductBuilder setName(String name) {
this.name = name;
return this;
}
public ProductBuilder setData(String data) {
Data = data;
return this;
}
int id;
String name;
String Data;
public Product build(){
return new Product(this);
}
}
}
| true |
ffc256e71d4a43a9fe087dee6268de5f276921d0
|
Java
|
DmitryYusupov/epamjavacore
|
/src/main/java/ru/epam/javacore/lesson_24_db_web/homework/common/business/repo/CommonRepoHelper.java
|
UTF-8
| 553 | 2.34375 | 2 |
[] |
no_license
|
package ru.epam.javacore.lesson_24_db_web.homework.common.business.repo;
import ru.epam.javacore.lesson_24_db_web.homework.common.business.domain.BaseEntity;
import java.util.Optional;
public final class CommonRepoHelper {
private CommonRepoHelper() {
}
public static Optional<Integer> findEntityIndexInArrayStorageById(BaseEntity[] data, long entityId) {
for (int i = 0; i < data.length; i++) {
if (Long.valueOf(entityId).equals(data[i].getId())) {
return Optional.of(i);
}
}
return Optional.empty();
}
}
| true |
1861d44c546ca4d80970076cf2c7893f4c3158d5
|
Java
|
redmic-project/server-vessel-vessels
|
/vessels-lib/src/main/java/es/redmic/vesselslib/events/vesseltracking/VesselTrackingEventTypes.java
|
UTF-8
| 573 | 1.679688 | 2 |
[
"Apache-2.0"
] |
permissive
|
package es.redmic.vesselslib.events.vesseltracking;
import es.redmic.brokerlib.avro.common.EventTypes;
public abstract class VesselTrackingEventTypes extends EventTypes {
public static String
// @formatter:off
UPDATE_VESSEL = "UPDATE_VESSEL";
//@formatter:on
public static boolean isLocked(String eventType) {
return EventTypes.isLocked(eventType);
}
public static boolean isSnapshot(String eventType) {
return EventTypes.isSnapshot(eventType);
}
public static boolean isUpdatable(String eventType) {
return EventTypes.isUpdatable(eventType);
}
}
| true |
fedad85d5200f461d84033d331ef21de42b87755
|
Java
|
gspandy/dubbo_center_monitor
|
/src/main/java/com/lvmama/soa/monitor/util/biz/DubboDetailUtil.java
|
UTF-8
| 6,235 | 2.5625 | 3 |
[] |
no_license
|
package com.lvmama.soa.monitor.util.biz;
import java.io.BufferedReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.lvmama.soa.monitor.util.DateUtil;
import com.lvmama.soa.monitor.util.StringUtil;
public class DubboDetailUtil {
private static final Log log=LogFactory.getLog(DubboDetailUtil.class);
public static String mergeDetailToStr(String oldDetail, String newDetail, boolean isMax) {
List<List<String>> oldDetailList = detailStrToList(oldDetail);
List<List<String>> newDetailList = detailStrToList(newDetail);
for (List<String> oldRow : oldDetailList) {
String oldTime = oldRow.get(0);
String oldValue = oldRow.get(1);
for (Iterator<List<String>> newIter = newDetailList.iterator(); newIter
.hasNext();) {
List<String> newRow = newIter.next();
String newTime = newRow.get(0);
String newValue = newRow.get(1);
if (oldTime.endsWith(newTime)) {
oldRow.remove(1);
if (isMax) {
oldRow.add(
1,
String.valueOf(Math.max(
Integer.valueOf(oldValue),
Integer.valueOf(newValue))));
} else {
oldRow.add(
1,
String.valueOf(Integer.valueOf(oldValue)
+ Integer.valueOf(newValue)));
}
newIter.remove();
}
}
}
oldDetailList.addAll(newDetailList);
return detailListToStr(oldDetailList);
}
public static List<List<String>> detailStrToList(String detailStr){
return detailStrToList(detailStr, null, null);
}
public static List<List<String>> detailStrToList(String detailStr, String hhmmStart,String hhmmEnd){
BufferedReader br = new BufferedReader(new StringReader(detailStr));
List<List<String>> resultList = new ArrayList<List<String>>();
try{
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
if ("".equals(line.trim())) {
continue;
}
String[] row = line.trim().split(" ");
String time = row[0].trim();
String value = row[1].trim();
if(!StringUtil.isEmpty(time)&&!StringUtil.isEmpty(value)){
if(!StringUtil.isEmpty(hhmmStart)&&hhmmStart.compareTo(time)>0){
continue;
}
if(!StringUtil.isEmpty(hhmmEnd)&&hhmmEnd.compareTo(time)<0){
continue;
}
List<String> l = new ArrayList<String>();
l.add(time);
l.add(value);
resultList.add(l);
}
}
}catch(Exception e){
log.error("detailStrToList error, detailStr:"+detailStr,e);
}finally{
try{
br.close();
}catch(Exception e){
throw new RuntimeException(e);
}
}
return resultList;
}
private static final String detailListToStr(List<List<String>> detailList) {
StringBuilder resultStr=new StringBuilder();
for(List<String> row:detailList){
try{
if(row==null){
continue;
}
String time=row.get(0).trim();
String value=row.get(1).trim();
if(!StringUtil.isEmpty(time)&&!StringUtil.isEmpty(value)){
resultStr.append(time).append(" ").append(value).append(StringUtil.getLineSeparator());
}
}catch(Exception e){
log.error("detailListToStr error",e);
}
}
return resultStr.toString();
}
public static String mergeDetailStr(List<String> detailContentList,boolean isMax){
//key--time, value--success, fail, elapsed times
Map<String,String> mergedDetail=new HashMap<String,String>();
for(String detail:detailContentList){
List<List<String>> singleDetail=detailStrToList(detail);
for(List<String> singleTimeValue:singleDetail){
String time=singleTimeValue.get(0);
String value=singleTimeValue.get(1);
String oldValue=mergedDetail.get(time);
if(oldValue==null){
mergedDetail.put(time, value);
continue;
}
String newValue;
if (isMax) {
newValue=String.valueOf(Math.max(
Integer.valueOf(oldValue),
Integer.valueOf(value)));
} else {
newValue=
String.valueOf(Integer.valueOf(oldValue)
+ Integer.valueOf(value));
}
mergedDetail.put(time, newValue);
}
}
List<List<String>> mergedDetailContentList=new ArrayList<List<String>>();
for(Entry<String,String> entry:mergedDetail.entrySet()){
String time=entry.getKey();
String value=entry.getValue();
List<String> l=new ArrayList<String>();
l.add(time);
l.add(value);
mergedDetailContentList.add(l);
}
Collections.sort(mergedDetailContentList, new Comparator<List<String>>(){
@Override
public int compare(List<String> o1, List<String> o2) {
String time1=o1.get(0);
String time2=o2.get(0);
return time1.compareTo(time2);
}
});
return detailListToStr(mergedDetailContentList);
}
public static void main(String args[])throws Exception{
int NUM_OF_DETAIL=243;
StringBuilder mockDetailStr=new StringBuilder();
long millSecForStartOfToday=DateUtil.trimToDay(DateUtil.now()).getTime();
for(int i=1;i<=60*24;i++){
millSecForStartOfToday=millSecForStartOfToday+60*1000L;
mockDetailStr.append(DateUtil.HHmm(new Date(millSecForStartOfToday))+" 1");
mockDetailStr.append(StringUtil.getLineSeparator());
}
List<String> detailList=new ArrayList<String>();
for(int i=1;i<=NUM_OF_DETAIL;i++){
detailList.add(mockDetailStr.toString());
}
//old logic START
long start=DateUtil.now().getTime();
String mergedDetailStr="";
for(String detail:detailList){
mergedDetailStr=mergeDetailToStr(mergedDetailStr,detail,false);
}
long cost=DateUtil.now().getTime()-start;
System.out.println("OLD logic cost "+cost+"ms to merge "+NUM_OF_DETAIL+" detail content");
//old logic END
//new logic START
long start2=DateUtil.now().getTime();
String mergedDetailStr2=mergeDetailStr(detailList,false);
long cost2=DateUtil.now().getTime()-start2;
System.out.println("NEW logic cost "+cost2+"ms to merge "+NUM_OF_DETAIL+" detail content");
System.out.println(mergedDetailStr2);
//new logic END
}
}
| true |
79b45204dfb2858c03267e68c8050cf3b27d37e8
|
Java
|
liscovich/ColoringGame
|
/src/main/java/edu/harvard/med/hcp/dao/hibernate/DecisionDaoImpl.java
|
UTF-8
| 296 | 1.632813 | 2 |
[] |
no_license
|
package edu.harvard.med.hcp.dao.hibernate;
import org.springframework.stereotype.Repository;
import edu.harvard.med.hcp.dao.DecisionDao;
import edu.harvard.med.hcp.model.Decision;
@Repository
public class DecisionDaoImpl extends GenericDaoImpl<Decision>
implements DecisionDao {
}
| true |
aa9ac72254d2fb62d1c61abe51661ca87c16e493
|
Java
|
yyr823/Test
|
/Test/src/com/java/neibulei/Hero3.java
|
UTF-8
| 1,060 | 3.59375 | 4 |
[] |
no_license
|
/**
*
*/
package com.java.neibulei;
/**
* @author PE
* @date 2019年6月24日 上午11:31:06
* @explain 匿名类
*/
// 匿名类指的是在声明一个类的同时实例化它
// 在匿名类中使用外部的局部变量,外部的局部变量必须修饰为final,在jdk8中,已经不需要强制修饰成final了,如果没有写final,不会报错,因为编译器偷偷的帮你加上了看不见的final
public abstract class Hero3 {
String name; // 姓名
float hp; // 血量
float armor; // 护甲
int moveSpeed; // 移动速度
public abstract void attack();
public static void main(String[] args) {
ADHero adh = new ADHero();
// 通过打印adh,可以看到adh这个对象属于ADHero类
adh.attack();
System.out.println(adh);
Hero3 h = new Hero3() {
// 当场实现attack方法
public void attack() {
System.out.println("新的进攻手段");
}
};
h.attack();
// 通过打印h,可以看到h这个对象属于Hero$1这么一个系统自动分配的类名
System.out.println(h);
}
}
| true |
0aa32af8c439b90e7192c078a0c3e60753292e08
|
Java
|
UncleSamlim/MyRepository
|
/阿里大药房/drugstore/src/cn/yueqian/com/service/impl/GoodsServiceImpl.java
|
UTF-8
| 801 | 2 | 2 |
[] |
no_license
|
package cn.yueqian.com.service.impl;
import java.util.List;
import java.util.Map;
import cn.yueqian.com.dao.IGoodsDao;
import cn.yueqian.com.dao.entity.Goods;
import cn.yueqian.com.dao.entity.GoodsKind;
import cn.yueqian.com.dao.impl.GoodsDaoImpl;
import cn.yueqian.com.service.IGoodsService;
public class GoodsServiceImpl implements IGoodsService{
private IGoodsDao goodsDao = new GoodsDaoImpl();
@Override
public List<Goods> selAllGoods() {
// TODO Auto-generated method stub
return goodsDao.selAllGoods();
}
@Override
public Goods selGoodsById(int id) {
// TODO Auto-generated method stub
return goodsDao.selGoodsById(id);
}
@Override
public List<Goods> selGoodsByKindId(int KindId) {
// TODO Auto-generated method stub
return goodsDao.selGoodsByKindId(KindId);
}
}
| true |
d7ba48590943a56768b8aaaed542e6ab80d2ec15
|
Java
|
tzx7788/ProjectAllocation
|
/ProjectAllocation-api-impl/src/test/java/ZhixiongTang/ProjectAllocation/api/impl/TestAdminService.java
|
UTF-8
| 7,550 | 2.09375 | 2 |
[] |
no_license
|
package ZhixiongTang.ProjectAllocation.api.impl;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.InputStream;
import javax.ws.rs.core.Response;
import org.apache.catalina.Context;
import org.apache.catalina.deploy.ApplicationParameter;
import org.apache.catalina.startup.Tomcat;
import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.springframework.web.context.ContextLoaderListener;
import ZhixiongTang.ProjectAllocation.api.AdminService;
import ZhixiongTang.ProjectAllocation.api.DatabaseService;
@RunWith(JUnit4.class)
public class TestAdminService {
int port;
private Tomcat tomcat;
@Before
public void startTomcat() throws Exception {
tomcat = new Tomcat();
tomcat.setBaseDir(System.getProperty("java.io.tmpdir"));
tomcat.setPort(0);
Context context = tomcat.addContext("",
System.getProperty("java.io.tmpdir"));
ApplicationParameter applicationParameter = new ApplicationParameter();
applicationParameter.setName("contextConfigLocation");
applicationParameter.setValue(getSpringConfigLocation());
context.addApplicationParameter(applicationParameter);
context.addApplicationListener(ContextLoaderListener.class.getName());
Tomcat.addServlet(context, "cxf", new CXFServlet());
context.addServletMapping("/" + getRestServicesPath() + "/*", "cxf");
tomcat.start();
port = tomcat.getConnector().getLocalPort();
System.out.println("Tomcat started on port:" + port);
DatabaseService service = JAXRSClientFactory.create("http://localhost:"
+ port + "/" + getRestServicesPath() + "/services/",
DatabaseService.class);
service.loadTestData("developer", 1);
}
@After
public void stopTomcat() throws Exception {
tomcat.stop();
}
protected String getRestServicesPath() {
return "foo";
}
protected String getSpringConfigLocation() {
return "classpath*:META-INF/spring-context.xml";
}
@Test
public void testGetInformation() {
AdminService service = JAXRSClientFactory.create("http://localhost:"
+ port + "/" + getRestServicesPath() + "/services/",
AdminService.class);
Response response = service.getInformationFromAid("a1");
System.out.println(response.getMetadata());
InputStream inputStream = (InputStream) response.getEntity();
String theString = null;
try {
theString = IOUtils.toString(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(theString);
JSONObject jsonObject = new JSONObject(theString);
jsonObject = jsonObject.getJSONObject("data");
assertEquals("admin", jsonObject.get("name"));
}
@Test
public void testLogin() {
AdminService service = JAXRSClientFactory.create("http://localhost:"
+ port + "/" + getRestServicesPath() + "/services/",
AdminService.class);
Response response = service.loginAdmin("a1", "");
System.out.println(response.getMetadata());
InputStream inputStream = (InputStream) response.getEntity();
String theString = null;
try {
theString = IOUtils.toString(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(theString);
JSONObject jsonObject = new JSONObject(theString);
jsonObject = jsonObject.getJSONObject("data");
assertEquals("admin", jsonObject.get("name"));
}
@Test
public void testLogout() {
AdminService service = JAXRSClientFactory.create("http://localhost:"
+ port + "/" + getRestServicesPath() + "/services/",
AdminService.class);
Response response = service.logoutAdmin("a1", "3e051af3f56067d8526cc1237134fcc8");
System.out.println(response.getMetadata());
InputStream inputStream = (InputStream) response.getEntity();
String theString = null;
try {
theString = IOUtils.toString(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(theString);
JSONObject jsonObject = new JSONObject(theString);
assertEquals("success", jsonObject.get("status"));
}
@Test
public void testGetAllStudent(){
AdminService service = JAXRSClientFactory.create("http://localhost:"
+ port + "/" + getRestServicesPath() + "/services/",
AdminService.class);
Response response = service.getAllStudents("a1", "3e051af3f56067d8526cc1237134fcc8");
System.out.println(response.getMetadata());
InputStream inputStream = (InputStream) response.getEntity();
String theString = null;
try {
theString = IOUtils.toString(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(theString);
JSONObject jsonObject = new JSONObject(theString);
JSONArray array = jsonObject.getJSONArray("data");
assertEquals(3, array.length());
}
@Test
public void testGetAllProfessor(){
AdminService service = JAXRSClientFactory.create("http://localhost:"
+ port + "/" + getRestServicesPath() + "/services/",
AdminService.class);
Response response = service.getAllProfessors("a1", "3e051af3f56067d8526cc1237134fcc8");
System.out.println(response.getMetadata());
InputStream inputStream = (InputStream) response.getEntity();
String theString = null;
try {
theString = IOUtils.toString(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(theString);
JSONObject jsonObject = new JSONObject(theString);
JSONArray array = jsonObject.getJSONArray("data");
assertEquals(3, array.length());
}
@Test
public void testDeleteStudent(){
AdminService service = JAXRSClientFactory.create("http://localhost:"
+ port + "/" + getRestServicesPath() + "/services/",
AdminService.class);
Response response = service.deleteStudent("a1","s1", "3e051af3f56067d8526cc1237134fcc8");
System.out.println(response.getMetadata());
InputStream inputStream = (InputStream) response.getEntity();
String theString = null;
try {
theString = IOUtils.toString(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(theString);
JSONObject jsonObject = new JSONObject(theString);
assertEquals("success",jsonObject.get("status"));
}
@Test
public void testDeleteProfessor(){
AdminService service = JAXRSClientFactory.create("http://localhost:"
+ port + "/" + getRestServicesPath() + "/services/",
AdminService.class);
Response response = service.deleteProfessor("a1","p1", "3e051af3f56067d8526cc1237134fcc8");
System.out.println(response.getMetadata());
InputStream inputStream = (InputStream) response.getEntity();
String theString = null;
try {
theString = IOUtils.toString(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(theString);
JSONObject jsonObject = new JSONObject(theString);
assertEquals("success",jsonObject.get("status"));
}
@Test
public void testMatching() {
AdminService service = JAXRSClientFactory.create("http://localhost:"
+ port + "/" + getRestServicesPath() + "/services/",
AdminService.class);
Response response = service.matchingBegin("a1","3e051af3f56067d8526cc1237134fcc8");
response = service.matching("a1","3e051af3f56067d8526cc1237134fcc8",false);
System.out.println(response.getMetadata());
InputStream inputStream = (InputStream) response.getEntity();
String theString = null;
try {
theString = IOUtils.toString(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(theString);
JSONObject jsonObject = new JSONObject(theString);
assertEquals("success",jsonObject.get("status"));
}
}
| true |
7e775161c906a70d42b26f830939a6b8265282e4
|
Java
|
Scarlett48/TargetTechTraining
|
/unittests/src/main/java/com/aique/service/StubCollaborator.java
|
UTF-8
| 144 | 1.796875 | 2 |
[] |
no_license
|
package com.aique.service;
public class StubCollaborator implements Collaborator{
public boolean isActive(){
return true;
}
}
| true |
0199eff6738b4bb9e63b4cb0533fd7bab064c03d
|
Java
|
GuangkunYu/Java
|
/JavaSE/src/basic_grammar/OperatorTest02.java
|
UTF-8
| 716 | 3.90625 | 4 |
[] |
no_license
|
package basic_grammar;
/*
需求:
一座寺庙里住着3个和尚,已知身高分别为150cm、210cm、165cm,请用程序实现获取这三个和尚的最高身高
*/
public class OperatorTest02 {
public static void main(String[] args) {
// 定义三个变量保存身高
int height1 = 150;
int height2 = 210;
int height3 = 165;
// 用三元运算符先获取前两个和尚的较高值,然后在比较较高的和剩余的一个
int temp = (height1 > height2) ? height1: height2;
int maxHeight = (temp > height3) ? temp: height3;
// 输出最高的身高
System.out.println("最高身高:" + maxHeight);
}
}
| true |
5b59d59c122bf2ef369f0ce52160e40bdd19e5c7
|
Java
|
qi17/Emos
|
/src/main/java/com/example/emos/wx/config/shrio/JWTUtil.java
|
UTF-8
| 2,026 | 2.328125 | 2 |
[] |
no_license
|
package com.example.emos.wx.config.shrio;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author 齐春晖
* @date Created in 18:53 2021/5/5
* @description
*/
@Component
@Slf4j
public class JWTUtil {
@Value("${emos.jwt.secret}")
private String secret;
@Value("${emos.jwt.expire}")
private int expire;
/**
* 通过UserId,创建一个token
* @param userId
* @return
*/
public String createToken(int userId){
DateTime offset = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, expire);
Algorithm algorithm = Algorithm.HMAC256(secret);//使用算法加密secret密钥
JWTCreator.Builder builder = JWT.create();
String token = builder.withClaim("userId", userId)
.withExpiresAt(offset)
.sign(algorithm);
return token;
}
/**
* 通过token获取userId
* @param token
* @return
*/
public int getUserId(String token){
DecodedJWT decodedJWT = JWT.decode(token);
int userId = decodedJWT.getClaim("userId").asInt();
return userId;
}
/**
*验证密钥
* @param token
*/
public void verifierToken(String token){
Algorithm algorithm =Algorithm.HMAC256(secret);//对密钥进行加密算法处理
JWTVerifier verifier = JWT.require(algorithm).build();//创建一个jwt的verifier对象
verifier.verify(token);//验证密钥和token(加密后的密钥部分)是否一致---sign
}
}
| true |
79d549ba6ecaba915a30bbb16bd77b17805bc25d
|
Java
|
dev-tp/cs4551
|
/src/activity1/DiscreteCosineTransformation.java
|
UTF-8
| 1,870 | 3.3125 | 3 |
[] |
no_license
|
package activity1;
class DiscreteCosineTransformation {
static double[][] apply(double[][] matrix) {
double[][] dctMatrix = new double[8][8];
for (int u = 0; u < 8; u++) {
for (int v = 0; v < 8; v++) {
double sum = 0.0;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
double a = Math.cos((2 * i + 1) * u * Math.PI / 16);
double b = Math.cos((2 * j + 1) * v * Math.PI / 16);
sum += a * b * (matrix[i][j] - 128);
}
double c = ((u == 0 ? Math.sqrt(2.0) / 2 : 1) * (v == 0 ? Math.sqrt(2.0) / 2 : 1)) / 4.0;
dctMatrix[u][v] = c * sum;
}
}
}
return dctMatrix;
}
static double[][] invert(double[][] dctMatrix) {
double[][] matrix = new double[8][8];
for (int u = 0; u < 8; u++) {
for (int v = 0; v < 8; v++) {
double sum = 0.0;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
double a = ((i == 0 ? Math.sqrt(2.0) / 2 : 1) * (j == 0 ? Math.sqrt(2.0) / 2 : 1)) / 4.0;
double b = Math.cos((2 * u + 1) * i * Math.PI / 16);
double c = Math.cos((2 * v + 1) * j * Math.PI / 16);
sum += a * b * c * dctMatrix[i][j];
}
matrix[u][v] = sum + 128;
}
}
}
return matrix;
}
static void printMatrix(double[][] matrix) {
for (double[] row : matrix) {
for (double column : row) {
System.out.printf("%.1f\t", column);
}
System.out.println();
}
}
}
| true |
dd56b02be56fc5bd9996bfeff47afa2f6e1f87c0
|
Java
|
qrh672114236/SuperClass
|
/app/src/main/java/com/example/superclass/image/chache/ImageCache.java
|
UTF-8
| 8,225 | 2.578125 | 3 |
[] |
no_license
|
package com.example.superclass.image.chache;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.util.LruCache;
import com.example.superclass.BuildConfig;
import com.example.superclass.image.chache.disk.DiskLruCache;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* 图片缓存 : 内存->复用池->磁盘->网络
*/
public class ImageCache {
private static ImageCache instance;
private Context context;
private LruCache<String, Bitmap> memoryCache;
private DiskLruCache diskLruCache;
BitmapFactory.Options options = new BitmapFactory.Options();
/**
* 定义一个复用池
*/
public static Set<WeakReference<Bitmap>> reuseablePool;
//二级缓存引用队列
ReferenceQueue referenceQueue;
Thread clearReferenceQueue;
boolean shutDown;
private ReferenceQueue<Bitmap> getReferenceQueue(){
if (null==referenceQueue){
//当弱引用需要被回收的时候,会进入到这个队列中
referenceQueue=new ReferenceQueue<Bitmap>();
//单开个线程 ,去扫描引用队列中 GC扫到的内容 ,交到native层去释放
clearReferenceQueue=new Thread(new Runnable() {
@Override
public void run() {
while (!shutDown){
try {
//remove 是阻塞线程
Reference<Bitmap> reference=referenceQueue.remove();
Bitmap bitmap=reference.get();
if (null!=bitmap&&!bitmap.isRecycled()){
bitmap.recycle();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
clearReferenceQueue.start();
}
return referenceQueue;
};
public static ImageCache getInstance() {
if (null == instance) {
synchronized (ImageCache.class) {
if (null == instance) {
instance = new ImageCache();
}
}
}
return instance;
}
public void init(Context context, String dir) {
this.context = context.getApplicationContext();
reuseablePool= Collections.synchronizedSet(new HashSet<WeakReference<Bitmap>>());
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//获得程序最大可使用内存 M
int memoryClass = manager.getMemoryClass();
//标示能够缓存的内存最大值 单位是byte
memoryCache = new LruCache<String, Bitmap>(memoryClass / 8 * 1024 * 1024) {
/**
* @return value 占用的内存大小
*/
@Override
protected int sizeOf(String key, Bitmap value) {
//19之前 复用是必须同等大小,才能复用 之后 复用图片 大小小于原图 也可以复用
if (Build.VERSION.SDK_INT>Build.VERSION_CODES.KITKAT){
return value.getAllocationByteCount();
}
return value.getByteCount();
}
/**
* 当lru满了 ,bitmap从lru中移除对象 会回调
*/
@Override
protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
if (oldValue.isMutable()) {//如果是设置成能服用的内存块,拉倒java管理
//3.0以下 Bitmap native
//3.0-8.0 java
//8.0开始 native
//把图片放到复用池
reuseablePool.add(new WeakReference<Bitmap>(oldValue,getReferenceQueue()));
} else {
//oldValue 就是移除的对象
oldValue.recycle();
}
}
};
//valueCount 表示一个key对应valueCount个文件
try {
diskLruCache=DiskLruCache.open(new File(dir), BuildConfig.VERSION_CODE,1 ,10*1024*1024);
} catch (IOException e) {
e.printStackTrace();
}
// getReferenceQueue();
}
public void putBitmapToMemory(String key, Bitmap bitmap) {
memoryCache.put(key, bitmap);
}
public Bitmap getBitmapFromMemory(String key) {
return memoryCache.get(key);
}
public void clearMemoryCache() {
memoryCache.evictAll();
}
//复用池处理
public Bitmap getReuseable(int w,int h,int inSampleSize){
if (Build.VERSION.SDK_INT<Build.VERSION_CODES.HONEYCOMB){
return null;
}
Bitmap reuseable=null;
Iterator<WeakReference<Bitmap>> iterator = reuseablePool.iterator();
while (iterator.hasNext()){
Bitmap bitmap=iterator.next().get();
if (null!=bitmap){
if (checkInBitmap(bitmap,w,h,inSampleSize)){
reuseable=bitmap;
iterator.remove();
break;
}else{
iterator.remove();
}
}
}
return reuseable;
}
private boolean checkInBitmap(Bitmap bitmap, int w, int h, int inSampleSize) {
if (Build.VERSION.SDK_INT<Build.VERSION_CODES.KITKAT){
return bitmap.getWidth()==w && bitmap.getHeight()==h &&inSampleSize==1;
}
if (inSampleSize>1){
w/=inSampleSize;
h/=inSampleSize;
}
int byteCount=w*h*getPixelsCount(bitmap.getConfig());
return byteCount<=bitmap.getAllocationByteCount();
}
private int getPixelsCount(Bitmap.Config config) {
if (config==Bitmap.Config.ARGB_8888){
return 4;
}
return 2;
}
/**
* 磁盘缓存的处理
*/
//磁盘存储
public void putBitMapToDisk(String key,Bitmap bitmap){
DiskLruCache.Snapshot snapshot=null;
OutputStream os=null;
try {
snapshot=diskLruCache.get(key);
//如果缓存中有这个文件 不处理
if (null==snapshot){
//如果没有 生成文件
DiskLruCache.Editor editor=diskLruCache.edit(key);
if (null!=editor){
os=editor.newOutputStream(0);
bitmap.compress(Bitmap.CompressFormat.JPEG,50,os);
editor.commit();
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (null!=snapshot){
snapshot.close();
}
if (null!=os){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//磁盘读取
public Bitmap getBitmapFromDisk(String key,Bitmap reuseable){
DiskLruCache.Snapshot snapshot=null;
Bitmap bitmap=null;
try {
snapshot=diskLruCache.get(key);
if (null==snapshot){
return null;
}
InputStream in=snapshot.getInputStream(0);
//解码图片
options.inMutable=true;
options.inBitmap=reuseable;
bitmap=BitmapFactory.decodeStream(in,null,options);
if (null!=bitmap){
memoryCache.put(key,bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (null!=snapshot){
snapshot.close();
}
}
return bitmap;
}
}
| true |
e99bac25461e8f8df68bdc38d730521c36f704ab
|
Java
|
AyogoHealth/cordova-plugin-oauth
|
/src/android/OAuthPlugin.java
|
UTF-8
| 9,551 | 1.664063 | 2 |
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright 2019 Ayogo Health Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ayogo.cordova.oauth;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import androidx.browser.customtabs.CustomTabsIntent;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.List;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewEngine;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class OAuthPlugin extends CordovaPlugin {
private final String TAG = "OAuthPlugin";
// Taken from Google's CustomTabsHelper
// https://github.com/GoogleChrome/custom-tabs-client/blob/da65829d7d4b80c00809c6c4aa7f61f88fc7ca26/shared/src/main/java/org/chromium/customtabsclient/shared/CustomTabsHelper.java
static final String STABLE_PACKAGE = "com.android.chrome";
static final String BETA_PACKAGE = "com.chrome.beta";
static final String DEV_PACKAGE = "com.chrome.dev";
static final String LOCAL_PACKAGE = "com.google.android.apps.chrome";
private static final String EXTRA_CUSTOM_TABS_KEEP_ALIVE = "android.support.customtabs.extra.KEEP_ALIVE";
private static final String ACTION_CUSTOM_TABS_CONNECTION = "android.support.customtabs.action.CustomTabsService";
/**
* The name of the package to use for the custom tab service.
*/
private String tabProvider = null;
/**
* Executes the request.
*
* This method is called from the WebView thread. To do a non-trivial amount of work, use:
* cordova.getThreadPool().execute(runnable);
*
* To run on the UI thread, use:
* cordova.getActivity().runOnUiThread(runnable);
*
* @param action The action to execute.
* @param rawArgs The exec() arguments in JSON form.
* @param callbackContext The callback context used when calling back into JavaScript.
* @return Whether the action was valid.
*/
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
if ("startOAuth".equals(action)) {
try {
String authEndpoint = args.getString(0);
this.startOAuth(authEndpoint);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
return true;
} catch (JSONException e) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
return false;
}
}
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION));
return false;
}
/**
* Called when the activity receives a new intent.
*
* We use this method to intercept the OAuth callback URI and dispatch a
* message to the WebView.
*/
@Override
public void onNewIntent(Intent intent) {
if (intent == null || !intent.getAction().equals(Intent.ACTION_VIEW)) {
return;
}
final Uri uri = intent.getData();
if (uri.getHost().equals("oauth_callback")) {
LOG.i(TAG, "OAuth called back with parameters.");
try {
JSONObject jsobj = new JSONObject();
for (String queryKey : uri.getQueryParameterNames()) {
jsobj.put(queryKey, uri.getQueryParameter(queryKey));
}
final String msg = jsobj.toString();
CordovaWebViewEngine engine = this.webView.getEngine();
final String jsCode = "window.dispatchEvent(new MessageEvent('message', { data: 'oauth::" + msg + "' }));";
if (engine != null) {
engine.evaluateJavascript(jsCode, null);
} else {
this.webView.sendJavascript(jsCode);
}
} catch (JSONException e) {
LOG.e(TAG, "JSON Serialization failed");
e.printStackTrace();
}
}
}
/**
* Launches the custom tab with the OAuth endpoint URL.
*
* @param url The URL of the OAuth endpoint.
*/
private void startOAuth(String url) {
String customTabsBrowser = findCustomTabProvider();
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
String packageName = this.findCustomTabProvider();
if (packageName != null) {
customTabsIntent.intent.setPackage(packageName);
}
customTabsIntent.launchUrl(this.cordova.getActivity(), Uri.parse(url));
}
/**
* Goes through all apps that handle VIEW intents and have a warmup service.
*
* Picks the one chosen by the user if there is one, otherwise makes a best
* effort to return a valid package name.
*
* This is <strong>not</strong> threadsafe.
*
* @return The package name recommended to use for connecting to custom
* tabs related components.
*/
private String findCustomTabProvider() {
if (this.tabProvider != null) {
return this.tabProvider;
}
PackageManager pm = this.cordova.getActivity().getPackageManager();
// Get default VIEW intent handler.
Intent activityIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"));
ResolveInfo defaultViewHandlerInfo = pm.resolveActivity(activityIntent, 0);
String defaultViewHandlerPackageName = null;
if (defaultViewHandlerInfo != null) {
defaultViewHandlerPackageName = defaultViewHandlerInfo.activityInfo.packageName;
}
// Get all apps that can handle VIEW intents.
List<ResolveInfo> resolvedActivityList = pm.queryIntentActivities(activityIntent, PackageManager.MATCH_ALL);
List<String> packagesSupportingCustomTabs = new ArrayList<>();
for (ResolveInfo info : resolvedActivityList) {
Intent serviceIntent = new Intent();
serviceIntent.setAction(ACTION_CUSTOM_TABS_CONNECTION);
serviceIntent.setPackage(info.activityInfo.packageName);
if (pm.resolveService(serviceIntent, 0) != null) {
packagesSupportingCustomTabs.add(info.activityInfo.packageName);
}
}
// Now packagesSupportingCustomTabs contains all apps that can handle both VIEW intents
// and service calls.
if (packagesSupportingCustomTabs.isEmpty()) {
this.tabProvider = null;
} else if (packagesSupportingCustomTabs.size() == 1) {
this.tabProvider = packagesSupportingCustomTabs.get(0);
} else if (!TextUtils.isEmpty(defaultViewHandlerPackageName) && !this.hasSpecializedHandlerIntents(activityIntent) && packagesSupportingCustomTabs.contains(defaultViewHandlerPackageName)) {
this.tabProvider = defaultViewHandlerPackageName;
} else if (packagesSupportingCustomTabs.contains(STABLE_PACKAGE)) {
this.tabProvider = STABLE_PACKAGE;
} else if (packagesSupportingCustomTabs.contains(BETA_PACKAGE)) {
this.tabProvider = BETA_PACKAGE;
} else if (packagesSupportingCustomTabs.contains(DEV_PACKAGE)) {
this.tabProvider = DEV_PACKAGE;
} else if (packagesSupportingCustomTabs.contains(LOCAL_PACKAGE)) {
this.tabProvider = LOCAL_PACKAGE;
}
return this.tabProvider;
}
/**
* Used to check whether there is a specialized handler for a given intent.
*
* @param intent The intent to check with.
* @return Whether there is a specialized handler for the given intent.
*/
private boolean hasSpecializedHandlerIntents(Intent intent) {
try {
PackageManager pm = this.cordova.getActivity().getPackageManager();
List<ResolveInfo> handlers = pm.queryIntentActivities(intent, PackageManager.GET_RESOLVED_FILTER);
if (handlers == null || handlers.size() == 0) {
return false;
}
for (ResolveInfo resolveInfo : handlers) {
IntentFilter filter = resolveInfo.filter;
if (filter == null || filter.countDataAuthorities() == 0 || filter.countDataPaths() == 0 || resolveInfo.activityInfo == null) {
continue;
}
return true;
}
} catch (RuntimeException e) {
LOG.e(TAG, "Runtime exception while getting specialized handlers");
}
return false;
}
}
| true |
050b5c6129a5cb8b53a498a0651c71ef86edaa4b
|
Java
|
tylermk04/adwords-alerting
|
/src/test/java/com/google/api/ads/adwords/awalerting/processor/AlertRulesProcessorTest.java
|
UTF-8
| 3,899 | 2.15625 | 2 |
[
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
// Copyright 2015 Google Inc. All Rights Reserved.
//
// 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.google.api.ads.adwords.awalerting.processor;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import com.google.api.ads.adwords.awalerting.AlertProcessingException;
import com.google.api.ads.adwords.awalerting.report.ReportData;
import com.google.api.ads.adwords.awalerting.util.ConfigTags;
import com.google.api.ads.adwords.awalerting.util.TestEntitiesGenerator;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/**
* Test case for the {@link AlertRulesProcessor} class.
*/
@RunWith(JUnit4.class)
public class AlertRulesProcessorTest {
private static final int NUMBER_OF_RULES = 3;
private static final int NUMBER_OF_REPORTS = 10;
@Spy
private AlertRulesProcessor alertRulesProcessor;
@Before
public void setUp() {
JsonObject alertRuleConfig = new JsonObject();
alertRuleConfig.addProperty(ConfigTags.CLASS_NAME, "NoOpAlertRule");
JsonArray configs = new JsonArray();
for (int i = 0; i < NUMBER_OF_RULES; ++i) {
configs.add(alertRuleConfig);
}
String alertMessage = TestEntitiesGenerator.getTestAlertMessageTemplate();
alertRulesProcessor = new AlertRulesProcessor(configs, alertMessage, 10);
MockitoAnnotations.initMocks(this);
}
@Test
public void testConstruction() {
assertEquals(
"Number of alert rules should match config setting.",
NUMBER_OF_RULES,
alertRulesProcessor.getRulesCount());
}
@Test
public void testProcessReports() throws IOException, AlertProcessingException {
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
((CountDownLatch) invocation.getArguments()[2]).countDown();
return null;
}
}).when(alertRulesProcessor).executeRunnableAlertRulesProcessor(
Mockito.<ExecutorService>anyObject(),
Mockito.<RunnableAlertRulesProcessor>anyObject(),
Mockito.<CountDownLatch>anyObject());
ReportData report = TestEntitiesGenerator.getTestReportData();
List<ReportData> reports = new ArrayList<ReportData>();
for (int i = 0; i < NUMBER_OF_REPORTS; ++i) {
reports.add(report);
}
alertRulesProcessor.processReports(reports);
ArgumentCaptor<CountDownLatch> argument = ArgumentCaptor.forClass(CountDownLatch.class);
verify(alertRulesProcessor, times(NUMBER_OF_REPORTS)).executeRunnableAlertRulesProcessor(
Mockito.<ExecutorService>anyObject(),
Mockito.<RunnableAlertRulesProcessor>anyObject(),
argument.capture());
assertEquals(
"CountDownLactch should reach 0 after all alert rule jobs complete",
0,
argument.getValue().getCount());
}
}
| true |
37d3a8aca13f22ec0d730444ab5e20dc00dc8581
|
Java
|
AgoraIO-Community/RTE-Innovation-Challenge-2020
|
/SDKChallengeProject/【duskMorning】AppManager/AppManager/app/src/main/java/com/zhou/appmanager/PermissionInfoActivity.java
|
UTF-8
| 2,834 | 2.3125 | 2 |
[
"MIT"
] |
permissive
|
package com.zhou.appmanager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.zhou.appmanager.model.AppInfo;
import com.zhou.appmanager.util.AppUtil;
public class PermissionInfoActivity extends AppCompatActivity {
private ListView permissionInfo_lv;
private String[] permissionInfos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permission_info);
permissionInfo_lv = findViewById(R.id.permissionInfo_lv);
AppInfo appInfo = getIntent().getParcelableExtra("appInfo");
permissionInfos = appInfo.getPermissionInfos();
setTitle(appInfo.getAppName()+"的权限");
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.item_permissioninfo, permissionInfos);
permissionInfo_lv.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.permission_info_option_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.copy_all:
StringBuilder sb = new StringBuilder();
for (int i=0;i<permissionInfos.length;i++) {
if (i != permissionInfos.length - 1) {
sb.append(permissionInfos[i]).append("\n");
} else {
sb.append(permissionInfos[i]);
}
}
//获取剪贴板管理器
ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
// 创建普通字符型ClipData
ClipData mClipData = ClipData.newPlainText("permissions", sb.toString());
// 将ClipData内容放到系统剪贴板里。
if (cm != null) {
Toast.makeText(this, "复制成功", Toast.LENGTH_SHORT).show();
cm.setPrimaryClip(mClipData);
} else {
NullPointerException exception = new NullPointerException();
AppUtil.exceptionToast(PermissionInfoActivity.this,exception.getMessage());
throw exception;
}
break;
}
return super.onOptionsItemSelected(item);
}
}
| true |
82fd70dba0f61f6e1675ad40e152eee0e1089c25
|
Java
|
zlf123456-ctrl/zuul
|
/server-a-api/src/main/java/com.mingyin.service/IServiceA.java
|
UTF-8
| 516 | 1.914063 | 2 |
[] |
no_license
|
package com.mingyin.service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@RequestMapping
public interface IServiceA {
@RequestMapping(value = "/sayHello",method = RequestMethod.GET)
public String sayHello(@RequestParam("name") String name);
@RequestMapping(value = "/findById",method = RequestMethod.GET)
String findById(@RequestParam("id") String id);
}
| true |
8cc7a0976efab3abbf6b9c71541c0939e56a4357
|
Java
|
ronimitra100/DataStructuresAndAlgorithms
|
/OutcoRoni/src/main/java/extra/CheckValidBST.java
|
UTF-8
| 1,381 | 3.46875 | 3 |
[] |
no_license
|
package extra;
/**
* Created by ronim_000 on 11/2/2019.
*/
public class CheckValidBST {
public static class Node{
int data;
Node left;
Node right;
public Node(int data){
this.data=data;
}
public Node(){
}
}
Node root;
Node left;
Node right;
public CheckValidBST(int rootValue){
this.root = new Node(rootValue);
}
public CheckValidBST(){
this.root = null;
}
public static void main(String[] args){
CheckValidBST myTree = new CheckValidBST();
myTree.root = new Node(4);
myTree.root.left = new Node(2);
myTree.root.right= new Node(6);
myTree.root.left.left = new Node(1);
myTree.root.left.right=new Node(3);
myTree.root.right.left=new Node(5);
myTree.root.right.right=new Node(10);
System.out.println(myTree.isValidBST(myTree.root));
}
public boolean isValidBST(Node node, int min, int max){
if (node==null){
return true;
}
if (node.data < min || node.data>max){
return false;
}
return (isValidBST(node.left, min, node.data-1) && isValidBST(node.right, node.data+1, max));
}
public boolean isValidBST(Node node){
return isValidBST(node, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
}
| true |
a8f589c41adc2b090794e28e17dd532b3d9a384b
|
Java
|
Rainicy/JavaStudyNotes
|
/DataStructAlgorithm/src/com/rainicy/chapter7/expression/ExpressionVariable.java
|
UTF-8
| 676 | 3.375 | 3 |
[] |
no_license
|
/*
* Created on June 19, 2014
*
* @author Rainicy
*/
package com.rainicy.chapter7.expression;
/**
* Class for a variable of an arithmetic expression.
*
* @version 1.0
* @author Rainicy
*/
public class ExpressionVariable extends ExpressionTerm {
protected Integer variable;
/** Constructor */
public ExpressionVariable(Integer var) {
variable = var;
}
/** Set value for variable. */
public void setVariable(Integer var) {
variable = var;
}
/** Get value */
public Integer getValue() {
return variable;
}
/** toString */
public String toString() {
return variable.toString();
}
}
| true |
bcaaaf624bdfba883633df41cea030bcb404eee3
|
Java
|
nararodriguess/fundamentosJava
|
/projetoAula03_09/src/pacoteAula03_09/classeAula03_09.java
|
ISO-8859-1
| 808 | 3.8125 | 4 |
[] |
no_license
|
package pacoteAula03_09;
import java.util.Scanner;
public class classeAula03_09 {
public static void main(String[] args) {
char continua = 's'; // tipagem das variveis e chamada para ler teclado
int num = 0, soma = 0, cont = 0;
Scanner entrada = new Scanner (System.in);
while (continua == 's') { // enquanto 'continua' for igual a sim, sera executado
System.out.print("Digite um nmero: ");
num = entrada.nextInt();
soma += num;
cont +=1;
entrada.nextLine();
System.out.print("Deseja continuar o programa ( s = sim; n = no)? "); // verifica se o looping continua
continua = entrada.nextLine().charAt(0);
}
System.out.printf("Voc digitou %d numeros e a soma dos nmeros digitados : %d", cont,soma); // mostra o resultado
}
}
| true |
141cfa5317a3d83ba89d3ff302b868b2cea3d026
|
Java
|
mathiasose/Chess
|
/Board.java
|
UTF-8
| 4,911 | 3.171875 | 3 |
[] |
no_license
|
package chess;
public class Board {
private Piece[][] board;
public static final Piece[][] startBoard =
{ { new Rook(PieceColor.BLACK), new Knight(PieceColor.BLACK), new Bishop(PieceColor.BLACK), new King(PieceColor.BLACK), new Queen(PieceColor.BLACK), new Bishop(PieceColor.BLACK), new Knight(PieceColor.BLACK), new Rook(PieceColor.BLACK) },
{ new Pawn(PieceColor.BLACK), new Pawn(PieceColor.BLACK), new Pawn(PieceColor.BLACK), new Pawn(PieceColor.BLACK), new Pawn(PieceColor.BLACK), new Pawn(PieceColor.BLACK), new Pawn(PieceColor.BLACK), new Pawn(PieceColor.BLACK) },
{ null, null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null, null },
{ new Pawn(PieceColor.WHITE), new Pawn(PieceColor.WHITE), new Pawn(PieceColor.WHITE), new Pawn(PieceColor.WHITE), new Pawn(PieceColor.WHITE), new Pawn(PieceColor.WHITE), new Pawn(PieceColor.WHITE), new Pawn(PieceColor.WHITE) },
{ new Rook(PieceColor.WHITE), new Knight(PieceColor.WHITE), new Bishop(PieceColor.WHITE), new Queen(PieceColor.WHITE), new King(PieceColor.WHITE), new Bishop(PieceColor.WHITE), new Knight(PieceColor.WHITE), new Rook(PieceColor.WHITE) }
};
public Board(){
board = new Piece[8][8];
for ( int i = 0; i < 8; i++ ) {
for ( int j = 0; j < 8; j++ ) {
board[i][j] = startBoard[i][j];
}
}
}
static int index(String position, int i) throws IllegalPositionException {
if ( position.length() != 2 )
throw new IllegalPositionException(position);
int r = (i == 1) ? position.charAt(0) - 'a' : 7 - (position.charAt(1) - '1');
// System.out.println(position + " => " + i + "->" + r);
if ( r < 0 || r > 7 )
throw new IllegalPositionException(position);
else
return r;
}
Piece getPiece(String position) throws IllegalPositionException {
int x = index(position, 1);
int y = index(position, 0);
return ( isOccupied(position) ) ? board[y][x] : null;
}
void setPiece(String position, Piece piece) throws IllegalPositionException {
board[index(position, 0)][index(position, 1)] = piece;
}
static boolean isStraight(String from, String to) throws IllegalPositionException{
return ( ( index(from, 0) == index(to, 0) ) || ( index(from, 1) == index(to, 1) ) );
}
static boolean isDiagonal(String from, String to) throws IllegalPositionException{
return ( Math.abs( index(from, 0) - index(to, 0) ) == Math.abs( index(from, 1) - index(to, 1) ) );
}
boolean isOccupiedBetween(String from, String to) throws IllegalPositionException{
int fromX = index(from, 1);
int fromY = index(from, 0);
int toX = index(to, 1);
int toY = index(to, 0);
int diffX = toX - fromX;
int diffY = toY - fromY;
int stepX = (diffX == 0) ? 0 : diffX/Math.abs(diffX);
int stepY = (diffY == 0) ? 0 : diffY/Math.abs(diffY);
int x = fromX + stepX;
int y = fromY + stepY;
while ( ( isStraight(from, to) || isDiagonal(from, to) ) && !(x == toX && y == toY) ) {
if ( isOccupied(x, y) ) return true;
x += stepX;
y += stepY;
}
return false;
}
boolean isOccupied(int x, int y) {
return ( board[y][x] != null );
}
boolean isOccupied(String pos) throws IllegalPositionException {
return isOccupied( index(pos, 1), index(pos, 0) );
}
boolean isLegalMove(PieceColor color, String from, String to) throws IllegalPositionException{
if ( !isOccupied(from) || getPiece(from).getPieceColor() != color )
return false;
if ( !isOccupied(to) )
return getPiece(from).canMove(from, to, this);
if ( getPiece(from).getPieceColor() == getPiece(to).getPieceColor() )
return false;
return getPiece(from).canTake(from, to, this);
}
void movePiece(String from, String to) throws IllegalPositionException, IllegalMoveException {
if ( isLegalMove(getPiece(from).getPieceColor(), from, to)){
System.out.println(getPiece(from).getPieceColor() + " " + getPiece(from).getName() + " from " + from + " to " + to);
board[index(to, 0)][index(to, 1)] = getPiece(from);
board[index(from, 0)][index(from, 1)] = null;
if ( board[index(to, 0)][index(to, 1)] instanceof Pawn )
board[index(to, 0)][index(to, 1)] = new Queen( getPiece(to).getPieceColor() );
} else throw new IllegalMoveException(from, to);
}
boolean isCheck(PieceColor color){
// egentlig en sjakk matt sjekk
for ( Piece[] row : board ) {
for ( Piece col : row ) {
if ( col instanceof King && col.getPieceColor() == color )
return false;
}
}
return true;
}
public String toString(){
String r = " a b c d e f g h\n";
r += " ------------------\n";
char y = '8';
for ( Piece[] row : board ) {
r += y + "|";
for ( Piece col : row ) {
r += ( col != null ) ? col.toChar() : ' ';
r += " ";
}
r += "|" + y-- + "\n";
}
r += " ------------------\n";
r += " a b c d e f g h\n";
return r;
}
}
| true |
d4e542e0519502a9ec9ae67bc1b3b965ce8c7787
|
Java
|
jesseng11/practice-problems
|
/src/String_IsRotation.java
|
UTF-8
| 383 | 3.265625 | 3 |
[] |
no_license
|
import java.io.*;
import java.util.*;
public class String_IsRotation {
public static void main(String[] args) {
System.out.println(isStrRotation("waterbottle", "erbottlewat"));
}
//O(n)
static boolean isStrRotation(String s1, String s2) {
if(s1.length() != s2.length())
return false;
String s1s1 = s1 + s1;
return s1s1.contains(s2);
}
}
| true |
c6346c7e56e97ffff244bb7bf7e138be2f54f049
|
Java
|
v1001001/lumchine
|
/lumchine-db/src/main/java/com/lumchine/db/dao/LumchinePermissionMapper.java
|
UTF-8
| 4,967 | 1.960938 | 2 |
[
"CC-BY-ND-4.0",
"MIT"
] |
permissive
|
package com.lumchine.db.dao;
import com.lumchine.db.domain.LumchinePermission;
import com.lumchine.db.domain.LumchinePermissionExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface LumchinePermissionMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
long countByExample(LumchinePermissionExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
int deleteByExample(LumchinePermissionExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
int insert(LumchinePermission record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
int insertSelective(LumchinePermission record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
LumchinePermission selectOneByExample(LumchinePermissionExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
LumchinePermission selectOneByExampleSelective(@Param("example") LumchinePermissionExample example, @Param("selective") LumchinePermission.Column ... selective);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
List<LumchinePermission> selectByExampleSelective(@Param("example") LumchinePermissionExample example, @Param("selective") LumchinePermission.Column ... selective);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
List<LumchinePermission> selectByExample(LumchinePermissionExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
LumchinePermission selectByPrimaryKeySelective(@Param("id") Integer id, @Param("selective") LumchinePermission.Column ... selective);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
LumchinePermission selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
LumchinePermission selectByPrimaryKeyWithLogicalDelete(@Param("id") Integer id, @Param("andLogicalDeleted") boolean andLogicalDeleted);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
int updateByExampleSelective(@Param("record") LumchinePermission record, @Param("example") LumchinePermissionExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
int updateByExample(@Param("record") LumchinePermission record, @Param("example") LumchinePermissionExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
int updateByPrimaryKeySelective(LumchinePermission record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
int updateByPrimaryKey(LumchinePermission record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
int logicalDeleteByExample(@Param("example") LumchinePermissionExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lumchine_permission
*
* @mbg.generated
*/
int logicalDeleteByPrimaryKey(Integer id);
}
| true |
db8167f03d54a1f3c5a876429d60ee47f1528a86
|
Java
|
BarbaralmBraz/Projeto-Cadastro-Aluno
|
/alunos/alunos/src/main/java/com/projeto/alunos/model/Aluno.java
|
UTF-8
| 424 | 1.929688 | 2 |
[] |
no_license
|
package com.projeto.alunos.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;
import lombok.Data;
@Table
@Entity
@Data
public class Aluno {
@Id @GeneratedValue
private Long id;
private String nome;
private String cpf;
private String rg;
private String endereco;
private String curso;
}
| true |
9750c2757f9ffae465d66773d5a0fa4fcb1f926c
|
Java
|
codersinan/MaestroPanel-Graduation
|
/app/src/main/java/net/sinancaliskan/maestropanel/ui/ServerActivity.java
|
UTF-8
| 6,400 | 2.046875 | 2 |
[] |
no_license
|
package net.sinancaliskan.maestropanel.ui;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sinancaliskan.maestropanel.API;
import net.sinancaliskan.maestropanel.R;
import net.sinancaliskan.maestropanel.interfaces.IServer;
import net.sinancaliskan.maestropanel.models.Reply;
import net.sinancaliskan.maestropanel.models.pojo.ServerObjects.Server;
import net.sinancaliskan.maestropanel.models.pojo.ServerObjects.ServerResource;
import net.sinancaliskan.maestropanel.utils.SharedInformation;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ServerActivity extends AppCompatActivity {
private ProgressDialog progressDialog;
private IServer service;
private Server model;
private Toolbar toolbar;
private List<ServerResource> models=new ArrayList<>();
private TextView version,host,serverName,processor,operatingSystem;
private LinearLayout linearLayout=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);
Bundle extras=getIntent().getExtras();
model= (Server) extras.get("model");
toolbar= (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle(model.name);
version= (TextView) findViewById(R.id.txtVersion);
version.setText(model.version);
host= (TextView) findViewById(R.id.txtHostName);
host.setText(model.host);
serverName= (TextView) findViewById(R.id.txtServerName);
serverName.setText(model.computerName);
processor= (TextView) findViewById(R.id.txtProcessor);
processor.setText(model.cpu);
operatingSystem= (TextView) findViewById(R.id.txtOperatingSystem);
operatingSystem.setText(model.operatingSystem);
progressDialog=new ProgressDialog(ServerActivity.this);
progressDialog.setMessage(getString(R.string.server)+ getString(R.string.isLoading));
progressDialog.setCancelable(false);
progressDialog.show();
linearLayout= (LinearLayout) findViewById(R.id.resources);
get(model.name);
}
private void get(String name){
service = API.getClient().create(IServer.class);
String key= SharedInformation.getData("serverKey");
Call<Reply> call=service.GetResources(key,name);
call.enqueue(new Callback<Reply>() {
@Override
public void onResponse(Call<Reply> call, Response<Reply> response) {
ArrayList<ServerResource> objects= ((ArrayList<ServerResource>) response.body().details);
ObjectMapper mapper = new ObjectMapper();
LinearLayout.LayoutParams paramLabel = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
paramLabel.setMargins(15,15,15,15);
LinearLayout.LayoutParams paramValue = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
paramValue.setMargins(100,15,15,15);
//labels
for (int i=0;i<objects.size();i++){
ServerResource model=mapper.convertValue(objects.get(i),ServerResource.class);
TextView label,value;
LinearLayout row=new LinearLayout(ServerActivity.this);
row.setOrientation(LinearLayout.HORIZONTAL);
//labels
LinearLayout labels=new LinearLayout(ServerActivity.this);
labels.setOrientation(LinearLayout.VERTICAL);
labels.setLayoutParams(paramLabel);
label=new TextView(ServerActivity.this);
label.setText(getString(R.string.resource));
label.setTextSize(20);
label.setTextColor(getResources().getColor(R.color.accent_blue));
labels.addView(label);
label=new TextView(ServerActivity.this);
label.setText(getString(R.string.total));
label.setTextSize(20);
label.setTextColor(getResources().getColor(R.color.accent_blue));
labels.addView(label);
label=new TextView(ServerActivity.this);
label.setText(getString(R.string.total));
label.setTextSize(20);
label.setTextColor(getResources().getColor(R.color.accent_blue));
labels.addView(label);
//values
LinearLayout values=new LinearLayout(ServerActivity.this);
values.setOrientation(LinearLayout.VERTICAL);
values.setLayoutParams(paramLabel);
value=new TextView(ServerActivity.this);
value.setText(model.resourceName);
value.setTextSize(20);
values.addView(value);
value=new TextView(ServerActivity.this);
value.setText(model.total);
value.setTextSize(20);
values.addView(value);
value=new TextView(ServerActivity.this);
value.setText(model.used);
value.setTextSize(20);
values.addView(value);
row.addView(labels,paramLabel);
row.addView(values,paramValue);
linearLayout.addView(row,paramValue);
}
if (progressDialog!=null)
progressDialog.dismiss();
}
@Override
public void onFailure(Call<Reply> call, Throwable throwable) {
call.cancel();
Toast.makeText(null, getString(R.string.somethingIsWrong), Toast.LENGTH_SHORT).show();
if (progressDialog!=null)
progressDialog.dismiss();
}
});
}
}
| true |
6e7a88929ee8fa98a8c2f362fd3e98cbd5bddeb2
|
Java
|
mariiayarema/Batch8JavaClasses
|
/src/com/syntax/class02/VariableValues.java
|
UTF-8
| 695 | 2.84375 | 3 |
[] |
no_license
|
package com.syntax.class02;
public class VariableValues {
public static void main(String[] args) {
// TODO Auto-generated method stub
byte vok1=23;
short vok2=456;
int vok3=63388;
long vok4=36372829383747l;
float vok5=1.3f;
double vok6=12.338;
char vok7=('B');
boolean vok8=true;
vok1=45;
vok2=564;
vok4=532673;
vok5=5437373l;
vok5=3.5f;
vok6=34.383347;
vok7=('M');
vok8=false;
System.out.println(vok1);
System.out.println(vok2);
System.out.println(vok3);
System.out.println(vok4);
System.out.println(vok5);
System.out.println(vok6);
System.out.println(vok7);
System.out.println(vok8);
}
}
| true |
e6f6f2e539cc227fa9e44f347351c6917dd66a27
|
Java
|
AmadeyKuspakov/alarm
|
/app/src/main/java/get/and/set/alarm/FlaotingWindow/FloatingWindowPresenterImpl.java
|
UTF-8
| 3,359 | 2.25 | 2 |
[] |
no_license
|
package get.and.set.alarm.FlaotingWindow;
import android.app.WallpaperManager;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import get.and.set.alarm.R;
import get.and.set.alarm.ServicesManager;
/**
* Created by Amadey on 8/14/2018.
*/
public class FloatingWindowPresenterImpl implements FloatingWindowPresenter{
private FloatingWindowService floatingWindowService;
private ServicesManager servicesManager;
private TextView.OnEditorActionListener onEditorActionListener = new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if(i == EditorInfo.IME_ACTION_DONE && arePhrasesSimilar(textView.getText().toString())){
floatingWindowService.stop();
}
return false;
}
};
public FloatingWindowPresenterImpl(FloatingWindowService floatingWindowService, ServicesManager servicesManager){
this.servicesManager = servicesManager;
this.floatingWindowService = floatingWindowService;
}
@Override
public WindowManager.LayoutParams getWindowParams() {
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
layoutParams.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
if(Build.VERSION.SDK_INT>25){
layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
}else {
layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
}
layoutParams.format = PixelFormat.OPAQUE;
return layoutParams;
}
@Override
public View getLayoutAsView(int id) {
View view = servicesManager.getLayoutInflater().inflate(id,null);
EditText editText = view.findViewById(R.id.editText);
editText.setOnEditorActionListener(onEditorActionListener);
if(Build.VERSION.SDK_INT>15){
view.setBackground(WallpaperManager.getInstance(servicesManager.getContext()).getFastDrawable());
}else{
view.setBackgroundDrawable(WallpaperManager.getInstance(servicesManager.getContext()).getFastDrawable());
}
return view;
}
private boolean arePhrasesSimilar(String typedInPhrase){
return floatingWindowService.getPhrase().equalsIgnoreCase(typedInPhrase);
}
@Override
public void startAlarm() {
startVibration();
startMusic();
}
private void startVibration(){
Vibrator vibrator = servicesManager.getVibrator();
long[] pattern = {0, 100, 1000};
vibrator.vibrate(pattern, 0);
}
private void startMusic(){
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
MediaPlayer mediaPlayer = MediaPlayer.create(servicesManager.getContext(), uri);
mediaPlayer.setLooping(true);
mediaPlayer.start();
}
}
| true |
341e86cd47d1f700c71d0de6ff8c860aaf684860
|
Java
|
sunshaochi/rccfgwd
|
/app/src/main/java/com/rmwl/rcchgwd/view/InfoView.java
|
UTF-8
| 1,821 | 2.078125 | 2 |
[] |
no_license
|
package com.rmwl.rcchgwd.view;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.rmwl.rcchgwd.R;
import com.rmwl.rcchgwd.bean.ProdIntervalBean;
import java.util.List;
/**
* Created by acer on 2018/8/22.
*/
public class InfoView extends LinearLayout{
private Context context;
private TextView tv_proname,tv_lv,tv_days,tv_rg,tv_person,tv_synum,tv_syname,tv_dw;
private LinearLayout ll_item;
public InfoView(Context context) {
super(context);
this.context=context;
}
public InfoView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
this.context=context;
}
public InfoView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context=context;
}
public void init(List<ProdIntervalBean> list){
if(list!=null&&list.size()>0){
removeAllViews();
for(int i=0;i<list.size();i++){
ProdIntervalBean bean=list.get(i);
View view= View.inflate(context, R.layout.item_info,null);
LinearLayout ll_top=view.findViewById(R.id.ll_top);
TextView tv_left=view.findViewById(R.id.tv_left);
TextView tv_right=view.findViewById(R.id.tv_right);
if(i==0){
ll_top.setVisibility(VISIBLE);
}else {
ll_top.setVisibility(GONE);
}
tv_left.setText(bean.getPurchaseAmount());
tv_right.setText(bean.getIntervalrate());
addView(view);
}
}
}
}
| true |
e33840a83df0d18af7c67914fa1682ba07630f82
|
Java
|
hhugohm/orm
|
/hibernate-jpa-spring/src/main/java/org/neos/hibernate/dao/TelephoneDaoImpl.java
|
UTF-8
| 325 | 2.09375 | 2 |
[] |
no_license
|
package org.neos.hibernate.dao;
import org.neos.hibernate.domain.Telephone;
import org.springframework.stereotype.Repository;
@Repository("telephoneDao")
public class TelephoneDaoImpl extends AbstractDaoImpl<Telephone>implements TelephoneDao {
public TelephoneDaoImpl() {
super(Telephone.class);
}
}
| true |
b97522b238bab8a8802b2adb4b2b3a2e37999d6b
|
Java
|
985498203/hrsystem
|
/src/main/java/com/hxzy/hrsystem/dao/impl/RecruitInfoDaoImpl.java
|
UTF-8
| 2,292 | 2.046875 | 2 |
[] |
no_license
|
package com.hxzy.hrsystem.dao.impl;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.hxzy.hrsystem.dao.RecruitInfoDao;
import com.hxzy.hrsystem.entity.Permission;
import com.hxzy.hrsystem.entity.RecruitInfo;
@SuppressWarnings("all")
@Component("recruitInfoDao")
@Repository(value="recruitInfoDao")
@Transactional
public class RecruitInfoDaoImpl implements RecruitInfoDao {
private SessionFactory sessionFactory;
@Resource
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory=sessionFactory;
}
private Session getSession() {
return this.sessionFactory.getCurrentSession();
}
//查询工单
@Override
public List<RecruitInfo> findRecruitInfoAll() {
// TODO Auto-generated method stub
String hql = "FROM RecruitInfo";
// List<Worder> list = this.getHibernateTemplate().find(hql);
return this.getSession().createQuery(hql).list();
}
//增
@Override
public void addRecruitInfo(RecruitInfo recruitInfo) {
// TODO Auto-generated method stub
getSession().save(recruitInfo);
}
//改
@Override
public void updataRecruitInfo(RecruitInfo recruitInfo) {
// TODO Auto-generated method stub
getSession().update(recruitInfo);
}
//删
@Override
public void deleteRecruitInfo(int id) {
Session session = this.getSession();
Query query = this.getSession().createQuery("from RecruitInfo r where r.recruitId =:recruitId");// 得到Query对象
query.setParameter("recruitId", id);
RecruitInfo recruitInfo = (RecruitInfo) query.uniqueResult();
session.delete(recruitInfo);
}
//根据ID查询
@Override
public void findRecruitInfoById(int id) {
// TODO Auto-generated method stub
String hql = "FROM Worder WHERE worderId = :worderId";
Query query = getSession().createQuery(hql);
query.setParameter("worderId", id);
RecruitInfo recruitInfo = (RecruitInfo) query.list().get(id);
}
}
| true |
6969edbb59acedefb08f3644414bcf1143d69e69
|
Java
|
damofujiki/UnsagaMod-for-1.12
|
/src/main/java/mods/hinasch/unsaga/ability/specialmove/action/AsyncGrandslam.java
|
UTF-8
| 2,372 | 2.21875 | 2 |
[] |
no_license
|
package mods.hinasch.unsaga.ability.specialmove.action;
import java.util.List;
import com.google.common.collect.ImmutableList;
import mods.hinasch.lib.particle.ParticleHelper;
import mods.hinasch.lib.sync.SafeUpdateEventByInterval;
import mods.hinasch.lib.util.SoundAndSFX;
import mods.hinasch.lib.world.WorldHelper;
import mods.hinasch.lib.world.XYZPos;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.init.Blocks;
import net.minecraft.init.SoundEvents;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class AsyncGrandslam extends SafeUpdateEventByInterval{
int index = 0;
final int endLength;
ImmutableList<BlockPos> explodePos;
final World world;
final double damage;
final boolean canWorldDestroy;
public AsyncGrandslam(World w,double damage,List<BlockPos> explodePos,boolean worldDestroy,EntityLivingBase sender) {
super(sender, "grandslam");
this.world = w;
this.damage = damage;
this.explodePos = ImmutableList.copyOf(explodePos);
this.endLength = this.explodePos.size();
this.canWorldDestroy = worldDestroy;
}
@Override
public int getIntervalThresold() {
// TODO 自動生成されたメソッド・スタブ
return 3;
}
@Override
public void loopByInterval() {
if(this.index<this.explodePos.size()){
BlockPos pos = this.explodePos.get(index);
if(this.canWorldDestroy){
if(WorldHelper.isServer(world)){
world.createExplosion(sender, pos.getX(), pos.getY(), pos.getZ(), 3.0F, false);
}
}else{
SoundAndSFX.playSound(world, pos.getX(), pos.getY(), pos.getZ(), SoundEvents.ENTITY_GENERIC_EXPLODE, SoundCategory.BLOCKS, 1.0F, 1.0F, true);
IBlockState state = world.getBlockState(pos.down());
if(state.getBlock()!=Blocks.AIR){
ParticleHelper.MovingType.FOUNTAIN.spawnParticle(world, new XYZPos(pos), EnumParticleTypes.BLOCK_DUST, world.rand, 20, 5.0F, Block.getStateId(state));
}
// ParticleHelper.MovingType.FOUNTAIN.spawnParticle(world, new XYZPos(pos), EnumParticleTypes.CLOUD, world.rand, 15, 3.0D);
}
}
index ++;
}
@Override
public boolean hasFinished() {
// TODO 自動生成されたメソッド・スタブ
return index>this.endLength;
}
}
| true |
54d7f3285767957d7e766f0ca5c7d6ba2a2b8b48
|
Java
|
leoberteck/Capstone-Project
|
/WhatTheWord/app/src/main/java/com/leoberteck/whattheword/data/entities/ScoreEntity.java
|
UTF-8
| 528 | 2.5625 | 3 |
[] |
no_license
|
package com.leoberteck.whattheword.data.entities;
public class ScoreEntity implements BaseEntity {
private Long id;
private Long score;
public ScoreEntity() {
}
public ScoreEntity(Long score) {
this.score = score;
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(long id) {
this.id = id;
}
public long getScore() {
return score;
}
public void setScore(long score) {
this.score = score;
}
}
| true |
ce5dcf594888ffefd78057ad96c996dd13b6be4f
|
Java
|
maxtardiveau/BusLogicDemoPlay
|
/app/models/PurchaseOrder.java
|
UTF-8
| 1,258 | 2.40625 | 2 |
[] |
no_license
|
package models;
import java.math.BigDecimal;
import java.util.List;
import java.util.Vector;
import javax.persistence.*;
import play.db.jpa.Model;
@Entity
@Table(name="purchaseorder")
public class PurchaseOrder extends Model {
@Column(name="amount_total")
public BigDecimal amountTotal;
public BigDecimal getAmountTotal() { return amountTotal; }
public void setAmountTotal(BigDecimal amountTotal) { this.amountTotal = amountTotal; }
@Column(name="paid")
public Boolean paid;
public Boolean getPaid() { return paid; }
public void setPaid(Boolean paid) { this.paid = paid; }
@Column(name="notes")
public String notes;
public String getNotes() { return notes; }
public void setNotes(String notes) { this.notes = notes; }
// Relationships
@ManyToOne(fetch=FetchType.LAZY)
public Customer customer;
public Customer getCustomer() { return customer; }
public void setCustomer(Customer customer) { this.customer = customer; }
@OneToMany(mappedBy="purchaseOrder", cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
@OrderBy("id desc")
public List<LineItem> lineItems = new Vector<LineItem>();
public List<LineItem> getLineItems() { return lineItems; }
public void setLineItems(List<LineItem> lineItems) { this.lineItems = lineItems; }
}
| true |
44657f7c8f7a514c74ec8972b2316e1172779d0d
|
Java
|
jluizmonte/SISGETE
|
/src/br/com/sisgete/controller/PacienteController.java
|
UTF-8
| 2,441 | 2.515625 | 3 |
[] |
no_license
|
package br.com.sisgete.controller;
import br.com.sisgete.model.DAO.PacienteDAO;
import br.com.sisgete.model.PacienteModel;
import java.util.ArrayList;
/**
*
* @author luiz
*/
public class PacienteController {
PacienteDAO pacienteDAO = new PacienteDAO();
/**
* salva um novo paciente
*
* @param pPacienteModel return int
* @return
*/
public int salvarPacienteController(PacienteModel pPacienteModel) {
return this.pacienteDAO.salvarPacienteDAO(pPacienteModel);
}
/**
* recupera um paciente pelo código
*
* @param pIdPaciente
* @return PacienteModel
*/
public PacienteModel getPacienteController(int pIdPaciente) {
return this.pacienteDAO.getPacienteDAO(pIdPaciente);
}
/**
* recupera um paciente pelo nome
*
* @param pPaciente
* @return
*/
public PacienteModel getPaciente(String pPaciente) {
return this.pacienteDAO.getPacienteDAO(pPaciente);
}
/**
* recupera um arrayList com todos os pacientes
*
* @return ArrayList
*/
public ArrayList<PacienteModel> getListaPacienteController() {
return this.pacienteDAO.getListaPacienteDAO();
}
/**
* recupera um arrayList com os pacientes com fichas ativas
*
* @return ArrayList
*/
public ArrayList<PacienteModel> getListaPacienteAtivoController() {
return this.pacienteDAO.getListaPacienteAtivoDAO();
}
/**
* recupera um arrayList com os pacientes liberados
*
* @return
*/
public ArrayList<PacienteModel> getListaPacienteLiberadoDAO() {
return this.pacienteDAO.getListaPacienteLiberadoDAO();
}
/**
* recupera um arrayList com os pacientes com fichas ativas
*
* @return
*/
public ArrayList<PacienteModel> getListaPacienteInativoDAO() {
return this.pacienteDAO.getListaPacienteInativoDAO();
}
/**
* atualiza Paciente
*
* @param pPacienteModel return boolean
* @return
*/
public boolean atualizarPacienteController(PacienteModel pPacienteModel) {
return this.pacienteDAO.atualizarPacienteDAO(pPacienteModel);
}
/**
* exclui Paciente
*
* @param pIdPaciente
* @return boolean
*/
public boolean excluirPacienteController(int pIdPaciente) {
return this.pacienteDAO.excluirPacienteDAO(pIdPaciente);
}
}
| true |
b6cc498efd3e1016a3bfe182393404ca179193c0
|
Java
|
vikumsri/G9.3_MAD_Submission
|
/app/src/main/java/com/example/affixpaws/FeedAdapter_v.java
|
UTF-8
| 2,365 | 2.265625 | 2 |
[] |
no_license
|
package com.example.affixpaws;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class FeedAdapter_v extends RecyclerView.Adapter<FeedAdapter_v.feedViewHolder>{
ArrayList<FeedData_v> postList;
public static class feedViewHolder extends RecyclerView.ViewHolder {
public ImageView profileImage;
public ImageView postImage;
public TextView userName;
public TextView caption;
public TextView likes;
public TextView comments;
public TextView favorites;
public feedViewHolder(View itemView) {
super(itemView);
postImage = itemView.findViewById(R.id.postImage);
profileImage = itemView.findViewById(R.id.profile_photo);
userName = itemView.findViewById(R.id.username);
caption = itemView.findViewById(R.id.caption);
likes = itemView.findViewById(R.id.likes);
comments = itemView.findViewById(R.id.comments);
favorites = itemView.findViewById(R.id.favorite);
}
}
public FeedAdapter_v(ArrayList<FeedData_v> postList){
this.postList = postList;
}
@NonNull
@Override
public feedViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_view_post_v,parent,false);
feedViewHolder viewHolder = new feedViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull feedViewHolder holder, int position) {
FeedData_v postdata = postList.get(position);
holder.profileImage.setImageResource(postdata.getProfileImage());
holder.postImage.setImageResource(postdata.getPostImage());
holder.userName.setText(postdata.getUserName());
holder.caption.setText(postdata.getCaption());
holder.likes.setText(postdata.getLikes());
holder.comments.setText(postdata.getComments());
holder.favorites.setText(postdata.getFavorites());
}
@Override
public int getItemCount() {
return postList.size();
}
}
| true |
38acceac5698b662e7447717f43a0a3983b7f061
|
Java
|
ysenarath/FalconFS
|
/src/main/java/lk/uomcse/fs/udp/Receiver.java
|
UTF-8
| 1,681 | 3.0625 | 3 |
[] |
no_license
|
package lk.uomcse.fs.udp;
import com.google.common.collect.Queues;
import lk.uomcse.fs.entity.Packet;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class Receiver extends Thread {
private boolean running;
private DatagramSocket socket;
private final BlockingQueue<Packet> packets;
/**
* Creates the part of client that handles receives
*
* @param socket Datagram socket
*/
public Receiver(DatagramSocket socket) {
this.packets = Queues.newLinkedBlockingDeque();
this.running = false;
this.socket = socket;
}
/**
* Thread function
*/
public void run() {
running = true;
while (running) {
byte[] buf = new byte[65536];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
try {
socket.receive(packet);
Packet p = new Packet(packet);
packets.offer(p);
} catch (IOException ignored) {
// -- Retry
}
}
}
/**
* Takes packets received from the queue
*
* @return received message
* @throws InterruptedException Whether receive was interrupted
*/
public Packet receive() throws InterruptedException {
return packets.take();
}
/**
* Sets run status and interrupt current activities
*
* @param running value
*/
public void setRunning(boolean running) {
this.running = running;
this.interrupt();
}
}
| true |
9a3401784f3d17dad459f66949880bc46fa5e06a
|
Java
|
frank-lesser/pikaparser
|
/src/main/java/pikaparser/clause/terminal/CharSeq.java
|
UTF-8
| 1,156 | 2.46875 | 2 |
[
"MIT"
] |
permissive
|
package pikaparser.clause.terminal;
import pikaparser.memotable.Match;
import pikaparser.memotable.MemoKey;
import pikaparser.memotable.MemoTable;
import pikaparser.parser.utils.StringUtils;
public class CharSeq extends Terminal {
public final String str;
public final boolean ignoreCase;
public CharSeq(String str, boolean ignoreCase) {
super();
this.str = str;
this.ignoreCase = ignoreCase;
}
@Override
public Match match(MemoTable memoTable, MemoKey memoKey, String input) {
if (memoKey.startPos <= input.length() - str.length()
&& input.regionMatches(ignoreCase, memoKey.startPos, str, 0, str.length())) {
// Terminals are not memoized (i.e. don't look in the memo table)
return new Match(memoKey, /* firstMatchingSubClauseIdx = */ 0, /* len = */ str.length(),
Match.NO_SUBCLAUSE_MATCHES);
}
return null;
}
@Override
public String toString() {
if (toStringCached == null) {
toStringCached = '"' + StringUtils.escapeString(str) + '"';
}
return toStringCached;
}
}
| true |
33de0f2b310e99950aa82ecb0ee4417c9ed743b7
|
Java
|
Anar-Framework/anar-adhocquery
|
/src/main/java/af/gov/anar/query/adhocquery/domain/ReportRunFrequency.java
|
UTF-8
| 1,004 | 2.515625 | 3 |
[] |
no_license
|
package af.gov.anar.query.adhocquery.domain;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public enum ReportRunFrequency {
DAILY(1, "reportRunFrequency.daily"),
WEEKLY(2, "reportRunFrequency.weekly"),
MONTHLY(3, "reportRunFrequency.monthly"),
YEARLY(4, "reportRunFrequency.yearly"),
CUSTOM(5, "reportRunFrequency.custom");
private static final Map<Long, ReportRunFrequency> MAP = Arrays.stream(ReportRunFrequency.values()).collect(Collectors.toMap(
ReportRunFrequency::getValue, e -> e
));
private final long value;
private final String code;
private ReportRunFrequency(final long value, final String code) {
this.value = value;
this.code = code;
}
public long getValue() {
return this.value;
}
public String getCode() {
return this.code;
}
public static ReportRunFrequency fromId(final long id) {
return ReportRunFrequency.MAP.get(id);
}
}
| true |
8d472ba96ec86954d3e9685d58cc5d0bb09bde2c
|
Java
|
geralex/SWG-NGE
|
/dsrc/sku.0/sys.server/compiled/game/script/theme_park/destructible.java
|
UTF-8
| 4,924 | 1.96875 | 2 |
[] |
no_license
|
package script.theme_park;
import script.*;
import script.base_class.*;
import script.combat_engine.*;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Vector;
import script.base_script;
import script.library.ai_lib;
import script.library.beast_lib;
import script.library.factions;
import script.library.trial;
import script.library.utils;
public class destructible extends script.base_script
{
public destructible()
{
}
public int OnAttach(obj_id self) throws InterruptedException
{
int hp = hasObjVar(self, "hp") ? getIntObjVar(self, "hp") : 5000;
setMaxHitpoints(self, hp);
setHitpoints(self, hp);
String attract = hasObjVar(self, "attraction") ? getStringObjVar(self, "attraction") : "none";
int attractRange = hasObjVar(self, "attraction_range") ? getIntObjVar(self, "attraction_range") : 20;
if (!attract.equals("none"))
{
trial.setInterest(self);
setTriggerVolume(self, attract, attractRange);
}
int ignore_player = hasObjVar(self, "ignore_player") ? getIntObjVar(self, "ignore_player") : 0;
if (ignore_player == 1)
{
factions.setIgnorePlayer(self);
}
return SCRIPT_CONTINUE;
}
public int OnObjectDisabled(obj_id self, obj_id killer) throws InterruptedException
{
location death = getLocation(self);
String effect = "clienteffect/combat_explosion_lair_large.cef";
if (hasObjVar(self, "deathEffect"))
{
effect = getStringObjVar(self, "deathEffect");
}
playClientEffectObj(killer, effect, self, "");
playClientEffectLoc(killer, effect, death, 0);
setInvulnerable(self, true);
messageTo(self, "destroyDisabledLair", null, .5f, false);
obj_id[] enemies = getWhoIsTargetingMe(self);
if (enemies != null && enemies.length > 1)
{
for (int i = 0; i < enemies.length; i++)
{
if (isPlayer(enemies[i]))
{
}
}
}
return SCRIPT_CONTINUE;
}
public int OnTriggerVolumeEntered(obj_id self, String volumeName, obj_id breacher) throws InterruptedException
{
if (!ai_lib.isMob(breacher) || beast_lib.isBeast(breacher))
{
return SCRIPT_CONTINUE;
}
String attraction_name = getStringObjVar(self, "attraction");
String social = ai_lib.getSocialGroup(breacher);
if (volumeName.equals(attraction_name))
{
if (social != null && !social.equals("") && social.equals(attraction_name))
{
startCombat(breacher, self);
}
}
return SCRIPT_CONTINUE;
}
public void setTriggerVolume(obj_id self, String vol_name, int vol_range) throws InterruptedException
{
createTriggerVolume(vol_name, vol_range, true);
}
public int destroyDisabledLair(obj_id self, dictionary params) throws InterruptedException
{
destroyObject(self);
return SCRIPT_CONTINUE;
}
public int OnObjectDamaged(obj_id self, obj_id attacker, obj_id weapon, int damage) throws InterruptedException
{
int curHP = getHitpoints(self);
int maxHP = getMaxHitpoints(self);
int smolder = (maxHP - (maxHP / 3));
int fire = (maxHP / 3);
if (!hasObjVar(self, "playingEffect"))
{
if (curHP < smolder)
{
if (curHP < fire)
{
location death = getLocation(self);
setObjVar(self, "playingEffect", 1);
messageTo(self, "effectManager", null, 15, true);
}
else
{
location death = getLocation(self);
setObjVar(self, "playingEffect", 1);
messageTo(self, "effectManager", null, 15, true);
}
}
}
return SCRIPT_CONTINUE;
}
public int effectManager(obj_id self, dictionary params) throws InterruptedException
{
removeObjVar(self, "playingEffect");
return SCRIPT_CONTINUE;
}
public void reportDeath(obj_id self, obj_id killer) throws InterruptedException
{
int row = getIntObjVar(self, "row");
String spawn_id = "none";
if (hasObjVar(self, "spawn_id"))
{
spawn_id = getStringObjVar(self, "spawn_id");
}
int respawn = getIntObjVar(self, "respawn");
dictionary dict = trial.getSessionDict(trial.getParent(self));
dict.put("object", self);
dict.put("row", row);
dict.put("spawn_id", spawn_id);
dict.put("respawn", respawn);
dict.put("killer", killer);
messageTo(trial.getParent(self), "terminationCallback", dict, 0.0f, false);
}
}
| true |
85c46d1c3b5550ce486ed6afc791c50b2a0c32b7
|
Java
|
andresc889/TheQuantumAvenger
|
/GameData.java
|
UTF-8
| 17,695 | 2.5 | 2 |
[] |
no_license
|
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import javax.vecmath.Vector2d;
public class GameData implements DisappearanceListener {
public final static int NUM_OF_FREE_PARTICLES = 25;
public final static int MIN_DISTANCE_FREE_PARTICLES_EDGES = 5;
public final static int CLEARANCE_DISTANCE = 100;
public final static int DIFFICULTY_EASY = 1;
public final static int DIFFICULTY_NORMAL = 2;
public final static int DIFFICULTY_HARD = 3;
private final static int INITIAL_LIFE = 100;
private boolean initialized;
private boolean keyUpOn;
private boolean keyLeftOn;
private boolean keyRightOn;
private boolean shooterOn;
private boolean shooterReleased;
final List<GameFigure> figures;
final List<Disappearable> figuresToRemove;
SpaceShip spaceShip;
private int life;
private int lifeDecreaseSpeed;
private int score;
private double maxSpaceShipDistance;
private int difficulty;
private int firedShotsCount;
private int accurateShotsCount;
private boolean win;
private boolean loss;
public GameData() {
initialized = false;
difficulty = DIFFICULTY_EASY;
firedShotsCount = 0;
accurateShotsCount = 0;
win = false;
loss = false;
keyUpOn = false;
keyLeftOn = false;
keyRightOn = false;
shooterOn = false;
shooterReleased = true;
figures = Collections.synchronizedList(new ArrayList<GameFigure>());
figuresToRemove = Collections.synchronizedList(new ArrayList<Disappearable>());
life = INITIAL_LIFE;
score = 0;
}
public void setDifficulty(int difficulty) {
this.difficulty = difficulty;
}
private void initialize() {
if (initialized) {
return;
}
double charges[] = {-1, 0, 1};
double chargeMultiplier;
switch (difficulty) {
case DIFFICULTY_EASY:
chargeMultiplier = 3;
lifeDecreaseSpeed = 5;
break;
case DIFFICULTY_NORMAL:
chargeMultiplier = 10;
lifeDecreaseSpeed = 7;
break;
case DIFFICULTY_HARD:
chargeMultiplier = 20;
lifeDecreaseSpeed = 10;
break;
default:
chargeMultiplier = 1;
}
int centerX = GamePanel.GAME_AREA_WIDTH / 2;
int centerY = GamePanel.GAME_AREA_HEIGHT / 2;
maxSpaceShipDistance = Math.sqrt(GamePanel.GAME_AREA_WIDTH * GamePanel.GAME_AREA_WIDTH + GamePanel.GAME_AREA_HEIGHT * GamePanel.GAME_AREA_HEIGHT);
// Add the space ship
spaceShip = new SpaceShip(1, chargeMultiplier * charges[difficulty == DIFFICULTY_EASY ? 1 : (Math.random() > 0.5 ? 0 : 2)]);
figures.add(spaceShip);
// Add free particles
FreeParticle newParticle;
int minX;
int minY;
int maxX;
int maxY;
int randomX;
int randomY;
for (int i = 0; i < NUM_OF_FREE_PARTICLES; i++) {
// Generate charge randomly
newParticle = new FreeParticle(0.5, chargeMultiplier * charges[(int) (3 * Math.random())]);
newParticle.setDisappearanceHandler(this);
// Set the position of the particle randomly and away from the center.
// Also, make sure every charge does not overlap with another
while (true) {
minX = minY = 0;
maxX = GamePanel.GAME_AREA_WIDTH - 2 * newParticle.collisionRadius;
maxY = GamePanel.GAME_AREA_HEIGHT - 2 * newParticle.collisionRadius;
randomX = minX + (int) ((maxX - minX + 1) * Math.random());
randomY = minY + (int) ((maxY - minY + 1) * Math.random());
Vector2d candidatePosition = new Vector2d(randomX, randomY);
// Make sure ship is cleared
Vector2d fromShip = new Vector2d(candidatePosition);
fromShip.sub(spaceShip.position);
if (fromShip.length() - newParticle.collisionRadius < CLEARANCE_DISTANCE) {
continue;
}
// Make sure all existing free particles are cleared
boolean existingFreeParticlesCleared = true;
for (int j = 0; j < figures.size(); j++) {
if (!(figures.get(j) instanceof FreeParticle)) {
continue;
}
Vector2d fromCurrentParticle = new Vector2d(candidatePosition);
fromCurrentParticle.sub(figures.get(j).position);
if (fromCurrentParticle.length() - newParticle.collisionRadius - figures.get(j).collisionRadius < MIN_DISTANCE_FREE_PARTICLES_EDGES) {
existingFreeParticlesCleared = false;
break;
}
}
if (existingFreeParticlesCleared) {
break;
}
}
newParticle.setPosition(new Vector2d(randomX, randomY));
// Set the initial velocity of 0-charge particles
if (newParticle.charge == 0) {
double randomAngle = 2 * Math.PI * Math.random();
newParticle.velocity = new Vector2d(Math.cos(randomAngle), Math.sin(randomAngle));
newParticle.velocity.scale(1 + 2 * Math.random());
}
figures.add(newParticle);
}
initialized = true;
}
public boolean isKeyUpOn() {
return keyUpOn;
}
public void setKeyUpOn(boolean keyUpOn) {
this.keyUpOn = keyUpOn;
}
public boolean isKeyLeftOn() {
return keyLeftOn;
}
public void setKeyLeftOn(boolean keyLeftOn) {
this.keyLeftOn = keyLeftOn;
}
public boolean isKeyRightOn() {
return keyRightOn;
}
public void setKeyRightOn(boolean keyRightOn) {
this.keyRightOn = keyRightOn;
}
public void setShooterOn(boolean shooterOn) {
if (shooterOn && !shooterReleased) {
return;
}
this.shooterOn = shooterOn;
this.shooterReleased = !shooterOn;
}
public void setShooterReleased(boolean shooterReleased) {
this.shooterReleased = shooterReleased;
}
public String getScoreAsString() {
return String.format("%07d", score);
}
public String getAccuracyPercentAsString() {
if (firedShotsCount > 0) {
return String.format("%.02f%%", accurateShotsCount * 100.0 / firedShotsCount);
} else {
return "N/A";
}
}
public double getLifeRemainingRatio() {
return (double)life / INITIAL_LIFE;
}
public boolean isWin() {
return win;
}
public boolean isLoss() {
return loss;
}
public void update() {
if (!initialized) {
initialize();
}
List<GameFigure> remove = new ArrayList<>();
GameFigure f;
Particle particle1;
Particle particle2;
double distance;
Vector2d unitNormal;
Vector2d unitTangent;
double normalInitialVelocity1;
double tangentInitialVelocity1;
double normalInitialVelocity2;
double tangentInitialVelocity2;
Vector2d newNormalVelocity1;
Vector2d newTangentVelocity1;
Vector2d newVelocity1;
Vector2d newNormalVelocity2;
Vector2d newTangentVelocity2;
Vector2d newVelocity2;
synchronized (figures) {
// Remove figures
synchronized(figuresToRemove) {
for (int i = 0; i < figuresToRemove.size(); i++) {
figures.remove(figuresToRemove.get(i));
}
figuresToRemove.clear();
}
// Check if we have to shoot a missile
if (shooterOn) {
Vector2d direction = spaceShip.getNormalizedDirection();
Vector2d startPosition = new Vector2d(direction);
startPosition.scale(Missile.MISSILE_RADIUS);
startPosition.add(spaceShip.getFrontPosition());
Vector2d startVelocity = new Vector2d(direction);
startVelocity.scale(Missile.MISSILE_SPEED);
Missile newMissile = new Missile(startPosition, startVelocity);
newMissile.setDisappearanceHandler(this);
figures.add(newMissile);
firedShotsCount++;
shooterOn = false;
}
for (int i = 0; i < figures.size(); i++) {
((Particle)figures.get(i)).setNetForce(new Vector2d(0, 0));
}
for (int i = 0; i < figures.size() && !loss; i++) {
f = figures.get(i);
// Check if we are updating the space ship
if (f instanceof SpaceShip) {
// Update the net force depending on keys
SpaceShip ship = (SpaceShip) f;
if (keyUpOn) {
Vector2d newNetForce = ship.getNormalizedDirection();
newNetForce.scale(0.3);
ship.setNetForce(newNetForce);
} else {
ship.setNetForce(new Vector2d(0, 0));
}
if (keyLeftOn) {
ship.rotateLeft();
} else if (keyRightOn) {
ship.rotateRight();
}
}
// Calculate the force between this particle and the others
particle1 = (Particle) f;
for (int j = i + 1; j < figures.size(); j++) {
particle2 = (Particle) figures.get(j);
boolean ignoreInteraction = false;
if (particle1 instanceof Destroyable) {
ignoreInteraction = ((Destroyable)particle1).isBeingDestroyed();
}
if (!ignoreInteraction && particle2 instanceof Destroyable) {
ignoreInteraction = ((Destroyable)particle2).isBeingDestroyed();
}
if (ignoreInteraction) {
continue;
}
Vector2d newForce = new Vector2d(particle2.position);
newForce.sub(particle1.position);
distance = newForce.length();
newForce.scale(-1 * particle1.charge * particle2.charge / Math.pow(newForce.length(), 3));
// Update the net force for both particles involved (except for SpaceShip)
if (!(particle1 instanceof SpaceShip)) {
particle1.netForce.add(newForce);
}
newForce.scale(-1);
if (!(particle2 instanceof SpaceShip)) {
particle2.netForce.add(newForce);
}
// Check for a collision
if (distance <= particle1.collisionRadius + particle2.collisionRadius) {
// Check if one of the particles is a missile and the other a free particle
if ((particle1 instanceof Missile && particle2 instanceof FreeParticle) || (particle1 instanceof FreeParticle && particle2 instanceof Missile)) {
Destroyable destroyable1 = (Destroyable)particle1;
Destroyable destroyable2 = (Destroyable)particle2;
FreeParticle particle = particle1 instanceof FreeParticle ? (FreeParticle)particle1 : (FreeParticle)particle2;
// Destroy both
if (!destroyable1.isBeingDestroyed() && !destroyable2.isBeingDestroyed()) {
destroyable1.destroy();
destroyable2.destroy();
// Increase score
int chargeMultiplier = particle.charge != 0 ? 2 : 1;
int radiusMultiplier = (int)((double)FreeParticle.MAX_RADIUS * 2 / particle.collisionRadius);
int speedMultiplier = (int)particle.velocity.length() + 1;
if (speedMultiplier > 20) {
speedMultiplier = 20;
}
Vector2d spaceShipDistance = new Vector2d(particle.position);
spaceShipDistance.sub(spaceShip.position);
int distanceMultiplier = (int)(spaceShipDistance.length() * 20 / maxSpaceShipDistance) + 1;
score += 5 * chargeMultiplier * radiusMultiplier * speedMultiplier * distanceMultiplier;
// Increase accurate shots count
accurateShotsCount++;
}
continue;
}
// Check if ship collided with a free particle
if ((particle1 instanceof SpaceShip && particle2 instanceof FreeParticle) || (particle1 instanceof FreeParticle && particle2 instanceof SpaceShip)) {
// Decrease life
life -= lifeDecreaseSpeed;
// Check if user lost
if (life <= 0) {
loss = true;
break;
}
}
// Handle collision according to method in http://www.imada.sdu.dk/~rolf/Edu/DM815/E10/2dcollisions.pdf
unitNormal = new Vector2d(particle2.position);
unitNormal.sub(particle1.position);
unitNormal.normalize();
unitTangent = new Vector2d(-1 * unitNormal.getY(), unitNormal.getX());
// Find the normal and tangent components of the initial velocities
normalInitialVelocity1 = particle1.velocity.dot(unitNormal);
tangentInitialVelocity1 = particle1.velocity.dot(unitTangent);
normalInitialVelocity2 = particle2.velocity.dot(unitNormal);
tangentInitialVelocity2 = particle2.velocity.dot(unitTangent);
// Obtain the new velocities
newNormalVelocity1 = new Vector2d(unitNormal);
newNormalVelocity1.scale((normalInitialVelocity1 * (particle1.mass - particle2.mass) + 2 * particle2.mass * normalInitialVelocity2) / (particle1.mass + particle2.mass));
newTangentVelocity1 = new Vector2d(unitTangent);
newTangentVelocity1.scale(tangentInitialVelocity1);
newNormalVelocity2 = new Vector2d(unitNormal);
newNormalVelocity2.scale((normalInitialVelocity2 * (particle2.mass - particle1.mass) + 2 * particle1.mass * normalInitialVelocity1) / (particle1.mass + particle2.mass));
newTangentVelocity2 = new Vector2d(unitTangent);
newTangentVelocity2.scale(tangentInitialVelocity2);
newVelocity1 = new Vector2d(newNormalVelocity1);
newVelocity1.add(newTangentVelocity1);
particle1.setVelocity(newVelocity1);
newVelocity2 = new Vector2d(newNormalVelocity2);
newVelocity2.add(newTangentVelocity2);
particle2.setVelocity(newVelocity2);
// Force them to be apart
particle2.overridePosition = true;
particle2.position = new Vector2d(unitNormal);
particle2.position.scale(particle1.collisionRadius + particle2.collisionRadius + 5);
particle2.position.add(particle1.position);
}
}
f.update();
}
figures.removeAll(remove);
}
}
@Override
public void processDisappearance(DisappearanceEvent event) {
synchronized (figuresToRemove) {
figuresToRemove.add(event.getObject());
if (event.getObject() instanceof FreeParticle) {
if (accurateShotsCount == NUM_OF_FREE_PARTICLES) {
win = true;
}
}
}
}
}
| true |
c69787edeadbd9cbb33248d5f937827036148cff
|
Java
|
hzr958/myProjects
|
/scmv6/web-mobile/src/main/java/com/smate/web/mobile/controller/data/dyn/MobileShareResDataController.java
|
UTF-8
| 4,132 | 1.875 | 2 |
[] |
no_license
|
package com.smate.web.mobile.controller.data.dyn;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import com.smate.core.base.utils.app.AppActionUtils;
import com.smate.core.base.utils.number.NumberUtils;
import com.smate.core.base.utils.security.Des3Utils;
import com.smate.core.base.utils.security.SecurityUtils;
import com.smate.web.mobile.consts.SmateShareConstant;
import com.smate.web.mobile.share.service.FindResInfoService;
import com.smate.web.mobile.share.service.ShareToSmateService;
import com.smate.web.mobile.share.vo.SmateShareVO;
/**
* 移动端资源分享控制器
*
* @author wsn
* @date May 23, 2019
*/
@Controller
public class MobileShareResDataController {
private static final Logger logger = LoggerFactory.getLogger(MobileShareResDataController.class);
@Value("${domainMobile}")
private String domainMobile;
@Value("${domainscm}")
private String domainScm;
private Map<String, ShareToSmateService> shareServiceMap;
@Autowired
private RestTemplate restTemplate;
@Autowired
private ShareToSmateService shareResToDynService;
@Autowired
private ShareToSmateService shareResToFriendService;
@Autowired
private ShareToSmateService shareResToGrpService;
@Autowired
private FindResInfoService findResInfoService;
/**
* 移动端资源分享入口 "data/psn/share/res",
*
* @param vo
* @return
*/
@RequestMapping(value = "/data/psn/share/res", produces = "application/json;charset=UTF-8")
@ResponseBody
public Object shareResToSmate(SmateShareVO vo) {
Long psnId = SecurityUtils.getCurrentUserId();
Map<String, Object> result = new HashMap<String, Object>();
String status = "error";
try {
// 需要分享到的模块
if (StringUtils.isNotBlank(vo.getShareTo()) && shareServiceMap.containsKey(vo.getShareTo())
&& NumberUtils.isNotNullOrZero(psnId)) {
vo.setDomainMobile(domainMobile);
vo.setDes3CurrentPsnId(Des3Utils.encodeToDes3(psnId.toString()));
result = shareServiceMap.get(vo.getShareTo()).doShare(vo);
status = "success";
} else {
vo.setErrorCode(SmateShareConstant.SHARE_ERROR_CODE_CHECK_FALSE);
vo.setErrorMsg(SmateShareConstant.SHARE_ERROR_MSG_CHECK_FALSE);
}
} catch (Exception e) {
logger.error("移动端分享资源异常,psnId={}, resId={}, resType={}, shareTo={}, grpId={}, friendId={}, shareText={}", psnId,
vo.getDes3ResId(), vo.getResType(), vo.getShareTo(), vo.getDes3GrpId(), vo.getDes3FriendIds(),
vo.getShareText(), e);
vo.setErrorCode(SmateShareConstant.SHARE_ERROR_CODE_INTERFACE_ERROR);
vo.setErrorMsg(SmateShareConstant.SHARE_ERROR_MSG_INTERFACE_ERROR);
}
result.put("result", status);
result.put("error_code", vo.getErrorCode());
result.put("error_msg", vo.getErrorMsg());
result.put("warn_code", vo.getWarnCode());
result.put("warn_msg", vo.getWarnMsg());
return AppActionUtils.buildReturnInfo(result, 0,
AppActionUtils.changeResultStatus(Objects.toString(status, "error")), vo.getErrorMsg());
}
/**
* 执行每个RequestMapping之前都会先执行这个
*/
@ModelAttribute
private void initShareServiceMap() {
if (shareServiceMap == null) {
shareServiceMap = new HashMap<String, ShareToSmateService>();
shareServiceMap.put(SmateShareConstant.SHARE_TO_DYNAMIC, shareResToDynService);
shareServiceMap.put(SmateShareConstant.SHARE_TO_FRIEND, shareResToFriendService);
shareServiceMap.put(SmateShareConstant.SHARE_TO_GROUP, shareResToGrpService);
}
}
}
| true |
fb67a9b031e78eee19de72085ef1dea604f6c618
|
Java
|
sandeep1502/Inventory
|
/Sample/src/main/java/com/project/ItemspecModel.java
|
UTF-8
| 904 | 2.046875 | 2 |
[] |
no_license
|
package com.project;
public class ItemspecModel {
private int item_id ;
private int itsp_index;
private String itsp_group;
private String itsp_title;
private String itsp_value;
public int getItem_id() {
return item_id;
}
public void setItem_id(int item_id) {
this.item_id = item_id;
}
public int getItsp_index() {
return itsp_index;
}
public void setItsp_index(int itsp_index) {
this.itsp_index = itsp_index;
}
public String getItsp_group() {
return itsp_group;
}
public void setItsp_group(String itsp_group) {
this.itsp_group = itsp_group;
}
public String getItsp_title() {
return itsp_title;
}
public void setItsp_title(String itsp_title) {
this.itsp_title = itsp_title;
}
public String getItsp_value() {
return itsp_value;
}
public void setItsp_value(String itsp_value) {
this.itsp_value = itsp_value;
}
}
| true |
1b599e9556f6b7debccdf63e01b561b1be98a46a
|
Java
|
NudgeApm/java-timeseries
|
/src/test/java/timeseries/operators/LagPolynomialSpec.java
|
UTF-8
| 2,424 | 2.625 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
package timeseries.operators;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import org.junit.Test;
import data.TestData;
import timeseries.TimeSeries;
import timeseries.operators.LagPolynomial;
public final class LagPolynomialSpec {
@Test
public void whenLagPolyInverseAppliedResultCorrect() {
TimeSeries series = TestData.ausbeerSeries();
LagPolynomial poly = LagPolynomial.differences(1);
LagPolynomial seasPoly = LagPolynomial.firstSeasonalDifference(4);
System.out.println(seasPoly);
assertThat(poly.applyInverse(series, 2), is(equalTo(series.at(1))));
}
@Test
public void whenLagPolyTwoDiffInverseAppliedResultCorrect() {
TimeSeries series = TestData.ausbeerSeries();
LagPolynomial poly = LagPolynomial.differences(2);
assertThat(poly.applyInverse(series, 2), is(equalTo(2 * series.at(1) - series.at(0))));
}
@Test
public void whenZeroDegreeLagPolynomialCreatedZeroDegreePolyReturned() {
LagPolynomial poly = new LagPolynomial();
assertThat(poly.coefficients, is(equalTo(new double[] {1.0})));
}
@Test
public void whenZeroDegreeLagPolyMultipliedByDiffPolyCoeffsCorrect() {
LagPolynomial poly = new LagPolynomial();
LagPolynomial diff = LagPolynomial.firstDifference();
LagPolynomial polyDiff = poly.times(diff);
assertThat(polyDiff.coefficients, is(equalTo(new double[] {1.0, -1.0})));
}
@Test
public void whenSecondDiffLagPolyCreatedCoefficientsCorrect() {
LagPolynomial poly = LagPolynomial.differences(2);
assertThat(poly.coefficients, is(equalTo(new double[] {1.0, -2.0, 1.0})));
}
@Test
public void whenSecondDiffArOneLagPolyCreatedCoefficientsCorrect() {
LagPolynomial diffPoly = LagPolynomial.differences(2);
LagPolynomial arOne = LagPolynomial.autoRegressive(0.5);
LagPolynomial poly = diffPoly.times(arOne);
assertThat(poly.coefficients, is(equalTo(new double[] {1.0, -2.5, 2.0, -0.5})));
}
@Test
public void whenNewAutoRegressivePolyCreatedCofficientsCorrect() {
LagPolynomial poly = LagPolynomial.autoRegressive(0.4);
assertThat(poly.coefficients, is(equalTo(new double[] {1.0, -0.4})));
}
@Test
public void whenNewMovingAveragePolyCreatedCofficientsCorrect() {
LagPolynomial poly = LagPolynomial.movingAverage(0.4);
assertThat(poly.coefficients, is(equalTo(new double[] {1.0, 0.4})));
}
}
| true |
3ee1f55c734f0cfb36dcd1217eb30d23bab94656
|
Java
|
Abdealitin/lab_assignments
|
/exceptions-practice/src/main/java/com/yash/multithreading/SyncDemo.java
|
UTF-8
| 997 | 3.296875 | 3 |
[] |
no_license
|
package com.yash.multithreading;
class FirstThread{
public void display(String s) {
System.out.print("["+s);
try {
Thread.sleep(1000);
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("]");
}
}
class SecondThread extends Thread{
String s;
FirstThread fobj;
SecondThread (FirstThread fp,String str){
fobj=fp;
s=str;
start();
}
public void run() {
fobj.display(s);
}
}
public class SyncDemo {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
FirstThread fnew = new FirstThread();
SecondThread ss = new SecondThread(fnew,"welcome");
//ss.sleep(1000);
ss.join(1000);
SecondThread ss1 = new SecondThread(fnew,"Hello");
//ss1.sleep(3000);
ss1.join(2500);
SecondThread ss2 = new SecondThread(fnew,"Trainees");
//ss2.sleep(3500);
ss2.join(3500);
Thread.sleep(2000);
System.out.println(ss2.isAlive());
}
}
| true |
37fd877b64c7a62523b8d4bd1c731fe94cfdd649
|
Java
|
nitaiaharoni1/Introduction-to-Computer-Graphics
|
/Ex6/Procyon/com/jogamp/newt/opengl/util/NEWTDemoListener.java
|
UTF-8
| 26,464 | 1.882813 | 2 |
[] |
no_license
|
//
// Decompiled by Procyon v0.5.30
//
package com.jogamp.newt.opengl.util;
import com.jogamp.common.util.IOUtil;
import com.jogamp.nativewindow.CapabilitiesImmutable;
import com.jogamp.newt.Display;
import com.jogamp.newt.event.*;
import com.jogamp.newt.opengl.GLWindow;
import com.jogamp.opengl.*;
import com.jogamp.opengl.util.Gamma;
import com.jogamp.opengl.util.PNGPixelRect;
import jogamp.newt.driver.PNGIcon;
import java.net.URLConnection;
import java.util.ArrayList;
public class NEWTDemoListener extends WindowAdapter implements KeyListener, MouseListener
{
protected final GLWindow glWindow;
final Display.PointerIcon[] pointerIcons;
int pointerIconIdx;
float gamma;
float brightness;
float contrast;
boolean confinedFixedCenter;
private boolean quitAdapterShouldQuit;
private boolean quitAdapterEnabled;
private boolean quitAdapterEnabled2;
public NEWTDemoListener(final GLWindow glWindow, final Display.PointerIcon[] pointerIcons) {
this.pointerIconIdx = 0;
this.gamma = 1.0f;
this.brightness = 0.0f;
this.contrast = 1.0f;
this.confinedFixedCenter = false;
this.quitAdapterShouldQuit = false;
this.quitAdapterEnabled = false;
this.quitAdapterEnabled2 = true;
this.glWindow = glWindow;
if (null != pointerIcons) {
this.pointerIcons = pointerIcons;
}
else {
this.pointerIcons = createPointerIcons(this.glWindow.getScreen().getDisplay());
}
}
public NEWTDemoListener(final GLWindow glWindow) {
this(glWindow, null);
}
protected void printlnState(final String s) {
System.err.println(s + ": " + this.glWindow.getX() + "/" + this.glWindow.getY() + " " + this.glWindow.getSurfaceWidth() + "x" + this.glWindow.getSurfaceHeight() + ", f " + this.glWindow.isFullscreen() + ", a " + this.glWindow.isAlwaysOnTop() + ", " + this.glWindow.getInsets() + ", state " + this.glWindow.getStateMaskString());
}
protected void printlnState(final String s, final String s2) {
System.err.println(s + ": " + this.glWindow.getX() + "/" + this.glWindow.getY() + " " + this.glWindow.getSurfaceWidth() + "x" + this.glWindow.getSurfaceHeight() + ", f " + this.glWindow.isFullscreen() + ", a " + this.glWindow.isAlwaysOnTop() + ", " + this.glWindow.getInsets() + ", state " + this.glWindow.getStateMaskString() + ", " + s2);
}
@Override
public void keyPressed(final KeyEvent keyEvent) {
if (keyEvent.isAutoRepeat() || keyEvent.isConsumed()) {
return;
}
switch (keyEvent.getKeySymbol()) {
case 32: {
keyEvent.setConsumed(true);
this.glWindow.invokeOnCurrentThread(new Runnable() {
@Override
public void run() {
if (NEWTDemoListener.this.glWindow.getAnimator().isPaused()) {
NEWTDemoListener.this.glWindow.getAnimator().resume();
}
else {
NEWTDemoListener.this.glWindow.getAnimator().pause();
}
}
});
break;
}
case 65: {
keyEvent.setConsumed(true);
this.glWindow.invokeOnNewThread(null, false, new Runnable() {
@Override
public void run() {
NEWTDemoListener.this.printlnState("[set alwaysontop pre]");
NEWTDemoListener.this.glWindow.setAlwaysOnTop(!NEWTDemoListener.this.glWindow.isAlwaysOnTop());
NEWTDemoListener.this.printlnState("[set alwaysontop post]");
}
});
break;
}
case 66: {
keyEvent.setConsumed(true);
this.glWindow.invokeOnNewThread(null, false, new Runnable() {
@Override
public void run() {
NEWTDemoListener.this.printlnState("[set alwaysonbottom pre]");
NEWTDemoListener.this.glWindow.setAlwaysOnBottom(!NEWTDemoListener.this.glWindow.isAlwaysOnBottom());
NEWTDemoListener.this.printlnState("[set alwaysonbottom post]");
}
});
break;
}
case 67: {
keyEvent.setConsumed(true);
this.glWindow.invokeOnNewThread(null, false, new Runnable() {
@Override
public void run() {
if (null != NEWTDemoListener.this.pointerIcons) {
NEWTDemoListener.this.printlnState("[set pointer-icon pre]");
final Display.PointerIcon pointerIcon = NEWTDemoListener.this.glWindow.getPointerIcon();
Display.PointerIcon pointerIcon2;
if (NEWTDemoListener.this.pointerIconIdx >= NEWTDemoListener.this.pointerIcons.length) {
pointerIcon2 = null;
NEWTDemoListener.this.pointerIconIdx = 0;
}
else {
pointerIcon2 = NEWTDemoListener.this.pointerIcons[NEWTDemoListener.this.pointerIconIdx++];
}
NEWTDemoListener.this.glWindow.setPointerIcon(pointerIcon2);
NEWTDemoListener.this.printlnState("[set pointer-icon post]", pointerIcon + " -> " + NEWTDemoListener.this.glWindow.getPointerIcon());
}
}
});
break;
}
case 68: {
keyEvent.setConsumed(true);
this.glWindow.invokeOnNewThread(null, false, new Runnable() {
@Override
public void run() {
NEWTDemoListener.this.printlnState("[set undecorated pre]");
NEWTDemoListener.this.glWindow.setUndecorated(!NEWTDemoListener.this.glWindow.isUndecorated());
NEWTDemoListener.this.printlnState("[set undecorated post]");
}
});
break;
}
case 70: {
keyEvent.setConsumed(true);
this.quitAdapterOff();
this.glWindow.invokeOnNewThread(null, false, new Runnable() {
@Override
public void run() {
NEWTDemoListener.this.printlnState("[set fullscreen pre]");
if (NEWTDemoListener.this.glWindow.isFullscreen()) {
NEWTDemoListener.this.glWindow.setFullscreen(false);
}
else if (keyEvent.isAltDown()) {
NEWTDemoListener.this.glWindow.setFullscreen(null);
}
else {
NEWTDemoListener.this.glWindow.setFullscreen(true);
}
NEWTDemoListener.this.printlnState("[set fullscreen post]");
NEWTDemoListener.this.quitAdapterOn();
}
});
break;
}
case 71: {
keyEvent.setConsumed(true);
this.glWindow.invokeOnNewThread(null, false, new Runnable() {
@Override
public void run() {
final float gamma = NEWTDemoListener.this.gamma + (keyEvent.isShiftDown() ? -0.1f : 0.1f);
System.err.println("[set gamma]: " + NEWTDemoListener.this.gamma + " -> " + gamma);
if (Gamma.setDisplayGamma(NEWTDemoListener.this.glWindow, gamma, NEWTDemoListener.this.brightness, NEWTDemoListener.this.contrast)) {
NEWTDemoListener.this.gamma = gamma;
}
}
});
break;
}
case 73: {
keyEvent.setConsumed(true);
this.glWindow.invokeOnNewThread(null, false, new Runnable() {
@Override
public void run() {
NEWTDemoListener.this.printlnState("[set pointer-visible pre]");
NEWTDemoListener.this.glWindow.setPointerVisible(!NEWTDemoListener.this.glWindow.isPointerVisible());
NEWTDemoListener.this.printlnState("[set pointer-visible post]");
}
});
break;
}
case 74: {
keyEvent.setConsumed(true);
this.glWindow.invokeOnNewThread(null, false, new Runnable() {
@Override
public void run() {
NEWTDemoListener.this.printlnState("[set pointer-confined pre]", "warp-center: " + keyEvent.isShiftDown());
final boolean confinedFixedCenter = !NEWTDemoListener.this.glWindow.isPointerConfined();
NEWTDemoListener.this.glWindow.confinePointer(confinedFixedCenter);
NEWTDemoListener.this.printlnState("[set pointer-confined post]", "warp-center: " + keyEvent.isShiftDown());
if (keyEvent.isShiftDown()) {
NEWTDemoListener.this.setConfinedFixedCenter(confinedFixedCenter);
}
else if (!confinedFixedCenter) {
NEWTDemoListener.this.setConfinedFixedCenter(false);
}
}
});
break;
}
case 77: {
keyEvent.setConsumed(true);
this.glWindow.invokeOnNewThread(null, false, new Runnable() {
@Override
public void run() {
boolean b;
boolean b2;
if (keyEvent.isControlDown()) {
b = false;
b2 = false;
}
else if (keyEvent.isShiftDown()) {
final boolean b3 = NEWTDemoListener.this.glWindow.isMaximizedHorz() && NEWTDemoListener.this.glWindow.isMaximizedVert();
b = !b3;
b2 = !b3;
}
else if (!keyEvent.isAltDown()) {
b = NEWTDemoListener.this.glWindow.isMaximizedHorz();
b2 = !NEWTDemoListener.this.glWindow.isMaximizedVert();
}
else if (keyEvent.isAltDown()) {
b = !NEWTDemoListener.this.glWindow.isMaximizedHorz();
b2 = NEWTDemoListener.this.glWindow.isMaximizedVert();
}
else {
b2 = NEWTDemoListener.this.glWindow.isMaximizedVert();
b = NEWTDemoListener.this.glWindow.isMaximizedHorz();
}
NEWTDemoListener.this.printlnState("[set maximize pre]", "max[vert " + b2 + ", horz " + b + "]");
NEWTDemoListener.this.glWindow.setMaximized(b, b2);
NEWTDemoListener.this.printlnState("[set maximize post]", "max[vert " + b2 + ", horz " + b + "]");
}
});
break;
}
case 81: {
if (this.quitAdapterEnabled && 0 == keyEvent.getModifiers()) {
System.err.println("QUIT Key " + Thread.currentThread());
this.quitAdapterShouldQuit = true;
break;
}
break;
}
case 80: {
keyEvent.setConsumed(true);
this.glWindow.invokeOnNewThread(null, false, new Runnable() {
@Override
public void run() {
NEWTDemoListener.this.printlnState("[set position pre]");
NEWTDemoListener.this.glWindow.setPosition(100, 100);
NEWTDemoListener.this.printlnState("[set position post]");
}
});
break;
}
case 82: {
keyEvent.setConsumed(true);
this.glWindow.invokeOnNewThread(null, false, new Runnable() {
@Override
public void run() {
NEWTDemoListener.this.printlnState("[set resizable pre]");
NEWTDemoListener.this.glWindow.setResizable(!NEWTDemoListener.this.glWindow.isResizable());
NEWTDemoListener.this.printlnState("[set resizable post]");
}
});
break;
}
case 83: {
keyEvent.setConsumed(true);
this.glWindow.invokeOnNewThread(null, false, new Runnable() {
@Override
public void run() {
NEWTDemoListener.this.printlnState("[set sticky pre]");
NEWTDemoListener.this.glWindow.setSticky(!NEWTDemoListener.this.glWindow.isSticky());
NEWTDemoListener.this.printlnState("[set sticky post]");
}
});
break;
}
case 86: {
keyEvent.setConsumed(true);
if (keyEvent.isControlDown()) {
this.glWindow.invoke(false, new GLRunnable() {
@Override
public boolean run(final GLAutoDrawable glAutoDrawable) {
final GL gl = glAutoDrawable.getGL();
final int swapInterval = gl.getSwapInterval();
int swapInterval2 = 0;
switch (swapInterval) {
case 0: {
swapInterval2 = -1;
break;
}
case -1: {
swapInterval2 = 1;
break;
}
case 1: {
swapInterval2 = 0;
break;
}
default: {
swapInterval2 = 1;
break;
}
}
gl.setSwapInterval(swapInterval2);
final GLAnimatorControl animator = glAutoDrawable.getAnimator();
if (null != animator) {
animator.resetFPSCounter();
}
if (glAutoDrawable instanceof FPSCounter) {
((FPSCounter)glAutoDrawable).resetFPSCounter();
}
System.err.println("Swap Interval: " + swapInterval + " -> " + swapInterval2 + " -> " + gl.getSwapInterval());
return true;
}
});
break;
}
this.glWindow.invokeOnNewThread(null, false, new Runnable() {
@Override
public void run() {
final boolean visible = NEWTDemoListener.this.glWindow.isVisible();
NEWTDemoListener.this.printlnState("[set visible pre]");
NEWTDemoListener.this.glWindow.setVisible(!visible);
NEWTDemoListener.this.printlnState("[set visible post]");
if (visible && !keyEvent.isShiftDown()) {
try {
Thread.sleep(5000L);
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
NEWTDemoListener.this.printlnState("[reset visible pre]");
NEWTDemoListener.this.glWindow.setVisible(true);
NEWTDemoListener.this.printlnState("[reset visible post]");
}
}
});
break;
}
case 87: {
keyEvent.setConsumed(true);
this.glWindow.invokeOnNewThread(null, false, new Runnable() {
@Override
public void run() {
NEWTDemoListener.this.printlnState("[set pointer-pos pre]");
NEWTDemoListener.this.glWindow.warpPointer(NEWTDemoListener.this.glWindow.getSurfaceWidth() / 2, NEWTDemoListener.this.glWindow.getSurfaceHeight() / 2);
NEWTDemoListener.this.printlnState("[set pointer-pos post]");
}
});
break;
}
case 88: {
keyEvent.setConsumed(true);
final float[] currentSurfaceScale = this.glWindow.getCurrentSurfaceScale(new float[2]);
float[] surfaceScale;
if (currentSurfaceScale[0] == 1.0f) {
surfaceScale = new float[] { 0.0f, 0.0f };
}
else {
surfaceScale = new float[] { 1.0f, 1.0f };
}
System.err.println("[set PixelScale pre]: had " + currentSurfaceScale[0] + "x" + currentSurfaceScale[1] + " -> req " + surfaceScale[0] + "x" + surfaceScale[1]);
this.glWindow.setSurfaceScale(surfaceScale);
final float[] requestedSurfaceScale = this.glWindow.getRequestedSurfaceScale(new float[2]);
final float[] currentSurfaceScale2 = this.glWindow.getCurrentSurfaceScale(new float[2]);
System.err.println("[set PixelScale post]: " + currentSurfaceScale[0] + "x" + currentSurfaceScale[1] + " (had) -> " + surfaceScale[0] + "x" + surfaceScale[1] + " (req) -> " + requestedSurfaceScale[0] + "x" + requestedSurfaceScale[1] + " (val) -> " + currentSurfaceScale2[0] + "x" + currentSurfaceScale2[1] + " (has)");
this.setTitle();
break;
}
}
}
@Override
public void keyReleased(final KeyEvent keyEvent) {
}
public void setConfinedFixedCenter(final boolean confinedFixedCenter) {
this.confinedFixedCenter = confinedFixedCenter;
}
@Override
public void mouseMoved(final MouseEvent mouseEvent) {
if (mouseEvent.isConfined()) {
this.mouseCenterWarp(mouseEvent);
}
}
@Override
public void mouseDragged(final MouseEvent mouseEvent) {
if (mouseEvent.isConfined()) {
this.mouseCenterWarp(mouseEvent);
}
}
@Override
public void mouseClicked(final MouseEvent mouseEvent) {
if (mouseEvent.getClickCount() == 2 && mouseEvent.getPointerCount() == 3) {
this.glWindow.setFullscreen(!this.glWindow.isFullscreen());
System.err.println("setFullscreen: " + this.glWindow.isFullscreen());
}
}
private void mouseCenterWarp(final MouseEvent mouseEvent) {
if (mouseEvent.isConfined() && this.confinedFixedCenter) {
this.glWindow.warpPointer(this.glWindow.getSurfaceWidth() / 2, this.glWindow.getSurfaceHeight() / 2);
}
}
@Override
public void mouseEntered(final MouseEvent mouseEvent) {
}
@Override
public void mouseExited(final MouseEvent mouseEvent) {
}
@Override
public void mousePressed(final MouseEvent mouseEvent) {
}
@Override
public void mouseReleased(final MouseEvent mouseEvent) {
}
@Override
public void mouseWheelMoved(final MouseEvent mouseEvent) {
}
protected void quitAdapterOff() {
this.quitAdapterEnabled2 = false;
}
protected void quitAdapterOn() {
this.clearQuitAdapter();
this.quitAdapterEnabled2 = true;
}
public void quitAdapterEnable(final boolean quitAdapterEnabled) {
this.quitAdapterEnabled = quitAdapterEnabled;
}
public void clearQuitAdapter() {
this.quitAdapterShouldQuit = false;
}
public boolean shouldQuit() {
return this.quitAdapterShouldQuit;
}
public void doQuit() {
this.quitAdapterShouldQuit = true;
}
@Override
public void windowDestroyNotify(final WindowEvent windowEvent) {
if (this.quitAdapterEnabled && this.quitAdapterEnabled2) {
System.err.println("QUIT Window " + Thread.currentThread());
this.quitAdapterShouldQuit = true;
}
}
public void setTitle() {
setTitle(this.glWindow);
}
public static void setTitle(final GLWindow glWindow) {
final CapabilitiesImmutable chosenCapabilities = glWindow.getChosenCapabilities();
final CapabilitiesImmutable requestedCapabilities = glWindow.getRequestedCapabilities();
final String s = ((null != chosenCapabilities) ? chosenCapabilities : requestedCapabilities).isBackgroundOpaque() ? "opaque" : "transl";
final float[] pixelsPerMM;
final float[] array = pixelsPerMM = glWindow.getPixelsPerMM(new float[2]);
final int n = 0;
pixelsPerMM[n] *= 25.4f;
final float[] array2 = array;
final int n2 = 1;
array2[n2] *= 25.4f;
final float[] minimumSurfaceScale = glWindow.getMinimumSurfaceScale(new float[2]);
final float[] maximumSurfaceScale = glWindow.getMaximumSurfaceScale(new float[2]);
final float[] requestedSurfaceScale = glWindow.getRequestedSurfaceScale(new float[2]);
final float[] currentSurfaceScale = glWindow.getCurrentSurfaceScale(new float[2]);
glWindow.setTitle("GLWindow[" + s + "], win: " + glWindow.getBounds() + ", pix: " + glWindow.getSurfaceWidth() + "x" + glWindow.getSurfaceHeight() + ", sDPI " + array[0] + " x " + array[1] + ", scale[min " + minimumSurfaceScale[0] + "x" + minimumSurfaceScale[1] + ", max " + maximumSurfaceScale[0] + "x" + maximumSurfaceScale[1] + ", req " + requestedSurfaceScale[0] + "x" + requestedSurfaceScale[1] + " -> has " + currentSurfaceScale[0] + "x" + currentSurfaceScale[1] + "]");
}
public static Display.PointerIcon[] createPointerIcons(final Display display) {
final ArrayList<Display.PointerIcon> list = new ArrayList<Display.PointerIcon>();
display.createNative();
final IOUtil.ClassResources classResources = new IOUtil.ClassResources(new String[] { "newt/data/cross-grey-alpha-16x16.png" }, display.getClass().getClassLoader(), null);
try {
final Display.PointerIcon pointerIcon = display.createPointerIcon(classResources, 8, 8);
list.add(pointerIcon);
System.err.printf("Create PointerIcon #%02d: %s%n", list.size(), pointerIcon.toString());
}
catch (Exception ex) {
System.err.println(ex.getMessage());
}
final IOUtil.ClassResources classResources2 = new IOUtil.ClassResources(new String[] { "newt/data/pointer-grey-alpha-16x24.png" }, display.getClass().getClassLoader(), null);
try {
final Display.PointerIcon pointerIcon2 = display.createPointerIcon(classResources2, 0, 0);
list.add(pointerIcon2);
System.err.printf("Create PointerIcon #%02d: %s%n", list.size(), pointerIcon2.toString());
}
catch (Exception ex2) {
System.err.println(ex2.getMessage());
}
final IOUtil.ClassResources classResources3 = new IOUtil.ClassResources(new String[] { "arrow-red-alpha-64x64.png" }, display.getClass().getClassLoader(), null);
try {
final Display.PointerIcon pointerIcon3 = display.createPointerIcon(classResources3, 0, 0);
list.add(pointerIcon3);
System.err.printf("Create PointerIcon #%02d: %s%n", list.size(), pointerIcon3.toString());
}
catch (Exception ex3) {
System.err.println(ex3.getMessage());
}
final IOUtil.ClassResources classResources4 = new IOUtil.ClassResources(new String[] { "arrow-blue-alpha-64x64.png" }, display.getClass().getClassLoader(), null);
try {
final Display.PointerIcon pointerIcon4 = display.createPointerIcon(classResources4, 0, 0);
list.add(pointerIcon4);
System.err.printf("Create PointerIcon #%02d: %s%n", list.size(), pointerIcon4.toString());
}
catch (Exception ex4) {
System.err.println(ex4.getMessage());
}
if (PNGIcon.isAvailable()) {
final IOUtil.ClassResources classResources5 = new IOUtil.ClassResources(new String[] { "jogamp-pointer-64x64.png" }, display.getClass().getClassLoader(), null);
try {
final URLConnection resolve = classResources5.resolve(0);
if (null != resolve) {
final PNGPixelRect read = PNGPixelRect.read(resolve.getInputStream(), null, false, 0, false);
System.err.printf("Create PointerIcon #%02d: %s%n", list.size() + 1, read.toString());
final Display.PointerIcon pointerIcon5 = display.createPointerIcon(read, 32, 0);
list.add(pointerIcon5);
System.err.printf("Create PointerIcon #%02d: %s%n", list.size(), pointerIcon5.toString());
}
}
catch (Exception ex5) {
System.err.println(ex5.getMessage());
}
}
return list.toArray(new Display.PointerIcon[list.size()]);
}
}
| true |
940d63d0156e9833ac919a02bcd0a7bb905b6d2b
|
Java
|
mihrsak/test
|
/Vjezbe/Vjezbanje/vjezbe/vjezbanje/ControlStatements/StringSwitch.java
|
UTF-8
| 599 | 3.421875 | 3 |
[] |
no_license
|
/**
*
*/
package vjezbe.vjezbanje.ControlStatements;
/**
* @author emahr
*
*/
public class StringSwitch {
/**
*
*/
public StringSwitch() {
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// String in switch
String str = "two";
switch(str) {
case "one":
System.out.println("one");
case "two":
System.out.println("two");
break;
case "three":
System.out.println("three");
break;
default:
System.out.println("no match");
break;
}
}
}
| true |
0c952c6147b2a5036073d554eccb6566c3e06878
|
Java
|
nassimbg/Problems
|
/src/test/java/ShortestUnsortedContinuousSubarrayTest.java
|
UTF-8
| 1,243 | 2.984375 | 3 |
[] |
no_license
|
import static org.junit.Assert.*;
import org.junit.Test;
public class ShortestUnsortedContinuousSubarrayTest {
@Test
public void findUnsortedSubarray() {
int length = ShortestUnsortedContinuousSubarray.findUnsortedSubarray(new int[] { 2, 6, 4, 8, 10, 9, 15 });
assertEquals(5, length);
}
@Test
public void findUnsortedSubarray2() {
int length = ShortestUnsortedContinuousSubarray.findUnsortedSubarray(new int[] {1,3,2,2,2 });
assertEquals(4, length);
}
@Test
public void findUnsortedSubarray3() {
int length = ShortestUnsortedContinuousSubarray.findUnsortedSubarray(new int[] {1,1});
assertEquals(0, length);
}
@Test
public void findUnsortedSubarray4() {
int length = ShortestUnsortedContinuousSubarray.findUnsortedSubarray(new int[] {1,2,4,5,3});
assertEquals(3, length);
}
@Test
public void findUnsortedSubarray5() {
int length = ShortestUnsortedContinuousSubarray.findUnsortedSubarray(new int[] {1,2,3,4});
assertEquals(0, length);
}
@Test
public void findUnsortedSubarray6() {
int length = ShortestUnsortedContinuousSubarray.findUnsortedSubarray(new int[] {1,3,5,4,2});
assertEquals(4, length);
}
}
| true |
84684745cb98f604c98525caf1718e3377e7e352
|
Java
|
ZengChen94/Object-Oriented-Programming
|
/HW08/src/model/ChatRoomModel.java
|
UTF-8
| 3,955 | 2.546875 | 3 |
[] |
no_license
|
package model;
import java.io.File;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import common.DataPacketChatRoom;
import common.IChatRoom;
import common.IReceiver;
import common.IUser;
import model.user.ProxyUser;
/**
* The chat room model in the chat room mini MVC.
*
*/
public class ChatRoomModel {
/**
* Chat room model to chat room view adapter.
*/
private IChatRoomModel2ChatRoomViewAdapter _viewAdapter;
/**
* Chat room model to main model adapter.
*/
private IChatRoomModel2ModelAdapter _mainModelAdapter;
/**
* The chat room object for this chat room model.
*/
private IChatRoom chatRoom;
/**
* The receiver for this chat room, receives data packets.
*/
private IReceiver receiver;
/**
* The receiverStub for this chat room, receives data packets.
*/
private IReceiver receiverStub;
/**
* Constructor.
* @param receiver is receiver for this chat room, receives data packets.
* @param receiverStub is receiverStub for this chat room, receives data packets.
* @param chatRoom is the chat room object for this chat room model.
* @param _mainModelAdapter is the chat room model to main model adapter.
* @param _viewAdapter is the chat room model to chat room view adapter.
*/
public ChatRoomModel(IReceiver receiver, IReceiver receiverStub, IChatRoom chatRoom, IChatRoomModel2ChatRoomViewAdapter _viewAdapter, IChatRoomModel2ModelAdapter _mainModelAdapter) {
this.receiver = receiver;
this.receiverStub = receiverStub;
this.chatRoom = chatRoom;
this._viewAdapter = _viewAdapter;
this._mainModelAdapter = _mainModelAdapter;
}
/**
* User exit this chat room.
*/
public void exitChatRoom() {
_viewAdapter.appendMessage("this chat room is quiting...");
_mainModelAdapter.exitChatRoom(chatRoom);
chatRoom.removeIReceiverStub(receiverStub);
}
/**
* Send text to the chat room in this chat room model.
* @param text is sent to the chat room in this chat room model.
*/
public void sendText(String text) {
chatRoom.sendPacket(new DataPacketChatRoom<String>(String.class, text, receiverStub));
}
/**
* Send file to the chat room in this chat room model.
* @param file is sent to the chat room in this chat room model.
*/
public void sendFile(File file) {
chatRoom.sendPacket(new DataPacketChatRoom<File>(File.class, file, receiverStub));
}
/**
* Send emoji to the chat room in this chat room model.
* @param emoji is sent to the chat room in this chat room model.
*/
public void sendEmoji(ImageIcon emoji) {
chatRoom.sendPacket(new DataPacketChatRoom<ImageIcon>(ImageIcon.class, emoji, receiverStub));
}
/**
* start the chat room model
*/
public void start() {
listUsers();
}
/**
* Refresh the user list to list users.
*/
public void listUsers() {
List<IUser> users = new ArrayList<>();
for (IReceiver rcvr : chatRoom.getIReceiverStubs()) {
try {
if (this.receiverStub.equals(rcvr)) {
users.add(this.receiver.getUserStub());
} else {
users.add(new ProxyUser(rcvr.getUserStub()));
}
} catch (RemoteException e) {
System.out.println("failed to get user stubs from receiver: " + rcvr);
e.printStackTrace();
}
}
_viewAdapter.listUsers(users);
}
/**
* Remove a receiverStub from this chat room.
* @param receiverStub is the receiverStub to remove from this chat room.
*/
public void removeReceiver(IReceiver receiverStub) {
chatRoom.removeIReceiverStubLocally(receiverStub);
listUsers();
}
/**
* Add a receiverStub to this chat room.
* @param receiverStub is the receiverStub to add to this chat room.
*/
public void addReceiver(IReceiver receiverStub) {
chatRoom.addIReceiverStubLocally(receiverStub);
listUsers();
}
/**
* Get chat room object from chat room model.
* @return chat room object in chat room model.
*/
public IChatRoom getChatRoom() {
return chatRoom;
}
}
| true |
ef24be08eeb2a480e8bb6202879819af94e37519
|
Java
|
royken/BracongoSC
|
/app/src/main/java/com/royken/bracongo/bracongosc/entities/Client.java
|
UTF-8
| 7,427 | 1.921875 | 2 |
[] |
no_license
|
package com.royken.bracongo.bracongosc.entities;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import java.io.Serializable;
import java.util.Date;
/**
* Created by vr.kenfack on 30/08/2017.
*/
@Entity(tableName = "clients")
public class Client implements Serializable {
@NonNull
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
@Expose(serialize = false, deserialize = false)
private int id;
@Expose(serialize = true, deserialize = true)
@SerializedName("raisonSociale")
@ColumnInfo(name = "nom")
private String nom;
@Expose(serialize = true, deserialize = true)
@SerializedName("nomProprietaire")
@ColumnInfo(name = "nomProprietaire")
private String nomProprietaire;
@Expose(serialize = true, deserialize = true)
@SerializedName("numero")
@ColumnInfo(name = "numero")
private String numero;
@Expose(serialize = true, deserialize = true)
@SerializedName("adresse")
@ColumnInfo(name = "adresse")
private String adresse;
@Expose(serialize = true, deserialize = true)
@SerializedName("quartier")
@ColumnInfo(name = "quartier")
private String quartier;
@Expose(serialize = true, deserialize = true)
@SerializedName("commune")
@ColumnInfo(name = "commune")
private String commune;
@Expose(serialize = true, deserialize = true)
@SerializedName("ville")
@ColumnInfo(name = "ville")
private String ville;
@Expose(serialize = true, deserialize = true)
@SerializedName("telephone")
@ColumnInfo(name = "telephone")
private String telephone;
@Expose(serialize = true, deserialize = true)
@SerializedName("type")
@ColumnInfo(name = "type")
private String type;
@Expose(serialize = true, deserialize = true)
@SerializedName("categorie")
@ColumnInfo(name = "categorie")
private String categorie;
@Expose(serialize = true, deserialize = true)
@SerializedName("regime")
@ColumnInfo(name = "regime")
private String regime;
@Expose(serialize = true, deserialize = true)
@SerializedName("latitude")
@ColumnInfo(name = "latitude")
private String latitude;
@Expose(serialize = true, deserialize = true)
@SerializedName("longitude")
@ColumnInfo(name = "longitude")
private String longitude;
@Expose(serialize = true, deserialize = true)
@SerializedName("dernierAchat")
@ColumnInfo(name = "dernierAchat")
private Date dernierAchat;
@Expose(serialize = true, deserialize = true)
@SerializedName("dateCreation")
@ColumnInfo(name = "dateCreation")
private Date dateCreation;
@Expose(serialize = true, deserialize = true)
@SerializedName("numeroContrat")
@ColumnInfo(name = "numeroContrat")
private String numeroContrat;
@Expose(serialize = true, deserialize = true)
@SerializedName("emballage")
@ColumnInfo(name = "emballage")
private Integer emballage;
@Expose(serialize = true, deserialize = true)
@SerializedName("consignationEmballages")
@ColumnInfo(name = "consignationEmballages")
private Integer consignationEmballages;
public Client() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getNomProprietaire() {
return nomProprietaire;
}
public void setNomProprietaire(String nomProprietaire) {
this.nomProprietaire = nomProprietaire;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public String getQuartier() {
return quartier;
}
public void setQuartier(String quartier) {
this.quartier = quartier;
}
public String getCommune() {
return commune;
}
public void setCommune(String commune) {
this.commune = commune;
}
public String getVille() {
return ville;
}
public void setVille(String ville) {
this.ville = ville;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCategorie() {
return categorie;
}
public void setCategorie(String categorie) {
this.categorie = categorie;
}
public String getRegime() {
return regime;
}
public void setRegime(String regime) {
this.regime = regime;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public Date getDernierAchat() {
return dernierAchat;
}
public void setDernierAchat(Date dernierAchat) {
this.dernierAchat = dernierAchat;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public String getNumeroContrat() {
return numeroContrat;
}
public void setNumeroContrat(String numeroContrat) {
this.numeroContrat = numeroContrat;
}
public Integer getEmballage() {
return emballage;
}
public void setEmballage(Integer emballage) {
this.emballage = emballage;
}
public Integer getConsignationEmballages() {
return consignationEmballages;
}
public void setConsignationEmballages(Integer consignationEmballages) {
this.consignationEmballages = consignationEmballages;
}
@Override
public String toString() {
return "Client{" +
"id=" + id +
", nom='" + nom + '\'' +
", nomProprietaire='" + nomProprietaire + '\'' +
", numero='" + numero + '\'' +
", adresse='" + adresse + '\'' +
", quartier='" + quartier + '\'' +
", commune='" + commune + '\'' +
", ville='" + ville + '\'' +
", telephone='" + telephone + '\'' +
", type='" + type + '\'' +
", categorie='" + categorie + '\'' +
", regime='" + regime + '\'' +
", latitude='" + latitude + '\'' +
", longitude='" + longitude + '\'' +
", dernierAchat=" + dernierAchat +
", dateCreation=" + dateCreation +
", numeroContrat='" + numeroContrat + '\'' +
", emballage=" + emballage +
'}';
}
}
| true |
6d2ab5f45db68a30a04a300ea99369017485dcad
|
Java
|
ColinLoveLucky/JavaProjectDemo
|
/xianggangLite-bk/src/main/java/com/qf/cobra/util/ZipUtils.java
|
UTF-8
| 788 | 2.65625 | 3 |
[] |
no_license
|
/**
*
*/
package com.qf.cobra.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
/**
* @author LongjunLu
*
*/
public class ZipUtils {
/**
* GZip解压
* @param input
* @return
* @throws IOException
*/
public static byte[] uncompress(byte[] input) throws IOException{
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(input);
GZIPInputStream gunzip = new GZIPInputStream(in);
try {
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
} finally {
gunzip.close();
}
in.close();
out.close();
return out.toByteArray();
}
}
| true |
7e41a5c422ccd17b4157ad034ab1b2f85b1f35a1
|
Java
|
victor19pa/Airports-v2
|
/Airport/src/main/java/Entities/EAirplane.java
|
UTF-8
| 590 | 1.921875 | 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 Entities;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter @Setter @ToString @NoArgsConstructor @AllArgsConstructor
public class EAirplane {
private int idAirplane;
private String model;
private int passengerCapacity;
private double tankCapacity;
private boolean available;
}
| true |
6fa94a439e2536c8eb7e7528d0d78b99d07a566e
|
Java
|
luizalmeida16/hibernate
|
/src/main/java/com/luizalmeida/bankProject/controller/AccountController.java
|
UTF-8
| 1,308 | 2.453125 | 2 |
[] |
no_license
|
package com.luizalmeida.bankProject.controller;
import java.net.URI;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.server.Uri;
import com.google.gson.Gson;
import com.luizalmeida.bankProject.dao.AccountDAO;
import com.luizalmeida.bankProject.model.Account;
@Path("accounts")
public class AccountController {
@Path("{id}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public String get(@PathParam("id") long id){
Account account = new AccountDAO().get(id);
return account.toJson();
}
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response create(String content) {
Account data = new Gson().fromJson(content, Account.class);
AccountDAO accountDAO = new AccountDAO();
data = accountDAO.create(data.getNumber(), data.getBalance());
System.out.println("Access the create");
URI uri = URI.create("/accounts/" + data.getId());
return Response.created(uri).build();
}
@GET
@Path("/delete")
@Produces(MediaType.APPLICATION_JSON)
public String delete(@QueryParam("id") long id){
String status = new AccountDAO().delete(id);
return status;
}
}
| true |
b6c3e01b4224439594b4e68f5b8e1f54d13588e0
|
Java
|
cckmit/RMIServer
|
/src/main/java/com/hgsoft/httpInterface/service/FindInvoiceDetailService.java
|
UTF-8
| 645 | 1.90625 | 2 |
[] |
no_license
|
package com.hgsoft.httpInterface.service;
import com.hgsoft.invoice.dao.InvoiceDetailDao;
import com.hgsoft.httpInterface.serviceInterface.IFindInvoiceDetailService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* Created by apple on 2016/11/30.
*/
@Service
public class FindInvoiceDetailService implements IFindInvoiceDetailService {
@Resource
private InvoiceDetailDao invoiceDetailDao;
@Override
public List<Map<String, Object>> findInvoiceTitleList(String cardno) {
return invoiceDetailDao.findInvoiceTitleList(cardno);
}
}
| true |
f9c8f3f21ae58ee17963a1b527754ce0a8f67b4f
|
Java
|
javierdotnet/mateu-erp
|
/dispo-logic/src/test/java/io/mateu/common/HotelAvailabilityTest.java
|
UTF-8
| 1,087 | 2.484375 | 2 |
[
"Beerware",
"CC-BY-3.0"
] |
permissive
|
package io.mateu.common;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class HotelAvailabilityTest
extends TestCase
{
@Override
protected void setUp() throws Exception {
super.setUp();
System.out.println("setup");
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
System.out.println("teardown");
}
/**
* Create the test case
*
* @param testName name of the test case
*/
public HotelAvailabilityTest(String testName )
{
super( testName );
System.out.println("hola");
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
System.out.println("xxx");
return new TestSuite( HotelAvailabilityTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
public void testParo() {
assertEquals(0, 0);
}
}
| true |
e4e98b198192264415b287c98f28cbfb146a37ff
|
Java
|
ttongniu/xxzx
|
/src/main/java/com/boco/xxzx/model/Dictionary.java
|
UTF-8
| 2,602 | 2.28125 | 2 |
[] |
no_license
|
package com.boco.xxzx.model;
import java.io.Serializable;
import java.util.Date;
import org.apache.ibatis.type.Alias;
/**
*
* @ClassName: Dictionary
* @Description:(字典实体类)
* @author: niutongtong
* @date: 2017年11月10日 下午4:13:03
*
*/
@Alias("Dictionary")
public class Dictionary implements Serializable{
private static final long serialVersionUID = 1L;
private Integer id;
/**
* 数据类型代码
*/
private String code;
/**
* 数据键
*/
private String key;
/**
* 数据值
*/
private String value;
/**
* 描述
*/
private String description ;
private User lastModifyUser;
private Date createTime;
private Date updateTime;
public Dictionary(Integer id, String code, String key, String value, String description, User lastModifyUser,
Date createTime, Date updateTime) {
super();
this.id = id;
this.code = code;
this.key = key;
this.value = value;
this.description = description;
this.lastModifyUser = lastModifyUser;
this.createTime = createTime;
this.updateTime = updateTime;
}
public Dictionary() {
super();
}
@Override
public String toString() {
return "Dictionary [id=" + id + ", code=" + code + ", key=" + key + ", value=" + value + ", description="
+ description + ", lastModifyUser=" + lastModifyUser + ", createTime=" + createTime + ", updateTime="
+ updateTime + "]";
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public User getLastModifyUser() {
return lastModifyUser;
}
public void setLastModifyUser(User lastModifyUser) {
this.lastModifyUser = lastModifyUser;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
| true |