blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
44e7e81197b705a3f445442a1cf010721b2ace92 | 11,630,771,504,159 | 1103ee517fdd485cb2027c6eaece3e893442ada3 | /CampingPrj/src/package1/CampFullStatus.java | 587851906dc0284a4eabc850fe9958997681edc1 | [] | no_license | hoodp/java-CampingProject | https://github.com/hoodp/java-CampingProject | 5a80e6dc17fe09e82f907d9d3dcc29860b3033fa | b12034d3857226bd2c8cfbbb77f3c61ff6ef0b5c | refs/heads/master | 2021-01-22T03:50:26.258000 | 2014-04-30T21:36:57 | 2014-04-30T21:36:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package package1;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
/**********************************************************************
* The following class inherits the SiteModel class and displays the
* camp status information. Two of the fields are different than the
* original site.
*
* @author Paul Hood
* @version 10/2013
*
*********************************************************************/
public class CampFullStatus extends SiteModel implements
ActionListener {
/** Table that displays the information */
private JTable table;
/** Scroll pane needed by the JTable */
private JScrollPane scrollPane;
/** Submits the form */
private JButton btnOK;
/** JDialog that is displayed */
private JDialog dialog;
/** Stores the current sites */
private ArrayList<Site> sites;
/** Stores the new column names */
private String[] columnNames = { "Name Reserving", "Checked In",
"Site #", "Estimated Days", "Days Remaining" };
/******************************************************************
* Constructor that Creates a JDialog and displayed the camp status
* information.
* @param parent JFrame that the dialog is displayed in
* @param sites ArrayList of the taken sites.
*****************************************************************/
public CampFullStatus(JFrame parent, ArrayList<Site> sites) {
super();
sites = new ArrayList<Site>(sites);
dialog = new JDialog(parent);
dialog.setTitle("Campground Status");
table = new JTable(this);
scrollPane = new JScrollPane(table);
dialog.add(scrollPane);
JPanel bottom = new JPanel();
dialog.getContentPane().add(bottom, BorderLayout.SOUTH);
btnOK = new JButton("OK");
btnOK.addActionListener(this);
btnOK.setHorizontalAlignment(SwingConstants.RIGHT);
bottom.add(btnOK);
// add the sites to display
addSites(sites);
dialog.setSize(750,300);
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
/******************************************************************
* This method adds the sites to the display.
* @param sites Site information
*****************************************************************/
public void addSites(ArrayList<Site> sites) {
for (int i = 0; i < sites.size(); i++) {
addSite(sites.get(i));
}
}
/******************************************************************
* This method returns the string of the column name.
* @param col int of the column
* @return String of the column name
*****************************************************************/
@Override
public String getColumnName(int col) {
return columnNames[col];
}
/******************************************************************
* This method returns the length of the columnNames array.
* @return int of the Length of the columnNames array
*****************************************************************/
@Override
public int getColumnCount() {
return columnNames.length;
}
/******************************************************************
* Method returns the size of the listSites array.
* @return int of the size of the listSites array
*****************************************************************/
@Override
public int getRowCount() {
return getListSites().size();
}
/******************************************************************
* Method updates the gui. This overrides the method from the
* SiteModel class.
* @param row of the table to update
* @param col of the row in the table
* @return The value to update to the table.
*****************************************************************/
@Override
public Object getValueAt(int row, int col) {
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Site unit = getSite(row);
switch (col) {
case 0:
return unit.getNameReserving();
case 1:
return format.format(unit.getCheckIn());
case 2:
return unit.getSiteNumber();
case 3:
return unit.getDaysStaying();
case 4:
return unit.dayCount();
default:
return null;
}
}
/******************************************************************
* This method is responsible for closing the dialog if the ok
* button is clicked.
*****************************************************************/
public void actionPerformed(ActionEvent e) {
JComponent event = (JComponent) e.getSource();
if (event == btnOK) {
// close the form
dialog.dispose();
}
}
}
| UTF-8 | Java | 4,817 | java | CampFullStatus.java | Java | [
{
"context": "fferent than the \n * original site.\n * \n * @author Paul Hood\n * @version 10/2013\n *\n *************************",
"end": 676,
"score": 0.9998131394386292,
"start": 667,
"tag": "NAME",
"value": "Paul Hood"
}
] | null | [] | package package1;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
/**********************************************************************
* The following class inherits the SiteModel class and displays the
* camp status information. Two of the fields are different than the
* original site.
*
* @author <NAME>
* @version 10/2013
*
*********************************************************************/
public class CampFullStatus extends SiteModel implements
ActionListener {
/** Table that displays the information */
private JTable table;
/** Scroll pane needed by the JTable */
private JScrollPane scrollPane;
/** Submits the form */
private JButton btnOK;
/** JDialog that is displayed */
private JDialog dialog;
/** Stores the current sites */
private ArrayList<Site> sites;
/** Stores the new column names */
private String[] columnNames = { "Name Reserving", "Checked In",
"Site #", "Estimated Days", "Days Remaining" };
/******************************************************************
* Constructor that Creates a JDialog and displayed the camp status
* information.
* @param parent JFrame that the dialog is displayed in
* @param sites ArrayList of the taken sites.
*****************************************************************/
public CampFullStatus(JFrame parent, ArrayList<Site> sites) {
super();
sites = new ArrayList<Site>(sites);
dialog = new JDialog(parent);
dialog.setTitle("Campground Status");
table = new JTable(this);
scrollPane = new JScrollPane(table);
dialog.add(scrollPane);
JPanel bottom = new JPanel();
dialog.getContentPane().add(bottom, BorderLayout.SOUTH);
btnOK = new JButton("OK");
btnOK.addActionListener(this);
btnOK.setHorizontalAlignment(SwingConstants.RIGHT);
bottom.add(btnOK);
// add the sites to display
addSites(sites);
dialog.setSize(750,300);
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
/******************************************************************
* This method adds the sites to the display.
* @param sites Site information
*****************************************************************/
public void addSites(ArrayList<Site> sites) {
for (int i = 0; i < sites.size(); i++) {
addSite(sites.get(i));
}
}
/******************************************************************
* This method returns the string of the column name.
* @param col int of the column
* @return String of the column name
*****************************************************************/
@Override
public String getColumnName(int col) {
return columnNames[col];
}
/******************************************************************
* This method returns the length of the columnNames array.
* @return int of the Length of the columnNames array
*****************************************************************/
@Override
public int getColumnCount() {
return columnNames.length;
}
/******************************************************************
* Method returns the size of the listSites array.
* @return int of the size of the listSites array
*****************************************************************/
@Override
public int getRowCount() {
return getListSites().size();
}
/******************************************************************
* Method updates the gui. This overrides the method from the
* SiteModel class.
* @param row of the table to update
* @param col of the row in the table
* @return The value to update to the table.
*****************************************************************/
@Override
public Object getValueAt(int row, int col) {
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Site unit = getSite(row);
switch (col) {
case 0:
return unit.getNameReserving();
case 1:
return format.format(unit.getCheckIn());
case 2:
return unit.getSiteNumber();
case 3:
return unit.getDaysStaying();
case 4:
return unit.dayCount();
default:
return null;
}
}
/******************************************************************
* This method is responsible for closing the dialog if the ok
* button is clicked.
*****************************************************************/
public void actionPerformed(ActionEvent e) {
JComponent event = (JComponent) e.getSource();
if (event == btnOK) {
// close the form
dialog.dispose();
}
}
}
| 4,814 | 0.550343 | 0.546398 | 154 | 30.279221 | 22.0485 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.584416 | false | false | 8 |
88ab7d79d565f88041b4c31087792ddc1ba733d8 | 35,150,012,378,512 | 05280e38a400d285da0b07a0c0e3861f2a0b9eb9 | /Revision [week 1-2]/Objects/Student.java | d258a20079f3891cca72cd9196cee1da67943d4c | [] | no_license | dickwyn/CSCP_2014 | https://github.com/dickwyn/CSCP_2014 | 18210785d3a70f51ee00a38c88fc2f44134494ba | 478e2a72f98464a4a3d27decf73d73201374db4e | refs/heads/master | 2016-08-11T11:16:45.443000 | 2016-02-26T04:45:25 | 2016-02-26T04:45:25 | 52,579,070 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package student;
public class Student {
private String name;
private int dob;
private char gender;
private String status;
static int numberOfStudents;
Student(String iname, int idob, char igender, String istatus) {
name = iname;
dob = idob;
gender = igender;
status = istatus;
}
public void PrintInfo() {
System.out.println(name);
System.out.println(dob);
System.out.println(gender);
System.out.println(status);
}
public String getStatus() {
return status;
}
public void setStatus (String iStatus) {
status = iStatus;
}
public void PrintStudentInfo() {
System.out.println(numberOfStudents);
}
}
| UTF-8 | Java | 648 | java | Student.java | Java | [] | null | [] | package student;
public class Student {
private String name;
private int dob;
private char gender;
private String status;
static int numberOfStudents;
Student(String iname, int idob, char igender, String istatus) {
name = iname;
dob = idob;
gender = igender;
status = istatus;
}
public void PrintInfo() {
System.out.println(name);
System.out.println(dob);
System.out.println(gender);
System.out.println(status);
}
public String getStatus() {
return status;
}
public void setStatus (String iStatus) {
status = iStatus;
}
public void PrintStudentInfo() {
System.out.println(numberOfStudents);
}
}
| 648 | 0.697531 | 0.697531 | 37 | 16.513514 | 14.64835 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.72973 | false | false | 8 |
472b496ac66f63567ec2b44164f2ca9767a0f3e4 | 36,137,854,845,425 | d1b295e763c054e62a5f14377bb814ab924f989a | /trunk/carter/test/dao/com/sageconsulting/util/BracketUtilityTest.java | e6559b77ea8b51672a49f406b8c2c622ef5eb4ed | [
"Apache-2.0"
] | permissive | piyush21upadhyay/TennisLeague | https://github.com/piyush21upadhyay/TennisLeague | 7a99ab92d13f3dd788df5c196bb9fbad5c3678e2 | 5f19ef2a8a993e61ad7bf73377c331e09a393e9f | refs/heads/master | 2022-05-23T23:36:39.702000 | 2021-04-24T13:24:46 | 2021-04-24T13:24:46 | 139,750,225 | 0 | 0 | null | false | 2021-09-24T04:48:04 | 2018-07-04T17:28:46 | 2021-04-24T13:25:10 | 2021-09-24T04:36:42 | 159,725 | 0 | 0 | 1 | Java | false | false | /*
* BracketUtilityTest.java
*
* Copyright © 2008-2009 City Golf League, LLC. All Rights Reserved
* http://www.citygolfleague.com
*
* @author Steve Paquin - Sage Software Consulting, Inc.
*/
package com.sageconsulting.util;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import junit.framework.TestCase;
import com.sageconsulting.model.BracketEntry;
import com.sageconsulting.model.City;
import com.sageconsulting.model.Course;
import com.sageconsulting.model.Match;
import com.sageconsulting.model.MatchScore;
import com.sageconsulting.model.Season;
import com.sageconsulting.model.User;
/**
* This class has unit tests for the {@link BracketUtility} class.
*/
public class BracketUtilityTest extends TestCase
{
//private Map<User, SeasonResult> results = new HashMap<User, SeasonResult>(20);
public void test()
{
int postSeasonCount = 64;
Course course = createCourse();
Season season = createSeason(course, postSeasonCount);
Calendar start = new GregorianCalendar();
List<BracketEntry> bracket = BracketUtility.generateBracket(season, start, 4);
System.out.println(BracketUtility.toString(bracket));
simulateSeason(season, course);
//updateResults(season);
//season.get
//SeasonResult[] resultArray = this.results.values().toArray(new SeasonResult[this.results.size()]);
SeasonResult[] results = createResults(postSeasonCount);
BracketUtility.fillBracket(bracket, results);
System.out.println(BracketUtility.toString(bracket));
// TODO: the bracket should be set up so the users are seeded in the order
// of thier userid. We should check to see if it is set up so that
// the users meet in the correct round.
}
private Season createSeason(Course course, int postSeasonCount)
{
Season season = new Season();
season.setCity(getCity());
season.setMatches(createMatches(postSeasonCount, course));
season.setName("Test Season"); //$NON-NLS-1$
season.setPostSeasonQualifyingCount(Integer.valueOf(postSeasonCount));
return season;
}
private SortedSet<Match> createMatches(int count, Course course)
{
TreeSet<Match> matches = new TreeSet<Match>(new Comparator<Match>()
{
public int compare(Match match1, Match match2)
{
int sort = match1.getPlayBy().compareTo(match2.getPlayBy());
if (sort == 0)
{
sort = match1.getGolfer1().getUsername().compareTo(match2.getGolfer1().getUsername());
}
return sort;
}
});
for (int i=0; i<count; i++)
{
Match match = new Match();
match.setGolfer1(createUser("Match"+i, "Golfer1")); //$NON-NLS-1$ //$NON-NLS-2$
match.setGolfer2(createUser("Match"+i, "Golfer2")); //$NON-NLS-1$ //$NON-NLS-2$
//match.setCourse(course);
match.setPlayBy(new Date());
matches.add(match);
}
return matches;
}
private User createUser(String first, String last)
{
User user = new User();
user.setFirstName(first);
user.setLastName(last);
user.setUsername(first+last);
//user.setHandicap(Double.valueOf(Math.random()*20));
return user;
}
@SuppressWarnings("boxing")
private Course createCourse()
{
City portland = new City();
portland.setName("Portland"); //$NON-NLS-1$
List<City> cities = new ArrayList<City>();
cities.add(portland);
Course course = new Course();
course.setCities(cities);
course.setCities(cities);
course.setName("Eastmoreland"); //$NON-NLS-1$
course.setMensPars(new Byte[] { 4, 4, 4, 4, 3, 5, 4, 3, 5, 4, 5, 3, 5, 4, 4, 4, 3, 4 });
course.setMensHandicaps(new Byte[] { 13, 3, 11, 9, 17, 1, 5, 15, 7, 14, 8, 18, 2, 12, 10, 4, 16, 6 });
course.setMensRating(Float.valueOf(74.4f));
course.setMensSlope(Integer.valueOf(115));
course.setWomensPars(new Byte[] { 4, 4, 4, 4, 3, 5, 4, 3, 5, 4, 5, 3, 5, 4, 4, 4, 3, 4 });
course.setWomensHandicaps(new Byte[] { 13, 3, 11, 9, 17, 1, 5, 15, 7, 14, 8, 18, 2, 12, 10, 4, 16, 6 });
course.setWomensRating(Float.valueOf(74.4f));
course.setWomensSlope(Integer.valueOf(115));
return course;
}
private void simulateSeason(Season season, Course course)
{
Calendar calendar = new GregorianCalendar();
Iterator<Match> matches = season.getMatches().iterator();
while(matches.hasNext())
{
Match match = matches.next();
MatchScore score = new MatchScore();
// TODO: Akash
/*score.computeStrokes(course, match.getGolfer1(), match.getGolfer2());
score.setPlayer1Hole1Score(Byte.valueOf((byte)5));
score.setPlayer1Hole2Score(Byte.valueOf((byte)5));
score.setPlayer1Hole3Score(Byte.valueOf((byte)5));
score.setPlayer1Hole4Score(Byte.valueOf((byte)5));
score.setPlayer1Hole5Score(Byte.valueOf((byte)5));
score.setPlayer1Hole6Score(Byte.valueOf((byte)5));
score.setPlayer1Hole7Score(Byte.valueOf((byte)5));
score.setPlayer1Hole8Score(Byte.valueOf((byte)5));
score.setPlayer1Hole9Score(Byte.valueOf((byte)5));
score.setPlayer1Hole10Score(Byte.valueOf((byte)5));
score.setPlayer1Hole11Score(Byte.valueOf((byte)5));
score.setPlayer1Hole12Score(Byte.valueOf((byte)5));
score.setPlayer1Hole13Score(Byte.valueOf((byte)5));
score.setPlayer1Hole14Score(Byte.valueOf((byte)5));
score.setPlayer1Hole15Score(Byte.valueOf((byte)5));
score.setPlayer1Hole16Score(Byte.valueOf((byte)5));
score.setPlayer1Hole17Score(Byte.valueOf((byte)5));
score.setPlayer1Hole18Score(Byte.valueOf((byte)5));
score.setPlayer2Hole1Score(Byte.valueOf((byte)5));
score.setPlayer2Hole2Score(Byte.valueOf((byte)5));
score.setPlayer2Hole3Score(Byte.valueOf((byte)5));
score.setPlayer2Hole4Score(Byte.valueOf((byte)5));
score.setPlayer2Hole5Score(Byte.valueOf((byte)5));
score.setPlayer2Hole6Score(Byte.valueOf((byte)5));
score.setPlayer2Hole7Score(Byte.valueOf((byte)5));
score.setPlayer2Hole8Score(Byte.valueOf((byte)5));
score.setPlayer2Hole9Score(Byte.valueOf((byte)5));
score.setPlayer2Hole10Score(Byte.valueOf((byte)5));
score.setPlayer2Hole11Score(Byte.valueOf((byte)5));
score.setPlayer2Hole12Score(Byte.valueOf((byte)5));
score.setPlayer2Hole13Score(Byte.valueOf((byte)5));
score.setPlayer2Hole14Score(Byte.valueOf((byte)5));
score.setPlayer2Hole15Score(Byte.valueOf((byte)5));
score.setPlayer2Hole16Score(Byte.valueOf((byte)5));
score.setPlayer2Hole17Score(Byte.valueOf((byte)5));
score.setPlayer2Hole18Score(Byte.valueOf((byte)5));
score.computeMatchScore();*/
match.setScore(score);
match.setPlayed(calendar.getTime());
//match.setCourse(course);
}
}
private SeasonResult[] createResults(int count)
{
List<SeasonResult> results = new ArrayList<SeasonResult>(count);
for (int i=0; i<count; i++)
{
User user = createUser("User", "Number"+(i+1)); //$NON-NLS-1$ //$NON-NLS-2$
user.setId(Long.valueOf(i));
SeasonResult result = new SeasonResult(user);
for (int j=count; j>i; j--)
{
result.incrementWins();
}
results.add(result);
}
return results.toArray(new SeasonResult[results.size()]);
}
private City getCity()
{
City city = new City();
city.setId(Long.valueOf(1));
city.setName("Portland"); //$NON-NLS-1$
city.setVersion(Integer.valueOf(1));
return city;
}
// private void updateResults(Season season)
// {
// SortedSet<Match> matches = season.getMatches();
// for (Match match : matches)
// {
// updateResults(match);
// }
// }
//
// private void updateResults(Match match)
// {
// if (null == match.getPlayed())
// {
// updateUser(match.getGolfer1());
// updateUser(match.getGolfer2());
// }
// else if (match.getResult().isTie())
// {
// updateTie(match.getGolfer1());
// updateTie(match.getGolfer2());
// }
// else
// {
// updateWin(match.getResult().getWinner());
// updateLoss(match.getResult().getLoser());
// }
// }
//
// private void updateUser(User user)
// {
// // Ignore the "bye" user
// if (user == null)
// {
// return;
// }
//
// SeasonResult result = this.results.get(user);
// if (null == result)
// {
// result = new SeasonResult(user);
// this.results.put(user, result);
// }
// }
//
// private void updateTie(User user)
// {
// SeasonResult result = getResult(user);
// result.incrementTies();
// this.results.put(user, result);
// }
//
// private void updateWin(User user)
// {
// // Ignore the "bye" user
// if (user == null)
// {
// return;
// }
//
// SeasonResult result = getResult(user);
// result.incrementWins();
// this.results.put(user, result);
// }
//
// private void updateLoss(User user)
// {
// // Ignore the "bye" user
// if (user == null)
// {
// return;
// }
//
// SeasonResult result = getResult(user);
// result.incrementLosses();
// this.results.put(user, result);
// }
//
// private SeasonResult getResult(User user)
// {
// SeasonResult result = this.results.get(user);
// if (null == result)
// {
// result = new SeasonResult(user);
// }
// return result;
// }
}
| UTF-8 | Java | 10,671 | java | BracketUtilityTest.java | Java | [
{
"context": "ed\n * http://www.citygolfleague.com\n * \n * @author Steve Paquin - Sage Software Consulting, Inc.\n */\npackage com.",
"end": 163,
"score": 0.9998534321784973,
"start": 151,
"tag": "NAME",
"value": "Steve Paquin"
},
{
"context": "++)\n {\n User user = createUser(\"User\", \"Number\"+(i+1)); //$NON-NLS-1$ //$NON-NLS-2$\n ",
"end": 7862,
"score": 0.8409587740898132,
"start": 7858,
"tag": "USERNAME",
"value": "User"
}
] | null | [] | /*
* BracketUtilityTest.java
*
* Copyright © 2008-2009 City Golf League, LLC. All Rights Reserved
* http://www.citygolfleague.com
*
* @author <NAME> - Sage Software Consulting, Inc.
*/
package com.sageconsulting.util;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import junit.framework.TestCase;
import com.sageconsulting.model.BracketEntry;
import com.sageconsulting.model.City;
import com.sageconsulting.model.Course;
import com.sageconsulting.model.Match;
import com.sageconsulting.model.MatchScore;
import com.sageconsulting.model.Season;
import com.sageconsulting.model.User;
/**
* This class has unit tests for the {@link BracketUtility} class.
*/
public class BracketUtilityTest extends TestCase
{
//private Map<User, SeasonResult> results = new HashMap<User, SeasonResult>(20);
public void test()
{
int postSeasonCount = 64;
Course course = createCourse();
Season season = createSeason(course, postSeasonCount);
Calendar start = new GregorianCalendar();
List<BracketEntry> bracket = BracketUtility.generateBracket(season, start, 4);
System.out.println(BracketUtility.toString(bracket));
simulateSeason(season, course);
//updateResults(season);
//season.get
//SeasonResult[] resultArray = this.results.values().toArray(new SeasonResult[this.results.size()]);
SeasonResult[] results = createResults(postSeasonCount);
BracketUtility.fillBracket(bracket, results);
System.out.println(BracketUtility.toString(bracket));
// TODO: the bracket should be set up so the users are seeded in the order
// of thier userid. We should check to see if it is set up so that
// the users meet in the correct round.
}
private Season createSeason(Course course, int postSeasonCount)
{
Season season = new Season();
season.setCity(getCity());
season.setMatches(createMatches(postSeasonCount, course));
season.setName("Test Season"); //$NON-NLS-1$
season.setPostSeasonQualifyingCount(Integer.valueOf(postSeasonCount));
return season;
}
private SortedSet<Match> createMatches(int count, Course course)
{
TreeSet<Match> matches = new TreeSet<Match>(new Comparator<Match>()
{
public int compare(Match match1, Match match2)
{
int sort = match1.getPlayBy().compareTo(match2.getPlayBy());
if (sort == 0)
{
sort = match1.getGolfer1().getUsername().compareTo(match2.getGolfer1().getUsername());
}
return sort;
}
});
for (int i=0; i<count; i++)
{
Match match = new Match();
match.setGolfer1(createUser("Match"+i, "Golfer1")); //$NON-NLS-1$ //$NON-NLS-2$
match.setGolfer2(createUser("Match"+i, "Golfer2")); //$NON-NLS-1$ //$NON-NLS-2$
//match.setCourse(course);
match.setPlayBy(new Date());
matches.add(match);
}
return matches;
}
private User createUser(String first, String last)
{
User user = new User();
user.setFirstName(first);
user.setLastName(last);
user.setUsername(first+last);
//user.setHandicap(Double.valueOf(Math.random()*20));
return user;
}
@SuppressWarnings("boxing")
private Course createCourse()
{
City portland = new City();
portland.setName("Portland"); //$NON-NLS-1$
List<City> cities = new ArrayList<City>();
cities.add(portland);
Course course = new Course();
course.setCities(cities);
course.setCities(cities);
course.setName("Eastmoreland"); //$NON-NLS-1$
course.setMensPars(new Byte[] { 4, 4, 4, 4, 3, 5, 4, 3, 5, 4, 5, 3, 5, 4, 4, 4, 3, 4 });
course.setMensHandicaps(new Byte[] { 13, 3, 11, 9, 17, 1, 5, 15, 7, 14, 8, 18, 2, 12, 10, 4, 16, 6 });
course.setMensRating(Float.valueOf(74.4f));
course.setMensSlope(Integer.valueOf(115));
course.setWomensPars(new Byte[] { 4, 4, 4, 4, 3, 5, 4, 3, 5, 4, 5, 3, 5, 4, 4, 4, 3, 4 });
course.setWomensHandicaps(new Byte[] { 13, 3, 11, 9, 17, 1, 5, 15, 7, 14, 8, 18, 2, 12, 10, 4, 16, 6 });
course.setWomensRating(Float.valueOf(74.4f));
course.setWomensSlope(Integer.valueOf(115));
return course;
}
private void simulateSeason(Season season, Course course)
{
Calendar calendar = new GregorianCalendar();
Iterator<Match> matches = season.getMatches().iterator();
while(matches.hasNext())
{
Match match = matches.next();
MatchScore score = new MatchScore();
// TODO: Akash
/*score.computeStrokes(course, match.getGolfer1(), match.getGolfer2());
score.setPlayer1Hole1Score(Byte.valueOf((byte)5));
score.setPlayer1Hole2Score(Byte.valueOf((byte)5));
score.setPlayer1Hole3Score(Byte.valueOf((byte)5));
score.setPlayer1Hole4Score(Byte.valueOf((byte)5));
score.setPlayer1Hole5Score(Byte.valueOf((byte)5));
score.setPlayer1Hole6Score(Byte.valueOf((byte)5));
score.setPlayer1Hole7Score(Byte.valueOf((byte)5));
score.setPlayer1Hole8Score(Byte.valueOf((byte)5));
score.setPlayer1Hole9Score(Byte.valueOf((byte)5));
score.setPlayer1Hole10Score(Byte.valueOf((byte)5));
score.setPlayer1Hole11Score(Byte.valueOf((byte)5));
score.setPlayer1Hole12Score(Byte.valueOf((byte)5));
score.setPlayer1Hole13Score(Byte.valueOf((byte)5));
score.setPlayer1Hole14Score(Byte.valueOf((byte)5));
score.setPlayer1Hole15Score(Byte.valueOf((byte)5));
score.setPlayer1Hole16Score(Byte.valueOf((byte)5));
score.setPlayer1Hole17Score(Byte.valueOf((byte)5));
score.setPlayer1Hole18Score(Byte.valueOf((byte)5));
score.setPlayer2Hole1Score(Byte.valueOf((byte)5));
score.setPlayer2Hole2Score(Byte.valueOf((byte)5));
score.setPlayer2Hole3Score(Byte.valueOf((byte)5));
score.setPlayer2Hole4Score(Byte.valueOf((byte)5));
score.setPlayer2Hole5Score(Byte.valueOf((byte)5));
score.setPlayer2Hole6Score(Byte.valueOf((byte)5));
score.setPlayer2Hole7Score(Byte.valueOf((byte)5));
score.setPlayer2Hole8Score(Byte.valueOf((byte)5));
score.setPlayer2Hole9Score(Byte.valueOf((byte)5));
score.setPlayer2Hole10Score(Byte.valueOf((byte)5));
score.setPlayer2Hole11Score(Byte.valueOf((byte)5));
score.setPlayer2Hole12Score(Byte.valueOf((byte)5));
score.setPlayer2Hole13Score(Byte.valueOf((byte)5));
score.setPlayer2Hole14Score(Byte.valueOf((byte)5));
score.setPlayer2Hole15Score(Byte.valueOf((byte)5));
score.setPlayer2Hole16Score(Byte.valueOf((byte)5));
score.setPlayer2Hole17Score(Byte.valueOf((byte)5));
score.setPlayer2Hole18Score(Byte.valueOf((byte)5));
score.computeMatchScore();*/
match.setScore(score);
match.setPlayed(calendar.getTime());
//match.setCourse(course);
}
}
private SeasonResult[] createResults(int count)
{
List<SeasonResult> results = new ArrayList<SeasonResult>(count);
for (int i=0; i<count; i++)
{
User user = createUser("User", "Number"+(i+1)); //$NON-NLS-1$ //$NON-NLS-2$
user.setId(Long.valueOf(i));
SeasonResult result = new SeasonResult(user);
for (int j=count; j>i; j--)
{
result.incrementWins();
}
results.add(result);
}
return results.toArray(new SeasonResult[results.size()]);
}
private City getCity()
{
City city = new City();
city.setId(Long.valueOf(1));
city.setName("Portland"); //$NON-NLS-1$
city.setVersion(Integer.valueOf(1));
return city;
}
// private void updateResults(Season season)
// {
// SortedSet<Match> matches = season.getMatches();
// for (Match match : matches)
// {
// updateResults(match);
// }
// }
//
// private void updateResults(Match match)
// {
// if (null == match.getPlayed())
// {
// updateUser(match.getGolfer1());
// updateUser(match.getGolfer2());
// }
// else if (match.getResult().isTie())
// {
// updateTie(match.getGolfer1());
// updateTie(match.getGolfer2());
// }
// else
// {
// updateWin(match.getResult().getWinner());
// updateLoss(match.getResult().getLoser());
// }
// }
//
// private void updateUser(User user)
// {
// // Ignore the "bye" user
// if (user == null)
// {
// return;
// }
//
// SeasonResult result = this.results.get(user);
// if (null == result)
// {
// result = new SeasonResult(user);
// this.results.put(user, result);
// }
// }
//
// private void updateTie(User user)
// {
// SeasonResult result = getResult(user);
// result.incrementTies();
// this.results.put(user, result);
// }
//
// private void updateWin(User user)
// {
// // Ignore the "bye" user
// if (user == null)
// {
// return;
// }
//
// SeasonResult result = getResult(user);
// result.incrementWins();
// this.results.put(user, result);
// }
//
// private void updateLoss(User user)
// {
// // Ignore the "bye" user
// if (user == null)
// {
// return;
// }
//
// SeasonResult result = getResult(user);
// result.incrementLosses();
// this.results.put(user, result);
// }
//
// private SeasonResult getResult(User user)
// {
// SeasonResult result = this.results.get(user);
// if (null == result)
// {
// result = new SeasonResult(user);
// }
// return result;
// }
}
| 10,665 | 0.581724 | 0.555764 | 297 | 34.925926 | 25.126104 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.848485 | false | false | 8 |
595fe9ede5e545e634a7195e843ec1f067813b5d | 10,015,863,775,166 | 1578a15aaa2ab9da04b15025e888b9cb6c3075fb | /src/main/java/com/burke/stocks/ModelClass.java | c0be2ef8f231cc0703213b22306633ca55d1c4ed | [] | no_license | kvburke/Stocks | https://github.com/kvburke/Stocks | c2879c487a6b21825c1b5b2cdd91d203e302300d | 97368135566420697f5106dce1b899f658b2a42d | refs/heads/master | 2021-01-10T08:01:10.401000 | 2015-11-12T22:44:21 | 2015-11-12T22:44:21 | 45,429,755 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.burke.stocks;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class ModelClass {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
//@Autowired
private DataSource dataSource = (DataSource)context.getBean("dataSource");
private JdbcTemplate jdbcTemplateObject = (JdbcTemplate)context.getBean("jdbcTemplate");
private int gstartmonth;
private int gendmonth;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public void ModelEnterStock(Stock stock){
String SQL = "insert into Stock (Symbol, Price, Monthpurchased) values (?, ?, ?)";
String stocksymbol = stock.getSymbol();
int stockprice = stock.getPrice();
int stockmonth = stock.getMonthpurchased();
jdbcTemplateObject.update( SQL, stocksymbol, stockprice, stockmonth);
}
public List<Percentages> PortfolioPercentages(){
String SQL = "select Symbol, sum(Price) from Stock.stock Group by Symbol";
List <Percentages> percentages=new ArrayList<Percentages>();
percentages = jdbcTemplateObject.query(SQL,
new PercentagesMapper());
return percentages;
}
public List<Price> StockOverTime(StockOverTime stockovertime){
gstartmonth=stockovertime.startmonth;
gendmonth=stockovertime.endmonth;
String SQL = "select Price, Monthpurchased from Stock where Symbol = '"+stockovertime.getSymbol()+"' AND Monthpurchased >="+stockovertime.getStartmonth()+" AND Monthpurchased <="+stockovertime.getEndmonth()+" ORDER BY Monthpurchased";
List <Price> stockovertimelist = jdbcTemplateObject.query(SQL, new PriceMapper());
System.out.print("Execution of POST reponse"+gstartmonth+""+gendmonth);
return stockovertimelist;
}
public void reset(){
String SQL = "TRUNCATE TABLE stock";
jdbcTemplateObject.update(SQL);
}
public List<Stock> grid(){
String SQL = "SELECT Symbol, Price, Monthpurchased from stock";
List<Stock> grid=jdbcTemplateObject.query(SQL, new StockMapper());
return grid;
}
public List<Custom> postgains(int month){
String SQL0 = "select * from Stock.stock U1 where (monthpurchased) = ( select max(monthpurchased) from Stock.stock where symbol = U1.symbol AND monthpurchased <="+month+") order by symbol ASC LIMIT 0, 1000";
List<Stock> stockrecord = jdbcTemplateObject.query(SQL0, new StockMapper());
//symbol, price list
String SQL1= "select symbol, count(price) from stock.stock where Monthpurchased<="+month+" group by symbol order by symbol ASC";
//symbol, count(price)
List<PostGainsPercentages> gains=jdbcTemplateObject.query(SQL1, new PostGainsPercentagesMapper());
//Stock entry=gainprice.get(0);
//int price=entry.getPrice();
//String SQL2 = "SELECT Symbol, Price*count(Symbol) from stock group by symbol";
//List<PostGainsPercentages> gains=jdbcTemplateObject.query(SQL2, new PostGainsPercentagesMapper());
Stock[] stockrecordarray= new Stock[stockrecord.size()];
PostGainsPercentages[] gainsarray =new PostGainsPercentages[gains.size()];
stockrecord.toArray(stockrecordarray);
gains.toArray(gainsarray);
ArrayList<Custom> complete = new ArrayList<Custom>();
for(int i=0; i<gainsarray.length; i++){
String symbol=stockrecordarray[i].getSymbol();
int price=stockrecordarray[i].getPrice();
int count=gainsarray[i].getCount();
int multiplied=price*count;
complete.add(new Custom(symbol, multiplied));
}
return complete;
}
} | UTF-8 | Java | 3,831 | java | ModelClass.java | Java | [] | null | [] | package com.burke.stocks;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class ModelClass {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
//@Autowired
private DataSource dataSource = (DataSource)context.getBean("dataSource");
private JdbcTemplate jdbcTemplateObject = (JdbcTemplate)context.getBean("jdbcTemplate");
private int gstartmonth;
private int gendmonth;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public void ModelEnterStock(Stock stock){
String SQL = "insert into Stock (Symbol, Price, Monthpurchased) values (?, ?, ?)";
String stocksymbol = stock.getSymbol();
int stockprice = stock.getPrice();
int stockmonth = stock.getMonthpurchased();
jdbcTemplateObject.update( SQL, stocksymbol, stockprice, stockmonth);
}
public List<Percentages> PortfolioPercentages(){
String SQL = "select Symbol, sum(Price) from Stock.stock Group by Symbol";
List <Percentages> percentages=new ArrayList<Percentages>();
percentages = jdbcTemplateObject.query(SQL,
new PercentagesMapper());
return percentages;
}
public List<Price> StockOverTime(StockOverTime stockovertime){
gstartmonth=stockovertime.startmonth;
gendmonth=stockovertime.endmonth;
String SQL = "select Price, Monthpurchased from Stock where Symbol = '"+stockovertime.getSymbol()+"' AND Monthpurchased >="+stockovertime.getStartmonth()+" AND Monthpurchased <="+stockovertime.getEndmonth()+" ORDER BY Monthpurchased";
List <Price> stockovertimelist = jdbcTemplateObject.query(SQL, new PriceMapper());
System.out.print("Execution of POST reponse"+gstartmonth+""+gendmonth);
return stockovertimelist;
}
public void reset(){
String SQL = "TRUNCATE TABLE stock";
jdbcTemplateObject.update(SQL);
}
public List<Stock> grid(){
String SQL = "SELECT Symbol, Price, Monthpurchased from stock";
List<Stock> grid=jdbcTemplateObject.query(SQL, new StockMapper());
return grid;
}
public List<Custom> postgains(int month){
String SQL0 = "select * from Stock.stock U1 where (monthpurchased) = ( select max(monthpurchased) from Stock.stock where symbol = U1.symbol AND monthpurchased <="+month+") order by symbol ASC LIMIT 0, 1000";
List<Stock> stockrecord = jdbcTemplateObject.query(SQL0, new StockMapper());
//symbol, price list
String SQL1= "select symbol, count(price) from stock.stock where Monthpurchased<="+month+" group by symbol order by symbol ASC";
//symbol, count(price)
List<PostGainsPercentages> gains=jdbcTemplateObject.query(SQL1, new PostGainsPercentagesMapper());
//Stock entry=gainprice.get(0);
//int price=entry.getPrice();
//String SQL2 = "SELECT Symbol, Price*count(Symbol) from stock group by symbol";
//List<PostGainsPercentages> gains=jdbcTemplateObject.query(SQL2, new PostGainsPercentagesMapper());
Stock[] stockrecordarray= new Stock[stockrecord.size()];
PostGainsPercentages[] gainsarray =new PostGainsPercentages[gains.size()];
stockrecord.toArray(stockrecordarray);
gains.toArray(gainsarray);
ArrayList<Custom> complete = new ArrayList<Custom>();
for(int i=0; i<gainsarray.length; i++){
String symbol=stockrecordarray[i].getSymbol();
int price=stockrecordarray[i].getPrice();
int count=gainsarray[i].getCount();
int multiplied=price*count;
complete.add(new Custom(symbol, multiplied));
}
return complete;
}
} | 3,831 | 0.736361 | 0.732446 | 215 | 16.823256 | 32.719475 | 235 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.660465 | false | false | 8 |
580d912edfce5c2ae23a28f0b92170ef772721de | 24,988,119,788,496 | a953800ff272f301787128f6a6c499a41437f76a | /JEESeminar/student/CDI_LABS/src/main/java/de/gedoplan/seminar/cdi/exercise/intercept/logger/TraceCallInterceptor.java | df7b9a18168e8a55504e688ab0cb834db0f9e16c | [] | no_license | amriz/JEE_Seminar | https://github.com/amriz/JEE_Seminar | a09e2b5af02e9a9c4a6b6914e5a12bf65bc166dc | 2fb5aa98099f2608fc35e5ae061ef13108d78b1a | refs/heads/master | 2023-08-06T15:58:22.942000 | 2019-12-07T14:02:55 | 2019-12-07T14:02:55 | 226,521,690 | 0 | 0 | null | false | 2023-07-22T23:43:40 | 2019-12-07T13:54:44 | 2019-12-07T14:05:33 | 2023-07-22T23:43:39 | 41,210 | 0 | 0 | 2 | Java | false | false | package de.gedoplan.seminar.cdi.exercise.intercept.logger;
import java.io.Serializable;
import javax.annotation.Priority;
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.transaction.UserTransaction;
import de.gedoplan.seminar.cdi.demo.intercept.interceptor.TransactionRequired;
import de.gedoplan.seminar.cdi.exercise.intercept.interceptor.TraceCall;
@TraceCall
@Interceptor
@Priority(Interceptor.Priority.APPLICATION+1)
public class TraceCallInterceptor implements Serializable {
@AroundInvoke
public Object printLog(InvocationContext invCtx) throws Exception {
System.out.println(invCtx.getMethod());
return invCtx.proceed();
}
}
| UTF-8 | Java | 785 | java | TraceCallInterceptor.java | Java | [] | null | [] | package de.gedoplan.seminar.cdi.exercise.intercept.logger;
import java.io.Serializable;
import javax.annotation.Priority;
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.transaction.UserTransaction;
import de.gedoplan.seminar.cdi.demo.intercept.interceptor.TransactionRequired;
import de.gedoplan.seminar.cdi.exercise.intercept.interceptor.TraceCall;
@TraceCall
@Interceptor
@Priority(Interceptor.Priority.APPLICATION+1)
public class TraceCallInterceptor implements Serializable {
@AroundInvoke
public Object printLog(InvocationContext invCtx) throws Exception {
System.out.println(invCtx.getMethod());
return invCtx.proceed();
}
}
| 785 | 0.806369 | 0.805096 | 26 | 28.192308 | 24.685747 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.730769 | false | false | 8 |
13f366a627d58393c29aa328461267bcfaf13e03 | 34,050,500,762,600 | ac0f6e99379bcc48301beb18374bac14b568d73c | /Software2G/src/com/software2g/contable/dao/IDonacionObjetoDao.java | f84d99520e334f518ba939dae2179a9b63118135 | [] | no_license | torvicgomez/software2g | https://github.com/torvicgomez/software2g | 8ce0e7ee49b786a65ad1c3284f4a28c43abf0200 | f5325c3a9e3fb17c753dc3d6fdd5d0d422c9f757 | refs/heads/master | 2020-12-24T14:46:10.924000 | 2015-08-23T19:16:14 | 2015-08-23T19:16:14 | 41,489,960 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.software2g.contable.dao;
import java.util.List;
import com.software2g.vo.Donacionobjeto;
/**
* The DAO interface for the Donacionobjeto entity.
*/
public interface IDonacionObjetoDao {
/**
* Return the persistent entities returned from a named query.
*/
@SuppressWarnings("unchecked")
public List findByNamedQuery(String queryName);
/**
* Return the persistent entities returned from a named query with named parameters.
*/
@SuppressWarnings("unchecked")
public List findByNamedQuery(String queryName, String[] paramNames, Object[] paramValues);
/**
* Find an entity by its id (primary key).
* @return The found entity instance or null if the entity does not exist.
*/
public Donacionobjeto findDonacionobjetoById(com.software2g.vo.DonacionobjetoPK id);
/**
* Return all persistent instances of the <code>Donacionobjeto</code> entity.
*/
public List<Donacionobjeto> findAllDonacionobjetos();
public List<Donacionobjeto> findAllDonacionobjetos(long idDona);
/**
* Make the given instance managed and persistent.
*/
public void persistDonacionobjeto(Donacionobjeto donacionobjeto);
/**
* Remove the given persistent instance.
*/
public void removeDonacionobjeto(Donacionobjeto donacionobjeto);
} | UTF-8 | Java | 1,289 | java | IDonacionObjetoDao.java | Java | [] | null | [] | package com.software2g.contable.dao;
import java.util.List;
import com.software2g.vo.Donacionobjeto;
/**
* The DAO interface for the Donacionobjeto entity.
*/
public interface IDonacionObjetoDao {
/**
* Return the persistent entities returned from a named query.
*/
@SuppressWarnings("unchecked")
public List findByNamedQuery(String queryName);
/**
* Return the persistent entities returned from a named query with named parameters.
*/
@SuppressWarnings("unchecked")
public List findByNamedQuery(String queryName, String[] paramNames, Object[] paramValues);
/**
* Find an entity by its id (primary key).
* @return The found entity instance or null if the entity does not exist.
*/
public Donacionobjeto findDonacionobjetoById(com.software2g.vo.DonacionobjetoPK id);
/**
* Return all persistent instances of the <code>Donacionobjeto</code> entity.
*/
public List<Donacionobjeto> findAllDonacionobjetos();
public List<Donacionobjeto> findAllDonacionobjetos(long idDona);
/**
* Make the given instance managed and persistent.
*/
public void persistDonacionobjeto(Donacionobjeto donacionobjeto);
/**
* Remove the given persistent instance.
*/
public void removeDonacionobjeto(Donacionobjeto donacionobjeto);
} | 1,289 | 0.740884 | 0.738557 | 39 | 31.102564 | 29.665482 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.025641 | false | false | 8 |
d74e80e4801ad7532cee9c3600b0f42a30b88b35 | 38,379,827,765,721 | 09fa69751a2afeb2ab56b4dadfae616e49d6b42b | /plugins/net.bioclipse.specmol/src/net/bioclipse/specmol/listeners/AssignmentPageFocusListener.java | 76aa715497660aca06431e8d3657875511740492 | [] | no_license | VijayEluri/bioclipse.speclipse | https://github.com/VijayEluri/bioclipse.speclipse | ce7c803bab32cdfe5e8cdf5c44253281178ba60b | 89a303867e9ee326ae72468d050d320d30ddfb05 | refs/heads/master | 2020-05-20T11:06:22.160000 | 2017-06-21T07:48:23 | 2017-06-21T07:48:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*****************************************************************************
* Copyright (c) 2008 Bioclipse Project
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*****************************************************************************/
package net.bioclipse.specmol.listeners;
import net.bioclipse.specmol.editor.AssignmentPage;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
public class AssignmentPageFocusListener implements FocusListener {
private AssignmentPage page;
public AssignmentPageFocusListener(AssignmentPage page) {
this.page = page;
}
public void focusGained(FocusEvent e) {
page.setFocus();
}
public void focusLost(FocusEvent e) {
page.lostFocus();
}
}
| UTF-8 | Java | 946 | java | AssignmentPageFocusListener.java | Java | [] | null | [] | /*****************************************************************************
* Copyright (c) 2008 Bioclipse Project
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*****************************************************************************/
package net.bioclipse.specmol.listeners;
import net.bioclipse.specmol.editor.AssignmentPage;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
public class AssignmentPageFocusListener implements FocusListener {
private AssignmentPage page;
public AssignmentPageFocusListener(AssignmentPage page) {
this.page = page;
}
public void focusGained(FocusEvent e) {
page.setFocus();
}
public void focusLost(FocusEvent e) {
page.lostFocus();
}
}
| 946 | 0.645877 | 0.637421 | 34 | 26.82353 | 27.187227 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.647059 | false | false | 8 |
874f0d04b05065b96bba82b999a9c6c876ed59cf | 37,847,251,834,017 | c8f5f3340dab32a45668861d34a1b444c3b8ceb8 | /common/pixelmon/blocks/BlockFossil.java | afc7dd6546872a2d027b13e3027e890135d130ee | [] | no_license | AceOTG/Pixelmon | https://github.com/AceOTG/Pixelmon | b1c9477753fdbb7c4e290d536699a5125017c50a | 19a7d97dd416c4b698b849d58f1ece9dc14ed193 | refs/heads/master | 2021-01-18T11:54:16.500000 | 2013-01-06T03:27:02 | 2013-01-06T03:27:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pixelmon.blocks;
import java.util.Random;
import cpw.mods.fml.client.registry.RenderingRegistry;
import pixelmon.Pixelmon;
import pixelmon.config.PixelmonBlocks;
import pixelmon.config.PixelmonCreativeTabs;
import pixelmon.config.PixelmonItems;
import pixelmon.config.PixelmonItemsFossils;
import pixelmon.enums.EnumEvolutionStone;
import net.minecraft.src.Block;
import net.minecraft.src.CreativeTabs;
import net.minecraft.src.Material;
public class BlockFossil extends Block {
public BlockFossil(int id) {
super(id, Material.rock);
setStepSound(Block.soundStoneFootstep);
setCreativeTab(PixelmonCreativeTabs.natural);
setTextureFile("/pixelmon/block/blocks.png");
blockIndexInTexture = 5;
}
@Override
public int getRenderType() {
return 0;
}
public int idDropped(int i, Random rand, int j) {
return PixelmonItemsFossils.getRandomFossilId();
}
}
| UTF-8 | Java | 885 | java | BlockFossil.java | Java | [] | null | [] | package pixelmon.blocks;
import java.util.Random;
import cpw.mods.fml.client.registry.RenderingRegistry;
import pixelmon.Pixelmon;
import pixelmon.config.PixelmonBlocks;
import pixelmon.config.PixelmonCreativeTabs;
import pixelmon.config.PixelmonItems;
import pixelmon.config.PixelmonItemsFossils;
import pixelmon.enums.EnumEvolutionStone;
import net.minecraft.src.Block;
import net.minecraft.src.CreativeTabs;
import net.minecraft.src.Material;
public class BlockFossil extends Block {
public BlockFossil(int id) {
super(id, Material.rock);
setStepSound(Block.soundStoneFootstep);
setCreativeTab(PixelmonCreativeTabs.natural);
setTextureFile("/pixelmon/block/blocks.png");
blockIndexInTexture = 5;
}
@Override
public int getRenderType() {
return 0;
}
public int idDropped(int i, Random rand, int j) {
return PixelmonItemsFossils.getRandomFossilId();
}
}
| 885 | 0.79661 | 0.79435 | 37 | 22.918919 | 18.891409 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.162162 | false | false | 8 |
3c1a4f2fa8cf6577d104f74066a60e008abadc87 | 37,847,251,832,637 | fa31cbf73960833f9bb2de7bc565b48ada5b5f24 | /src/main/java/com/jubaka/remoting/model/RemoteExecutor.java | 684b4dd7927450b2833bab0e667202d084a1c868 | [] | no_license | xPosted/spring-rmi-remoteExec | https://github.com/xPosted/spring-rmi-remoteExec | f53acf0cf3415cf12d32c809ae7419ce80af75ee | 883da3a8a5bb32b738909e1a41563abe92cf9081 | refs/heads/master | 2021-05-14T08:07:04.098000 | 2018-07-19T23:46:28 | 2018-07-19T23:46:28 | 116,286,451 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jubaka.remoting.model;
/**
* Created by root on 04.01.18.
*/
public interface RemoteExecutor {
void test();
}
| UTF-8 | Java | 129 | java | RemoteExecutor.java | Java | [
{
"context": "kage com.jubaka.remoting.model;\n\n/**\n * Created by root on 04.01.18.\n */\npublic interface RemoteExecutor ",
"end": 58,
"score": 0.9942806959152222,
"start": 54,
"tag": "USERNAME",
"value": "root"
}
] | null | [] | package com.jubaka.remoting.model;
/**
* Created by root on 04.01.18.
*/
public interface RemoteExecutor {
void test();
}
| 129 | 0.674419 | 0.627907 | 8 | 15.125 | 14.365214 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 8 |
ed3c618ee8ed6a40d9c36024230a9f057d604989 | 34,720,515,665,451 | 39bc0db57a8e01f3f3c5b9a0c7cf8286512fe503 | /src/main/java/com/nitian/socket/util/protocol/ssl/SSL.java | 237228c3900c30c54c47443e67b537ce6fe8709c | [] | no_license | 1036225283/nio-server | https://github.com/1036225283/nio-server | f4ab9d3fd70a5222e71b1c95b8f939c3fc1392f3 | b2bfdc4b747d7ae28b9b22571cf067284e439abb | refs/heads/master | 2020-04-09T18:22:39.724000 | 2018-03-03T02:52:27 | 2018-03-03T02:52:27 | 160,510,275 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nitian.socket.util.protocol.ssl;
import com._1036225283.util.self.java.UtilByte;
import com._1036225283.util.self.time.UtilTime;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* ssl
* Created by xws on 6/25/17.
*/
public class SSL {
// bs[0]:(22): change_cipher_spec(20) alert(21) handshake(22) application_data(23)
// bs[1] bs[2]:(0x0301):version
// bs[3] bs[4]:(0x0b06): data length
// bs[5]:(0x01): client hello
// bs[6]-bs[9]:time
// bs[10]-bs[42]:random
// bs[43]-bs[45]:session id
// bs[46]+68:cipher
public static int SSLHandshake = 22;
public static int SSHApplicationData = 23;
public static int SSLClientHello = 1;
public static int SSLClientKeyChange = 16;
public static int SSLServerHello = 23;
public static void test(byte[] bs, int length) {
System.out.println(UtilByte.toHex(bs, length));
int ch0 = bs[0];
int ch1 = bs[1];
int ch2 = bs[2];
int ch3 = bs[3];
int ch4 = bs[4];
if (ch0 == 22) {
System.out.println("this is handshake");
}
System.out.println(UtilByte.toHex((byte) ch1));
System.out.println(UtilByte.toHex((byte) ch2));
System.out.println(UtilByte.toHex((byte) ch3));
System.out.println(UtilByte.toHex((byte) ch4));
if (bs[5] == 1) {
System.out.println("client hello");
}
//get time
long ch6 = bs[6];
long ch7 = bs[7];
long ch8 = bs[8];
long ch9 = bs[9];
long second = (ch6 << 24) + (ch7 << 16) + (ch8 << 8) + ch9;
Date date = new Date(second);
SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(dateFormater.format(date));
//get session id
int ch43 = bs[43];
System.out.println("[43] : " + UtilByte.toHex((byte) ch43));
if (ch43 == 0) {
System.out.println("session id is empty");
String cipher = new String(bs, 46, 68);
System.out.println(cipher);
}
String cipher = new String(bs, length - 68, 68);
System.out.println(cipher);
}
//get handshake protocol
public static int getHandshakeProtocol(byte[] bs) {
return bs[0];
}
//get handshake protocol version
public static int getHandshakeProtocolVersion(byte[] bs) {
int high = bs[1];
int low = bs[2];
return (high << 8) + low;
}
//get handshake data length
public static int getHandshakeProtocolLength(byte[] bs) {
int high = bs[4];
int low = bs[5];
return (high << 8) + low;
}
//get handshake type
public static int getHandshakeType(byte[] bs) {
return bs[8];
}
//get client hello length
public static long getClientHelloLength(byte[] bs) {
long bit1 = bs[7];
long bit2 = bs[8];
long bit3 = bs[9];
return (bit1 << 16) + (bit2 << 8) + bit3;
}
//get client hello version
public static int getClientHelloVersion(byte[] bs) {
int high = bs[10];
int low = bs[11];
return (high << 8) + low;
}
//get client hello random time
public static String getClientHelloRandomTime(byte[] bs) {
long bit1 = bs[12];
long bit2 = bs[13];
long bit3 = bs[14];
long bit4 = bs[15];
long time = (bit1 << 24) + (bit2 << 16) + (bit3 << 8) + bit4;
System.out.println(UtilTime.dateToyyyyMMddHHmmss(new Date(time)));
return UtilTime.dateToyyyyMMddHHmmss(new Date(time));
}
//get client hello random
public static String getClientHelloRandom(byte[] bs) {
return new String(bs, 16, 28);
}
}
| UTF-8 | Java | 3,781 | java | SSL.java | Java | [
{
"context": ";\nimport java.util.Date;\n\n/**\n * ssl\n * Created by xws on 6/25/17.\n */\npublic class SSL {\n\n // bs[0]:",
"end": 231,
"score": 0.9990041255950928,
"start": 228,
"tag": "USERNAME",
"value": "xws"
}
] | null | [] | package com.nitian.socket.util.protocol.ssl;
import com._1036225283.util.self.java.UtilByte;
import com._1036225283.util.self.time.UtilTime;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* ssl
* Created by xws on 6/25/17.
*/
public class SSL {
// bs[0]:(22): change_cipher_spec(20) alert(21) handshake(22) application_data(23)
// bs[1] bs[2]:(0x0301):version
// bs[3] bs[4]:(0x0b06): data length
// bs[5]:(0x01): client hello
// bs[6]-bs[9]:time
// bs[10]-bs[42]:random
// bs[43]-bs[45]:session id
// bs[46]+68:cipher
public static int SSLHandshake = 22;
public static int SSHApplicationData = 23;
public static int SSLClientHello = 1;
public static int SSLClientKeyChange = 16;
public static int SSLServerHello = 23;
public static void test(byte[] bs, int length) {
System.out.println(UtilByte.toHex(bs, length));
int ch0 = bs[0];
int ch1 = bs[1];
int ch2 = bs[2];
int ch3 = bs[3];
int ch4 = bs[4];
if (ch0 == 22) {
System.out.println("this is handshake");
}
System.out.println(UtilByte.toHex((byte) ch1));
System.out.println(UtilByte.toHex((byte) ch2));
System.out.println(UtilByte.toHex((byte) ch3));
System.out.println(UtilByte.toHex((byte) ch4));
if (bs[5] == 1) {
System.out.println("client hello");
}
//get time
long ch6 = bs[6];
long ch7 = bs[7];
long ch8 = bs[8];
long ch9 = bs[9];
long second = (ch6 << 24) + (ch7 << 16) + (ch8 << 8) + ch9;
Date date = new Date(second);
SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(dateFormater.format(date));
//get session id
int ch43 = bs[43];
System.out.println("[43] : " + UtilByte.toHex((byte) ch43));
if (ch43 == 0) {
System.out.println("session id is empty");
String cipher = new String(bs, 46, 68);
System.out.println(cipher);
}
String cipher = new String(bs, length - 68, 68);
System.out.println(cipher);
}
//get handshake protocol
public static int getHandshakeProtocol(byte[] bs) {
return bs[0];
}
//get handshake protocol version
public static int getHandshakeProtocolVersion(byte[] bs) {
int high = bs[1];
int low = bs[2];
return (high << 8) + low;
}
//get handshake data length
public static int getHandshakeProtocolLength(byte[] bs) {
int high = bs[4];
int low = bs[5];
return (high << 8) + low;
}
//get handshake type
public static int getHandshakeType(byte[] bs) {
return bs[8];
}
//get client hello length
public static long getClientHelloLength(byte[] bs) {
long bit1 = bs[7];
long bit2 = bs[8];
long bit3 = bs[9];
return (bit1 << 16) + (bit2 << 8) + bit3;
}
//get client hello version
public static int getClientHelloVersion(byte[] bs) {
int high = bs[10];
int low = bs[11];
return (high << 8) + low;
}
//get client hello random time
public static String getClientHelloRandomTime(byte[] bs) {
long bit1 = bs[12];
long bit2 = bs[13];
long bit3 = bs[14];
long bit4 = bs[15];
long time = (bit1 << 24) + (bit2 << 16) + (bit3 << 8) + bit4;
System.out.println(UtilTime.dateToyyyyMMddHHmmss(new Date(time)));
return UtilTime.dateToyyyyMMddHHmmss(new Date(time));
}
//get client hello random
public static String getClientHelloRandom(byte[] bs) {
return new String(bs, 16, 28);
}
}
| 3,781 | 0.568633 | 0.520762 | 139 | 26.201439 | 21.772593 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.489209 | false | false | 8 |
42b1e85dda2e451ca33ee5ddee6c6002703b4c57 | 38,912,403,705,457 | 622e32d3f136ca8a9d9f97bcadfbc4823728a84e | /APP/GOE/app/src/main/java/com/example/goe/ElectryUse_Activity.java | 08cf1bbcf4141de80f0d1b6c98a13ba5d5ad438b | [] | no_license | Nam-SW/GOE | https://github.com/Nam-SW/GOE | 69d3a3051cea904af9fd81a564da138a15ea31f7 | ed841a88bbd66980a3122673750d030b825e7578 | refs/heads/master | 2020-08-31T01:16:40.301000 | 2020-01-07T10:31:34 | 2020-01-07T10:31:34 | 218,543,795 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.goe;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class ElectryUse_Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_electry_use_);
final int a = 1220;
final TextView txt = findViewById(R.id.elec);
ImageButton btn = findViewById(R.id.btnrotate);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
txt.setText(a+"Kwh");
}
});
}
}
| UTF-8 | Java | 771 | java | ElectryUse_Activity.java | Java | [] | null | [] | package com.example.goe;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class ElectryUse_Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_electry_use_);
final int a = 1220;
final TextView txt = findViewById(R.id.elec);
ImageButton btn = findViewById(R.id.btnrotate);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
txt.setText(a+"Kwh");
}
});
}
}
| 771 | 0.662776 | 0.657588 | 34 | 21.67647 | 21.626129 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.382353 | false | false | 8 |
085e68c1f44f3e94ed27e0f3e20f2d620f863c37 | 38,293,928,419,133 | 20f720e058d169f5f294d3ea9051ec944a02f079 | /src/com/shsxt/date/TestDate.java | af7dc184a7041c5476fe12595b286380b00d192b | [] | no_license | 690877126/javacoom | https://github.com/690877126/javacoom | 665d32e9da88ef111ec90e0e4958f78479c357ba | f3b536321e336f960b3cf6dd4b7a999150e4dfcf | refs/heads/master | 2021-01-12T05:37:20.448000 | 2016-12-22T13:57:44 | 2016-12-22T13:57:44 | 77,148,882 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.shsxt.date;
import java.util.Date;
/**
* 1、获取当前时间
* new Date()
* System.currentTimeMillis();
* @author Administrator
*
*/
public class TestDate {
public static void main(String[] args) {
//当前时间 -->日期格式
Date nowTime =new Date();
System.out.println(nowTime);
//当前时间 -->长整形数
long nowTime2 =System.currentTimeMillis();
System.out.println(nowTime2);
}
}
| UTF-8 | Java | 460 | java | TestDate.java | Java | [
{
"context": "te()\r\n * System.currentTimeMillis(); \r\n * @author Administrator\r\n *\r\n */\r\npublic class TestDate {\r\n\r\n\tpublic stat",
"end": 144,
"score": 0.8888399004936218,
"start": 131,
"tag": "NAME",
"value": "Administrator"
}
] | null | [] | package com.shsxt.date;
import java.util.Date;
/**
* 1、获取当前时间
* new Date()
* System.currentTimeMillis();
* @author Administrator
*
*/
public class TestDate {
public static void main(String[] args) {
//当前时间 -->日期格式
Date nowTime =new Date();
System.out.println(nowTime);
//当前时间 -->长整形数
long nowTime2 =System.currentTimeMillis();
System.out.println(nowTime2);
}
}
| 460 | 0.623188 | 0.615942 | 24 | 15.25 | 13.845125 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.958333 | false | false | 8 |
d14b8be618f786d4e21b49e7066cdb352ac9e904 | 25,494,925,910,699 | e4f31b3b1b07cf280b3cc4b78fd325b0af68edec | /DecorateMode/src/main/java/com/qny/pizza/PizzaStore.java | 27e7c74485fb6cbb2ca475426709b90c1b5c1027 | [] | no_license | jueqingsizhe66/DesignPattern | https://github.com/jueqingsizhe66/DesignPattern | 937bcbd22efc9167f5b5aad679764464afad0ec8 | f0e0a8145a63e73a19d540c72a85cd297cb7e5b2 | refs/heads/master | 2023-06-21T07:48:47.611000 | 2023-03-13T16:30:24 | 2023-03-13T16:30:24 | 126,268,093 | 3 | 3 | null | false | 2023-06-14T22:19:06 | 2018-03-22T02:28:20 | 2023-03-10T17:20:15 | 2023-06-14T22:19:04 | 1,741 | 4 | 3 | 2 | Java | false | false | package com.qny.pizza;
/**
* @author Zhaoliang Ye 叶昭良(zl_ye@qny.chng.com.cn)
* @version V0.1
* @Title: PizzaStore.java
* @Description: (用一句话描述该文件做什么 ?)
* @Package com.qny.pizza
* @Time: 2023/3/11 23:49
*/
public class PizzaStore {
public static void main(String[] args) {
Pizza pizza = new ThickCrustPizza();
Pizza cheesePizza = new Cheese(pizza);
Pizza olivePizza = new Olive(pizza);
System.out.println(cheesePizza.description+ "\n " + cheesePizza.cost());
System.out.println(olivePizza.description+ "\n " + olivePizza.cost());
}
}
| UTF-8 | Java | 620 | java | PizzaStore.java | Java | [
{
"context": "package com.qny.pizza;\n\n/**\n * @author Zhaoliang Ye 叶昭良(zl_ye@qny.chng.com.cn)\n * @version V0.1\n * @T",
"end": 51,
"score": 0.9998524785041809,
"start": 39,
"tag": "NAME",
"value": "Zhaoliang Ye"
},
{
"context": "ckage com.qny.pizza;\n\n/**\n * @author Zhaoliang Ye 叶昭良(zl_ye@qny.chng.com.cn)\n * @version V0.1\n * @Title",
"end": 55,
"score": 0.9997987747192383,
"start": 52,
"tag": "NAME",
"value": "叶昭良"
},
{
"context": "e com.qny.pizza;\n\n/**\n * @author Zhaoliang Ye 叶昭良(zl_ye@qny.chng.com.cn)\n * @version V0.1\n * @Title: PizzaStore.java\n * @",
"end": 77,
"score": 0.9999354481697083,
"start": 56,
"tag": "EMAIL",
"value": "zl_ye@qny.chng.com.cn"
}
] | null | [] | package com.qny.pizza;
/**
* @author <NAME> 叶昭良(<EMAIL>)
* @version V0.1
* @Title: PizzaStore.java
* @Description: (用一句话描述该文件做什么 ?)
* @Package com.qny.pizza
* @Time: 2023/3/11 23:49
*/
public class PizzaStore {
public static void main(String[] args) {
Pizza pizza = new ThickCrustPizza();
Pizza cheesePizza = new Cheese(pizza);
Pizza olivePizza = new Olive(pizza);
System.out.println(cheesePizza.description+ "\n " + cheesePizza.cost());
System.out.println(olivePizza.description+ "\n " + olivePizza.cost());
}
}
| 600 | 0.647458 | 0.625424 | 20 | 28.5 | 23.544638 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 8 |
2cb31434ba3287ee8e7e9979617a54888cdf7fa7 | 4,483,945,886,239 | 776b3f77f5dbd5501b94ffdc4c37d96889b6b8f9 | /dynmictype/src/main/java/news/fan/dynmictype/MainActivity.java | a1d0d7a13add9b88d3a671a2d9de470e50996c6b | [] | no_license | kisdy502/FanNews | https://github.com/kisdy502/FanNews | 98d4d2da609e53831a8a09ba72dd12e8fa6be79c | 24ebd204ab8e013e280e1720bd22b193abc1f19e | refs/heads/master | 2021-04-27T00:22:01.863000 | 2018-04-04T09:58:19 | 2018-04-04T09:58:19 | 123,800,598 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package news.fan.dynmictype;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
static HashMap<String, Class> map = new HashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String channelId1 = "yingfeike";
String channelId2 = "fangzheng";
String channelId3 = "chuangwei";
create(channelId1);
}
static {
map.put("chuangwei", ConfigChuangwei.class);
map.put("yingfeike", ConfigInfeike.class);
map.put("fangzheng", ConfigFangzheng.class);
}
private void create(String channelId) {
Class clz = map.get(channelId);
if (clz != null) {
try {
Config config = (Config) clz.newInstance();
Log.d("MainActivity", config.getProp_BootVideo());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
static class Config {
protected String prop_BootVideo;
public String getProp_BootVideo() {
return prop_BootVideo;
}
public void setProp_BootVideo(String prop_BootVideo) {
prop_BootVideo = prop_BootVideo;
}
}
static class ConfigChuangwei extends Config {
public ConfigChuangwei() {
prop_BootVideo = "sys.bootvideo.skyworth";
}
}
static class ConfigInfeike extends Config {
public ConfigInfeike() {
prop_BootVideo = "sys.bootvideo.ifeike";
}
}
static class ConfigFangzheng extends Config {
public ConfigFangzheng() {
prop_BootVideo = "sys.bootvideo.fangzheng";
}
}
@Retention(RetentionPolicy.RUNTIME)
public @interface ChannelType {
String value();
}
}
| UTF-8 | Java | 2,170 | java | MainActivity.java | Java | [
{
"context": "yout.activity_main);\n String channelId1 = \"yingfeike\";\n String channelId2 = \"fangzheng\";\n ",
"end": 554,
"score": 0.8430811762809753,
"start": 545,
"tag": "USERNAME",
"value": "yingfeike"
}
] | null | [] | package news.fan.dynmictype;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
static HashMap<String, Class> map = new HashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String channelId1 = "yingfeike";
String channelId2 = "fangzheng";
String channelId3 = "chuangwei";
create(channelId1);
}
static {
map.put("chuangwei", ConfigChuangwei.class);
map.put("yingfeike", ConfigInfeike.class);
map.put("fangzheng", ConfigFangzheng.class);
}
private void create(String channelId) {
Class clz = map.get(channelId);
if (clz != null) {
try {
Config config = (Config) clz.newInstance();
Log.d("MainActivity", config.getProp_BootVideo());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
static class Config {
protected String prop_BootVideo;
public String getProp_BootVideo() {
return prop_BootVideo;
}
public void setProp_BootVideo(String prop_BootVideo) {
prop_BootVideo = prop_BootVideo;
}
}
static class ConfigChuangwei extends Config {
public ConfigChuangwei() {
prop_BootVideo = "sys.bootvideo.skyworth";
}
}
static class ConfigInfeike extends Config {
public ConfigInfeike() {
prop_BootVideo = "sys.bootvideo.ifeike";
}
}
static class ConfigFangzheng extends Config {
public ConfigFangzheng() {
prop_BootVideo = "sys.bootvideo.fangzheng";
}
}
@Retention(RetentionPolicy.RUNTIME)
public @interface ChannelType {
String value();
}
}
| 2,170 | 0.613364 | 0.61106 | 80 | 26.125 | 20.641811 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.425 | false | false | 8 |
4dcca104df1c9bf821cf6069a06b174d1d91ff05 | 31,035,433,715,345 | 735b5f4d46286366acc7031632f1d34172c5e2a3 | /src/main/java/com/biz/iolist/service/DeptService.java | 3d95a6cad146b7f09b73ec137b2af574fd3746a5 | [] | no_license | panddegy/SpMVC_IOlist | https://github.com/panddegy/SpMVC_IOlist | 40890715dbd1ca816d783386fd5586b1f75ff5f9 | 525763e4c838cdf108f5bcfd1b22a8b6b2f00dc0 | refs/heads/master | 2020-05-05T01:27:26.089000 | 2019-04-22T01:47:48 | 2019-04-22T01:47:48 | 179,603,438 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.biz.iolist.service;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.biz.iolist.mapper.DeptMapper;
import com.biz.iolist.mapper.ProductMapper;
import com.biz.iolist.model.DeptVO;
import com.biz.iolist.model.ProductVO;
@Service
public class DeptService {
@Autowired
SqlSession sqlSession;
public List<DeptVO> selectAllDept(){
DeptMapper deptMapper=sqlSession.getMapper(DeptMapper.class);
return deptMapper.selectAllDept();
}
public DeptVO findByDeptId(String d_code) {
DeptMapper deptMapper=sqlSession.getMapper(DeptMapper.class);
return deptMapper.findByDeptId(d_code);
}
public int insertDept(DeptVO deptVO) {
DeptMapper deptMapper=sqlSession.getMapper(DeptMapper.class);
return deptMapper.insertDept(deptVO);
}
public int updateDept(DeptVO deptVO) {
DeptMapper deptMapper=sqlSession.getMapper(DeptMapper.class);
return deptMapper.updateDept(deptVO);
}
public int deleteDept(String d_code) {
DeptMapper deptMapper=sqlSession.getMapper(DeptMapper.class);
return deptMapper.deleteDept(d_code);
}
public List<DeptVO> findByDeptName(String d_name){
DeptMapper deptMapper=sqlSession.getMapper(DeptMapper.class);
return deptMapper.findByDeptName(d_name);
}
}
| UTF-8 | Java | 1,409 | java | DeptService.java | Java | [] | null | [] | package com.biz.iolist.service;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.biz.iolist.mapper.DeptMapper;
import com.biz.iolist.mapper.ProductMapper;
import com.biz.iolist.model.DeptVO;
import com.biz.iolist.model.ProductVO;
@Service
public class DeptService {
@Autowired
SqlSession sqlSession;
public List<DeptVO> selectAllDept(){
DeptMapper deptMapper=sqlSession.getMapper(DeptMapper.class);
return deptMapper.selectAllDept();
}
public DeptVO findByDeptId(String d_code) {
DeptMapper deptMapper=sqlSession.getMapper(DeptMapper.class);
return deptMapper.findByDeptId(d_code);
}
public int insertDept(DeptVO deptVO) {
DeptMapper deptMapper=sqlSession.getMapper(DeptMapper.class);
return deptMapper.insertDept(deptVO);
}
public int updateDept(DeptVO deptVO) {
DeptMapper deptMapper=sqlSession.getMapper(DeptMapper.class);
return deptMapper.updateDept(deptVO);
}
public int deleteDept(String d_code) {
DeptMapper deptMapper=sqlSession.getMapper(DeptMapper.class);
return deptMapper.deleteDept(d_code);
}
public List<DeptVO> findByDeptName(String d_name){
DeptMapper deptMapper=sqlSession.getMapper(DeptMapper.class);
return deptMapper.findByDeptName(d_name);
}
}
| 1,409 | 0.767211 | 0.767211 | 61 | 21.90164 | 22.666292 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.47541 | false | false | 8 |
369271bc235d4ba6a625a58c8b723577bb82177f | 31,035,433,714,891 | a3c7e9bf3c46b73b08c158f877ab24e2d16aff11 | /delegation-server/src/main/java/eu/rcauth/delegserver/storage/sql/SQLTraceRecordStore.java | 47e8b54c2fb87e5325568a21abfdd04c46f2ec73 | [
"Apache-2.0"
] | permissive | rcauth-eu/aarc-delegation-server | https://github.com/rcauth-eu/aarc-delegation-server | 467427d332b7594add81a7f179be0d1d576fa100 | cceb15166c7a623cc7e4943ddd2ad311bf9f8f67 | refs/heads/0.2.3-release | 2022-10-26T23:02:08.874000 | 2022-07-29T14:11:00 | 2022-07-29T14:11:00 | 52,094,831 | 2 | 0 | Apache-2.0 | false | 2022-07-29T14:56:53 | 2016-02-19T14:58:10 | 2019-02-18T14:01:47 | 2022-07-29T14:36:33 | 348 | 2 | 0 | 1 | Java | false | false | package eu.rcauth.delegserver.storage.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.inject.Provider;
import eu.rcauth.delegserver.storage.TraceRecord;
import eu.rcauth.delegserver.storage.TraceRecordStore;
import eu.rcauth.delegserver.storage.sql.table.TraceRecordTable;
import edu.uiuc.ncsa.security.core.Identifier;
import edu.uiuc.ncsa.security.core.exceptions.GeneralException;
import edu.uiuc.ncsa.security.core.exceptions.NFWException;
import edu.uiuc.ncsa.security.core.util.BasicIdentifier;
import edu.uiuc.ncsa.security.storage.data.MapConverter;
import edu.uiuc.ncsa.security.storage.sql.ConnectionPool;
import edu.uiuc.ncsa.security.storage.sql.SQLStore;
import edu.uiuc.ncsa.security.storage.sql.internals.ColumnDescriptorEntry;
import edu.uiuc.ncsa.security.storage.sql.internals.ColumnMap;
import edu.uiuc.ncsa.security.storage.sql.internals.Table;
public class SQLTraceRecordStore extends SQLStore<TraceRecord> implements TraceRecordStore<TraceRecord> {
public static final String DEFAULT_TABLENAME = "trace_records";
public SQLTraceRecordStore(ConnectionPool connectionPool,
Table table,
Provider<TraceRecord> identifiableProvider,
MapConverter<TraceRecord> converter) {
super(connectionPool, table, identifiableProvider, converter);
}
public int getNextSequenceNumber(Identifier identifier) {
List<Identifier> ids = new ArrayList<>();
ids.add(identifier);
List<TraceRecord> traceRecords = getAll(ids);
if ( traceRecords != null )
return traceRecords.size();
else
return 0;
}
public List<TraceRecord> getAll(List<Identifier> ids) {
Connection c = getConnection();
List<TraceRecord> resultSet = new ArrayList<>();
try {
if ( !(getTable() instanceof TraceRecordTable) )
throw new NFWException("The table implementation " + getTable().getFQTablename() + " + does not extend TraceRecordTable!");
TraceRecordTable table = (TraceRecordTable) getTable();
// construct statement using the ids provided
PreparedStatement stmt = c.prepareStatement(table.createMultiSelectStatement(ids.size()));
for (int i=0 ; i<ids.size() ; i++) {
stmt.setString(i + 1, ids.get(i).toString() );
}
stmt.executeQuery();
ResultSet rs = stmt.getResultSet();
// iterate over result set
while ( rs.next() ) {
ColumnMap map = rsToMap(rs);
TraceRecord t = create();
populate(map, t);
resultSet.add(t);
}
rs.close();
stmt.close();
} catch (SQLException e) {
destroyConnection(c);
throw new GeneralException("Error getting objects from the provided ID set", e);
} finally {
releaseConnection(c);
}
if ( resultSet.isEmpty() )
return null;
return resultSet;
}
@Override
public void save(TraceRecord value) {
if (containsKey(value))
update(value);
else
register(value);
}
@Override
public void update(TraceRecord value) {
if (!containsValue(value))
throw new GeneralException("Error: cannot update non-existent entry for\"" +
value.getIdentifierString() + "\". Register it first or call save.");
Connection c = getConnection();
try {
PreparedStatement stmt = c.prepareStatement(getTable().createUpdateStatement());
ColumnMap map = depopulate(value);
int i = 1;
for (ColumnDescriptorEntry cde : getTable().getColumnDescriptor()) {
// now we loop through the table and set each and every one of these
if (!cde.isPrimaryKey()) {
Object obj = map.get(cde.getName());
// Dates confuse setObject, so turn it into an SQL Timestamp object.
if (obj instanceof Date)
obj = new Timestamp(((Date) obj).getTime());
if (obj instanceof BasicIdentifier)
stmt.setString(i++, obj.toString());
else
stmt.setObject(i++, obj);
}
}
// now set the two primary keys: cnHash and sequence_nr
stmt.setString(i++, value.getCnHash());
stmt.setInt(i, value.getSequenceNr());
stmt.executeUpdate();
stmt.close();
} catch (SQLException e) {
destroyConnection(c);
throw new GeneralException("Error updating approval with identifier = \"" + value.getIdentifierString(), e);
} finally {
releaseConnection(c);
}
}
@Override
public boolean containsKey(Object key) {
if ( !(key instanceof TraceRecord) )
return super.containsKey(key);
TraceRecord value = (TraceRecord) key;
Connection c = getConnection();
boolean rc = false;
try {
PreparedStatement stmt = c.prepareStatement( ((TraceRecordTable)getTable()).createMultiKeySelectStatement() );
stmt.setString(1, value.getCnHash());
stmt.setInt(2, value.getSequenceNr());
stmt.execute();// just execute() since executeQuery(x) would throw an exception regardless of content of x as per JDBC spec.
ResultSet rs = stmt.getResultSet();
rc = rs.next();
rs.close();
stmt.close();
} catch (SQLException e) {
destroyConnection(c);
e.printStackTrace();
} finally {
releaseConnection(c);
}
return rc;
}
}
| UTF-8 | Java | 6,063 | java | SQLTraceRecordStore.java | Java | [] | null | [] | package eu.rcauth.delegserver.storage.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.inject.Provider;
import eu.rcauth.delegserver.storage.TraceRecord;
import eu.rcauth.delegserver.storage.TraceRecordStore;
import eu.rcauth.delegserver.storage.sql.table.TraceRecordTable;
import edu.uiuc.ncsa.security.core.Identifier;
import edu.uiuc.ncsa.security.core.exceptions.GeneralException;
import edu.uiuc.ncsa.security.core.exceptions.NFWException;
import edu.uiuc.ncsa.security.core.util.BasicIdentifier;
import edu.uiuc.ncsa.security.storage.data.MapConverter;
import edu.uiuc.ncsa.security.storage.sql.ConnectionPool;
import edu.uiuc.ncsa.security.storage.sql.SQLStore;
import edu.uiuc.ncsa.security.storage.sql.internals.ColumnDescriptorEntry;
import edu.uiuc.ncsa.security.storage.sql.internals.ColumnMap;
import edu.uiuc.ncsa.security.storage.sql.internals.Table;
public class SQLTraceRecordStore extends SQLStore<TraceRecord> implements TraceRecordStore<TraceRecord> {
public static final String DEFAULT_TABLENAME = "trace_records";
public SQLTraceRecordStore(ConnectionPool connectionPool,
Table table,
Provider<TraceRecord> identifiableProvider,
MapConverter<TraceRecord> converter) {
super(connectionPool, table, identifiableProvider, converter);
}
public int getNextSequenceNumber(Identifier identifier) {
List<Identifier> ids = new ArrayList<>();
ids.add(identifier);
List<TraceRecord> traceRecords = getAll(ids);
if ( traceRecords != null )
return traceRecords.size();
else
return 0;
}
public List<TraceRecord> getAll(List<Identifier> ids) {
Connection c = getConnection();
List<TraceRecord> resultSet = new ArrayList<>();
try {
if ( !(getTable() instanceof TraceRecordTable) )
throw new NFWException("The table implementation " + getTable().getFQTablename() + " + does not extend TraceRecordTable!");
TraceRecordTable table = (TraceRecordTable) getTable();
// construct statement using the ids provided
PreparedStatement stmt = c.prepareStatement(table.createMultiSelectStatement(ids.size()));
for (int i=0 ; i<ids.size() ; i++) {
stmt.setString(i + 1, ids.get(i).toString() );
}
stmt.executeQuery();
ResultSet rs = stmt.getResultSet();
// iterate over result set
while ( rs.next() ) {
ColumnMap map = rsToMap(rs);
TraceRecord t = create();
populate(map, t);
resultSet.add(t);
}
rs.close();
stmt.close();
} catch (SQLException e) {
destroyConnection(c);
throw new GeneralException("Error getting objects from the provided ID set", e);
} finally {
releaseConnection(c);
}
if ( resultSet.isEmpty() )
return null;
return resultSet;
}
@Override
public void save(TraceRecord value) {
if (containsKey(value))
update(value);
else
register(value);
}
@Override
public void update(TraceRecord value) {
if (!containsValue(value))
throw new GeneralException("Error: cannot update non-existent entry for\"" +
value.getIdentifierString() + "\". Register it first or call save.");
Connection c = getConnection();
try {
PreparedStatement stmt = c.prepareStatement(getTable().createUpdateStatement());
ColumnMap map = depopulate(value);
int i = 1;
for (ColumnDescriptorEntry cde : getTable().getColumnDescriptor()) {
// now we loop through the table and set each and every one of these
if (!cde.isPrimaryKey()) {
Object obj = map.get(cde.getName());
// Dates confuse setObject, so turn it into an SQL Timestamp object.
if (obj instanceof Date)
obj = new Timestamp(((Date) obj).getTime());
if (obj instanceof BasicIdentifier)
stmt.setString(i++, obj.toString());
else
stmt.setObject(i++, obj);
}
}
// now set the two primary keys: cnHash and sequence_nr
stmt.setString(i++, value.getCnHash());
stmt.setInt(i, value.getSequenceNr());
stmt.executeUpdate();
stmt.close();
} catch (SQLException e) {
destroyConnection(c);
throw new GeneralException("Error updating approval with identifier = \"" + value.getIdentifierString(), e);
} finally {
releaseConnection(c);
}
}
@Override
public boolean containsKey(Object key) {
if ( !(key instanceof TraceRecord) )
return super.containsKey(key);
TraceRecord value = (TraceRecord) key;
Connection c = getConnection();
boolean rc = false;
try {
PreparedStatement stmt = c.prepareStatement( ((TraceRecordTable)getTable()).createMultiKeySelectStatement() );
stmt.setString(1, value.getCnHash());
stmt.setInt(2, value.getSequenceNr());
stmt.execute();// just execute() since executeQuery(x) would throw an exception regardless of content of x as per JDBC spec.
ResultSet rs = stmt.getResultSet();
rc = rs.next();
rs.close();
stmt.close();
} catch (SQLException e) {
destroyConnection(c);
e.printStackTrace();
} finally {
releaseConnection(c);
}
return rc;
}
}
| 6,063 | 0.60729 | 0.606301 | 179 | 32.87151 | 29.088964 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.569832 | false | false | 8 |
3e7dc0fa8978f6504f65dbdf48c458e5dbad893f | 29,746,943,526,453 | a5f04dcf7e19c136591617e88af59048152f66d8 | /services/src/openkilda-gui/src/main/java/org/usermanagement/dao/repository/UserRepository.java | d4ae85d3eb4db8c14c972af75f7b7414393d07cc | [
"Apache-2.0"
] | permissive | Bobafettywut/open-kilda | https://github.com/Bobafettywut/open-kilda | cb267a2ff5d3acd187d1b18dc6e5305e67499848 | 7f98bf42f83e1b684334743662fc664e69991861 | refs/heads/master | 2020-03-23T02:26:57.406000 | 2018-07-12T08:33:30 | 2018-07-12T08:33:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.usermanagement.dao.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Set;
import org.usermanagement.dao.entity.RoleEntity;
import org.usermanagement.dao.entity.UserEntity;
/**
* The Interface UserRepository.
*/
@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
/**
* Find by username.
*
* @param userName the user name
* @return the user entity
*/
UserEntity findByUsername(String userName);
/**
* Find by active flag.
*
* @param activeFlag the active flag
* @return the list
*/
List<UserEntity> findByActiveFlag(boolean activeFlag);
/**
* Find byroles.
*
* @param roleEntity the role entity
* @return the list
*/
List<UserEntity> findByroles(RoleEntity roleEntity);
/**
* @param userId
* @return
*/
UserEntity findByUserId(long userId);
/**
* Find by roles role id.
*
* @param roleId the role id
* @return the sets the
*/
Set<UserEntity> findByRoles_roleId(Long roleId);
/**
* Find by user id in.
*
* @param userIds the user ids
* @return the list
*/
List<UserEntity> findByUserIdIn(Set<Long> userIds);
}
| UTF-8 | Java | 1,435 | java | UserRepository.java | Java | [
{
"context": "d by username.\r\n *\r\n * @param userName the user name\r\n * @return the user entity\r\n */\r\n Use",
"end": 526,
"score": 0.7758427858352661,
"start": 517,
"tag": "USERNAME",
"value": "user name"
}
] | null | [] | package org.usermanagement.dao.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Set;
import org.usermanagement.dao.entity.RoleEntity;
import org.usermanagement.dao.entity.UserEntity;
/**
* The Interface UserRepository.
*/
@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
/**
* Find by username.
*
* @param userName the user name
* @return the user entity
*/
UserEntity findByUsername(String userName);
/**
* Find by active flag.
*
* @param activeFlag the active flag
* @return the list
*/
List<UserEntity> findByActiveFlag(boolean activeFlag);
/**
* Find byroles.
*
* @param roleEntity the role entity
* @return the list
*/
List<UserEntity> findByroles(RoleEntity roleEntity);
/**
* @param userId
* @return
*/
UserEntity findByUserId(long userId);
/**
* Find by roles role id.
*
* @param roleId the role id
* @return the sets the
*/
Set<UserEntity> findByRoles_roleId(Long roleId);
/**
* Find by user id in.
*
* @param userIds the user ids
* @return the list
*/
List<UserEntity> findByUserIdIn(Set<Long> userIds);
}
| 1,435 | 0.614634 | 0.614634 | 63 | 20.777779 | 19.242352 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 8 |
2ee9d92a1036662753c6d32f4a0f7db915ab6790 | 30,124,900,648,012 | fbc7db32a2a6d965d06d370614472a38c5473900 | /ImplementStack.java | ad95e137ccc010e751aded3bd53090cfd845ebce | [] | no_license | nikhilnadagouda/Java | https://github.com/nikhilnadagouda/Java | d018663f5f45cd3ecb4d0e93b27a036a8d7e706e | c7786225cf5baca6ec303bc2ebe011398959d442 | refs/heads/master | 2020-05-25T19:23:34.786000 | 2017-10-16T02:03:44 | 2017-10-16T02:03:44 | 51,691,134 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //Implement Stack using Arrays only which supports
//push, pop, peek, size operations on Generic datatypes
public class Stack<T> {
private int stackSize;
private T [] stackArr;
private int top;
private int intialSize;
private int limit;
public Stack() throws Exception{
intialSize = 50;
limit =10;
stacksize = initialSize;
stackArr = new T [stackSize];
top = -1;
}
public Stack(int size) throws Exception{
if (size<0){
throw new Exception("Negative Stack Size");
}
stacksize = size;
stackArr = new T [size];
top = -1;
initialSize = size;
limit =10;
}
pulic void push(<T> entry){
if(isStackFull()){
ensureCapacity();
}
stackArr[++top] = entry;
}
public <T> pop() throws Exception{
if(isStackEmpty()){
throw new Exception("Stack is Empty");
}
<T> entry = stackArr[top--];
return entry;
}
public <T> peek() throws Exception
{
if(isStackEmpty()){
throw new Exception("Stack is Empty");
}
<T> entry = stackArr[top];
return entry;
}
public int size(){
return (top+1);
}
public boolean isStackEmpty(){
return(top == -1);
}
public boolean isStackFull(){
return (top == stackSize -1);
}
private void ensureCapacity(){
int newSize = stackSize +limit;
stackArr = Arrays.copy(stackArr, newSize);
}
}
| UTF-8 | Java | 1,217 | java | ImplementStack.java | Java | [] | null | [] | //Implement Stack using Arrays only which supports
//push, pop, peek, size operations on Generic datatypes
public class Stack<T> {
private int stackSize;
private T [] stackArr;
private int top;
private int intialSize;
private int limit;
public Stack() throws Exception{
intialSize = 50;
limit =10;
stacksize = initialSize;
stackArr = new T [stackSize];
top = -1;
}
public Stack(int size) throws Exception{
if (size<0){
throw new Exception("Negative Stack Size");
}
stacksize = size;
stackArr = new T [size];
top = -1;
initialSize = size;
limit =10;
}
pulic void push(<T> entry){
if(isStackFull()){
ensureCapacity();
}
stackArr[++top] = entry;
}
public <T> pop() throws Exception{
if(isStackEmpty()){
throw new Exception("Stack is Empty");
}
<T> entry = stackArr[top--];
return entry;
}
public <T> peek() throws Exception
{
if(isStackEmpty()){
throw new Exception("Stack is Empty");
}
<T> entry = stackArr[top];
return entry;
}
public int size(){
return (top+1);
}
public boolean isStackEmpty(){
return(top == -1);
}
public boolean isStackFull(){
return (top == stackSize -1);
}
private void ensureCapacity(){
int newSize = stackSize +limit;
stackArr = Arrays.copy(stackArr, newSize);
}
}
| 1,217 | 0.691865 | 0.682005 | 77 | 14.805195 | 14.603005 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 8 |
96b9291fa9be5e000601ec2ddf0c8ca06725486c | 26,852,135,545,888 | bd738ecb6bf6d40e4da21fa83f510858d9d6558d | /src/java/Servlet/AgeCalculatorServlet.java | 5b7ca63545c1a9e1f5a5e6d1aa8d800659e1ef4a | [] | no_license | Minchul-Sung/Week2Lab_Calculators | https://github.com/Minchul-Sung/Week2Lab_Calculators | 637da480e4aca40851d6ba3b74d89210776745a3 | 75a737b1c954df6145184df02759347ae2dd725e | refs/heads/master | 2022-12-22T23:49:43.070000 | 2020-09-28T04:26:19 | 2020-09-28T04:26:19 | 299,189,078 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Min Chul, Sung [808360]
*/
public class AgeCalculatorServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
getServletContext().getRequestDispatcher("/WEB-INF/agecalculator.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String strAge = request.getParameter("enterAge");
int getAge = 0;
int result = 0;
String resultMessage = "Your age next birthday will be ";
if(!strAge.equals("") || strAge != null) {
getAge = Integer.parseInt(strAge);
result = getAge + 1;
} else {
response.getWriter().println("You must give your current age.");
}
request.setAttribute("resultMess", resultMessage+result);
getServletContext().getRequestDispatcher("/WEB-INF/agecalculator.jsp").forward(request, response);
}
}
| UTF-8 | Java | 1,424 | java | AgeCalculatorServlet.java | Java | [
{
"context": "rvlet.http.HttpServletResponse;\r\n\r\n/**\r\n * @author Min Chul, Sung [808360]\r\n */\r\npublic class AgeCalculatorSe",
"end": 279,
"score": 0.9998598098754883,
"start": 271,
"tag": "NAME",
"value": "Min Chul"
},
{
"context": ".HttpServletResponse;\r\n\r\n/**\r\n * @author Min Chul, Sung [808360]\r\n */\r\npublic class AgeCalculatorServlet ",
"end": 285,
"score": 0.9975379109382629,
"start": 281,
"tag": "NAME",
"value": "Sung"
}
] | null | [] | package Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author <NAME>, Sung [808360]
*/
public class AgeCalculatorServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
getServletContext().getRequestDispatcher("/WEB-INF/agecalculator.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String strAge = request.getParameter("enterAge");
int getAge = 0;
int result = 0;
String resultMessage = "Your age next birthday will be ";
if(!strAge.equals("") || strAge != null) {
getAge = Integer.parseInt(strAge);
result = getAge + 1;
} else {
response.getWriter().println("You must give your current age.");
}
request.setAttribute("resultMess", resultMessage+result);
getServletContext().getRequestDispatcher("/WEB-INF/agecalculator.jsp").forward(request, response);
}
}
| 1,422 | 0.655197 | 0.648876 | 40 | 33.549999 | 33.909401 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.675 | false | false | 8 |
d513b6b440201301d32e003f42b364ee018c8eb2 | 31,215,822,320,594 | c7c96771354fe66b55704f29de4a08de7dea10f8 | /service/src/main/java/org/ops4j/pax/wicket/internal/injection/registry/OSGiServiceRegistryProxyTargetLocatorFactory.java | 2951427a883e8807ef89836a1ce1e0b1bbcfdc27 | [
"Classpath-exception-2.0",
"BSD-3-Clause",
"CPL-1.0",
"CDDL-1.0",
"MIT",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain",
"EPL-1.0",
"LGPL-2.0-or-later",
"W3C",
"MPL-1.1"
] | permissive | ops4j/org.ops4j.pax.wicket | https://github.com/ops4j/org.ops4j.pax.wicket | 0ee542164c48298f1a86a880f4942d9422f7ec46 | ef7cb4bdf918e9e61ec69789b9c690567616faa9 | refs/heads/master | 2023-07-30T00:53:00.001000 | 2018-10-04T13:15:13 | 2018-10-04T13:15:13 | 1,228,775 | 16 | 19 | Apache-2.0 | false | 2022-12-21T18:50:39 | 2011-01-07T06:22:43 | 2020-06-16T18:12:09 | 2022-12-21T18:50:36 | 10,552 | 30 | 26 | 14 | Java | false | false |
/**
* Copyright OPS4J
*
* 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.
*
* @author nmw
* @version $Id: $Id
*/
package org.ops4j.pax.wicket.internal.injection.registry;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.ops4j.pax.wicket.api.PaxWicketBeanFilter;
import org.ops4j.pax.wicket.api.PaxWicketBeanInjectionSource;
import org.ops4j.pax.wicket.internal.injection.BundleAnalysingComponentInstantiationListener;
import org.ops4j.pax.wicket.spi.FutureProxyTargetLocator;
import org.ops4j.pax.wicket.spi.ProxyTargetLocator;
import org.ops4j.pax.wicket.spi.ProxyTargetLocatorFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleReference;
import org.osgi.framework.Filter;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(service = { ProxyTargetLocatorFactory.class })
public class OSGiServiceRegistryProxyTargetLocatorFactory implements
ProxyTargetLocatorFactory.DelayableProxyTargetLocatorFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(OSGiServiceRegistryProxyTargetLocatorFactory.class);
/**
* <p>Constructor for OSGiServiceRegistryProxyTargetLocatorFactory.</p>
*/
public OSGiServiceRegistryProxyTargetLocatorFactory() {
}
/**
* <p>getName.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getName() {
return PaxWicketBeanInjectionSource.INJECTION_SOURCE_SERVICE_REGISTRY;
}
/** {@inheritDoc} */
public ProxyTargetLocator createProxyTargetLocator(BundleContext callingContext, Field field, Class<?> page,
Map<String, String> overwrites) {
BundleContext context;
if (page.getClassLoader() instanceof BundleReference) {
// Fetch the Bundlecontext of the page class to locate the service
BundleReference reference = (BundleReference) page.getClassLoader();
context = reference.getBundle().getBundleContext();
LOGGER.debug("Using the Bundlereference of class {} for locating services", page);
} else {
context = callingContext;
LOGGER.debug("Using the PAX Wicket BundlereContext for locating services");
}
Filter filter = getFilter(context, field);
// is it am Iterable?
Class<?> type = field.getType();
if (type.equals(Iterable.class)) {
Class<?> argument = BundleAnalysingComponentInstantiationListener.getGenericTypeArgument(field);
LOGGER.debug("Inject Iterable for type {}", argument);
return new StaticProxyTargetLocator(createIterable(argument, filter, context), page);
}
// or a supported collection...
if (type.equals(Collection.class) || type.equals(Set.class) || type.equals(List.class)) {
Class<?> argument = BundleAnalysingComponentInstantiationListener.getGenericTypeArgument(field);
LOGGER.debug("Inject Collection, Set or List for type {}", argument);
return new StaticProxyTargetLocator(createCollection(argument, filter, context), page);
}
OSGiServiceRegistryProxyTargetLocator locator =
new OSGiServiceRegistryProxyTargetLocator(context, filter,
type, page);
if (locator.fetchReferences() != null) {
return locator;
} else {
return null;
}
}
/** {@inheritDoc} */
public FutureProxyTargetLocator createFutureProxyTargetLocator(BundleContext context, Field field,
Class<?> realFieldType, Class<?> page,
Map<String, String> overwrites) {
return new OSGiServiceRegistryProxyTargetLocator(context, getFilter(context, field),
realFieldType, page);
}
private static Filter getFilter(BundleContext context, Field field) {
PaxWicketBeanFilter annotation = field.getAnnotation(PaxWicketBeanFilter.class);
if (annotation != null) {
String value = annotation.value();
if (value != null && !value.isEmpty()) {
try {
return context.createFilter(value);
} catch (InvalidSyntaxException e) {
throw new IllegalArgumentException("Filterstring is invalid", e);
}
}
}
return null;
}
/**
* Creates an {@link Iterable} for the given type and filter using the specified context
*
* @param <T>
* @param type
* @param filter
* @param context
* @return
*/
private static <T> ServiceReferenceIterable<T> createIterable(Class<T> type, Filter filter,
BundleContext context) {
return new ServiceReferenceIterable<T>(type, filter != null ? filter.toString() : null, context);
}
private static <T> ServiceReferenceCollection<T> createCollection(Class<T> type, Filter filter,
BundleContext context) {
ServiceReferenceIterable<T> iterable = createIterable(type, filter, context);
return new ServiceReferenceCollection<T>(iterable);
}
}
| UTF-8 | Java | 5,787 | java | OSGiServiceRegistryProxyTargetLocatorFactory.java | Java | [
{
"context": "nd\n * limitations under the License.\n *\n * @author nmw\n * @version $Id: $Id\n */\npackage org.ops4j.pax.wi",
"end": 599,
"score": 0.9996923208236694,
"start": 596,
"tag": "USERNAME",
"value": "nmw"
}
] | null | [] |
/**
* Copyright OPS4J
*
* 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.
*
* @author nmw
* @version $Id: $Id
*/
package org.ops4j.pax.wicket.internal.injection.registry;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.ops4j.pax.wicket.api.PaxWicketBeanFilter;
import org.ops4j.pax.wicket.api.PaxWicketBeanInjectionSource;
import org.ops4j.pax.wicket.internal.injection.BundleAnalysingComponentInstantiationListener;
import org.ops4j.pax.wicket.spi.FutureProxyTargetLocator;
import org.ops4j.pax.wicket.spi.ProxyTargetLocator;
import org.ops4j.pax.wicket.spi.ProxyTargetLocatorFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleReference;
import org.osgi.framework.Filter;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(service = { ProxyTargetLocatorFactory.class })
public class OSGiServiceRegistryProxyTargetLocatorFactory implements
ProxyTargetLocatorFactory.DelayableProxyTargetLocatorFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(OSGiServiceRegistryProxyTargetLocatorFactory.class);
/**
* <p>Constructor for OSGiServiceRegistryProxyTargetLocatorFactory.</p>
*/
public OSGiServiceRegistryProxyTargetLocatorFactory() {
}
/**
* <p>getName.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getName() {
return PaxWicketBeanInjectionSource.INJECTION_SOURCE_SERVICE_REGISTRY;
}
/** {@inheritDoc} */
public ProxyTargetLocator createProxyTargetLocator(BundleContext callingContext, Field field, Class<?> page,
Map<String, String> overwrites) {
BundleContext context;
if (page.getClassLoader() instanceof BundleReference) {
// Fetch the Bundlecontext of the page class to locate the service
BundleReference reference = (BundleReference) page.getClassLoader();
context = reference.getBundle().getBundleContext();
LOGGER.debug("Using the Bundlereference of class {} for locating services", page);
} else {
context = callingContext;
LOGGER.debug("Using the PAX Wicket BundlereContext for locating services");
}
Filter filter = getFilter(context, field);
// is it am Iterable?
Class<?> type = field.getType();
if (type.equals(Iterable.class)) {
Class<?> argument = BundleAnalysingComponentInstantiationListener.getGenericTypeArgument(field);
LOGGER.debug("Inject Iterable for type {}", argument);
return new StaticProxyTargetLocator(createIterable(argument, filter, context), page);
}
// or a supported collection...
if (type.equals(Collection.class) || type.equals(Set.class) || type.equals(List.class)) {
Class<?> argument = BundleAnalysingComponentInstantiationListener.getGenericTypeArgument(field);
LOGGER.debug("Inject Collection, Set or List for type {}", argument);
return new StaticProxyTargetLocator(createCollection(argument, filter, context), page);
}
OSGiServiceRegistryProxyTargetLocator locator =
new OSGiServiceRegistryProxyTargetLocator(context, filter,
type, page);
if (locator.fetchReferences() != null) {
return locator;
} else {
return null;
}
}
/** {@inheritDoc} */
public FutureProxyTargetLocator createFutureProxyTargetLocator(BundleContext context, Field field,
Class<?> realFieldType, Class<?> page,
Map<String, String> overwrites) {
return new OSGiServiceRegistryProxyTargetLocator(context, getFilter(context, field),
realFieldType, page);
}
private static Filter getFilter(BundleContext context, Field field) {
PaxWicketBeanFilter annotation = field.getAnnotation(PaxWicketBeanFilter.class);
if (annotation != null) {
String value = annotation.value();
if (value != null && !value.isEmpty()) {
try {
return context.createFilter(value);
} catch (InvalidSyntaxException e) {
throw new IllegalArgumentException("Filterstring is invalid", e);
}
}
}
return null;
}
/**
* Creates an {@link Iterable} for the given type and filter using the specified context
*
* @param <T>
* @param type
* @param filter
* @param context
* @return
*/
private static <T> ServiceReferenceIterable<T> createIterable(Class<T> type, Filter filter,
BundleContext context) {
return new ServiceReferenceIterable<T>(type, filter != null ? filter.toString() : null, context);
}
private static <T> ServiceReferenceCollection<T> createCollection(Class<T> type, Filter filter,
BundleContext context) {
ServiceReferenceIterable<T> iterable = createIterable(type, filter, context);
return new ServiceReferenceCollection<T>(iterable);
}
}
| 5,787 | 0.685329 | 0.68291 | 142 | 39.746479 | 32.509464 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65493 | false | false | 8 |
18d73f01f97fd31ffe4a24e74af263d5baa27e22 | 29,042,568,869,479 | f6a74b4106ff9259bc47caefc44e8e61eb6ed353 | /src/com/hoperun/api/service/impl/MessageServiceImpl.java | a4a46afaeb9959154d525673fbac7bd16ba3093a | [] | no_license | HappyMinChao/CorpWechatApi | https://github.com/HappyMinChao/CorpWechatApi | 8ca9737d35405453b5d183426e0ed6700cdad76c | 9fbaa72c535cfa09a8916eb1a21a94fe0e3d2432 | refs/heads/master | 2020-09-16T11:36:48.232000 | 2018-01-11T07:29:47 | 2018-01-11T07:29:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hoperun.api.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hoperun.api.entity.ApiUser;
import com.hoperun.api.entity.MsgReceive;
import com.hoperun.api.entity.MsgResult;
import com.hoperun.api.entity.MsgSend;
import com.hoperun.api.entity.MsgTask;
import com.hoperun.api.entity.SurveyInfo;
import com.hoperun.api.entity.User;
import com.hoperun.api.service.AgentService;
import com.hoperun.api.service.ApiUserService;
import com.hoperun.api.service.MessageService;
import com.hoperun.api.service.MsgReceiveService;
import com.hoperun.api.service.MsgResultService;
import com.hoperun.api.service.MsgSendService;
import com.hoperun.api.service.MsgTaskService;
import com.hoperun.api.service.SurveyInfoService;
import com.hoperun.api.service.UserService;
import com.hoperun.api.utils.BackMessage;
import com.hoperun.api.utils.Constants;
import com.hoperun.api.utils.Helper;
import com.hoperun.api.utils.MD5;
import com.hoperun.api.vo.DataReceive;
import com.hoperun.api.vo.DataResult;
import com.hoperun.api.vo.ReqArticle;
import com.hoperun.api.vo.ReqHead;
import com.hoperun.api.vo.ReqJson;
import com.hoperun.api.vo.ReqNews;
import com.hoperun.api.vo.ReqReceiver;
import com.hoperun.api.vo.ReqSender;
import com.hoperun.api.vo.ReqText;
import com.hoperun.api.vo.ReqTouser;
@Service
public class MessageServiceImpl implements MessageService {
@Autowired
private UserService userService;
@Autowired
private AgentService agentService;
@Autowired
private ApiUserService apiUserService;
@Autowired
private MsgTaskService msgTaskService;
@Autowired
private MsgReceiveService msgReceiveService;
@Autowired
private MsgSendService msgSendService;
@Autowired
private MsgResultService msgResultService;
@Autowired
private SurveyInfoService surveyInfoService;
private static final Logger logger = LoggerFactory
.getLogger(MessageServiceImpl.class);
public String executeReceiveMessage(String message) {
String uuid = Helper.getUUID();
String busiid = "000000000000000000";
try {
if (StringUtils.isEmpty(message)) {
return BackMessage.resultJson(-4001, busiid);
}
ObjectMapper mapper = new ObjectMapper();
ReqJson json = mapper.readValue(message, ReqJson.class);
if (json == null) {
return BackMessage.resultJson(-4001, busiid);
}
ReqHead head = json.getHead();
if (head == null) {
return BackMessage.resultJson(-4002, busiid);
}
String apiuser = head.getApiuser();
if (StringUtils.isEmpty(apiuser)) {
return BackMessage.resultJson(-4003, busiid);
}
String apipass = head.getApipass();
if (StringUtils.isEmpty(apipass)) {
return BackMessage.resultJson(-4004, busiid);
}
MD5 md5 = new MD5();
ApiUser apiUser = apiUserService.getAipUserbyUserCode(apiuser);
if (apiUser == null
|| !StringUtils
.equals(md5.getMD5ofStr(apipass).toLowerCase(),
apiUser.getPassword().toLowerCase())) {
return BackMessage.resultJson(-4016, busiid);
}
String agentkey = json.getAgentkey();
if (StringUtils.isEmpty(agentkey)) {
return BackMessage.resultJson(-4008, busiid);
}
// 非客服类消息校验;
if (!"QIYEKEFU".equals(agentkey)) {
List<ReqTouser> tousers = json.getTouser();
if (tousers == null || tousers.size() == 0) {
return BackMessage.resultJson(-4005, busiid);
}
for (ReqTouser touser : tousers) {
if (StringUtils.isEmpty(touser.getUserid())
&& (StringUtils.isEmpty(touser.getUsername()) || StringUtils
.isEmpty(touser.getMobile()))) {
return BackMessage.resultJson(-4006, uuid);
}
}
} else {
// 客服消息专属校验
ReqSender sender = json.getSender();
if (sender == null) {
return BackMessage.resultJson(-4018, busiid);
}
String senderType = sender.getType();
if (StringUtils.isEmpty(senderType)) {
return BackMessage.resultJson(-4019, busiid);
}
String senderId = sender.getId();
if (StringUtils.isEmpty(senderId)) {
return BackMessage.resultJson(-4020, busiid);
}
ReqReceiver receiver = json.getReceiver();
if (receiver == null) {
return BackMessage.resultJson(-4021, busiid);
}
String receiverType = receiver.getType();
if (StringUtils.isEmpty(receiverType)) {
return BackMessage.resultJson(-4022, busiid);
}
String receiverId = receiver.getId();
if (StringUtils.isEmpty(receiverId)) {
return BackMessage.resultJson(-4023, busiid);
}
}
String msgtype = json.getMsgtype();
if (StringUtils.isEmpty(msgtype)) {
return BackMessage.resultJson(-4009, busiid);
}
if (!"text".equals(msgtype) && !"news".equals(msgtype)) {
return BackMessage.resultJson(-4010, busiid);
}
if ("text".equals(msgtype)) {
ReqText text = json.getText();
if (text == null) {
return BackMessage.resultJson(-4011, busiid);
}
String content = text.getContent();
if (StringUtils.isEmpty(content)) {
return BackMessage.resultJson(-4012, busiid);
}
}
if ("news".equals(msgtype)) {
ReqNews news = json.getNews();
if (news == null) {
return BackMessage.resultJson(-4013, busiid);
}
List<ReqArticle> articles = news.getArticles();
if (articles == null || articles.size() == 0) {
return BackMessage.resultJson(-4014, busiid);
}
for (ReqArticle article : articles) {
if (StringUtils.isEmpty(article.getTitle())
|| StringUtils.isEmpty(article.getDescription())) {
return BackMessage.resultJson(-4015, busiid);
}
}
}
DataReceive rece = new DataReceive();
rece.setTaskId(uuid);
rece.setMessage(message);
rece.setJson(json);
// 验证完毕;
if (Constants.REQ_JSON_LIST.size() < 2000) {
Constants.REQ_JSON_LIST.add(rece);
} else {
logger.info("OUT-OFF:" + uuid);
}
} catch (Exception e) {
logger.error("接收消息异常:" + e.getMessage());
return BackMessage.resultJson(-4017, busiid);
}
return BackMessage.resultJson(0, uuid);
}
public void executeSendMessage(MsgTask task) {
MsgTask mt = new MsgTask();
String taskId = task.getTaskId();
String agentKey = task.getAgentKey();
try {
String sendMessage = msgSendService.getSendMessage(taskId);
logger.info("sendMessage:" + sendMessage);
String getTokenUrl = Constants.API_CODE_MAP
.get("GET-CORP-TOKEN-URL");
getTokenUrl = getTokenUrl + "?agentKey=" + agentKey;
logger.info("getTokenUrl:" + getTokenUrl);
String accessToken = Helper.doGet(getTokenUrl, "utf-8");
String sendMsgUrl = Constants.API_CODE_MAP.get("DOMAIN-NAME")
+ "/cgi-bin/message/send?access_token=" + accessToken;
logger.info("sendMsgUrl:" + sendMsgUrl);
String back = Helper.doPost(sendMsgUrl, sendMessage, "utf-8");
logger.info("back:" + back);
if (!StringUtils.isEmpty(back) && back.startsWith("{")) {
String errorMsg = "";
ObjectMapper mapper = new ObjectMapper();
DataResult result = mapper.readValue(back, DataResult.class);
mt.setTaskId(taskId);
mt.setStatus(Constants.OVER_STATUS);
mt.setErrorCode(result.getErrcode());
// 将英文说明转化为中文对照;
errorMsg = Constants.API_CODE_MAP.get(mt.getErrorCode());
errorMsg = StringUtils.isEmpty(errorMsg) ? result.getErrmsg()
: errorMsg;
mt.setErrorMsg(errorMsg);
int serialNo = 1;
ArrayList<String> arrays = Helper.splitStr(back, 3600, "utf-8");
if (arrays != null && arrays.size() > 0) {
MsgResult rlt = new MsgResult();
rlt.setTaskId(taskId);
rlt.setStatus(Constants.INIT_STATUS);
msgResultService.modifyMsgResult(rlt);
for (String msg : arrays) {
rlt = new MsgResult();
rlt.setTaskId(taskId);
rlt.setSerialNo(serialNo);
rlt.setMessage(msg);
msgResultService.saveMsgResult(rlt);
serialNo++;
}
}
} else {
mt.setTaskId(taskId);
mt.setStatus(Constants.OVER_STATUS);
mt.setErrorCode("-9999");
mt.setErrorMsg("企业号自定义:腾讯返回结果为空!");
}
} catch (Exception e) {
e.printStackTrace();
logger.error("执行消息发送异常:" + e.getMessage());
mt.setTaskId(taskId);
mt.setStatus(Constants.OVER_STATUS);
mt.setErrorCode("-9999");
mt.setErrorMsg("系统异常");
}
msgTaskService.modifyMsgTask(mt);
}
public void executeSaveTask(DataReceive rece) {
try {
logger.info("taskId:" + rece.getTaskId());
logger.info("jsonMessage:" + rece.getMessage());
int serialNo = 1;
Long agentId = null;
ArrayList<String> arrays = Helper.splitStr(rece.getMessage(), 3600,
"utf-8");
if (arrays != null && arrays.size() > 0) {
MsgReceive msgRece = null;
for (String msg : arrays) {
msgRece = new MsgReceive();
msgRece.setTaskId(rece.getTaskId());
msgRece.setSerialNo(serialNo);
msgRece.setMessage(msg);
msgReceiveService.saveMsgReceive(msgRece);
serialNo++;
}
}
String userId = "";
String toUserStr = "";
User user = null;
List<ReqTouser> tousers = rece.getJson().getTouser();
if (tousers != null && tousers.size() > 0) {
for (ReqTouser touser : tousers) {
if (!StringUtils.isEmpty(touser.getUserid())) {
userId = touser.getUserid();
toUserStr = toUserStr + "|" + userId;
} else {
if (!StringUtils.isEmpty(touser.getUsername())
&& !StringUtils.isEmpty(touser.getMobile())) {
// 查询出对应的userId
user = userService.getUserByUserNameAndMobile(
touser.getUsername(), touser.getMobile());
if (user != null
&& !StringUtils.isEmpty(user.getUserId())) {
userId = user.getUserId();
toUserStr = toUserStr + "|" + userId;
}
}
}
}
if (!StringUtils.isEmpty(toUserStr)) {
toUserStr = toUserStr.substring(1, toUserStr.length());
}
}
agentId = agentService.getAgentIdByAgentKey(rece.getJson()
.getAgentkey());
logger.info("agentId:" + agentId + "="
+ rece.getJson().getAgentkey());
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put("touser", toUserStr);
jsonMap.put("toparty", "");
jsonMap.put("totag", "");
jsonMap.put("agentid", agentId);
if ("text".equals(rece.getJson().getMsgtype())) {
jsonMap.put("msgtype", "text");
Map<String, Object> text = new HashMap<String, Object>();
text.put("content", rece.getJson().getText().getContent());
jsonMap.put("text", text);
jsonMap.put("safe", 0);
}
if ("news".equals(rece.getJson().getMsgtype())) {
jsonMap.put("msgtype", "news");
Map<String, Object> news = new HashMap<String, Object>();
List<Map<String, Object>> articles = new ArrayList<Map<String, Object>>();
if (rece.getJson().getNews().getArticles() != null
&& rece.getJson().getNews().getArticles().size() > 0) {
Map<String, Object> article = null;
for (ReqArticle ra : rece.getJson().getNews().getArticles()) {
article = new HashMap<String, Object>();
article.put("title", ra.getTitle());
article.put("description", ra.getDescription());
if (!StringUtils.isEmpty(ra.getUrl())) {
article.put("url", ra.getUrl());
} else {
if (!StringUtils.isEmpty(ra.getTasktype())) {
String addr = Constants.API_CODE_MAP
.get("CLAIM-NOTIC-DETAIL-URL")
+ "&taskId=" + rece.getTaskId();
logger.info("taskType:" + ra.getTasktype());
logger.info("addr:" + addr);
article.put("url", addr);
if (StringUtils.equals(rece.getJson()
.getAgentkey(), "SURVEY")
&& StringUtils.equals(ra.getTasktype(),
"01")) {
article.put("description",
ra.getDescription()
+ "\n\n点击消息即表示接收任务");
}
}
}
article.put("picurl", ra.getPicurl());
articles.add(article);
}
news.put("articles", articles);
}
jsonMap.put("news", news);
}
ObjectMapper mapper = new ObjectMapper();
String sendJson = mapper.writeValueAsString(jsonMap);
logger.info("sendJson:" + sendJson);
serialNo = 1;
arrays = Helper.splitStr(sendJson, 3600, "utf-8");
if (arrays != null && arrays.size() > 0) {
MsgSend send = null;
for (String msg : arrays) {
send = new MsgSend();
send.setTaskId(rece.getTaskId());
send.setSerialNo(serialNo);
send.setMessage(msg);
msgSendService.saveMsgSend(send);
serialNo++;
}
}
MsgTask task = new MsgTask();
task.setUserId(userId);
task.setTaskId(rece.getTaskId());
task.setUserCode(rece.getJson().getHead().getApiuser());
task.setAgentKey(rece.getJson().getAgentkey());
msgTaskService.saveMsgTask(task);
if ("SURVEY".equals(rece.getJson().getAgentkey())) {
SurveyInfo info = new SurveyInfo();
info.setUserId(userId);
info.setTaskId(rece.getTaskId());
info.setSurveyTitle(rece.getJson().getNews().getArticles()
.get(0).getTitle());
info.setSurveyContent(rece.getJson().getNews().getArticles()
.get(0).getDescription());
info.setSurveyType(rece.getJson().getNews().getArticles()
.get(0).getTasktype());
info.setCreateBy(rece.getJson().getHead().getApiuser());
info.setOperateBy(rece.getJson().getHead().getApiuser());
info.setResultBack(Constants.INIT_STATUS);
surveyInfoService.saveSurveyInfo(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 13,837 | java | MessageServiceImpl.java | Java | [] | null | [] | package com.hoperun.api.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hoperun.api.entity.ApiUser;
import com.hoperun.api.entity.MsgReceive;
import com.hoperun.api.entity.MsgResult;
import com.hoperun.api.entity.MsgSend;
import com.hoperun.api.entity.MsgTask;
import com.hoperun.api.entity.SurveyInfo;
import com.hoperun.api.entity.User;
import com.hoperun.api.service.AgentService;
import com.hoperun.api.service.ApiUserService;
import com.hoperun.api.service.MessageService;
import com.hoperun.api.service.MsgReceiveService;
import com.hoperun.api.service.MsgResultService;
import com.hoperun.api.service.MsgSendService;
import com.hoperun.api.service.MsgTaskService;
import com.hoperun.api.service.SurveyInfoService;
import com.hoperun.api.service.UserService;
import com.hoperun.api.utils.BackMessage;
import com.hoperun.api.utils.Constants;
import com.hoperun.api.utils.Helper;
import com.hoperun.api.utils.MD5;
import com.hoperun.api.vo.DataReceive;
import com.hoperun.api.vo.DataResult;
import com.hoperun.api.vo.ReqArticle;
import com.hoperun.api.vo.ReqHead;
import com.hoperun.api.vo.ReqJson;
import com.hoperun.api.vo.ReqNews;
import com.hoperun.api.vo.ReqReceiver;
import com.hoperun.api.vo.ReqSender;
import com.hoperun.api.vo.ReqText;
import com.hoperun.api.vo.ReqTouser;
@Service
public class MessageServiceImpl implements MessageService {
@Autowired
private UserService userService;
@Autowired
private AgentService agentService;
@Autowired
private ApiUserService apiUserService;
@Autowired
private MsgTaskService msgTaskService;
@Autowired
private MsgReceiveService msgReceiveService;
@Autowired
private MsgSendService msgSendService;
@Autowired
private MsgResultService msgResultService;
@Autowired
private SurveyInfoService surveyInfoService;
private static final Logger logger = LoggerFactory
.getLogger(MessageServiceImpl.class);
public String executeReceiveMessage(String message) {
String uuid = Helper.getUUID();
String busiid = "000000000000000000";
try {
if (StringUtils.isEmpty(message)) {
return BackMessage.resultJson(-4001, busiid);
}
ObjectMapper mapper = new ObjectMapper();
ReqJson json = mapper.readValue(message, ReqJson.class);
if (json == null) {
return BackMessage.resultJson(-4001, busiid);
}
ReqHead head = json.getHead();
if (head == null) {
return BackMessage.resultJson(-4002, busiid);
}
String apiuser = head.getApiuser();
if (StringUtils.isEmpty(apiuser)) {
return BackMessage.resultJson(-4003, busiid);
}
String apipass = head.getApipass();
if (StringUtils.isEmpty(apipass)) {
return BackMessage.resultJson(-4004, busiid);
}
MD5 md5 = new MD5();
ApiUser apiUser = apiUserService.getAipUserbyUserCode(apiuser);
if (apiUser == null
|| !StringUtils
.equals(md5.getMD5ofStr(apipass).toLowerCase(),
apiUser.getPassword().toLowerCase())) {
return BackMessage.resultJson(-4016, busiid);
}
String agentkey = json.getAgentkey();
if (StringUtils.isEmpty(agentkey)) {
return BackMessage.resultJson(-4008, busiid);
}
// 非客服类消息校验;
if (!"QIYEKEFU".equals(agentkey)) {
List<ReqTouser> tousers = json.getTouser();
if (tousers == null || tousers.size() == 0) {
return BackMessage.resultJson(-4005, busiid);
}
for (ReqTouser touser : tousers) {
if (StringUtils.isEmpty(touser.getUserid())
&& (StringUtils.isEmpty(touser.getUsername()) || StringUtils
.isEmpty(touser.getMobile()))) {
return BackMessage.resultJson(-4006, uuid);
}
}
} else {
// 客服消息专属校验
ReqSender sender = json.getSender();
if (sender == null) {
return BackMessage.resultJson(-4018, busiid);
}
String senderType = sender.getType();
if (StringUtils.isEmpty(senderType)) {
return BackMessage.resultJson(-4019, busiid);
}
String senderId = sender.getId();
if (StringUtils.isEmpty(senderId)) {
return BackMessage.resultJson(-4020, busiid);
}
ReqReceiver receiver = json.getReceiver();
if (receiver == null) {
return BackMessage.resultJson(-4021, busiid);
}
String receiverType = receiver.getType();
if (StringUtils.isEmpty(receiverType)) {
return BackMessage.resultJson(-4022, busiid);
}
String receiverId = receiver.getId();
if (StringUtils.isEmpty(receiverId)) {
return BackMessage.resultJson(-4023, busiid);
}
}
String msgtype = json.getMsgtype();
if (StringUtils.isEmpty(msgtype)) {
return BackMessage.resultJson(-4009, busiid);
}
if (!"text".equals(msgtype) && !"news".equals(msgtype)) {
return BackMessage.resultJson(-4010, busiid);
}
if ("text".equals(msgtype)) {
ReqText text = json.getText();
if (text == null) {
return BackMessage.resultJson(-4011, busiid);
}
String content = text.getContent();
if (StringUtils.isEmpty(content)) {
return BackMessage.resultJson(-4012, busiid);
}
}
if ("news".equals(msgtype)) {
ReqNews news = json.getNews();
if (news == null) {
return BackMessage.resultJson(-4013, busiid);
}
List<ReqArticle> articles = news.getArticles();
if (articles == null || articles.size() == 0) {
return BackMessage.resultJson(-4014, busiid);
}
for (ReqArticle article : articles) {
if (StringUtils.isEmpty(article.getTitle())
|| StringUtils.isEmpty(article.getDescription())) {
return BackMessage.resultJson(-4015, busiid);
}
}
}
DataReceive rece = new DataReceive();
rece.setTaskId(uuid);
rece.setMessage(message);
rece.setJson(json);
// 验证完毕;
if (Constants.REQ_JSON_LIST.size() < 2000) {
Constants.REQ_JSON_LIST.add(rece);
} else {
logger.info("OUT-OFF:" + uuid);
}
} catch (Exception e) {
logger.error("接收消息异常:" + e.getMessage());
return BackMessage.resultJson(-4017, busiid);
}
return BackMessage.resultJson(0, uuid);
}
public void executeSendMessage(MsgTask task) {
MsgTask mt = new MsgTask();
String taskId = task.getTaskId();
String agentKey = task.getAgentKey();
try {
String sendMessage = msgSendService.getSendMessage(taskId);
logger.info("sendMessage:" + sendMessage);
String getTokenUrl = Constants.API_CODE_MAP
.get("GET-CORP-TOKEN-URL");
getTokenUrl = getTokenUrl + "?agentKey=" + agentKey;
logger.info("getTokenUrl:" + getTokenUrl);
String accessToken = Helper.doGet(getTokenUrl, "utf-8");
String sendMsgUrl = Constants.API_CODE_MAP.get("DOMAIN-NAME")
+ "/cgi-bin/message/send?access_token=" + accessToken;
logger.info("sendMsgUrl:" + sendMsgUrl);
String back = Helper.doPost(sendMsgUrl, sendMessage, "utf-8");
logger.info("back:" + back);
if (!StringUtils.isEmpty(back) && back.startsWith("{")) {
String errorMsg = "";
ObjectMapper mapper = new ObjectMapper();
DataResult result = mapper.readValue(back, DataResult.class);
mt.setTaskId(taskId);
mt.setStatus(Constants.OVER_STATUS);
mt.setErrorCode(result.getErrcode());
// 将英文说明转化为中文对照;
errorMsg = Constants.API_CODE_MAP.get(mt.getErrorCode());
errorMsg = StringUtils.isEmpty(errorMsg) ? result.getErrmsg()
: errorMsg;
mt.setErrorMsg(errorMsg);
int serialNo = 1;
ArrayList<String> arrays = Helper.splitStr(back, 3600, "utf-8");
if (arrays != null && arrays.size() > 0) {
MsgResult rlt = new MsgResult();
rlt.setTaskId(taskId);
rlt.setStatus(Constants.INIT_STATUS);
msgResultService.modifyMsgResult(rlt);
for (String msg : arrays) {
rlt = new MsgResult();
rlt.setTaskId(taskId);
rlt.setSerialNo(serialNo);
rlt.setMessage(msg);
msgResultService.saveMsgResult(rlt);
serialNo++;
}
}
} else {
mt.setTaskId(taskId);
mt.setStatus(Constants.OVER_STATUS);
mt.setErrorCode("-9999");
mt.setErrorMsg("企业号自定义:腾讯返回结果为空!");
}
} catch (Exception e) {
e.printStackTrace();
logger.error("执行消息发送异常:" + e.getMessage());
mt.setTaskId(taskId);
mt.setStatus(Constants.OVER_STATUS);
mt.setErrorCode("-9999");
mt.setErrorMsg("系统异常");
}
msgTaskService.modifyMsgTask(mt);
}
public void executeSaveTask(DataReceive rece) {
try {
logger.info("taskId:" + rece.getTaskId());
logger.info("jsonMessage:" + rece.getMessage());
int serialNo = 1;
Long agentId = null;
ArrayList<String> arrays = Helper.splitStr(rece.getMessage(), 3600,
"utf-8");
if (arrays != null && arrays.size() > 0) {
MsgReceive msgRece = null;
for (String msg : arrays) {
msgRece = new MsgReceive();
msgRece.setTaskId(rece.getTaskId());
msgRece.setSerialNo(serialNo);
msgRece.setMessage(msg);
msgReceiveService.saveMsgReceive(msgRece);
serialNo++;
}
}
String userId = "";
String toUserStr = "";
User user = null;
List<ReqTouser> tousers = rece.getJson().getTouser();
if (tousers != null && tousers.size() > 0) {
for (ReqTouser touser : tousers) {
if (!StringUtils.isEmpty(touser.getUserid())) {
userId = touser.getUserid();
toUserStr = toUserStr + "|" + userId;
} else {
if (!StringUtils.isEmpty(touser.getUsername())
&& !StringUtils.isEmpty(touser.getMobile())) {
// 查询出对应的userId
user = userService.getUserByUserNameAndMobile(
touser.getUsername(), touser.getMobile());
if (user != null
&& !StringUtils.isEmpty(user.getUserId())) {
userId = user.getUserId();
toUserStr = toUserStr + "|" + userId;
}
}
}
}
if (!StringUtils.isEmpty(toUserStr)) {
toUserStr = toUserStr.substring(1, toUserStr.length());
}
}
agentId = agentService.getAgentIdByAgentKey(rece.getJson()
.getAgentkey());
logger.info("agentId:" + agentId + "="
+ rece.getJson().getAgentkey());
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put("touser", toUserStr);
jsonMap.put("toparty", "");
jsonMap.put("totag", "");
jsonMap.put("agentid", agentId);
if ("text".equals(rece.getJson().getMsgtype())) {
jsonMap.put("msgtype", "text");
Map<String, Object> text = new HashMap<String, Object>();
text.put("content", rece.getJson().getText().getContent());
jsonMap.put("text", text);
jsonMap.put("safe", 0);
}
if ("news".equals(rece.getJson().getMsgtype())) {
jsonMap.put("msgtype", "news");
Map<String, Object> news = new HashMap<String, Object>();
List<Map<String, Object>> articles = new ArrayList<Map<String, Object>>();
if (rece.getJson().getNews().getArticles() != null
&& rece.getJson().getNews().getArticles().size() > 0) {
Map<String, Object> article = null;
for (ReqArticle ra : rece.getJson().getNews().getArticles()) {
article = new HashMap<String, Object>();
article.put("title", ra.getTitle());
article.put("description", ra.getDescription());
if (!StringUtils.isEmpty(ra.getUrl())) {
article.put("url", ra.getUrl());
} else {
if (!StringUtils.isEmpty(ra.getTasktype())) {
String addr = Constants.API_CODE_MAP
.get("CLAIM-NOTIC-DETAIL-URL")
+ "&taskId=" + rece.getTaskId();
logger.info("taskType:" + ra.getTasktype());
logger.info("addr:" + addr);
article.put("url", addr);
if (StringUtils.equals(rece.getJson()
.getAgentkey(), "SURVEY")
&& StringUtils.equals(ra.getTasktype(),
"01")) {
article.put("description",
ra.getDescription()
+ "\n\n点击消息即表示接收任务");
}
}
}
article.put("picurl", ra.getPicurl());
articles.add(article);
}
news.put("articles", articles);
}
jsonMap.put("news", news);
}
ObjectMapper mapper = new ObjectMapper();
String sendJson = mapper.writeValueAsString(jsonMap);
logger.info("sendJson:" + sendJson);
serialNo = 1;
arrays = Helper.splitStr(sendJson, 3600, "utf-8");
if (arrays != null && arrays.size() > 0) {
MsgSend send = null;
for (String msg : arrays) {
send = new MsgSend();
send.setTaskId(rece.getTaskId());
send.setSerialNo(serialNo);
send.setMessage(msg);
msgSendService.saveMsgSend(send);
serialNo++;
}
}
MsgTask task = new MsgTask();
task.setUserId(userId);
task.setTaskId(rece.getTaskId());
task.setUserCode(rece.getJson().getHead().getApiuser());
task.setAgentKey(rece.getJson().getAgentkey());
msgTaskService.saveMsgTask(task);
if ("SURVEY".equals(rece.getJson().getAgentkey())) {
SurveyInfo info = new SurveyInfo();
info.setUserId(userId);
info.setTaskId(rece.getTaskId());
info.setSurveyTitle(rece.getJson().getNews().getArticles()
.get(0).getTitle());
info.setSurveyContent(rece.getJson().getNews().getArticles()
.get(0).getDescription());
info.setSurveyType(rece.getJson().getNews().getArticles()
.get(0).getTasktype());
info.setCreateBy(rece.getJson().getHead().getApiuser());
info.setOperateBy(rece.getJson().getHead().getApiuser());
info.setResultBack(Constants.INIT_STATUS);
surveyInfoService.saveSurveyInfo(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 13,837 | 0.663787 | 0.651709 | 480 | 27.460417 | 20.525961 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.59375 | false | false | 8 |
40860a114712f4045c58bf85a55c9e71b653df5c | 29,042,568,870,228 | 471a6511c91a87111aac30d9e1d0cf44812af6a2 | /src/main/java/org/codelibs/fess/es/cbean/cf/UserCF.java | 125864549ea941d697a87c11182ea8d7d7c94da6 | [
"Apache-2.0"
] | permissive | beavis28/fess | https://github.com/beavis28/fess | 1160e8a66de4805ee235d1ce64f409f8247bf737 | 8dbc3e9b77c93fe270ff15210dfe3000cc3c9d8c | refs/heads/master | 2020-12-11T07:39:26.254000 | 2015-10-11T06:51:14 | 2015-10-11T06:51:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.codelibs.fess.es.cbean.cf;
import org.codelibs.fess.es.cbean.cf.bs.BsUserCF;
/**
* @author FreeGen
*/
public class UserCF extends BsUserCF {
}
| UTF-8 | Java | 159 | java | UserCF.java | Java | [
{
"context": "libs.fess.es.cbean.cf.bs.BsUserCF;\n\n/**\n * @author FreeGen\n */\npublic class UserCF extends BsUserCF {\n}\n",
"end": 113,
"score": 0.9995011687278748,
"start": 106,
"tag": "USERNAME",
"value": "FreeGen"
}
] | null | [] | package org.codelibs.fess.es.cbean.cf;
import org.codelibs.fess.es.cbean.cf.bs.BsUserCF;
/**
* @author FreeGen
*/
public class UserCF extends BsUserCF {
}
| 159 | 0.72956 | 0.72956 | 9 | 16.666666 | 18.654758 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 8 |
aa6d9964a8c4035e591a7f64d0d0b152c6014810 | 21,741,124,488,631 | 8e23d9fc57c848edfe58412646247aea902ef4af | /src/com/platymuus/lolsim/players/Summoner.java | ed6b593bc2cc32d5c798a0116503e5de09911585 | [] | no_license | SpaceManiac/LeagueSimulator | https://github.com/SpaceManiac/LeagueSimulator | 6d5809fb13f5d1ce6db73c694fc3310d50d4139c | 6df6ce972cf5f10d3ff8a6f83f9828dbed0d8fe6 | refs/heads/master | 2021-01-01T18:12:13.341000 | 2012-12-25T02:37:16 | 2012-12-25T02:37:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.platymuus.lolsim.players;
import com.platymuus.lolsim.SimRandom;
import java.util.HashMap;
/**
* Represents persistent data about an individual Summoner.
*/
public class Summoner {
/**
* The summoner's name.
*/
private String name;
/**
* The players preffered class, ex. Tank, Passive Support, Jungle ect.
*/
private String affinity;
/**
* Summoner Level.
*/
private int level;
/**
* The player's general skill at video games.
*/
private int skill;
/**
* The skill a player gets as he learns how the game works.
*/
private int learnedSkill = 0;
/**
* Map from champion name and number played to how good a player is at said champion.
*/
private final HashMap<String, Integer> champs = new HashMap<String, Integer>();
/**
* The amount a play is online between never(0) and 24/7(1).
*/
private double activity;
/**
* The number of games played and learned from.
*/
private int gamesPlayed;
/**
* The map of per-queue information on this summoner.
*/
private final HashMap<String, QueueInfo> queueInfo = new HashMap<String, QueueInfo>();
private int logoffs;
private int logons;
/**
* Construct a new summoner.
*/
public Summoner() {
activity = calculateActivity();
skill = 1 + (int) (Math.random() * 100);
name = SimRandom.generateName();
}
/**
* Get this Summoner's name.
*
* @return The name.
*/
public String getName() {
return name;
}
/**
* Calculate the total individual skill score of this summoner.
*
* @return The score.
*/
public int score() {
return skill + learnedSkill + (int) (Math.random() * 100);
}
public int getSkill() {
return skill;
}
public int getLearnedSkill() {
return learnedSkill;
}
/**
* Is used whevever a player wins or loses a game to determine how much they learned from that game
*/
public void learn() {
gamesPlayed += 1;
learnedSkill += (int) (3 * Math.pow(Math.E, -.002 * Math.E * gamesPlayed));
}
/**
* Get the Elo rating for this summoner in a given queue.
*
* @param queue The queue id.
* @return The Elo rating.
*/
public int getElo(String queue) {
return queueInfo(queue).elo;
}
/**
* Set the Elo rating for this summoner in a given queue.
*
* @param queue The queue id.
* @param elo The Elo rating.
*/
public void setElo(String queue, int elo) {
queueInfo(queue).elo = elo;
}
/**
* Get the win count for this summoner in a given queue.
*
* @param queue The queue id.
* @return The number of wins.
*/
public int getWon(String queue) {
return queueInfo(queue).won;
}
/**
* Set the win count for this summoner in a given queue.
*
* @param queue The queue id.
* @param won The number of wins.
*/
public void setWon(String queue, int won) {
queueInfo(queue).won = won;
}
/**
* Get the loss count for this summoner in a given queue.
*
* @param queue The queue id.
* @return The number of losses.
*/
public int getLost(String queue) {
return queueInfo(queue).lost;
}
/**
* Set the loss count for this summoner in a given queue.
*
* @param queue The queue id.
* @param lost The number of losses.
*/
public void setLost(String queue, int lost) {
queueInfo(queue).lost = lost;
}
/**
* Add a logon to the summoner's statistics.
*/
public void addLogon() {
logons++;
}
/**
* Add a logoff to the summoner's statistics.
*/
public void addLogoff() {
logoffs++;
}
/**
* Returns a summoner's preference weight for a given queue.
*
* @param queue The queue id.
* @return The preference weight.
*/
public int getWeight(String queue) {
return queueInfo(queue).weight;
}
/**
* Set a summoner's preference weight for a given queue.
*
* @param queue The queue id.
* @param weight The preference weight.
*/
public void setWeight(String queue, int weight) {
queueInfo(queue).weight = weight;
}
/**
* Return often this summoner is online.
*
* @return A value from 0.0 to 1.0 indicating how much of the time the summoner is online.
*/
public double getActivity() {
return activity;
}
/**
* Calculates a players activity between 1 and 0
*
* @return activity
*/
private double calculateActivity() {
double random = Math.random();
if (random < .05) {
return Math.pow(Math.E, -60 * random);
} else if (random < .95) {
return Math.sin(Math.sqrt(random) * Math.PI / 180);
} else {
return -Math.pow(random - .8585779, 2) + .02 + 2.104e-7;
}
}
/**
* Create or get a QueueInfo structure for a queue.
*
* @param queue The queue id.
* @return The existing or created QueueInfo.
*/
private QueueInfo queueInfo(String queue) {
if (!queueInfo.containsKey(queue)) {
queueInfo.put(queue, new QueueInfo());
}
return queueInfo.get(queue);
}
/**
* A storage structure for per-queue data.
*/
private class QueueInfo {
public int elo = 1200;
public int won = 0;
public int lost = 0;
public int weight = 1;
}
}
| UTF-8 | Java | 5,716 | java | Summoner.java | Java | [] | null | [] | package com.platymuus.lolsim.players;
import com.platymuus.lolsim.SimRandom;
import java.util.HashMap;
/**
* Represents persistent data about an individual Summoner.
*/
public class Summoner {
/**
* The summoner's name.
*/
private String name;
/**
* The players preffered class, ex. Tank, Passive Support, Jungle ect.
*/
private String affinity;
/**
* Summoner Level.
*/
private int level;
/**
* The player's general skill at video games.
*/
private int skill;
/**
* The skill a player gets as he learns how the game works.
*/
private int learnedSkill = 0;
/**
* Map from champion name and number played to how good a player is at said champion.
*/
private final HashMap<String, Integer> champs = new HashMap<String, Integer>();
/**
* The amount a play is online between never(0) and 24/7(1).
*/
private double activity;
/**
* The number of games played and learned from.
*/
private int gamesPlayed;
/**
* The map of per-queue information on this summoner.
*/
private final HashMap<String, QueueInfo> queueInfo = new HashMap<String, QueueInfo>();
private int logoffs;
private int logons;
/**
* Construct a new summoner.
*/
public Summoner() {
activity = calculateActivity();
skill = 1 + (int) (Math.random() * 100);
name = SimRandom.generateName();
}
/**
* Get this Summoner's name.
*
* @return The name.
*/
public String getName() {
return name;
}
/**
* Calculate the total individual skill score of this summoner.
*
* @return The score.
*/
public int score() {
return skill + learnedSkill + (int) (Math.random() * 100);
}
public int getSkill() {
return skill;
}
public int getLearnedSkill() {
return learnedSkill;
}
/**
* Is used whevever a player wins or loses a game to determine how much they learned from that game
*/
public void learn() {
gamesPlayed += 1;
learnedSkill += (int) (3 * Math.pow(Math.E, -.002 * Math.E * gamesPlayed));
}
/**
* Get the Elo rating for this summoner in a given queue.
*
* @param queue The queue id.
* @return The Elo rating.
*/
public int getElo(String queue) {
return queueInfo(queue).elo;
}
/**
* Set the Elo rating for this summoner in a given queue.
*
* @param queue The queue id.
* @param elo The Elo rating.
*/
public void setElo(String queue, int elo) {
queueInfo(queue).elo = elo;
}
/**
* Get the win count for this summoner in a given queue.
*
* @param queue The queue id.
* @return The number of wins.
*/
public int getWon(String queue) {
return queueInfo(queue).won;
}
/**
* Set the win count for this summoner in a given queue.
*
* @param queue The queue id.
* @param won The number of wins.
*/
public void setWon(String queue, int won) {
queueInfo(queue).won = won;
}
/**
* Get the loss count for this summoner in a given queue.
*
* @param queue The queue id.
* @return The number of losses.
*/
public int getLost(String queue) {
return queueInfo(queue).lost;
}
/**
* Set the loss count for this summoner in a given queue.
*
* @param queue The queue id.
* @param lost The number of losses.
*/
public void setLost(String queue, int lost) {
queueInfo(queue).lost = lost;
}
/**
* Add a logon to the summoner's statistics.
*/
public void addLogon() {
logons++;
}
/**
* Add a logoff to the summoner's statistics.
*/
public void addLogoff() {
logoffs++;
}
/**
* Returns a summoner's preference weight for a given queue.
*
* @param queue The queue id.
* @return The preference weight.
*/
public int getWeight(String queue) {
return queueInfo(queue).weight;
}
/**
* Set a summoner's preference weight for a given queue.
*
* @param queue The queue id.
* @param weight The preference weight.
*/
public void setWeight(String queue, int weight) {
queueInfo(queue).weight = weight;
}
/**
* Return often this summoner is online.
*
* @return A value from 0.0 to 1.0 indicating how much of the time the summoner is online.
*/
public double getActivity() {
return activity;
}
/**
* Calculates a players activity between 1 and 0
*
* @return activity
*/
private double calculateActivity() {
double random = Math.random();
if (random < .05) {
return Math.pow(Math.E, -60 * random);
} else if (random < .95) {
return Math.sin(Math.sqrt(random) * Math.PI / 180);
} else {
return -Math.pow(random - .8585779, 2) + .02 + 2.104e-7;
}
}
/**
* Create or get a QueueInfo structure for a queue.
*
* @param queue The queue id.
* @return The existing or created QueueInfo.
*/
private QueueInfo queueInfo(String queue) {
if (!queueInfo.containsKey(queue)) {
queueInfo.put(queue, new QueueInfo());
}
return queueInfo.get(queue);
}
/**
* A storage structure for per-queue data.
*/
private class QueueInfo {
public int elo = 1200;
public int won = 0;
public int lost = 0;
public int weight = 1;
}
}
| 5,716 | 0.564906 | 0.555283 | 246 | 22.235773 | 21.985428 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.239837 | false | false | 8 |
aed1fa2f802cb311ff99c4a2e5b725e83034956c | 9,208,409,933,244 | f947db54370ae2bbc3c00f8e71b5f1ad168809e8 | /GND_JAX/src/gnd_jax/GND/PoPs.java | d6f62570567c6dc139a308f6dc7eaa37e9953ba0 | [] | no_license | GeneralizedNuclearData/exampleCodes | https://github.com/GeneralizedNuclearData/exampleCodes | 7c6797b923c27505f4f1bfb280db238cd6067b02 | 0016155bb4619fc6e962708cdabde0eee4331f4e | refs/heads/master | 2020-12-30T11:59:09.141000 | 2017-05-17T11:37:34 | 2017-05-17T11:37:34 | 91,461,578 | 1 | 0 | null | false | 2017-05-17T11:37:35 | 2017-05-16T13:28:15 | 2017-05-16T13:39:50 | 2017-05-17T11:37:35 | 1,434 | 0 | 0 | 0 | Java | null | null | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.04.27 at 11:31:49 AM PDT
//
package gnd_jax.GND;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="aliases" type="{}aliases" minOccurs="0"/>
* <element name="gaugeBosons" type="{}gaugeBosons" minOccurs="0"/>
* <element name="leptons" type="{}leptons" minOccurs="0"/>
* <element name="baryons" type="{}baryons" minOccurs="0"/>
* <element name="chemicalElements" type="{}chemicalElements" minOccurs="0"/>
* </sequence>
* <attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="version" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="format" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"aliases",
"gaugeBosons",
"leptons",
"baryons",
"chemicalElements"
})
@XmlRootElement(name = "PoPs")
public class PoPs {
protected Aliases aliases;
protected GaugeBosons gaugeBosons;
protected Leptons leptons;
protected Baryons baryons;
protected ChemicalElements chemicalElements;
@XmlAttribute(name = "name", required = true)
protected String name;
@XmlAttribute(name = "version", required = true)
protected String version;
@XmlAttribute(name = "format", required = true)
protected String format;
/**
* Gets the value of the aliases property.
*
* @return
* possible object is
* {@link Aliases }
*
*/
public Aliases getAliases() {
return aliases;
}
/**
* Sets the value of the aliases property.
*
* @param value
* allowed object is
* {@link Aliases }
*
*/
public void setAliases(Aliases value) {
this.aliases = value;
}
/**
* Gets the value of the gaugeBosons property.
*
* @return
* possible object is
* {@link GaugeBosons }
*
*/
public GaugeBosons getGaugeBosons() {
return gaugeBosons;
}
/**
* Sets the value of the gaugeBosons property.
*
* @param value
* allowed object is
* {@link GaugeBosons }
*
*/
public void setGaugeBosons(GaugeBosons value) {
this.gaugeBosons = value;
}
/**
* Gets the value of the leptons property.
*
* @return
* possible object is
* {@link Leptons }
*
*/
public Leptons getLeptons() {
return leptons;
}
/**
* Sets the value of the leptons property.
*
* @param value
* allowed object is
* {@link Leptons }
*
*/
public void setLeptons(Leptons value) {
this.leptons = value;
}
/**
* Gets the value of the baryons property.
*
* @return
* possible object is
* {@link Baryons }
*
*/
public Baryons getBaryons() {
return baryons;
}
/**
* Sets the value of the baryons property.
*
* @param value
* allowed object is
* {@link Baryons }
*
*/
public void setBaryons(Baryons value) {
this.baryons = value;
}
/**
* Gets the value of the chemicalElements property.
*
* @return
* possible object is
* {@link ChemicalElements }
*
*/
public ChemicalElements getChemicalElements() {
return chemicalElements;
}
/**
* Sets the value of the chemicalElements property.
*
* @param value
* allowed object is
* {@link ChemicalElements }
*
*/
public void setChemicalElements(ChemicalElements value) {
this.chemicalElements = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersion() {
return version;
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersion(String value) {
this.version = value;
}
/**
* Gets the value of the format property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFormat() {
return format;
}
/**
* Sets the value of the format property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFormat(String value) {
this.format = value;
}
}
| UTF-8 | Java | 6,147 | java | PoPs.java | Java | [] | null | [] | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.04.27 at 11:31:49 AM PDT
//
package gnd_jax.GND;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="aliases" type="{}aliases" minOccurs="0"/>
* <element name="gaugeBosons" type="{}gaugeBosons" minOccurs="0"/>
* <element name="leptons" type="{}leptons" minOccurs="0"/>
* <element name="baryons" type="{}baryons" minOccurs="0"/>
* <element name="chemicalElements" type="{}chemicalElements" minOccurs="0"/>
* </sequence>
* <attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="version" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="format" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"aliases",
"gaugeBosons",
"leptons",
"baryons",
"chemicalElements"
})
@XmlRootElement(name = "PoPs")
public class PoPs {
protected Aliases aliases;
protected GaugeBosons gaugeBosons;
protected Leptons leptons;
protected Baryons baryons;
protected ChemicalElements chemicalElements;
@XmlAttribute(name = "name", required = true)
protected String name;
@XmlAttribute(name = "version", required = true)
protected String version;
@XmlAttribute(name = "format", required = true)
protected String format;
/**
* Gets the value of the aliases property.
*
* @return
* possible object is
* {@link Aliases }
*
*/
public Aliases getAliases() {
return aliases;
}
/**
* Sets the value of the aliases property.
*
* @param value
* allowed object is
* {@link Aliases }
*
*/
public void setAliases(Aliases value) {
this.aliases = value;
}
/**
* Gets the value of the gaugeBosons property.
*
* @return
* possible object is
* {@link GaugeBosons }
*
*/
public GaugeBosons getGaugeBosons() {
return gaugeBosons;
}
/**
* Sets the value of the gaugeBosons property.
*
* @param value
* allowed object is
* {@link GaugeBosons }
*
*/
public void setGaugeBosons(GaugeBosons value) {
this.gaugeBosons = value;
}
/**
* Gets the value of the leptons property.
*
* @return
* possible object is
* {@link Leptons }
*
*/
public Leptons getLeptons() {
return leptons;
}
/**
* Sets the value of the leptons property.
*
* @param value
* allowed object is
* {@link Leptons }
*
*/
public void setLeptons(Leptons value) {
this.leptons = value;
}
/**
* Gets the value of the baryons property.
*
* @return
* possible object is
* {@link Baryons }
*
*/
public Baryons getBaryons() {
return baryons;
}
/**
* Sets the value of the baryons property.
*
* @param value
* allowed object is
* {@link Baryons }
*
*/
public void setBaryons(Baryons value) {
this.baryons = value;
}
/**
* Gets the value of the chemicalElements property.
*
* @return
* possible object is
* {@link ChemicalElements }
*
*/
public ChemicalElements getChemicalElements() {
return chemicalElements;
}
/**
* Sets the value of the chemicalElements property.
*
* @param value
* allowed object is
* {@link ChemicalElements }
*
*/
public void setChemicalElements(ChemicalElements value) {
this.chemicalElements = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersion() {
return version;
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersion(String value) {
this.version = value;
}
/**
* Gets the value of the format property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFormat() {
return format;
}
/**
* Sets the value of the format property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFormat(String value) {
this.format = value;
}
}
| 6,147 | 0.55767 | 0.549211 | 259 | 22.733591 | 21.478786 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.212355 | false | false | 8 |
2c83d93cecd423461f58b169267cc787cf0b1d5b | 7,146,825,606,367 | 33d7b1569a478551c0d729e2bdd52e935ba9b74f | /PackageTest/src/my/Okay.java | 9faee8f01717ff773799be661f31c073c55ec3f8 | [] | no_license | psuu0007/AppJavaAvdClass | https://github.com/psuu0007/AppJavaAvdClass | b3e305cec79d444fe4a912bbfdf7a561a1e3ee01 | 57683ca9c014f294e81cf7cedc322463d28a91c2 | refs/heads/master | 2022-12-20T23:20:53.591000 | 2020-06-11T09:32:42 | 2020-06-23T03:01:09 | 239,939,344 | 12 | 4 | null | false | 2022-12-16T12:14:14 | 2020-02-12T06:04:53 | 2022-10-25T23:14:45 | 2022-12-16T12:14:11 | 11,212 | 5 | 4 | 5 | Java | false | false | package my;
public class Okay {
}
| UTF-8 | Java | 41 | java | Okay.java | Java | [] | null | [] | package my;
public class Okay {
}
| 41 | 0.585366 | 0.585366 | 5 | 6.2 | 7.62627 | 19 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 8 |
09784dd8f0664f0a4ef945710672bac000f01848 | 13,640,816,184,384 | 9159c6f20fe08ad7992a4cd044fc3206398f7c58 | /corejava/src/com/tyss/javaapp/thread/Pro7Callable.java | cc6f9d4715eeb10a20416f4a4710174338a77a04 | [] | no_license | bhavanar315/ELF-06June19-tyss-bhavani | https://github.com/bhavanar315/ELF-06June19-tyss-bhavani | 91def5b909f567536d04e69c9bb6193503398a04 | e2ee506ee99e0e958fb72e3bdaaf6e3315b84975 | refs/heads/master | 2020-07-21T07:45:19.944000 | 2019-09-06T07:43:42 | 2019-09-06T07:43:42 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tyss.javaapp.thread;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import lombok.extern.java.Log;
@Log
public class Pro7Callable {
public static void main(String[] args) {
Pro7Pencil p=new Pro7Pencil();
FutureTask<Integer> ft =new FutureTask<Integer>(p);
Thread t1=new Thread(ft);
t1.start();
try {
int i=ft.get();
log.info(""+i);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 542 | java | Pro7Callable.java | Java | [] | null | [] | package com.tyss.javaapp.thread;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import lombok.extern.java.Log;
@Log
public class Pro7Callable {
public static void main(String[] args) {
Pro7Pencil p=new Pro7Pencil();
FutureTask<Integer> ft =new FutureTask<Integer>(p);
Thread t1=new Thread(ft);
t1.start();
try {
int i=ft.get();
log.info(""+i);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
| 542 | 0.693727 | 0.684502 | 26 | 19.846153 | 16.176174 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.846154 | false | false | 8 |
e7c4f62a9729b2190feb3aedf2a36d0620bc076b | 29,214,367,610,114 | 511b11358b678d61f9ea03f1f47deae86f241383 | /PS1/atfaust2/Anagram.java | 6dac10bd3f012f1fca2badcba52257ea38fbfaae | [] | no_license | vasharm2/Homework | https://github.com/vasharm2/Homework | a9a04d36794400627a024882c41344d3771963a1 | cb9ff936c4e7ab0d01c5b0d2045265afe5520118 | refs/heads/master | 2021-01-18T12:44:56.356000 | 2015-12-02T02:03:23 | 2015-12-02T02:03:23 | 43,036,226 | 0 | 0 | null | true | 2015-09-24T01:05:33 | 2015-09-24T01:05:30 | 2015-09-16T20:28:08 | 2015-09-23T23:21:52 | 537 | 0 | 0 | 0 | null | null | null | import java.util.*;
import java.io.*;
/*
************************************************
____ ____ _ ___ __
/ ___/ ___| / |/ _ \ / /_
| | \___ \ | | (_) | '_ \
| |___ ___) | | |\__, | (_) |
\____|____/ |_| /_/ \___/
Problem set 1
Question 1
A common problem in computer science is finding patterns within data.
This problem will simulate that in a way that is easy to see what is happening.
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward.
Allowances may be made for adjustments to capital letters, punctuation, and word dividers.
an anagram is a word, phrase, or name formed by rearranging the letters of another.
Given a String S, determine if it is an anagram of a palindrome.
Return true if the String is an anagram of a palindrome, and false otherwise.
For example, the String “oatrtro” will return true (rotator), while the String “false” will return false.
PLEASE LOOK AT PS1.txt FOR MORE DETAILS!!!
************************************************
*/
public class Anagram {
/*
* This is a simple contains class for Arrays
*/
public static boolean contains(char[] list,char c)
{
for(char ch:list)
{
if(ch == c)
{
return true;
}
}
return false;
}
/*
* This is a simple index of class for an array
*/
public static int indexOf(char[] list,char c)
{
int counter = 0;
for(char ch:list)
{
if(ch == c)
{
return counter;
}
counter ++;
}
return -1;
}
/*
* This is a method that counts the number of nonzero terms in
* an array
*/
public static int nonZeroTerms(char[] list)
{
int counter = 0;
for(char c:list)
{
if(c != 0)
{
counter ++;
}
}
return counter;
}
/*
* This program checks to see if something is an anagram. This is
* done by putting the word into an array of characters and going through term
* by term to see if there are duplicates. If there are then both are set to zero.
* For any anagram this will leave us with 1 or 0 nonzero terms which we check at the end
* whfdwfh -- 000d000 -- is an anagram
*/
public static boolean anagram(String input) {
//takes input and makes it an array of all lowercase chars
input.toLowerCase();
char[] word = input.toCharArray();
int counter = 0;
for(char c:word)
{
if(c != 0)
{
word[counter] = 0;
if(contains(word,c))
word[indexOf(word,c)] = 0;
else
{
word[counter] = c;
}
counter++;
}
}
for(char c:word)
{
System.out.println((int)c);
}
if(nonZeroTerms(word) == 0 || nonZeroTerms(word) == 1)
{
return true;
}
return false;
}
public static void main(String[] args) {
File file = new File("Anagram.txt");
try {
Scanner scan = new Scanner(file);
int numberOfCases = scan.nextInt();
for(int i = 0; i < numberOfCases; i++) {
String input = scan.next();
System.out.println(anagram(input));
}
scan.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} | UTF-8 | Java | 3,089 | java | Anagram.java | Java | [] | null | [] | import java.util.*;
import java.io.*;
/*
************************************************
____ ____ _ ___ __
/ ___/ ___| / |/ _ \ / /_
| | \___ \ | | (_) | '_ \
| |___ ___) | | |\__, | (_) |
\____|____/ |_| /_/ \___/
Problem set 1
Question 1
A common problem in computer science is finding patterns within data.
This problem will simulate that in a way that is easy to see what is happening.
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward.
Allowances may be made for adjustments to capital letters, punctuation, and word dividers.
an anagram is a word, phrase, or name formed by rearranging the letters of another.
Given a String S, determine if it is an anagram of a palindrome.
Return true if the String is an anagram of a palindrome, and false otherwise.
For example, the String “oatrtro” will return true (rotator), while the String “false” will return false.
PLEASE LOOK AT PS1.txt FOR MORE DETAILS!!!
************************************************
*/
public class Anagram {
/*
* This is a simple contains class for Arrays
*/
public static boolean contains(char[] list,char c)
{
for(char ch:list)
{
if(ch == c)
{
return true;
}
}
return false;
}
/*
* This is a simple index of class for an array
*/
public static int indexOf(char[] list,char c)
{
int counter = 0;
for(char ch:list)
{
if(ch == c)
{
return counter;
}
counter ++;
}
return -1;
}
/*
* This is a method that counts the number of nonzero terms in
* an array
*/
public static int nonZeroTerms(char[] list)
{
int counter = 0;
for(char c:list)
{
if(c != 0)
{
counter ++;
}
}
return counter;
}
/*
* This program checks to see if something is an anagram. This is
* done by putting the word into an array of characters and going through term
* by term to see if there are duplicates. If there are then both are set to zero.
* For any anagram this will leave us with 1 or 0 nonzero terms which we check at the end
* whfdwfh -- 000d000 -- is an anagram
*/
public static boolean anagram(String input) {
//takes input and makes it an array of all lowercase chars
input.toLowerCase();
char[] word = input.toCharArray();
int counter = 0;
for(char c:word)
{
if(c != 0)
{
word[counter] = 0;
if(contains(word,c))
word[indexOf(word,c)] = 0;
else
{
word[counter] = c;
}
counter++;
}
}
for(char c:word)
{
System.out.println((int)c);
}
if(nonZeroTerms(word) == 0 || nonZeroTerms(word) == 1)
{
return true;
}
return false;
}
public static void main(String[] args) {
File file = new File("Anagram.txt");
try {
Scanner scan = new Scanner(file);
int numberOfCases = scan.nextInt();
for(int i = 0; i < numberOfCases; i++) {
String input = scan.next();
System.out.println(anagram(input));
}
scan.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} | 3,089 | 0.592075 | 0.58493 | 139 | 21.158274 | 24.880508 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.007194 | false | false | 8 |
5728909340730c7e7d490e0e33732b07eab30195 | 19,430,432,101,152 | f6064d912ad477e86dfd82249236d4433c45cce6 | /parent/interface/src/main/java/com/it/core/service/SellerService.java | b9e42a09b0ccedbf80698ce85bbeffbe26a95bc0 | [] | no_license | yujiawei1313/PYG | https://github.com/yujiawei1313/PYG | 9037894305affc2e8e9d67ded10692633f23df9f | d11d35e4e4cd30dec5d8af378756fde78947ae39 | refs/heads/master | 2022-12-22T19:40:24.054000 | 2019-12-11T14:23:28 | 2019-12-11T14:23:28 | 227,380,929 | 0 | 0 | null | false | 2022-12-16T07:16:03 | 2019-12-11T14:09:12 | 2019-12-11T14:34:35 | 2022-12-16T07:16:00 | 13,187 | 0 | 0 | 12 | JavaScript | false | false | package com.it.core.service;
import com.it.core.pojo.entity.PageResult;
import com.it.core.pojo.seller.Seller;
import org.springframework.web.bind.annotation.RequestBody;
public interface SellerService {
public void add(Seller seller);
public PageResult findPage(Seller seller, Integer page, Integer rows);
public Seller findOne(String id);
public void updateStatus(String sellerId, String status);
}
| UTF-8 | Java | 423 | java | SellerService.java | Java | [] | null | [] | package com.it.core.service;
import com.it.core.pojo.entity.PageResult;
import com.it.core.pojo.seller.Seller;
import org.springframework.web.bind.annotation.RequestBody;
public interface SellerService {
public void add(Seller seller);
public PageResult findPage(Seller seller, Integer page, Integer rows);
public Seller findOne(String id);
public void updateStatus(String sellerId, String status);
}
| 423 | 0.77305 | 0.77305 | 16 | 25.4375 | 24.919794 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6875 | false | false | 8 |
84a0f4b41d54ff10ec7bde97785e3f0ed30c321c | 24,816,321,076,185 | 1e67de689ad293179a90c9675938a3d1546f4b39 | /Mis_Proyectos_actuales/src/PaginaCursos/ElAlumnoYaEstaInscritoAlCurso.java | 74b26e86b51776f6b940335bcc4e1896213d4960 | [] | no_license | HernanEzequielAibar/archivos | https://github.com/HernanEzequielAibar/archivos | 58e7c9293ebb9f982d454ce87dbf18f429def170 | 09f8995a6f8b67768bd709121064425ff872dc82 | refs/heads/master | 2023-05-02T18:18:29.971000 | 2021-05-21T13:51:19 | 2021-05-21T13:51:19 | 334,132,346 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package PaginaCursos;
@SuppressWarnings("serial")
public class ElAlumnoYaEstaInscritoAlCurso extends Exception {
}
| UTF-8 | Java | 117 | java | ElAlumnoYaEstaInscritoAlCurso.java | Java | [] | null | [] | package PaginaCursos;
@SuppressWarnings("serial")
public class ElAlumnoYaEstaInscritoAlCurso extends Exception {
}
| 117 | 0.82906 | 0.82906 | 6 | 18.5 | 22.216736 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 8 |
885f28d76297975651eafb8596797f1a270e704f | 3,710,851,774,617 | debb8324b63fbca79dcbdc6d2711ab76ef7906c3 | /src/subset_practice/subset_practice.java | b82289ccdad8d277719fe550997db6c57a0adc22 | [] | no_license | alin2202/class_practice_2015 | https://github.com/alin2202/class_practice_2015 | 6fe5cc02a6511fdea52569cb5c1d820af8b258b2 | 1bf25cbe60ec99c5e451c6b3268705a9b6d3cc25 | refs/heads/master | 2021-01-10T14:28:57.097000 | 2015-10-29T02:35:51 | 2015-10-29T02:35:51 | 43,181,071 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package subset_practice;
import java.util.ArrayList;
public class subset_practice {
public static void main(String[] args) {
int[] intSet = {5, 7, 1, 2};
// int[] set = {5, 7, 13, 14, 3, 17, 9, 3, 11, 20};
// ArrayList<Integer> arraySet = new ArrayList<Integer>();
// for (int i = 0; i < intSet.length; i++){
// arraySet.add(intSet[i]);
// }
int target = 16;
subset_algorithm subsetobj = new subset_algorithm();
// //DEBUG: checking sum function
// int sum = subsetobj.getArrayListSum(arraySet);
ArrayList<Integer> subset = subsetobj.getSubset(intSet, target);
System.out.println(subset);
}
}
| UTF-8 | Java | 654 | java | subset_practice.java | Java | [] | null | [] | package subset_practice;
import java.util.ArrayList;
public class subset_practice {
public static void main(String[] args) {
int[] intSet = {5, 7, 1, 2};
// int[] set = {5, 7, 13, 14, 3, 17, 9, 3, 11, 20};
// ArrayList<Integer> arraySet = new ArrayList<Integer>();
// for (int i = 0; i < intSet.length; i++){
// arraySet.add(intSet[i]);
// }
int target = 16;
subset_algorithm subsetobj = new subset_algorithm();
// //DEBUG: checking sum function
// int sum = subsetobj.getArrayListSum(arraySet);
ArrayList<Integer> subset = subsetobj.getSubset(intSet, target);
System.out.println(subset);
}
}
| 654 | 0.619266 | 0.585627 | 25 | 24.16 | 21.353558 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.44 | false | false | 8 |
becc28515c50b56fbfb9b9bc0ae32dd4ff8ac51e | 14,860,586,848,423 | b764f8ae820f6a0ef7dee83b5c244c890803fdb6 | /src/main/java/com/tdevilleduc/urthehero/core/service/HelloService.java | 646d974d1f3731d6500d8e7560b144d21797aec9 | [] | no_license | tdevilleduc/urthehero-core | https://github.com/tdevilleduc/urthehero-core | d17fc1bb622a478a8639630fd726b62320963527 | 4223eb58bb3d16d63bae4f3f60f93cf778a78e7c | refs/heads/master | 2020-12-12T12:39:52.271000 | 2020-02-07T18:59:52 | 2020-02-07T18:59:52 | 234,128,617 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tdevilleduc.urthehero.core.service;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.springframework.stereotype.Service;
@Service
public class HelloService {
@ConfigProperty(name = "greeting")
String greeting;
public String politeHello(String name){
return greeting + " " + name;
}
public String hello(String name){
return "Hello " + name;
}
} | UTF-8 | Java | 424 | java | HelloService.java | Java | [] | null | [] | package com.tdevilleduc.urthehero.core.service;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.springframework.stereotype.Service;
@Service
public class HelloService {
@ConfigProperty(name = "greeting")
String greeting;
public String politeHello(String name){
return greeting + " " + name;
}
public String hello(String name){
return "Hello " + name;
}
} | 424 | 0.705189 | 0.705189 | 19 | 21.368422 | 20.008448 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.315789 | false | false | 2 |
c0e0e6fb470483b3069e1b372bb3cc0c832cb895 | 14,336,600,838,921 | 96796dc09fe0a02c2b312f0642f89007f9d4c7c5 | /src/main/java/com/v/bean/Orders.java | 60bb02c40839a4244077b198cb9d588e593a5950 | [
"MIT"
] | permissive | John-Zeng/projectv | https://github.com/John-Zeng/projectv | 631c28a7bcdfc024b7011a9054b1a24b7c6ea0d4 | 674aec4e211fbba7b32bf1e530b2c545ecd09584 | refs/heads/master | 2020-03-23T21:15:48.905000 | 2018-08-01T14:38:48 | 2018-08-01T14:38:48 | 142,093,869 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.v.bean;
import java.util.Date;
import java.util.List;
public class Orders {
private Integer id;
private String oId;
private Date odTime;
private String username;
private String addrId;
private Double total;
private List<Record> records;
private Address address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getoId() {
return oId;
}
public void setoId(String oId) {
this.oId = oId == null ? null : oId.trim();
}
public Date getOdTime() {
return odTime;
}
public void setOdTime(Date odTime) {
this.odTime = odTime;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getAddrId() {
return addrId;
}
public void setAddrId(String addrId) {
this.addrId = addrId == null ? null : addrId.trim();
}
public Double getTotal() {
return total;
}
public void setTotal(Double total) {
this.total = total;
}
public List<Record> getRecords() {
return records;
}
public void setRecords(List<Record> records) {
this.records = records;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Orders [id=" + id + ", oId=" + oId + ", odTime=" + odTime + ", username=" + username + ", addrId="
+ addrId + ", total=" + total + ", address=" + address + "]";
}
} | UTF-8 | Java | 1,800 | java | Orders.java | Java | [
{
"context": "\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String userna",
"end": 796,
"score": 0.9328415989875793,
"start": 788,
"tag": "USERNAME",
"value": "username"
},
{
"context": "d=\" + oId + \", odTime=\" + odTime + \", username=\" + username + \", addrId=\"\n + addrId + \", total",
"end": 1690,
"score": 0.9590420126914978,
"start": 1682,
"tag": "USERNAME",
"value": "username"
}
] | null | [] | package com.v.bean;
import java.util.Date;
import java.util.List;
public class Orders {
private Integer id;
private String oId;
private Date odTime;
private String username;
private String addrId;
private Double total;
private List<Record> records;
private Address address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getoId() {
return oId;
}
public void setoId(String oId) {
this.oId = oId == null ? null : oId.trim();
}
public Date getOdTime() {
return odTime;
}
public void setOdTime(Date odTime) {
this.odTime = odTime;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getAddrId() {
return addrId;
}
public void setAddrId(String addrId) {
this.addrId = addrId == null ? null : addrId.trim();
}
public Double getTotal() {
return total;
}
public void setTotal(Double total) {
this.total = total;
}
public List<Record> getRecords() {
return records;
}
public void setRecords(List<Record> records) {
this.records = records;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Orders [id=" + id + ", oId=" + oId + ", odTime=" + odTime + ", username=" + username + ", addrId="
+ addrId + ", total=" + total + ", address=" + address + "]";
}
} | 1,800 | 0.561667 | 0.561667 | 94 | 18.159575 | 19.884401 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.361702 | false | false | 2 |
6ecc5c0cd69a9330ff9f58fdbd65f092997201ef | 17,815,524,363,019 | 8d3c54983e1e57e166b0e946baeda38e2b7aeb15 | /jnpf-system/jnpf-system-base/jnpf-system-base-entity/src/main/java/jnpf/base/model/dbtable/DbTableUpForm.java | 8a73c7f7df0e9ab90c21bd7a8f046812928336ca | [] | no_license | houzhanwu/lowCodePlatform | https://github.com/houzhanwu/lowCodePlatform | 01d3c6f8fc30eb6dfd6d0beea55c705231fd97a5 | 88c0822c974b129d6c5423fec59d7de9fa907527 | refs/heads/master | 2023-08-30T04:07:23.106000 | 2021-11-17T02:33:20 | 2021-11-17T02:33:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jnpf.base.model.dbtable;
import lombok.Data;
@Data
public class DbTableUpForm extends DbTableCrForm {
}
| UTF-8 | Java | 116 | java | DbTableUpForm.java | Java | [] | null | [] | package jnpf.base.model.dbtable;
import lombok.Data;
@Data
public class DbTableUpForm extends DbTableCrForm {
}
| 116 | 0.784483 | 0.784483 | 9 | 11.888889 | 17.123373 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 2 |
cf740d66dca629f3a0200199433e44d899123bf5 | 6,047,313,994,856 | fe1f2c68a0540195b227ebee1621819766ac073b | /OVO_jdgui/myobfuscated/bpa.java | 11b7866393465b5ed08e8be3f8e82f07d32a4217 | [] | no_license | Sulley01/KPI_4 | https://github.com/Sulley01/KPI_4 | 41d1fd816a3c0b2ab42cff54a4d83c1d536e19d3 | 04ed45324f255746869510f0b201120bbe4785e3 | refs/heads/master | 2020-03-09T05:03:37.279000 | 2018-04-18T16:52:10 | 2018-04-18T16:52:10 | 128,602,787 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package myobfuscated;
public final class bpa
extends bpe
{
public bpa(blv paramblv)
{
super(paramblv);
}
protected final int a(int paramInt)
{
if (paramInt < 10000) {
return paramInt;
}
return paramInt - 10000;
}
protected final void a(StringBuilder paramStringBuilder, int paramInt)
{
if (paramInt < 10000)
{
paramStringBuilder.append("(3202)");
return;
}
paramStringBuilder.append("(3203)");
}
}
/* Location: C:\dex2jar-2.0\classes-dex2jar.jar!\myobfuscated\bpa.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 632 | java | bpa.java | Java | [] | null | [] | package myobfuscated;
public final class bpa
extends bpe
{
public bpa(blv paramblv)
{
super(paramblv);
}
protected final int a(int paramInt)
{
if (paramInt < 10000) {
return paramInt;
}
return paramInt - 10000;
}
protected final void a(StringBuilder paramStringBuilder, int paramInt)
{
if (paramInt < 10000)
{
paramStringBuilder.append("(3202)");
return;
}
paramStringBuilder.append("(3203)");
}
}
/* Location: C:\dex2jar-2.0\classes-dex2jar.jar!\myobfuscated\bpa.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 632 | 0.617089 | 0.563291 | 34 | 17.617647 | 20.033817 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.235294 | false | false | 2 |
351a0dfcc9e7f7908eba11ea26936261e47cef6d | 6,416,681,205,781 | 8e60b11601a6f025a818091b55573de60ba3ded6 | /CyxteraCalculadora/src/java/com/cystera/prueba/api/IdSesionDTO.java | 8058c089d4a7a088346afcb8c3bcd6487d0f21e0 | [] | no_license | tavosg3/PruebaCysteraCalculadora | https://github.com/tavosg3/PruebaCysteraCalculadora | 2203d0aef0b7ba257a536a2b7c8c37b350f4afa3 | cd6cee18e7a8882902570a1047004c5bdedaed3b | refs/heads/master | 2020-06-08T14:21:59.501000 | 2019-06-26T08:32:27 | 2019-06-26T08:32:27 | 193,243,343 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.cystera.prueba.api;
import java.io.Serializable;
/**
*
* @author tavos
*/
public class IdSesionDTO implements Serializable{
private static final long serialVersionUID = 1;
private Integer idSesion;
public Integer getIdSesion() {
return idSesion;
}
public void setIdSesion(Integer idSesion) {
this.idSesion = idSesion;
}
}
| UTF-8 | Java | 603 | java | IdSesionDTO.java | Java | [
{
"context": "mport java.io.Serializable;\r\n\r\n/**\r\n *\r\n * @author tavos\r\n */\r\npublic class IdSesionDTO implements Seriali",
"end": 282,
"score": 0.9995465278625488,
"start": 277,
"tag": "USERNAME",
"value": "tavos"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.cystera.prueba.api;
import java.io.Serializable;
/**
*
* @author tavos
*/
public class IdSesionDTO implements Serializable{
private static final long serialVersionUID = 1;
private Integer idSesion;
public Integer getIdSesion() {
return idSesion;
}
public void setIdSesion(Integer idSesion) {
this.idSesion = idSesion;
}
}
| 603 | 0.658375 | 0.656716 | 27 | 20.333334 | 21.807236 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 2 |
d63476a8a2e1f75f3b1a8500b7dcc66683d22e92 | 4,501,125,795,335 | 008ceaeb273a312865303f7b21c8f90f6f95e97d | /src/main/java/uk/linde/indigo/dashboard/tabs/CylindersTabContent.java | 5fd5bdf46cfe2322eff2988d3265b76ee5cf1125 | [] | no_license | Pryades/liv-iq-insights | https://github.com/Pryades/liv-iq-insights | 67ca4a33936f770906cd1076b95383bb51f6043b | a7118669e6014c0817f56de9c31f24df67179325 | refs/heads/master | 2020-12-24T10:23:54.568000 | 2019-11-08T12:40:45 | 2019-11-08T12:40:45 | 73,088,053 | 0 | 0 | null | false | 2020-10-12T23:18:05 | 2016-11-07T14:46:57 | 2019-11-08T12:42:09 | 2020-10-12T23:18:03 | 15,373 | 0 | 0 | 2 | Java | false | false | package uk.linde.indigo.dashboard.tabs;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import uk.linde.indigo.application.SmartStationFillingsDlg;
import uk.linde.indigo.common.AppContext;
import uk.linde.indigo.common.BaseException;
import uk.linde.indigo.common.DateRange;
import uk.linde.indigo.common.GenericControlerVto;
import uk.linde.indigo.common.ModalParent;
import uk.linde.indigo.common.PagedContent;
import uk.linde.indigo.common.BaseTable;
import uk.linde.indigo.common.PagedTable;
import uk.linde.indigo.dal.BaseManager;
import uk.linde.indigo.dto.BaseDto;
import uk.linde.indigo.dto.Cylinder;
import uk.linde.indigo.dto.Device;
import uk.linde.indigo.dto.Hospital;
import uk.linde.indigo.dto.Parameter;
import uk.linde.indigo.dto.Plant;
import uk.linde.indigo.dto.Query;
import uk.linde.indigo.dto.Region;
import uk.linde.indigo.dto.query.CylinderQuery;
import uk.linde.indigo.dto.query.FillingQuery;
import uk.linde.indigo.ioc.IOCManager;
import uk.linde.indigo.vto.CylinderVto;
import uk.linde.indigo.vto.controlers.CylinderControlerVto;
import com.vaadin.ui.Button;
import com.vaadin.ui.Component;
/**
*
* @author Dismer Ronda
*
*/
public class CylindersTabContent extends PagedContent implements ModalParent
{
private static final long serialVersionUID = 6400815443474805069L;
@Getter @Setter private List<Region> regions;
@Getter @Setter private Plant plant;
@Getter @Setter private Device device;
@Getter @Setter private Hospital hospital;
@Getter @Setter private DateRange dateRange;
private CylindersTab parentWidget;
public CylindersTabContent( AppContext ctx, CylindersTab parentWidget )
{
super( ctx );
this.parentWidget = parentWidget;
setOrderby( "cylinder_serial" );
setOrder( "asc" );
}
@Override
public boolean hasNew()
{
return false;
}
@Override
public boolean hasModify()
{
return false;
}
@Override
public boolean hasDelete()
{
return false;
}
@Override
public String getResourceKey()
{
return "cylindersConfig";
}
@Override
public String[] getVisibleCols()
{
return new String[]{ "cylinder_serial", "gas_type", "size", "plant_name", "device_mac_address", "device_serial", "device_icc", "device_version", "device_ble_version", "device_battery_charge", "filling_count" };
}
@Override
public BaseTable createTable() throws BaseException
{
return new PagedTable( CylinderVto.class, this, getContext(), getContext().getIntegerParameter( Parameter.PAR_DEFAULT_PAGE_SIZE ) );
}
@Override
public Component getQueryComponent()
{
return null;
}
@Override
public Query getQueryObject()
{
CylinderQuery query = new CylinderQuery();
if ( device != null )
query.setRef_device( device.getId() );
if ( plant != null )
query.setRef_plant( plant.getId() );
else
query.setRegions( regions );
if ( hospital != null )
query.setRef_hospital( hospital.getId() );
query.setFrom_date( dateRange.getFrom() );
query.setTo_date( dateRange.getTo() );
query.setValid( parentWidget.getValid().booleanValue() ? true : null );
return query;
}
@Override
public void onOperationNew()
{
}
@Override
public void onOperationModify( BaseDto dto )
{
}
@Override
public void onOperationDelete( BaseDto dto )
{
}
@Override
public GenericControlerVto getControlerVto( AppContext ctx )
{
return new CylinderControlerVto( ctx );
}
@Override
public BaseDto getFieldDto()
{
return new Cylinder();
}
@Override
public BaseManager getFieldManagerImp()
{
return IOCManager._CylindersManager;
}
@Override
public void onSelectedRow()
{
super.onSelectedRow();
//parentWidget.onSelectedFilling( (Long)getTable().getTable().getValue() );
}
@Override
public void preProcessRows( List<BaseDto> rows )
{
}
@Override
public boolean hasAddRight()
{
return false;
}
@Override
public boolean hasModifyRight()
{
return false;
}
@Override
public boolean hasDeleteRight()
{
return false;
}
@Override
public boolean hasDeleteAllRight()
{
return false;
}
@Override
public void updateComponent()
{
}
private void showFillingsDlg( Cylinder cylinder )
{
if ( cylinder.getFilling_count() > 0 )
{
FillingQuery query = new FillingQuery();
query.setFrom_date( dateRange.getFrom() );
query.setTo_date( dateRange.getTo() );
query.setRef_cylinder( cylinder.getId() );
query.setValid( parentWidget.getValid().booleanValue() ? true : null );
if ( plant != null )
query.setRef_plant( plant.getId() );
else
query.setRegions( regions );
if ( hospital != null )
query.setRef_hospital( hospital.getId() );
SmartStationFillingsDlg dlg = new SmartStationFillingsDlg( query );
dlg.setContext( getContext() );
dlg.createComponents();
getUI().addWindow( dlg );
}
}
@Override
public void onFieldEvent( Component component, String column )
{
Button button = (Button)component;
CylinderVto vto = (CylinderVto)button.getData();
Cylinder cylinder = (Cylinder)vto.getDtoObj();
if ( column.equals( "filling_count" ) )
showFillingsDlg( cylinder );
}
}
| UTF-8 | Java | 5,147 | java | CylindersTabContent.java | Java | [
{
"context": "mport com.vaadin.ui.Component;\n\n/**\n * \n * @author Dismer Ronda\n * \n */\npublic class CylindersTabContent extends ",
"end": 1172,
"score": 0.9998642802238464,
"start": 1160,
"tag": "NAME",
"value": "Dismer Ronda"
}
] | null | [] | package uk.linde.indigo.dashboard.tabs;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import uk.linde.indigo.application.SmartStationFillingsDlg;
import uk.linde.indigo.common.AppContext;
import uk.linde.indigo.common.BaseException;
import uk.linde.indigo.common.DateRange;
import uk.linde.indigo.common.GenericControlerVto;
import uk.linde.indigo.common.ModalParent;
import uk.linde.indigo.common.PagedContent;
import uk.linde.indigo.common.BaseTable;
import uk.linde.indigo.common.PagedTable;
import uk.linde.indigo.dal.BaseManager;
import uk.linde.indigo.dto.BaseDto;
import uk.linde.indigo.dto.Cylinder;
import uk.linde.indigo.dto.Device;
import uk.linde.indigo.dto.Hospital;
import uk.linde.indigo.dto.Parameter;
import uk.linde.indigo.dto.Plant;
import uk.linde.indigo.dto.Query;
import uk.linde.indigo.dto.Region;
import uk.linde.indigo.dto.query.CylinderQuery;
import uk.linde.indigo.dto.query.FillingQuery;
import uk.linde.indigo.ioc.IOCManager;
import uk.linde.indigo.vto.CylinderVto;
import uk.linde.indigo.vto.controlers.CylinderControlerVto;
import com.vaadin.ui.Button;
import com.vaadin.ui.Component;
/**
*
* @author <NAME>
*
*/
public class CylindersTabContent extends PagedContent implements ModalParent
{
private static final long serialVersionUID = 6400815443474805069L;
@Getter @Setter private List<Region> regions;
@Getter @Setter private Plant plant;
@Getter @Setter private Device device;
@Getter @Setter private Hospital hospital;
@Getter @Setter private DateRange dateRange;
private CylindersTab parentWidget;
public CylindersTabContent( AppContext ctx, CylindersTab parentWidget )
{
super( ctx );
this.parentWidget = parentWidget;
setOrderby( "cylinder_serial" );
setOrder( "asc" );
}
@Override
public boolean hasNew()
{
return false;
}
@Override
public boolean hasModify()
{
return false;
}
@Override
public boolean hasDelete()
{
return false;
}
@Override
public String getResourceKey()
{
return "cylindersConfig";
}
@Override
public String[] getVisibleCols()
{
return new String[]{ "cylinder_serial", "gas_type", "size", "plant_name", "device_mac_address", "device_serial", "device_icc", "device_version", "device_ble_version", "device_battery_charge", "filling_count" };
}
@Override
public BaseTable createTable() throws BaseException
{
return new PagedTable( CylinderVto.class, this, getContext(), getContext().getIntegerParameter( Parameter.PAR_DEFAULT_PAGE_SIZE ) );
}
@Override
public Component getQueryComponent()
{
return null;
}
@Override
public Query getQueryObject()
{
CylinderQuery query = new CylinderQuery();
if ( device != null )
query.setRef_device( device.getId() );
if ( plant != null )
query.setRef_plant( plant.getId() );
else
query.setRegions( regions );
if ( hospital != null )
query.setRef_hospital( hospital.getId() );
query.setFrom_date( dateRange.getFrom() );
query.setTo_date( dateRange.getTo() );
query.setValid( parentWidget.getValid().booleanValue() ? true : null );
return query;
}
@Override
public void onOperationNew()
{
}
@Override
public void onOperationModify( BaseDto dto )
{
}
@Override
public void onOperationDelete( BaseDto dto )
{
}
@Override
public GenericControlerVto getControlerVto( AppContext ctx )
{
return new CylinderControlerVto( ctx );
}
@Override
public BaseDto getFieldDto()
{
return new Cylinder();
}
@Override
public BaseManager getFieldManagerImp()
{
return IOCManager._CylindersManager;
}
@Override
public void onSelectedRow()
{
super.onSelectedRow();
//parentWidget.onSelectedFilling( (Long)getTable().getTable().getValue() );
}
@Override
public void preProcessRows( List<BaseDto> rows )
{
}
@Override
public boolean hasAddRight()
{
return false;
}
@Override
public boolean hasModifyRight()
{
return false;
}
@Override
public boolean hasDeleteRight()
{
return false;
}
@Override
public boolean hasDeleteAllRight()
{
return false;
}
@Override
public void updateComponent()
{
}
private void showFillingsDlg( Cylinder cylinder )
{
if ( cylinder.getFilling_count() > 0 )
{
FillingQuery query = new FillingQuery();
query.setFrom_date( dateRange.getFrom() );
query.setTo_date( dateRange.getTo() );
query.setRef_cylinder( cylinder.getId() );
query.setValid( parentWidget.getValid().booleanValue() ? true : null );
if ( plant != null )
query.setRef_plant( plant.getId() );
else
query.setRegions( regions );
if ( hospital != null )
query.setRef_hospital( hospital.getId() );
SmartStationFillingsDlg dlg = new SmartStationFillingsDlg( query );
dlg.setContext( getContext() );
dlg.createComponents();
getUI().addWindow( dlg );
}
}
@Override
public void onFieldEvent( Component component, String column )
{
Button button = (Button)component;
CylinderVto vto = (CylinderVto)button.getData();
Cylinder cylinder = (Cylinder)vto.getDtoObj();
if ( column.equals( "filling_count" ) )
showFillingsDlg( cylinder );
}
}
| 5,141 | 0.720808 | 0.716922 | 245 | 20.008163 | 24.297812 | 212 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.526531 | false | false | 2 |
e3b1dc7ce0ed714b9b5311b2e5472382ffed9789 | 4,501,125,795,593 | cb603d78e4658ddbb101ac35667de3af0306096f | /assignment5/src/assignment5/Regex.java | c8e161bbd0056d835dea915c992a8a40b52730bc | [] | no_license | kujiraOo/OOP-Course | https://github.com/kujiraOo/OOP-Course | 17f1c69764c6173154ae210f908c4954e2d78571 | 9e110824e792b324966afdff94d62dd5644b62fa | refs/heads/master | 2021-01-10T07:57:45.790000 | 2016-04-18T10:21:42 | 2016-04-18T10:21:42 | 51,511,473 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package assignment5;
import java.util.Scanner;
public class Regex {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
selectItemToCheck(sc);
}
private static void checkRegex(String message, String regex, Scanner sc) {
String input = "";
System.out.println(message);
input = sc.nextLine();
if (input.matches(regex))
System.out.println("The input matches the regex");
else
System.out.println("The input doesn't match the regex");
System.out.println("Continue checking? y/n");
input = sc.nextLine();
if (input.equals("y"))
checkRegex(message, regex, sc);
}
private static void selectItemToCheck(Scanner sc) {
System.out.println("Please select item to check:"
+ "\n1 - International phone number"
+ "\n2 - Finnish personal identity code"
+ "\n3 - Number less than 1000" + "\n4 - Date"
+ "\nq - To quit");
String input = sc.nextLine();
switch (input) {
// Check phone number
case "1":
String phoneNumCheckMessage = "Please enter a phone number in "
+ "international format to check"
+ "\nFor example +358-40-1345678";
String interPhoneNumRegex = "\\+\\d{1,3}-\\d{1,5}-\\d{4,8}";
checkRegex(phoneNumCheckMessage, interPhoneNumRegex, sc);
selectItemToCheck(sc);
break;
case "2":
// Check Finnish id code
String personalIdCheckMessage = "Please enter Finnish personal identity number to check"
+ "\nFor example 120570-467W";
String personalIdCodeRegex = "\\d{6}-\\d{3}[A-Z]";
checkRegex(personalIdCheckMessage, personalIdCodeRegex, sc);
selectItemToCheck(sc);
break;
case "3":
// Check a number less than 1000
String numberCheckMessage = "Please enter a number less than 1000";
String numberLessThan1000Regex = "0|[1-9]\\d{1,2}|-[1-9]\\d*";
checkRegex(numberCheckMessage, numberLessThan1000Regex, sc);
selectItemToCheck(sc);
break;
case "4":
// Check date, no leap years
String dateCheckMessage = "Please enter date to check,"
+ "\nFor example Jan. 1. 2014";
String dateRegex = "(((Jan|Mar|May|Jul|Aug|Oct|Dec). ([1-9]|[1-2][0-9]|3[0-1]))|"
+ "((Apr|Jun|Sep|Nov). ([1-9]|[1-2][0-9]|30))|"
+ "Feb. ([1-9]|1[0-9]|2[0-9]))" + ". [1-2]\\d{1,3}";
checkRegex(dateCheckMessage, dateRegex, sc);
selectItemToCheck(sc);
break;
case "q":
System.out.println("Quitting the program...");
break;
default:
selectItemToCheck(sc);
}
}
}
| UTF-8 | Java | 2,441 | java | Regex.java | Java | [] | null | [] | package assignment5;
import java.util.Scanner;
public class Regex {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
selectItemToCheck(sc);
}
private static void checkRegex(String message, String regex, Scanner sc) {
String input = "";
System.out.println(message);
input = sc.nextLine();
if (input.matches(regex))
System.out.println("The input matches the regex");
else
System.out.println("The input doesn't match the regex");
System.out.println("Continue checking? y/n");
input = sc.nextLine();
if (input.equals("y"))
checkRegex(message, regex, sc);
}
private static void selectItemToCheck(Scanner sc) {
System.out.println("Please select item to check:"
+ "\n1 - International phone number"
+ "\n2 - Finnish personal identity code"
+ "\n3 - Number less than 1000" + "\n4 - Date"
+ "\nq - To quit");
String input = sc.nextLine();
switch (input) {
// Check phone number
case "1":
String phoneNumCheckMessage = "Please enter a phone number in "
+ "international format to check"
+ "\nFor example +358-40-1345678";
String interPhoneNumRegex = "\\+\\d{1,3}-\\d{1,5}-\\d{4,8}";
checkRegex(phoneNumCheckMessage, interPhoneNumRegex, sc);
selectItemToCheck(sc);
break;
case "2":
// Check Finnish id code
String personalIdCheckMessage = "Please enter Finnish personal identity number to check"
+ "\nFor example 120570-467W";
String personalIdCodeRegex = "\\d{6}-\\d{3}[A-Z]";
checkRegex(personalIdCheckMessage, personalIdCodeRegex, sc);
selectItemToCheck(sc);
break;
case "3":
// Check a number less than 1000
String numberCheckMessage = "Please enter a number less than 1000";
String numberLessThan1000Regex = "0|[1-9]\\d{1,2}|-[1-9]\\d*";
checkRegex(numberCheckMessage, numberLessThan1000Regex, sc);
selectItemToCheck(sc);
break;
case "4":
// Check date, no leap years
String dateCheckMessage = "Please enter date to check,"
+ "\nFor example Jan. 1. 2014";
String dateRegex = "(((Jan|Mar|May|Jul|Aug|Oct|Dec). ([1-9]|[1-2][0-9]|3[0-1]))|"
+ "((Apr|Jun|Sep|Nov). ([1-9]|[1-2][0-9]|30))|"
+ "Feb. ([1-9]|1[0-9]|2[0-9]))" + ". [1-2]\\d{1,3}";
checkRegex(dateCheckMessage, dateRegex, sc);
selectItemToCheck(sc);
break;
case "q":
System.out.println("Quitting the program...");
break;
default:
selectItemToCheck(sc);
}
}
}
| 2,441 | 0.650553 | 0.609996 | 91 | 25.824175 | 23.653912 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.813187 | false | false | 2 |
32518c1c2708921d7126cdd2936f95218e2f9e5b | 28,681,791,672,205 | 6cd12493795d51078c61bebd185ba3b1a56d582c | /CryptMobile/src/Files.java | 0e90157705ff535631b9cc2d0848397736301176 | [] | no_license | mind1master/infomatrix2010 | https://github.com/mind1master/infomatrix2010 | 7ecb45955742660df5524f962d2da02ddb36c813 | 6e40f27e1701f5b0d8efdeb64d7fd2fbf13e81b3 | refs/heads/master | 2021-05-16T02:58:36.555000 | 2012-10-23T10:10:26 | 2012-10-23T10:10:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Random;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextField;
/**
* @author Admin
*/
public class Files extends MIDlet implements CommandListener {
Form frm,waitform;
Display ds;
TextField filename,pass,ok,sk;
Command doit, gen,send,lSend,exit;
Alert a,b;
ChoiceGroup wtd;
Random r;
long p,q,n,f,e,d;
boolean wg=false;
public long QuickPow(long a, long w, long n)
{
//s=a^w mod n; быстрое возведение a в степень w по модулю n
long s = 1, v = w, c = a;
if ((a < 0) || (w < 0))
{
System.out.println("s = "+s+" v = "+v+", c = "+c);
System.out.println("Error QuickPow");
}
while (v != 0)
{
if (v % 2 == 1)
{
s = (s * c) % n;
v = (v - 1) / 2;
}
else v = v / 2;
c = (c * c) % n;
}
return s;
}
public long generateSimple() {
long res;
res=r.nextInt(1000);
//System.out.println(p);
if (res<0) {
res=-res;
}
if (res % 2==0) {
res++;
}
boolean pr=false;
while ( !pr) {
pr=true;
for (int i=3; i<res; i++) {
if (res % i==0) {
pr=false;
}
}
res=res+2;
//System.out.println(p);
}
res=res-2;
//System.out.println(p);
return res;
}
public void generateNumbers () {
p=generateSimple();
q=generateSimple();
//p and q
n=p*q;
f=(p-1)*(q-1);
e=3; // 2^2^n+1
while (f % e==0) {
e++;
}
//long k=r.nextInt()+1;
long k=1;
boolean b;
b=false;
while (!b) {
if ((1+k*f) % e==0) {
b=true;
}
k++;
}
k--;
d=(1+k*f);
d=d/e;
ok.setString(Integer.toString((int) e)+" "+Integer.toString((int) n));
sk.setString(Long.toString(d)+" "+Integer.toString((int) n));
wg=true;
}
public void crypt() throws IOException {
FileConnection fc = null;
if (wg) {
long m=0;
fc = (FileConnection) Connector.open("file:///"+filename.getString());
byte[] b = new byte[(int)fc.fileSize()];
InputStream is= fc.openInputStream();
int l=is.read(b); //size
is.close();
DataOutputStream os = fc.openDataOutputStream();
for (int i=0;i<l;i++) {
long h=QuickPow(b[i], e, n);
os.writeLong(h);
}
os.close();
}
fc.close();
}
public void decrypt() {
FileConnection fc = null;
if (sk.getString()!=(Long.toString(d)+" "+Integer.toString((int) n))) {
StringBuffer tb;
tb= new StringBuffer(sk.getString());
String ts ="";
for (int i=0; i<tb.length(); i++) {
if (tb.charAt(i)!=' ') {
ts+=tb.charAt(i);
} else {
System.out.println(ts);
d=Long.parseLong(ts);
ts="";
}
}
System.out.println(ts);
n=Long.parseLong(ts);
wg=true;
}
if (wg) {
long h=0;
/*String ts="";
StringBuffer sb,ob;
ob = new StringBuffer("");
sb = new StringBuffer(intext.getString()+" "); */
try {
fc = (FileConnection) Connector.open("file:///"+filename.getString());
DataInputStream is = fc.openDataInputStream();
StringBuffer sb= new StringBuffer("");
long l=fc.fileSize()/8;
for (int i=0; i<l; i++) {
h=is.readLong();
long h2=QuickPow(h, d, n);
sb.append((char)h2);
}
is.close();
fc.delete();
fc.create();
OutputStream os = fc.openOutputStream();
for (int i=0; i<sb.length(); i++) {
os.write(sb.charAt(i));
}
os.close();
fc.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void startApp() {
ds=Display.getDisplay(this);
frm=new Form("File crypting");
Enumeration e=FileSystemRegistry.listRoots();
while (e.hasMoreElements())
{
frm.append((String)e.nextElement());
}
filename= new TextField("File path:", "E:/test.png", 255, TextField.ANY);
frm.append(filename);
ok = new TextField("Public key:", "", 50, TextField.ANY);
frm.append(ok);
sk = new TextField("Private key:", "", 50, TextField.ANY);
frm.append(sk);
wtd = new ChoiceGroup("Action: ", List.POPUP);
wtd.append("Encrypting", null);
wtd.append("Decrypting", null);
frm.append(wtd);
doit = new Command("Do it", Command.OK, 0);
frm.setCommandListener(this);
gen = new Command("Generate keys",Command.OK,2);
frm.addCommand(gen);
exit = new Command("Back",Command.BACK,4);
frm.addCommand(exit);
frm.addCommand(doit);
ds.setCurrent(frm);
//doStuff();
r=new Random();
waitform= new Form("Ожидание");
waitform.append("Подождите пожалуйста...");
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
public void commandAction(Command c, Displayable d) {
if (c==doit) {
b= new Alert("Подождите пожалуйста...", "Подождите пожалуйста...", null, AlertType.INFO);
b.setTimeout(Alert.FOREVER);
ds.setCurrent(b);
if (wtd.isSelected(0)) {
try {
crypt();
} catch (IOException ex) {
ex.printStackTrace();
}
} else {
decrypt();
}
a= new Alert("Done", "Done", null, AlertType.INFO);
a.setTimeout(1000);
ds.setCurrent(a);
} else if(c==exit) {
destroyApp(false);
} else if (c==gen) {
generateNumbers();
}
}
} | UTF-8 | Java | 7,633 | java | Files.java | Java | [
{
"context": "vax.microedition.lcdui.TextField;\n\n\n/**\n * @author Admin\n */\npublic class Files extends MIDlet implements ",
"end": 922,
"score": 0.8875449895858765,
"start": 917,
"tag": "NAME",
"value": "Admin"
}
] | null | [] | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Random;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextField;
/**
* @author Admin
*/
public class Files extends MIDlet implements CommandListener {
Form frm,waitform;
Display ds;
TextField filename,pass,ok,sk;
Command doit, gen,send,lSend,exit;
Alert a,b;
ChoiceGroup wtd;
Random r;
long p,q,n,f,e,d;
boolean wg=false;
public long QuickPow(long a, long w, long n)
{
//s=a^w mod n; быстрое возведение a в степень w по модулю n
long s = 1, v = w, c = a;
if ((a < 0) || (w < 0))
{
System.out.println("s = "+s+" v = "+v+", c = "+c);
System.out.println("Error QuickPow");
}
while (v != 0)
{
if (v % 2 == 1)
{
s = (s * c) % n;
v = (v - 1) / 2;
}
else v = v / 2;
c = (c * c) % n;
}
return s;
}
public long generateSimple() {
long res;
res=r.nextInt(1000);
//System.out.println(p);
if (res<0) {
res=-res;
}
if (res % 2==0) {
res++;
}
boolean pr=false;
while ( !pr) {
pr=true;
for (int i=3; i<res; i++) {
if (res % i==0) {
pr=false;
}
}
res=res+2;
//System.out.println(p);
}
res=res-2;
//System.out.println(p);
return res;
}
public void generateNumbers () {
p=generateSimple();
q=generateSimple();
//p and q
n=p*q;
f=(p-1)*(q-1);
e=3; // 2^2^n+1
while (f % e==0) {
e++;
}
//long k=r.nextInt()+1;
long k=1;
boolean b;
b=false;
while (!b) {
if ((1+k*f) % e==0) {
b=true;
}
k++;
}
k--;
d=(1+k*f);
d=d/e;
ok.setString(Integer.toString((int) e)+" "+Integer.toString((int) n));
sk.setString(Long.toString(d)+" "+Integer.toString((int) n));
wg=true;
}
public void crypt() throws IOException {
FileConnection fc = null;
if (wg) {
long m=0;
fc = (FileConnection) Connector.open("file:///"+filename.getString());
byte[] b = new byte[(int)fc.fileSize()];
InputStream is= fc.openInputStream();
int l=is.read(b); //size
is.close();
DataOutputStream os = fc.openDataOutputStream();
for (int i=0;i<l;i++) {
long h=QuickPow(b[i], e, n);
os.writeLong(h);
}
os.close();
}
fc.close();
}
public void decrypt() {
FileConnection fc = null;
if (sk.getString()!=(Long.toString(d)+" "+Integer.toString((int) n))) {
StringBuffer tb;
tb= new StringBuffer(sk.getString());
String ts ="";
for (int i=0; i<tb.length(); i++) {
if (tb.charAt(i)!=' ') {
ts+=tb.charAt(i);
} else {
System.out.println(ts);
d=Long.parseLong(ts);
ts="";
}
}
System.out.println(ts);
n=Long.parseLong(ts);
wg=true;
}
if (wg) {
long h=0;
/*String ts="";
StringBuffer sb,ob;
ob = new StringBuffer("");
sb = new StringBuffer(intext.getString()+" "); */
try {
fc = (FileConnection) Connector.open("file:///"+filename.getString());
DataInputStream is = fc.openDataInputStream();
StringBuffer sb= new StringBuffer("");
long l=fc.fileSize()/8;
for (int i=0; i<l; i++) {
h=is.readLong();
long h2=QuickPow(h, d, n);
sb.append((char)h2);
}
is.close();
fc.delete();
fc.create();
OutputStream os = fc.openOutputStream();
for (int i=0; i<sb.length(); i++) {
os.write(sb.charAt(i));
}
os.close();
fc.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void startApp() {
ds=Display.getDisplay(this);
frm=new Form("File crypting");
Enumeration e=FileSystemRegistry.listRoots();
while (e.hasMoreElements())
{
frm.append((String)e.nextElement());
}
filename= new TextField("File path:", "E:/test.png", 255, TextField.ANY);
frm.append(filename);
ok = new TextField("Public key:", "", 50, TextField.ANY);
frm.append(ok);
sk = new TextField("Private key:", "", 50, TextField.ANY);
frm.append(sk);
wtd = new ChoiceGroup("Action: ", List.POPUP);
wtd.append("Encrypting", null);
wtd.append("Decrypting", null);
frm.append(wtd);
doit = new Command("Do it", Command.OK, 0);
frm.setCommandListener(this);
gen = new Command("Generate keys",Command.OK,2);
frm.addCommand(gen);
exit = new Command("Back",Command.BACK,4);
frm.addCommand(exit);
frm.addCommand(doit);
ds.setCurrent(frm);
//doStuff();
r=new Random();
waitform= new Form("Ожидание");
waitform.append("Подождите пожалуйста...");
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
public void commandAction(Command c, Displayable d) {
if (c==doit) {
b= new Alert("Подождите пожалуйста...", "Подождите пожалуйста...", null, AlertType.INFO);
b.setTimeout(Alert.FOREVER);
ds.setCurrent(b);
if (wtd.isSelected(0)) {
try {
crypt();
} catch (IOException ex) {
ex.printStackTrace();
}
} else {
decrypt();
}
a= new Alert("Done", "Done", null, AlertType.INFO);
a.setTimeout(1000);
ds.setCurrent(a);
} else if(c==exit) {
destroyApp(false);
} else if (c==gen) {
generateNumbers();
}
}
} | 7,633 | 0.473656 | 0.466224 | 306 | 23.627451 | 19.737619 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.699346 | false | false | 2 |
5d8e4c75ecc7e11881ad8e5f9e21a56718c6f9fe | 6,562,710,065,143 | 4e390e1d3ee8db4277d7e86c74e67730a3583a1b | /components/fade_components_sources/component-1/fade/src/test/java/org/realityforge/fade/TestConstantPool.java | 237bd9a035508fd310d95a16da940277d5fb4ed1 | [] | no_license | WasteService/WasteService.github.io | https://github.com/WasteService/WasteService.github.io | 6dd28b9673895dc53c00bfee751a0378d684813a | fefe1185e6c7a53806f28e759f5104904a80db01 | refs/heads/master | 2023-01-05T09:56:28.057000 | 2020-10-28T10:13:53 | 2020-10-28T10:13:53 | 307,663,150 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.realityforge.fade;
import java.io.IOException;
import java.io.InputStream;
import junit.framework.TestCase;
public class TestConstantPool
extends TestCase
{
public void test_readClassData_initVars_EmptyClass()
throws Exception
{
final byte[] bytes = loadTestData( "EmptyClass.class.dat" );
final ConstantPool constantPool = ConstantPool.parseConstantPool( bytes );
assertEquals( "data", bytes, constantPool.data );
final int count = 16;
assertEquals( "offsets.length", constantPool.offsets.length, count );
assertEquals( "strings.length", constantPool.strings.length, count );
for( int i = 0; i < count; i++ )
{
assertNull( "strings[" + i + "]", constantPool.strings[i] );
}
}
public void test_getEntryType_tooLow_EmptyClass()
throws Exception
{
try
{
getEmptyClassData().getEntryType( 0 );
fail( "Expected to get an IllegalArgumentException when accessing 0th entry" );
}
catch( final ClassFormatError cfe )
{
final String message =
"Can not access constant pool element 0 as it is not in the range [1-16)";
assertEquals( "getMessage()", message, cfe.getMessage() );
}
}
public void test_getEntryType_tooHigh_EmptyClass()
throws Exception
{
try
{
getEmptyClassData().getEntryType( 16 );
fail( "Expected to get an IllegalArgumentException when accessing 16th entry" );
}
catch( final ClassFormatError cfe )
{
final String message =
"Can not access constant pool element 16 as it is not in the range [1-16)";
assertEquals( "getMessage()", message, cfe.getMessage() );
}
}
public void test_getClassHeaderOffset_EmptyClass()
throws Exception
{
assertEquals( "getClassHeaderOffset()", 226, getEmptyClassData().getClassHeaderOffset() );
}
public void test_getConstantCount_EmptyClass()
throws Exception
{
assertEquals( "getConstantCount()", 15, getEmptyClassData().getConstantCount() );
}
public void test_getUtfEntry_EmptyClass()
throws Exception
{
final ConstantPool constantPool = getEmptyClassData();
final String value = constantPool.getUtfEntry( 6 );
assertEquals( "getUtfEntry( 6 )", "Code", value );
assertEquals( "strings[6] post get", value, constantPool.strings[6] );
//Verify that regetting will get cached value
assertEquals( "getUtfEntry( 6 )", value, constantPool.getUtfEntry( 6 ) );
assertTrue( "strings[6] identical", value == constantPool.strings[6] );
}
public void test_getClassEntry_EmptyClass()
throws Exception
{
final ConstantPool constantPool = getEmptyClassData();
final String value = constantPool.getClassEntry( 2 );
assertEquals( "getClassEntry( 2 )", "org/realityforge/fade/data/EmptyClass", value );
assertEquals( "strings[2] post get", value, constantPool.strings[2] );
assertEquals( "strings[14] post get", value, constantPool.strings[14] );
assertTrue( "strings[2] == strings[14]", constantPool.strings[2] == constantPool.strings[14] );
// Verify using cached value
assertEquals( "getClassEntry( 2 )", value, constantPool.getClassEntry( 2 ) );
assertTrue( "strings[2] identical", value == constantPool.strings[2] );
assertTrue( "strings[14] identical", value == constantPool.strings[14] );
}
public void test_getEntryType_EmptyClass()
throws Exception
{
assertEquals( "getUtfEntry( 13 )", getEmptyClassData().getEntryType( 13 ), ClassFileFormat.CONSTANT_NameAndType );
}
public void test_getNameFromNameAndType_MethodRef_EmptyClass()
throws Exception
{
final ConstantPool constantPool = getEmptyClassData();
final String value = "<init>";
assertEquals( "getNameFromNameAndType( 13 )", constantPool.getNameFromNameAndType( 13 ), value );
assertEquals( "strings[4] post get", value, constantPool.strings[4] );
}
public void test_getTypeFromNameAndType_MethodRef_EmptyClass()
throws Exception
{
final ConstantPool constantPool = getEmptyClassData();
final String value = "()V";
assertEquals( "getTypeFromNameAndType( 13 )", constantPool.getTypeFromNameAndType( 13 ), value );
assertEquals( "strings[5] post get", value, constantPool.strings[5] );
}
public void test_getClassFromRef_MethodRef_EmptyClass()
throws Exception
{
final ConstantPool constantPool = getEmptyClassData();
final String value = "java/lang/Object";
assertEquals( "getClassFromRef( 1 )", constantPool.getClassFromRef( 1 ), value );
assertEquals( "strings[15] post get", value, constantPool.strings[15] );
}
public void test_getNameFromRef_EmptyClass()
throws Exception
{
final ConstantPool constantPool = getEmptyClassData();
final String value = "<init>";
assertEquals( "getNameFromRef( 1 )", constantPool.getNameFromRef( 1 ), value );
assertEquals( "strings[4] post get", value, constantPool.strings[4] );
}
public void test_getTypeFromRef_EmptyClass()
throws Exception
{
final ConstantPool constantPool = getEmptyClassData();
final String value = "()V";
assertEquals( "getTypeFromRef( 1 )", constantPool.getTypeFromRef( 1 ), value );
assertEquals( "strings[5] post get", value, constantPool.strings[5] );
}
public void test_getFloatEntry_NonEmptyClass()
throws Exception
{
assertEquals( "getFloatEntry( 4 )", 32.5F, getNonEmptyClassData().getFloatEntry( 4 ), 0.0 );
}
public void test_getDoubleEntry_NonEmptyClass()
throws Exception
{
assertEquals( "getDoubleEntry( 7 )", 55.0D, getNonEmptyClassData().getDoubleEntry( 7 ), 0.0 );
}
public void test_getIntegerEntry_NonEmptyClass()
throws Exception
{
assertEquals( "getIntegerEntry( 22 )", 42, getNonEmptyClassData().getIntegerEntry( 22 ) );
}
public void test_getLongEntry_NonEmptyClass()
throws Exception
{
assertEquals( "getLongEntry( 5 )", 3L, getNonEmptyClassData().getLongEntry( 5 ) );
}
public void test_getStringEntry_NonEmptyClass()
throws Exception
{
final ConstantPool constantPool = getNonEmptyClassData();
final String value = constantPool.getStringEntry( 2 );
assertEquals( "getStringEntry( 2 )", "What is 6 x 9 in base 13?", value );
assertEquals( "strings[2] post get", value, constantPool.strings[2] );
assertTrue( "strings[2] identical", value == constantPool.getStringEntry( 2 ) );
assertTrue( "strings[2] identical", value == constantPool.strings[2] );
}
public void test_getNameFromRef_FieldRef_NonEmptyClass()
throws Exception
{
final ConstantPool constantPool = getNonEmptyClassData();
final String value = "m_question";
assertEquals( "getNameFromRef( 3 )", constantPool.getNameFromRef( 3 ), value );
assertEquals( "strings[23] post get", value, constantPool.strings[23] );
}
public void test_getTypeFromRef_FieldRef_NonEmptyClass()
throws Exception
{
final ConstantPool constantPool = getNonEmptyClassData();
final String value = "Ljava/lang/String;";
assertEquals( "getTypeFromRef( 3 )", value, constantPool.getTypeFromRef( 3 ) );
assertEquals( "strings[24] post get", value, constantPool.strings[24] );
}
public void test_getClassFromRef_FieldRef_NonEmptyClass()
throws Exception
{
final ConstantPool constantPool = getNonEmptyClassData();
final String value = "org/realityforge/fade/data/NonEmptyClass";
assertEquals( "getClassFromRef( 3 )", value, constantPool.getClassFromRef( 3 ) );
assertEquals( "strings[16] post get", value, constantPool.strings[16] );
}
public void test_getNameFromRef_InterfaceMethodRef_NonEmptyClass()
throws Exception
{
final ConstantPool constantPool = getNonEmptyClassData();
final String value = "runJumpSkipAndPlay";
assertEquals( "getNameFromRef( 9 )", value, constantPool.getNameFromRef( 9 ) );
assertEquals( "strings[56] post get", value, constantPool.strings[56] );
}
public void test_getTypeFromRef_InterfaceMethodRef_NonEmptyClass()
throws Exception
{
final ConstantPool constantPool = getNonEmptyClassData();
final String value = "()V";
assertEquals( "getTypeFromRef( 9 )", value, constantPool.getTypeFromRef( 9 ) );
assertEquals( "strings[57] post get", value, constantPool.strings[57] );
}
public void test_getClassFromRef_InterfaceMethod_NonEmptyClass()
throws Exception
{
final ConstantPool constantPool = getNonEmptyClassData();
final String value = "org/realityforge/fade/data/MyInterface";
assertEquals( "getClassFromRef( 9 )", value, constantPool.getClassFromRef( 9 ) );
assertEquals( "strings[18] post get", value, constantPool.strings[18] );
}
public void test_attempt_getTypeFromNameAndType_onNonRef_NonEmptyClass()
throws Exception
{
try
{
getNonEmptyClassData().getTypeFromRef( 2 );
fail( "Expected to get an exception" );
}
catch( final ClassFormatError cfe )
{
final String message =
"Unexpected type for constant pool element 2. Expected a ref type but got 8 at position 15";
assertEquals( "getMessage()", message, cfe.getMessage() );
}
}
public void test_attempt_getStringEntry_onNonString_NonEmptyClass()
throws Exception
{
try
{
getNonEmptyClassData().getStringEntry( 1 );
}
catch( final ClassFormatError cfe )
{
final String message =
"Unexpected type for constant pool element 1. Expected: 8 Actual: 10 at position 10";
assertEquals( "getMessage()", message, cfe.getMessage() );
}
}
public void test_parseUtfString()
throws Exception
{
final byte[] data = new byte[]{0, 6, 'a', (byte)0xCF, (byte)0x8F, (byte)0xEF, (byte)0x8F, (byte)0x80};
final String value = ConstantPool.parseUtfString( data, 0, 0 );
assertEquals( "value.length", 3, value.length() );
assertEquals( "value.charAt( 0 )", 'a', value.charAt( 0 ) );
assertEquals( "value.charAt( 1 )", 975, value.charAt( 1 ) );
assertEquals( "value.charAt( 2 )", 62400, value.charAt( 2 ) );
}
public void test_parseConstantPool_with_truncation()
{
try
{
final byte[] data = new byte[10];
data[8]= 2;
data[9]= 0;
ConstantPool.parseConstantPool( data );
fail( "Expected exception" );
}
catch( final ClassFormatError cfe )
{
final String message = "Class file truncated when parsing constant pool at position 10";
assertEquals( "getMessage()", message, cfe.getMessage() );
}
}
public void test_parseConstantPool_with_unkown_tag()
{
try
{
final byte[] data = new byte[11];
data[8]= 1;
data[9]= 0;
data[10]= 42;
ConstantPool.parseConstantPool( data );
fail( "Expected exception" );
}
catch( final ClassFormatError cfe )
{
final String message = "Bad constant pool tag 42 at position 10";
assertEquals( "getMessage()", message, cfe.getMessage() );
}
}
private ConstantPool getEmptyClassData()
throws Exception
{
final byte[] bytes = loadTestData( "EmptyClass.class.dat" );
return ConstantPool.parseConstantPool( bytes );
}
private ConstantPool getNonEmptyClassData()
throws Exception
{
final byte[] bytes = loadTestData( "NonEmptyClass.class.dat" );
return ConstantPool.parseConstantPool( bytes );
}
private byte[] loadTestData( final String resource )
throws IOException
{
final InputStream input = TestConstantPool.class.getResourceAsStream( resource );
assertNotNull( "Seemingly missing test data: " + resource, input );
final int size = input.available();
final byte[] bytes = new byte[size];
final int count = input.read( bytes );
assertEquals( "Unable to fully read testdata for: " + resource, count, size );
return bytes;
}
}
| UTF-8 | Java | 11,833 | java | TestConstantPool.java | Java | [] | null | [] | package org.realityforge.fade;
import java.io.IOException;
import java.io.InputStream;
import junit.framework.TestCase;
public class TestConstantPool
extends TestCase
{
public void test_readClassData_initVars_EmptyClass()
throws Exception
{
final byte[] bytes = loadTestData( "EmptyClass.class.dat" );
final ConstantPool constantPool = ConstantPool.parseConstantPool( bytes );
assertEquals( "data", bytes, constantPool.data );
final int count = 16;
assertEquals( "offsets.length", constantPool.offsets.length, count );
assertEquals( "strings.length", constantPool.strings.length, count );
for( int i = 0; i < count; i++ )
{
assertNull( "strings[" + i + "]", constantPool.strings[i] );
}
}
public void test_getEntryType_tooLow_EmptyClass()
throws Exception
{
try
{
getEmptyClassData().getEntryType( 0 );
fail( "Expected to get an IllegalArgumentException when accessing 0th entry" );
}
catch( final ClassFormatError cfe )
{
final String message =
"Can not access constant pool element 0 as it is not in the range [1-16)";
assertEquals( "getMessage()", message, cfe.getMessage() );
}
}
public void test_getEntryType_tooHigh_EmptyClass()
throws Exception
{
try
{
getEmptyClassData().getEntryType( 16 );
fail( "Expected to get an IllegalArgumentException when accessing 16th entry" );
}
catch( final ClassFormatError cfe )
{
final String message =
"Can not access constant pool element 16 as it is not in the range [1-16)";
assertEquals( "getMessage()", message, cfe.getMessage() );
}
}
public void test_getClassHeaderOffset_EmptyClass()
throws Exception
{
assertEquals( "getClassHeaderOffset()", 226, getEmptyClassData().getClassHeaderOffset() );
}
public void test_getConstantCount_EmptyClass()
throws Exception
{
assertEquals( "getConstantCount()", 15, getEmptyClassData().getConstantCount() );
}
public void test_getUtfEntry_EmptyClass()
throws Exception
{
final ConstantPool constantPool = getEmptyClassData();
final String value = constantPool.getUtfEntry( 6 );
assertEquals( "getUtfEntry( 6 )", "Code", value );
assertEquals( "strings[6] post get", value, constantPool.strings[6] );
//Verify that regetting will get cached value
assertEquals( "getUtfEntry( 6 )", value, constantPool.getUtfEntry( 6 ) );
assertTrue( "strings[6] identical", value == constantPool.strings[6] );
}
public void test_getClassEntry_EmptyClass()
throws Exception
{
final ConstantPool constantPool = getEmptyClassData();
final String value = constantPool.getClassEntry( 2 );
assertEquals( "getClassEntry( 2 )", "org/realityforge/fade/data/EmptyClass", value );
assertEquals( "strings[2] post get", value, constantPool.strings[2] );
assertEquals( "strings[14] post get", value, constantPool.strings[14] );
assertTrue( "strings[2] == strings[14]", constantPool.strings[2] == constantPool.strings[14] );
// Verify using cached value
assertEquals( "getClassEntry( 2 )", value, constantPool.getClassEntry( 2 ) );
assertTrue( "strings[2] identical", value == constantPool.strings[2] );
assertTrue( "strings[14] identical", value == constantPool.strings[14] );
}
public void test_getEntryType_EmptyClass()
throws Exception
{
assertEquals( "getUtfEntry( 13 )", getEmptyClassData().getEntryType( 13 ), ClassFileFormat.CONSTANT_NameAndType );
}
public void test_getNameFromNameAndType_MethodRef_EmptyClass()
throws Exception
{
final ConstantPool constantPool = getEmptyClassData();
final String value = "<init>";
assertEquals( "getNameFromNameAndType( 13 )", constantPool.getNameFromNameAndType( 13 ), value );
assertEquals( "strings[4] post get", value, constantPool.strings[4] );
}
public void test_getTypeFromNameAndType_MethodRef_EmptyClass()
throws Exception
{
final ConstantPool constantPool = getEmptyClassData();
final String value = "()V";
assertEquals( "getTypeFromNameAndType( 13 )", constantPool.getTypeFromNameAndType( 13 ), value );
assertEquals( "strings[5] post get", value, constantPool.strings[5] );
}
public void test_getClassFromRef_MethodRef_EmptyClass()
throws Exception
{
final ConstantPool constantPool = getEmptyClassData();
final String value = "java/lang/Object";
assertEquals( "getClassFromRef( 1 )", constantPool.getClassFromRef( 1 ), value );
assertEquals( "strings[15] post get", value, constantPool.strings[15] );
}
public void test_getNameFromRef_EmptyClass()
throws Exception
{
final ConstantPool constantPool = getEmptyClassData();
final String value = "<init>";
assertEquals( "getNameFromRef( 1 )", constantPool.getNameFromRef( 1 ), value );
assertEquals( "strings[4] post get", value, constantPool.strings[4] );
}
public void test_getTypeFromRef_EmptyClass()
throws Exception
{
final ConstantPool constantPool = getEmptyClassData();
final String value = "()V";
assertEquals( "getTypeFromRef( 1 )", constantPool.getTypeFromRef( 1 ), value );
assertEquals( "strings[5] post get", value, constantPool.strings[5] );
}
public void test_getFloatEntry_NonEmptyClass()
throws Exception
{
assertEquals( "getFloatEntry( 4 )", 32.5F, getNonEmptyClassData().getFloatEntry( 4 ), 0.0 );
}
public void test_getDoubleEntry_NonEmptyClass()
throws Exception
{
assertEquals( "getDoubleEntry( 7 )", 55.0D, getNonEmptyClassData().getDoubleEntry( 7 ), 0.0 );
}
public void test_getIntegerEntry_NonEmptyClass()
throws Exception
{
assertEquals( "getIntegerEntry( 22 )", 42, getNonEmptyClassData().getIntegerEntry( 22 ) );
}
public void test_getLongEntry_NonEmptyClass()
throws Exception
{
assertEquals( "getLongEntry( 5 )", 3L, getNonEmptyClassData().getLongEntry( 5 ) );
}
public void test_getStringEntry_NonEmptyClass()
throws Exception
{
final ConstantPool constantPool = getNonEmptyClassData();
final String value = constantPool.getStringEntry( 2 );
assertEquals( "getStringEntry( 2 )", "What is 6 x 9 in base 13?", value );
assertEquals( "strings[2] post get", value, constantPool.strings[2] );
assertTrue( "strings[2] identical", value == constantPool.getStringEntry( 2 ) );
assertTrue( "strings[2] identical", value == constantPool.strings[2] );
}
public void test_getNameFromRef_FieldRef_NonEmptyClass()
throws Exception
{
final ConstantPool constantPool = getNonEmptyClassData();
final String value = "m_question";
assertEquals( "getNameFromRef( 3 )", constantPool.getNameFromRef( 3 ), value );
assertEquals( "strings[23] post get", value, constantPool.strings[23] );
}
public void test_getTypeFromRef_FieldRef_NonEmptyClass()
throws Exception
{
final ConstantPool constantPool = getNonEmptyClassData();
final String value = "Ljava/lang/String;";
assertEquals( "getTypeFromRef( 3 )", value, constantPool.getTypeFromRef( 3 ) );
assertEquals( "strings[24] post get", value, constantPool.strings[24] );
}
public void test_getClassFromRef_FieldRef_NonEmptyClass()
throws Exception
{
final ConstantPool constantPool = getNonEmptyClassData();
final String value = "org/realityforge/fade/data/NonEmptyClass";
assertEquals( "getClassFromRef( 3 )", value, constantPool.getClassFromRef( 3 ) );
assertEquals( "strings[16] post get", value, constantPool.strings[16] );
}
public void test_getNameFromRef_InterfaceMethodRef_NonEmptyClass()
throws Exception
{
final ConstantPool constantPool = getNonEmptyClassData();
final String value = "runJumpSkipAndPlay";
assertEquals( "getNameFromRef( 9 )", value, constantPool.getNameFromRef( 9 ) );
assertEquals( "strings[56] post get", value, constantPool.strings[56] );
}
public void test_getTypeFromRef_InterfaceMethodRef_NonEmptyClass()
throws Exception
{
final ConstantPool constantPool = getNonEmptyClassData();
final String value = "()V";
assertEquals( "getTypeFromRef( 9 )", value, constantPool.getTypeFromRef( 9 ) );
assertEquals( "strings[57] post get", value, constantPool.strings[57] );
}
public void test_getClassFromRef_InterfaceMethod_NonEmptyClass()
throws Exception
{
final ConstantPool constantPool = getNonEmptyClassData();
final String value = "org/realityforge/fade/data/MyInterface";
assertEquals( "getClassFromRef( 9 )", value, constantPool.getClassFromRef( 9 ) );
assertEquals( "strings[18] post get", value, constantPool.strings[18] );
}
public void test_attempt_getTypeFromNameAndType_onNonRef_NonEmptyClass()
throws Exception
{
try
{
getNonEmptyClassData().getTypeFromRef( 2 );
fail( "Expected to get an exception" );
}
catch( final ClassFormatError cfe )
{
final String message =
"Unexpected type for constant pool element 2. Expected a ref type but got 8 at position 15";
assertEquals( "getMessage()", message, cfe.getMessage() );
}
}
public void test_attempt_getStringEntry_onNonString_NonEmptyClass()
throws Exception
{
try
{
getNonEmptyClassData().getStringEntry( 1 );
}
catch( final ClassFormatError cfe )
{
final String message =
"Unexpected type for constant pool element 1. Expected: 8 Actual: 10 at position 10";
assertEquals( "getMessage()", message, cfe.getMessage() );
}
}
public void test_parseUtfString()
throws Exception
{
final byte[] data = new byte[]{0, 6, 'a', (byte)0xCF, (byte)0x8F, (byte)0xEF, (byte)0x8F, (byte)0x80};
final String value = ConstantPool.parseUtfString( data, 0, 0 );
assertEquals( "value.length", 3, value.length() );
assertEquals( "value.charAt( 0 )", 'a', value.charAt( 0 ) );
assertEquals( "value.charAt( 1 )", 975, value.charAt( 1 ) );
assertEquals( "value.charAt( 2 )", 62400, value.charAt( 2 ) );
}
public void test_parseConstantPool_with_truncation()
{
try
{
final byte[] data = new byte[10];
data[8]= 2;
data[9]= 0;
ConstantPool.parseConstantPool( data );
fail( "Expected exception" );
}
catch( final ClassFormatError cfe )
{
final String message = "Class file truncated when parsing constant pool at position 10";
assertEquals( "getMessage()", message, cfe.getMessage() );
}
}
public void test_parseConstantPool_with_unkown_tag()
{
try
{
final byte[] data = new byte[11];
data[8]= 1;
data[9]= 0;
data[10]= 42;
ConstantPool.parseConstantPool( data );
fail( "Expected exception" );
}
catch( final ClassFormatError cfe )
{
final String message = "Bad constant pool tag 42 at position 10";
assertEquals( "getMessage()", message, cfe.getMessage() );
}
}
private ConstantPool getEmptyClassData()
throws Exception
{
final byte[] bytes = loadTestData( "EmptyClass.class.dat" );
return ConstantPool.parseConstantPool( bytes );
}
private ConstantPool getNonEmptyClassData()
throws Exception
{
final byte[] bytes = loadTestData( "NonEmptyClass.class.dat" );
return ConstantPool.parseConstantPool( bytes );
}
private byte[] loadTestData( final String resource )
throws IOException
{
final InputStream input = TestConstantPool.class.getResourceAsStream( resource );
assertNotNull( "Seemingly missing test data: " + resource, input );
final int size = input.available();
final byte[] bytes = new byte[size];
final int count = input.read( bytes );
assertEquals( "Unable to fully read testdata for: " + resource, count, size );
return bytes;
}
}
| 11,833 | 0.687822 | 0.669568 | 341 | 33.700878 | 31.118706 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.750733 | false | false | 2 |
81889fd14e36695263b833f6d730e9dcd1c65b6c | 16,509,854,307,942 | eecd645783a20bb902092ca311a0affebd4b1f4d | /src/com/pattern/decorate/StarBuzzCoffee.java | cc61599c02d34957a9bfcdb36465677ce32d19b2 | [] | no_license | ParkCheung/design-pattern | https://github.com/ParkCheung/design-pattern | 7b4a5894c12cfda5421dc39d2a1bf5b0acd3dd7c | 694fa225ed736f0fa6e87f7d5c1443b72c5d5d8d | refs/heads/master | 2017-11-16T16:50:18.170000 | 2016-12-04T07:07:10 | 2016-12-04T07:07:10 | 68,358,199 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pattern.decorate;
/**
* 装饰者模式测试类
*
* Created by MrZhang on 2016/12/4.
*/
public class StarBuzzCoffee {
public static void main(String[] args) {
//咖啡类
Beverage beverage = new Espresso();
System.out.println(beverage.getDescription() +" $" + beverage.cost());
Beverage beverage1 = new DarkRoast();
//两份mocha
beverage1 = new Mocha(beverage1);
beverage1= new Mocha(beverage1);
beverage1 = new Milk(beverage1);
System.out.println(beverage1.getDescription() + " $"+beverage1.cost());
}
}
| UTF-8 | Java | 609 | java | StarBuzzCoffee.java | Java | [
{
"context": "attern.decorate;\n\n/**\n * 装饰者模式测试类\n *\n * Created by MrZhang on 2016/12/4.\n */\npublic class StarBuzzCoffee {\n ",
"end": 71,
"score": 0.9985613226890564,
"start": 64,
"tag": "USERNAME",
"value": "MrZhang"
}
] | null | [] | package com.pattern.decorate;
/**
* 装饰者模式测试类
*
* Created by MrZhang on 2016/12/4.
*/
public class StarBuzzCoffee {
public static void main(String[] args) {
//咖啡类
Beverage beverage = new Espresso();
System.out.println(beverage.getDescription() +" $" + beverage.cost());
Beverage beverage1 = new DarkRoast();
//两份mocha
beverage1 = new Mocha(beverage1);
beverage1= new Mocha(beverage1);
beverage1 = new Milk(beverage1);
System.out.println(beverage1.getDescription() + " $"+beverage1.cost());
}
}
| 609 | 0.614065 | 0.586621 | 25 | 22.32 | 23.744844 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.32 | false | false | 2 |
a8daa2d38e8f7e946e22c6f585227fd8e234278f | 21,053,929,749,718 | 98876d27fd13c8a18162c5b6cc755758a408a6dc | /src/main/java/com/staples/dashboard/app/dao/mappers/DotcomActivityVOMapper.java | e1503ca18a9ee1f67649fae5615f2c0f8dc34d93 | [] | no_license | SHUBHAM1991/HeliosTest | https://github.com/SHUBHAM1991/HeliosTest | 37f96614d2da3a679eeb9134b972ce63e2dcbdd6 | 8053b53b7aadb03cf883b11088cdd31aa2d113e1 | refs/heads/master | 2022-02-07T13:04:54.922000 | 2022-01-25T17:52:37 | 2022-01-25T17:52:37 | 119,514,398 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.staples.dashboard.app.dao.mappers;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.RowMapper;
import com.staples.dashboard.app.constants.MapperConstants;
import com.staples.dashboard.app.vo.DotcomAcitivityVO;
/**
* The Class DotcomActivityVOMapper.
*
* @author KumBi002
* @version 1.0 Revision history
* <p>
* ------------------------------------------------------------
* </p>
* <p>
* <table>
* <tr>
* <td>Version</td>
* <td>Date</td>
* <td>Author</td>
* <td>Description</td>
* </tr>
* <tr>
* <td>1.0</td>
* <td>Dec 4, 2015</td>
* <td>KumBi002</td>
* <td>Initial Draft</td>
* </tr>
* </table>
* </p>
* <p>
* ------------------------------------------------------------
* </p>
*/
public class DotcomActivityVOMapper implements RowMapper<DotcomAcitivityVO>,
StaplesDashBoardRowMapper {
/**
* Method implementation to get row map.
*
* @param ResultSet
* rs
* @param int rowNum
* @return AbabdonedCartVO
* @throws SQLException
*/
@Override
public DotcomAcitivityVO mapRow(ResultSet rs, int rowNum)
throws SQLException {
DotcomAcitivityVO dotcomActivityVO = new DotcomAcitivityVO();
dotcomActivityVO.setSkuNumber(rs.getString(MapperConstants.DOTCOM_SKU));
dotcomActivityVO.setItemDescription(rs
.getString(MapperConstants.DOTCOM_SKU_NAME));
dotcomActivityVO.setOrderContact(rs
.getString(MapperConstants.DOTCOM_ORDER_CONTACT));
dotcomActivityVO.setActDate(rs
.getString(MapperConstants.DOTCOM_ACT_DATE));
dotcomActivityVO.setAct(rs.getString(MapperConstants.DOTCOM_ACT));
return dotcomActivityVO;
}
/**
* Method implementation to get row map.
*
* @param List
* <Map<String,Object>> resultMap
* @return List<Object>
*/
@Override
public List<Object> mapRow(List<Map<String, Object>> resultMap) {
List<Object> objects = null;
DotcomAcitivityVO dotcomActivityVO = null;
if (resultMap != null && !resultMap.isEmpty()) {
for (Map<String, Object> rs : resultMap) {
if (objects == null) {
objects = new ArrayList<Object>();
}
dotcomActivityVO = new DotcomAcitivityVO();
dotcomActivityVO
.setSkuNumber(rs.get(MapperConstants.DOTCOM_SKU) == null ? MapperConstants.BLANK_STRING
: rs.get(MapperConstants.DOTCOM_SKU).toString());
dotcomActivityVO
.setItemDescription(rs
.get(MapperConstants.DOTCOM_SKU_NAME) == null ? MapperConstants.BLANK_STRING
: rs.get(MapperConstants.DOTCOM_SKU_NAME)
.toString());
dotcomActivityVO
.setOrderContact(rs
.get(MapperConstants.DOTCOM_ORDER_CONTACT) == null ? MapperConstants.BLANK_STRING
: rs.get(MapperConstants.DOTCOM_ORDER_CONTACT)
.toString());
dotcomActivityVO
.setActDate(rs.get(MapperConstants.DOTCOM_ACT_DATE) == null ? MapperConstants.BLANK_STRING
: rs.get(MapperConstants.DOTCOM_ACT_DATE)
.toString());
dotcomActivityVO
.setAct(rs.get(MapperConstants.DOTCOM_ACT) == null ? MapperConstants.BLANK_STRING
: rs.get(MapperConstants.DOTCOM_ACT).toString());
dotcomActivityVO
.setPrice(rs.get(MapperConstants.DOTCOM_PRICE) == null ? MapperConstants.BLANK_STRING
: rs.get(MapperConstants.DOTCOM_PRICE).toString());
dotcomActivityVO
.setQuantity(rs.get(MapperConstants.DOTCOM_QUANTITY) == null ? MapperConstants.BLANK_STRING
: rs.get(MapperConstants.DOTCOM_QUANTITY).toString());
dotcomActivityVO
.setThumbnail(rs.get(MapperConstants.DOTCOM_THUMBNAIL) == null ? MapperConstants.BLANK_STRING
: rs.get(MapperConstants.DOTCOM_THUMBNAIL)
.toString());
objects.add(dotcomActivityVO);
}
}
return objects;
}
}
| UTF-8 | Java | 3,964 | java | DotcomActivityVOMapper.java | Java | [
{
"context": "* The Class DotcomActivityVOMapper.\n * \n * @author KumBi002\n * @version 1.0 Revision history\n * <p>\n",
"end": 408,
"score": 0.9997165203094482,
"start": 400,
"tag": "USERNAME",
"value": "KumBi002"
},
{
"context": "\n * <td>Dec 4, 2015</td>\n * <td>KumBi002</td>\n * <td>Initial Draft</td>\n * ",
"end": 834,
"score": 0.9893353581428528,
"start": 826,
"tag": "USERNAME",
"value": "KumBi002"
}
] | null | [] | package com.staples.dashboard.app.dao.mappers;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.RowMapper;
import com.staples.dashboard.app.constants.MapperConstants;
import com.staples.dashboard.app.vo.DotcomAcitivityVO;
/**
* The Class DotcomActivityVOMapper.
*
* @author KumBi002
* @version 1.0 Revision history
* <p>
* ------------------------------------------------------------
* </p>
* <p>
* <table>
* <tr>
* <td>Version</td>
* <td>Date</td>
* <td>Author</td>
* <td>Description</td>
* </tr>
* <tr>
* <td>1.0</td>
* <td>Dec 4, 2015</td>
* <td>KumBi002</td>
* <td>Initial Draft</td>
* </tr>
* </table>
* </p>
* <p>
* ------------------------------------------------------------
* </p>
*/
public class DotcomActivityVOMapper implements RowMapper<DotcomAcitivityVO>,
StaplesDashBoardRowMapper {
/**
* Method implementation to get row map.
*
* @param ResultSet
* rs
* @param int rowNum
* @return AbabdonedCartVO
* @throws SQLException
*/
@Override
public DotcomAcitivityVO mapRow(ResultSet rs, int rowNum)
throws SQLException {
DotcomAcitivityVO dotcomActivityVO = new DotcomAcitivityVO();
dotcomActivityVO.setSkuNumber(rs.getString(MapperConstants.DOTCOM_SKU));
dotcomActivityVO.setItemDescription(rs
.getString(MapperConstants.DOTCOM_SKU_NAME));
dotcomActivityVO.setOrderContact(rs
.getString(MapperConstants.DOTCOM_ORDER_CONTACT));
dotcomActivityVO.setActDate(rs
.getString(MapperConstants.DOTCOM_ACT_DATE));
dotcomActivityVO.setAct(rs.getString(MapperConstants.DOTCOM_ACT));
return dotcomActivityVO;
}
/**
* Method implementation to get row map.
*
* @param List
* <Map<String,Object>> resultMap
* @return List<Object>
*/
@Override
public List<Object> mapRow(List<Map<String, Object>> resultMap) {
List<Object> objects = null;
DotcomAcitivityVO dotcomActivityVO = null;
if (resultMap != null && !resultMap.isEmpty()) {
for (Map<String, Object> rs : resultMap) {
if (objects == null) {
objects = new ArrayList<Object>();
}
dotcomActivityVO = new DotcomAcitivityVO();
dotcomActivityVO
.setSkuNumber(rs.get(MapperConstants.DOTCOM_SKU) == null ? MapperConstants.BLANK_STRING
: rs.get(MapperConstants.DOTCOM_SKU).toString());
dotcomActivityVO
.setItemDescription(rs
.get(MapperConstants.DOTCOM_SKU_NAME) == null ? MapperConstants.BLANK_STRING
: rs.get(MapperConstants.DOTCOM_SKU_NAME)
.toString());
dotcomActivityVO
.setOrderContact(rs
.get(MapperConstants.DOTCOM_ORDER_CONTACT) == null ? MapperConstants.BLANK_STRING
: rs.get(MapperConstants.DOTCOM_ORDER_CONTACT)
.toString());
dotcomActivityVO
.setActDate(rs.get(MapperConstants.DOTCOM_ACT_DATE) == null ? MapperConstants.BLANK_STRING
: rs.get(MapperConstants.DOTCOM_ACT_DATE)
.toString());
dotcomActivityVO
.setAct(rs.get(MapperConstants.DOTCOM_ACT) == null ? MapperConstants.BLANK_STRING
: rs.get(MapperConstants.DOTCOM_ACT).toString());
dotcomActivityVO
.setPrice(rs.get(MapperConstants.DOTCOM_PRICE) == null ? MapperConstants.BLANK_STRING
: rs.get(MapperConstants.DOTCOM_PRICE).toString());
dotcomActivityVO
.setQuantity(rs.get(MapperConstants.DOTCOM_QUANTITY) == null ? MapperConstants.BLANK_STRING
: rs.get(MapperConstants.DOTCOM_QUANTITY).toString());
dotcomActivityVO
.setThumbnail(rs.get(MapperConstants.DOTCOM_THUMBNAIL) == null ? MapperConstants.BLANK_STRING
: rs.get(MapperConstants.DOTCOM_THUMBNAIL)
.toString());
objects.add(dotcomActivityVO);
}
}
return objects;
}
}
| 3,964 | 0.645812 | 0.642028 | 125 | 30.712 | 24.036911 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.36 | false | false | 2 |
8b0de7c2828ea81dcd6f1583fbbbe61b2b631b81 | 39,006,893,003,324 | a078d39f807956cc5b00bc01667207d63c33802e | /spring-properties-encryption/src/test/java/com/ryaltech/utils/spring/encryption/BaseTest.java | d22d893aa12fe75f990ced2954bd0d9455003b1e | [] | no_license | arykov/spring-properties-encryption | https://github.com/arykov/spring-properties-encryption | 5aa09e5261ed3b54bed84c479cde8187a26b4db9 | 37a5e19ba9c08c7099302a8d8a0f67d3e65cd492 | refs/heads/master | 2022-12-21T13:12:34.890000 | 2020-06-01T17:26:12 | 2020-06-01T17:26:12 | 224,729,061 | 0 | 0 | null | false | 2022-12-14T20:39:41 | 2019-11-28T21:02:12 | 2020-06-01T17:26:15 | 2022-12-14T20:39:41 | 92 | 0 | 0 | 2 | Java | false | false | package com.ryaltech.utils.spring.encryption;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.logging.LogManager;
public class BaseTest {
public static final String PROPERTIES_FILE_NAME = "application.properties";
public static final String PROPERTIES_FILE_NAME_SOURCE = "application.properties.source";
public static final String YML_FILE_NAME = "application.yml";
public static final String YML_FILE_NAME_SOURCE = "application.yml.source";
public static final String YML_FILE_NAME_VERIFICATION = "application.yml.verification";
public static final String KEY_FILE = "syskey.dat";
static {
configureLogging();
}
public static void configureLogging() {
try (InputStream is = BaseTest.class.getClassLoader().getResourceAsStream("logging.properties")) {
LogManager.getLogManager().readConfiguration(is);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
public static void deleteKeyFile() {
new File(KEY_FILE).delete();
}
public static void deleteAllWorkFiles() {
deleteKeyFile();
new File(PROPERTIES_FILE_NAME).delete();
new File(YML_FILE_NAME).delete();
}
public static byte[] readFullyFromClassPath(String fromFile) {
FileSystem sourceFs = null;
try {
URI uri = ClassLoader.getSystemResource(fromFile).toURI();
Path sourcePath;
if("jar".equals(uri.getScheme())) {
String[] array = uri.toString().split("!");
sourceFs = FileSystems.newFileSystem(URI.create(array[0]), new HashMap());
sourcePath = sourceFs.getPath(array[1]);
}else {
sourcePath = Paths.get(uri);
}
return Files.readAllBytes(sourcePath);
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
if(sourceFs != null) {
try {
sourceFs.close();
}catch(Exception ex) {
}
}
}
}
public static void copyFromClassPathToFs(String fromFile, String toFile) {
FileSystem sourceFs = null;
try {
URI uri = ClassLoader.getSystemResource(fromFile).toURI();
Path sourcePath;
if("jar".equals(uri.getScheme())) {
String[] array = uri.toString().split("!");
sourceFs = FileSystems.newFileSystem(URI.create(array[0]), new HashMap());
sourcePath = sourceFs.getPath(array[1]);
}else {
sourcePath = Paths.get(uri);
}
Files.copy(sourcePath, Paths.get(toFile));
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
if(sourceFs != null) {
try {
sourceFs.close();
}catch(Exception ex) {
}
}
}
}
}
| UTF-8 | Java | 2,774 | java | BaseTest.java | Java | [] | null | [] | package com.ryaltech.utils.spring.encryption;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.logging.LogManager;
public class BaseTest {
public static final String PROPERTIES_FILE_NAME = "application.properties";
public static final String PROPERTIES_FILE_NAME_SOURCE = "application.properties.source";
public static final String YML_FILE_NAME = "application.yml";
public static final String YML_FILE_NAME_SOURCE = "application.yml.source";
public static final String YML_FILE_NAME_VERIFICATION = "application.yml.verification";
public static final String KEY_FILE = "syskey.dat";
static {
configureLogging();
}
public static void configureLogging() {
try (InputStream is = BaseTest.class.getClassLoader().getResourceAsStream("logging.properties")) {
LogManager.getLogManager().readConfiguration(is);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
public static void deleteKeyFile() {
new File(KEY_FILE).delete();
}
public static void deleteAllWorkFiles() {
deleteKeyFile();
new File(PROPERTIES_FILE_NAME).delete();
new File(YML_FILE_NAME).delete();
}
public static byte[] readFullyFromClassPath(String fromFile) {
FileSystem sourceFs = null;
try {
URI uri = ClassLoader.getSystemResource(fromFile).toURI();
Path sourcePath;
if("jar".equals(uri.getScheme())) {
String[] array = uri.toString().split("!");
sourceFs = FileSystems.newFileSystem(URI.create(array[0]), new HashMap());
sourcePath = sourceFs.getPath(array[1]);
}else {
sourcePath = Paths.get(uri);
}
return Files.readAllBytes(sourcePath);
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
if(sourceFs != null) {
try {
sourceFs.close();
}catch(Exception ex) {
}
}
}
}
public static void copyFromClassPathToFs(String fromFile, String toFile) {
FileSystem sourceFs = null;
try {
URI uri = ClassLoader.getSystemResource(fromFile).toURI();
Path sourcePath;
if("jar".equals(uri.getScheme())) {
String[] array = uri.toString().split("!");
sourceFs = FileSystems.newFileSystem(URI.create(array[0]), new HashMap());
sourcePath = sourceFs.getPath(array[1]);
}else {
sourcePath = Paths.get(uri);
}
Files.copy(sourcePath, Paths.get(toFile));
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
if(sourceFs != null) {
try {
sourceFs.close();
}catch(Exception ex) {
}
}
}
}
}
| 2,774 | 0.697188 | 0.695746 | 102 | 26.196079 | 23.824949 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.509804 | false | false | 2 |
8dce8ea107f80fe9b38ee486f6a81b96a55b693e | 36,352,603,194,049 | d7b4ee590d57dbe7550253b35a6de836cb08ce3f | /dubbo-demo/dubbo-server-api/src/main/java/com/lee9213/service/IHelloService.java | 32dbac5f259572a1b0e8899a2c1116cc5190d5b3 | [] | no_license | lee9213/gupao-demo | https://github.com/lee9213/gupao-demo | b50484ba3eddd3055cec12788f4569de20891e75 | abbab1f39b17d824d11342617d174b15b4220e9c | refs/heads/master | 2020-03-25T15:39:55.419000 | 2018-08-28T02:07:40 | 2018-08-28T02:07:40 | 143,895,115 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lee9213.service;
/**
* @author lee9213@163.com
* @version 1.0
* @date 2018-08-14 20:39
*/
public interface IHelloService {
String hello(String message);
}
| UTF-8 | Java | 178 | java | IHelloService.java | Java | [
{
"context": "package com.lee9213.service;\n\n/**\n * @author lee9213@163.com\n * @version 1.0\n * @date 2018-08-14 20:39\n */\npub",
"end": 60,
"score": 0.999920666217804,
"start": 45,
"tag": "EMAIL",
"value": "lee9213@163.com"
}
] | null | [] | package com.lee9213.service;
/**
* @author <EMAIL>
* @version 1.0
* @date 2018-08-14 20:39
*/
public interface IHelloService {
String hello(String message);
}
| 170 | 0.674157 | 0.533708 | 12 | 13.833333 | 13.371819 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 2 |
6dc4c409c852ab8e7959d4b0ae06b675d916120b | 24,275,155,201,033 | c9dc78e30f90b991004da934b1f61e30b04639f8 | /recursionDriver.java | 7977df1f45ab09176dc21e96845a2746e85a5e0a | [] | no_license | Siyu1923/ArrayExamples | https://github.com/Siyu1923/ArrayExamples | 84b368765f8da612d4c4207398c690bfc4c26d7b | be05b10d35fecb46b021adf9d1f0f5ba97ad042d | refs/heads/master | 2020-03-31T10:22:51.421000 | 2018-11-05T20:48:52 | 2018-11-05T20:48:52 | 152,132,526 | 0 | 0 | null | true | 2018-10-08T19:11:24 | 2018-10-08T19:11:24 | 2018-10-08T14:01:15 | 2018-10-08T14:01:14 | 2 | 0 | 0 | 0 | null | false | null | public class recursionDriver
{
public static int count(int n)
{
/*
-----task 1 -----
if (n==0)
return 0;
return 4+count(n-1);
-----task 2 -----
if (n==0)
return 0;
return 20+count(n-1);
-----task 3 -----
if (n==0)
return 0;
return 10+count(n-1);
-----task 4 -----
if (n==1)
return 1;
return n+count(n-2);
*/
if (n==2)
return 0;
return n+count(n-2);
}
public static void main(String[] args)
{
/*
* Count
* 1. Number of legs 10 elephant have
* 2. Number of students in a school if each
* classs has 20 students and there are 12 rooms
* 3. Number of fingers if there are 8 people
* 4. Find the sum of odd numbers from 0 to N
* 5. Find the sum of even numbers from 0 to N
*/
int counted=0;
// Task 1.
counted = count(5);
System.out.println(counted);
}
}
| UTF-8 | Java | 902 | java | recursionDriver.java | Java | [] | null | [] | public class recursionDriver
{
public static int count(int n)
{
/*
-----task 1 -----
if (n==0)
return 0;
return 4+count(n-1);
-----task 2 -----
if (n==0)
return 0;
return 20+count(n-1);
-----task 3 -----
if (n==0)
return 0;
return 10+count(n-1);
-----task 4 -----
if (n==1)
return 1;
return n+count(n-2);
*/
if (n==2)
return 0;
return n+count(n-2);
}
public static void main(String[] args)
{
/*
* Count
* 1. Number of legs 10 elephant have
* 2. Number of students in a school if each
* classs has 20 students and there are 12 rooms
* 3. Number of fingers if there are 8 people
* 4. Find the sum of odd numbers from 0 to N
* 5. Find the sum of even numbers from 0 to N
*/
int counted=0;
// Task 1.
counted = count(5);
System.out.println(counted);
}
}
| 902 | 0.527716 | 0.482262 | 48 | 17.770834 | 13.952658 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.270833 | false | false | 2 |
c67418540513d42ed2727c7817c2b3fab4fc5111 | 11,553,462,062,226 | 97ae99cf3cd9d3060ea84c6f1a3bbb4231bb3e95 | /mihealth_DNP/src/main/java/com/mihealth/controller/exception/ExceptionController.java | 7a2dc5f2ebabee0cd24ee9874114067a12ee2b7f | [] | no_license | srwhitebox/MiHealth | https://github.com/srwhitebox/MiHealth | 5d6514f5a1fa3c6958a13f0c4d2c8888ecdd666d | 17dd6a0154e921f7581a8223632596f4f0d54d19 | refs/heads/master | 2020-04-17T02:47:57.241000 | 2019-01-17T03:28:49 | 2019-01-17T03:28:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mihealth.controller.exception;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class ExceptionController {
@RequestMapping(value = {"/400", "/404", "/500"}, method = RequestMethod.GET)
public String exception() {
return "default/home.html";
}
}
| UTF-8 | Java | 419 | java | ExceptionController.java | Java | [] | null | [] | package com.mihealth.controller.exception;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class ExceptionController {
@RequestMapping(value = {"/400", "/404", "/500"}, method = RequestMethod.GET)
public String exception() {
return "default/home.html";
}
}
| 419 | 0.768496 | 0.747017 | 14 | 28.928572 | 25.655588 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.928571 | false | false | 2 |
68979afbb71d2bc13a7c75816fec0c9fae06a2c2 | 34,583,076,693,403 | 4fde206d2b86e7426677db808c91fa590840bb03 | /src/app/PickList.java | 0e59b3d03ef831925aff2482e83bb3a3d4912544 | [] | no_license | helghast79/WheelOfDeath | https://github.com/helghast79/WheelOfDeath | feccea640c56aa125b825925656ee698a90632a8 | 4e36f052bb14a7589d5e7835f18b8fc7ba17ea48 | refs/heads/master | 2021-01-10T11:36:22.207000 | 2016-04-28T12:06:31 | 2016-04-28T12:06:31 | 55,557,236 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package app;
import java.util.HashSet;
import java.util.Set;
/**
* This class holds the properties of each round to be used in the wheel of death class
*
* @author Miguel Chambel
*
*/
public class PickList {
private String name;
private Set<String> chooseList;
private Set<String> ignoreList;
public PickList(String name){
this.name = name;
this.chooseList = new HashSet<String>();
this.ignoreList = new HashSet<String>();
}
public String getName() {
return name;
}
public Set<String> getChooseList() {
return chooseList;
}
public void addToChooseList(String value) {
chooseList.add(value);
}
public boolean removeFromChooseList(String value) {
return chooseList.remove(value);
}
public Set<String> getIgnoreList() {
return ignoreList;
}
public void addToIgnoreList(String value) {
ignoreList.add(value);
}
public boolean removeFromIgnoreList(String value) {
return ignoreList.remove(value);
}
}
| UTF-8 | Java | 1,071 | java | PickList.java | Java | [
{
"context": "be used in the wheel of death class\n *\n * @author Miguel Chambel\n *\n */\npublic class PickList {\n\n private Strin",
"end": 186,
"score": 0.9998636841773987,
"start": 172,
"tag": "NAME",
"value": "Miguel Chambel"
}
] | null | [] | package app;
import java.util.HashSet;
import java.util.Set;
/**
* This class holds the properties of each round to be used in the wheel of death class
*
* @author <NAME>
*
*/
public class PickList {
private String name;
private Set<String> chooseList;
private Set<String> ignoreList;
public PickList(String name){
this.name = name;
this.chooseList = new HashSet<String>();
this.ignoreList = new HashSet<String>();
}
public String getName() {
return name;
}
public Set<String> getChooseList() {
return chooseList;
}
public void addToChooseList(String value) {
chooseList.add(value);
}
public boolean removeFromChooseList(String value) {
return chooseList.remove(value);
}
public Set<String> getIgnoreList() {
return ignoreList;
}
public void addToIgnoreList(String value) {
ignoreList.add(value);
}
public boolean removeFromIgnoreList(String value) {
return ignoreList.remove(value);
}
}
| 1,063 | 0.640523 | 0.640523 | 53 | 19.207546 | 20.031446 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.301887 | false | false | 2 |
979ef623d7628122139a9c94efd23568411c55f3 | 22,677,427,387,797 | 0640b52faea7595719e8470c001020d3ea005c3b | /src/com/tmind/mss/pub/constants/DmsConstants.java | 4e85686db2925a744f1016b00a02ed14e0bae6ae | [] | no_license | uusilver/sims | https://github.com/uusilver/sims | 9b3ac1b24ab49d03c9a8259d874927d28fa7d2d6 | edbf632a17b797e95b08190945b03ca8124cac58 | refs/heads/master | 2016-09-06T09:50:46.494000 | 2015-01-15T07:14:54 | 2015-01-15T07:14:54 | 25,300,500 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tmind.mss.pub.constants;
import com.tmind.framework.pub.web.BaseFrameworkApplication;
//记录系统常量
public class DmsConstants {
public static final int COUNT_FOR_EVERY_PAGE = 10;//每业显示条数
// tables name in hql
public static final String MOD_MATERIAL_REQ = "com.tmind.dms.pub.po.DmsModStatistics";
public static final String C_USER_INFO = "com.tmind.dms.pub.po.CUserInfo";
public static final String C_ORG_NJ = "com.tmind.dms.pub.po.COrganizationNj";
public static final String DMS_MATERIAL_STATISTICS = "com.tmind.dms.pub.po.DmsMaterialStatistics";
public static final String DMS_STA_CONTENT = "com.tmind.dms.pub.po.DmsStaContent";
public static final String DMS_MATERIAL_INFO = "com.tmind.dms.pub.po.DmsMaterialInfo";
public static final String C_ORG_NJ_TYPE = "com.tmind.dms.pub.po.COrganizationType";
public static final String C_ORG_NJ_TYPE_ID = "com.tmind.dms.pub.po.COrganizationTypeId";
public static final String DMS_USER_PROPERTY = "com.tmind.dms.pub.po.DmsUserProperty";
//关帐
public static final String DMS_ACCOUNT_CLOSE = "C";
//调帐开始时间
public static final String DMS_MOD_ACCOUNT_START_TIME = "MS";
//调帐开始时间
public static final String DMS_MOD_ACCOUNT_END_TIME = "MN";
//物料申领开始时间
public static final String DMS_MATERIAL_APP_START_TIME = "RS";
//物料申领结束时间
public static final String DMS_MATERIAL_APP_END_TIME = "RN";
//营业厅未入库告警时限
public static final String DMS_MATERIAL_NOTIN_BUSS_ALARM = "BJ";
//营业厅未入库上级告警时限
public static final String DMS_MATERIAL_NOTIN_LEAD_ALARM = "SJ";
//物料有效期
public static final String DMS_MATERIAL_EFFECT_TIME = "YX";
//系统短信发送时间
public static final String DMS_SMS_SEND_TIME = "SS";
//库房
public static final String CLOSE_OBJECT_NAME_DEPOT = "DEPOT";
//区域
public static final String CLOSE_OBJECT_NAME_AREA = "AREA";
//营业厅
public static final String CLOSE_OBJECT_NAME_BUSS = "BUSS";
public static final String DMS_MATERIAL_FLOW_INFO = "com.tmind.dms.pub.po.DmsMaterialFlowInfo";
public static final String DMS_MATERIAL_RELATION = "com.tmind.dms.pub.po.DmsMaterielRelation";
public static final String DMS_MATERIAL_TOTAL_INFO = "com.tmind.dms.pub.po.DmsFlowTotalInfo";
// form type 单据类型
public static final Long FORM_TYPE_REQUIRE = new Long(0);//物料需求单
public static final Long FORM_TYPE_APPLY = new Long(1);//物料申领
public static final Long FORM_TYPE_EXPORT = new Long(2);//物料出库单
public static final Long FORM_TYPE_BACK = new Long(3);//物料退库单
public static final Long FORM_TYPE_HANDOUT = new Long(4);//统一下发单
public static final Long FORM_TYPE_CUS_BACK = new Long(5);//顾客退库单
public static final Long FORM_TYPE_IMPORT = new Long(6);//物料入库单
public static final Long FORM_TYPE_BACK_APPLY = new Long(7);//物料退库申请单
public static final Long FORM_TYPE_CUS_EXPORT = new Long(8);//顾客出库单
public static final Long FORM_TYPE_SUB_BACK = new Long(9);//下级退库入库单
public static final Long FORM_TYPE_HELP_BACK_APPLY = new Long(10);//调配退库申请单
public static final Long FORM_TYPE_HELP_BACK = new Long(11);//调配退库单
public static final Long FORM_TYPE_HELP_SELF_IMPORT = new Long(12);//本区调配入库单
public static final Long FORM_TYPE_HELP_OTHER_IMPORT = new Long(13);//别区调配入库单
public static final Long FORM_TYPE_HELP_OUT = new Long(14);//外协出库单
public static final Long FORM_TYPE_WASTE_OUT = new Long(15);//损耗出库单
public static final Long FORM_TYPE_DIS_IMPORT = new Long(16);//差异量补入单
public static final Long FORM_TYPE_DIS_BACK_APPLY = new Long(17);//差异量退库申请单
public static final Long FORM_TYPE_DIS_BACK = new Long(18);//差异量退库单
public static final Long FORM_TYPE_CONVERT_OUT = new Long(19);//活动类型转换出库单
public static final Long FORM_TYPE_CONVERT_IMPORT = new Long(20);//活动类型转换入库单
public static final Long FORM_TYPE_HANDOUT_CONFIG = new Long(21);//模板配置统一下发单
public static final Long FORM_TYPE_ADJUST_BACK = new Long(22);//调配中转入库单
public static final Long FORM_TYPE_ADJUST_OUT = new Long(23);//调配出库单
public static final Long FORM_TYPE_HANDOUT_CONFIG_TEMP = new Long(24);//模板配置统一下发临时出库
public static final Long FORM_TYPE_MAT_CLEAR_ZERO = new Long(25);//物料清零申请单
public static final Long FORM_TYPE_DIFF_CLEAR_ZERO = new Long(26);//差异量清零申请单
//调配入库退回所添加的单据类型
public static final Long FORM_TYPE_ADJUST_OUT_BACK_APPLY = new Long(27); //调配入库退回申请单
public static final Long FORM_TYPE_ADJUST_OUT_BACK = new Long(28); //调配入库退回单
public static final Long FORM_TYPE_ADJUST_BACK_IMPORT = new Long(29); //调配退回入库
public static final Long FROM_TYPE_ADJUST_IMPORT_AGAIN = new Long(30); //调配2次入库
//操作类型
public static final Long OPER_TYPE_REQUIRE = new Long(0);//物料需求单
public static final Long OPER_TYPE_APPLY = new Long(1);//物料申领
public static final Long OPER_TYPE_EXPORT = new Long(2);//物料出库单
public static final Long OPER_TYPE_BACK = new Long(3);//物料退库单
public static final Long OPER_TYPE_HANDOUT = new Long(4);//统一下发单
public static final Long OPER_TYPE_CUS_BACK = new Long(5);//顾客退库单
public static final Long OPER_TYPE_IMPORT = new Long(6);//物料入库单
public static final Long OPER_TYPE_BACK_APPLY = new Long(7);//物料退库申请单
public static final Long OPER_TYPE_CUS_EXPORT = new Long(8);//顾客出库单
public static final Long OPER_TYPE_BACK_IMPORT = new Long(9);//下级退库入库单
public static final Long OPER_TYPE_HELP_BACK_APPLY = new Long(10);//调配退库申请单
public static final Long OPER_TYPE_HELP_BACK = new Long(11);//调配退库单
public static final Long OPER_TYPE_HELP_SELF_IMPORT = new Long(12);//本区调配入库单
public static final Long OPER_TYPE_HELP_OTHER_IMPORT = new Long(13);//别区调配入库单
public static final Long OPER_TYPE_HELP_OUT = new Long(14);//外协出库单
public static final Long OPER_TYPE_WASTE_OUT = new Long(15);//损耗出库单
public static final Long OPER_TYPE_DIS_IMPORT = new Long(16);//差异量补入单
public static final Long OPER_TYPE_DIS_BACK_APPLY = new Long(17);//差异量退库申请单
public static final Long OPER_TYPE_DIS_BACK = new Long(18);//差异量退库单
public static final Long OPER_TYPE_CONVERT_OUT = new Long(19);//活动类型转换出库单
public static final Long OPER_TYPE_CONVERT_IMPORT = new Long(20);//活动类型转换入库单
public static final Long OPER_TYPE_HANDOUT_CONFIG = new Long(21);//模板配置统一下发单
public static final Long OPER_TYPE_ADJUST_BACK = new Long(22);//调配中转入库单
public static final Long OPER_TYPE_ADJUST_OUT = new Long(23);//调配出库单
public static final Long OPER_TYPE_DIFF_CLEAR_ZERO = new Long(25);//差异量清零申请单
public static final Long OPER_TYPE_HANDOUT_CONFIG_TEMP = new Long(26);//模板配置统一下发临时出库
//调配入库退回所添加的操作
public static final Long OPER_TYPE_ADJUST_OUT_BACK_APPLY = new Long(27); //调配入库退回申请单
public static final Long OPER_TYPE_ADJUST_OUT_BACK = new Long(28); //调配入库退回单
public static final Long OPER_TYPE_ADJUST_BACK_IMPORT = new Long(29); //调配退回入库
public static final Long OPER_TYPE_ADJUST_IMPORT_AGAIN = new Long(30); //调配2次入库
//记录单据状态
public static final Long FORM_STATUS_SAVE = new Long(1);//保存
public static final Long FORM_STATUS_SUBMIT = new Long(2);//提交
public static final Long FORM_STATUS_BACK = new Long(3);//退回
public static final Long FORM_STATUS_STAY = new Long(4);//暂留
public static final Long FORM_STATUS_FINISH = new Long(5);//完成
public static final Long FORM_STATUS_DISABLE = new Long(6);//作废
public static final Long FORM_STATUS_EXAMINED = new Long(7);//已审批
//流水状态
public static final String FLOW_STATE_SUBMIT = "S";//提交
public static final String FLOW_STATE_FINISH = "F";//完成
public static final String FLOW_STATE_BACK = "B";//退回(目前在调配入库退回中使用)
//短信模版类型
public static final Long SMS_TEMP_TYPE_OUT = new Long(1);//出库
public static final Long SMS_TEMP_TYPE_APPLY = new Long(0);//申领
public static final Long SMS_TEMP_TYPE_NOT_IMPORT = new Long(2);//未入库
public static final Long SMS_TEMP_TYPE_NOT_EXPORT = new Long(3);//未出库
public static final Long SMS_TEMP_TYPE_OVERDUE= new Long(4);//过期
public static final Long SMS_TEMP_TYPE_LACK = new Long(5);//库存不足
// 出账报表excel文件导出目录
public static final String REPORTFORMDOWNPATH = BaseFrameworkApplication.FrameworkWebAppRootPath+"dms/jsp/statistics/";
//订单状态
public static final int SAVE_REQ_INFO = 1; //保存
public static final int SAVE_AS_REQUIRE_REQ_INFO = 2; //保存为需求但
public static final int SUBMIT_REQ_INFO = 3; //提交
public static final int NO_BUDGET_REQ_INFO = 4; //无预算
public static final int HANDLE_REQ_INFO = 5; //处理中
public static final int FINISH_REQ_INFO = 6; //完成
public static final int DISABLE_REQ_INFO = 7; //作废
//订单操作步骤
public static final int INDENT_SAVE_SUCCED = 1; //保存订货单
public static final int MAIL_CONNECT_FAILE = 2; //邮件服务器连接不上
public static final int ORDER_SEND_SUCCED = 3; //订单生成
//订单类型
public static final int ORDER_TYPE_COMMON = 1; //普通订货单
public static final int ORDER_TYPE_NET = 2; //网络设备订货单
public static final int ORDER_TYPE_BUY = 3; //购货单
public static final int ORDER_TYPE_CONTR= 4; //签订合同
public static final int ORDER_TYPE_COMP = 5; //招标比价
public static final int ORDER_TYPE_BUS = 6; //营业厅订单
//采购品状态
public static final int MATE_STATE_WAIT_CONTR = 0; //待签合同
public static final int MATE_STATE_WAIT_DISTR = 1; //待分发
public static final int MATE_STATE_WAIT_HANDLE = 2; //待处理
public static final int MATE_STATE_WAIT_PAY= 3; //待付款
public static final int MATE_STATE_WAIT_FINISH = 4; //完成
public static final int MATE_STATE_DISABLE = 5; //作废
//订单状态
public static final String ORDER_STATE_AVAILABLE = "A"; //有效
public static final String ORDER_STATE_UNAVAILABLE = "U"; //无效
public static final String ORDER_STATE_PIGONHOLE = "2"; //已归档
public static final String ORDER_STATE_UNPIGONHOLE = "1"; //未归档
//短信提醒类型
public static final int MESSAGE_TYPE_APPLY = 0; //物料申领
public static final int MESSAGE_TYPE_HANDOUT = 1;//物品统一下发
public static final int MESSAGE_TYPE_NOIMPORT = 2;//时限为入库
public static final int MESSAGE_TYPE_NOEXPORT = 3;//时限未出库
public static final int MESSAGE_TYPE_OVERDUE = 4;//物料过期
public static final int MESSAGE_TYPE_LACK = 5;//库存量不足
//短信内容状态
public static final String MESSAGE_STATE_NOSEND = "N"; //未发送
public static final String MESSAGE_STATE_ALSEND = "Y"; //已发送
//短信内容提醒--宏
public static final String MESSAGE_MACRO_DATE = "date"; //日期
public static final String MESSAGE_MACRO_UPPERORG = "upperOrg"; //上级
public static final String MESSAGE_MACRO_LOWERORG = "lowerOrg"; //下级
public static final String MESSAGE_MACRO_GOODSINFO = "goodsInfo"; //物品
public static final String MESSAGE_MACRO_ORGNAME = "orgName"; //营业厅名称
public static final String MESSAGE_MACRO_TIMELIMIT = "timeLimit"; //时间期限
//操作类型--联系信息更新
public static final Long LINK_UPDATE_TYPE_ORG = new Long(0);
public static final Long LINK_UPDATE_TYPE_AREA = new Long(1);
public static final Long LINK_UPDATE_TYPE_ORG_CLEAR = new Long(2);
//用户层级
public static final String LEVEL_MASTERMIND = "-1";//策划组
public static final String LEVEL_DEPOT = "0";//库房
public static final String LEVEL_CANTONAL_CENTER_OR_COUNTY_COMPANY = "1";//市区营销中心/县公司
public static final String LEVEL_AREA = "2";//区域
//物料大类
public static final String WHOLE_TYPE_YINGXIAO = "1";//营销类
public static final String WHOLE_TYPE_PROJECT = "2";//工程类
public static final String WHOLE_TYPE_PERMANENT_ASSETS = "3";//固定资产类
public static final String WHOLE_TYPE_NOT_PERMANENT_ASSETS_A = "4";//非固定资产A类
public static final String WHOLE_TYPE_NOT_PERMANENT_ASSETS_B = "5";//非固定资产B类
//物料状态记录(需求物料流水)中物料状态(MATERIAL_STATE)状态
public static final String MATERIAL_STATE_SAVE = "1";//1.保存;
public static final String MATERIAL_STATE_SUBMIT = "2";//2.待审批;
public static final String MATERIAL_STATE_BACK = "3";//3.退回;
public static final String MATERIAL_STATE_OUT = "4";//4.待入库;
public static final String MATERIAL_STATE_TO_SUM = "5";//5.待汇总;
public static final String MATERIAL_STATE_SUM = "6";//6.已汇总;
public static final String MATERIAL_STATE_REQ = "7";//7.已请购;
public static final String MATERIAL_STATE_TO_IN = "8";//8.待收货;
public static final String MATERIAL_STATE_DONE = "9";//9.完成。
public static final String MATERIAL_STATE_TO_REQ = "0";//0.待请购。
//物料状态记录(需求物料流水)中当前物料所处层级(CURR_LEVEL)
public static final String MATER_CURR_LEVEL_ORG = "1";//1 营业厅
public static final String MATER_CURR_LEVEL_AREA = "2";//2 区域
public static final String MATER_CURR_LEVEL_CENTER = "3";//3 市区营销中心
public static final String MATER_CURR_LEVEL_MART = "4";//4 市场部
//物料状态记录(需求物料流水)中各层级操作单类型,同操作总记录表中操作类型(OPER_TEYP)
public static final String OPER_TEYP_APPLY_SUBMIT = "1";//1 物料申请
public static final String OPER_TEYP_MATER_OUT = "2";//2 物料下发
public static final String OPER_TEYP_MATER_BACK = "3";//3 物料退回
public static final String OPER_TEYP_APPLY_SUM = "4";//4 物料汇总
public static final String OPER_TEYP_APPLY_REQ = "5";//5 物料请购
public static final String OPER_TEYP_MATER_IN = "6";//6 物料入库
//操作总记录表中操作单状态(OPER_STATE)
public static final String MATER_OPER_STATE_SAVE = "0";//0 保存
public static final String MATER_OPER_STATE_TO_DONE = "1";//1 待处理
public static final String MATER_OPER_STATE_DOING = "2";//2 处理中
public static final String MATER_OPER_STATE_DONE = "3";//3 已处理
// 全部县公司的TYPE
public static final String COUNTY_ALL_TYPE = "'57','58','59','60','61'";
//全部区域的TYPE
public static final String AREA_ALL_TYPE = "'51','52','53','54','55'";
public static final String DMS_IP_TEST = "http://192.168.16.30/dms/jsp/main.jsp";
public static final String DMS_IP_TEST_2 = "http://10.33.89.37:8899/dms/jsp/main.jsp";
public static final String MPMS_IP_TEST = "http://10.33.32.87:8899/mpms/mpms/jsp/main.jsp";
public static final String DMS_IP = "http://10.33.89.37/dms/jsp/main.jsp";
public static final String MPMS_IP = "http://10.33.32.87:88/mpms/mpms/jsp/main.jsp";
}
| UTF-8 | Java | 17,080 | java | DmsConstants.java | Java | [
{
"context": " public static final String DMS_IP_TEST = \"http://192.168.16.30/dms/jsp/main.jsp\";\r\n public static final Str",
"end": 14607,
"score": 0.9995549321174622,
"start": 14594,
"tag": "IP_ADDRESS",
"value": "192.168.16.30"
},
{
"context": "ublic static final String DMS_IP_TEST_2 = \"http://10.33.89.37:8899/dms/jsp/main.jsp\";\r\n public static fina",
"end": 14696,
"score": 0.9565410614013672,
"start": 14685,
"tag": "IP_ADDRESS",
"value": "10.33.89.37"
},
{
"context": "public static final String MPMS_IP_TEST = \"http://10.33.32.87:8899/mpms/mpms/jsp/main.jsp\";\r\n \r\n publ",
"end": 14789,
"score": 0.8681795001029968,
"start": 14778,
"tag": "IP_ADDRESS",
"value": "10.33.32.87"
},
{
"context": " public static final String DMS_IP = \"http://10.33.89.37/dms/jsp/main.jsp\";\r\n public static",
"end": 14880,
"score": 0.5606541633605957,
"start": 14879,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": " public static final String DMS_IP = \"http://10.33.89.37/dms/jsp/main.jsp\";\r\n public static fina",
"end": 14884,
"score": 0.5073617100715637,
"start": 14884,
"tag": "IP_ADDRESS",
"value": ""
},
{
"context": "ublic static final String DMS_IP = \"http://10.33.89.37/dms/jsp/main.jsp\";\r\n public static final ",
"end": 14887,
"score": 0.5151446461677551,
"start": 14886,
"tag": "IP_ADDRESS",
"value": "9"
}
] | null | [] | package com.tmind.mss.pub.constants;
import com.tmind.framework.pub.web.BaseFrameworkApplication;
//记录系统常量
public class DmsConstants {
public static final int COUNT_FOR_EVERY_PAGE = 10;//每业显示条数
// tables name in hql
public static final String MOD_MATERIAL_REQ = "com.tmind.dms.pub.po.DmsModStatistics";
public static final String C_USER_INFO = "com.tmind.dms.pub.po.CUserInfo";
public static final String C_ORG_NJ = "com.tmind.dms.pub.po.COrganizationNj";
public static final String DMS_MATERIAL_STATISTICS = "com.tmind.dms.pub.po.DmsMaterialStatistics";
public static final String DMS_STA_CONTENT = "com.tmind.dms.pub.po.DmsStaContent";
public static final String DMS_MATERIAL_INFO = "com.tmind.dms.pub.po.DmsMaterialInfo";
public static final String C_ORG_NJ_TYPE = "com.tmind.dms.pub.po.COrganizationType";
public static final String C_ORG_NJ_TYPE_ID = "com.tmind.dms.pub.po.COrganizationTypeId";
public static final String DMS_USER_PROPERTY = "com.tmind.dms.pub.po.DmsUserProperty";
//关帐
public static final String DMS_ACCOUNT_CLOSE = "C";
//调帐开始时间
public static final String DMS_MOD_ACCOUNT_START_TIME = "MS";
//调帐开始时间
public static final String DMS_MOD_ACCOUNT_END_TIME = "MN";
//物料申领开始时间
public static final String DMS_MATERIAL_APP_START_TIME = "RS";
//物料申领结束时间
public static final String DMS_MATERIAL_APP_END_TIME = "RN";
//营业厅未入库告警时限
public static final String DMS_MATERIAL_NOTIN_BUSS_ALARM = "BJ";
//营业厅未入库上级告警时限
public static final String DMS_MATERIAL_NOTIN_LEAD_ALARM = "SJ";
//物料有效期
public static final String DMS_MATERIAL_EFFECT_TIME = "YX";
//系统短信发送时间
public static final String DMS_SMS_SEND_TIME = "SS";
//库房
public static final String CLOSE_OBJECT_NAME_DEPOT = "DEPOT";
//区域
public static final String CLOSE_OBJECT_NAME_AREA = "AREA";
//营业厅
public static final String CLOSE_OBJECT_NAME_BUSS = "BUSS";
public static final String DMS_MATERIAL_FLOW_INFO = "com.tmind.dms.pub.po.DmsMaterialFlowInfo";
public static final String DMS_MATERIAL_RELATION = "com.tmind.dms.pub.po.DmsMaterielRelation";
public static final String DMS_MATERIAL_TOTAL_INFO = "com.tmind.dms.pub.po.DmsFlowTotalInfo";
// form type 单据类型
public static final Long FORM_TYPE_REQUIRE = new Long(0);//物料需求单
public static final Long FORM_TYPE_APPLY = new Long(1);//物料申领
public static final Long FORM_TYPE_EXPORT = new Long(2);//物料出库单
public static final Long FORM_TYPE_BACK = new Long(3);//物料退库单
public static final Long FORM_TYPE_HANDOUT = new Long(4);//统一下发单
public static final Long FORM_TYPE_CUS_BACK = new Long(5);//顾客退库单
public static final Long FORM_TYPE_IMPORT = new Long(6);//物料入库单
public static final Long FORM_TYPE_BACK_APPLY = new Long(7);//物料退库申请单
public static final Long FORM_TYPE_CUS_EXPORT = new Long(8);//顾客出库单
public static final Long FORM_TYPE_SUB_BACK = new Long(9);//下级退库入库单
public static final Long FORM_TYPE_HELP_BACK_APPLY = new Long(10);//调配退库申请单
public static final Long FORM_TYPE_HELP_BACK = new Long(11);//调配退库单
public static final Long FORM_TYPE_HELP_SELF_IMPORT = new Long(12);//本区调配入库单
public static final Long FORM_TYPE_HELP_OTHER_IMPORT = new Long(13);//别区调配入库单
public static final Long FORM_TYPE_HELP_OUT = new Long(14);//外协出库单
public static final Long FORM_TYPE_WASTE_OUT = new Long(15);//损耗出库单
public static final Long FORM_TYPE_DIS_IMPORT = new Long(16);//差异量补入单
public static final Long FORM_TYPE_DIS_BACK_APPLY = new Long(17);//差异量退库申请单
public static final Long FORM_TYPE_DIS_BACK = new Long(18);//差异量退库单
public static final Long FORM_TYPE_CONVERT_OUT = new Long(19);//活动类型转换出库单
public static final Long FORM_TYPE_CONVERT_IMPORT = new Long(20);//活动类型转换入库单
public static final Long FORM_TYPE_HANDOUT_CONFIG = new Long(21);//模板配置统一下发单
public static final Long FORM_TYPE_ADJUST_BACK = new Long(22);//调配中转入库单
public static final Long FORM_TYPE_ADJUST_OUT = new Long(23);//调配出库单
public static final Long FORM_TYPE_HANDOUT_CONFIG_TEMP = new Long(24);//模板配置统一下发临时出库
public static final Long FORM_TYPE_MAT_CLEAR_ZERO = new Long(25);//物料清零申请单
public static final Long FORM_TYPE_DIFF_CLEAR_ZERO = new Long(26);//差异量清零申请单
//调配入库退回所添加的单据类型
public static final Long FORM_TYPE_ADJUST_OUT_BACK_APPLY = new Long(27); //调配入库退回申请单
public static final Long FORM_TYPE_ADJUST_OUT_BACK = new Long(28); //调配入库退回单
public static final Long FORM_TYPE_ADJUST_BACK_IMPORT = new Long(29); //调配退回入库
public static final Long FROM_TYPE_ADJUST_IMPORT_AGAIN = new Long(30); //调配2次入库
//操作类型
public static final Long OPER_TYPE_REQUIRE = new Long(0);//物料需求单
public static final Long OPER_TYPE_APPLY = new Long(1);//物料申领
public static final Long OPER_TYPE_EXPORT = new Long(2);//物料出库单
public static final Long OPER_TYPE_BACK = new Long(3);//物料退库单
public static final Long OPER_TYPE_HANDOUT = new Long(4);//统一下发单
public static final Long OPER_TYPE_CUS_BACK = new Long(5);//顾客退库单
public static final Long OPER_TYPE_IMPORT = new Long(6);//物料入库单
public static final Long OPER_TYPE_BACK_APPLY = new Long(7);//物料退库申请单
public static final Long OPER_TYPE_CUS_EXPORT = new Long(8);//顾客出库单
public static final Long OPER_TYPE_BACK_IMPORT = new Long(9);//下级退库入库单
public static final Long OPER_TYPE_HELP_BACK_APPLY = new Long(10);//调配退库申请单
public static final Long OPER_TYPE_HELP_BACK = new Long(11);//调配退库单
public static final Long OPER_TYPE_HELP_SELF_IMPORT = new Long(12);//本区调配入库单
public static final Long OPER_TYPE_HELP_OTHER_IMPORT = new Long(13);//别区调配入库单
public static final Long OPER_TYPE_HELP_OUT = new Long(14);//外协出库单
public static final Long OPER_TYPE_WASTE_OUT = new Long(15);//损耗出库单
public static final Long OPER_TYPE_DIS_IMPORT = new Long(16);//差异量补入单
public static final Long OPER_TYPE_DIS_BACK_APPLY = new Long(17);//差异量退库申请单
public static final Long OPER_TYPE_DIS_BACK = new Long(18);//差异量退库单
public static final Long OPER_TYPE_CONVERT_OUT = new Long(19);//活动类型转换出库单
public static final Long OPER_TYPE_CONVERT_IMPORT = new Long(20);//活动类型转换入库单
public static final Long OPER_TYPE_HANDOUT_CONFIG = new Long(21);//模板配置统一下发单
public static final Long OPER_TYPE_ADJUST_BACK = new Long(22);//调配中转入库单
public static final Long OPER_TYPE_ADJUST_OUT = new Long(23);//调配出库单
public static final Long OPER_TYPE_DIFF_CLEAR_ZERO = new Long(25);//差异量清零申请单
public static final Long OPER_TYPE_HANDOUT_CONFIG_TEMP = new Long(26);//模板配置统一下发临时出库
//调配入库退回所添加的操作
public static final Long OPER_TYPE_ADJUST_OUT_BACK_APPLY = new Long(27); //调配入库退回申请单
public static final Long OPER_TYPE_ADJUST_OUT_BACK = new Long(28); //调配入库退回单
public static final Long OPER_TYPE_ADJUST_BACK_IMPORT = new Long(29); //调配退回入库
public static final Long OPER_TYPE_ADJUST_IMPORT_AGAIN = new Long(30); //调配2次入库
//记录单据状态
public static final Long FORM_STATUS_SAVE = new Long(1);//保存
public static final Long FORM_STATUS_SUBMIT = new Long(2);//提交
public static final Long FORM_STATUS_BACK = new Long(3);//退回
public static final Long FORM_STATUS_STAY = new Long(4);//暂留
public static final Long FORM_STATUS_FINISH = new Long(5);//完成
public static final Long FORM_STATUS_DISABLE = new Long(6);//作废
public static final Long FORM_STATUS_EXAMINED = new Long(7);//已审批
//流水状态
public static final String FLOW_STATE_SUBMIT = "S";//提交
public static final String FLOW_STATE_FINISH = "F";//完成
public static final String FLOW_STATE_BACK = "B";//退回(目前在调配入库退回中使用)
//短信模版类型
public static final Long SMS_TEMP_TYPE_OUT = new Long(1);//出库
public static final Long SMS_TEMP_TYPE_APPLY = new Long(0);//申领
public static final Long SMS_TEMP_TYPE_NOT_IMPORT = new Long(2);//未入库
public static final Long SMS_TEMP_TYPE_NOT_EXPORT = new Long(3);//未出库
public static final Long SMS_TEMP_TYPE_OVERDUE= new Long(4);//过期
public static final Long SMS_TEMP_TYPE_LACK = new Long(5);//库存不足
// 出账报表excel文件导出目录
public static final String REPORTFORMDOWNPATH = BaseFrameworkApplication.FrameworkWebAppRootPath+"dms/jsp/statistics/";
//订单状态
public static final int SAVE_REQ_INFO = 1; //保存
public static final int SAVE_AS_REQUIRE_REQ_INFO = 2; //保存为需求但
public static final int SUBMIT_REQ_INFO = 3; //提交
public static final int NO_BUDGET_REQ_INFO = 4; //无预算
public static final int HANDLE_REQ_INFO = 5; //处理中
public static final int FINISH_REQ_INFO = 6; //完成
public static final int DISABLE_REQ_INFO = 7; //作废
//订单操作步骤
public static final int INDENT_SAVE_SUCCED = 1; //保存订货单
public static final int MAIL_CONNECT_FAILE = 2; //邮件服务器连接不上
public static final int ORDER_SEND_SUCCED = 3; //订单生成
//订单类型
public static final int ORDER_TYPE_COMMON = 1; //普通订货单
public static final int ORDER_TYPE_NET = 2; //网络设备订货单
public static final int ORDER_TYPE_BUY = 3; //购货单
public static final int ORDER_TYPE_CONTR= 4; //签订合同
public static final int ORDER_TYPE_COMP = 5; //招标比价
public static final int ORDER_TYPE_BUS = 6; //营业厅订单
//采购品状态
public static final int MATE_STATE_WAIT_CONTR = 0; //待签合同
public static final int MATE_STATE_WAIT_DISTR = 1; //待分发
public static final int MATE_STATE_WAIT_HANDLE = 2; //待处理
public static final int MATE_STATE_WAIT_PAY= 3; //待付款
public static final int MATE_STATE_WAIT_FINISH = 4; //完成
public static final int MATE_STATE_DISABLE = 5; //作废
//订单状态
public static final String ORDER_STATE_AVAILABLE = "A"; //有效
public static final String ORDER_STATE_UNAVAILABLE = "U"; //无效
public static final String ORDER_STATE_PIGONHOLE = "2"; //已归档
public static final String ORDER_STATE_UNPIGONHOLE = "1"; //未归档
//短信提醒类型
public static final int MESSAGE_TYPE_APPLY = 0; //物料申领
public static final int MESSAGE_TYPE_HANDOUT = 1;//物品统一下发
public static final int MESSAGE_TYPE_NOIMPORT = 2;//时限为入库
public static final int MESSAGE_TYPE_NOEXPORT = 3;//时限未出库
public static final int MESSAGE_TYPE_OVERDUE = 4;//物料过期
public static final int MESSAGE_TYPE_LACK = 5;//库存量不足
//短信内容状态
public static final String MESSAGE_STATE_NOSEND = "N"; //未发送
public static final String MESSAGE_STATE_ALSEND = "Y"; //已发送
//短信内容提醒--宏
public static final String MESSAGE_MACRO_DATE = "date"; //日期
public static final String MESSAGE_MACRO_UPPERORG = "upperOrg"; //上级
public static final String MESSAGE_MACRO_LOWERORG = "lowerOrg"; //下级
public static final String MESSAGE_MACRO_GOODSINFO = "goodsInfo"; //物品
public static final String MESSAGE_MACRO_ORGNAME = "orgName"; //营业厅名称
public static final String MESSAGE_MACRO_TIMELIMIT = "timeLimit"; //时间期限
//操作类型--联系信息更新
public static final Long LINK_UPDATE_TYPE_ORG = new Long(0);
public static final Long LINK_UPDATE_TYPE_AREA = new Long(1);
public static final Long LINK_UPDATE_TYPE_ORG_CLEAR = new Long(2);
//用户层级
public static final String LEVEL_MASTERMIND = "-1";//策划组
public static final String LEVEL_DEPOT = "0";//库房
public static final String LEVEL_CANTONAL_CENTER_OR_COUNTY_COMPANY = "1";//市区营销中心/县公司
public static final String LEVEL_AREA = "2";//区域
//物料大类
public static final String WHOLE_TYPE_YINGXIAO = "1";//营销类
public static final String WHOLE_TYPE_PROJECT = "2";//工程类
public static final String WHOLE_TYPE_PERMANENT_ASSETS = "3";//固定资产类
public static final String WHOLE_TYPE_NOT_PERMANENT_ASSETS_A = "4";//非固定资产A类
public static final String WHOLE_TYPE_NOT_PERMANENT_ASSETS_B = "5";//非固定资产B类
//物料状态记录(需求物料流水)中物料状态(MATERIAL_STATE)状态
public static final String MATERIAL_STATE_SAVE = "1";//1.保存;
public static final String MATERIAL_STATE_SUBMIT = "2";//2.待审批;
public static final String MATERIAL_STATE_BACK = "3";//3.退回;
public static final String MATERIAL_STATE_OUT = "4";//4.待入库;
public static final String MATERIAL_STATE_TO_SUM = "5";//5.待汇总;
public static final String MATERIAL_STATE_SUM = "6";//6.已汇总;
public static final String MATERIAL_STATE_REQ = "7";//7.已请购;
public static final String MATERIAL_STATE_TO_IN = "8";//8.待收货;
public static final String MATERIAL_STATE_DONE = "9";//9.完成。
public static final String MATERIAL_STATE_TO_REQ = "0";//0.待请购。
//物料状态记录(需求物料流水)中当前物料所处层级(CURR_LEVEL)
public static final String MATER_CURR_LEVEL_ORG = "1";//1 营业厅
public static final String MATER_CURR_LEVEL_AREA = "2";//2 区域
public static final String MATER_CURR_LEVEL_CENTER = "3";//3 市区营销中心
public static final String MATER_CURR_LEVEL_MART = "4";//4 市场部
//物料状态记录(需求物料流水)中各层级操作单类型,同操作总记录表中操作类型(OPER_TEYP)
public static final String OPER_TEYP_APPLY_SUBMIT = "1";//1 物料申请
public static final String OPER_TEYP_MATER_OUT = "2";//2 物料下发
public static final String OPER_TEYP_MATER_BACK = "3";//3 物料退回
public static final String OPER_TEYP_APPLY_SUM = "4";//4 物料汇总
public static final String OPER_TEYP_APPLY_REQ = "5";//5 物料请购
public static final String OPER_TEYP_MATER_IN = "6";//6 物料入库
//操作总记录表中操作单状态(OPER_STATE)
public static final String MATER_OPER_STATE_SAVE = "0";//0 保存
public static final String MATER_OPER_STATE_TO_DONE = "1";//1 待处理
public static final String MATER_OPER_STATE_DOING = "2";//2 处理中
public static final String MATER_OPER_STATE_DONE = "3";//3 已处理
// 全部县公司的TYPE
public static final String COUNTY_ALL_TYPE = "'57','58','59','60','61'";
//全部区域的TYPE
public static final String AREA_ALL_TYPE = "'51','52','53','54','55'";
public static final String DMS_IP_TEST = "http://192.168.16.30/dms/jsp/main.jsp";
public static final String DMS_IP_TEST_2 = "http://10.33.89.37:8899/dms/jsp/main.jsp";
public static final String MPMS_IP_TEST = "http://10.33.32.87:8899/mpms/mpms/jsp/main.jsp";
public static final String DMS_IP = "http://10.33.89.37/dms/jsp/main.jsp";
public static final String MPMS_IP = "http://10.33.32.87:88/mpms/mpms/jsp/main.jsp";
}
| 17,080 | 0.658585 | 0.639803 | 280 | 51.621429 | 30.804213 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.853571 | false | false | 2 |
d8eddabf40c205bdb33b37a9ff4167d22a2370dd | 9,869,834,885,084 | 4ea2481c636d340a6a682dff33e0bd3cf3f46b83 | /app/src/main/java/teamtreehouse/com/iamhere/WeatherInformation.java | 30aa5b40545301102804496bcb2e887ee5982e8e | [] | no_license | fiek2016/IamHere | https://github.com/fiek2016/IamHere | ad421c7df3b42904f20c70a7a3d895c6c5ef93de | 75a395d3d023b3fefdde29ba6aaa50183f79b71f | refs/heads/master | 2017-12-30T00:51:13.273000 | 2016-09-21T17:43:22 | 2016-09-21T17:43:22 | 68,842,439 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package teamtreehouse.com.iamhere;
public class WeatherInformation {
private int id;
private String cityName, temp, time;
public WeatherInformation() {
super();
}
public WeatherInformation(int id, String name, String temperature, String time) {
super();
this.id = id;
this.cityName = name;
this.temp = temperature;
this.time = time;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
WeatherInformation other = (WeatherInformation) obj;
if (id != other.id)
return false;
return true;
}
@Override
public String toString() {
return "Product [id=" + id + ", City=" + cityName + ", Temperature="
+ temp + ", Time=" + time + "]";
}
}
| UTF-8 | Java | 1,359 | java | WeatherInformation.java | Java | [] | null | [] | package teamtreehouse.com.iamhere;
public class WeatherInformation {
private int id;
private String cityName, temp, time;
public WeatherInformation() {
super();
}
public WeatherInformation(int id, String name, String temperature, String time) {
super();
this.id = id;
this.cityName = name;
this.temp = temperature;
this.time = time;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
WeatherInformation other = (WeatherInformation) obj;
if (id != other.id)
return false;
return true;
}
@Override
public String toString() {
return "Product [id=" + id + ", City=" + cityName + ", Temperature="
+ temp + ", Time=" + time + "]";
}
}
| 1,359 | 0.645327 | 0.64312 | 81 | 15.777778 | 16.19404 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.654321 | false | false | 2 |
b1bf034b23162aac845cf5898b1686eb5a779c53 | 23,192,823,468,442 | 1a9142b3de91dfd0d98f9bdf05c1ea0260511fd0 | /src/rebound/text/UCS4CodePoint.java | eae6f40a20fddd482874a0e76cd8daa69e1dbf09 | [] | no_license | PuppyPi/rebound-core | https://github.com/PuppyPi/rebound-core | bd2ae8cc56fdc5fec1ab1646601d250bc4895547 | 16cce813163a170a405306b5c43116723fa3d76c | refs/heads/master | 2023-07-27T05:07:01.710000 | 2023-07-14T21:34:59 | 2023-07-14T21:34:59 | 176,217,975 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package rebound.text;
import rebound.annotations.semantic.simpledata.ActuallyUnsigned;
public class UCS4CodePoint
{
protected final int codeUnit;
public UCS4CodePoint(@ActuallyUnsigned int codeUnit)
{
this.codeUnit = codeUnit;
}
public @ActuallyUnsigned int getCodeUnit()
{
return codeUnit;
}
/**
* This will always be just the codepoint (other code may rely on this being true!!)
*/
@Override
public int hashCode()
{
return codeUnit;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UCS4CodePoint other = (UCS4CodePoint) obj;
if (codeUnit != other.codeUnit)
return false;
return true;
}
@Override
public String toString()
{
return "'"+StringUtilities.ucs4ToUTF16String(new int[]{this.codeUnit})+"'";
}
}
| UTF-8 | Java | 883 | java | UCS4CodePoint.java | Java | [] | null | [] | package rebound.text;
import rebound.annotations.semantic.simpledata.ActuallyUnsigned;
public class UCS4CodePoint
{
protected final int codeUnit;
public UCS4CodePoint(@ActuallyUnsigned int codeUnit)
{
this.codeUnit = codeUnit;
}
public @ActuallyUnsigned int getCodeUnit()
{
return codeUnit;
}
/**
* This will always be just the codepoint (other code may rely on this being true!!)
*/
@Override
public int hashCode()
{
return codeUnit;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UCS4CodePoint other = (UCS4CodePoint) obj;
if (codeUnit != other.codeUnit)
return false;
return true;
}
@Override
public String toString()
{
return "'"+StringUtilities.ucs4ToUTF16String(new int[]{this.codeUnit})+"'";
}
}
| 883 | 0.693092 | 0.685164 | 49 | 17.020409 | 20.121559 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.489796 | false | false | 2 |
578d532cca859e9c0d4cf4bf002e077bc5167dd6 | 34,428,457,870,266 | 613862a8701bbef5327fe5142f26d2cdb6a8e24e | /src/SystemNpruPool/ConnectDB.java | a94226915b706124236da4a35f66cea04c43f3b2 | [] | no_license | nopindy135/MyApp | https://github.com/nopindy135/MyApp | 10a02e49aa0aa416440de2ad6fc70c9f04d61490 | 3d7424dec26994b8dea18a701ce84db964324ba6 | refs/heads/master | 2021-01-10T05:49:54.736000 | 2016-03-17T20:48:25 | 2016-03-17T20:48:25 | 51,521,992 | 0 | 1 | null | false | 2016-02-13T12:26:33 | 2016-02-11T15:01:03 | 2016-02-11T15:04:56 | 2016-02-13T12:21:23 | 200 | 0 | 1 | 1 | Java | null | null | /*
* 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 SystemNpruPool;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author Godonlyknows
*/
public interface ConnectDB {
String usernameDB = "root";
String passwordDB = "";
// Connection connect = null;
String urlConnection = "jdbc:mysql://127.0.0.1:3306/npru_pool?useUnicode=true&characterEncoding=UTF-8";
}
| UTF-8 | Java | 659 | java | ConnectDB.java | Java | [
{
"context": "ion;\nimport java.sql.Statement;\n\n/**\n *\n * @author Godonlyknows\n */\npublic interface ConnectDB {\n String usern",
"end": 417,
"score": 0.9994441270828247,
"start": 405,
"tag": "USERNAME",
"value": "Godonlyknows"
},
{
"context": " = null;\n String urlConnection = \"jdbc:mysql://127.0.0.1:3306/npru_pool?useUnicode=true&characterEncoding=",
"end": 594,
"score": 0.9994263052940369,
"start": 585,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | null | [] | /*
* 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 SystemNpruPool;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author Godonlyknows
*/
public interface ConnectDB {
String usernameDB = "root";
String passwordDB = "";
// Connection connect = null;
String urlConnection = "jdbc:mysql://127.0.0.1:3306/npru_pool?useUnicode=true&characterEncoding=UTF-8";
}
| 659 | 0.732929 | 0.716237 | 26 | 24.346153 | 25.139523 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false | 2 |
44353d58bf282c0c6642c1d8c771a83abee62bbd | 34,411,278,005,886 | ce7f903717967b26a7de5ed99ccf560a4e1971f2 | /src/main/java/com/sample/configuration/SoapClient.java | 824bd22ec3014e2ae822e9f74d4ec2d2e49317a3 | [] | no_license | noelnole/Wsdl-observer | https://github.com/noelnole/Wsdl-observer | fc15b29718007c2fb35b8a4ae56ab1c49b7843ae | 440b4dc717a657569d984e314ab40e7b0f5a4eca | refs/heads/master | 2021-01-19T11:17:57.630000 | 2017-04-12T15:48:38 | 2017-04-12T15:48:38 | 87,953,511 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sample.configuration;
import hello.wsdl.GetQuote;
import hello.wsdl.GetQuoteResponse;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import org.springframework.ws.soap.client.SoapFaultClientException;
import org.springframework.ws.soap.client.core.SoapActionCallback;
import javax.annotation.PostConstruct;
/**
* This class extends from WebServiceGatewaySupport to return a GetQuoteReponse.
* An alternative of this impletation could be using generic class:
* SoapClient<R,T> with this clase we can avoid use GetQuoteResponse
* and use R as the response and T how the request
*
* @author Noel Rodriguez
*/
@Slf4j
public abstract class SoapClient extends WebServiceGatewaySupport {
@Autowired
private Jaxb2Marshaller marshaller;
public GetQuoteResponse marshalSendAndReceive(String ticker) {
GetQuote request = new GetQuote();
request.setSymbol(ticker);
try {
return (GetQuoteResponse) getWebServiceTemplate().marshalSendAndReceive("http://www.webservicex.com/stockquote.asmx",
request,
new SoapActionCallback("http://www.webserviceX.NET/GetQuote"));
} catch (SoapFaultClientException e) {
logger.error("Error", e);
return null;
}
}
@PostConstruct
private void init() {
setMarshaller(marshaller);
setUnmarshaller(marshaller);
}
} | UTF-8 | Java | 1,627 | java | SoapClient.java | Java | [
{
"context": "s the response and T how the request\n *\n * @author Noel Rodriguez\n */\n@Slf4j\npublic abstract class SoapClient exten",
"end": 836,
"score": 0.999875545501709,
"start": 822,
"tag": "NAME",
"value": "Noel Rodriguez"
}
] | null | [] | package com.sample.configuration;
import hello.wsdl.GetQuote;
import hello.wsdl.GetQuoteResponse;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import org.springframework.ws.soap.client.SoapFaultClientException;
import org.springframework.ws.soap.client.core.SoapActionCallback;
import javax.annotation.PostConstruct;
/**
* This class extends from WebServiceGatewaySupport to return a GetQuoteReponse.
* An alternative of this impletation could be using generic class:
* SoapClient<R,T> with this clase we can avoid use GetQuoteResponse
* and use R as the response and T how the request
*
* @author <NAME>
*/
@Slf4j
public abstract class SoapClient extends WebServiceGatewaySupport {
@Autowired
private Jaxb2Marshaller marshaller;
public GetQuoteResponse marshalSendAndReceive(String ticker) {
GetQuote request = new GetQuote();
request.setSymbol(ticker);
try {
return (GetQuoteResponse) getWebServiceTemplate().marshalSendAndReceive("http://www.webservicex.com/stockquote.asmx",
request,
new SoapActionCallback("http://www.webserviceX.NET/GetQuote"));
} catch (SoapFaultClientException e) {
logger.error("Error", e);
return null;
}
}
@PostConstruct
private void init() {
setMarshaller(marshaller);
setUnmarshaller(marshaller);
}
} | 1,619 | 0.732637 | 0.728334 | 48 | 32.916668 | 28.842123 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.479167 | false | false | 2 |
2f40d38f32bcf1f3e4e9e77a37aa742889cb8150 | 15,401,752,729,573 | ce487e3714fcefa3abd05c398e647803cfc4b5d4 | /AlgorithmsImplementation/src/ChocolateFeast.java | 344e502e49ce5dbfc523d5bb4b01dacdbedbc91b | [] | no_license | natnayr/HackerRank | https://github.com/natnayr/HackerRank | f2b73a522b4695498b83cc3491b492f1e7375319 | cf665f513fcce5d6bca63b3147e5b9f394146f8f | refs/heads/master | 2021-01-10T07:00:15.225000 | 2016-02-09T11:13:35 | 2016-02-09T11:13:35 | 47,095,819 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class ChocolateFeast {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int T = in.nextInt();
while(T > 0){
int N = in.nextInt();
int C = in.nextInt();
int M = in.nextInt();
int chocCount = N/C;
int wrapperCount = chocCount;
while(wrapperCount >= M){
int newChoc = (wrapperCount/M);
wrapperCount = (wrapperCount%M) + newChoc;
chocCount += newChoc;
}
System.out.println(chocCount);
}
}
}
| UTF-8 | Java | 551 | java | ChocolateFeast.java | Java | [] | null | [] | import java.util.Scanner;
public class ChocolateFeast {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int T = in.nextInt();
while(T > 0){
int N = in.nextInt();
int C = in.nextInt();
int M = in.nextInt();
int chocCount = N/C;
int wrapperCount = chocCount;
while(wrapperCount >= M){
int newChoc = (wrapperCount/M);
wrapperCount = (wrapperCount%M) + newChoc;
chocCount += newChoc;
}
System.out.println(chocCount);
}
}
}
| 551 | 0.618875 | 0.61706 | 28 | 18.678572 | 14.711641 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.571429 | false | false | 2 |
4ce7680223f9ddd5e8963931d10d6a0e594d1398 | 644,245,096,233 | 5b57ac8b13747a75d822ba1ee0475270f7f79ee7 | /app/src/main/java/im/kirillt/yandexmoneyclient/MainActivity.java | d882711a20ac26e120823c614ec7da3b2547cf72 | [] | no_license | KirillTim/YandexMoneyClient | https://github.com/KirillTim/YandexMoneyClient | abdf2bb48e76e5561c8ed5c937fd4fe81c6cf4ed | 4c72da3f1119b39e0f1cd593a0fbc5c427fff6d0 | refs/heads/master | 2020-04-11T09:55:08.435000 | 2015-10-04T19:05:23 | 2015-10-04T19:05:23 | 42,479,139 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package im.kirillt.yandexmoneyclient;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.io.IOException;
import de.greenrobot.event.EventBus;
import im.kirillt.yandexmoneyclient.events.AnyErrorEvent;
import im.kirillt.yandexmoneyclient.events.IncomingTransferProcessResultEvent;
import im.kirillt.yandexmoneyclient.events.download.DownloadAllEvent;
import im.kirillt.yandexmoneyclient.fragments.AboutFragment;
import im.kirillt.yandexmoneyclient.fragments.HistoryFragment;
import im.kirillt.yandexmoneyclient.fragments.MainFragment;
import im.kirillt.yandexmoneyclient.fragments.SettingsFragment;
public class MainActivity extends BaseActivity {
private DrawerLayout drawerLayout;
private MenuItem curMenuItemId = null;
private Menu menu = null;
private Fragment currentFragment;
private LinearLayout toolBarInnerView;
private FloatingActionButton mainFab;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("MainActivity", "onCreate()");
super.onCreate(savedInstanceState);
/* if (!YMCApplication.auth2Session.isAuthorized()) {
Toast.makeText(this, "You are not authorized", Toast.LENGTH_SHORT).show();
YMCApplication.deleteToken(this);
finish();
}*/
setContentView(R.layout.activity_main);
mainFab = (FloatingActionButton)findViewById(R.id.activity_main_fab);
initToolbar();
initDrawerLayout();
currentFragment = MainFragment.newInstance();
getSupportFragmentManager().beginTransaction().add(R.id.activity_main_fragment, currentFragment).commit();
}
private void initToolbar() {
toolBarInnerView = (LinearLayout) findViewById(R.id.account_info_container);
toolBarInnerView.setVisibility(View.GONE);
final Toolbar toolbar = (Toolbar) findViewById(R.id.activity_main_toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp);
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
private void initDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView view = (NavigationView) findViewById(R.id.navigation_view);
view.setNavigationItemSelectedListener(menuItem -> {
selectDrawerItem(menuItem);
menuItem.setChecked(true);
drawerLayout.closeDrawers();
setTitle(menuItem.getTitle());
return true;
});
menu = view.getMenu();
curMenuItemId = menu.getItem(0);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void selectDrawerItem(MenuItem menuItem) {
if (menuItem == curMenuItemId) {
return ;
}
curMenuItemId = menuItem;
switch(menuItem.getItemId()) {
case R.id.drawer_home:
currentFragment = MainFragment.newInstance();
break;
case R.id.drawer_pay:
curMenuItemId = menu.getItem(0);
PaymentActivity.startActivity(MainActivity.this);
break;
case R.id.drawer_history:
currentFragment = HistoryFragment.newInstance();
break;
case R.id.drawer_settings:
currentFragment = SettingsFragment.newInstance();
break;
case R.id.drawer_about:
currentFragment = AboutFragment.newInstance();
break;
default:
currentFragment = MainFragment.newInstance();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.activity_main_fragment, currentFragment).commit();
}
@Override
public void onStart() {
Log.i("MainActivity", "onStart()");
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
Log.i("MainActivity", "onStop()");
EventBus.getDefault().unregister(this);
super.onStop();
}
public void onEventMainThread(AnyErrorEvent errorEvent) {
if (errorEvent.getException() instanceof IOException) {
Toast.makeText(this, getString(R.string.net_error),Toast.LENGTH_SHORT).show();
}
}
public void onEventAsync(DownloadAllEvent event) {
event.download();
}
public void onEventMainThread(IncomingTransferProcessResultEvent event) {
Toast.makeText(this, event.result, Toast.LENGTH_SHORT).show();
}
public LinearLayout getToolBarInnerView() {
return toolBarInnerView;
}
public FloatingActionButton getFab() {
return mainFab;
}
}
| UTF-8 | Java | 5,648 | java | MainActivity.java | Java | [] | null | [] | package im.kirillt.yandexmoneyclient;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.io.IOException;
import de.greenrobot.event.EventBus;
import im.kirillt.yandexmoneyclient.events.AnyErrorEvent;
import im.kirillt.yandexmoneyclient.events.IncomingTransferProcessResultEvent;
import im.kirillt.yandexmoneyclient.events.download.DownloadAllEvent;
import im.kirillt.yandexmoneyclient.fragments.AboutFragment;
import im.kirillt.yandexmoneyclient.fragments.HistoryFragment;
import im.kirillt.yandexmoneyclient.fragments.MainFragment;
import im.kirillt.yandexmoneyclient.fragments.SettingsFragment;
public class MainActivity extends BaseActivity {
private DrawerLayout drawerLayout;
private MenuItem curMenuItemId = null;
private Menu menu = null;
private Fragment currentFragment;
private LinearLayout toolBarInnerView;
private FloatingActionButton mainFab;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("MainActivity", "onCreate()");
super.onCreate(savedInstanceState);
/* if (!YMCApplication.auth2Session.isAuthorized()) {
Toast.makeText(this, "You are not authorized", Toast.LENGTH_SHORT).show();
YMCApplication.deleteToken(this);
finish();
}*/
setContentView(R.layout.activity_main);
mainFab = (FloatingActionButton)findViewById(R.id.activity_main_fab);
initToolbar();
initDrawerLayout();
currentFragment = MainFragment.newInstance();
getSupportFragmentManager().beginTransaction().add(R.id.activity_main_fragment, currentFragment).commit();
}
private void initToolbar() {
toolBarInnerView = (LinearLayout) findViewById(R.id.account_info_container);
toolBarInnerView.setVisibility(View.GONE);
final Toolbar toolbar = (Toolbar) findViewById(R.id.activity_main_toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp);
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
private void initDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView view = (NavigationView) findViewById(R.id.navigation_view);
view.setNavigationItemSelectedListener(menuItem -> {
selectDrawerItem(menuItem);
menuItem.setChecked(true);
drawerLayout.closeDrawers();
setTitle(menuItem.getTitle());
return true;
});
menu = view.getMenu();
curMenuItemId = menu.getItem(0);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void selectDrawerItem(MenuItem menuItem) {
if (menuItem == curMenuItemId) {
return ;
}
curMenuItemId = menuItem;
switch(menuItem.getItemId()) {
case R.id.drawer_home:
currentFragment = MainFragment.newInstance();
break;
case R.id.drawer_pay:
curMenuItemId = menu.getItem(0);
PaymentActivity.startActivity(MainActivity.this);
break;
case R.id.drawer_history:
currentFragment = HistoryFragment.newInstance();
break;
case R.id.drawer_settings:
currentFragment = SettingsFragment.newInstance();
break;
case R.id.drawer_about:
currentFragment = AboutFragment.newInstance();
break;
default:
currentFragment = MainFragment.newInstance();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.activity_main_fragment, currentFragment).commit();
}
@Override
public void onStart() {
Log.i("MainActivity", "onStart()");
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
Log.i("MainActivity", "onStop()");
EventBus.getDefault().unregister(this);
super.onStop();
}
public void onEventMainThread(AnyErrorEvent errorEvent) {
if (errorEvent.getException() instanceof IOException) {
Toast.makeText(this, getString(R.string.net_error),Toast.LENGTH_SHORT).show();
}
}
public void onEventAsync(DownloadAllEvent event) {
event.download();
}
public void onEventMainThread(IncomingTransferProcessResultEvent event) {
Toast.makeText(this, event.result, Toast.LENGTH_SHORT).show();
}
public LinearLayout getToolBarInnerView() {
return toolBarInnerView;
}
public FloatingActionButton getFab() {
return mainFab;
}
}
| 5,648 | 0.671565 | 0.669618 | 163 | 33.650307 | 25.234734 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.613497 | false | false | 2 |
df0f89c1e5e0b0811a32cf57f82c1df9ae6dca1f | 3,427,383,946,713 | 78eb7211bf2e2446fd1e6e910a7cdee6186c505e | /configuration/src/main/java/org/openhie/openempi/configuration/xml/singlebestrecord/impl/SingleBestRecordDocumentImpl.java | 6a0b743bf4f93c851c58b4048b246adfcc041152 | [] | no_license | okuneyegabriel/os-cr | https://github.com/okuneyegabriel/os-cr | d2ce962cc09f3302a6ee3b485b18459081e93fd4 | 0b33f97a38cb02da20480ffa45518c1d1c977db3 | refs/heads/master | 2021-01-20T03:03:49.645000 | 2015-12-10T16:02:44 | 2015-12-10T16:02:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* An XML document type.
* Localname: single-best-record
* Namespace: http://configuration.openempi.openhie.org/single-best-record
* Java type: org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordDocument
*
* Automatically generated - do not modify.
*/
package org.openhie.openempi.configuration.xml.singlebestrecord.impl;
/**
* A document containing one single-best-record(@http://configuration.openempi.openhie.org/single-best-record) element.
*
* This is a complex type.
*/
public class SingleBestRecordDocumentImpl extends org.openhie.openempi.configuration.xml.impl.SingleBestRecordDocumentImpl implements org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordDocument
{
public SingleBestRecordDocumentImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName SINGLEBESTRECORD$0 =
new javax.xml.namespace.QName("http://configuration.openempi.openhie.org/single-best-record", "single-best-record");
/**
* Gets the "single-best-record" element
*/
public org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType getSingleBestRecord()
{
synchronized (monitor())
{
check_orphaned();
org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType target = null;
target = (org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType)get_store().find_element_user(SINGLEBESTRECORD$0, 0);
if (target == null)
{
return null;
}
return target;
}
}
/**
* Sets the "single-best-record" element
*/
public void setSingleBestRecord(org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType singleBestRecord)
{
synchronized (monitor())
{
check_orphaned();
org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType target = null;
target = (org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType)get_store().find_element_user(SINGLEBESTRECORD$0, 0);
if (target == null)
{
target = (org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType)get_store().add_element_user(SINGLEBESTRECORD$0);
}
target.set(singleBestRecord);
}
}
/**
* Appends and returns a new empty "single-best-record" element
*/
public org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType addNewSingleBestRecord()
{
synchronized (monitor())
{
check_orphaned();
org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType target;
target = (org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType)get_store().add_element_user(SINGLEBESTRECORD$0);
return target;
}
}
}
| UTF-8 | Java | 3,072 | java | SingleBestRecordDocumentImpl.java | Java | [] | null | [] | /*
* An XML document type.
* Localname: single-best-record
* Namespace: http://configuration.openempi.openhie.org/single-best-record
* Java type: org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordDocument
*
* Automatically generated - do not modify.
*/
package org.openhie.openempi.configuration.xml.singlebestrecord.impl;
/**
* A document containing one single-best-record(@http://configuration.openempi.openhie.org/single-best-record) element.
*
* This is a complex type.
*/
public class SingleBestRecordDocumentImpl extends org.openhie.openempi.configuration.xml.impl.SingleBestRecordDocumentImpl implements org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordDocument
{
public SingleBestRecordDocumentImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName SINGLEBESTRECORD$0 =
new javax.xml.namespace.QName("http://configuration.openempi.openhie.org/single-best-record", "single-best-record");
/**
* Gets the "single-best-record" element
*/
public org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType getSingleBestRecord()
{
synchronized (monitor())
{
check_orphaned();
org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType target = null;
target = (org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType)get_store().find_element_user(SINGLEBESTRECORD$0, 0);
if (target == null)
{
return null;
}
return target;
}
}
/**
* Sets the "single-best-record" element
*/
public void setSingleBestRecord(org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType singleBestRecord)
{
synchronized (monitor())
{
check_orphaned();
org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType target = null;
target = (org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType)get_store().find_element_user(SINGLEBESTRECORD$0, 0);
if (target == null)
{
target = (org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType)get_store().add_element_user(SINGLEBESTRECORD$0);
}
target.set(singleBestRecord);
}
}
/**
* Appends and returns a new empty "single-best-record" element
*/
public org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType addNewSingleBestRecord()
{
synchronized (monitor())
{
check_orphaned();
org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType target;
target = (org.openhie.openempi.configuration.xml.singlebestrecord.SingleBestRecordType)get_store().add_element_user(SINGLEBESTRECORD$0);
return target;
}
}
}
| 3,072 | 0.686523 | 0.684245 | 76 | 39.421051 | 48.183109 | 214 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.263158 | false | false | 2 |
86e57579f7ad657e4d15c67091591fccc3a8d881 | 6,751,688,596,847 | 3cf2820ea021ff2c3714abe0db7390da2527dc5b | /JavaSandbox/src/main/java/demo/objectSerialize/msgpack/Simple2.java | 74c526ba978e557e9f71a4d3b7ca37a455ef97cc | [] | no_license | mamatumo/mySandBox | https://github.com/mamatumo/mySandBox | 7e575eac01986c01e99b2de6dfaa07e694dba2b7 | 40607093aaa34eaf29465469540b8d840e958dd4 | refs/heads/master | 2015-07-28T13:04:59 | 2015-07-17T09:26:48 | 2015-07-17T09:26:48 | 186,620 | 0 | 0 | null | false | 2015-06-17T11:23:54 | 2009-04-27T11:08:22 | 2015-05-22T11:20:17 | 2015-06-17T11:23:54 | 5,488 | 1 | 0 | 0 | Java | null | null | package demo.objectSerialize.msgpack;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.jruby.RubyProcess.Sys;
import org.msgpack.MessagePack;
import org.msgpack.packer.Packer;
import org.msgpack.type.Value;
import org.msgpack.unpacker.Unpacker;
import demo.objectSerialize.data.BaseData;
import demo.objectSerialize.data.DataA;
import demo.objectSerialize.data.DataB;
/**
* マニュアルの Dynamic typing
* 実行時の型でシリアライズ・デシリアライズできないか。
*
* @author mamatumo
*
*/
public class Simple2 {
public static void main(String[] args) {
try {
MessagePack msgpack = new MessagePack();
// あえてアノテーションなしで登録で。
msgpack.register(BaseData.class);
msgpack.register(DataA.class);
msgpack.register(DataB.class);
DataA data = new DataA();
data.setName("nanan");
data.setAge(234);
data.setMemoA("ni3i3iksf");
BaseData store = data;
// serialize
byte[] bytes = msgpack.write(store);
System.out.println(new String(bytes, "UTF-8"));
Value value = msgpack.read(bytes);
System.out.println(value.getType().toString());
// // deserialize
// Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes.toByteArray()));
// BaseData restore = unpacker.read(BaseData.class);
// System.out.println(restore.getClass());
// System.out.println(restore.toString());
//
// // ダメ。抽象化したクラスで保存もダメ。 抽象化したクラスで復元もダメ。。System.out.println((DataA)restore);
// // packerだとダメなのか???
//
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| UTF-8 | Java | 1,755 | java | Simple2.java | Java | [
{
"context": "ping \n * 実行時の型でシリアライズ・デシリアライズできないか。\n * \n * @author mamatumo\n * \n */\npublic class Simple2 {\n\n\tpublic static vo",
"end": 520,
"score": 0.9994916319847107,
"start": 512,
"tag": "USERNAME",
"value": "mamatumo"
}
] | null | [] | package demo.objectSerialize.msgpack;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.jruby.RubyProcess.Sys;
import org.msgpack.MessagePack;
import org.msgpack.packer.Packer;
import org.msgpack.type.Value;
import org.msgpack.unpacker.Unpacker;
import demo.objectSerialize.data.BaseData;
import demo.objectSerialize.data.DataA;
import demo.objectSerialize.data.DataB;
/**
* マニュアルの Dynamic typing
* 実行時の型でシリアライズ・デシリアライズできないか。
*
* @author mamatumo
*
*/
public class Simple2 {
public static void main(String[] args) {
try {
MessagePack msgpack = new MessagePack();
// あえてアノテーションなしで登録で。
msgpack.register(BaseData.class);
msgpack.register(DataA.class);
msgpack.register(DataB.class);
DataA data = new DataA();
data.setName("nanan");
data.setAge(234);
data.setMemoA("ni3i3iksf");
BaseData store = data;
// serialize
byte[] bytes = msgpack.write(store);
System.out.println(new String(bytes, "UTF-8"));
Value value = msgpack.read(bytes);
System.out.println(value.getType().toString());
// // deserialize
// Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes.toByteArray()));
// BaseData restore = unpacker.read(BaseData.class);
// System.out.println(restore.getClass());
// System.out.println(restore.toString());
//
// // ダメ。抽象化したクラスで保存もダメ。 抽象化したクラスで復元もダメ。。System.out.println((DataA)restore);
// // packerだとダメなのか???
//
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| 1,755 | 0.711918 | 0.707457 | 66 | 22.772728 | 20.16958 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.833333 | false | false | 2 |
1848069faf68680fb7669ad8195584a603a6d288 | 3,530,463,138,827 | 9c757279e11020d1583d18697ffe8971aa566c9d | /src/utils/Paths.java | bc24dd13009f2d0df0183fb457df10c8598f3154 | [] | no_license | JPCoding/Cellulary_Simulator_Pluemer_Jens | https://github.com/JPCoding/Cellulary_Simulator_Pluemer_Jens | b045bf132199696e2a87b6d90abae2b4ed3fbaaa | 298164c714cd8c127ace914a182065d5cc5edd74 | refs/heads/master | 2016-08-12T20:46:05.239000 | 2016-01-31T16:08:52 | 2016-01-31T16:08:52 | 44,195,860 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package utils;
import java.io.File;
/** Provides access to application paths. */
public interface Paths
{
class FolderName
{
private static final String USER_DIR = System.getProperty("user.dir");
private static final String LANGUGE_FILE = "language";
private static final String PROPERTIE_FOLDER = "properties";
private static final String AUTOMATON_FOLDER = "automata";
private static final String AUTOMATON_INTERNAL_CLASS_FOLDER = "bin" + File.separator + "classfiles";
private static final String LOG_FILE_FOLDER = "logs";
private static final String LOG_FILE_COMPILER_ERRORS = "compiler" + File.separator + "compiler.log";
private static final String LOG_FILE_INFO = "info.log";
private static final String LOG_FILE_ERROR = "error.log";
private static final String LOG_FILE_WARNING = "warning.log";
private static final String LOG_FILE_GENERAL = "log.log";
}
public static final String AUTOMATA_CLASS_FILES = FolderName.USER_DIR
+ File.separator
+ FolderName.AUTOMATON_INTERNAL_CLASS_FOLDER;
public static final String AUTOMATA_JAVA_FILES = FolderName.USER_DIR
+ File.separator
+ FolderName.AUTOMATON_FOLDER;
public static final String LOG_FILES = FolderName.USER_DIR
+ File.separator
+ FolderName.LOG_FILE_FOLDER;
public static final String LOG_FILE_COMPILER_ERROR = LOG_FILES
+ File.separator
+ FolderName.LOG_FILE_COMPILER_ERRORS;
public static final String LOG_FILES_GENERAL = LOG_FILES
+ File.separator
+ FolderName.LOG_FILE_GENERAL;
public static final String LOG_FILE_INFO = LOG_FILES
+ File.separator
+ FolderName.LOG_FILE_INFO;
public static final String LOG_FILE_ERROR = LOG_FILES
+ File.separator
+ FolderName.LOG_FILE_ERROR;
public static final String LOG_FILE_WARNING = LOG_FILES
+ File.separator
+ FolderName.LOG_FILE_WARNING;
public static final String PROPERTIE_FILES = FolderName.USER_DIR
+ File.separator
+ FolderName.PROPERTIE_FOLDER;
public static final String LANGUAGE_PROPERTIE = PROPERTIE_FILES
+ File.separator
+ FolderName.LANGUGE_FILE;
public static final String AUTOMATA_DUMMY_FILE = FolderName.USER_DIR
+ File.separator
+ "src"
+ File.separator
+ "model"
+ File.separator
+ "automaton"
+ File.separator
+ "internalautomata"
+ File.separator
+ "ConwaysGameOfLife.java";
public static final String DEFAULT_PATH = FolderName.USER_DIR;
}
| UTF-8 | Java | 4,909 | java | Paths.java | Java | [] | null | [] | package utils;
import java.io.File;
/** Provides access to application paths. */
public interface Paths
{
class FolderName
{
private static final String USER_DIR = System.getProperty("user.dir");
private static final String LANGUGE_FILE = "language";
private static final String PROPERTIE_FOLDER = "properties";
private static final String AUTOMATON_FOLDER = "automata";
private static final String AUTOMATON_INTERNAL_CLASS_FOLDER = "bin" + File.separator + "classfiles";
private static final String LOG_FILE_FOLDER = "logs";
private static final String LOG_FILE_COMPILER_ERRORS = "compiler" + File.separator + "compiler.log";
private static final String LOG_FILE_INFO = "info.log";
private static final String LOG_FILE_ERROR = "error.log";
private static final String LOG_FILE_WARNING = "warning.log";
private static final String LOG_FILE_GENERAL = "log.log";
}
public static final String AUTOMATA_CLASS_FILES = FolderName.USER_DIR
+ File.separator
+ FolderName.AUTOMATON_INTERNAL_CLASS_FOLDER;
public static final String AUTOMATA_JAVA_FILES = FolderName.USER_DIR
+ File.separator
+ FolderName.AUTOMATON_FOLDER;
public static final String LOG_FILES = FolderName.USER_DIR
+ File.separator
+ FolderName.LOG_FILE_FOLDER;
public static final String LOG_FILE_COMPILER_ERROR = LOG_FILES
+ File.separator
+ FolderName.LOG_FILE_COMPILER_ERRORS;
public static final String LOG_FILES_GENERAL = LOG_FILES
+ File.separator
+ FolderName.LOG_FILE_GENERAL;
public static final String LOG_FILE_INFO = LOG_FILES
+ File.separator
+ FolderName.LOG_FILE_INFO;
public static final String LOG_FILE_ERROR = LOG_FILES
+ File.separator
+ FolderName.LOG_FILE_ERROR;
public static final String LOG_FILE_WARNING = LOG_FILES
+ File.separator
+ FolderName.LOG_FILE_WARNING;
public static final String PROPERTIE_FILES = FolderName.USER_DIR
+ File.separator
+ FolderName.PROPERTIE_FOLDER;
public static final String LANGUAGE_PROPERTIE = PROPERTIE_FILES
+ File.separator
+ FolderName.LANGUGE_FILE;
public static final String AUTOMATA_DUMMY_FILE = FolderName.USER_DIR
+ File.separator
+ "src"
+ File.separator
+ "model"
+ File.separator
+ "automaton"
+ File.separator
+ "internalautomata"
+ File.separator
+ "ConwaysGameOfLife.java";
public static final String DEFAULT_PATH = FolderName.USER_DIR;
}
| 4,909 | 0.36097 | 0.36097 | 69 | 70.115944 | 35.348999 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.362319 | false | false | 2 |
d1ba08dc9b7cf98e49af1a2dac681090cbbe7ef4 | 29,016,799,051,814 | 7242b9141efd4bf96a0209233b1c58fecceda7b9 | /Android app/app/src/main/java/com/example/myapplication/DTO/UserAndTaskDto.java | 8c41084451b0b6dc7600bd0ffd931268da50e3b4 | [] | no_license | nikolinastamenic/PMA | https://github.com/nikolinastamenic/PMA | 928da1c35f075dfe246ce964f5b16f69816adca7 | f48008269466ff51cdcf114d8d3e8428610d69e6 | refs/heads/master | 2021-07-10T19:01:12.718000 | 2020-07-04T18:33:15 | 2020-07-04T18:33:15 | 243,334,879 | 0 | 0 | null | false | 2021-04-26T20:21:52 | 2020-02-26T18:25:13 | 2020-07-04T18:33:48 | 2021-04-26T20:21:52 | 17,391 | 0 | 0 | 1 | Java | false | false | package com.example.myapplication.DTO;
import java.util.List;
import lombok.Data;
@Data
public class UserAndTaskDto {
private UserDto user;
private List<AllTaskDto> tasks;
}
| UTF-8 | Java | 186 | java | UserAndTaskDto.java | Java | [] | null | [] | package com.example.myapplication.DTO;
import java.util.List;
import lombok.Data;
@Data
public class UserAndTaskDto {
private UserDto user;
private List<AllTaskDto> tasks;
}
| 186 | 0.752688 | 0.752688 | 12 | 14.5 | 14.384598 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 2 |
a229ee75a77ee7036de884c894f500ba6cb8dff9 | 30,777,735,651,460 | 3d8261feea951a27b08e3dcf4f0302ed90902523 | /src/gerenciaFuncionariosNova/Funcionario.java | e648a613794b24feb6c69606ca41cf05932624c0 | [] | no_license | olaviolacerda/APOSTILAJAVAOO | https://github.com/olaviolacerda/APOSTILAJAVAOO | a9d1b34d6395ba5269772e37cc3979834e8b50a5 | 537807725cce83412706394793b4783a6257bdfa | refs/heads/master | 2018-01-15T04:35:23.867000 | 2016-06-08T18:17:33 | 2016-06-08T18:17:33 | 55,810,658 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gerenciaFuncionariosNova;
public class Funcionario {
String nome;
String departamento;
// String data;
String rg;
double salario;
Data dataDeEntrada;
void recebeAumento(double aumento) {
this.salario = this.salario + aumento;
}
double calculaGanhoAnual() {
return this.salario * 12;
}
void mostra() {
System.out.println("Nome: " + this.nome);
System.out.println("RG: " + this.rg);
System.out.println("Departamento: " + this.departamento);
// System.out.println("Data de entrada: " + this.data);
System.out.println("Salario: " + this.salario);
System.out.println("Salario Anual: " + this.calculaGanhoAnual());
}
void mostraData() {
System.out.println("Data de entrada: " + this.dataDeEntrada.formatada());
}
}
| UTF-8 | Java | 754 | java | Funcionario.java | Java | [] | null | [] | package gerenciaFuncionariosNova;
public class Funcionario {
String nome;
String departamento;
// String data;
String rg;
double salario;
Data dataDeEntrada;
void recebeAumento(double aumento) {
this.salario = this.salario + aumento;
}
double calculaGanhoAnual() {
return this.salario * 12;
}
void mostra() {
System.out.println("Nome: " + this.nome);
System.out.println("RG: " + this.rg);
System.out.println("Departamento: " + this.departamento);
// System.out.println("Data de entrada: " + this.data);
System.out.println("Salario: " + this.salario);
System.out.println("Salario Anual: " + this.calculaGanhoAnual());
}
void mostraData() {
System.out.println("Data de entrada: " + this.dataDeEntrada.formatada());
}
}
| 754 | 0.696286 | 0.693634 | 31 | 23.32258 | 21.532251 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.548387 | false | false | 2 |
38d9eefadf3933b1b4ab94f3744987b930d970ce | 22,780,506,556,757 | a404eb51ccbb6cb5bace5cdf7cb2a33d6661cfb3 | /src/main/java/com/ising99/wkis/service/impl/SingHistoryServiceImpl.java | 36aee50bdf6da83daf4183dcea5f10d6437f6417 | [] | no_license | hulkppw/wkis | https://github.com/hulkppw/wkis | bc3b6f6bac12a2c17035e14060ab217abba48456 | 40b394e4dacc373b1cc9f88d41b6516aa7326689 | refs/heads/master | 2021-01-20T18:33:47.216000 | 2016-07-20T23:41:39 | 2016-07-20T23:41:39 | 63,821,955 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ising99.wkis.service.impl;
import com.ising99.wkis.dao.*;
import com.ising99.wkis.dao.base.DataSourceInstances;
import com.ising99.wkis.dao.base.DataSourceSwitch;
import com.ising99.wkis.domain.PageData;
import com.ising99.wkis.domain.SingHistory;
import com.ising99.wkis.parameter.*;
import com.ising99.wkis.service.SingHistoryService;
import com.ising99.wkis.utils.PageUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service("SingHistoryService")
public class SingHistoryServiceImpl implements SingHistoryService {
@Resource
SingHistoryMapper singHistoryMapper;
@Override
public int add(SingHistoryParam param) {
DataSourceSwitch.setDataSourceType(DataSourceInstances.KOD);
return singHistoryMapper.add(param);
}
@Override
public PageData<SingHistory> getList(SingHistoryParam param) {
DataSourceSwitch.setDataSourceType(DataSourceInstances.KOD);
PageData<SingHistory> pageData = new PageData<SingHistory>();
pageData.setRecordcount(singHistoryMapper.getCount(param));
if (pageData.getRecordcount() == 0) {
return pageData;
}
pageData.setPagecount(PageUtils.getPageCount(pageData.getRecordcount(), param.getPagesize()));
param.setPageindex(param.getPageindex() > pageData.getPagecount() ? pageData.getPagecount() : param.getPageindex());
DataSourceSwitch.setDataSourceType(DataSourceInstances.KOD);
pageData.setList(singHistoryMapper.getList(param));
return pageData;
}
@Override
public int delete(SingHistoryParam param) {
DataSourceSwitch.setDataSourceType(DataSourceInstances.KOD);
return singHistoryMapper.delete(param);
}
}
| UTF-8 | Java | 1,760 | java | SingHistoryServiceImpl.java | Java | [] | null | [] | package com.ising99.wkis.service.impl;
import com.ising99.wkis.dao.*;
import com.ising99.wkis.dao.base.DataSourceInstances;
import com.ising99.wkis.dao.base.DataSourceSwitch;
import com.ising99.wkis.domain.PageData;
import com.ising99.wkis.domain.SingHistory;
import com.ising99.wkis.parameter.*;
import com.ising99.wkis.service.SingHistoryService;
import com.ising99.wkis.utils.PageUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service("SingHistoryService")
public class SingHistoryServiceImpl implements SingHistoryService {
@Resource
SingHistoryMapper singHistoryMapper;
@Override
public int add(SingHistoryParam param) {
DataSourceSwitch.setDataSourceType(DataSourceInstances.KOD);
return singHistoryMapper.add(param);
}
@Override
public PageData<SingHistory> getList(SingHistoryParam param) {
DataSourceSwitch.setDataSourceType(DataSourceInstances.KOD);
PageData<SingHistory> pageData = new PageData<SingHistory>();
pageData.setRecordcount(singHistoryMapper.getCount(param));
if (pageData.getRecordcount() == 0) {
return pageData;
}
pageData.setPagecount(PageUtils.getPageCount(pageData.getRecordcount(), param.getPagesize()));
param.setPageindex(param.getPageindex() > pageData.getPagecount() ? pageData.getPagecount() : param.getPageindex());
DataSourceSwitch.setDataSourceType(DataSourceInstances.KOD);
pageData.setList(singHistoryMapper.getList(param));
return pageData;
}
@Override
public int delete(SingHistoryParam param) {
DataSourceSwitch.setDataSourceType(DataSourceInstances.KOD);
return singHistoryMapper.delete(param);
}
}
| 1,760 | 0.75 | 0.739205 | 48 | 35.666668 | 28.72378 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.541667 | false | false | 2 |
09d1c8e4070792d3b73ab008d0a8065fd40d1e01 | 31,001,074,008,522 | 83d95788004b39615f14c0cc2d7108c20a5a824f | /SMPD/PR/src/PR_GUI.java | ef1f578722279269ca63220302b0b145bf4e74b9 | [] | no_license | Vityoube/WEEiA_PROJEKTY | https://github.com/Vityoube/WEEiA_PROJEKTY | b0aa3fc1f3da12ffd5bd19e45b6b191d9203e025 | 0813ef1373b09842b58532a2fe8c3e0f441baa99 | refs/heads/master | 2020-06-10T16:11:13.818000 | 2017-02-15T13:10:46 | 2017-02-15T13:10:46 | 75,941,827 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import Jama.*;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* PR_GUI.java
*
* Created on 2015-03-05, 19:40:56
*/
/**
*
* @author krzy
*/
public class PR_GUI extends javax.swing.JFrame {
String InData; // dataset from a text file will be placed here
int ClassCount = 0, FeatureCount = 0;
double[][] F, FNew; // original feature matrix and transformed feature
// matrix
int[] ClassLabels, SampleCount;
String[] ClassNames;
/** Creates new form PR_GUI */
public PR_GUI() {
initComponents();
setSize(720, 410);
}
/**
* 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() {
rbg_F = new javax.swing.ButtonGroup();
b_read = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
l_dataset_name_l = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
l_dataset_name = new javax.swing.JLabel();
l_nfeatures = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
selbox_nfeat = new javax.swing.JComboBox();
jSeparator1 = new javax.swing.JSeparator();
f_rb_extr = new javax.swing.JRadioButton();
f_rb_sel = new javax.swing.JRadioButton();
b_deriveFS = new javax.swing.JButton();
jLabel10 = new javax.swing.JLabel();
f_combo_criterion = new javax.swing.JComboBox();
f_combo_PCA_LDA = new javax.swing.JComboBox();
jLabel12 = new javax.swing.JLabel();
tf_PCA_Energy = new javax.swing.JTextField();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
l_NewDim = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jComboBox2 = new javax.swing.JComboBox();
b_Train = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jLabel16 = new javax.swing.JLabel();
tf_TrainSetSize = new javax.swing.JTextField();
jLabel17 = new javax.swing.JLabel();
jPanel5 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
l_FLD_winner = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
l_FLD_val = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
b_read.setText("Read dataset");
b_read.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_readActionPerformed(evt);
}
});
getContentPane().add(b_read);
b_read.setBounds(20, 10, 130, 25);
jPanel2.setBackground(new java.awt.Color(204, 255, 255));
jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabel1.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N
jLabel1.setText("Dataset info");
l_dataset_name_l.setText("Name:");
jLabel3.setText("Classes:");
jLabel4.setText("Features:");
l_dataset_name.setText("...");
l_nfeatures.setText("...");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel2Layout.createSequentialGroup().addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup().addComponent(l_dataset_name_l)
.addGap(18, 18, 18).addComponent(l_dataset_name))
.addComponent(jLabel1))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup().addGap(115, 115, 115)
.addComponent(jLabel3))
.addGroup(jPanel2Layout.createSequentialGroup().addGap(94, 94, 94)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(l_nfeatures)))
.addGap(100, 100, 100)));
jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1).addComponent(jLabel3))
.addGap(10, 10, 10)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(l_dataset_name_l).addComponent(jLabel4).addComponent(l_dataset_name)
.addComponent(l_nfeatures))
.addContainerGap(24, Short.MAX_VALUE)));
getContentPane().add(jPanel2);
jPanel2.setBounds(10, 50, 320, 80);
jButton2.setText("Parse dataset");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
getContentPane().add(jButton2);
jButton2.setBounds(190, 10, 130, 25);
jPanel3.setBackground(new java.awt.Color(255, 255, 204));
jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jPanel3.setLayout(null);
jLabel5.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N
jLabel5.setText("Feature space");
jPanel3.add(jLabel5);
jLabel5.setBounds(14, 2, 118, 26);
jLabel6.setText("FS Dimension");
jPanel3.add(jLabel6);
jLabel6.setBounds(178, 9, 78, 16);
String[] dimensions = new String[63];
for (Integer i = 1; i <= 63; i++)
dimensions[i - 1] = i.toString();
selbox_nfeat.setModel(new javax.swing.DefaultComboBoxModel(dimensions));
selbox_nfeat.setEnabled(true);
jPanel3.add(selbox_nfeat);
selbox_nfeat.setBounds(268, 6, 34, 22);
jPanel3.add(jSeparator1);
jSeparator1.setBounds(14, 41, 290, 10);
f_rb_extr.setBackground(new java.awt.Color(255, 255, 204));
rbg_F.add(f_rb_extr);
f_rb_extr.setText("Feature extraction");
f_rb_extr.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
f_rb_extrActionPerformed(evt);
}
});
jPanel3.add(f_rb_extr);
f_rb_extr.setBounds(10, 110, 133, 25);
f_rb_sel.setBackground(new java.awt.Color(255, 255, 204));
rbg_F.add(f_rb_sel);
f_rb_sel.setSelected(true);
f_rb_sel.setText("Feature selection");
f_rb_sel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
f_rb_selActionPerformed(evt);
}
});
jPanel3.add(f_rb_sel);
f_rb_sel.setBounds(10, 60, 127, 25);
b_deriveFS.setText("Derive Feature Space");
b_deriveFS.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_deriveFSActionPerformed(evt);
}
});
jPanel3.add(b_deriveFS);
b_deriveFS.setBounds(10, 180, 292, 25);
jLabel10.setText("Criterion");
jPanel3.add(jLabel10);
jLabel10.setBounds(200, 50, 49, 16);
f_combo_criterion.setModel(
new javax.swing.DefaultComboBoxModel(new String[] { "Fisher discriminant", "Classification error" }));
f_combo_criterion.setEnabled(false);
jPanel3.add(f_combo_criterion);
f_combo_criterion.setBounds(160, 70, 140, 22);
f_combo_PCA_LDA.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "PCA", "LDA" }));
f_combo_PCA_LDA.setEnabled(false);
jPanel3.add(f_combo_PCA_LDA);
f_combo_PCA_LDA.setBounds(190, 110, 70, 22);
jLabel12.setText("Energy");
jPanel3.add(jLabel12);
jLabel12.setBounds(20, 150, 39, 16);
tf_PCA_Energy.setText("80");
jPanel3.add(tf_PCA_Energy);
tf_PCA_Energy.setBounds(70, 150, 30, 22);
jLabel14.setText("%");
jPanel3.add(jLabel14);
jLabel14.setBounds(110, 150, 20, 16);
jLabel15.setText("New dimension:");
jPanel3.add(jLabel15);
jLabel15.setBounds(160, 150, 92, 16);
l_NewDim.setText("...");
jPanel3.add(l_NewDim);
l_NewDim.setBounds(270, 150, 30, 16);
getContentPane().add(jPanel3);
jPanel3.setBounds(10, 140, 320, 220);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 156, Short.MAX_VALUE));
jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 126, Short.MAX_VALUE));
getContentPane().add(jPanel1);
jPanel1.setBounds(530, 10, 160, 130);
jPanel4.setBackground(new java.awt.Color(204, 255, 204));
jPanel4.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jPanel4.setLayout(null);
jLabel8.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N
jLabel8.setText("Classifier");
jPanel4.add(jLabel8);
jLabel8.setBounds(10, 0, 79, 26);
jLabel9.setText("Method");
jPanel4.add(jLabel9);
jLabel9.setBounds(14, 44, 42, 16);
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Nearest neighbor (NN)",
"Nearest Mean (NM)", "k-Nearest Neighbor (k-NN)", "k-Nearest Mean (k-NM)" }));
jPanel4.add(jComboBox2);
jComboBox2.setBounds(74, 41, 178, 22);
b_Train.setText("Train");
b_Train.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_TrainActionPerformed(evt);
}
});
jPanel4.add(b_Train);
b_Train.setBounds(40, 130, 98, 25);
jButton4.setText("Execute");
jPanel4.add(jButton4);
jButton4.setBounds(210, 130, 96, 25);
jLabel16.setText("Training part:");
jPanel4.add(jLabel16);
jLabel16.setBounds(20, 170, 80, 16);
tf_TrainSetSize.setText("80");
jPanel4.add(tf_TrainSetSize);
tf_TrainSetSize.setBounds(110, 170, 20, 22);
jLabel17.setText("%");
jPanel4.add(jLabel17);
jLabel17.setBounds(140, 170, 20, 16);
getContentPane().add(jPanel4);
jPanel4.setBounds(340, 150, 350, 210);
jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Results"));
jPanel5.setLayout(null);
jLabel2.setText("FS Winner:");
jPanel5.add(jLabel2);
jLabel2.setBounds(10, 30, 70, 16);
l_FLD_winner.setText("xxx");
jPanel5.add(l_FLD_winner);
l_FLD_winner.setBounds(100, 30, 18, 16);
jLabel13.setText("FLD value: ");
jPanel5.add(jLabel13);
jLabel13.setBounds(10, 60, 70, 16);
l_FLD_val.setText("vvv");
jPanel5.add(l_FLD_val);
l_FLD_val.setBounds(100, 60, 48, 16);
getContentPane().add(jPanel5);
jPanel5.setBounds(340, 10, 160, 130);
pack();
}// </editor-fold>//GEN-END:initComponents
private void f_rb_selActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_f_rb_selActionPerformed
f_combo_criterion.setEnabled(true);
f_combo_PCA_LDA.setEnabled(false);
}// GEN-LAST:event_f_rb_selActionPerformed
private void f_rb_extrActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_f_rb_extrActionPerformed
f_combo_criterion.setEnabled(false);
f_combo_PCA_LDA.setEnabled(true);
}// GEN-LAST:event_f_rb_extrActionPerformed
private void b_readActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_b_readActionPerformed
// reads in a text file; contents is placed into a variable of String
// type
InData = readDataSet();
}// GEN-LAST:event_b_readActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton2ActionPerformed
// Analyze text inputted from a file: determine class number and labels
// and number
// of features; build feature matrix: columns - samples, rows - features
try {
if (InData != null) {
getDatasetParameters();
l_nfeatures.setText(FeatureCount + "");
fillFeatureMatrix();
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}// GEN-LAST:event_jButton2ActionPerformed
private void b_deriveFSActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_b_deriveFSActionPerformed
// derive optimal feature space
if (F == null)
return;
if (f_rb_sel.isSelected()) {
// the chosen strategy is feature selection
int[] flags = new int[FeatureCount];
selectFeatures(flags, Integer.parseInt((String) selbox_nfeat.getSelectedItem()));
} else if (f_rb_extr.isSelected()) {
double TotEnergy = Double.parseDouble(tf_PCA_Energy.getText()) / 100.0;
// Target dimension (if k>0) or flag for energy-based dimension
// (k=0)
int k = 0;
// double[][] FF = { {1,1}, {1,2}};
// double[][] FF = { {-2,0,2}, {-1,0,1}};
// F is an array of initial features, FNew is the resulting array
double[][] FFNorm = centerAroundMean(F);
Matrix Cov = computeCovarianceMatrix(FFNorm);
Matrix TransformMat = extractFeatures(Cov, TotEnergy, k);
FNew = projectSamples(new Matrix(FFNorm), TransformMat);
// FNew is a matrix with samples projected to a new feature space
l_NewDim.setText(FNew.length + "");
}
}// GEN-LAST:event_b_deriveFSActionPerformed
private void b_TrainActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_b_TrainActionPerformed
// first step: split dataset (in new feature space) into training /
// testing parts
if (FNew == null)
return; // no reduced feature space have been derived
Classifier Cl = new Classifier();
Cl.generateTraining_and_Test_Sets(FNew, tf_TrainSetSize.getText());
}// GEN-LAST:event_b_TrainActionPerformed
/**
* @param args
* the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PR_GUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton b_Train;
private javax.swing.JButton b_deriveFS;
private javax.swing.JButton b_read;
private javax.swing.JComboBox f_combo_PCA_LDA;
private javax.swing.JComboBox f_combo_criterion;
private javax.swing.JRadioButton f_rb_extr;
private javax.swing.JRadioButton f_rb_sel;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton4;
private javax.swing.JComboBox jComboBox2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JLabel l_FLD_val;
private javax.swing.JLabel l_FLD_winner;
private javax.swing.JLabel l_NewDim;
private javax.swing.JLabel l_dataset_name;
private javax.swing.JLabel l_dataset_name_l;
private javax.swing.JLabel l_nfeatures;
private javax.swing.ButtonGroup rbg_F;
private javax.swing.JComboBox selbox_nfeat;
private javax.swing.JTextField tf_PCA_Energy;
private javax.swing.JTextField tf_TrainSetSize;
// End of variables declaration//GEN-END:variables
private String readDataSet() {
String s_tmp, s_out = "";
JFileChooser jfc = new JFileChooser();
jfc.setCurrentDirectory(new File(".."));
FileNameExtensionFilter filter = new FileNameExtensionFilter("Datasets - plain text files", "txt");
jfc.setFileFilter(filter);
if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
try {
BufferedReader br = new BufferedReader(new FileReader(jfc.getSelectedFile()));
while ((s_tmp = br.readLine()) != null)
s_out += s_tmp + '$';
br.close();
l_dataset_name.setText(jfc.getSelectedFile().getName());
} catch (Exception e) {
}
}
return s_out;
}
private void getDatasetParameters() throws Exception {
// based on data stored in InData determine: class count and names,
// number of samples
// and number of features; set the corresponding variables
String stmp = InData, saux = "";
// analyze the first line and get feature count: assume that number of
// features
// equals number of commas
saux = InData.substring(InData.indexOf(',') + 1, InData.indexOf('$'));
if (saux.length() == 0)
throw new Exception("The first line is empty");
// saux stores the first line beginning from the first comma
int count = 0;
while (saux.indexOf(',') > 0) {
saux = saux.substring(saux.indexOf(',') + 1);
count++;
}
FeatureCount = count + 1; // the first parameter
// Determine number of classes, class names and number of samples per
// class
boolean New;
int index = -1;
List<String> NameList = new ArrayList<String>();
List<Integer> CountList = new ArrayList<Integer>();
List<Integer> LabelList = new ArrayList<Integer>();
while (stmp.length() > 1) {
saux = stmp.substring(0, stmp.indexOf(' '));
New = true;
index++; // new class index
for (int i = 0; i < NameList.size(); i++)
if (saux.equals(NameList.get(i))) {
New = false;
index = i; // class index
}
if (New) {
NameList.add(saux);
CountList.add(0);
} else {
CountList.set(index, CountList.get(index).intValue() + 1);
}
LabelList.add(index); // class index for current row
stmp = stmp.substring(stmp.indexOf('$') + 1);
}
// based on results of the above analysis, create variables
ClassNames = new String[NameList.size()];
for (int i = 0; i < ClassNames.length; i++)
ClassNames[i] = NameList.get(i);
SampleCount = new int[CountList.size()];
for (int i = 0; i < SampleCount.length; i++)
SampleCount[i] = CountList.get(i).intValue() + 1;
ClassLabels = new int[LabelList.size()];
for (int i = 0; i < ClassLabels.length; i++)
ClassLabels[i] = LabelList.get(i).intValue();
System.out.println(SampleCount[0] + SampleCount[1]);
}
private void fillFeatureMatrix() throws Exception {
// having determined array size and class labels, fills in the feature
// matrix
int n = 0;
String saux, stmp = InData;
for (int i = 0; i < SampleCount.length; i++)
n += SampleCount[i];
if (n <= 0)
throw new Exception("no samples found");
F = new double[FeatureCount][n]; // samples are placed column-wise
for (int j = 0; j < n; j++) {
saux = stmp.substring(0, stmp.indexOf('$'));
saux = saux.substring(stmp.indexOf(',') + 1);
for (int i = 0; i < FeatureCount - 1; i++) {
F[i][j] = Double.parseDouble(saux.substring(0, saux.indexOf(',')));
saux = saux.substring(saux.indexOf(',') + 1);
}
F[FeatureCount - 1][j] = Double.parseDouble(saux);
stmp = stmp.substring(stmp.indexOf('$') + 1);
}
int cc = 1;
}
private void selectFeatures(int[] flags, int d) {
// for now: check all individual features using 1D, 2-class Fisher
// criterion
if (d == 1) {
double FLD = 0, tmp;
int max_ind = -1;
for (int i = 0; i < FeatureCount; i++) {
if ((tmp = computeFisherLD(F[i])) > FLD) {
FLD = tmp;
max_ind = i + 1;
}
}
l_FLD_winner.setText(max_ind + "");
l_FLD_val.setText(FLD + "");
} else if (d > 1) {
double FSD = 0, tmp;
int fMaxIndex = -1;
List<double[][]> featuresCombinations = new ArrayList<double[][]>();
double[][] featuresCombination = new double[d][SampleCount[0] + SampleCount[1]];
generateFeaturesCombinations(featuresCombinations, 0, d, featuresCombination);
for (int i = 0; i < featuresCombinations.size(); i++) {
if ((tmp = computeFSD(featuresCombinations.get(i), d)) > FSD) {
System.out.println("Calculating Fisher for feature " + i+1);
FSD = tmp;
fMaxIndex++;
System.out.println("The Fisher for feature " + i+1 + " equals " + FSD);
}
}
l_FLD_winner.setText(fMaxIndex + "");
l_FLD_val.setText(FSD + "");
}
// to do: compute for higher dimensional spaces, use e.g. SFS for
// candidate selection
}
List<Integer> numbers=new ArrayList<Integer>();
private void generateFeaturesCombinations(List<double[][]> featuresCombinations, int start, int dimensions,
double[][] featureCombination) {
if (dimensions == 0) {
featuresCombinations.add(featureCombination);
System.out.println(numbers);
System.out.println("The matrix has been added successfully!");
return;
}
for (int i = start; i < F.length; i++) {
featureCombination[featureCombination.length - dimensions] = Arrays.copyOfRange(F[i], 0,
SampleCount[0] + SampleCount[1]);
numbers.add(i);
generateFeaturesCombinations(featuresCombinations, i + 1, dimensions - 1, featureCombination);
}
}
private BigInteger calculateCombinationsCount(int d) {
BigInteger dFactorial = BigInteger.valueOf(1), nFactorial = BigInteger.valueOf(1),
nMinusDFactorial = BigInteger.valueOf(1);
int n = SampleCount[0] + SampleCount[1];
for (long i = 1; i < d; i++)
dFactorial.multiply(BigInteger.valueOf(i));
for (long i = 1; i < n; i++)
nFactorial.multiply(BigInteger.valueOf(i));
for (long i = 1; i < n - d; i++)
nMinusDFactorial.multiply(BigInteger.valueOf(i));
return nFactorial.divide(dFactorial.multiply(nMinusDFactorial));
}
private double computeFisherLD(double[] vec) {
// 1D, 2-classes
double mA = 0, mB = 0, sA = 0, sB = 0;
for (int i = 0; i < vec.length; i++) {
if (ClassLabels[i] == 0) {
mA += vec[i];
sA += vec[i] * vec[i];
} else {
mB += vec[i];
sB += vec[i] * vec[i];
}
}
mA /= SampleCount[0];
mB /= SampleCount[1];
sA = sA / SampleCount[0] - mA * mA;
sB = sB / SampleCount[1] - mB * mB;
return Math.abs(mA - mB) / (Math.sqrt(sA) + Math.sqrt(sB));
}
private double computeFSD(double[][] m, int d) {
double[][] xA = new double[d][SampleCount[0]];
double[][] xB = new double[d][SampleCount[1]];
for (int i = 0; i < m.length; i++) {
xA[i] = Arrays.copyOfRange(m[i], 0, SampleCount[0]);
xB[i] = Arrays.copyOfRange(m[i], SampleCount[0], SampleCount[0] + SampleCount[1]);
}
double[] mA = new double[d];
double[] mB = new double[d];
for (int i = 0; i < d; i++) {
mA[i] = 0;
mB[i] = 0;
for (int j = 0; j < xA[i].length; j++) {
mA[i] += xA[i][j];
}
for (int k = 0; k < xB[i].length; k++)
mB[i] += xB[i][k];
mA[i] /= SampleCount[0];
mB[i] /= SampleCount[1];
}
for (int i=0; i<m.length;i++){
for (int j1=0;j1<xA[i].length;j1++){
xA[i][j1]-=mA[i];
}
for (int j2=0;j2<xB[i].length;j2++){
xB[i][j2]-=mB[i];
}
}
Matrix matrixA = new Matrix(xA);
Matrix matrixB = new Matrix(xB);
Matrix matrixATransposed =matrixA.transpose();
Matrix matrixBTransposed =matrixB.transpose();
Matrix cA = matrixA.times(matrixATransposed);
Matrix cB = matrixB.times(matrixBTransposed);
double sA = cA.det();
double sB = cB.det();
double[] mS = new double[d];
for (int i = 0; i < d; i++)
mS[i] = Math.abs(mA[i] - mB[i]);
double mS2 = 0;
for (double mi : mS)
mS2 += mi * mi;
mS2 /= Math.sqrt(mS2);
return mS2 / (sA + sB);
}
private Matrix extractFeatures(Matrix C, double Ek, int k) {
Matrix evecs, evals;
// compute eigenvalues and eigenvectors
evecs = C.eig().getV();
evals = C.eig().getD();
// PM: projection matrix that will hold a set dominant eigenvectors
Matrix PM;
if (k > 0) {
// preset dimension of new feature space
// PM = new double[evecs.getRowDimension()][k];
PM = evecs.getMatrix(0, evecs.getRowDimension() - 1, evecs.getColumnDimension() - k,
evecs.getColumnDimension() - 1);
} else {
// dimension will be determined based on scatter energy
double TotEVal = evals.trace(); // total energy
double EAccum = 0;
int m = evals.getColumnDimension() - 1;
while (EAccum < Ek * TotEVal) {
EAccum += evals.get(m, m);
m--;
}
PM = evecs.getMatrix(0, evecs.getRowDimension() - 1, m + 1, evecs.getColumnDimension() - 1);
}
/*
* System.out.println("Eigenvectors"); for(int i=0; i<r; i++){ for(int
* j=0; j<c; j++){ System.out.print(evecs[i][j]+" "); }
* System.out.println(); } System.out.println("Eigenvalues"); for(int
* i=0; i<r; i++){ for(int j=0; j<c; j++){
* System.out.print(evals[i][j]+" "); } System.out.println(); }
*/
return PM;
}
private Matrix computeCovarianceMatrix(double[][] m) {
// double[][] C = new double[M.length][M.length];
Matrix M = new Matrix(m);
Matrix MT = M.transpose();
Matrix C = M.times(MT);
return C;
}
private double[][] centerAroundMean(double[][] M) {
double[] mean = new double[M.length];
for (int i = 0; i < M.length; i++)
for (int j = 0; j < M[0].length; j++)
mean[i] += M[i][j];
for (int i = 0; i < M.length; i++)
mean[i] /= M[0].length;
for (int i = 0; i < M.length; i++)
for (int j = 0; j < M[0].length; j++)
M[i][j] -= mean[i];
return M;
}
private double[][] projectSamples(Matrix FOld, Matrix TransformMat) {
return (FOld.transpose().times(TransformMat)).transpose().getArrayCopy();
}
}
class Classifier {
double[][] TrainingSet, TestSet;
int[] ClassLabels;
final int TRAIN_SET = 0, TEST_SET = 1;
void generateTraining_and_Test_Sets(double[][] Dataset, String TrainSetSize) {
int[] Index = new int[Dataset[0].length];
double Th = Double.parseDouble(TrainSetSize) / 100.0;
int TrainCount = 0, TestCount = 0;
for (int i = 0; i < Dataset[0].length; i++)
if (Math.random() <= Th) {
Index[i] = TRAIN_SET;
TrainCount++;
} else {
Index[i] = TEST_SET;
TestCount++;
}
TrainingSet = new double[Dataset.length][TrainCount];
TestSet = new double[Dataset.length][TestCount];
TrainCount = 0;
TestCount = 0;
// label vectors for training/test sets
for (int i = 0; i < Index.length; i++) {
if (Index[i] == TRAIN_SET) {
System.arraycopy(Dataset[i], 0, TrainingSet[TrainCount++], 0, Dataset[0].length);
} else
System.arraycopy(Dataset[i], 0, TestSet[TestCount++], 0, Dataset[0].length);
}
}
protected void trainClissifier(double[][] TrainSet) {
}
}
class NNClassifier extends Classifier {
@Override
protected void trainClissifier(double[][] TrainSet) {
}
} | UTF-8 | Java | 27,086 | java | PR_GUI.java | Java | [
{
"context": "ted on 2015-03-05, 19:40:56\n */\n\n/**\n *\n * @author krzy\n */\npublic class PR_GUI extends javax.swing.JFram",
"end": 452,
"score": 0.9995759725570679,
"start": 448,
"tag": "USERNAME",
"value": "krzy"
}
] | null | [] |
import java.io.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import Jama.*;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* PR_GUI.java
*
* Created on 2015-03-05, 19:40:56
*/
/**
*
* @author krzy
*/
public class PR_GUI extends javax.swing.JFrame {
String InData; // dataset from a text file will be placed here
int ClassCount = 0, FeatureCount = 0;
double[][] F, FNew; // original feature matrix and transformed feature
// matrix
int[] ClassLabels, SampleCount;
String[] ClassNames;
/** Creates new form PR_GUI */
public PR_GUI() {
initComponents();
setSize(720, 410);
}
/**
* 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() {
rbg_F = new javax.swing.ButtonGroup();
b_read = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
l_dataset_name_l = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
l_dataset_name = new javax.swing.JLabel();
l_nfeatures = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
selbox_nfeat = new javax.swing.JComboBox();
jSeparator1 = new javax.swing.JSeparator();
f_rb_extr = new javax.swing.JRadioButton();
f_rb_sel = new javax.swing.JRadioButton();
b_deriveFS = new javax.swing.JButton();
jLabel10 = new javax.swing.JLabel();
f_combo_criterion = new javax.swing.JComboBox();
f_combo_PCA_LDA = new javax.swing.JComboBox();
jLabel12 = new javax.swing.JLabel();
tf_PCA_Energy = new javax.swing.JTextField();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
l_NewDim = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jComboBox2 = new javax.swing.JComboBox();
b_Train = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jLabel16 = new javax.swing.JLabel();
tf_TrainSetSize = new javax.swing.JTextField();
jLabel17 = new javax.swing.JLabel();
jPanel5 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
l_FLD_winner = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
l_FLD_val = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
b_read.setText("Read dataset");
b_read.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_readActionPerformed(evt);
}
});
getContentPane().add(b_read);
b_read.setBounds(20, 10, 130, 25);
jPanel2.setBackground(new java.awt.Color(204, 255, 255));
jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabel1.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N
jLabel1.setText("Dataset info");
l_dataset_name_l.setText("Name:");
jLabel3.setText("Classes:");
jLabel4.setText("Features:");
l_dataset_name.setText("...");
l_nfeatures.setText("...");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel2Layout.createSequentialGroup().addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup().addComponent(l_dataset_name_l)
.addGap(18, 18, 18).addComponent(l_dataset_name))
.addComponent(jLabel1))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup().addGap(115, 115, 115)
.addComponent(jLabel3))
.addGroup(jPanel2Layout.createSequentialGroup().addGap(94, 94, 94)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(l_nfeatures)))
.addGap(100, 100, 100)));
jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1).addComponent(jLabel3))
.addGap(10, 10, 10)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(l_dataset_name_l).addComponent(jLabel4).addComponent(l_dataset_name)
.addComponent(l_nfeatures))
.addContainerGap(24, Short.MAX_VALUE)));
getContentPane().add(jPanel2);
jPanel2.setBounds(10, 50, 320, 80);
jButton2.setText("Parse dataset");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
getContentPane().add(jButton2);
jButton2.setBounds(190, 10, 130, 25);
jPanel3.setBackground(new java.awt.Color(255, 255, 204));
jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jPanel3.setLayout(null);
jLabel5.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N
jLabel5.setText("Feature space");
jPanel3.add(jLabel5);
jLabel5.setBounds(14, 2, 118, 26);
jLabel6.setText("FS Dimension");
jPanel3.add(jLabel6);
jLabel6.setBounds(178, 9, 78, 16);
String[] dimensions = new String[63];
for (Integer i = 1; i <= 63; i++)
dimensions[i - 1] = i.toString();
selbox_nfeat.setModel(new javax.swing.DefaultComboBoxModel(dimensions));
selbox_nfeat.setEnabled(true);
jPanel3.add(selbox_nfeat);
selbox_nfeat.setBounds(268, 6, 34, 22);
jPanel3.add(jSeparator1);
jSeparator1.setBounds(14, 41, 290, 10);
f_rb_extr.setBackground(new java.awt.Color(255, 255, 204));
rbg_F.add(f_rb_extr);
f_rb_extr.setText("Feature extraction");
f_rb_extr.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
f_rb_extrActionPerformed(evt);
}
});
jPanel3.add(f_rb_extr);
f_rb_extr.setBounds(10, 110, 133, 25);
f_rb_sel.setBackground(new java.awt.Color(255, 255, 204));
rbg_F.add(f_rb_sel);
f_rb_sel.setSelected(true);
f_rb_sel.setText("Feature selection");
f_rb_sel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
f_rb_selActionPerformed(evt);
}
});
jPanel3.add(f_rb_sel);
f_rb_sel.setBounds(10, 60, 127, 25);
b_deriveFS.setText("Derive Feature Space");
b_deriveFS.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_deriveFSActionPerformed(evt);
}
});
jPanel3.add(b_deriveFS);
b_deriveFS.setBounds(10, 180, 292, 25);
jLabel10.setText("Criterion");
jPanel3.add(jLabel10);
jLabel10.setBounds(200, 50, 49, 16);
f_combo_criterion.setModel(
new javax.swing.DefaultComboBoxModel(new String[] { "Fisher discriminant", "Classification error" }));
f_combo_criterion.setEnabled(false);
jPanel3.add(f_combo_criterion);
f_combo_criterion.setBounds(160, 70, 140, 22);
f_combo_PCA_LDA.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "PCA", "LDA" }));
f_combo_PCA_LDA.setEnabled(false);
jPanel3.add(f_combo_PCA_LDA);
f_combo_PCA_LDA.setBounds(190, 110, 70, 22);
jLabel12.setText("Energy");
jPanel3.add(jLabel12);
jLabel12.setBounds(20, 150, 39, 16);
tf_PCA_Energy.setText("80");
jPanel3.add(tf_PCA_Energy);
tf_PCA_Energy.setBounds(70, 150, 30, 22);
jLabel14.setText("%");
jPanel3.add(jLabel14);
jLabel14.setBounds(110, 150, 20, 16);
jLabel15.setText("New dimension:");
jPanel3.add(jLabel15);
jLabel15.setBounds(160, 150, 92, 16);
l_NewDim.setText("...");
jPanel3.add(l_NewDim);
l_NewDim.setBounds(270, 150, 30, 16);
getContentPane().add(jPanel3);
jPanel3.setBounds(10, 140, 320, 220);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 156, Short.MAX_VALUE));
jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 126, Short.MAX_VALUE));
getContentPane().add(jPanel1);
jPanel1.setBounds(530, 10, 160, 130);
jPanel4.setBackground(new java.awt.Color(204, 255, 204));
jPanel4.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jPanel4.setLayout(null);
jLabel8.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N
jLabel8.setText("Classifier");
jPanel4.add(jLabel8);
jLabel8.setBounds(10, 0, 79, 26);
jLabel9.setText("Method");
jPanel4.add(jLabel9);
jLabel9.setBounds(14, 44, 42, 16);
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Nearest neighbor (NN)",
"Nearest Mean (NM)", "k-Nearest Neighbor (k-NN)", "k-Nearest Mean (k-NM)" }));
jPanel4.add(jComboBox2);
jComboBox2.setBounds(74, 41, 178, 22);
b_Train.setText("Train");
b_Train.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_TrainActionPerformed(evt);
}
});
jPanel4.add(b_Train);
b_Train.setBounds(40, 130, 98, 25);
jButton4.setText("Execute");
jPanel4.add(jButton4);
jButton4.setBounds(210, 130, 96, 25);
jLabel16.setText("Training part:");
jPanel4.add(jLabel16);
jLabel16.setBounds(20, 170, 80, 16);
tf_TrainSetSize.setText("80");
jPanel4.add(tf_TrainSetSize);
tf_TrainSetSize.setBounds(110, 170, 20, 22);
jLabel17.setText("%");
jPanel4.add(jLabel17);
jLabel17.setBounds(140, 170, 20, 16);
getContentPane().add(jPanel4);
jPanel4.setBounds(340, 150, 350, 210);
jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Results"));
jPanel5.setLayout(null);
jLabel2.setText("FS Winner:");
jPanel5.add(jLabel2);
jLabel2.setBounds(10, 30, 70, 16);
l_FLD_winner.setText("xxx");
jPanel5.add(l_FLD_winner);
l_FLD_winner.setBounds(100, 30, 18, 16);
jLabel13.setText("FLD value: ");
jPanel5.add(jLabel13);
jLabel13.setBounds(10, 60, 70, 16);
l_FLD_val.setText("vvv");
jPanel5.add(l_FLD_val);
l_FLD_val.setBounds(100, 60, 48, 16);
getContentPane().add(jPanel5);
jPanel5.setBounds(340, 10, 160, 130);
pack();
}// </editor-fold>//GEN-END:initComponents
private void f_rb_selActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_f_rb_selActionPerformed
f_combo_criterion.setEnabled(true);
f_combo_PCA_LDA.setEnabled(false);
}// GEN-LAST:event_f_rb_selActionPerformed
private void f_rb_extrActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_f_rb_extrActionPerformed
f_combo_criterion.setEnabled(false);
f_combo_PCA_LDA.setEnabled(true);
}// GEN-LAST:event_f_rb_extrActionPerformed
private void b_readActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_b_readActionPerformed
// reads in a text file; contents is placed into a variable of String
// type
InData = readDataSet();
}// GEN-LAST:event_b_readActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton2ActionPerformed
// Analyze text inputted from a file: determine class number and labels
// and number
// of features; build feature matrix: columns - samples, rows - features
try {
if (InData != null) {
getDatasetParameters();
l_nfeatures.setText(FeatureCount + "");
fillFeatureMatrix();
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}// GEN-LAST:event_jButton2ActionPerformed
private void b_deriveFSActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_b_deriveFSActionPerformed
// derive optimal feature space
if (F == null)
return;
if (f_rb_sel.isSelected()) {
// the chosen strategy is feature selection
int[] flags = new int[FeatureCount];
selectFeatures(flags, Integer.parseInt((String) selbox_nfeat.getSelectedItem()));
} else if (f_rb_extr.isSelected()) {
double TotEnergy = Double.parseDouble(tf_PCA_Energy.getText()) / 100.0;
// Target dimension (if k>0) or flag for energy-based dimension
// (k=0)
int k = 0;
// double[][] FF = { {1,1}, {1,2}};
// double[][] FF = { {-2,0,2}, {-1,0,1}};
// F is an array of initial features, FNew is the resulting array
double[][] FFNorm = centerAroundMean(F);
Matrix Cov = computeCovarianceMatrix(FFNorm);
Matrix TransformMat = extractFeatures(Cov, TotEnergy, k);
FNew = projectSamples(new Matrix(FFNorm), TransformMat);
// FNew is a matrix with samples projected to a new feature space
l_NewDim.setText(FNew.length + "");
}
}// GEN-LAST:event_b_deriveFSActionPerformed
private void b_TrainActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_b_TrainActionPerformed
// first step: split dataset (in new feature space) into training /
// testing parts
if (FNew == null)
return; // no reduced feature space have been derived
Classifier Cl = new Classifier();
Cl.generateTraining_and_Test_Sets(FNew, tf_TrainSetSize.getText());
}// GEN-LAST:event_b_TrainActionPerformed
/**
* @param args
* the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PR_GUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton b_Train;
private javax.swing.JButton b_deriveFS;
private javax.swing.JButton b_read;
private javax.swing.JComboBox f_combo_PCA_LDA;
private javax.swing.JComboBox f_combo_criterion;
private javax.swing.JRadioButton f_rb_extr;
private javax.swing.JRadioButton f_rb_sel;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton4;
private javax.swing.JComboBox jComboBox2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JLabel l_FLD_val;
private javax.swing.JLabel l_FLD_winner;
private javax.swing.JLabel l_NewDim;
private javax.swing.JLabel l_dataset_name;
private javax.swing.JLabel l_dataset_name_l;
private javax.swing.JLabel l_nfeatures;
private javax.swing.ButtonGroup rbg_F;
private javax.swing.JComboBox selbox_nfeat;
private javax.swing.JTextField tf_PCA_Energy;
private javax.swing.JTextField tf_TrainSetSize;
// End of variables declaration//GEN-END:variables
private String readDataSet() {
String s_tmp, s_out = "";
JFileChooser jfc = new JFileChooser();
jfc.setCurrentDirectory(new File(".."));
FileNameExtensionFilter filter = new FileNameExtensionFilter("Datasets - plain text files", "txt");
jfc.setFileFilter(filter);
if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
try {
BufferedReader br = new BufferedReader(new FileReader(jfc.getSelectedFile()));
while ((s_tmp = br.readLine()) != null)
s_out += s_tmp + '$';
br.close();
l_dataset_name.setText(jfc.getSelectedFile().getName());
} catch (Exception e) {
}
}
return s_out;
}
private void getDatasetParameters() throws Exception {
// based on data stored in InData determine: class count and names,
// number of samples
// and number of features; set the corresponding variables
String stmp = InData, saux = "";
// analyze the first line and get feature count: assume that number of
// features
// equals number of commas
saux = InData.substring(InData.indexOf(',') + 1, InData.indexOf('$'));
if (saux.length() == 0)
throw new Exception("The first line is empty");
// saux stores the first line beginning from the first comma
int count = 0;
while (saux.indexOf(',') > 0) {
saux = saux.substring(saux.indexOf(',') + 1);
count++;
}
FeatureCount = count + 1; // the first parameter
// Determine number of classes, class names and number of samples per
// class
boolean New;
int index = -1;
List<String> NameList = new ArrayList<String>();
List<Integer> CountList = new ArrayList<Integer>();
List<Integer> LabelList = new ArrayList<Integer>();
while (stmp.length() > 1) {
saux = stmp.substring(0, stmp.indexOf(' '));
New = true;
index++; // new class index
for (int i = 0; i < NameList.size(); i++)
if (saux.equals(NameList.get(i))) {
New = false;
index = i; // class index
}
if (New) {
NameList.add(saux);
CountList.add(0);
} else {
CountList.set(index, CountList.get(index).intValue() + 1);
}
LabelList.add(index); // class index for current row
stmp = stmp.substring(stmp.indexOf('$') + 1);
}
// based on results of the above analysis, create variables
ClassNames = new String[NameList.size()];
for (int i = 0; i < ClassNames.length; i++)
ClassNames[i] = NameList.get(i);
SampleCount = new int[CountList.size()];
for (int i = 0; i < SampleCount.length; i++)
SampleCount[i] = CountList.get(i).intValue() + 1;
ClassLabels = new int[LabelList.size()];
for (int i = 0; i < ClassLabels.length; i++)
ClassLabels[i] = LabelList.get(i).intValue();
System.out.println(SampleCount[0] + SampleCount[1]);
}
private void fillFeatureMatrix() throws Exception {
// having determined array size and class labels, fills in the feature
// matrix
int n = 0;
String saux, stmp = InData;
for (int i = 0; i < SampleCount.length; i++)
n += SampleCount[i];
if (n <= 0)
throw new Exception("no samples found");
F = new double[FeatureCount][n]; // samples are placed column-wise
for (int j = 0; j < n; j++) {
saux = stmp.substring(0, stmp.indexOf('$'));
saux = saux.substring(stmp.indexOf(',') + 1);
for (int i = 0; i < FeatureCount - 1; i++) {
F[i][j] = Double.parseDouble(saux.substring(0, saux.indexOf(',')));
saux = saux.substring(saux.indexOf(',') + 1);
}
F[FeatureCount - 1][j] = Double.parseDouble(saux);
stmp = stmp.substring(stmp.indexOf('$') + 1);
}
int cc = 1;
}
private void selectFeatures(int[] flags, int d) {
// for now: check all individual features using 1D, 2-class Fisher
// criterion
if (d == 1) {
double FLD = 0, tmp;
int max_ind = -1;
for (int i = 0; i < FeatureCount; i++) {
if ((tmp = computeFisherLD(F[i])) > FLD) {
FLD = tmp;
max_ind = i + 1;
}
}
l_FLD_winner.setText(max_ind + "");
l_FLD_val.setText(FLD + "");
} else if (d > 1) {
double FSD = 0, tmp;
int fMaxIndex = -1;
List<double[][]> featuresCombinations = new ArrayList<double[][]>();
double[][] featuresCombination = new double[d][SampleCount[0] + SampleCount[1]];
generateFeaturesCombinations(featuresCombinations, 0, d, featuresCombination);
for (int i = 0; i < featuresCombinations.size(); i++) {
if ((tmp = computeFSD(featuresCombinations.get(i), d)) > FSD) {
System.out.println("Calculating Fisher for feature " + i+1);
FSD = tmp;
fMaxIndex++;
System.out.println("The Fisher for feature " + i+1 + " equals " + FSD);
}
}
l_FLD_winner.setText(fMaxIndex + "");
l_FLD_val.setText(FSD + "");
}
// to do: compute for higher dimensional spaces, use e.g. SFS for
// candidate selection
}
List<Integer> numbers=new ArrayList<Integer>();
private void generateFeaturesCombinations(List<double[][]> featuresCombinations, int start, int dimensions,
double[][] featureCombination) {
if (dimensions == 0) {
featuresCombinations.add(featureCombination);
System.out.println(numbers);
System.out.println("The matrix has been added successfully!");
return;
}
for (int i = start; i < F.length; i++) {
featureCombination[featureCombination.length - dimensions] = Arrays.copyOfRange(F[i], 0,
SampleCount[0] + SampleCount[1]);
numbers.add(i);
generateFeaturesCombinations(featuresCombinations, i + 1, dimensions - 1, featureCombination);
}
}
private BigInteger calculateCombinationsCount(int d) {
BigInteger dFactorial = BigInteger.valueOf(1), nFactorial = BigInteger.valueOf(1),
nMinusDFactorial = BigInteger.valueOf(1);
int n = SampleCount[0] + SampleCount[1];
for (long i = 1; i < d; i++)
dFactorial.multiply(BigInteger.valueOf(i));
for (long i = 1; i < n; i++)
nFactorial.multiply(BigInteger.valueOf(i));
for (long i = 1; i < n - d; i++)
nMinusDFactorial.multiply(BigInteger.valueOf(i));
return nFactorial.divide(dFactorial.multiply(nMinusDFactorial));
}
private double computeFisherLD(double[] vec) {
// 1D, 2-classes
double mA = 0, mB = 0, sA = 0, sB = 0;
for (int i = 0; i < vec.length; i++) {
if (ClassLabels[i] == 0) {
mA += vec[i];
sA += vec[i] * vec[i];
} else {
mB += vec[i];
sB += vec[i] * vec[i];
}
}
mA /= SampleCount[0];
mB /= SampleCount[1];
sA = sA / SampleCount[0] - mA * mA;
sB = sB / SampleCount[1] - mB * mB;
return Math.abs(mA - mB) / (Math.sqrt(sA) + Math.sqrt(sB));
}
private double computeFSD(double[][] m, int d) {
double[][] xA = new double[d][SampleCount[0]];
double[][] xB = new double[d][SampleCount[1]];
for (int i = 0; i < m.length; i++) {
xA[i] = Arrays.copyOfRange(m[i], 0, SampleCount[0]);
xB[i] = Arrays.copyOfRange(m[i], SampleCount[0], SampleCount[0] + SampleCount[1]);
}
double[] mA = new double[d];
double[] mB = new double[d];
for (int i = 0; i < d; i++) {
mA[i] = 0;
mB[i] = 0;
for (int j = 0; j < xA[i].length; j++) {
mA[i] += xA[i][j];
}
for (int k = 0; k < xB[i].length; k++)
mB[i] += xB[i][k];
mA[i] /= SampleCount[0];
mB[i] /= SampleCount[1];
}
for (int i=0; i<m.length;i++){
for (int j1=0;j1<xA[i].length;j1++){
xA[i][j1]-=mA[i];
}
for (int j2=0;j2<xB[i].length;j2++){
xB[i][j2]-=mB[i];
}
}
Matrix matrixA = new Matrix(xA);
Matrix matrixB = new Matrix(xB);
Matrix matrixATransposed =matrixA.transpose();
Matrix matrixBTransposed =matrixB.transpose();
Matrix cA = matrixA.times(matrixATransposed);
Matrix cB = matrixB.times(matrixBTransposed);
double sA = cA.det();
double sB = cB.det();
double[] mS = new double[d];
for (int i = 0; i < d; i++)
mS[i] = Math.abs(mA[i] - mB[i]);
double mS2 = 0;
for (double mi : mS)
mS2 += mi * mi;
mS2 /= Math.sqrt(mS2);
return mS2 / (sA + sB);
}
private Matrix extractFeatures(Matrix C, double Ek, int k) {
Matrix evecs, evals;
// compute eigenvalues and eigenvectors
evecs = C.eig().getV();
evals = C.eig().getD();
// PM: projection matrix that will hold a set dominant eigenvectors
Matrix PM;
if (k > 0) {
// preset dimension of new feature space
// PM = new double[evecs.getRowDimension()][k];
PM = evecs.getMatrix(0, evecs.getRowDimension() - 1, evecs.getColumnDimension() - k,
evecs.getColumnDimension() - 1);
} else {
// dimension will be determined based on scatter energy
double TotEVal = evals.trace(); // total energy
double EAccum = 0;
int m = evals.getColumnDimension() - 1;
while (EAccum < Ek * TotEVal) {
EAccum += evals.get(m, m);
m--;
}
PM = evecs.getMatrix(0, evecs.getRowDimension() - 1, m + 1, evecs.getColumnDimension() - 1);
}
/*
* System.out.println("Eigenvectors"); for(int i=0; i<r; i++){ for(int
* j=0; j<c; j++){ System.out.print(evecs[i][j]+" "); }
* System.out.println(); } System.out.println("Eigenvalues"); for(int
* i=0; i<r; i++){ for(int j=0; j<c; j++){
* System.out.print(evals[i][j]+" "); } System.out.println(); }
*/
return PM;
}
private Matrix computeCovarianceMatrix(double[][] m) {
// double[][] C = new double[M.length][M.length];
Matrix M = new Matrix(m);
Matrix MT = M.transpose();
Matrix C = M.times(MT);
return C;
}
private double[][] centerAroundMean(double[][] M) {
double[] mean = new double[M.length];
for (int i = 0; i < M.length; i++)
for (int j = 0; j < M[0].length; j++)
mean[i] += M[i][j];
for (int i = 0; i < M.length; i++)
mean[i] /= M[0].length;
for (int i = 0; i < M.length; i++)
for (int j = 0; j < M[0].length; j++)
M[i][j] -= mean[i];
return M;
}
private double[][] projectSamples(Matrix FOld, Matrix TransformMat) {
return (FOld.transpose().times(TransformMat)).transpose().getArrayCopy();
}
}
class Classifier {
double[][] TrainingSet, TestSet;
int[] ClassLabels;
final int TRAIN_SET = 0, TEST_SET = 1;
void generateTraining_and_Test_Sets(double[][] Dataset, String TrainSetSize) {
int[] Index = new int[Dataset[0].length];
double Th = Double.parseDouble(TrainSetSize) / 100.0;
int TrainCount = 0, TestCount = 0;
for (int i = 0; i < Dataset[0].length; i++)
if (Math.random() <= Th) {
Index[i] = TRAIN_SET;
TrainCount++;
} else {
Index[i] = TEST_SET;
TestCount++;
}
TrainingSet = new double[Dataset.length][TrainCount];
TestSet = new double[Dataset.length][TestCount];
TrainCount = 0;
TestCount = 0;
// label vectors for training/test sets
for (int i = 0; i < Index.length; i++) {
if (Index[i] == TRAIN_SET) {
System.arraycopy(Dataset[i], 0, TrainingSet[TrainCount++], 0, Dataset[0].length);
} else
System.arraycopy(Dataset[i], 0, TestSet[TestCount++], 0, Dataset[0].length);
}
}
protected void trainClissifier(double[][] TrainSet) {
}
}
class NNClassifier extends Classifier {
@Override
protected void trainClissifier(double[][] TrainSet) {
}
} | 27,086 | 0.679982 | 0.648527 | 804 | 32.689056 | 24.602417 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.971393 | false | false | 2 |
618998a2e78ebfaf5c074399a4ceab45dfd4a308 | 2,284,922,638,057 | 46f9fb331c9c04f6d9dab7e4a373bfa9bba2ac2e | /KeepCode/app/src/main/java/com/example/keepcode/AddNote.java | e17d9d038756e8e6a865ceaa8a5c67b0a52f5af4 | [
"MIT"
] | permissive | jynlin3/Mobile-computing | https://github.com/jynlin3/Mobile-computing | 34a6f8fa6fb263e113e57212f3640d80ea125efe | a8eb09caaf321efa5604f21091f5bd9a4dadee2e | refs/heads/master | 2020-12-10T02:33:15.877000 | 2020-03-19T01:44:32 | 2020-03-19T01:44:32 | 233,482,541 | 0 | 0 | MIT | false | 2020-03-19T01:44:34 | 2020-01-13T00:50:43 | 2020-03-19T01:02:01 | 2020-03-19T01:44:33 | 462 | 0 | 0 | 0 | Java | false | false | package com.example.keepcode;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.preference.PreferenceManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.cryptobrewery.syntaxview.SyntaxView;
public class AddNote extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Toolbar toolbar;
EditText noteTitle;
Note note;
ArrayList<Spinner> spinners;
ArrayList<SyntaxView> codeViews;
ArrayList<EditText> textViews;
LinearLayout layout;
Map<String, List<String>> langTagMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_note);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("New Note");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
spinners = new ArrayList<>();
codeViews = new ArrayList<>();
textViews = new ArrayList<>();
noteTitle = findViewById(R.id.noteTitle);
EditText noteDetails = findViewById(R.id.noteDetails);
textViews.add(noteDetails);
layout = findViewById(R.id.content);
initializeLangTagMap();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String font = sharedPref.getString("Font", "Roboto");
// Debug logging
// Toast toast = Toast.makeText(getApplicationContext(), "Font: " + font, Toast.LENGTH_SHORT);
// toast.show();
note = (Note) getIntent().getSerializableExtra("note");
String savedNoteTitle = null;
String savedNoteContent = null;
if (savedInstanceState != null) {
// Load title and content from the saved instance
savedNoteTitle = savedInstanceState.getString("title");
savedNoteContent = savedInstanceState.getString("content");
}
else if (note != null) {
// Load title and content from database
savedNoteTitle = note.getTitle();
savedNoteContent = note.getContent();
}
if(savedNoteContent != null && savedNoteTitle != null)
{
noteTitle.setText(savedNoteTitle);
getSupportActionBar().setTitle(savedNoteTitle);
// Create Code View and Text View according to the saved instance
String[] contents = savedNoteContent.split(getSupportLang());
Pattern pattern = Pattern.compile(getSupportLang());
Matcher matcher = pattern.matcher(savedNoteContent);
noteDetails.setText(contents[0]);
for (int i = 1; i<contents.length;i+=2)
{
matcher.find();
matcher.find();
String codeLang = matcher.group().replaceAll("<</|>>", "");
// Special handle for C++, because + is a special character in regular expression
if (codeLang.compareTo("Cpp") == 0)
codeLang = "C++";
addCodeView(codeLang);
codeViews.get(i/2).getCode().setText(contents[i]);
if(i+1 < contents.length)
textViews.get(i/2+1).setText(contents[i+1]);
}
}
setFont(font);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.save_menu, menu);
return true;
}
private int getIndex(Spinner spinner, String myString){
for (int i = 0; i < spinner.getCount(); i++)
{
if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(myString))
{
return i;
}
}
return 0;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.delete:
if(note != null) {
NoteDatabase.getInstance(this).noteDao().deleteByNoteId(note.getId());
Toast.makeText(this, "Note: " + noteTitle.getText().toString() + " is deleted.", Toast.LENGTH_SHORT)
.show();
}
goToMain();
break;
case R.id.addCode:
addCodeView("Java");
break;
case R.id.share:
shareNote();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void goToMain(){
setResult(RESULT_OK);
finish();
}
private String getNoteDetails(boolean addTags)
{
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < textViews.size(); i++)
{
sb.append(textViews.get(i).getText().toString());
if(i<codeViews.size()) {
if(addTags)
sb.append(langTagMap.get(spinners.get(i).getSelectedItem().toString()).get(0));
else
sb.append("\n\n");
sb.append(codeViews.get(i).getCode().getText().toString());
if(addTags)
sb.append(langTagMap.get(spinners.get(i).getSelectedItem().toString()).get(1));
else
sb.append("\n\n");
}
}
return sb.toString();
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("title", noteTitle.getText().toString());
outState.putString("content", getNoteDetails(true));
}
private void addCodeView(String lang)
{
//create spinner to choose programming language
List<String> spinnerArray = Arrays.asList(SyntaxView.getSupportLanguage());
Spinner spinner = new Spinner(this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
spinner.setAdapter(spinnerArrayAdapter);
spinner.setSelection(spinnerArray.indexOf(lang));
spinner.setOnItemSelectedListener(new SpinnerActionListener(codeViews.size()));
layout.addView(spinner);
spinners.add(spinner);
//create SyntaxView
SyntaxView codeView = new SyntaxView(this);
codeView.setAutoIndent(true);
codeView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
layout.addView(codeView);
codeViews.add(codeView);
//create EditText
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
EditText textView = (EditText) inflater.inflate(R.layout.multiedittext, layout, false);
layout.addView(textView);
textViews.add(textView);
}
@Override
public void onBackPressed() {
// saveNote();
Toast.makeText(this, "Note: " + noteTitle.getText().toString() + " is saved.", Toast.LENGTH_SHORT)
.show();
super.onBackPressed();
}
public void setFont(String fontName)
{
String file = "";
if (fontName.equals("Open Sans"))
{
file = "OpenSans-Regular.ttf";
}
if (fontName.equals("Inconsolata"))
{
file = "progfont.ttf";
}
if (fontName.equals("Roboto"))
{
file = "Roboto-Regular.ttf";
}
// Set the fonts
Typeface tf = Typeface.createFromAsset(getAssets(), file);
for (EditText tv : textViews )
{
tv.setTypeface(tf);
}
for (SyntaxView sv : codeViews )
{
sv.setFont(tf);
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String fontName = (String) parent.getSelectedItem();
ArrayAdapter adapter = (ArrayAdapter) parent.getAdapter();
adapter.getPosition(fontName);
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(getString(R.string.font_key), fontName);
editor.apply();
setFont(fontName);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
private class SpinnerActionListener implements AdapterView.OnItemSelectedListener{
private int index;
public SpinnerActionListener(int index)
{
this.index = index;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = parent.getItemAtPosition(position).toString();
SyntaxView curCodeView = codeViews.get(index);
// Update syntax highlighting for different languages
String code = curCodeView.getCode().getText().toString();
curCodeView.getCode().setText("");
curCodeView.setLanguage(selectedItem);
curCodeView.getCode().setText(code);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
private void initializeLangTagMap(){
langTagMap = new HashMap<>();
String[] langs = SyntaxView.getSupportLanguage();
for (String l : langs) {
List<String> tags = new ArrayList<>();
// Special handle for C++, because + is a special character in regular expression.
if (l.compareTo("C++") == 0) {
tags.add("<<Cpp>>");
tags.add("<</Cpp>>");
}
else {
tags.add("<<" + l + ">>");
tags.add("<</" + l + ">>");
}
langTagMap.put(l, tags);
}
}
private String getSupportLang()
{
StringBuffer sb = new StringBuffer("");
for(List<String>tags:langTagMap.values())
{
for(String tag:tags)
{
sb.append(tag);
sb.append("|");
}
}
if(sb.length() > 0)
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
@Override
public boolean onSupportNavigateUp()
{
onBackPressed();
return true;
}
private void shareNote()
{
Intent mSharingIntent = new Intent(Intent.ACTION_SEND);
mSharingIntent.setType("text/plain");
mSharingIntent.putExtra(Intent.EXTRA_SUBJECT, noteTitle.getText().toString());
mSharingIntent.putExtra(Intent.EXTRA_TEXT, getNoteDetails(false));
startActivity(Intent.createChooser(mSharingIntent, "Share text via"));
}
@Override
protected void onPause() {
saveNote();
super.onPause();
}
private void saveNote(){
Date currentTime = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
if (note==null) {
// Add Note
Note newNote = new Note(noteTitle.getText().toString(), getNoteDetails(true),
dateFormat.format(currentTime), dateFormat.format(currentTime));
NoteDatabase.getInstance(this).noteDao().insert(newNote);
}
else {
// Update Note
Note newNote = new Note(note.getId(), noteTitle.getText().toString(), getNoteDetails(true),
note.getCreate_time(), dateFormat.format(currentTime));
NoteDatabase.getInstance(this).noteDao().update(newNote);
}
}
}
| UTF-8 | Java | 13,049 | java | AddNote.java | Java | [] | null | [] | package com.example.keepcode;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.preference.PreferenceManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.cryptobrewery.syntaxview.SyntaxView;
public class AddNote extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Toolbar toolbar;
EditText noteTitle;
Note note;
ArrayList<Spinner> spinners;
ArrayList<SyntaxView> codeViews;
ArrayList<EditText> textViews;
LinearLayout layout;
Map<String, List<String>> langTagMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_note);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("New Note");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
spinners = new ArrayList<>();
codeViews = new ArrayList<>();
textViews = new ArrayList<>();
noteTitle = findViewById(R.id.noteTitle);
EditText noteDetails = findViewById(R.id.noteDetails);
textViews.add(noteDetails);
layout = findViewById(R.id.content);
initializeLangTagMap();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String font = sharedPref.getString("Font", "Roboto");
// Debug logging
// Toast toast = Toast.makeText(getApplicationContext(), "Font: " + font, Toast.LENGTH_SHORT);
// toast.show();
note = (Note) getIntent().getSerializableExtra("note");
String savedNoteTitle = null;
String savedNoteContent = null;
if (savedInstanceState != null) {
// Load title and content from the saved instance
savedNoteTitle = savedInstanceState.getString("title");
savedNoteContent = savedInstanceState.getString("content");
}
else if (note != null) {
// Load title and content from database
savedNoteTitle = note.getTitle();
savedNoteContent = note.getContent();
}
if(savedNoteContent != null && savedNoteTitle != null)
{
noteTitle.setText(savedNoteTitle);
getSupportActionBar().setTitle(savedNoteTitle);
// Create Code View and Text View according to the saved instance
String[] contents = savedNoteContent.split(getSupportLang());
Pattern pattern = Pattern.compile(getSupportLang());
Matcher matcher = pattern.matcher(savedNoteContent);
noteDetails.setText(contents[0]);
for (int i = 1; i<contents.length;i+=2)
{
matcher.find();
matcher.find();
String codeLang = matcher.group().replaceAll("<</|>>", "");
// Special handle for C++, because + is a special character in regular expression
if (codeLang.compareTo("Cpp") == 0)
codeLang = "C++";
addCodeView(codeLang);
codeViews.get(i/2).getCode().setText(contents[i]);
if(i+1 < contents.length)
textViews.get(i/2+1).setText(contents[i+1]);
}
}
setFont(font);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.save_menu, menu);
return true;
}
private int getIndex(Spinner spinner, String myString){
for (int i = 0; i < spinner.getCount(); i++)
{
if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(myString))
{
return i;
}
}
return 0;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.delete:
if(note != null) {
NoteDatabase.getInstance(this).noteDao().deleteByNoteId(note.getId());
Toast.makeText(this, "Note: " + noteTitle.getText().toString() + " is deleted.", Toast.LENGTH_SHORT)
.show();
}
goToMain();
break;
case R.id.addCode:
addCodeView("Java");
break;
case R.id.share:
shareNote();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void goToMain(){
setResult(RESULT_OK);
finish();
}
private String getNoteDetails(boolean addTags)
{
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < textViews.size(); i++)
{
sb.append(textViews.get(i).getText().toString());
if(i<codeViews.size()) {
if(addTags)
sb.append(langTagMap.get(spinners.get(i).getSelectedItem().toString()).get(0));
else
sb.append("\n\n");
sb.append(codeViews.get(i).getCode().getText().toString());
if(addTags)
sb.append(langTagMap.get(spinners.get(i).getSelectedItem().toString()).get(1));
else
sb.append("\n\n");
}
}
return sb.toString();
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("title", noteTitle.getText().toString());
outState.putString("content", getNoteDetails(true));
}
private void addCodeView(String lang)
{
//create spinner to choose programming language
List<String> spinnerArray = Arrays.asList(SyntaxView.getSupportLanguage());
Spinner spinner = new Spinner(this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
spinner.setAdapter(spinnerArrayAdapter);
spinner.setSelection(spinnerArray.indexOf(lang));
spinner.setOnItemSelectedListener(new SpinnerActionListener(codeViews.size()));
layout.addView(spinner);
spinners.add(spinner);
//create SyntaxView
SyntaxView codeView = new SyntaxView(this);
codeView.setAutoIndent(true);
codeView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
layout.addView(codeView);
codeViews.add(codeView);
//create EditText
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
EditText textView = (EditText) inflater.inflate(R.layout.multiedittext, layout, false);
layout.addView(textView);
textViews.add(textView);
}
@Override
public void onBackPressed() {
// saveNote();
Toast.makeText(this, "Note: " + noteTitle.getText().toString() + " is saved.", Toast.LENGTH_SHORT)
.show();
super.onBackPressed();
}
public void setFont(String fontName)
{
String file = "";
if (fontName.equals("Open Sans"))
{
file = "OpenSans-Regular.ttf";
}
if (fontName.equals("Inconsolata"))
{
file = "progfont.ttf";
}
if (fontName.equals("Roboto"))
{
file = "Roboto-Regular.ttf";
}
// Set the fonts
Typeface tf = Typeface.createFromAsset(getAssets(), file);
for (EditText tv : textViews )
{
tv.setTypeface(tf);
}
for (SyntaxView sv : codeViews )
{
sv.setFont(tf);
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String fontName = (String) parent.getSelectedItem();
ArrayAdapter adapter = (ArrayAdapter) parent.getAdapter();
adapter.getPosition(fontName);
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(getString(R.string.font_key), fontName);
editor.apply();
setFont(fontName);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
private class SpinnerActionListener implements AdapterView.OnItemSelectedListener{
private int index;
public SpinnerActionListener(int index)
{
this.index = index;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = parent.getItemAtPosition(position).toString();
SyntaxView curCodeView = codeViews.get(index);
// Update syntax highlighting for different languages
String code = curCodeView.getCode().getText().toString();
curCodeView.getCode().setText("");
curCodeView.setLanguage(selectedItem);
curCodeView.getCode().setText(code);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
private void initializeLangTagMap(){
langTagMap = new HashMap<>();
String[] langs = SyntaxView.getSupportLanguage();
for (String l : langs) {
List<String> tags = new ArrayList<>();
// Special handle for C++, because + is a special character in regular expression.
if (l.compareTo("C++") == 0) {
tags.add("<<Cpp>>");
tags.add("<</Cpp>>");
}
else {
tags.add("<<" + l + ">>");
tags.add("<</" + l + ">>");
}
langTagMap.put(l, tags);
}
}
private String getSupportLang()
{
StringBuffer sb = new StringBuffer("");
for(List<String>tags:langTagMap.values())
{
for(String tag:tags)
{
sb.append(tag);
sb.append("|");
}
}
if(sb.length() > 0)
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
@Override
public boolean onSupportNavigateUp()
{
onBackPressed();
return true;
}
private void shareNote()
{
Intent mSharingIntent = new Intent(Intent.ACTION_SEND);
mSharingIntent.setType("text/plain");
mSharingIntent.putExtra(Intent.EXTRA_SUBJECT, noteTitle.getText().toString());
mSharingIntent.putExtra(Intent.EXTRA_TEXT, getNoteDetails(false));
startActivity(Intent.createChooser(mSharingIntent, "Share text via"));
}
@Override
protected void onPause() {
saveNote();
super.onPause();
}
private void saveNote(){
Date currentTime = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
if (note==null) {
// Add Note
Note newNote = new Note(noteTitle.getText().toString(), getNoteDetails(true),
dateFormat.format(currentTime), dateFormat.format(currentTime));
NoteDatabase.getInstance(this).noteDao().insert(newNote);
}
else {
// Update Note
Note newNote = new Note(note.getId(), noteTitle.getText().toString(), getNoteDetails(true),
note.getCreate_time(), dateFormat.format(currentTime));
NoteDatabase.getInstance(this).noteDao().update(newNote);
}
}
}
| 13,049 | 0.58242 | 0.581117 | 372 | 33.077957 | 26.424509 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.610215 | false | false | 2 |
64ac746ae9721a2a7d7458becd95eab7c506c8f9 | 4,372,276,742,055 | 8c1ba3cd6b9cc5fe11af1503140df7ba07406f74 | /niuniu-server/niuniu-entity/src/main/java/com/mouchina/moumou_server/entity/income/AgentIncomeParameter.java | 7691f979356342977389e33063e409a245b4fd3f | [] | no_license | hxxy2003/niuniu-parent1 | https://github.com/hxxy2003/niuniu-parent1 | 1404c784793fe949552524a24a78993f2224a8f7 | c4414b9b74f084f16b1b47fde9ffc8c8cc200f3b | refs/heads/master | 2018-03-24T21:33:58.595000 | 2016-12-23T07:43:49 | 2016-12-23T07:43:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mouchina.moumou_server.entity.income;
/**
* 代理商收益参数实体类
* @author Administrator
*
*/
public class AgentIncomeParameter {
private Double publishAdvertIncomeCounty; //区县代理商发布广告收益比例参数
private Double publishAdvertIncomeCentre; //中心代理商发布广告收益比例参数
private Double publishAdvertIncomeStarlevel; //星级代理商发布广告收益比例参数
private Double areaAdvertIncomeCounty; //区县代理商区域广告收益比例参数
private Double promotionCommissionAdvertIncomeCountyToCentre; //区县代理商区域广告收益比例参数
private Double promotionCommissionAdvertIncomeCountyToStarlevel; //区县代理商推广星级代理商提成广告收益比例参数
private Double promotionCommissionAdvertIncomeCentreToStarlevel; //中心代理商推广星级代理商提成广告收益比例参数
private Double recommendAdvertIncomeCounty; //区县代理商推荐收益比例参数
private Double recommendAdvertIncomeCentre; //中心代理商推荐收益比例参数
private Double recommendAdvertIncomeStarlevel; //星级代理商推荐收益比例参数
private Double publishAdvertDeduct; //发布广告系统扣除比例参数
public Double getPublishAdvertIncomeCounty() {
return publishAdvertIncomeCounty;
}
public void setPublishAdvertIncomeCounty(Double publishAdvertIncomeCounty) {
this.publishAdvertIncomeCounty = publishAdvertIncomeCounty;
}
public Double getPublishAdvertIncomeCentre() {
return publishAdvertIncomeCentre;
}
public void setPublishAdvertIncomeCentre(Double publishAdvertIncomeCentre) {
this.publishAdvertIncomeCentre = publishAdvertIncomeCentre;
}
public Double getPublishAdvertIncomeStarlevel() {
return publishAdvertIncomeStarlevel;
}
public void setPublishAdvertIncomeStarlevel(Double publishAdvertIncomeStarlevel) {
this.publishAdvertIncomeStarlevel = publishAdvertIncomeStarlevel;
}
public Double getAreaAdvertIncomeCounty() {
return areaAdvertIncomeCounty;
}
public void setAreaAdvertIncomeCounty(Double areaAdvertIncomeCounty) {
this.areaAdvertIncomeCounty = areaAdvertIncomeCounty;
}
public Double getPromotionCommissionAdvertIncomeCountyToCentre() {
return promotionCommissionAdvertIncomeCountyToCentre;
}
public void setPromotionCommissionAdvertIncomeCountyToCentre(Double promotionCommissionAdvertIncomeCountyToCentre) {
this.promotionCommissionAdvertIncomeCountyToCentre = promotionCommissionAdvertIncomeCountyToCentre;
}
public Double getPromotionCommissionAdvertIncomeCountyToStarlevel() {
return promotionCommissionAdvertIncomeCountyToStarlevel;
}
public void setPromotionCommissionAdvertIncomeCountyToStarlevel(
Double promotionCommissionAdvertIncomeCountyToStarlevel) {
this.promotionCommissionAdvertIncomeCountyToStarlevel = promotionCommissionAdvertIncomeCountyToStarlevel;
}
public Double getPromotionCommissionAdvertIncomeCentreToStarlevel() {
return promotionCommissionAdvertIncomeCentreToStarlevel;
}
public void setPromotionCommissionAdvertIncomeCentreToStarlevel(
Double promotionCommissionAdvertIncomeCentreToStarlevel) {
this.promotionCommissionAdvertIncomeCentreToStarlevel = promotionCommissionAdvertIncomeCentreToStarlevel;
}
public Double getRecommendAdvertIncomeCounty() {
return recommendAdvertIncomeCounty;
}
public void setRecommendAdvertIncomeCounty(Double recommendAdvertIncomeCounty) {
this.recommendAdvertIncomeCounty = recommendAdvertIncomeCounty;
}
public Double getRecommendAdvertIncomeCentre() {
return recommendAdvertIncomeCentre;
}
public void setRecommendAdvertIncomeCentre(Double recommendAdvertIncomeCentre) {
this.recommendAdvertIncomeCentre = recommendAdvertIncomeCentre;
}
public Double getRecommendAdvertIncomeStarlevel() {
return recommendAdvertIncomeStarlevel;
}
public void setRecommendAdvertIncomeStarlevel(Double recommendAdvertIncomeStarlevel) {
this.recommendAdvertIncomeStarlevel = recommendAdvertIncomeStarlevel;
}
public Double getPublishAdvertDeduct() {
return publishAdvertDeduct;
}
public void setPublishAdvertDeduct(Double publishAdvertDeduct) {
this.publishAdvertDeduct = publishAdvertDeduct;
}
}
| UTF-8 | Java | 4,201 | java | AgentIncomeParameter.java | Java | [
{
"context": "erver.entity.income;\n\n/**\n * 代理商收益参数实体类\n * @author Administrator\n *\n */\npublic class AgentIncomeParameter {\n\n\tpriv",
"end": 93,
"score": 0.9543154239654541,
"start": 80,
"tag": "NAME",
"value": "Administrator"
}
] | null | [] | package com.mouchina.moumou_server.entity.income;
/**
* 代理商收益参数实体类
* @author Administrator
*
*/
public class AgentIncomeParameter {
private Double publishAdvertIncomeCounty; //区县代理商发布广告收益比例参数
private Double publishAdvertIncomeCentre; //中心代理商发布广告收益比例参数
private Double publishAdvertIncomeStarlevel; //星级代理商发布广告收益比例参数
private Double areaAdvertIncomeCounty; //区县代理商区域广告收益比例参数
private Double promotionCommissionAdvertIncomeCountyToCentre; //区县代理商区域广告收益比例参数
private Double promotionCommissionAdvertIncomeCountyToStarlevel; //区县代理商推广星级代理商提成广告收益比例参数
private Double promotionCommissionAdvertIncomeCentreToStarlevel; //中心代理商推广星级代理商提成广告收益比例参数
private Double recommendAdvertIncomeCounty; //区县代理商推荐收益比例参数
private Double recommendAdvertIncomeCentre; //中心代理商推荐收益比例参数
private Double recommendAdvertIncomeStarlevel; //星级代理商推荐收益比例参数
private Double publishAdvertDeduct; //发布广告系统扣除比例参数
public Double getPublishAdvertIncomeCounty() {
return publishAdvertIncomeCounty;
}
public void setPublishAdvertIncomeCounty(Double publishAdvertIncomeCounty) {
this.publishAdvertIncomeCounty = publishAdvertIncomeCounty;
}
public Double getPublishAdvertIncomeCentre() {
return publishAdvertIncomeCentre;
}
public void setPublishAdvertIncomeCentre(Double publishAdvertIncomeCentre) {
this.publishAdvertIncomeCentre = publishAdvertIncomeCentre;
}
public Double getPublishAdvertIncomeStarlevel() {
return publishAdvertIncomeStarlevel;
}
public void setPublishAdvertIncomeStarlevel(Double publishAdvertIncomeStarlevel) {
this.publishAdvertIncomeStarlevel = publishAdvertIncomeStarlevel;
}
public Double getAreaAdvertIncomeCounty() {
return areaAdvertIncomeCounty;
}
public void setAreaAdvertIncomeCounty(Double areaAdvertIncomeCounty) {
this.areaAdvertIncomeCounty = areaAdvertIncomeCounty;
}
public Double getPromotionCommissionAdvertIncomeCountyToCentre() {
return promotionCommissionAdvertIncomeCountyToCentre;
}
public void setPromotionCommissionAdvertIncomeCountyToCentre(Double promotionCommissionAdvertIncomeCountyToCentre) {
this.promotionCommissionAdvertIncomeCountyToCentre = promotionCommissionAdvertIncomeCountyToCentre;
}
public Double getPromotionCommissionAdvertIncomeCountyToStarlevel() {
return promotionCommissionAdvertIncomeCountyToStarlevel;
}
public void setPromotionCommissionAdvertIncomeCountyToStarlevel(
Double promotionCommissionAdvertIncomeCountyToStarlevel) {
this.promotionCommissionAdvertIncomeCountyToStarlevel = promotionCommissionAdvertIncomeCountyToStarlevel;
}
public Double getPromotionCommissionAdvertIncomeCentreToStarlevel() {
return promotionCommissionAdvertIncomeCentreToStarlevel;
}
public void setPromotionCommissionAdvertIncomeCentreToStarlevel(
Double promotionCommissionAdvertIncomeCentreToStarlevel) {
this.promotionCommissionAdvertIncomeCentreToStarlevel = promotionCommissionAdvertIncomeCentreToStarlevel;
}
public Double getRecommendAdvertIncomeCounty() {
return recommendAdvertIncomeCounty;
}
public void setRecommendAdvertIncomeCounty(Double recommendAdvertIncomeCounty) {
this.recommendAdvertIncomeCounty = recommendAdvertIncomeCounty;
}
public Double getRecommendAdvertIncomeCentre() {
return recommendAdvertIncomeCentre;
}
public void setRecommendAdvertIncomeCentre(Double recommendAdvertIncomeCentre) {
this.recommendAdvertIncomeCentre = recommendAdvertIncomeCentre;
}
public Double getRecommendAdvertIncomeStarlevel() {
return recommendAdvertIncomeStarlevel;
}
public void setRecommendAdvertIncomeStarlevel(Double recommendAdvertIncomeStarlevel) {
this.recommendAdvertIncomeStarlevel = recommendAdvertIncomeStarlevel;
}
public Double getPublishAdvertDeduct() {
return publishAdvertDeduct;
}
public void setPublishAdvertDeduct(Double publishAdvertDeduct) {
this.publishAdvertDeduct = publishAdvertDeduct;
}
}
| 4,201 | 0.860974 | 0.860974 | 91 | 41.20879 | 32.335983 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.549451 | false | false | 2 |
0427ffef0fa68c1aef45e97710a2dc19d615cca5 | 506,806,142,154 | bea72a2f012b4c398ca34907f59381eea23df6b3 | /src/main/java/cn/imaq/trainingcollege/domain/anal/ManagerIncomeAnal.java | 5280c70ce195b7fb4642406a2e975be0add9da0d | [] | no_license | DeepAQ/TrainingCollege | https://github.com/DeepAQ/TrainingCollege | 4646b10f8884e9d5c6326d5564ee895982c52eca | a6156a11893fb83eb9dbf4609a9f2a5a9e523649 | refs/heads/master | 2021-07-25T00:28:37.284000 | 2018-07-11T03:54:37 | 2018-07-11T03:54:37 | 124,690,776 | 2 | 0 | null | false | 2021-04-25T07:23:27 | 2018-03-10T19:18:04 | 2021-03-24T12:53:43 | 2021-04-25T07:23:27 | 330 | 2 | 0 | 3 | Java | false | false | package cn.imaq.trainingcollege.domain.anal;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
@Data
public class ManagerIncomeAnal {
private Map<String, Integer> monthlyTotal = new TreeMap<>();
private Map<String, Integer> monthlyOrders = new TreeMap<>();
private Integer total;
private Integer orders;
private Integer onlineTotal;
private Integer offlineTotal;
private Integer avgPrice;
private Double finishRate;
private Map<String, Integer> byCollege = new HashMap<>();
private Map<String, Integer> byTags = new HashMap<>();
private Map<String, Integer> ordersByCollege = new HashMap<>();
private Map<String, Integer> ordersByTags = new HashMap<>();
}
| UTF-8 | Java | 762 | java | ManagerIncomeAnal.java | Java | [] | null | [] | package cn.imaq.trainingcollege.domain.anal;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
@Data
public class ManagerIncomeAnal {
private Map<String, Integer> monthlyTotal = new TreeMap<>();
private Map<String, Integer> monthlyOrders = new TreeMap<>();
private Integer total;
private Integer orders;
private Integer onlineTotal;
private Integer offlineTotal;
private Integer avgPrice;
private Double finishRate;
private Map<String, Integer> byCollege = new HashMap<>();
private Map<String, Integer> byTags = new HashMap<>();
private Map<String, Integer> ordersByCollege = new HashMap<>();
private Map<String, Integer> ordersByTags = new HashMap<>();
}
| 762 | 0.715223 | 0.715223 | 34 | 21.411764 | 23.452227 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.676471 | false | false | 2 |
442d5c8cbbb144e76e670b583a086b84daaddd6e | 19,052,474,941,973 | f65d8efd8488c3f26ec272067534453916bb433b | /guava-study/src/main/java/org/woodwhales/guava/lru/LinkedHashMapSoftReferencesLruCache.java | ad67c719c2300650d261d30138def58b3c91ae8b | [
"WTFPL"
] | permissive | woodwhales/woodwhales-study | https://github.com/woodwhales/woodwhales-study | 3c63d08e7aff503484905ea857ba389d5ee972d6 | d8b95c559d3223b54211418bce78b9d9d41f9b08 | refs/heads/master | 2023-03-04T16:04:59.516000 | 2022-08-21T07:16:20 | 2022-08-21T07:16:20 | 184,915,908 | 2 | 3 | WTFPL | false | 2023-03-01T03:42:52 | 2019-05-04T16:00:32 | 2022-06-07T06:10:57 | 2023-03-01T03:42:51 | 10,869 | 1 | 3 | 8 | Java | false | false | package org.woodwhales.guava.lru;
import com.google.common.base.Preconditions;
import java.lang.ref.SoftReference;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
/**
* @projectName: guava
* @author: woodwhales
* @date: 20.7.5 00:45
* @description: 使用软引用对缓存进行增强
*/
public class LinkedHashMapSoftReferencesLruCache<K, V> implements LruCache<K, V> {
private final int limit;
private final InternalLruLinkedHashMapCache<K, V> cache;
private class InternalLruLinkedHashMapCache<K, V> extends LinkedHashMap<K, SoftReference<V>> {
private int limit;
public InternalLruLinkedHashMapCache(int limit) {
super(limit, 0.75f, true);
this.limit = limit;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, SoftReference<V>> eldest) {
return this.size() > this.limit;
}
}
public LinkedHashMapSoftReferencesLruCache(int limit) {
Preconditions.checkArgument(limit > 0, "this limit must big than zero.");
this.limit = limit;
this.cache = new InternalLruLinkedHashMapCache<>(limit);
}
@Override
public void put(K key, V value) {
this.cache.put(key, new SoftReference<>(value));
}
@Override
public V get(K key) {
SoftReference<V> softReference = this.cache.get(key);
if(Objects.isNull(softReference)) {
return null;
}
return softReference.get();
}
@Override
public void remove(K key) {
this.cache.remove(key);
}
@Override
public void clear() {
this.cache.clear();
}
@Override
public int size() {
return this.cache.size();
}
@Override
public int limit() {
return this.limit;
}
}
| UTF-8 | Java | 1,832 | java | LinkedHashMapSoftReferencesLruCache.java | Java | [
{
"context": "l.Objects;\n\n/**\n * @projectName: guava\n * @author: woodwhales\n * @date: 20.7.5 00:45\n * @description: 使用软引用对缓存进",
"end": 247,
"score": 0.9996618628501892,
"start": 237,
"tag": "USERNAME",
"value": "woodwhales"
}
] | null | [] | package org.woodwhales.guava.lru;
import com.google.common.base.Preconditions;
import java.lang.ref.SoftReference;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
/**
* @projectName: guava
* @author: woodwhales
* @date: 20.7.5 00:45
* @description: 使用软引用对缓存进行增强
*/
public class LinkedHashMapSoftReferencesLruCache<K, V> implements LruCache<K, V> {
private final int limit;
private final InternalLruLinkedHashMapCache<K, V> cache;
private class InternalLruLinkedHashMapCache<K, V> extends LinkedHashMap<K, SoftReference<V>> {
private int limit;
public InternalLruLinkedHashMapCache(int limit) {
super(limit, 0.75f, true);
this.limit = limit;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, SoftReference<V>> eldest) {
return this.size() > this.limit;
}
}
public LinkedHashMapSoftReferencesLruCache(int limit) {
Preconditions.checkArgument(limit > 0, "this limit must big than zero.");
this.limit = limit;
this.cache = new InternalLruLinkedHashMapCache<>(limit);
}
@Override
public void put(K key, V value) {
this.cache.put(key, new SoftReference<>(value));
}
@Override
public V get(K key) {
SoftReference<V> softReference = this.cache.get(key);
if(Objects.isNull(softReference)) {
return null;
}
return softReference.get();
}
@Override
public void remove(K key) {
this.cache.remove(key);
}
@Override
public void clear() {
this.cache.clear();
}
@Override
public int size() {
return this.cache.size();
}
@Override
public int limit() {
return this.limit;
}
}
| 1,832 | 0.631084 | 0.624447 | 75 | 23.106667 | 23.047529 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.453333 | false | false | 2 |
6e525f528c05c30a1ba1bffd6b65c7160099d559 | 25,881,472,979,324 | b7c21fc59c36af3431b4f731a03a01883c5772ea | /src/main/java/br/com/feliperudolfe/comum/repositorio/DAOGenerico.java | 32532d02ada653682e769ccc32bbbede1567e4b8 | [] | no_license | feliperudolfe/projeto-modelo | https://github.com/feliperudolfe/projeto-modelo | 9a2f4d356e46dbfc94e43ca00f5e20f88be0cd17 | 1953592ee60ed88db69ad53ee56b8c37694ef293 | refs/heads/master | 2020-04-03T12:08:45.083000 | 2018-11-04T19:17:49 | 2018-11-04T19:17:49 | 155,242,516 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.feliperudolfe.comum.repositorio;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import org.jboss.logging.Logger;
import br.com.feliperudolfe.comum.modelo.dto.Mensagem;
import br.com.feliperudolfe.comum.modelo.entidade.Entidade;
import br.com.feliperudolfe.comum.tratamento.DatabaseException;
/**
* @author Felipe Rudolfe
*
* @param <T>
* @param <E>
*/
public abstract class DAOGenerico<T, E extends Entidade<T>> implements DAO<T, E> {
private final Logger LOGGER = Logger.getLogger(DAOGenerico.class);
private static final String PU = "modelo-pu";
@PersistenceContext(name = PU)
private EntityManager em;
private Class<E> classe;
public DAOGenerico(Class<E> classe) {
this.classe = classe;
}// DAOGenerico()
@Override
public void inserir(E entidade) throws DatabaseException {
try {
this.getEM().persist(entidade);
} catch (Exception e) {
LOGGER.info(e);
throw new DatabaseException(Mensagem.ERRO, "Ocorre um erro durante a executar desta operação.");
}// try-catch
}// inserir()
@Override
public void atualizar(E entidade) throws DatabaseException {
try {
this.getEM().merge(entidade);
} catch (Exception e) {
LOGGER.info(e);
throw new DatabaseException(Mensagem.ERRO, "Ocorre um erro durante a executar desta operação.");
}// try-catch
}// atualizar()
@Override
public void remover(E entidade) throws DatabaseException {
try {
this.getEM().remove(entidade);
} catch (Throwable e) {
LOGGER.info(e);
throw new DatabaseException(Mensagem.ERRO, "Ocorre um erro durante a executar desta operação.");
}// try-catch
}// remover()
@Override
public List<E> listar() {
TypedQuery<E> typedQuery = null;
final CriteriaBuilder builder = this.getEM().getCriteriaBuilder();
final CriteriaQuery<E> criteriaQuery = builder.createQuery(this.classe);
criteriaQuery.from(this.classe);
typedQuery = this.getEM().createQuery(criteriaQuery);
return typedQuery.getResultList();
}// listar()
@Override
public E buscar(T codigo) {
return this.getEM().find(this.classe, codigo);
}// buscar()
protected E executarConsultaSimples(String sql) {
Query query = this.getEM().createQuery(sql);
return executarQuerySimples(query);
}// executarConsultaSimples()
@SuppressWarnings("unchecked")
protected E executarQuerySimples(Query query) {
E retorno = null;
try {
retorno = (E) query.getSingleResult();
} catch (NoResultException e) {
return retorno;
} // try-cacth
return retorno;
}// executarQuerySimples()
protected List<E> executarConsulta(String sql) {
Query query = this.getEM().createQuery(sql);
return executarQuery(query);
}// executarConsulta()
protected List<E> executarConsultaComLimite(String sql, int limite) {
Query query = this.getEM().createQuery(sql);
return executarQueryComLimite(query, limite);
}// executarConsulta()
protected List<E> executarConsultaComLimite(String sql, int inicio, int limite) {
Query query = this.getEM().createQuery(sql);
return executarQueryComLimite(query, inicio, limite);
}// executarConsulta()
@SuppressWarnings("unchecked")
protected List<E> executarQuery(Query query) {
return query.getResultList();
}// executarQuery()
protected int executarQueryUpdate(Query query) {
return query.executeUpdate();
}// executarQuery()
@SuppressWarnings("unchecked")
protected List<E> executarQueryComLimite(Query query, int limite) {
return query.setMaxResults(limite).getResultList();
}// executarQueryComLimite()
@SuppressWarnings("unchecked")
protected List<E> executarQueryComLimite(Query query, int inicio, int limite) {
return query.setFirstResult(inicio).setMaxResults(limite).getResultList();
}// executarQueryComLimite()
@Override
public Long count() {
CriteriaBuilder cb = this.getEM().getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
cq.select(cb.count(cq.from(this.classe)));
return this.getEM().createQuery(cq).getSingleResult();
}// count()
protected EntityManager getEM() {
return this.em;
}// getEM()
} | UTF-8 | Java | 4,332 | java | DAOGenerico.java | Java | [
{
"context": "omum.tratamento.DatabaseException;\n\n/**\n * @author Felipe Rudolfe\n *\n * @param <T>\n * @param <E>\n */\npublic abstrac",
"end": 615,
"score": 0.9998698830604553,
"start": 601,
"tag": "NAME",
"value": "Felipe Rudolfe"
}
] | null | [] | package br.com.feliperudolfe.comum.repositorio;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import org.jboss.logging.Logger;
import br.com.feliperudolfe.comum.modelo.dto.Mensagem;
import br.com.feliperudolfe.comum.modelo.entidade.Entidade;
import br.com.feliperudolfe.comum.tratamento.DatabaseException;
/**
* @author <NAME>
*
* @param <T>
* @param <E>
*/
public abstract class DAOGenerico<T, E extends Entidade<T>> implements DAO<T, E> {
private final Logger LOGGER = Logger.getLogger(DAOGenerico.class);
private static final String PU = "modelo-pu";
@PersistenceContext(name = PU)
private EntityManager em;
private Class<E> classe;
public DAOGenerico(Class<E> classe) {
this.classe = classe;
}// DAOGenerico()
@Override
public void inserir(E entidade) throws DatabaseException {
try {
this.getEM().persist(entidade);
} catch (Exception e) {
LOGGER.info(e);
throw new DatabaseException(Mensagem.ERRO, "Ocorre um erro durante a executar desta operação.");
}// try-catch
}// inserir()
@Override
public void atualizar(E entidade) throws DatabaseException {
try {
this.getEM().merge(entidade);
} catch (Exception e) {
LOGGER.info(e);
throw new DatabaseException(Mensagem.ERRO, "Ocorre um erro durante a executar desta operação.");
}// try-catch
}// atualizar()
@Override
public void remover(E entidade) throws DatabaseException {
try {
this.getEM().remove(entidade);
} catch (Throwable e) {
LOGGER.info(e);
throw new DatabaseException(Mensagem.ERRO, "Ocorre um erro durante a executar desta operação.");
}// try-catch
}// remover()
@Override
public List<E> listar() {
TypedQuery<E> typedQuery = null;
final CriteriaBuilder builder = this.getEM().getCriteriaBuilder();
final CriteriaQuery<E> criteriaQuery = builder.createQuery(this.classe);
criteriaQuery.from(this.classe);
typedQuery = this.getEM().createQuery(criteriaQuery);
return typedQuery.getResultList();
}// listar()
@Override
public E buscar(T codigo) {
return this.getEM().find(this.classe, codigo);
}// buscar()
protected E executarConsultaSimples(String sql) {
Query query = this.getEM().createQuery(sql);
return executarQuerySimples(query);
}// executarConsultaSimples()
@SuppressWarnings("unchecked")
protected E executarQuerySimples(Query query) {
E retorno = null;
try {
retorno = (E) query.getSingleResult();
} catch (NoResultException e) {
return retorno;
} // try-cacth
return retorno;
}// executarQuerySimples()
protected List<E> executarConsulta(String sql) {
Query query = this.getEM().createQuery(sql);
return executarQuery(query);
}// executarConsulta()
protected List<E> executarConsultaComLimite(String sql, int limite) {
Query query = this.getEM().createQuery(sql);
return executarQueryComLimite(query, limite);
}// executarConsulta()
protected List<E> executarConsultaComLimite(String sql, int inicio, int limite) {
Query query = this.getEM().createQuery(sql);
return executarQueryComLimite(query, inicio, limite);
}// executarConsulta()
@SuppressWarnings("unchecked")
protected List<E> executarQuery(Query query) {
return query.getResultList();
}// executarQuery()
protected int executarQueryUpdate(Query query) {
return query.executeUpdate();
}// executarQuery()
@SuppressWarnings("unchecked")
protected List<E> executarQueryComLimite(Query query, int limite) {
return query.setMaxResults(limite).getResultList();
}// executarQueryComLimite()
@SuppressWarnings("unchecked")
protected List<E> executarQueryComLimite(Query query, int inicio, int limite) {
return query.setFirstResult(inicio).setMaxResults(limite).getResultList();
}// executarQueryComLimite()
@Override
public Long count() {
CriteriaBuilder cb = this.getEM().getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
cq.select(cb.count(cq.from(this.classe)));
return this.getEM().createQuery(cq).getSingleResult();
}// count()
protected EntityManager getEM() {
return this.em;
}// getEM()
} | 4,324 | 0.742025 | 0.742025 | 146 | 28.636986 | 23.79734 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.575342 | false | false | 2 |
55795d1405f06adc9b6be1405680c654dd81e53c | 19,138,374,338,031 | 9d6b4968fd1095e35505a9ce8bd003cdd0fd90b4 | /src/main/java/com/iss/cnaf/manager/power/dao/PowerMapper.java | bf66ad61f90df9be043846d7c2888dcd2839d47f | [] | no_license | YangZhaoJun1/Excel | https://github.com/YangZhaoJun1/Excel | 20a3960ba104e50229fef07ea861105848bc0a08 | c95e8d9208a2996ea6e485043ad9ddf305ca298b | refs/heads/master | 2020-03-09T00:53:16.827000 | 2018-04-08T06:29:41 | 2018-04-08T06:29:41 | 128,499,249 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.iss.cnaf.manager.power.dao;
import java.util.List;
import java.util.Map;
import com.github.pagehelper.Page;
import com.iss.cnaf.manager.power.vo.Power;
import com.iss.cnaf.manager.sys.model.QueryParam;
public interface PowerMapper {
Page<Power> queryPowers(QueryParam param);
/**
*
* @method_name:queryPowerByRole 通过用户主键查询权限
* @author: WJF
* @date 2017年3月13日 下午2:02:06
* @version V1.0
* @param userId 用户主键对应数据库user_id
* @return
*/
List<Power> queryPowerByUser(String userId);
List<Power> queryPowerList();
/**
*
* @method_name:queryFistLevel 查询该用户的一级节点
* @author: WJF
* @date 2017年3月22日 上午10:11:22
* @version V1.0
* @param userId 用户编号
* @return
*/
Power queryFistLevel(Integer treeCode);
/**
*
* @method_name:querySecondLevel 通过父节点查询二级节点
* @author: WJF
* @date 2017年3月22日 上午10:13:09
* @version V1.0
* @param parentCode 父节点
* @param userId 用户编号
* @return
*/
List<Power> querySecondLevel(Map<String, Object> map);
List<Power> queryRightPowerList(String roleId);
List<Power> queryPowerList(List<Integer> powerIds);
List<Power> queryAllPowerList();
}
| UTF-8 | Java | 1,270 | java | PowerMapper.java | Java | [
{
"context": "thod_name:queryPowerByRole 通过用户主键查询权限\n\t * @author: WJF\n\t * @date 2017年3月13日 下午2:02:06\n\t * @version V1.0\n",
"end": 366,
"score": 0.9991539716720581,
"start": 363,
"tag": "USERNAME",
"value": "WJF"
},
{
"context": "method_name:queryFistLevel 查询该用户的一级节点\n\t * @author: WJF\n\t * @date 2017年3月22日 上午10:11:22\n\t * @version V1.0",
"end": 617,
"score": 0.9987897872924805,
"start": 614,
"tag": "USERNAME",
"value": "WJF"
},
{
"context": "hod_name:querySecondLevel 通过父节点查询二级节点\n\t * @author: WJF\n\t * @date 2017年3月22日 上午10:13:09\n\t * @version V1.0",
"end": 823,
"score": 0.9983966946601868,
"start": 820,
"tag": "USERNAME",
"value": "WJF"
}
] | null | [] | package com.iss.cnaf.manager.power.dao;
import java.util.List;
import java.util.Map;
import com.github.pagehelper.Page;
import com.iss.cnaf.manager.power.vo.Power;
import com.iss.cnaf.manager.sys.model.QueryParam;
public interface PowerMapper {
Page<Power> queryPowers(QueryParam param);
/**
*
* @method_name:queryPowerByRole 通过用户主键查询权限
* @author: WJF
* @date 2017年3月13日 下午2:02:06
* @version V1.0
* @param userId 用户主键对应数据库user_id
* @return
*/
List<Power> queryPowerByUser(String userId);
List<Power> queryPowerList();
/**
*
* @method_name:queryFistLevel 查询该用户的一级节点
* @author: WJF
* @date 2017年3月22日 上午10:11:22
* @version V1.0
* @param userId 用户编号
* @return
*/
Power queryFistLevel(Integer treeCode);
/**
*
* @method_name:querySecondLevel 通过父节点查询二级节点
* @author: WJF
* @date 2017年3月22日 上午10:13:09
* @version V1.0
* @param parentCode 父节点
* @param userId 用户编号
* @return
*/
List<Power> querySecondLevel(Map<String, Object> map);
List<Power> queryRightPowerList(String roleId);
List<Power> queryPowerList(List<Integer> powerIds);
List<Power> queryAllPowerList();
}
| 1,270 | 0.702109 | 0.663445 | 56 | 19.321428 | 17.312368 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.964286 | false | false | 2 |
968d84467c0fd17285737b577fb86cdb3b6db28b | 4,372,276,747,662 | 6069e058be406e120457f24ec22d97b44f289c60 | /.svn/pristine/04/044e63286ca28c8b98522871fb028d915c7eeb10.svn-base | babbdff75b35b5db508797c29d1b61df280481e0 | [] | no_license | idontkillcoyotes/Proyecto-X | https://github.com/idontkillcoyotes/Proyecto-X | 03e17208d16054ced36c94a39d91085f57e1abed | 3aea0c76436e4aaa071c952be983892650bdae29 | refs/heads/master | 2021-04-26T16:53:58.061000 | 2017-10-13T20:35:19 | 2017-10-13T20:35:19 | 106,871,855 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package src.ai;
import java.util.Stack;
import src.sprites.Misil;
/**
* El arma de la nave jefe
*
* @author Díaz Figueroa Rodrigo Martín, Labrisca Joaquín
*/
public class ArmaJefe1 extends Arma {
/**
* Constructor
*/
public ArmaJefe1(Misil m, int cant) {
super(m, cant);
}
/**
* Setea la cantidad de misiles del arma
* @param aux Nueva cantidad de misiles del arma
*/
public void setCantMisiles(int aux){
if (aux>=5){
this.cantMisiles=5;
}
else{
this.cantMisiles+=aux;
}
}
/**
* Retorna una pila de misiles cuando una nave dispara mas de uno a la vez
* @param x Coordenada x en el mapa
* @param y Coordenada y en el mapa
* @param dx Velocidad sobre x
* @param dy Velocidad sobre y
* @param ancho Ancho de la nave que dispara
* @param alto Alto de la nave que dispara
* @return Pila de misiles que representa los disparados de la nave
*/
public Stack<Misil> cloneMisiles(int x,int y,int dx, int dy,int ancho, int alto){
Stack<Misil> misiles=new Stack<Misil>();
int s=this.misil.getSpeed();
if (this.cantMisiles==1){
misiles.push(misil.clone(x+(ancho/2), y, 0, dy*(-1*s)));
misiles.push(misil.clone(x, y, dx*(-1*s), dy*(-1*s)));
misiles.push(misil.clone(x, y+(alto/2), dx*(-1*s), 0));
misiles.push(misil.clone(x, y+(alto), dx*(-1*s), dy*s));
misiles.push(misil.clone(x+(ancho/2), y+(alto), 0, dy*(1*s)));
}else {
if (this.cantMisiles==2){
misiles.push(misil.clone(x+(ancho/2), y, 0, dy*(-1*s)));
misiles.push(misil.clone(x+ancho, y, dx*(1*s), dy*(-1*s)));
misiles.push(misil.clone(x+ancho, y+(alto/2), dx*(1*s), 0));
misiles.push(misil.clone(x+ancho, y+(alto), dx*(1*s), dy*s));
misiles.push(misil.clone(x+(ancho/2), y+(alto), 0, dy*(1*s)));
}
}
return misiles;
}
}
| UTF-8 | Java | 1,789 | 044e63286ca28c8b98522871fb028d915c7eeb10.svn-base | Java | [
{
"context": "sil;\n/**\n * El arma de la nave jefe\n * \n * @author Díaz Figueroa Rodrigo Martín, Labrisca Joaquín\n */\npublic class",
"end": 127,
"score": 0.999878466129303,
"start": 114,
"tag": "NAME",
"value": "Díaz Figueroa"
},
{
"context": " arma de la nave jefe\n * \n * @author Díaz Figueroa Rodrigo Martín, Labrisca Joaquín\n */\npublic class ArmaJefe1 exte",
"end": 142,
"score": 0.9989789128303528,
"start": 128,
"tag": "NAME",
"value": "Rodrigo Martín"
},
{
"context": " jefe\n * \n * @author Díaz Figueroa Rodrigo Martín, Labrisca Joaquín\n */\npublic class ArmaJefe1 extends Arma {\t\n\t/**\n\t",
"end": 160,
"score": 0.9998676180839539,
"start": 144,
"tag": "NAME",
"value": "Labrisca Joaquín"
}
] | null | [] | package src.ai;
import java.util.Stack;
import src.sprites.Misil;
/**
* El arma de la nave jefe
*
* @author <NAME> <NAME>, <NAME>
*/
public class ArmaJefe1 extends Arma {
/**
* Constructor
*/
public ArmaJefe1(Misil m, int cant) {
super(m, cant);
}
/**
* Setea la cantidad de misiles del arma
* @param aux Nueva cantidad de misiles del arma
*/
public void setCantMisiles(int aux){
if (aux>=5){
this.cantMisiles=5;
}
else{
this.cantMisiles+=aux;
}
}
/**
* Retorna una pila de misiles cuando una nave dispara mas de uno a la vez
* @param x Coordenada x en el mapa
* @param y Coordenada y en el mapa
* @param dx Velocidad sobre x
* @param dy Velocidad sobre y
* @param ancho Ancho de la nave que dispara
* @param alto Alto de la nave que dispara
* @return Pila de misiles que representa los disparados de la nave
*/
public Stack<Misil> cloneMisiles(int x,int y,int dx, int dy,int ancho, int alto){
Stack<Misil> misiles=new Stack<Misil>();
int s=this.misil.getSpeed();
if (this.cantMisiles==1){
misiles.push(misil.clone(x+(ancho/2), y, 0, dy*(-1*s)));
misiles.push(misil.clone(x, y, dx*(-1*s), dy*(-1*s)));
misiles.push(misil.clone(x, y+(alto/2), dx*(-1*s), 0));
misiles.push(misil.clone(x, y+(alto), dx*(-1*s), dy*s));
misiles.push(misil.clone(x+(ancho/2), y+(alto), 0, dy*(1*s)));
}else {
if (this.cantMisiles==2){
misiles.push(misil.clone(x+(ancho/2), y, 0, dy*(-1*s)));
misiles.push(misil.clone(x+ancho, y, dx*(1*s), dy*(-1*s)));
misiles.push(misil.clone(x+ancho, y+(alto/2), dx*(1*s), 0));
misiles.push(misil.clone(x+ancho, y+(alto), dx*(1*s), dy*s));
misiles.push(misil.clone(x+(ancho/2), y+(alto), 0, dy*(1*s)));
}
}
return misiles;
}
}
| 1,761 | 0.630459 | 0.613662 | 61 | 28.278688 | 24.077152 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.573771 | false | false | 2 |
|
067eac033f9b45c0425f86911f5de280c6050b20 | 18,769,007,135,288 | 22d84d7a2d5f56c8def947a30c750b22e6cb4231 | /ThreeNumAverage.java | c94afd7db3dabf6048c7f9ae0ee2453de2bf0800 | [] | no_license | nickpkim/Unit-2-Nick-Kim | https://github.com/nickpkim/Unit-2-Nick-Kim | 90152e48bc37608843366ebdad1cc7a6b6278d90 | 504dd751702ac70f10e0eda9f28cd600473a80a5 | refs/heads/master | 2020-08-04T12:09:59.137000 | 2019-10-01T15:40:57 | 2019-10-01T15:40:57 | 212,133,095 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class ThreeNumAverage{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter 3 numbers:");
int num1 = scan.nextInt();
int num2 = scan.nextInt();
int num3 = scan.nextInt();
double avg = ((double)(num1+num2+num3))/3;
System.out.println(avg);
}
}
| UTF-8 | Java | 363 | java | ThreeNumAverage.java | Java | [] | null | [] | import java.util.Scanner;
public class ThreeNumAverage{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter 3 numbers:");
int num1 = scan.nextInt();
int num2 = scan.nextInt();
int num3 = scan.nextInt();
double avg = ((double)(num1+num2+num3))/3;
System.out.println(avg);
}
}
| 363 | 0.650138 | 0.628099 | 15 | 23.200001 | 16.924145 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.533333 | false | false | 2 |
892dda2a68c7024080f5a73e53bf0792b28ee5e1 | 15,891,379,066,866 | 82228fd6d004834b7dc7150c0b1c4f3d15955d67 | /pizzeria-dao/src/main/java/fr/pizzeria/dao/IClientDao.java | 673d14b5ab2fde51dcd87f1c2652214b17febcfe | [
"MIT"
] | permissive | elfindel69/formation-dta | https://github.com/elfindel69/formation-dta | 5db60903f86ed2f102fbe4bb958ca2596d15ac33 | 9478ff331ab03ae1ee775e3bb6264d0f6cb2c605 | refs/heads/master | 2020-04-06T04:26:58.117000 | 2016-06-07T08:40:19 | 2016-06-07T08:40:19 | 57,122,685 | 0 | 0 | null | false | 2016-05-17T17:12:15 | 2016-04-26T11:27:39 | 2016-04-26T12:31:41 | 2016-05-17T17:12:15 | 198 | 0 | 0 | 0 | Java | null | null | package fr.pizzeria.dao;
import java.util.List;
import fr.pizzeria.exceptions.DaoException;
import fr.pizzeria.model.Client;
public interface IClientDao {
/**
* Liste des pizzas
*
* @return liste des pizzas
* @throws DaoException
*/
List<Client> findAllClients() throws DaoException;
/**
* Ajout d'une pizza
*
* @param newPizza
* pizza à ajouter
*
*/
void saveClient(Client newPizza) throws DaoException;
/**
* MAJ d'un client
*
* @param idClient
* id du Client à MAJ
* @param updateClient
* client modifié
*/
void updateClient(int idClient, Client updateClient) throws DaoException;
/**
* Suppression d'un client
*
* @param codePizza
* id du Client à supprimer
*/
void deleteClient(int idClient) throws DaoException;
Client connect(String email, String password);
fr.pizzeria.model.Client findByNom(String string);
Client findOne(int i);
}
| UTF-8 | Java | 1,013 | java | IClientDao.java | Java | [] | null | [] | package fr.pizzeria.dao;
import java.util.List;
import fr.pizzeria.exceptions.DaoException;
import fr.pizzeria.model.Client;
public interface IClientDao {
/**
* Liste des pizzas
*
* @return liste des pizzas
* @throws DaoException
*/
List<Client> findAllClients() throws DaoException;
/**
* Ajout d'une pizza
*
* @param newPizza
* pizza à ajouter
*
*/
void saveClient(Client newPizza) throws DaoException;
/**
* MAJ d'un client
*
* @param idClient
* id du Client à MAJ
* @param updateClient
* client modifié
*/
void updateClient(int idClient, Client updateClient) throws DaoException;
/**
* Suppression d'un client
*
* @param codePizza
* id du Client à supprimer
*/
void deleteClient(int idClient) throws DaoException;
Client connect(String email, String password);
fr.pizzeria.model.Client findByNom(String string);
Client findOne(int i);
}
| 1,013 | 0.630327 | 0.630327 | 51 | 17.784313 | 18.369106 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.941176 | false | false | 2 |
769577c58cb98d78a3b32ce2f16cabf5f20ae1b0 | 24,618,752,608,451 | 2bb3940b6ee77cc0e7778b624e479fd7d81fc3b8 | /src/managers/entity_managers/CollisionManager.java | 50abd2a24a81ad5c0539482f530384344cbe1f6a | [] | no_license | 11Marlowe/frogger-clone | https://github.com/11Marlowe/frogger-clone | 9051519ba98c3757bdb856f5e8e12305d36e3ca0 | 146ec48619fd88b10b7689a9eb3b2e5f2838ff30 | refs/heads/master | 2020-03-15T09:57:06.211000 | 2018-05-25T06:52:09 | 2018-05-25T06:52:09 | 132,087,236 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package managers.entity_managers;
import java.util.ArrayList;
import entities.Car;
import entities.Frog;
import entities.Log;
import entities.Score;
import entities.Turtle;
import entities.Water;
import entities.WaterBorder;
import helpers.Direction;
import helpers.GameInfo;
public class CollisionManager {
private ArrayList<Log> lList;
private ArrayList<Car> cList;
private Frog player;
private Water water;
private WaterBorder wb;
private Turtle t;
private boolean isOnLog, isOnWater;
private int count;
public CollisionManager(Frog player, ArrayList<Log> lList, ArrayList<Car> cList,
Turtle t) {
this.player = player;
this.cList = cList;
this.lList = lList;
this.t = t;
water = new Water();
wb = new WaterBorder();
isOnLog = false;
isOnWater = false;
count = 0;
}
public void update() {
checkForPlayerOnLog();
CheckForPlayerOnWaterBorder();
handleCarCollision();
checkForPlayerOnWater();
checkForTurtleCollection();
}
public void checkForTurtleCollection() {
if(player.getCollRect().intersects(t.getCollRect())) {
t.setIsCollected(true);
Score.incrementScore();
}
}
private void checkForPlayerOnLog() {
count = 0;
for(Log log : lList) {
logCheckHelper(log);
}
}
private void logCheckHelper(Log log) {
if(player.getCollRect().intersects(log.getCollRect()) && log.getDir() == Direction.LEFT) {
player.setOnRLog(false);
player.setOnLLog(true);
isOnLog = true;
count++;
}
else if(player.getCollRect().intersects(log.getCollRect()) && log.getDir() == Direction.RIGHT) {
player.setOnLLog(false);
player.setOnRLog(true);
isOnLog = true;
count++;
}
}
private void checkForPlayerOnWater() {
if(player.getCollRect().intersects(water.getCollRect()) && count == 0) {
isOnLog = false;
isOnWater = true;
}
if(isOnWater && !isOnLog) {
player.resetPlayer();
isOnWater = false;
}
}
private void CheckForPlayerOnWaterBorder() {
if(player.getCollRect().intersects(wb.getBRect()) ||
player.getCollRect().intersects(wb.getSRect())) {
player.setOnLLog(false);
player.setOnRLog(false);
}
else if(player.getCollRect().intersects(wb.getNRect())) {
player.resetPlayer();
player.setOnLLog(false);
player.setOnRLog(false);
}
}
private void handleCarCollision() {
for(Car car : cList) {
if(player.getCollRect().intersects(car.getCollRect())) {
player.resetPlayer();
}
}
}
}
| UTF-8 | Java | 2,457 | java | CollisionManager.java | Java | [] | null | [] | package managers.entity_managers;
import java.util.ArrayList;
import entities.Car;
import entities.Frog;
import entities.Log;
import entities.Score;
import entities.Turtle;
import entities.Water;
import entities.WaterBorder;
import helpers.Direction;
import helpers.GameInfo;
public class CollisionManager {
private ArrayList<Log> lList;
private ArrayList<Car> cList;
private Frog player;
private Water water;
private WaterBorder wb;
private Turtle t;
private boolean isOnLog, isOnWater;
private int count;
public CollisionManager(Frog player, ArrayList<Log> lList, ArrayList<Car> cList,
Turtle t) {
this.player = player;
this.cList = cList;
this.lList = lList;
this.t = t;
water = new Water();
wb = new WaterBorder();
isOnLog = false;
isOnWater = false;
count = 0;
}
public void update() {
checkForPlayerOnLog();
CheckForPlayerOnWaterBorder();
handleCarCollision();
checkForPlayerOnWater();
checkForTurtleCollection();
}
public void checkForTurtleCollection() {
if(player.getCollRect().intersects(t.getCollRect())) {
t.setIsCollected(true);
Score.incrementScore();
}
}
private void checkForPlayerOnLog() {
count = 0;
for(Log log : lList) {
logCheckHelper(log);
}
}
private void logCheckHelper(Log log) {
if(player.getCollRect().intersects(log.getCollRect()) && log.getDir() == Direction.LEFT) {
player.setOnRLog(false);
player.setOnLLog(true);
isOnLog = true;
count++;
}
else if(player.getCollRect().intersects(log.getCollRect()) && log.getDir() == Direction.RIGHT) {
player.setOnLLog(false);
player.setOnRLog(true);
isOnLog = true;
count++;
}
}
private void checkForPlayerOnWater() {
if(player.getCollRect().intersects(water.getCollRect()) && count == 0) {
isOnLog = false;
isOnWater = true;
}
if(isOnWater && !isOnLog) {
player.resetPlayer();
isOnWater = false;
}
}
private void CheckForPlayerOnWaterBorder() {
if(player.getCollRect().intersects(wb.getBRect()) ||
player.getCollRect().intersects(wb.getSRect())) {
player.setOnLLog(false);
player.setOnRLog(false);
}
else if(player.getCollRect().intersects(wb.getNRect())) {
player.resetPlayer();
player.setOnLLog(false);
player.setOnRLog(false);
}
}
private void handleCarCollision() {
for(Car car : cList) {
if(player.getCollRect().intersects(car.getCollRect())) {
player.resetPlayer();
}
}
}
}
| 2,457 | 0.69068 | 0.689459 | 113 | 20.743362 | 19.149055 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.20354 | false | false | 2 |
be5a2275fb343773bc7340eb5f47ccdab27780eb | 36,189,394,457,083 | c083fb489b690b0776621dd956ca4850191135d7 | /SpringProject1/src/com/mypackage/Address.java | 85c6e7b4305d86130f51e07c80a34c89f1673157 | [] | no_license | depbajra7/java | https://github.com/depbajra7/java | 8eaafbac42b39e17187dc6aac7442baf4c80a218 | c8b992b9530f9da6457bd40df3b0e9a155d48504 | refs/heads/master | 2020-04-07T03:04:16.913000 | 2018-11-17T16:03:21 | 2018-11-17T16:03:21 | 158,001,298 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mypackage;
public class Address {
private int addrid;
private String state;
private int zip;
public int getAddrid() {
return addrid;
}
public void setAddrid(int addrid) {
this.addrid = addrid;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getZip() {
return zip;
}
public void setZip(int zip) {
this.zip = zip;
}
}
| UTF-8 | Java | 429 | java | Address.java | Java | [] | null | [] | package com.mypackage;
public class Address {
private int addrid;
private String state;
private int zip;
public int getAddrid() {
return addrid;
}
public void setAddrid(int addrid) {
this.addrid = addrid;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getZip() {
return zip;
}
public void setZip(int zip) {
this.zip = zip;
}
}
| 429 | 0.671329 | 0.671329 | 28 | 14.321428 | 11.554385 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.428571 | false | false | 2 |
160b85ed95991aa718ce7e91f7feb24a8b58b48b | 30,897,994,760,824 | 3cf964a9c7cf4acec0aac3440e21fde0bf62dc5e | /app/src/main/java/com/yikang/health/widget/time/DateViewUtils.java | e0bf5108582a93783c78e403312a0598edaba43f | [] | no_license | gs-wb/Baby | https://github.com/gs-wb/Baby | 9e422e99004472931c5a6b16a146cc8c6651f2f3 | dfadc5e2386f6371187d5fe63be5c276468816fa | refs/heads/master | 2016-09-12T08:53:19.528000 | 2016-05-31T10:08:06 | 2016-05-31T10:08:06 | 57,957,502 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yikang.health.widget.time;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.yikang.health.R;
import java.util.Calendar;
/**
* Created by zwb on 2016/5/1.
*/
public class DateViewUtils {
Context mContext;
public DateViewUtils(Context context){
mContext = context;
}
public View initFullDateView(final TextView dateView) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View timepickerview = inflater.inflate(R.layout.timepicker, null);
ScreenInfo screenInfo = new ScreenInfo((Activity)mContext);
final WheelMain wheelMain = new WheelMain(timepickerview, false);
wheelMain.screenheight = screenInfo.getHeight();
wheelMain.screenwidth = screenInfo.getWidth();
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH)+1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
wheelMain.initDateTimePicker(year, month, day);
wheelMain.setScollerListener(new WheelMain.ScollerListener(){
@Override
public void onWheelScoller() {
dateView.setText(wheelMain.getTime());
}
});
return timepickerview;
}
public View initDateDayView(int day,final TextView dateView) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View timepickerview = inflater.inflate(R.layout.timepicker_of_day, null);
ScreenInfo screenInfo = new ScreenInfo((Activity)mContext);
final WheelMain wheelMain = new WheelMain(timepickerview, false);
wheelMain.screenheight = screenInfo.getHeight();
wheelMain.screenwidth = screenInfo.getWidth();
wheelMain.initDateTimePicker(day);
wheelMain.setScollerListener(new WheelMain.ScollerListener() {
@Override
public void onWheelScoller() {
dateView.setText(wheelMain.getTime());
}
});
return timepickerview;
}
}
| UTF-8 | Java | 2,161 | java | DateViewUtils.java | Java | [
{
"context": ".R;\n\nimport java.util.Calendar;\n\n/**\n * Created by zwb on 2016/5/1.\n */\npublic class DateViewUtils {\n ",
"end": 274,
"score": 0.9995413422584534,
"start": 271,
"tag": "USERNAME",
"value": "zwb"
}
] | null | [] | package com.yikang.health.widget.time;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.yikang.health.R;
import java.util.Calendar;
/**
* Created by zwb on 2016/5/1.
*/
public class DateViewUtils {
Context mContext;
public DateViewUtils(Context context){
mContext = context;
}
public View initFullDateView(final TextView dateView) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View timepickerview = inflater.inflate(R.layout.timepicker, null);
ScreenInfo screenInfo = new ScreenInfo((Activity)mContext);
final WheelMain wheelMain = new WheelMain(timepickerview, false);
wheelMain.screenheight = screenInfo.getHeight();
wheelMain.screenwidth = screenInfo.getWidth();
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH)+1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
wheelMain.initDateTimePicker(year, month, day);
wheelMain.setScollerListener(new WheelMain.ScollerListener(){
@Override
public void onWheelScoller() {
dateView.setText(wheelMain.getTime());
}
});
return timepickerview;
}
public View initDateDayView(int day,final TextView dateView) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View timepickerview = inflater.inflate(R.layout.timepicker_of_day, null);
ScreenInfo screenInfo = new ScreenInfo((Activity)mContext);
final WheelMain wheelMain = new WheelMain(timepickerview, false);
wheelMain.screenheight = screenInfo.getHeight();
wheelMain.screenwidth = screenInfo.getWidth();
wheelMain.initDateTimePicker(day);
wheelMain.setScollerListener(new WheelMain.ScollerListener() {
@Override
public void onWheelScoller() {
dateView.setText(wheelMain.getTime());
}
});
return timepickerview;
}
}
| 2,161 | 0.67515 | 0.671911 | 60 | 35.016666 | 24.460506 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.683333 | false | false | 2 |
c0753e8cf942697c2c1f4bb0a70864a63fc39bd2 | 31,301,721,699,617 | 101335c0041ed1bbb016c61adca2b4f65ddb9636 | /app/src/main/java/com/rdmchain/gallery/Activity/MainActivity.java | a178a645c329e0f5224054e790345a2d8307506c | [] | no_license | Roy-Jang/GridLayoutImageRecyclerView_Android | https://github.com/Roy-Jang/GridLayoutImageRecyclerView_Android | 0685c0fb80f112937e1a574f5268ce23e88dbbdd | ebdf36f9966f9d7329251723c7ec8dcae0456426 | refs/heads/master | 2022-12-01T11:17:18.436000 | 2020-08-11T07:15:18 | 2020-08-11T07:15:18 | 285,223,420 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rdmchain.gallery.Activity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import com.rdmchain.gallery.Adapter.AdapterItems;
import com.rdmchain.gallery.Api.ApiClient;
import com.rdmchain.gallery.Api.ApiInterface;
import com.rdmchain.gallery.Data.Items;
import com.rdmchain.gallery.Data.ItemsDataResponse;
import com.rdmchain.gallery.R;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity implements AdapterItems.OnLoadMoreListener {
// Context
private Context mContext;
// View 관련
private RecyclerView mRecyclerView;
private ProgressBar mProgressBar;
private NestedScrollView mNestedScrollView;
//Api
private ApiInterface mApiInterface;
// 리스트 관련
private AdapterItems mAdapter;
private List<Items> itemsList;
private int nextPage, totalCount;
private GridLayoutManager mGridLayoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
// View
mNestedScrollView = findViewById(R.id.nestedScrollView);
mRecyclerView = findViewById(R.id.recyclerView);
mProgressBar = findViewById(R.id.progressBar);
// 리스트 기본값
itemsList = new ArrayList<Items>();
mGridLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(mGridLayoutManager);
mAdapter = new AdapterItems(this, itemsList, mContext, mProgressBar);
mRecyclerView.setAdapter(mAdapter);
nextPage = 1;
totalCount = 0;
mApiInterface = ApiClient.getApiclient().create(ApiInterface.class);
// 처음 페이지
callApi(false);
// 추가 페이지
mNestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
@Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if(v.getChildAt(v.getChildCount() - 1) != null) {
if ((scrollY >= (v.getChildAt(v.getChildCount() - 1).getMeasuredHeight() - v.getMeasuredHeight())) && scrollY > oldScrollY) {
mAdapter.showLoading();
}
}
}
});
}
@Override
public void onLoadMore() {
callApi(true);
}
private void callApi(final boolean isMore) {
Call <ItemsDataResponse> call = mApiInterface.getItems(nextPage);
call.enqueue(new Callback<ItemsDataResponse>() {
@Override
public void onResponse(Call<ItemsDataResponse> call, Response<ItemsDataResponse> response) {
if (response.body().getItems().size() > 0) {
if (isMore) {
try {
Thread.sleep(1500);
mAdapter.dismissLoading();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
mAdapter.addItems(response.body().getItems());
nextPage = response.body().getNextPage();
totalCount = response.body().getTotal();
if (nextPage == 0) {
mAdapter.setMore(false);
}
} else {
// 없을 경우
mRecyclerView.setVisibility(View.GONE);
}
}
@Override
public void onFailure(Call<ItemsDataResponse> call, Throwable t) {
// 오류
Log.e("jang", "" + t);
}
});
}
}
| UTF-8 | Java | 4,207 | java | MainActivity.java | Java | [] | null | [] | package com.rdmchain.gallery.Activity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import com.rdmchain.gallery.Adapter.AdapterItems;
import com.rdmchain.gallery.Api.ApiClient;
import com.rdmchain.gallery.Api.ApiInterface;
import com.rdmchain.gallery.Data.Items;
import com.rdmchain.gallery.Data.ItemsDataResponse;
import com.rdmchain.gallery.R;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity implements AdapterItems.OnLoadMoreListener {
// Context
private Context mContext;
// View 관련
private RecyclerView mRecyclerView;
private ProgressBar mProgressBar;
private NestedScrollView mNestedScrollView;
//Api
private ApiInterface mApiInterface;
// 리스트 관련
private AdapterItems mAdapter;
private List<Items> itemsList;
private int nextPage, totalCount;
private GridLayoutManager mGridLayoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
// View
mNestedScrollView = findViewById(R.id.nestedScrollView);
mRecyclerView = findViewById(R.id.recyclerView);
mProgressBar = findViewById(R.id.progressBar);
// 리스트 기본값
itemsList = new ArrayList<Items>();
mGridLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(mGridLayoutManager);
mAdapter = new AdapterItems(this, itemsList, mContext, mProgressBar);
mRecyclerView.setAdapter(mAdapter);
nextPage = 1;
totalCount = 0;
mApiInterface = ApiClient.getApiclient().create(ApiInterface.class);
// 처음 페이지
callApi(false);
// 추가 페이지
mNestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
@Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if(v.getChildAt(v.getChildCount() - 1) != null) {
if ((scrollY >= (v.getChildAt(v.getChildCount() - 1).getMeasuredHeight() - v.getMeasuredHeight())) && scrollY > oldScrollY) {
mAdapter.showLoading();
}
}
}
});
}
@Override
public void onLoadMore() {
callApi(true);
}
private void callApi(final boolean isMore) {
Call <ItemsDataResponse> call = mApiInterface.getItems(nextPage);
call.enqueue(new Callback<ItemsDataResponse>() {
@Override
public void onResponse(Call<ItemsDataResponse> call, Response<ItemsDataResponse> response) {
if (response.body().getItems().size() > 0) {
if (isMore) {
try {
Thread.sleep(1500);
mAdapter.dismissLoading();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
mAdapter.addItems(response.body().getItems());
nextPage = response.body().getNextPage();
totalCount = response.body().getTotal();
if (nextPage == 0) {
mAdapter.setMore(false);
}
} else {
// 없을 경우
mRecyclerView.setVisibility(View.GONE);
}
}
@Override
public void onFailure(Call<ItemsDataResponse> call, Throwable t) {
// 오류
Log.e("jang", "" + t);
}
});
}
}
| 4,207 | 0.611714 | 0.608339 | 123 | 32.731709 | 26.721106 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.577236 | false | false | 2 |
b7e82404a53be7ab02f370559a48040686a2d3c9 | 2,138,893,721,577 | 93180beb7fb0902a43383360ca0bd769f4692d44 | /webapp Project/jupiter/src/main/java/com/laioffer/job/entity/ResultResponse.java | 3bdc9a0665f9c1563e0a0bcd3c13dc13778eba12 | [] | no_license | xiaoxue123123/WebApplication | https://github.com/xiaoxue123123/WebApplication | c4839181e163f7d9a7d386c4466b5ba36ea1d819 | b05d9791f76cdf928576b13c2f8d942c6f29eb59 | refs/heads/master | 2023-03-04T01:28:06.541000 | 2021-12-10T02:13:33 | 2021-12-10T02:13:33 | 339,176,702 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.laioffer.job.entity;
/**
* ResultResponse is for the response result from the requests,
* and it's going to be used multiple times.
* **/
public class ResultResponse {
public String result;
public ResultResponse() {
}
public ResultResponse(String result) {
this.result = result;
}
}
| UTF-8 | Java | 331 | java | ResultResponse.java | Java | [] | null | [] | package com.laioffer.job.entity;
/**
* ResultResponse is for the response result from the requests,
* and it's going to be used multiple times.
* **/
public class ResultResponse {
public String result;
public ResultResponse() {
}
public ResultResponse(String result) {
this.result = result;
}
}
| 331 | 0.667674 | 0.667674 | 18 | 17.388889 | 18.994556 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 2 |
9cc2341694b4b993f7cf7d9cec8d05fda62f3f45 | 3,324,304,694,668 | bfb621b11896ac6afb3a3573a9a114f5f814796b | /JDF/src/com/xdarkness/framework/orm/Mysql2Oracle.java | c5b216692191a73e4b36afef294b7977bcaac3fb | [] | no_license | dalinhuang/xdarkness | https://github.com/dalinhuang/xdarkness | b728bf5644a6ae99b7a756e9bc8c52fcde14029e | 243c938b1b59ea5bda748f1b6e6bc41f88815f0d | refs/heads/master | 2016-08-11T14:10:41.821000 | 2011-07-29T15:54:58 | 2011-07-29T15:54:58 | 48,953,917 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xdarkness.framework.orm;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;
import org.dom4j.io.SAXReader;
import com.xdarkness.framework.io.FileUtil;
import com.xdarkness.framework.orm.data.DataTable;
import com.xdarkness.framework.sql.QueryBuilder;
import com.xdarkness.framework.util.XString;
public class Mysql2Oracle {
public static String generateOneTableSQL(String tableName) {
StringBuffer sb = new StringBuffer();
try {
Class clz = Class.forName("com.xdarkness.schema." + tableName
+ "Schema");
Schema sc = (Schema) clz.newInstance();
SchemaColumn[] cols = SchemaUtil.getColumns(sc);
ArrayList pkList = new ArrayList();
sb.append("drop table " + tableName + " cascade constraints;\n");
sb.append("create table " + tableName + " (\n");
for (int i = 0; i < cols.length; i++) {
SchemaColumn col = cols[i];
String dataType = "";
if ((col.getColumnType() == 8) || (col.getColumnType() == 7))
dataType = "integer";
else if (col.getColumnType() == 1) {
if ((col.getLength() < 8) && (col.getLength() > 0))
dataType = "varchar(" + col.getLength() + ")";
else if (col.getLength() >= 8)
dataType = "varchar2(" + col.getLength() + ")";
else {
dataType = "long";
}
} else if (col.getColumnType() == 5)
dataType = "float";
else if (col.getColumnType() == 0)
dataType = "date";
else {
dataType = "varchar2(" + col.getLength() + ")";
}
if (col.isPrimaryKey()) {
pkList.add(col.getColumnName());
}
sb.append(col.getColumnName());
sb.append(" " + dataType);
sb.append(col.isMandatory() ? " not null" : " ");
sb.append(",\n");
}
sb.append("constraint PK_" + tableName + " primary key ("
+ XString.join(pkList.toArray(), ",") + ")\n");
sb.append(");\n");
System.out.println(sb.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return sb.toString();
}
public static void dealFile(String fileName) {
BackupTableGenerator btg = new BackupTableGenerator();
btg.setFileName(fileName);
try {
btg.toBackupTable();
} catch (Exception e) {
e.printStackTrace();
}
try {
generateSQL(fileName);
} catch (Exception e) {
e.printStackTrace();
}
fileName = fileName.substring(0, fileName.length() - 4) + "_B.pdm";
try {
generateSQL(fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void generateSQL(String fileName) throws Exception {
File f = new File(fileName);
if (!f.exists()) {
throw new RuntimeException("文件不存在");
}
SAXReader reader = new SAXReader(false);
Document doc = reader.read(f);
Element root = doc.getRootElement();
Namespace nso = root.getNamespaceForPrefix("o");
Namespace nsc = root.getNamespaceForPrefix("c");
Namespace nsa = root.getNamespaceForPrefix("a");
Element rootObject = root.element(new QName("RootObject", nso));
Element children = rootObject.element(new QName("Children", nsc));
Element model = children.element(new QName("Model", nso));
List tables = model.element(new QName("Tables", nsc)).elements();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < tables.size(); i++) {
Element table = (Element) tables.get(i);
String tableName = table.elementText(new QName("Code", nsa));
sb.append(generateOneTableSQL(tableName));
}
fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
FileUtil.writeText("DB/Oracle/"
+ fileName.substring(0, fileName.length() - 4) + ".sql", sb
.toString());
}
public static void importData() {
DataTable dt = new QueryBuilder("show tables").executeDataTable();
for (int i = 0; i < dt.getRowCount(); i++) {
StringBuffer valueSQL = new StringBuffer();
String tableName = dt.getString(i, 0);
valueSQL.append("truncate table " + tableName + ";\n");
if ((!tableName.startsWith("b"))
&& (!"zcarticle".equals(tableName))) {
DataTable dtValue = new QueryBuilder("select * from "
+ dt.getString(i, 0)).executeDataTable();
for (int j = 0; j < dtValue.getRowCount(); j++) {
StringBuffer sb = new StringBuffer();
sb.append("insert into ");
sb.append(tableName);
sb.append(" values(");
for (int k = 0; k < dtValue.getColCount(); k++) {
if (k != 0)
sb.append(",'" + dtValue.getString(j, k) + "'");
else {
sb.append("'" + dtValue.getString(j, k) + "'");
}
}
sb.append(")");
valueSQL.append(sb + ";\n");
}
}
System.out.println(valueSQL.toString());
}
}
public static void main(String[] args) {
String str = "skycms";
String[] files = str.split("\\,");
for (int i = 0; i < files.length; i++) {
String fileName = "DB/" + files[i] + ".pdm";
dealFile(fileName);
}
}
} | UTF-8 | Java | 5,228 | java | Mysql2Oracle.java | Java | [] | null | [] | package com.xdarkness.framework.orm;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;
import org.dom4j.io.SAXReader;
import com.xdarkness.framework.io.FileUtil;
import com.xdarkness.framework.orm.data.DataTable;
import com.xdarkness.framework.sql.QueryBuilder;
import com.xdarkness.framework.util.XString;
public class Mysql2Oracle {
public static String generateOneTableSQL(String tableName) {
StringBuffer sb = new StringBuffer();
try {
Class clz = Class.forName("com.xdarkness.schema." + tableName
+ "Schema");
Schema sc = (Schema) clz.newInstance();
SchemaColumn[] cols = SchemaUtil.getColumns(sc);
ArrayList pkList = new ArrayList();
sb.append("drop table " + tableName + " cascade constraints;\n");
sb.append("create table " + tableName + " (\n");
for (int i = 0; i < cols.length; i++) {
SchemaColumn col = cols[i];
String dataType = "";
if ((col.getColumnType() == 8) || (col.getColumnType() == 7))
dataType = "integer";
else if (col.getColumnType() == 1) {
if ((col.getLength() < 8) && (col.getLength() > 0))
dataType = "varchar(" + col.getLength() + ")";
else if (col.getLength() >= 8)
dataType = "varchar2(" + col.getLength() + ")";
else {
dataType = "long";
}
} else if (col.getColumnType() == 5)
dataType = "float";
else if (col.getColumnType() == 0)
dataType = "date";
else {
dataType = "varchar2(" + col.getLength() + ")";
}
if (col.isPrimaryKey()) {
pkList.add(col.getColumnName());
}
sb.append(col.getColumnName());
sb.append(" " + dataType);
sb.append(col.isMandatory() ? " not null" : " ");
sb.append(",\n");
}
sb.append("constraint PK_" + tableName + " primary key ("
+ XString.join(pkList.toArray(), ",") + ")\n");
sb.append(");\n");
System.out.println(sb.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return sb.toString();
}
public static void dealFile(String fileName) {
BackupTableGenerator btg = new BackupTableGenerator();
btg.setFileName(fileName);
try {
btg.toBackupTable();
} catch (Exception e) {
e.printStackTrace();
}
try {
generateSQL(fileName);
} catch (Exception e) {
e.printStackTrace();
}
fileName = fileName.substring(0, fileName.length() - 4) + "_B.pdm";
try {
generateSQL(fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void generateSQL(String fileName) throws Exception {
File f = new File(fileName);
if (!f.exists()) {
throw new RuntimeException("文件不存在");
}
SAXReader reader = new SAXReader(false);
Document doc = reader.read(f);
Element root = doc.getRootElement();
Namespace nso = root.getNamespaceForPrefix("o");
Namespace nsc = root.getNamespaceForPrefix("c");
Namespace nsa = root.getNamespaceForPrefix("a");
Element rootObject = root.element(new QName("RootObject", nso));
Element children = rootObject.element(new QName("Children", nsc));
Element model = children.element(new QName("Model", nso));
List tables = model.element(new QName("Tables", nsc)).elements();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < tables.size(); i++) {
Element table = (Element) tables.get(i);
String tableName = table.elementText(new QName("Code", nsa));
sb.append(generateOneTableSQL(tableName));
}
fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
FileUtil.writeText("DB/Oracle/"
+ fileName.substring(0, fileName.length() - 4) + ".sql", sb
.toString());
}
public static void importData() {
DataTable dt = new QueryBuilder("show tables").executeDataTable();
for (int i = 0; i < dt.getRowCount(); i++) {
StringBuffer valueSQL = new StringBuffer();
String tableName = dt.getString(i, 0);
valueSQL.append("truncate table " + tableName + ";\n");
if ((!tableName.startsWith("b"))
&& (!"zcarticle".equals(tableName))) {
DataTable dtValue = new QueryBuilder("select * from "
+ dt.getString(i, 0)).executeDataTable();
for (int j = 0; j < dtValue.getRowCount(); j++) {
StringBuffer sb = new StringBuffer();
sb.append("insert into ");
sb.append(tableName);
sb.append(" values(");
for (int k = 0; k < dtValue.getColCount(); k++) {
if (k != 0)
sb.append(",'" + dtValue.getString(j, k) + "'");
else {
sb.append("'" + dtValue.getString(j, k) + "'");
}
}
sb.append(")");
valueSQL.append(sb + ";\n");
}
}
System.out.println(valueSQL.toString());
}
}
public static void main(String[] args) {
String str = "skycms";
String[] files = str.split("\\,");
for (int i = 0; i < files.length; i++) {
String fileName = "DB/" + files[i] + ".pdm";
dealFile(fileName);
}
}
} | 5,228 | 0.609046 | 0.603296 | 174 | 28 | 20.903996 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.143678 | false | false | 2 |
ce4dd6b0f5c4d05288333a3a889c6b2417b3a259 | 4,183,298,154,646 | 395e60e050235765a43d4996a8a71bd676296d0c | /src/main/java/com/ingestion/kafka/service/KafkaProducerService.java | f70d3f97d178d4ac7af37638c64996f8ba509817 | [] | no_license | trayambakkumar/Kafka-using-springboot | https://github.com/trayambakkumar/Kafka-using-springboot | f06a22dcf2688188a956544cbbb949785033090e | 700d0ad02daa0c4b40a5aedab5caf9587cd2fde7 | refs/heads/master | 2023-03-19T11:55:54.798000 | 2021-03-08T05:07:04 | 2021-03-08T05:07:04 | 345,537,379 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ingestion.kafka.service;
import com.ingestion.kafka.constants.AppConstants;
import com.ingestion.kafka.models.Event;
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.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
@Service
public class KafkaProducerService {
private static final Logger logger
= LoggerFactory.getLogger(KafkaProducerService.class);
@Value(value = "${event.topic.name}")
private String topicName;
private KafkaTemplate<String, Event> kafkaTemplate;
@Autowired
public KafkaProducerService(KafkaTemplate<String, Event> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
public void saveCreateEventLog(Event event) {
logger.info(String.format("Event created -> %s", event));
ListenableFuture<SendResult<String, Event>> future
= this.kafkaTemplate.send(topicName, event);
future.addCallback(new ListenableFutureCallback<>() {
@Override
public void onFailure(Throwable throwable) {
logger.error("Event couldn't be sent " + event, throwable);
}
@Override
public void onSuccess(SendResult<String, Event> stringObjectSendResult) {
logger.info("Event created: " + event + " with offset " +
stringObjectSendResult.getRecordMetadata().offset());
}
});
}
}
| UTF-8 | Java | 1,782 | java | KafkaProducerService.java | Java | [] | null | [] | package com.ingestion.kafka.service;
import com.ingestion.kafka.constants.AppConstants;
import com.ingestion.kafka.models.Event;
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.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
@Service
public class KafkaProducerService {
private static final Logger logger
= LoggerFactory.getLogger(KafkaProducerService.class);
@Value(value = "${event.topic.name}")
private String topicName;
private KafkaTemplate<String, Event> kafkaTemplate;
@Autowired
public KafkaProducerService(KafkaTemplate<String, Event> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
public void saveCreateEventLog(Event event) {
logger.info(String.format("Event created -> %s", event));
ListenableFuture<SendResult<String, Event>> future
= this.kafkaTemplate.send(topicName, event);
future.addCallback(new ListenableFutureCallback<>() {
@Override
public void onFailure(Throwable throwable) {
logger.error("Event couldn't be sent " + event, throwable);
}
@Override
public void onSuccess(SendResult<String, Event> stringObjectSendResult) {
logger.info("Event created: " + event + " with offset " +
stringObjectSendResult.getRecordMetadata().offset());
}
});
}
}
| 1,782 | 0.705948 | 0.704826 | 48 | 36.125 | 26.5382 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 2 |
fb0c64fa1374de4087b401fd9443901c2fc3544b | 7,808,250,553,451 | ce5a93dfe8fc69c616b9fbda76142997d6801e3f | /src/TestQuestions/MinWord.java | 73c268dfe9bb19e832176b3b6ff31dacac0170f9 | [] | no_license | gauravdwivedi/Foundation | https://github.com/gauravdwivedi/Foundation | 18ec8e37d864047e3d4ffc1c7913272ef21f9ddc | b76d3dd99e15d59223636cbbecef405d3537b1ce | refs/heads/master | 2021-01-02T01:58:21.038000 | 2019-11-28T08:29:53 | 2019-11-28T08:29:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package TestQuestions;
public class MinWord {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
//
// public static String minLengthWord(String input) {
//
// int minWordStart=0;
// int minWordEnd =input.length()-1;
//
//
//
//
// }
}
| UTF-8 | Java | 286 | java | MinWord.java | Java | [] | null | [] | package TestQuestions;
public class MinWord {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
//
// public static String minLengthWord(String input) {
//
// int minWordStart=0;
// int minWordEnd =input.length()-1;
//
//
//
//
// }
}
| 286 | 0.622378 | 0.615385 | 21 | 12.619047 | 16.063789 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.190476 | false | false | 2 |
3ca5dab88cfaaaed8e265a5d3da5dcca72d9c642 | 10,024,453,674,725 | 7999532358f798d9abdfe719c609c258835b6128 | /src/sketch/ProcessingSketch.java | 440b4950cdae454a029aaf82345da55394f0f952 | [] | no_license | dgop92/Kinematic-Simulator | https://github.com/dgop92/Kinematic-Simulator | 27363a1eb631d5208a6f6844dd3919541052443e | db56488b11f27942b4cd9a6007358a5066be70a2 | refs/heads/master | 2022-12-07T07:09:57.819000 | 2020-08-31T14:24:44 | 2020-08-31T14:24:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sketch;
import processing.core.PApplet;
import vectors.Acceleration;
import vectors.Position;
import vectors.Velocity;
import main.SketchEvents;
public class ProcessingSketch extends PApplet{
private SketchEvents sketchEvents;
private int MAX_BALL_SIZE = 5;
private Ball[] balls;
private int ballIndex;
//Flags
public boolean isAskingForBallPosition = false;
public boolean isRunning = false;
@Override
public void settings() {
size(500, 500);
}
@Override
public void setup() {
frameRate(30);
background(0);
initSketch();
}
private void initSketch(){
balls = new Ball[MAX_BALL_SIZE];
ballIndex = 0;
}
@Override
public void draw() {
background(0);
simulateKinematic();
previewBall();
previewBalls();
}
@Override
public void mousePressed() {
if (isAskingForBallPosition){
sketchEvents.sendBallPosition(new Position(mouseX, mouseY));
isAskingForBallPosition = false;
}
}
private void simulateKinematic(){
if (isRunning){
for (int i = 0; i < ballIndex; i++) {
Ball ball = balls[i];
ball.onUpdate();
}
}
}
private void previewBall(){
if (isAskingForBallPosition){
Ball.previewBall(this, mouseX, mouseY);
}
}
private void previewBalls(){
if (!isRunning){
for (int i = 0; i < ballIndex; i++) {
Ball ball = balls[i];
ball.drawBall();
}
}
}
public void createBall(Position ballPosition, Velocity ballVelocity,
Acceleration ballAcceleration){
if (ballIndex < MAX_BALL_SIZE){
Ball newBall = new Ball(this, ballPosition, ballVelocity, ballAcceleration);
balls[ballIndex] = newBall;
ballIndex ++;
}else{
//Send error message to interface
}
}
public void restartSketch(){
initSketch();
isRunning = false;
}
public void run(SketchEvents sketchEvents) {
String[] processingArgs = { ProcessingSketch.class.getName() };
PApplet.runSketch(processingArgs, this);
this.sketchEvents = sketchEvents;
}
} | UTF-8 | Java | 2,374 | java | ProcessingSketch.java | Java | [] | null | [] | package sketch;
import processing.core.PApplet;
import vectors.Acceleration;
import vectors.Position;
import vectors.Velocity;
import main.SketchEvents;
public class ProcessingSketch extends PApplet{
private SketchEvents sketchEvents;
private int MAX_BALL_SIZE = 5;
private Ball[] balls;
private int ballIndex;
//Flags
public boolean isAskingForBallPosition = false;
public boolean isRunning = false;
@Override
public void settings() {
size(500, 500);
}
@Override
public void setup() {
frameRate(30);
background(0);
initSketch();
}
private void initSketch(){
balls = new Ball[MAX_BALL_SIZE];
ballIndex = 0;
}
@Override
public void draw() {
background(0);
simulateKinematic();
previewBall();
previewBalls();
}
@Override
public void mousePressed() {
if (isAskingForBallPosition){
sketchEvents.sendBallPosition(new Position(mouseX, mouseY));
isAskingForBallPosition = false;
}
}
private void simulateKinematic(){
if (isRunning){
for (int i = 0; i < ballIndex; i++) {
Ball ball = balls[i];
ball.onUpdate();
}
}
}
private void previewBall(){
if (isAskingForBallPosition){
Ball.previewBall(this, mouseX, mouseY);
}
}
private void previewBalls(){
if (!isRunning){
for (int i = 0; i < ballIndex; i++) {
Ball ball = balls[i];
ball.drawBall();
}
}
}
public void createBall(Position ballPosition, Velocity ballVelocity,
Acceleration ballAcceleration){
if (ballIndex < MAX_BALL_SIZE){
Ball newBall = new Ball(this, ballPosition, ballVelocity, ballAcceleration);
balls[ballIndex] = newBall;
ballIndex ++;
}else{
//Send error message to interface
}
}
public void restartSketch(){
initSketch();
isRunning = false;
}
public void run(SketchEvents sketchEvents) {
String[] processingArgs = { ProcessingSketch.class.getName() };
PApplet.runSketch(processingArgs, this);
this.sketchEvents = sketchEvents;
}
} | 2,374 | 0.569082 | 0.563184 | 105 | 21.619047 | 18.808498 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.485714 | false | false | 2 |
ed246134c3b1709c9ab9e10293454a5f8d7f50cf | 13,804,024,898,520 | 5fb2edd24da3042e3def986666735412dabf6c40 | /Android/SecChat/app/src/main/java/com/razuvaevdd/secchat/MainActivity.java | 815fc9323c043eaaed742e5629a342634a8613df | [
"MIT"
] | permissive | RazuvaevDD/I2PSecChat | https://github.com/RazuvaevDD/I2PSecChat | 5b2796bd10f93d213bde90edf1c8d76d55881dbf | d26894c7849dadade8cc59c3ff390e20896f8dc5 | refs/heads/release | 2023-03-09T12:07:44.387000 | 2021-02-21T15:07:53 | 2021-02-21T15:07:53 | 315,027,754 | 1 | 6 | MIT | false | 2021-02-22T08:51:58 | 2020-11-22T12:04:56 | 2021-02-21T15:07:58 | 2021-02-21T15:14:38 | 10,576 | 0 | 3 | 0 | Java | false | false | package com.razuvaevdd.secchat;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;
import com.razuvaevdd.I2PConnector.I2PConnector;
import com.razuvaevdd.I2PConnector.TypeOfConnection;
import com.razuvaevdd.Objects.*;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
/////Необходимо для доступа в интернет (не трогать!)/////
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/////////////////////////////////////////////////////////
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.text1);
new I2PConnector(getApplicationContext(), TypeOfConnection.HTTPConnection);
////////////////Пример отправки сообщения////////////////
I2PConnector.sendMessage(new Message(
I2PConnector.getMyAccount(),
I2PConnector.getMyAccount(),
"testMsgFromClient",
TypeOfMessage.StringMessage,
"ВКакуюКомнату"));
/////////////////////////////////////////////////////////
/////////////////Пример приема сообщения/////////////////
while (!(I2PConnector.haveNewMessages())) {
try {
textView.setText("[INFO] Main: Ждем пока что-то появится...");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String firstMessageBody = I2PConnector.getNewMessages().get(0).message;
/////////////////////////////////////////////////////////
textView.setText("Получено сообщение: "+firstMessageBody);
}
}
| UTF-8 | Java | 2,039 | java | MainActivity.java | Java | [] | null | [] | package com.razuvaevdd.secchat;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;
import com.razuvaevdd.I2PConnector.I2PConnector;
import com.razuvaevdd.I2PConnector.TypeOfConnection;
import com.razuvaevdd.Objects.*;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
/////Необходимо для доступа в интернет (не трогать!)/////
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/////////////////////////////////////////////////////////
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.text1);
new I2PConnector(getApplicationContext(), TypeOfConnection.HTTPConnection);
////////////////Пример отправки сообщения////////////////
I2PConnector.sendMessage(new Message(
I2PConnector.getMyAccount(),
I2PConnector.getMyAccount(),
"testMsgFromClient",
TypeOfMessage.StringMessage,
"ВКакуюКомнату"));
/////////////////////////////////////////////////////////
/////////////////Пример приема сообщения/////////////////
while (!(I2PConnector.haveNewMessages())) {
try {
textView.setText("[INFO] Main: Ждем пока что-то появится...");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String firstMessageBody = I2PConnector.getNewMessages().get(0).message;
/////////////////////////////////////////////////////////
textView.setText("Получено сообщение: "+firstMessageBody);
}
}
| 2,039 | 0.572928 | 0.565058 | 47 | 39.553192 | 25.194401 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.531915 | false | false | 2 |
78af0f42b42baa2ca30e3339be0805cb3e2c335f | 3,942,780,021,703 | f1490f54bab67aa12fd6a88b179c9609dbe9c812 | /wechatclient/src/main/java/com/qi/wechatclient/view/EditTextWithCompound.java | 6b712068e6f85acc14397d06a9a5491476b4b2eb | [] | no_license | qiqiqiqiqi/zhoubaoqi | https://github.com/qiqiqiqiqi/zhoubaoqi | b18f8902ae64873ca0245192343f4c416ebabfa2 | 429d55aa7d9cc99328a6f09eb73b5e608cbcf77e | refs/heads/master | 2023-08-17T15:57:49.252000 | 2023-08-02T12:10:15 | 2023-08-02T12:10:15 | 112,817,096 | 6 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.qi.wechatclient.view;
import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import com.qi.wechatclient.R;
import com.qi.wechatclient.common.WechatApplication;
import com.qi.wechatclient.utils.LogUtil;
import com.qi.wechatclient.utils.StringUtil;
import java.nio.charset.Charset;
/**
* Created by 13324 on 2016/11/9.
*/
@SuppressLint("AppCompatCustomView")
public class EditTextWithCompound extends EditText implements TextWatcher, View.OnFocusChangeListener, MenuItem.OnMenuItemClickListener {
private String TAG = EditTextWithCompound.class.getSimpleName();
protected OnInputListener onInputListener;
private Drawable leftDrawable;
/**
* the right drawable of EditText, default drawable is R.drawable.edit_text_delete_icon on resource.
*/
private Drawable rightDrawable;
private Drawable rightfulBackgroundDrawable;
private Drawable unlawfulBackgroundDrawable;
private int paddingLeft, paddingRight;
/**
* define type of this EditText One of {@link #TYPE_NORMAL}, {@link #TYPE_PHONE}, {@link #TYPE_EMAIL}, or {@link #TYPE_PHONE_EMAIL}.
*/
private int type = TYPE_NORMAL;
public static final int TYPE_NORMAL = 0;//默認的輸入類型
public static final int TYPE_PHONE = 1;//手機號碼
public static final int TYPE_EMAIL = 2;//email
public static final int TYPE_PHONE_EMAIL = 3;//手機和email
private int minLength = 1;
private int maxLength = Integer.MAX_VALUE;
private boolean isIntact = false;
private boolean pwdEyeEnable = false;
private boolean autoChange = false;
private CharSequence charSequence;
private boolean needFilter = true;//是否需要过滤特殊字符,默认需要过滤
private boolean needRestrict = true;//是否需要限制特殊,默认需要限制
public static final int MAX_TEXT_LENGTH = 32;
public static final int MAX_TEXT_LENGTH_NORMAL = 16;//原有的一些名称长度为16的
public EditTextWithCompound(Context context) {
super(context);
init();
}
public EditTextWithCompound(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public EditTextWithCompound(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
leftDrawable = getCompoundDrawables()[0];
rightDrawable = getCompoundDrawables()[2];
rightfulBackgroundDrawable = getResources().getDrawable(R.drawable.bg_bottom_line);
unlawfulBackgroundDrawable = getResources().getDrawable(R.drawable.bg_bottom_line);
if (rightDrawable == null) {
rightDrawable = getResources().getDrawable(R.drawable.login_delete);
}
paddingLeft = getPaddingLeft();
paddingRight = getPaddingRight();
setDrawable();
addTextChangedListener(this);
setOnFocusChangeListener(this);
setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
}
@Override
public void setSelection(int index) {
try {
String content = getText().toString();
if (index >= content.length()) {
index = content.length();
}
super.setSelection(index);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
setDrawable();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
LogUtil.d(TAG, "beforeTextChanged()-s:" + s + " start:" + start + " count:" + count + " after:" + after);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
LogUtil.d(TAG, "onTextChanged()-s:" + s + " start:" + start + " count:" + count + " before:" + before);
if (isIntact) {
charSequence = s.subSequence(start, start + count);
// LogUtil.d(TAG, "onTextChanged()-charSequence:" + charSequence);
}
}
@Override
public void afterTextChanged(Editable editable) {
LogUtil.d(TAG, "afterTextChanged() isIntact:" + isIntact + "autoChange:" + autoChange);
if (isIntact) {
isIntact = false;
editable.replace(0, editable.toString().length(), charSequence);
// setText(charSequence);
try {
setSelection(length());
} catch (Exception e) {
e.printStackTrace();
}
} else {
if (autoChange) { // skip execution if triggered by code
autoChange = false; // next change is not triggered by code
setDrawable();
if (isRightful()) {
onRightful();
} else {
onUnlawful();
}
return;
}
int startSelection = getSelectionStart();
String strOld = editable.toString();
String str = editable.toString();
int byteLength = str.getBytes(Charset.forName("GBK")).length;
while (byteLength > maxLength) {
int currentLength = str.length();
str = str.substring(0, currentLength - 1);
byteLength = str.getBytes(Charset.forName("GBK")).length;
}
if (!strOld.equals(str)) {
if (editable.toString().length() != 0 && str.length() != 0) {
autoChange = true;
}
editable.replace(0, editable.toString().length(), str);
}
try {
setSelection(Math.min(str.length(), startSelection));
} catch (Exception e) {
e.printStackTrace();
}
setRightful(rightfulBackgroundDrawable);
if (isRightful()) {
onRightful();
} else {
onUnlawful();
}
if (needRestrict && !StringUtil.isEmpty(str)) {
// ToastUtil.showToast(R.string.SPECIAL_CHAR_ERROR);
}
}
}
public void isNeedFilter(boolean isNeedFilter) {//是否需要过滤特殊字符
needFilter = isNeedFilter;
}
/**
* 是否限制特殊字符,默认限制
* true 限制;false不限制
*
* @param needRestrict
*/
public void setNeedRestrict(boolean needRestrict) {
this.needRestrict = needRestrict;
}
/**
* 判斷輸入的長度是否滿足規定
*
* @return
*/
public boolean isRightful() {
switch (type) {
case TYPE_NORMAL:
return length() >= minLength && length() <= maxLength;
case TYPE_PHONE:
return StringUtil.isPhone(getText().toString()) && length() >= minLength && length() <= maxLength;
case TYPE_EMAIL:
return StringUtil.isEmail(getText().toString()) && length() >= minLength && length() <= maxLength;
case TYPE_PHONE_EMAIL:
return (StringUtil.isPhone(getText().toString()) || StringUtil.isEmail(getText().toString())) && length() >= minLength && length() <= maxLength;
}
return false;
}
private void onRightful() {
if (onInputListener != null) {
onInputListener.onRightful();
}
}
private void onUnlawful() {
if (onInputListener != null) {
onInputListener.onUnlawful();
}
}
/**
* 設置輸入框的背景,可以自定義,否則使用默認的背景
*
* @param drawable
*/
public void setRightful(Drawable drawable) {
// LogUtil.d(TAG,"setRightful()");
// if (drawable != null)
rightfulBackgroundDrawable = drawable;
setBackgroundDrawable(rightfulBackgroundDrawable);
setDrawable();
}
public void setUnlawful() {
setBackgroundDrawable(unlawfulBackgroundDrawable);
setDrawable();
}
public void hideDeleteDrawable() {
rightDrawable = null;
setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null,
rightDrawable, null);
}
public void showDeleteDrawable() {
rightDrawable = WechatApplication.getWechatApplication().getResources().getDrawable(
R.drawable.login_delete);
setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null,
rightDrawable, null);
}
public void setRightfulBackgroundDrawable(Drawable rightfulBackgroundDrawable) {
this.rightfulBackgroundDrawable = rightfulBackgroundDrawable;
setDrawable();
}
public void setDrawable() {
// LogUtil.d(TAG,"setDrawable()- length():" + length() + " isFocused:" + isFocused());
if (length() == 0 || !isFocused()) {
super.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null, null, null);
} else {
super.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null, rightDrawable, null);
}
setPadding(paddingLeft, 0, paddingRight, 0);
}
public void setPaddingLeft(int paddingLeft) {
this.paddingLeft = paddingLeft;
setDrawable();
}
public void setPaddingRight(int paddingRight) {
this.paddingRight = paddingRight;
setDrawable();
}
public void setMinLength(int minLength) {
this.minLength = minLength;
}
public void setMaxLength(int maxLength) {
this.maxLength = maxLength;
setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
}
public void setIntactText(String intactText) {
isIntact = true;
removeTextChangedListener(this);//因为监听是异步的线程,所以把监听去掉
setText(intactText);
try {
setSelection(length());
} catch (Exception e) {
e.printStackTrace();
}
setDrawable();
addTextChangedListener(this);//设置好文字后,再加上监听
}
@Override
public boolean onTextContextMenuItem(int id) {
if (id == android.R.id.paste) {//粘貼的時候
if (type == TYPE_PHONE || type == TYPE_PHONE_EMAIL) {
ClipboardManager clip = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
String text = clip.getText().toString().trim();
if (!TextUtils.isEmpty(text)) {
if (!text.contains("@")) {
if (text.startsWith("+86 ")) {
text = text.substring(4);
}
if (text.startsWith("+86")) {
text = text.substring(3);
}
if (text.contains("-")) {
text = text.replace("-", "");
}
text = text.replaceAll(" ", "");// // 当联系人的号码是在通讯录中粘贴过来时会出现空格,正则会匹配不上
setText(text);
try {
setSelection(length());
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
}
}
return super.onTextContextMenuItem(id);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (isFocused() && rightDrawable != null && event.getX() > (getWidth() - getPaddingRight() - rightDrawable.getIntrinsicWidth())
&& (event.getX() < ((getWidth() - getPaddingRight())))) {
if (pwdEyeEnable) {
if (getTransformationMethod() instanceof PasswordTransformationMethod) {
setTransformationMethod(null);
rightDrawable = getResources().getDrawable(R.drawable.login_invisible);
} else {
setTransformationMethod(PasswordTransformationMethod.getInstance());
rightDrawable = getResources().getDrawable(R.drawable.login_visible);
}
} else {
this.setText("");
if (onInputListener != null) {
onInputListener.onClearText();
}
}
setDrawable();
}
}
return super.onTouchEvent(event);
}
public void setOnInputListener(OnInputListener l) {
onInputListener = l;
}
public void setType(int type) {
this.type = type;
switch (type) {
case TYPE_PHONE:
setInputType(InputType.TYPE_CLASS_PHONE);
break;
case TYPE_EMAIL:
// setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
break;
case TYPE_PHONE_EMAIL:
case TYPE_NORMAL:
setInputType(InputType.TYPE_CLASS_TEXT);
break;
}
}
@Override
protected void onCreateContextMenu(ContextMenu menu) {
super.onCreateContextMenu(menu);
}
@Override
public boolean onMenuItemClick(MenuItem item) {
return onTextContextMenuItem(item.getItemId());
}
public interface OnInputListener {
void onRightful();
void onUnlawful();
void onClearText();
}
}
| UTF-8 | Java | 14,258 | java | EditTextWithCompound.java | Java | [
{
"context": "port java.nio.charset.Charset;\n\n/**\n * Created by 13324 on 2016/11/9.\n */\n@SuppressLint(\"AppCompatCustomV",
"end": 824,
"score": 0.9979874491691589,
"start": 819,
"tag": "USERNAME",
"value": "13324"
}
] | null | [] | package com.qi.wechatclient.view;
import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import com.qi.wechatclient.R;
import com.qi.wechatclient.common.WechatApplication;
import com.qi.wechatclient.utils.LogUtil;
import com.qi.wechatclient.utils.StringUtil;
import java.nio.charset.Charset;
/**
* Created by 13324 on 2016/11/9.
*/
@SuppressLint("AppCompatCustomView")
public class EditTextWithCompound extends EditText implements TextWatcher, View.OnFocusChangeListener, MenuItem.OnMenuItemClickListener {
private String TAG = EditTextWithCompound.class.getSimpleName();
protected OnInputListener onInputListener;
private Drawable leftDrawable;
/**
* the right drawable of EditText, default drawable is R.drawable.edit_text_delete_icon on resource.
*/
private Drawable rightDrawable;
private Drawable rightfulBackgroundDrawable;
private Drawable unlawfulBackgroundDrawable;
private int paddingLeft, paddingRight;
/**
* define type of this EditText One of {@link #TYPE_NORMAL}, {@link #TYPE_PHONE}, {@link #TYPE_EMAIL}, or {@link #TYPE_PHONE_EMAIL}.
*/
private int type = TYPE_NORMAL;
public static final int TYPE_NORMAL = 0;//默認的輸入類型
public static final int TYPE_PHONE = 1;//手機號碼
public static final int TYPE_EMAIL = 2;//email
public static final int TYPE_PHONE_EMAIL = 3;//手機和email
private int minLength = 1;
private int maxLength = Integer.MAX_VALUE;
private boolean isIntact = false;
private boolean pwdEyeEnable = false;
private boolean autoChange = false;
private CharSequence charSequence;
private boolean needFilter = true;//是否需要过滤特殊字符,默认需要过滤
private boolean needRestrict = true;//是否需要限制特殊,默认需要限制
public static final int MAX_TEXT_LENGTH = 32;
public static final int MAX_TEXT_LENGTH_NORMAL = 16;//原有的一些名称长度为16的
public EditTextWithCompound(Context context) {
super(context);
init();
}
public EditTextWithCompound(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public EditTextWithCompound(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
leftDrawable = getCompoundDrawables()[0];
rightDrawable = getCompoundDrawables()[2];
rightfulBackgroundDrawable = getResources().getDrawable(R.drawable.bg_bottom_line);
unlawfulBackgroundDrawable = getResources().getDrawable(R.drawable.bg_bottom_line);
if (rightDrawable == null) {
rightDrawable = getResources().getDrawable(R.drawable.login_delete);
}
paddingLeft = getPaddingLeft();
paddingRight = getPaddingRight();
setDrawable();
addTextChangedListener(this);
setOnFocusChangeListener(this);
setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
}
@Override
public void setSelection(int index) {
try {
String content = getText().toString();
if (index >= content.length()) {
index = content.length();
}
super.setSelection(index);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
setDrawable();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
LogUtil.d(TAG, "beforeTextChanged()-s:" + s + " start:" + start + " count:" + count + " after:" + after);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
LogUtil.d(TAG, "onTextChanged()-s:" + s + " start:" + start + " count:" + count + " before:" + before);
if (isIntact) {
charSequence = s.subSequence(start, start + count);
// LogUtil.d(TAG, "onTextChanged()-charSequence:" + charSequence);
}
}
@Override
public void afterTextChanged(Editable editable) {
LogUtil.d(TAG, "afterTextChanged() isIntact:" + isIntact + "autoChange:" + autoChange);
if (isIntact) {
isIntact = false;
editable.replace(0, editable.toString().length(), charSequence);
// setText(charSequence);
try {
setSelection(length());
} catch (Exception e) {
e.printStackTrace();
}
} else {
if (autoChange) { // skip execution if triggered by code
autoChange = false; // next change is not triggered by code
setDrawable();
if (isRightful()) {
onRightful();
} else {
onUnlawful();
}
return;
}
int startSelection = getSelectionStart();
String strOld = editable.toString();
String str = editable.toString();
int byteLength = str.getBytes(Charset.forName("GBK")).length;
while (byteLength > maxLength) {
int currentLength = str.length();
str = str.substring(0, currentLength - 1);
byteLength = str.getBytes(Charset.forName("GBK")).length;
}
if (!strOld.equals(str)) {
if (editable.toString().length() != 0 && str.length() != 0) {
autoChange = true;
}
editable.replace(0, editable.toString().length(), str);
}
try {
setSelection(Math.min(str.length(), startSelection));
} catch (Exception e) {
e.printStackTrace();
}
setRightful(rightfulBackgroundDrawable);
if (isRightful()) {
onRightful();
} else {
onUnlawful();
}
if (needRestrict && !StringUtil.isEmpty(str)) {
// ToastUtil.showToast(R.string.SPECIAL_CHAR_ERROR);
}
}
}
public void isNeedFilter(boolean isNeedFilter) {//是否需要过滤特殊字符
needFilter = isNeedFilter;
}
/**
* 是否限制特殊字符,默认限制
* true 限制;false不限制
*
* @param needRestrict
*/
public void setNeedRestrict(boolean needRestrict) {
this.needRestrict = needRestrict;
}
/**
* 判斷輸入的長度是否滿足規定
*
* @return
*/
public boolean isRightful() {
switch (type) {
case TYPE_NORMAL:
return length() >= minLength && length() <= maxLength;
case TYPE_PHONE:
return StringUtil.isPhone(getText().toString()) && length() >= minLength && length() <= maxLength;
case TYPE_EMAIL:
return StringUtil.isEmail(getText().toString()) && length() >= minLength && length() <= maxLength;
case TYPE_PHONE_EMAIL:
return (StringUtil.isPhone(getText().toString()) || StringUtil.isEmail(getText().toString())) && length() >= minLength && length() <= maxLength;
}
return false;
}
private void onRightful() {
if (onInputListener != null) {
onInputListener.onRightful();
}
}
private void onUnlawful() {
if (onInputListener != null) {
onInputListener.onUnlawful();
}
}
/**
* 設置輸入框的背景,可以自定義,否則使用默認的背景
*
* @param drawable
*/
public void setRightful(Drawable drawable) {
// LogUtil.d(TAG,"setRightful()");
// if (drawable != null)
rightfulBackgroundDrawable = drawable;
setBackgroundDrawable(rightfulBackgroundDrawable);
setDrawable();
}
public void setUnlawful() {
setBackgroundDrawable(unlawfulBackgroundDrawable);
setDrawable();
}
public void hideDeleteDrawable() {
rightDrawable = null;
setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null,
rightDrawable, null);
}
public void showDeleteDrawable() {
rightDrawable = WechatApplication.getWechatApplication().getResources().getDrawable(
R.drawable.login_delete);
setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null,
rightDrawable, null);
}
public void setRightfulBackgroundDrawable(Drawable rightfulBackgroundDrawable) {
this.rightfulBackgroundDrawable = rightfulBackgroundDrawable;
setDrawable();
}
public void setDrawable() {
// LogUtil.d(TAG,"setDrawable()- length():" + length() + " isFocused:" + isFocused());
if (length() == 0 || !isFocused()) {
super.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null, null, null);
} else {
super.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null, rightDrawable, null);
}
setPadding(paddingLeft, 0, paddingRight, 0);
}
public void setPaddingLeft(int paddingLeft) {
this.paddingLeft = paddingLeft;
setDrawable();
}
public void setPaddingRight(int paddingRight) {
this.paddingRight = paddingRight;
setDrawable();
}
public void setMinLength(int minLength) {
this.minLength = minLength;
}
public void setMaxLength(int maxLength) {
this.maxLength = maxLength;
setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
}
public void setIntactText(String intactText) {
isIntact = true;
removeTextChangedListener(this);//因为监听是异步的线程,所以把监听去掉
setText(intactText);
try {
setSelection(length());
} catch (Exception e) {
e.printStackTrace();
}
setDrawable();
addTextChangedListener(this);//设置好文字后,再加上监听
}
@Override
public boolean onTextContextMenuItem(int id) {
if (id == android.R.id.paste) {//粘貼的時候
if (type == TYPE_PHONE || type == TYPE_PHONE_EMAIL) {
ClipboardManager clip = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
String text = clip.getText().toString().trim();
if (!TextUtils.isEmpty(text)) {
if (!text.contains("@")) {
if (text.startsWith("+86 ")) {
text = text.substring(4);
}
if (text.startsWith("+86")) {
text = text.substring(3);
}
if (text.contains("-")) {
text = text.replace("-", "");
}
text = text.replaceAll(" ", "");// // 当联系人的号码是在通讯录中粘贴过来时会出现空格,正则会匹配不上
setText(text);
try {
setSelection(length());
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
}
}
return super.onTextContextMenuItem(id);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (isFocused() && rightDrawable != null && event.getX() > (getWidth() - getPaddingRight() - rightDrawable.getIntrinsicWidth())
&& (event.getX() < ((getWidth() - getPaddingRight())))) {
if (pwdEyeEnable) {
if (getTransformationMethod() instanceof PasswordTransformationMethod) {
setTransformationMethod(null);
rightDrawable = getResources().getDrawable(R.drawable.login_invisible);
} else {
setTransformationMethod(PasswordTransformationMethod.getInstance());
rightDrawable = getResources().getDrawable(R.drawable.login_visible);
}
} else {
this.setText("");
if (onInputListener != null) {
onInputListener.onClearText();
}
}
setDrawable();
}
}
return super.onTouchEvent(event);
}
public void setOnInputListener(OnInputListener l) {
onInputListener = l;
}
public void setType(int type) {
this.type = type;
switch (type) {
case TYPE_PHONE:
setInputType(InputType.TYPE_CLASS_PHONE);
break;
case TYPE_EMAIL:
// setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
break;
case TYPE_PHONE_EMAIL:
case TYPE_NORMAL:
setInputType(InputType.TYPE_CLASS_TEXT);
break;
}
}
@Override
protected void onCreateContextMenu(ContextMenu menu) {
super.onCreateContextMenu(menu);
}
@Override
public boolean onMenuItemClick(MenuItem item) {
return onTextContextMenuItem(item.getItemId());
}
public interface OnInputListener {
void onRightful();
void onUnlawful();
void onClearText();
}
}
| 14,258 | 0.578003 | 0.575122 | 411 | 32.781021 | 27.989843 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.549878 | false | false | 2 |
afa0aff7e22cd07849c83e8a2190ef308c67ac14 | 4,655,744,576,528 | e48c7a75e504e330a076730dc1580196c9d15480 | /src/patterns/Diamond.java | ea5fe65820fe0c6b9a568c4ada2e5356d6b6fb89 | [] | no_license | pvenkatesh216/General | https://github.com/pvenkatesh216/General | 4163ae693f2cd6738f8069493453e9d863f7f3f6 | e6194fae244d1a286817e35f560319f94014ac5a | refs/heads/master | 2021-09-08T10:55:26.614000 | 2018-03-09T10:41:16 | 2018-03-09T10:41:16 | 124,526,151 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package patterns;
import java.util.Scanner;
public class Diamond {
public static void main(String[] args) {
int n=5;
int space=4;
int c;
int k;
for (k=1;k<=n;k++)
{
System.out.println("");
for (c=1;c<=space;c++)
{
System.out.print(" ");
space--;
}
for (c=1;c<=2*k-1;c++)
{
System.out.print("*");
}
}
}
}
| UTF-8 | Java | 394 | java | Diamond.java | Java | [] | null | [] | package patterns;
import java.util.Scanner;
public class Diamond {
public static void main(String[] args) {
int n=5;
int space=4;
int c;
int k;
for (k=1;k<=n;k++)
{
System.out.println("");
for (c=1;c<=space;c++)
{
System.out.print(" ");
space--;
}
for (c=1;c<=2*k-1;c++)
{
System.out.print("*");
}
}
}
}
| 394 | 0.469543 | 0.451777 | 30 | 11.133333 | 11.107755 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.3 | false | false | 2 |
45511f476e509b320626a5c2b80ee4d00ec780a5 | 5,841,155,530,268 | 4c6e269229c05c3d5e7dc761779f84b7bdb2fbfd | /demo-aop/src/main/java/aspects/SampleAspect.java | 273a617a316f6b754240fd18038c749be1cc3de7 | [] | no_license | Smitty0078/RevatureLabs | https://github.com/Smitty0078/RevatureLabs | 0286db0e4edb8c3739aa64b253978119fd46f6d0 | d7c608dfd7eb4c8dbd81f2b5e72164d7fe1b53a8 | refs/heads/main | 2023-08-04T07:50:40.089000 | 2021-10-04T20:58:18 | 2021-10-04T20:58:18 | 382,160,891 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package aspects;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class SampleAspect {
@Before(value="execution (* service.EmployeeService.*(..))")
public void beforeAdvice(JoinPoint joinPoint) {
System.out.println("calling before aspect "+joinPoint.getSignature().toString());
}
@After(value="execution(* service.EmployeeService.*(..))")
public void afterAdvice(JoinPoint joinPoint) {
System.out.println("calling after aspect "+joinPoint.getSignature().toString());
}
}
| UTF-8 | Java | 677 | java | SampleAspect.java | Java | [] | null | [] | package aspects;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class SampleAspect {
@Before(value="execution (* service.EmployeeService.*(..))")
public void beforeAdvice(JoinPoint joinPoint) {
System.out.println("calling before aspect "+joinPoint.getSignature().toString());
}
@After(value="execution(* service.EmployeeService.*(..))")
public void afterAdvice(JoinPoint joinPoint) {
System.out.println("calling after aspect "+joinPoint.getSignature().toString());
}
}
| 677 | 0.768095 | 0.768095 | 23 | 28.434782 | 26.82119 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.869565 | false | false | 2 |
601099d42efb7bd1873cc2c7527b76a6845c3b85 | 31,576,599,593,810 | 189c02db22e8966e7476226381f5b971fb83703c | /src/com/hcl/atf/taf/model/DefectExportData.java | f3fef58beec6dc54b9080de7e0a6bb1d61cd4569 | [] | no_license | Bokam501/TAF | https://github.com/Bokam501/TAF | 9f28d077cec70e4291daeb6b819a162de21f9e2b | 10f85ecadaba049c77299be3433e88a6595a9788 | refs/heads/master | 2020-06-15T20:01:20.882000 | 2019-07-11T06:53:21 | 2019-07-11T06:53:21 | 195,347,963 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hcl.atf.taf.model;
import static javax.persistence.GenerationType.IDENTITY;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* DefectExportData - Details of defect, Defect System Id, TAF Bug Id , Defect System Bug id are maintained.
*/
@Entity
@Table(name = "defect_export_data")
public class DefectExportData implements java.io.Serializable {
private Integer defectExportDataId;
private Integer defectManagementSystemId;
private Integer testExecutionResultsBugId;
private String defectSystemCode;
private Date defectExportDate;
public DefectExportData(){
}
public DefectExportData(Integer defectExportDataId, Integer defectManagementSystemId, Integer testExecutionResultsBugId,String defectSystemCode,Date defectExportDate){
this.defectExportDataId = defectExportDataId;
this.defectManagementSystemId = defectManagementSystemId;
this.testExecutionResultsBugId = testExecutionResultsBugId;
this.defectSystemCode = defectSystemCode;
this.defectExportDate = defectExportDate;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "defectExportDataId", unique = true, nullable = false)
public Integer getDefectExportDataId() {
return defectExportDataId;
}
public void setDefectExportDataId(Integer defectExportDataId) {
this.defectExportDataId = defectExportDataId;
}
@Column(name = "defectManagementSystemId")
public Integer getDefectManagementSystemId() {
return defectManagementSystemId;
}
public void setDefectManagementSystemId(Integer defectManagementSystemId) {
this.defectManagementSystemId = defectManagementSystemId;
}
@Column(name = "testExecutionResultsBugId")
public Integer getTestExecutionResultsBugId() {
return testExecutionResultsBugId;
}
public void setTestExecutionResultsBugId(Integer testExecutionResultsBugId) {
this.testExecutionResultsBugId = testExecutionResultsBugId;
}
@Column(name = "defectSystemCode")
public String getDefectSystemCode() {
return defectSystemCode;
}
public void setDefectSystemCode(String defectSystemCode) {
this.defectSystemCode = defectSystemCode;
}
@Column(name = "defectExportDate")
public Date getDefectExportDate() {
return defectExportDate;
}
public void setDefectExportDate(Date defectExportDate) {
this.defectExportDate = defectExportDate;
}
}
| UTF-8 | Java | 2,543 | java | DefectExportData.java | Java | [] | null | [] | package com.hcl.atf.taf.model;
import static javax.persistence.GenerationType.IDENTITY;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* DefectExportData - Details of defect, Defect System Id, TAF Bug Id , Defect System Bug id are maintained.
*/
@Entity
@Table(name = "defect_export_data")
public class DefectExportData implements java.io.Serializable {
private Integer defectExportDataId;
private Integer defectManagementSystemId;
private Integer testExecutionResultsBugId;
private String defectSystemCode;
private Date defectExportDate;
public DefectExportData(){
}
public DefectExportData(Integer defectExportDataId, Integer defectManagementSystemId, Integer testExecutionResultsBugId,String defectSystemCode,Date defectExportDate){
this.defectExportDataId = defectExportDataId;
this.defectManagementSystemId = defectManagementSystemId;
this.testExecutionResultsBugId = testExecutionResultsBugId;
this.defectSystemCode = defectSystemCode;
this.defectExportDate = defectExportDate;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "defectExportDataId", unique = true, nullable = false)
public Integer getDefectExportDataId() {
return defectExportDataId;
}
public void setDefectExportDataId(Integer defectExportDataId) {
this.defectExportDataId = defectExportDataId;
}
@Column(name = "defectManagementSystemId")
public Integer getDefectManagementSystemId() {
return defectManagementSystemId;
}
public void setDefectManagementSystemId(Integer defectManagementSystemId) {
this.defectManagementSystemId = defectManagementSystemId;
}
@Column(name = "testExecutionResultsBugId")
public Integer getTestExecutionResultsBugId() {
return testExecutionResultsBugId;
}
public void setTestExecutionResultsBugId(Integer testExecutionResultsBugId) {
this.testExecutionResultsBugId = testExecutionResultsBugId;
}
@Column(name = "defectSystemCode")
public String getDefectSystemCode() {
return defectSystemCode;
}
public void setDefectSystemCode(String defectSystemCode) {
this.defectSystemCode = defectSystemCode;
}
@Column(name = "defectExportDate")
public Date getDefectExportDate() {
return defectExportDate;
}
public void setDefectExportDate(Date defectExportDate) {
this.defectExportDate = defectExportDate;
}
}
| 2,543 | 0.779001 | 0.779001 | 88 | 26.897728 | 29.043478 | 168 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.215909 | false | false | 2 |
c503d41e3bd7aea084103f288a0b28571d71c91f | 23,665,269,804,609 | 7494e577fdcd7f9ad8ee4a236c2745b0ec5e9e70 | /LES.java | 2d6703e6f7db9a6e93861e6149c8e8fd8fa7df2f | [] | no_license | OscarAlex/Data-structures-in-Java | https://github.com/OscarAlex/Data-structures-in-Java | bf9a540c9fdbb9787e99b16de91d6bd0ca17e100 | 236f099e92eadc1abfefb9dbc19ce54acb1a1b5a | refs/heads/master | 2021-10-11T12:09:59.661000 | 2019-01-25T15:15:54 | 2019-01-25T15:15:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Lista Enlazada Simple
*/
public class LES
{
private Nodo raiz;
private Nodo fin;
private Nodo temp;
private int tam;
public Nodo getRaiz()
{
return raiz;
}
public void setRaiz(Nodo raiz)
{
this.raiz= raiz;
}
public Nodo getFin()
{
return fin;
}
public void setFin(Nodo fin)
{
this.fin= fin;
}
public int getTam()
{
return tam;
}
public LES()
{
raiz= null;
fin= null;
tam= 0;
}
public LES(Nodo nvo)
{
if(raiz==null)
{
fin=raiz=nvo;
tam++;
}
}
public LES(LES x)
{
if(raiz == null)
{
raiz= x.getRaiz();
fin= x.getFin();
tam= x.getTam();
}
}
//Enlaza primero los nuevos y luego mueve los necesarios
//NUNCA mover la raíz
public void insertarPrincipio(Nodo nvo)
{
if(raiz==null)
{
fin=raiz=nvo;
tam++;
}
else
{
nvo.setPtr(raiz);
raiz=nvo;
tam++;
}
}
public void insertarFinal(Nodo nvo)
{
if(raiz==null)
{
raiz=nvo=fin;
tam++;
}
else
{
fin.setPtr(nvo);
fin=nvo;
tam++;
}
}
public void insertarPos(Nodo nvo, int y)
{
if(y<=tam)
{
if(raiz==null)
{
temp=raiz=nvo=fin;
tam++;
}
else if(y==0)
{
insertarPrincipio(nvo);
}
else if(y==tam)
{
insertarFinal(nvo);
}
else
{
temp=raiz;
for(int i=1; i<y; i++)
{
temp=temp.getPtr();
}
nvo.setPtr(temp.getPtr());
temp.setPtr(nvo);
tam++;
}
}
else
{
System.out.println("No se puede no. "+y);
}
}
public Nodo eliminarPrincipio()
{
if(raiz!=null)
{
temp=raiz;
raiz=temp.getPtr();
temp.setPtr(null);
tam--;
}
return temp;
}
public Nodo eliminarFinal()
{
if(raiz!=null)
{
temp=raiz;
while(temp.getPtr()!=fin)
{
temp=temp.getPtr();
}
fin=temp;
temp=temp.getPtr();
fin.setPtr(null);
tam--;
}
return temp;
}
public Nodo eliminarPos(int y)
{
if(y==0)
{
eliminarPrincipio();
}
else if(raiz!=null && y<tam)
{
temp=raiz;
Nodo ant=raiz;
for(int i=1;i<y;i++)
{
ant=ant.getPtr();
}
temp=ant.getPtr();
ant.setPtr(temp.getPtr());
temp.setPtr(null);
tam--;
}
else
{
System.out.println("No se puede borrar lo que no existe");
}
return temp;
}
public void imprimir()
{
if(raiz!=null)
{
Nodo tmp= raiz;
while(tmp!=null)
{
System.out.println(tmp.getInfo());
tmp=tmp.getPtr();
}
}
}
}
| UTF-8 | Java | 3,559 | java | LES.java | Java | [] | null | [] |
/**
* Lista Enlazada Simple
*/
public class LES
{
private Nodo raiz;
private Nodo fin;
private Nodo temp;
private int tam;
public Nodo getRaiz()
{
return raiz;
}
public void setRaiz(Nodo raiz)
{
this.raiz= raiz;
}
public Nodo getFin()
{
return fin;
}
public void setFin(Nodo fin)
{
this.fin= fin;
}
public int getTam()
{
return tam;
}
public LES()
{
raiz= null;
fin= null;
tam= 0;
}
public LES(Nodo nvo)
{
if(raiz==null)
{
fin=raiz=nvo;
tam++;
}
}
public LES(LES x)
{
if(raiz == null)
{
raiz= x.getRaiz();
fin= x.getFin();
tam= x.getTam();
}
}
//Enlaza primero los nuevos y luego mueve los necesarios
//NUNCA mover la raíz
public void insertarPrincipio(Nodo nvo)
{
if(raiz==null)
{
fin=raiz=nvo;
tam++;
}
else
{
nvo.setPtr(raiz);
raiz=nvo;
tam++;
}
}
public void insertarFinal(Nodo nvo)
{
if(raiz==null)
{
raiz=nvo=fin;
tam++;
}
else
{
fin.setPtr(nvo);
fin=nvo;
tam++;
}
}
public void insertarPos(Nodo nvo, int y)
{
if(y<=tam)
{
if(raiz==null)
{
temp=raiz=nvo=fin;
tam++;
}
else if(y==0)
{
insertarPrincipio(nvo);
}
else if(y==tam)
{
insertarFinal(nvo);
}
else
{
temp=raiz;
for(int i=1; i<y; i++)
{
temp=temp.getPtr();
}
nvo.setPtr(temp.getPtr());
temp.setPtr(nvo);
tam++;
}
}
else
{
System.out.println("No se puede no. "+y);
}
}
public Nodo eliminarPrincipio()
{
if(raiz!=null)
{
temp=raiz;
raiz=temp.getPtr();
temp.setPtr(null);
tam--;
}
return temp;
}
public Nodo eliminarFinal()
{
if(raiz!=null)
{
temp=raiz;
while(temp.getPtr()!=fin)
{
temp=temp.getPtr();
}
fin=temp;
temp=temp.getPtr();
fin.setPtr(null);
tam--;
}
return temp;
}
public Nodo eliminarPos(int y)
{
if(y==0)
{
eliminarPrincipio();
}
else if(raiz!=null && y<tam)
{
temp=raiz;
Nodo ant=raiz;
for(int i=1;i<y;i++)
{
ant=ant.getPtr();
}
temp=ant.getPtr();
ant.setPtr(temp.getPtr());
temp.setPtr(null);
tam--;
}
else
{
System.out.println("No se puede borrar lo que no existe");
}
return temp;
}
public void imprimir()
{
if(raiz!=null)
{
Nodo tmp= raiz;
while(tmp!=null)
{
System.out.println(tmp.getInfo());
tmp=tmp.getPtr();
}
}
}
}
| 3,559 | 0.369028 | 0.367622 | 183 | 18.437159 | 12.027525 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.36612 | false | false | 2 |
0b5a50c59a4181a9fd127f104ba8bc2982eb36ad | 22,333,829,981,760 | 9a23b2a26ae80aadf57273baca6460631f5d3723 | /BchainEnabledOLYMPUS/core/src/test/java/eu/olympus/unit/util/TestKeySerializer.java | 53580527cfb49c5fa730f9b25fcc7367793b50dc | [
"Apache-2.0"
] | permissive | rafaeltm/OLChainEnabled | https://github.com/rafaeltm/OLChainEnabled | 67a674b24cd0a861a092fa78d56b578ea5b5fad4 | 85c9d571e116bb751532107fa22b8614cb5dac8a | refs/heads/main | 2023-08-04T06:45:24.571000 | 2021-09-16T12:55:03 | 2021-09-16T12:55:03 | 384,412,627 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package eu.olympus.unit.util;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import eu.olympus.util.multisign.MS;
import eu.olympus.util.multisign.MSauxArg;
import eu.olympus.util.multisign.MSverfKey;
import eu.olympus.util.psmultisign.PSauxArg;
import eu.olympus.util.psmultisign.PSms;
import org.apache.commons.codec.binary.Base64;
import org.junit.Test;
import eu.olympus.TestParameters;
import eu.olympus.model.SerializedKey;
import eu.olympus.model.exceptions.MSSetupException;
import eu.olympus.util.KeySerializer;
public class TestKeySerializer{
private static final String PAIRING_NAME="eu.olympus.util.pairingBLS461.PairingBuilderBLS461";
private final byte[] seed = "random value random value random value random value random".getBytes();
private Set<String> attrNames=new HashSet<>(Arrays.asList("name","age"));
@Test
public void testKeySerializerEC() throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
ECPublicKey publicKey = TestParameters.getECPublicKey1();
SerializedKey key = KeySerializer.serialize(publicKey);
ECPublicKey result = (ECPublicKey) KeySerializer.deSerialize(key);
assertThat(result, is(publicKey));
key = KeySerializer.serialize(TestParameters.getECPrivateKey1());
assertEquals(TestParameters.getECPrivateKey1(), KeySerializer.deSerialize(key));
}
@Test
public void testKeySerializerRSA() throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
RSAPublicKey publicKey = TestParameters.getRSAPublicKey1();
SerializedKey key = KeySerializer.serialize(publicKey);
RSAPublicKey result = (RSAPublicKey) KeySerializer.deSerialize(key);
assertThat(result, is(publicKey));
key = KeySerializer.serialize(TestParameters.getRSAPrivateKey1());
assertEquals(TestParameters.getRSAPrivateKey1(), KeySerializer.deSerialize(key));
}
@Test
public void testKeySerializerPSverfKey() throws NoSuchAlgorithmException, InvalidKeyException, MSSetupException, InvalidKeySpecException {
MS psScheme=new PSms();
int nServers=3;
//Generate auxArg and setup
MSauxArg auxArg=new PSauxArg(PAIRING_NAME,attrNames);
psScheme.setup(nServers,auxArg, seed);
MSverfKey publicKey=psScheme.kg().getSecond();
SerializedKey key = KeySerializer.serialize(publicKey);
MSverfKey result = (MSverfKey) KeySerializer.deSerialize(key);
assertThat(result, is(publicKey));
}
@Test (expected = InvalidKeyException.class)
public void testBadPSverfKey() throws NoSuchAlgorithmException, InvalidKeyException, MSSetupException, InvalidKeySpecException {
MS psScheme=new PSms();
int nServers=3;
//Generate auxArg and setup
MSauxArg auxArg=new PSauxArg(PAIRING_NAME,attrNames);
psScheme.setup(nServers,auxArg, seed);
MSverfKey publicKey=psScheme.kg().getSecond();
SerializedKey key = KeySerializer.serialize(publicKey);
key.setEncoded(Base64.encodeBase64String("This is not an encoded key!!".getBytes()));
KeySerializer.deSerialize(key);
fail();
}
@Test(expected = Exception.class)
public void testKeySerializerUnknown() throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
ECPublicKey publicKey = TestParameters.getECPublicKey1();
SerializedKey key = KeySerializer.serialize(publicKey);
key.setAlgorithm("SHA");
KeySerializer.deSerialize(key);
fail();
}
}
| UTF-8 | Java | 3,754 | java | TestKeySerializer.java | Java | [] | null | [] | package eu.olympus.unit.util;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import eu.olympus.util.multisign.MS;
import eu.olympus.util.multisign.MSauxArg;
import eu.olympus.util.multisign.MSverfKey;
import eu.olympus.util.psmultisign.PSauxArg;
import eu.olympus.util.psmultisign.PSms;
import org.apache.commons.codec.binary.Base64;
import org.junit.Test;
import eu.olympus.TestParameters;
import eu.olympus.model.SerializedKey;
import eu.olympus.model.exceptions.MSSetupException;
import eu.olympus.util.KeySerializer;
public class TestKeySerializer{
private static final String PAIRING_NAME="eu.olympus.util.pairingBLS461.PairingBuilderBLS461";
private final byte[] seed = "random value random value random value random value random".getBytes();
private Set<String> attrNames=new HashSet<>(Arrays.asList("name","age"));
@Test
public void testKeySerializerEC() throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
ECPublicKey publicKey = TestParameters.getECPublicKey1();
SerializedKey key = KeySerializer.serialize(publicKey);
ECPublicKey result = (ECPublicKey) KeySerializer.deSerialize(key);
assertThat(result, is(publicKey));
key = KeySerializer.serialize(TestParameters.getECPrivateKey1());
assertEquals(TestParameters.getECPrivateKey1(), KeySerializer.deSerialize(key));
}
@Test
public void testKeySerializerRSA() throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
RSAPublicKey publicKey = TestParameters.getRSAPublicKey1();
SerializedKey key = KeySerializer.serialize(publicKey);
RSAPublicKey result = (RSAPublicKey) KeySerializer.deSerialize(key);
assertThat(result, is(publicKey));
key = KeySerializer.serialize(TestParameters.getRSAPrivateKey1());
assertEquals(TestParameters.getRSAPrivateKey1(), KeySerializer.deSerialize(key));
}
@Test
public void testKeySerializerPSverfKey() throws NoSuchAlgorithmException, InvalidKeyException, MSSetupException, InvalidKeySpecException {
MS psScheme=new PSms();
int nServers=3;
//Generate auxArg and setup
MSauxArg auxArg=new PSauxArg(PAIRING_NAME,attrNames);
psScheme.setup(nServers,auxArg, seed);
MSverfKey publicKey=psScheme.kg().getSecond();
SerializedKey key = KeySerializer.serialize(publicKey);
MSverfKey result = (MSverfKey) KeySerializer.deSerialize(key);
assertThat(result, is(publicKey));
}
@Test (expected = InvalidKeyException.class)
public void testBadPSverfKey() throws NoSuchAlgorithmException, InvalidKeyException, MSSetupException, InvalidKeySpecException {
MS psScheme=new PSms();
int nServers=3;
//Generate auxArg and setup
MSauxArg auxArg=new PSauxArg(PAIRING_NAME,attrNames);
psScheme.setup(nServers,auxArg, seed);
MSverfKey publicKey=psScheme.kg().getSecond();
SerializedKey key = KeySerializer.serialize(publicKey);
key.setEncoded(Base64.encodeBase64String("This is not an encoded key!!".getBytes()));
KeySerializer.deSerialize(key);
fail();
}
@Test(expected = Exception.class)
public void testKeySerializerUnknown() throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
ECPublicKey publicKey = TestParameters.getECPublicKey1();
SerializedKey key = KeySerializer.serialize(publicKey);
key.setAlgorithm("SHA");
KeySerializer.deSerialize(key);
fail();
}
}
| 3,754 | 0.800746 | 0.795152 | 104 | 35.096153 | 32.410088 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.759615 | false | false | 2 |
959c5c1fd50a9644755055b0794dfc8c6c2d4909 | 22,978,075,060,539 | 8cd9fe171f521ecaca041c03c01403977100a9dd | /workspace/Client/src/gui/TwoEntriesPanel.java | 1301d0a7ebffde0769d165110eda09e1ab13e2b0 | [] | no_license | edri/GENial | https://github.com/edri/GENial | e70e8d1eac1d9471dc2d56225692937a995529a1 | f2aa56e5208f61a629423597ca22869389a71700 | refs/heads/master | 2021-01-25T05:15:13.099000 | 2015-06-17T11:49:37 | 2015-06-17T11:49:37 | 34,391,605 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.UnknownHostException;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import application.App;
public class TwoEntriesPanel extends EntriesPanel {
private AppFrame mainFrame;
private JPanel fieldsPanel;
private JPanel mainPanel;
private JPanel firstPanel;
private JLabel firstFieldDesc;
private JTextField firstTextField;
private JPanel secondPanel;
private JLabel secondFieldDesc;
private JTextField secondTextField;
private JPanel buttonPanel;
private JButton confirmButton;
private JButton backButton;
private App app;
public TwoEntriesPanel(App app, String field1, String field2, boolean addButton, AppFrame mainFrame){
this.app = app;
fieldsPanel = new JPanel();
fieldsPanel.setLayout(new BoxLayout(fieldsPanel, BoxLayout.PAGE_AXIS));
firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(1,2));
firstFieldDesc = new JLabel(field1, SwingConstants.RIGHT);
firstTextField = new JTextField(15);
firstPanel.add(firstFieldDesc, Component.RIGHT_ALIGNMENT);
firstPanel.add(firstTextField, Component.LEFT_ALIGNMENT);
secondPanel = new JPanel();
secondPanel.setLayout(new GridLayout(1,4));
secondFieldDesc = new JLabel(field2, SwingConstants.RIGHT);
if (app.getStatus().equals("auth")){
secondTextField = new JPasswordField(8);
} else {
secondTextField = new JTextField(8);
}
secondPanel.add(secondFieldDesc);
secondPanel.add(secondTextField);
fieldsPanel.add(firstPanel);
fieldsPanel.add(secondPanel);
buttonPanel = new JPanel();
if (addButton){
backButton = new JButton("Retour");
backButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
app.prepareChoice();
}
});
buttonPanel.add(backButton);
}
confirmButton = new JButton("Continuer");
confirmButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String status = app.getStatus();
switch(status){
case "connection":
try {
app.connectToServer(firstTextField.getText(), Integer.parseInt(secondTextField.getText()));
} catch (NumberFormatException e1) {
mainFrame.display("Format du port incorrect (doit etre un entier positif).", Color.RED);
//e1.printStackTrace();
} catch (UnknownHostException e1) {
mainFrame.display("Adresse inconnue.", Color.RED);
//e1.printStackTrace();
} catch (IOException e1) {
mainFrame.display("Une erreur est survenue, vous avez ete deconnecte.", Color.RED);
//e1.printStackTrace();
}
break;
case "auth":
System.out.println("AUTH : nom = " + firstTextField.getText() + ", mdp = " + secondTextField.getText());
if (firstTextField.getText().equals("") || firstTextField.getText() == null){
mainFrame.display("Le nom d'utilisateur n'a pas été renseigné", Color.RED);
} else if(secondTextField.getText().equals("") || secondTextField.getText() == null){
mainFrame.display("Le mot de passe n'a pas été renseigné", Color.RED);
} else {
app.auth(firstTextField.getText(), secondTextField.getText());
}
break;
case "register":
if (firstTextField.getText().equals("") || firstTextField.getText() == null){
mainFrame.display("Le nom d'utilisateur n'a pas été renseigné", Color.RED);
} else if(secondTextField.getText().equals("") || secondTextField.getText() == null){
mainFrame.display("Le mot de passe n'a pas été renseigné", Color.RED);
} else {
app.register(firstTextField.getText(), secondTextField.getText());
}
break;
default:
mainFrame.display("Erreur status inconnu...", Color.RED);
}
}
});
buttonPanel.add(confirmButton);
mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.add(fieldsPanel);
mainPanel.add(buttonPanel);
this.add(mainPanel);
}
public void updateField(String field1, String field2){
firstFieldDesc.setText(field1);
secondFieldDesc.setText(field2);
}
public String getFieldContent(int fieldNb){
if (fieldNb == 1){
return firstFieldDesc.getText();
} else if (fieldNb == 2){
return secondFieldDesc.getText();
} else {
return null;
}
}
}
| ISO-8859-2 | Java | 4,655 | java | TwoEntriesPanel.java | Java | [] | null | [] | package gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.UnknownHostException;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import application.App;
public class TwoEntriesPanel extends EntriesPanel {
private AppFrame mainFrame;
private JPanel fieldsPanel;
private JPanel mainPanel;
private JPanel firstPanel;
private JLabel firstFieldDesc;
private JTextField firstTextField;
private JPanel secondPanel;
private JLabel secondFieldDesc;
private JTextField secondTextField;
private JPanel buttonPanel;
private JButton confirmButton;
private JButton backButton;
private App app;
public TwoEntriesPanel(App app, String field1, String field2, boolean addButton, AppFrame mainFrame){
this.app = app;
fieldsPanel = new JPanel();
fieldsPanel.setLayout(new BoxLayout(fieldsPanel, BoxLayout.PAGE_AXIS));
firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(1,2));
firstFieldDesc = new JLabel(field1, SwingConstants.RIGHT);
firstTextField = new JTextField(15);
firstPanel.add(firstFieldDesc, Component.RIGHT_ALIGNMENT);
firstPanel.add(firstTextField, Component.LEFT_ALIGNMENT);
secondPanel = new JPanel();
secondPanel.setLayout(new GridLayout(1,4));
secondFieldDesc = new JLabel(field2, SwingConstants.RIGHT);
if (app.getStatus().equals("auth")){
secondTextField = new JPasswordField(8);
} else {
secondTextField = new JTextField(8);
}
secondPanel.add(secondFieldDesc);
secondPanel.add(secondTextField);
fieldsPanel.add(firstPanel);
fieldsPanel.add(secondPanel);
buttonPanel = new JPanel();
if (addButton){
backButton = new JButton("Retour");
backButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
app.prepareChoice();
}
});
buttonPanel.add(backButton);
}
confirmButton = new JButton("Continuer");
confirmButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String status = app.getStatus();
switch(status){
case "connection":
try {
app.connectToServer(firstTextField.getText(), Integer.parseInt(secondTextField.getText()));
} catch (NumberFormatException e1) {
mainFrame.display("Format du port incorrect (doit etre un entier positif).", Color.RED);
//e1.printStackTrace();
} catch (UnknownHostException e1) {
mainFrame.display("Adresse inconnue.", Color.RED);
//e1.printStackTrace();
} catch (IOException e1) {
mainFrame.display("Une erreur est survenue, vous avez ete deconnecte.", Color.RED);
//e1.printStackTrace();
}
break;
case "auth":
System.out.println("AUTH : nom = " + firstTextField.getText() + ", mdp = " + secondTextField.getText());
if (firstTextField.getText().equals("") || firstTextField.getText() == null){
mainFrame.display("Le nom d'utilisateur n'a pas été renseigné", Color.RED);
} else if(secondTextField.getText().equals("") || secondTextField.getText() == null){
mainFrame.display("Le mot de passe n'a pas été renseigné", Color.RED);
} else {
app.auth(firstTextField.getText(), secondTextField.getText());
}
break;
case "register":
if (firstTextField.getText().equals("") || firstTextField.getText() == null){
mainFrame.display("Le nom d'utilisateur n'a pas été renseigné", Color.RED);
} else if(secondTextField.getText().equals("") || secondTextField.getText() == null){
mainFrame.display("Le mot de passe n'a pas été renseigné", Color.RED);
} else {
app.register(firstTextField.getText(), secondTextField.getText());
}
break;
default:
mainFrame.display("Erreur status inconnu...", Color.RED);
}
}
});
buttonPanel.add(confirmButton);
mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.add(fieldsPanel);
mainPanel.add(buttonPanel);
this.add(mainPanel);
}
public void updateField(String field1, String field2){
firstFieldDesc.setText(field1);
secondFieldDesc.setText(field2);
}
public String getFieldContent(int fieldNb){
if (fieldNb == 1){
return firstFieldDesc.getText();
} else if (fieldNb == 2){
return secondFieldDesc.getText();
} else {
return null;
}
}
}
| 4,655 | 0.715701 | 0.710532 | 150 | 29.953333 | 25.396414 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.08 | false | false | 2 |
f0d0a50208b8d23e785b5b7f7dc6d56a9f3243d5 | 32,942,399,218,255 | 82cc4d87029e673da1edd33dd5aa0f68105d3b36 | /src/main/java/com/programmingjavaweb/mapper/BuildingMapper.java | 55704d4f6773b19447824c4f0b7676bcba1feb65 | [] | no_license | nguyenhien0209/estate-platform-jdbc-servlet | https://github.com/nguyenhien0209/estate-platform-jdbc-servlet | 7128999b40cd6f13d8a7d713e77b1e7ca8413d47 | 6188f3c9481a49cd010f24137f8a26b0efd4a1ba | refs/heads/master | 2022-11-25T12:02:37.296000 | 2019-11-06T06:45:23 | 2019-11-06T06:45:23 | 213,524,800 | 0 | 0 | null | false | 2022-11-16T05:31:01 | 2019-10-08T01:49:18 | 2019-11-06T06:46:02 | 2022-11-16T05:30:58 | 2,814 | 0 | 0 | 2 | JavaScript | false | false | package com.programmingjavaweb.mapper;
import com.programmingjavaweb.model.BuildingModel;
import com.programmingjavaweb.utils.ConverterUtil;
import java.sql.ResultSet;
public class BuildingMapper implements RowMapper<BuildingModel> {
@Override
public BuildingModel mapRow(ResultSet resultSet) {
BuildingModel buildingModel = new ConverterUtil().resultToModel(new BuildingModel(), resultSet);
buildingModel.setTypeArrays(buildingModel.getType().split(","));
return buildingModel;
}
}
| UTF-8 | Java | 522 | java | BuildingMapper.java | Java | [] | null | [] | package com.programmingjavaweb.mapper;
import com.programmingjavaweb.model.BuildingModel;
import com.programmingjavaweb.utils.ConverterUtil;
import java.sql.ResultSet;
public class BuildingMapper implements RowMapper<BuildingModel> {
@Override
public BuildingModel mapRow(ResultSet resultSet) {
BuildingModel buildingModel = new ConverterUtil().resultToModel(new BuildingModel(), resultSet);
buildingModel.setTypeArrays(buildingModel.getType().split(","));
return buildingModel;
}
}
| 522 | 0.773946 | 0.773946 | 15 | 33.799999 | 30.725018 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 2 |
4e43862309c323648e5ee469ab51aaea3caac3dd | 17,617,955,890,070 | 7f75140bd90b46fc04d41f39fbf6c0e826d57dc8 | /app/src/main/java/com/example/textme/ProfileActivity.java | 99e321b23c13f2eee92986c70f5cdf95e1e00a74 | [] | no_license | gig50/textMeAndroid | https://github.com/gig50/textMeAndroid | 18d07da1d3abe6db54b4383d77ddb2e10740a0fd | 9af6239c2ca27489b0a1b89180127e24f0c8c38f | refs/heads/master | 2020-05-24T08:35:42.252000 | 2019-05-19T02:53:30 | 2019-05-19T02:53:30 | 187,187,019 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.textme;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.net.Uri;
import android.os.Bundle;
import com.bumptech.glide.Glide;
import com.example.textme.Adapters.StoryAdapter;
import com.example.textme.Dialogs.editStatusDialog;
import com.example.textme.Dialogs.setProfileImageDialog;
import com.example.textme.Models.Story;
import com.example.textme.Models.User;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.FileProvider;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class ProfileActivity extends AppCompatActivity {
// ------------- REQUESTS CODES ----------------
private static final int PICK_IMAGE_REQUEST = 1;
private static final int TAKE_PHOTO_REQUEST = 2;
private static final int PICK_STORY_PHOTO_REQUEST = 3;
private static final int TAKE_STORY_PHOTO_REQUEST = 4;
// ************* VARIABLES *****************
//Views
ImageView profileImage;
TextView tvProfileName;
ImageButton editStatus;
TextView status;
ImageButton ivLikes;
TextView tvLikes;
//Refs
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("users_profile_images");
//User
User user;
String userId;
boolean Like;
//Profile Img Uri
private Uri mImageUri;
//Progress Dialog
ProgressDialog dialog;
// Story Variables
RecyclerView rvStory;
List<Story> stories = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
userId = getIntent().getStringExtra("id"); // Getting User Id
findViews();
buildUI();
setRvStory();
// Checking If Client Profile or Contact Profile
if(!(userId.matches(FirebaseAuth.getInstance().getCurrentUser().getUid()))){
editStatus.setVisibility(View.GONE);
toggleLike();
} else {
editStatus.setVisibility(View.VISIBLE);
// ON Profile Image Clicked
profileImage.setOnClickListener((v -> {// Open Edit Profile Image Dialog
DialogFragment dialogFragment = new setProfileImageDialog();
dialogFragment.show(getSupportFragmentManager(), "set");
}));
ivLikes.setClickable(false);
// ON Edit Status Clicked
editStatus.setOnClickListener((v -> {// Open Edit Status Dialog
DialogFragment dialogFragment = new editStatusDialog();
Bundle bundle = new Bundle();
bundle.putParcelable("model", user);
dialogFragment.setArguments(bundle);
dialogFragment.show(getSupportFragmentManager(), "edit");
}));
}
}
// **********************************
// ------------ LIKES ---------------
// **********************************
// Posting Like on DB and Animating Drawables
private void toggleLike() {
ivLikes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!Like) {
FirebaseDatabase.getInstance().getReference().child("Likes").child(userId).child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(true).addOnSuccessListener((s -> {
transition(ivLikes);
Like = true;
}));
} else {
FirebaseDatabase.getInstance().getReference().child("Likes").child(userId).child(FirebaseAuth.getInstance().getCurrentUser().getUid()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
reverseTransition(ivLikes);
Like = false;
}
});
}
}
});
}
// Getting Likes Count Method
private void bringLikes(){
FirebaseDatabase.getInstance().getReference().child("Likes").child(userId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
tvLikes.setText(String.valueOf(dataSnapshot.getChildrenCount()));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
// ***************************************
// -------- BUILDING UI METHOD -----------
// ***************************************
private void buildUI() {
//Bringing Name
FirebaseDatabase.getInstance().getReference().child("Users").child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
user = dataSnapshot.getValue(User.class);
tvProfileName.setText(user.getDisplayName());
// Checking for User status
if (user.getUserStatus() != null) {
status.setText(user.getUserStatus());
}
storageReference.child(user.getId()).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
user.setUserImageUri(uri.toString());
Glide.with(getApplicationContext()).load(uri).centerCrop().placeholder(R.drawable.user_placeholder).into(profileImage);
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
// Setting The uploading Image Progress Bar
dialog = new ProgressDialog(ProfileActivity.this);
dialog.setMessage(getString(R.string.upload_img));
FirebaseDatabase.getInstance().getReference().child("Likes").child(userId).orderByChild(FirebaseAuth.getInstance().getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.getValue() != null) {
HashMap hashMap = (HashMap) dataSnapshot.getValue();
Like = (boolean) hashMap.get(FirebaseAuth.getInstance().getCurrentUser().getUid());
if(Like) {ivLikes.setImageResource(R.drawable.heart_filled);
tvLikes.setTextColor(getResources().getColor(android.R.color.holo_red_light));
} else {
tvLikes.setTextColor(getResources().getColor(android.R.color.black));
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
bringLikes();
}
// ***************************************
// ---------- Activitiy Result -----------
// ***************************************
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
dialog.show();
mImageUri = data.getData();
profileImage.setImageURI(mImageUri);
UploadProfileImage();
}
if (requestCode == TAKE_PHOTO_REQUEST && resultCode == RESULT_OK) {
dialog.show();
Glide.with(getApplicationContext()).load(mImageUri).placeholder(R.drawable.user_placeholder).centerCrop().into(profileImage);
UploadProfileImage();
buildUI();
}
if (requestCode == PICK_STORY_PHOTO_REQUEST && resultCode == RESULT_OK){
mImageUri = data.getData();
UploadStory();
}
if (requestCode == TAKE_STORY_PHOTO_REQUEST && resultCode == RESULT_OK){
UploadStory();
}
}
private void UploadStory(){
DatabaseReference collections = FirebaseDatabase.getInstance().getReference().child("Collections").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
String id = collections.push().getKey();
collections.child(id).setValue(new Story(user.getDisplayName(),user.getUserImageUri(),id)).addOnSuccessListener((s)->{
FirebaseStorage.getInstance().getReference().child("Collections").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(id).putFile(mImageUri);
}).addOnFailureListener((f)->{
Snackbar.make(tvProfileName,f.getLocalizedMessage(),Snackbar.LENGTH_LONG);
});
}
// Uploading Image from setProfileDialog to FirebaseStorage
private void UploadProfileImage() {
if (mImageUri != null) {
storageReference.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(ProfileActivity.this, getString(R.string.photo_successfully_changed), Toast.LENGTH_SHORT).show();
buildUI();
dialog.dismiss();
}
}).addOnFailureListener((f -> {
Snackbar.make(tvProfileName, f.getLocalizedMessage(), Snackbar.LENGTH_LONG);
dialog.dismiss();
}));
}
}
public void openCameraForProfile() {
Intent pictureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
if (pictureIntent.resolveActivity(getPackageManager()) != null) {
//Create a file to store the image
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
if (photoFile != null) {
mImageUri = FileProvider.getUriForFile(this, "com.example.textme", photoFile);
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
mImageUri);
startActivityForResult(pictureIntent,
TAKE_PHOTO_REQUEST);
}
}
}
public void openCameraForStory() {
Intent pictureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
if (pictureIntent.resolveActivity(getPackageManager()) != null) {
//Create a file to store the image
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
if (photoFile != null) {
mImageUri = FileProvider.getUriForFile(this, "com.example.textme", photoFile);
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
mImageUri);
startActivityForResult(pictureIntent,
TAKE_STORY_PHOTO_REQUEST);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
String mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void findViews() {
tvProfileName = findViewById(R.id.tvProfileName);
profileImage = findViewById(R.id.ciContactImage);
status = findViewById(R.id.tvStatus);
editStatus = findViewById(R.id.statusEdit);
ivLikes = findViewById(R.id.ivLikes);
tvLikes = findViewById(R.id.tvLikes);
rvStory = findViewById(R.id.rvStorys);
}
// ***************************
// -------- Storys -----------
// ***************************
private void setRvStory(){
bringStories();
rvStory.setLayoutManager(new GridLayoutManager(this,4));
rvStory.setHasFixedSize(true);
}
private void bringStories() {
FirebaseDatabase.getInstance().getReference().child("Collections").child(userId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
stories.add(snapshot.getValue(Story.class));
}
rvStory.setAdapter(new StoryAdapter(stories,getApplicationContext(),userId,getSupportFragmentManager()));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
protected void onResume() {
super.onResume();
buildUI();
}
// *******************************
// -------- Animations -----------
// *******************************
private void transition(ImageButton button){
Drawable[] layers = new Drawable[2];
layers[0] = getResources().getDrawable(R.drawable.heart);
layers[1] = getResources().getDrawable(R.drawable.heart_filled);
TransitionDrawable transition = new TransitionDrawable(layers);
transition.setCrossFadeEnabled(true);
button.setImageDrawable(transition);
transition.startTransition(500 /*animation duration*/);
tvLikes.setTextColor(getResources().getColor(android.R.color.holo_red_light));
}
private void reverseTransition(ImageButton button){
Drawable[] layers = new Drawable[2];
layers[1] = getResources().getDrawable(R.drawable.heart);
layers[0] = getResources().getDrawable(R.drawable.heart_filled);
TransitionDrawable transition = new TransitionDrawable(layers);
transition.setCrossFadeEnabled(true);
button.setImageDrawable(transition);
transition.startTransition(500 /*animation duration*/);
tvLikes.setTextColor(getResources().getColor(android.R.color.black));
}
}
| UTF-8 | Java | 16,676 | java | ProfileActivity.java | Java | [] | null | [] | package com.example.textme;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.net.Uri;
import android.os.Bundle;
import com.bumptech.glide.Glide;
import com.example.textme.Adapters.StoryAdapter;
import com.example.textme.Dialogs.editStatusDialog;
import com.example.textme.Dialogs.setProfileImageDialog;
import com.example.textme.Models.Story;
import com.example.textme.Models.User;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.FileProvider;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class ProfileActivity extends AppCompatActivity {
// ------------- REQUESTS CODES ----------------
private static final int PICK_IMAGE_REQUEST = 1;
private static final int TAKE_PHOTO_REQUEST = 2;
private static final int PICK_STORY_PHOTO_REQUEST = 3;
private static final int TAKE_STORY_PHOTO_REQUEST = 4;
// ************* VARIABLES *****************
//Views
ImageView profileImage;
TextView tvProfileName;
ImageButton editStatus;
TextView status;
ImageButton ivLikes;
TextView tvLikes;
//Refs
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("users_profile_images");
//User
User user;
String userId;
boolean Like;
//Profile Img Uri
private Uri mImageUri;
//Progress Dialog
ProgressDialog dialog;
// Story Variables
RecyclerView rvStory;
List<Story> stories = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
userId = getIntent().getStringExtra("id"); // Getting User Id
findViews();
buildUI();
setRvStory();
// Checking If Client Profile or Contact Profile
if(!(userId.matches(FirebaseAuth.getInstance().getCurrentUser().getUid()))){
editStatus.setVisibility(View.GONE);
toggleLike();
} else {
editStatus.setVisibility(View.VISIBLE);
// ON Profile Image Clicked
profileImage.setOnClickListener((v -> {// Open Edit Profile Image Dialog
DialogFragment dialogFragment = new setProfileImageDialog();
dialogFragment.show(getSupportFragmentManager(), "set");
}));
ivLikes.setClickable(false);
// ON Edit Status Clicked
editStatus.setOnClickListener((v -> {// Open Edit Status Dialog
DialogFragment dialogFragment = new editStatusDialog();
Bundle bundle = new Bundle();
bundle.putParcelable("model", user);
dialogFragment.setArguments(bundle);
dialogFragment.show(getSupportFragmentManager(), "edit");
}));
}
}
// **********************************
// ------------ LIKES ---------------
// **********************************
// Posting Like on DB and Animating Drawables
private void toggleLike() {
ivLikes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!Like) {
FirebaseDatabase.getInstance().getReference().child("Likes").child(userId).child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(true).addOnSuccessListener((s -> {
transition(ivLikes);
Like = true;
}));
} else {
FirebaseDatabase.getInstance().getReference().child("Likes").child(userId).child(FirebaseAuth.getInstance().getCurrentUser().getUid()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
reverseTransition(ivLikes);
Like = false;
}
});
}
}
});
}
// Getting Likes Count Method
private void bringLikes(){
FirebaseDatabase.getInstance().getReference().child("Likes").child(userId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
tvLikes.setText(String.valueOf(dataSnapshot.getChildrenCount()));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
// ***************************************
// -------- BUILDING UI METHOD -----------
// ***************************************
private void buildUI() {
//Bringing Name
FirebaseDatabase.getInstance().getReference().child("Users").child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
user = dataSnapshot.getValue(User.class);
tvProfileName.setText(user.getDisplayName());
// Checking for User status
if (user.getUserStatus() != null) {
status.setText(user.getUserStatus());
}
storageReference.child(user.getId()).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
user.setUserImageUri(uri.toString());
Glide.with(getApplicationContext()).load(uri).centerCrop().placeholder(R.drawable.user_placeholder).into(profileImage);
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
// Setting The uploading Image Progress Bar
dialog = new ProgressDialog(ProfileActivity.this);
dialog.setMessage(getString(R.string.upload_img));
FirebaseDatabase.getInstance().getReference().child("Likes").child(userId).orderByChild(FirebaseAuth.getInstance().getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.getValue() != null) {
HashMap hashMap = (HashMap) dataSnapshot.getValue();
Like = (boolean) hashMap.get(FirebaseAuth.getInstance().getCurrentUser().getUid());
if(Like) {ivLikes.setImageResource(R.drawable.heart_filled);
tvLikes.setTextColor(getResources().getColor(android.R.color.holo_red_light));
} else {
tvLikes.setTextColor(getResources().getColor(android.R.color.black));
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
bringLikes();
}
// ***************************************
// ---------- Activitiy Result -----------
// ***************************************
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
dialog.show();
mImageUri = data.getData();
profileImage.setImageURI(mImageUri);
UploadProfileImage();
}
if (requestCode == TAKE_PHOTO_REQUEST && resultCode == RESULT_OK) {
dialog.show();
Glide.with(getApplicationContext()).load(mImageUri).placeholder(R.drawable.user_placeholder).centerCrop().into(profileImage);
UploadProfileImage();
buildUI();
}
if (requestCode == PICK_STORY_PHOTO_REQUEST && resultCode == RESULT_OK){
mImageUri = data.getData();
UploadStory();
}
if (requestCode == TAKE_STORY_PHOTO_REQUEST && resultCode == RESULT_OK){
UploadStory();
}
}
private void UploadStory(){
DatabaseReference collections = FirebaseDatabase.getInstance().getReference().child("Collections").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
String id = collections.push().getKey();
collections.child(id).setValue(new Story(user.getDisplayName(),user.getUserImageUri(),id)).addOnSuccessListener((s)->{
FirebaseStorage.getInstance().getReference().child("Collections").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(id).putFile(mImageUri);
}).addOnFailureListener((f)->{
Snackbar.make(tvProfileName,f.getLocalizedMessage(),Snackbar.LENGTH_LONG);
});
}
// Uploading Image from setProfileDialog to FirebaseStorage
private void UploadProfileImage() {
if (mImageUri != null) {
storageReference.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(ProfileActivity.this, getString(R.string.photo_successfully_changed), Toast.LENGTH_SHORT).show();
buildUI();
dialog.dismiss();
}
}).addOnFailureListener((f -> {
Snackbar.make(tvProfileName, f.getLocalizedMessage(), Snackbar.LENGTH_LONG);
dialog.dismiss();
}));
}
}
public void openCameraForProfile() {
Intent pictureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
if (pictureIntent.resolveActivity(getPackageManager()) != null) {
//Create a file to store the image
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
if (photoFile != null) {
mImageUri = FileProvider.getUriForFile(this, "com.example.textme", photoFile);
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
mImageUri);
startActivityForResult(pictureIntent,
TAKE_PHOTO_REQUEST);
}
}
}
public void openCameraForStory() {
Intent pictureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
if (pictureIntent.resolveActivity(getPackageManager()) != null) {
//Create a file to store the image
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
if (photoFile != null) {
mImageUri = FileProvider.getUriForFile(this, "com.example.textme", photoFile);
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
mImageUri);
startActivityForResult(pictureIntent,
TAKE_STORY_PHOTO_REQUEST);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
String mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void findViews() {
tvProfileName = findViewById(R.id.tvProfileName);
profileImage = findViewById(R.id.ciContactImage);
status = findViewById(R.id.tvStatus);
editStatus = findViewById(R.id.statusEdit);
ivLikes = findViewById(R.id.ivLikes);
tvLikes = findViewById(R.id.tvLikes);
rvStory = findViewById(R.id.rvStorys);
}
// ***************************
// -------- Storys -----------
// ***************************
private void setRvStory(){
bringStories();
rvStory.setLayoutManager(new GridLayoutManager(this,4));
rvStory.setHasFixedSize(true);
}
private void bringStories() {
FirebaseDatabase.getInstance().getReference().child("Collections").child(userId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
stories.add(snapshot.getValue(Story.class));
}
rvStory.setAdapter(new StoryAdapter(stories,getApplicationContext(),userId,getSupportFragmentManager()));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
protected void onResume() {
super.onResume();
buildUI();
}
// *******************************
// -------- Animations -----------
// *******************************
private void transition(ImageButton button){
Drawable[] layers = new Drawable[2];
layers[0] = getResources().getDrawable(R.drawable.heart);
layers[1] = getResources().getDrawable(R.drawable.heart_filled);
TransitionDrawable transition = new TransitionDrawable(layers);
transition.setCrossFadeEnabled(true);
button.setImageDrawable(transition);
transition.startTransition(500 /*animation duration*/);
tvLikes.setTextColor(getResources().getColor(android.R.color.holo_red_light));
}
private void reverseTransition(ImageButton button){
Drawable[] layers = new Drawable[2];
layers[1] = getResources().getDrawable(R.drawable.heart);
layers[0] = getResources().getDrawable(R.drawable.heart_filled);
TransitionDrawable transition = new TransitionDrawable(layers);
transition.setCrossFadeEnabled(true);
button.setImageDrawable(transition);
transition.startTransition(500 /*animation duration*/);
tvLikes.setTextColor(getResources().getColor(android.R.color.black));
}
}
| 16,676 | 0.608779 | 0.60764 | 421 | 38.610451 | 33.607563 | 221 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.522565 | false | false | 2 |
0e50fb0c1c3e3d7607844f426ba9c621582a1d2e | 15,753,940,075,100 | 3d9f1b6d6f3ed29d08025f05666216e1b8c45eab | /lesson3/src/main/java/pro/bolshakov/geekbrains/lesson3/domain/article/AppArticles.java | 8b6aa6964a6aa8f41a81930bf98c19bcf7c5ac5e | [] | no_license | bolshakov-coach/springlevelone | https://github.com/bolshakov-coach/springlevelone | 0b7c1747e2f6ade2fa2ab20b0a97b930ed90d18d | e6052cbca127556466d9de0fd346a6ef86b74db9 | refs/heads/master | 2023-01-23T20:42:35.278000 | 2020-10-30T16:37:47 | 2020-10-30T16:37:47 | 292,530,389 | 0 | 11 | null | false | 2020-11-01T20:16:12 | 2020-09-03T09:52:05 | 2020-10-30T16:37:51 | 2020-11-01T20:15:45 | 220 | 0 | 9 | 0 | Java | false | false | package pro.bolshakov.geekbrains.lesson3.domain.article;
import org.hibernate.cfg.Configuration;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
public class AppArticles {
public static void main(String[] args) {
EntityManagerFactory entityFactory = new Configuration()
.configure("article-hiber.cfg.xml")
.buildSessionFactory();
EntityManager em = entityFactory.createEntityManager();
Category category = new Category();
category.setName("Joke");
createEntity(em, category);
Author authorIvan = new Author();
authorIvan.setFirstname("Ivan");
authorIvan.setLastname("Ivanov");
authorIvan.setEmail("some@email");
createEntity(em, authorIvan);
Article articleIvan = new Article();
articleIvan.setTitle("Ivan article");
articleIvan.setContent("I am a god");
articleIvan.setCategory(readEntity(em, Category.class, 1L));
articleIvan.setAuthor(readEntity(em, Author.class, 2L));
createEntity(em, articleIvan);
/*Article articleGoga = new Article();
articleGoga.setTitle("Goga novel");
articleGoga.setContent("I have visited all hotels on Turkey");
articleGoga.setAuthor(new Author("Goga", "Grogorian", "goga@mail"));
articleGoga.setCategory(new Category("novel"));
articleGoga.setAuthor(saveEntity(em, new Author("Goga", "Grogorian", "goga@mail")));
articleGoga.setCategory(saveEntity(em, new Category("novel")));
createEntity(em, articleGoga);*/
}
private static <T> void createEntity(EntityManager em, T entity){
System.out.println("Creating entity");
//open transaction
em.getTransaction().begin();
//put person into persist area of Hibernate
em.persist(entity);
//commit/close transaction
em.getTransaction().commit();
System.out.println("Creating finished");
}
private static <T> T readEntity(EntityManager em, Class<T> clazz, long id){
System.out.println("Start reading");
em.getTransaction().begin();
T person = em.find(clazz, id);
em.getTransaction().commit();
System.out.println("Reading completed->" + person);
return person;
}
private static <T> T saveEntity(EntityManager em, T entity){
System.out.println("Start saving");
em.getTransaction().begin();
T savedEntity = em.merge(entity);
em.getTransaction().commit();
System.out.println("Saving completed->" + savedEntity);
return savedEntity;
}
}
| UTF-8 | Java | 2,686 | java | AppArticles.java | Java | [
{
"context": " = new Author();\n authorIvan.setFirstname(\"Ivan\");\n authorIvan.setLastname(\"Ivanov\");\n ",
"end": 679,
"score": 0.9997513294219971,
"start": 675,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "irstname(\"Ivan\");\n authorIvan.setLastname(\"Ivanov\");\n authorIvan.setEmail(\"some@email\");\n\n ",
"end": 721,
"score": 0.9996767640113831,
"start": 715,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "tLastname(\"Ivanov\");\n authorIvan.setEmail(\"some@email\");\n\n createEntity(em, authorIvan);\n\n ",
"end": 764,
"score": 0.941214382648468,
"start": 754,
"tag": "EMAIL",
"value": "some@email"
},
{
"context": "key\");\n\n articleGoga.setAuthor(new Author(\"Goga\", \"Grogorian\", \"goga@mail\"));\n articleGoga",
"end": 1329,
"score": 0.8391328454017639,
"start": 1325,
"tag": "NAME",
"value": "Goga"
},
{
"context": " articleGoga.setAuthor(new Author(\"Goga\", \"Grogorian\", \"goga@mail\"));\n articleGoga.setCategory(",
"end": 1342,
"score": 0.9097374081611633,
"start": 1333,
"tag": "NAME",
"value": "Grogorian"
},
{
"context": "leGoga.setAuthor(new Author(\"Goga\", \"Grogorian\", \"goga@mail\"));\n articleGoga.setCategory(new Category(",
"end": 1355,
"score": 0.8526219129562378,
"start": 1346,
"tag": "EMAIL",
"value": "goga@mail"
},
{
"context": " articleGoga.setAuthor(saveEntity(em, new Author(\"Goga\", \"Grogorian\", \"goga@mail\")));\n articleGog",
"end": 1478,
"score": 0.9123217463493347,
"start": 1474,
"tag": "NAME",
"value": "Goga"
},
{
"context": "Goga.setAuthor(saveEntity(em, new Author(\"Goga\", \"Grogorian\", \"goga@mail\")));\n articleGoga.setCategory",
"end": 1491,
"score": 0.9851914048194885,
"start": 1482,
"tag": "NAME",
"value": "Grogorian"
},
{
"context": "(saveEntity(em, new Author(\"Goga\", \"Grogorian\", \"goga@mail\")));\n articleGoga.setCategory(saveEntity(e",
"end": 1504,
"score": 0.8151119351387024,
"start": 1496,
"tag": "EMAIL",
"value": "oga@mail"
}
] | null | [] | package pro.bolshakov.geekbrains.lesson3.domain.article;
import org.hibernate.cfg.Configuration;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
public class AppArticles {
public static void main(String[] args) {
EntityManagerFactory entityFactory = new Configuration()
.configure("article-hiber.cfg.xml")
.buildSessionFactory();
EntityManager em = entityFactory.createEntityManager();
Category category = new Category();
category.setName("Joke");
createEntity(em, category);
Author authorIvan = new Author();
authorIvan.setFirstname("Ivan");
authorIvan.setLastname("Ivanov");
authorIvan.setEmail("<EMAIL>");
createEntity(em, authorIvan);
Article articleIvan = new Article();
articleIvan.setTitle("Ivan article");
articleIvan.setContent("I am a god");
articleIvan.setCategory(readEntity(em, Category.class, 1L));
articleIvan.setAuthor(readEntity(em, Author.class, 2L));
createEntity(em, articleIvan);
/*Article articleGoga = new Article();
articleGoga.setTitle("Goga novel");
articleGoga.setContent("I have visited all hotels on Turkey");
articleGoga.setAuthor(new Author("Goga", "Grogorian", "<EMAIL>"));
articleGoga.setCategory(new Category("novel"));
articleGoga.setAuthor(saveEntity(em, new Author("Goga", "Grogorian", "g<EMAIL>")));
articleGoga.setCategory(saveEntity(em, new Category("novel")));
createEntity(em, articleGoga);*/
}
private static <T> void createEntity(EntityManager em, T entity){
System.out.println("Creating entity");
//open transaction
em.getTransaction().begin();
//put person into persist area of Hibernate
em.persist(entity);
//commit/close transaction
em.getTransaction().commit();
System.out.println("Creating finished");
}
private static <T> T readEntity(EntityManager em, Class<T> clazz, long id){
System.out.println("Start reading");
em.getTransaction().begin();
T person = em.find(clazz, id);
em.getTransaction().commit();
System.out.println("Reading completed->" + person);
return person;
}
private static <T> T saveEntity(EntityManager em, T entity){
System.out.println("Start saving");
em.getTransaction().begin();
T savedEntity = em.merge(entity);
em.getTransaction().commit();
System.out.println("Saving completed->" + savedEntity);
return savedEntity;
}
}
| 2,680 | 0.64408 | 0.642964 | 89 | 29.179775 | 25.271809 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.719101 | false | false | 2 |
0c597f7ee11649db264234664a543e3a3aea22d0 | 24,197,845,806,899 | b110be48e9db9f4abdeac311cfff90964177299b | /dhis-2/dhis-api/src/test/java/org/hisp/dhis/dataelement/CategoryComboTest.java | dbbbb70d27adf45372ca2d749dc0633c6f0d9c5f | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | dhis2/dhis2-core | https://github.com/dhis2/dhis2-core | 5410b4257a023003977c4731ebc581005cd5910a | 50c9aba33a36ced8b7af0d907729ef191afa280e | refs/heads/master | 2023-08-31T07:48:05.369000 | 2023-08-31T06:48:56 | 2023-08-31T06:48:56 | 66,940,520 | 283 | 381 | BSD-3-Clause | false | 2023-09-14T19:39:31 | 2016-08-30T12:57:05 | 2023-09-05T04:53:35 | 2023-09-14T19:39:31 | 186,058 | 258 | 305 | 41 | Java | false | false | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.dataelement;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.List;
import org.hisp.dhis.category.Category;
import org.hisp.dhis.category.CategoryCombo;
import org.hisp.dhis.category.CategoryOption;
import org.hisp.dhis.category.CategoryOptionCombo;
import org.hisp.dhis.common.DataDimensionType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* @author Lars Helge Overland
*/
class CategoryComboTest {
private CategoryOption categoryOptionA;
private CategoryOption categoryOptionB;
private CategoryOption categoryOptionC;
private CategoryOption categoryOptionD;
private CategoryOption categoryOptionE;
private CategoryOption categoryOptionF;
private Category categoryA;
private Category categoryB;
private Category categoryC;
private CategoryCombo categoryCombo;
// -------------------------------------------------------------------------
// Fixture
// -------------------------------------------------------------------------
@BeforeEach
void before() {
categoryOptionA = new CategoryOption("OptionA");
categoryOptionB = new CategoryOption("OptionB");
categoryOptionC = new CategoryOption("OptionC");
categoryOptionD = new CategoryOption("OptionD");
categoryOptionE = new CategoryOption("OptionE");
categoryOptionF = new CategoryOption("OptionF");
categoryA = new Category("CategoryA", DataDimensionType.DISAGGREGATION);
categoryB = new Category("CategoryB", DataDimensionType.DISAGGREGATION);
categoryC = new Category("CategoryC", DataDimensionType.DISAGGREGATION);
categoryA.getCategoryOptions().add(categoryOptionA);
categoryA.getCategoryOptions().add(categoryOptionB);
categoryB.getCategoryOptions().add(categoryOptionC);
categoryB.getCategoryOptions().add(categoryOptionD);
categoryC.getCategoryOptions().add(categoryOptionE);
categoryC.getCategoryOptions().add(categoryOptionF);
categoryOptionA.getCategories().add(categoryA);
categoryOptionB.getCategories().add(categoryA);
categoryOptionC.getCategories().add(categoryB);
categoryOptionD.getCategories().add(categoryB);
categoryOptionE.getCategories().add(categoryC);
categoryOptionF.getCategories().add(categoryC);
categoryCombo = new CategoryCombo("CategoryCombo", DataDimensionType.DISAGGREGATION);
categoryCombo.getCategories().add(categoryA);
categoryCombo.getCategories().add(categoryB);
categoryCombo.getCategories().add(categoryC);
}
@Test
void testGenerateOptionCombosList() {
List<CategoryOptionCombo> list = categoryCombo.generateOptionCombosList();
assertNotNull(list);
assertEquals(8, list.size());
assertEquals(
createCategoryOptionCombo(categoryCombo, categoryOptionA, categoryOptionC, categoryOptionE),
list.get(0));
assertEquals(
createCategoryOptionCombo(categoryCombo, categoryOptionA, categoryOptionC, categoryOptionF),
list.get(1));
assertEquals(
createCategoryOptionCombo(categoryCombo, categoryOptionA, categoryOptionD, categoryOptionE),
list.get(2));
assertEquals(
createCategoryOptionCombo(categoryCombo, categoryOptionA, categoryOptionD, categoryOptionF),
list.get(3));
assertEquals(
createCategoryOptionCombo(categoryCombo, categoryOptionB, categoryOptionC, categoryOptionE),
list.get(4));
assertEquals(
createCategoryOptionCombo(categoryCombo, categoryOptionB, categoryOptionC, categoryOptionF),
list.get(5));
assertEquals(
createCategoryOptionCombo(categoryCombo, categoryOptionB, categoryOptionD, categoryOptionE),
list.get(6));
assertEquals(
createCategoryOptionCombo(categoryCombo, categoryOptionB, categoryOptionD, categoryOptionF),
list.get(7));
}
@Test
void test() {
List<CategoryOptionCombo> list = categoryCombo.generateOptionCombosList();
categoryCombo.generateOptionCombos();
assertEquals(list, categoryCombo.getSortedOptionCombos());
}
private static CategoryOptionCombo createCategoryOptionCombo(
CategoryCombo categoryCombo, CategoryOption... categoryOptions) {
CategoryOptionCombo categoryOptionCombo = new CategoryOptionCombo();
categoryOptionCombo.setCategoryCombo(categoryCombo);
for (CategoryOption categoryOption : categoryOptions) {
categoryOptionCombo.getCategoryOptions().add(categoryOption);
}
return categoryOptionCombo;
}
}
| UTF-8 | Java | 6,124 | java | CategoryComboTest.java | Java | [
{
"context": "import org.junit.jupiter.api.Test;\n\n/**\n * @author Lars Helge Overland\n */\nclass CategoryComboTest {\n\n private Category",
"end": 2080,
"score": 0.9998622536659241,
"start": 2061,
"tag": "NAME",
"value": "Lars Helge Overland"
}
] | null | [] | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.dataelement;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.List;
import org.hisp.dhis.category.Category;
import org.hisp.dhis.category.CategoryCombo;
import org.hisp.dhis.category.CategoryOption;
import org.hisp.dhis.category.CategoryOptionCombo;
import org.hisp.dhis.common.DataDimensionType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* @author <NAME>
*/
class CategoryComboTest {
private CategoryOption categoryOptionA;
private CategoryOption categoryOptionB;
private CategoryOption categoryOptionC;
private CategoryOption categoryOptionD;
private CategoryOption categoryOptionE;
private CategoryOption categoryOptionF;
private Category categoryA;
private Category categoryB;
private Category categoryC;
private CategoryCombo categoryCombo;
// -------------------------------------------------------------------------
// Fixture
// -------------------------------------------------------------------------
@BeforeEach
void before() {
categoryOptionA = new CategoryOption("OptionA");
categoryOptionB = new CategoryOption("OptionB");
categoryOptionC = new CategoryOption("OptionC");
categoryOptionD = new CategoryOption("OptionD");
categoryOptionE = new CategoryOption("OptionE");
categoryOptionF = new CategoryOption("OptionF");
categoryA = new Category("CategoryA", DataDimensionType.DISAGGREGATION);
categoryB = new Category("CategoryB", DataDimensionType.DISAGGREGATION);
categoryC = new Category("CategoryC", DataDimensionType.DISAGGREGATION);
categoryA.getCategoryOptions().add(categoryOptionA);
categoryA.getCategoryOptions().add(categoryOptionB);
categoryB.getCategoryOptions().add(categoryOptionC);
categoryB.getCategoryOptions().add(categoryOptionD);
categoryC.getCategoryOptions().add(categoryOptionE);
categoryC.getCategoryOptions().add(categoryOptionF);
categoryOptionA.getCategories().add(categoryA);
categoryOptionB.getCategories().add(categoryA);
categoryOptionC.getCategories().add(categoryB);
categoryOptionD.getCategories().add(categoryB);
categoryOptionE.getCategories().add(categoryC);
categoryOptionF.getCategories().add(categoryC);
categoryCombo = new CategoryCombo("CategoryCombo", DataDimensionType.DISAGGREGATION);
categoryCombo.getCategories().add(categoryA);
categoryCombo.getCategories().add(categoryB);
categoryCombo.getCategories().add(categoryC);
}
@Test
void testGenerateOptionCombosList() {
List<CategoryOptionCombo> list = categoryCombo.generateOptionCombosList();
assertNotNull(list);
assertEquals(8, list.size());
assertEquals(
createCategoryOptionCombo(categoryCombo, categoryOptionA, categoryOptionC, categoryOptionE),
list.get(0));
assertEquals(
createCategoryOptionCombo(categoryCombo, categoryOptionA, categoryOptionC, categoryOptionF),
list.get(1));
assertEquals(
createCategoryOptionCombo(categoryCombo, categoryOptionA, categoryOptionD, categoryOptionE),
list.get(2));
assertEquals(
createCategoryOptionCombo(categoryCombo, categoryOptionA, categoryOptionD, categoryOptionF),
list.get(3));
assertEquals(
createCategoryOptionCombo(categoryCombo, categoryOptionB, categoryOptionC, categoryOptionE),
list.get(4));
assertEquals(
createCategoryOptionCombo(categoryCombo, categoryOptionB, categoryOptionC, categoryOptionF),
list.get(5));
assertEquals(
createCategoryOptionCombo(categoryCombo, categoryOptionB, categoryOptionD, categoryOptionE),
list.get(6));
assertEquals(
createCategoryOptionCombo(categoryCombo, categoryOptionB, categoryOptionD, categoryOptionF),
list.get(7));
}
@Test
void test() {
List<CategoryOptionCombo> list = categoryCombo.generateOptionCombosList();
categoryCombo.generateOptionCombos();
assertEquals(list, categoryCombo.getSortedOptionCombos());
}
private static CategoryOptionCombo createCategoryOptionCombo(
CategoryCombo categoryCombo, CategoryOption... categoryOptions) {
CategoryOptionCombo categoryOptionCombo = new CategoryOptionCombo();
categoryOptionCombo.setCategoryCombo(categoryCombo);
for (CategoryOption categoryOption : categoryOptions) {
categoryOptionCombo.getCategoryOptions().add(categoryOption);
}
return categoryOptionCombo;
}
}
| 6,111 | 0.749673 | 0.746897 | 146 | 40.945206 | 30.106382 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.863014 | false | false | 2 |
efe7ca26b79518d54d11088331cb973d2c71c06d | 24,678,882,091,251 | c1d05cd83234b2acfb7a403254d8e21d573956a8 | /src/com/xierw/design/partterns/behavioralPattern/command/example1/PasteCommand.java | 32dd1f00e3df80e6985de9c4aea409a123ef5885 | [] | no_license | XieRW/1429382875-qq.com | https://github.com/XieRW/1429382875-qq.com | 1107986445413f9b345dab819764b0c6d9d17956 | 1bec9648da835d3737e4b5b8cce3f3dcd2cbd97c | refs/heads/master | 2021-05-21T10:02:33.710000 | 2020-05-18T13:57:40 | 2020-05-18T13:57:40 | 252,647,645 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xierw.design.partterns.behavioralPattern.command.example1;
import com.sun.deploy.util.StringUtils;
/**
* 从剪贴板粘贴文字
*
* @date 2020-04-23
* @author xie
* @email 1429382875@qq.com
*/
public class PasteCommand extends Command {
public PasteCommand(Editor editor) {
super(editor);
}
/**
* 执行命令
* @return
*/
@Override
public boolean excute() {
// 粘贴板未初始化或者值为空字符串,则不处理
if (editor.clipboard == null || editor.clipboard.isEmpty()){
return false;
}
// 先备份
backup();
// 然后把粘贴板的内容插入到选中的插入符号位置
editor.textField.insert(editor.clipboard,editor.textField.getCaretPosition());
return true;
}
}
| UTF-8 | Java | 834 | java | PasteCommand.java | Java | [
{
"context": "\n/**\n * 从剪贴板粘贴文字\n *\n * @date 2020-04-23\n * @author xie\n * @email 1429382875@qq.com\n */\npublic class Past",
"end": 166,
"score": 0.9954240322113037,
"start": 163,
"tag": "USERNAME",
"value": "xie"
},
{
"context": "字\n *\n * @date 2020-04-23\n * @author xie\n * @email 1429382875@qq.com\n */\npublic class PasteCommand extends Command {\n\n",
"end": 194,
"score": 0.9998383522033691,
"start": 177,
"tag": "EMAIL",
"value": "1429382875@qq.com"
}
] | null | [] | package com.xierw.design.partterns.behavioralPattern.command.example1;
import com.sun.deploy.util.StringUtils;
/**
* 从剪贴板粘贴文字
*
* @date 2020-04-23
* @author xie
* @email <EMAIL>
*/
public class PasteCommand extends Command {
public PasteCommand(Editor editor) {
super(editor);
}
/**
* 执行命令
* @return
*/
@Override
public boolean excute() {
// 粘贴板未初始化或者值为空字符串,则不处理
if (editor.clipboard == null || editor.clipboard.isEmpty()){
return false;
}
// 先备份
backup();
// 然后把粘贴板的内容插入到选中的插入符号位置
editor.textField.insert(editor.clipboard,editor.textField.getCaretPosition());
return true;
}
}
| 824 | 0.608033 | 0.581717 | 35 | 19.628571 | 20.955853 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 2 |
5488e45b21b51ad7b972ce73fc79b23fa44f7fd6 | 14,637,248,559,835 | c2de12e28acd1e8589f70a38ec08377365bace59 | /taobaoke-service/src/main/java/com/igogogo/service/impl/Ig_WxServiceImpl.java | 74c13979cd2d19aaff170dabef10125568241ada | [] | no_license | 84330299/taobaoke | https://github.com/84330299/taobaoke | 39d85c15c74ca149803d2ce9ca4675e091947886 | dfa293e09b367e1bb65bf6a177e5f79e32798230 | refs/heads/master | 2020-03-27T20:44:11.399000 | 2018-09-02T14:03:23 | 2018-09-02T14:03:23 | 147,090,442 | 2 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.igogogo.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.igogogo.dao.Ig_WxMapper;
import com.igogogo.domain.Ig_Wx;
import com.igogogo.service.Ig_WxService;
@Service
@Transactional
public class Ig_WxServiceImpl implements Ig_WxService {
@Autowired
private Ig_WxMapper ig_WxMapper;
@Override
public int add(Ig_Wx t) {
return ig_WxMapper.insertSelective(t);
}
@Override
public int addmore(List<Ig_Wx> ts) {
int result = 0;
try {
for (Ig_Wx t : ts) {
add(t);
}
result = 1;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
public int delete(Integer id) {
return ig_WxMapper.deleteByPrimaryKey(id);
}
@Override
public int deleteByMoreId(List<Integer> ids) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int update(Integer id, Ig_Wx t) {
t.setWxid(id);
return ig_WxMapper.updateByPrimaryKeySelective(t);
}
@Override
public int updatemore(List<Ig_Wx> ts) {
// TODO Auto-generated method stub
return 0;
}
@Override
public List<Ig_Wx> query() {
return ig_WxMapper.query();
}
@Override
public Ig_Wx queryById(Integer id) {
return ig_WxMapper.queryById(id);
}
@Override
public int queryCount() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int queryCountByKeyWord(String keyword) {
// TODO Auto-generated method stub
return 0;
}
@Override
public List<Ig_Wx> queryByPage(Map<String, Object> map) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Ig_Wx> queryKeyWordByPage(Map<String, Object> map) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Ig_Wx> queryByCondition(Map<String, Object> condition) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Ig_Wx> queryByConditionByPage(Map<String, Object> condition) {
// TODO Auto-generated method stub
return null;
}
}
| UTF-8 | Java | 2,132 | java | Ig_WxServiceImpl.java | Java | [] | null | [] | package com.igogogo.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.igogogo.dao.Ig_WxMapper;
import com.igogogo.domain.Ig_Wx;
import com.igogogo.service.Ig_WxService;
@Service
@Transactional
public class Ig_WxServiceImpl implements Ig_WxService {
@Autowired
private Ig_WxMapper ig_WxMapper;
@Override
public int add(Ig_Wx t) {
return ig_WxMapper.insertSelective(t);
}
@Override
public int addmore(List<Ig_Wx> ts) {
int result = 0;
try {
for (Ig_Wx t : ts) {
add(t);
}
result = 1;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
public int delete(Integer id) {
return ig_WxMapper.deleteByPrimaryKey(id);
}
@Override
public int deleteByMoreId(List<Integer> ids) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int update(Integer id, Ig_Wx t) {
t.setWxid(id);
return ig_WxMapper.updateByPrimaryKeySelective(t);
}
@Override
public int updatemore(List<Ig_Wx> ts) {
// TODO Auto-generated method stub
return 0;
}
@Override
public List<Ig_Wx> query() {
return ig_WxMapper.query();
}
@Override
public Ig_Wx queryById(Integer id) {
return ig_WxMapper.queryById(id);
}
@Override
public int queryCount() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int queryCountByKeyWord(String keyword) {
// TODO Auto-generated method stub
return 0;
}
@Override
public List<Ig_Wx> queryByPage(Map<String, Object> map) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Ig_Wx> queryKeyWordByPage(Map<String, Object> map) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Ig_Wx> queryByCondition(Map<String, Object> condition) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Ig_Wx> queryByConditionByPage(Map<String, Object> condition) {
// TODO Auto-generated method stub
return null;
}
}
| 2,132 | 0.716698 | 0.713884 | 109 | 18.559633 | 18.906546 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.357798 | false | false | 2 |
48d20dc5a3bafccead0cb39c5cf59e4f0a1a3b82 | 19,774,029,485,523 | d60e287543a95a20350c2caeabafbec517cabe75 | /LACCPlus/Camel/10381_1.java | a3a1f00f3527953800165215f46b6229436bc209 | [
"MIT"
] | permissive | sgholamian/log-aware-clone-detection | https://github.com/sgholamian/log-aware-clone-detection | 242067df2db6fd056f8d917cfbc143615c558b2c | 9993cb081c420413c231d1807bfff342c39aa69a | refs/heads/main | 2023-07-20T09:32:19.757000 | 2021-08-27T15:02:50 | 2021-08-27T15:02:50 | 337,837,827 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //,temp,ThriftProducerAsyncTest.java,169,194,temp,ThriftProducerAsyncTest.java,142,167
//,2
public class xxx {
@Test
public void testOneWayMethodInvocation() throws Exception {
LOG.info("Thrift one-way method async test start");
final CountDownLatch latch = new CountDownLatch(1);
final Object requestBody = null;
responseBody = new Object();
template.asyncCallbackSendBody("direct:thrift-zip", requestBody, new SynchronizationAdapter() {
@Override
public void onComplete(Exchange exchange) {
responseBody = exchange.getMessage().getBody();
latch.countDown();
}
@Override
public void onFailure(Exchange exchange) {
responseBody = exchange.getException();
latch.countDown();
}
});
latch.await(5, TimeUnit.SECONDS);
assertNull(responseBody);
}
}; | UTF-8 | Java | 962 | java | 10381_1.java | Java | [] | null | [] | //,temp,ThriftProducerAsyncTest.java,169,194,temp,ThriftProducerAsyncTest.java,142,167
//,2
public class xxx {
@Test
public void testOneWayMethodInvocation() throws Exception {
LOG.info("Thrift one-way method async test start");
final CountDownLatch latch = new CountDownLatch(1);
final Object requestBody = null;
responseBody = new Object();
template.asyncCallbackSendBody("direct:thrift-zip", requestBody, new SynchronizationAdapter() {
@Override
public void onComplete(Exchange exchange) {
responseBody = exchange.getMessage().getBody();
latch.countDown();
}
@Override
public void onFailure(Exchange exchange) {
responseBody = exchange.getException();
latch.countDown();
}
});
latch.await(5, TimeUnit.SECONDS);
assertNull(responseBody);
}
}; | 962 | 0.607069 | 0.591476 | 31 | 30.064516 | 27.603104 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.774194 | false | false | 2 |
9cec22cd7ad4fd0c1a8358244f3f2e7c3adf8919 | 14,001,593,450,400 | f85f116777e71bfb8a419ccc8320c12d0130fa23 | /src/main/java/com/chainsys/bookshelf/TodaysSpecial.java | 7216816fafbf57fc436334145d54a1deaec45b40 | [] | no_license | csys-fresher-batch-2019/bookshelfapp-spring-ramola | https://github.com/csys-fresher-batch-2019/bookshelfapp-spring-ramola | 4db39e6d4b6611117d9992ecffb1e6de84084a64 | 2ddb99e82b1646e834eb1deaf2a6ce59d43b1f39 | refs/heads/master | 2021-01-16T04:08:36.510000 | 2020-03-23T14:58:42 | 2020-03-23T14:58:42 | 242,971,811 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chainsys.bookshelf;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.chainsys.bookshelf.implementations.BooksDAOImpl;
import com.chainsys.bookshelf.model.Book;
@WebServlet("/TodaysSpecial")
public class TodaysSpecial extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BooksDAOImpl bl = new BooksDAOImpl();
List<Book> l = new ArrayList<Book>();
// PrintWriter out = response.getWriter();
try {
l = bl.findTodaysSpecial();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 913 | java | TodaysSpecial.java | Java | [] | null | [] | package com.chainsys.bookshelf;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.chainsys.bookshelf.implementations.BooksDAOImpl;
import com.chainsys.bookshelf.model.Book;
@WebServlet("/TodaysSpecial")
public class TodaysSpecial extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BooksDAOImpl bl = new BooksDAOImpl();
List<Book> l = new ArrayList<Book>();
// PrintWriter out = response.getWriter();
try {
l = bl.findTodaysSpecial();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 913 | 0.779847 | 0.778751 | 37 | 23.675676 | 21.287039 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.162162 | false | false | 2 |
0e78f0b755d85900c3d1bdea6101dfd434827a93 | 28,011,776,748,621 | a640036e9d28159d8f57a2d71ed83ed2c8563b8f | /EmailApplication/src/com/smartweights/mail/pdf/PDFTableProperties.java | 9ed3d6897a7779562e44138ff7c922cc2af1ae03 | [] | no_license | ramakrishna65/email-restfulService | https://github.com/ramakrishna65/email-restfulService | f3d03a26802c1202f7ebbd8a8eb76ff6875e28d3 | 65b07b8adabb1bc1e2ef2be6629b21c01235e0f8 | refs/heads/master | 2021-01-10T05:00:58.058000 | 2016-01-19T16:20:44 | 2016-01-19T16:20:44 | 49,964,460 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package com.smartweights.mail.pdf;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.stereotype.Component;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
/**
* @author Rama
*
*/
@Component("pdfTableProperties")
public class PDFTableProperties {
public static final String COMPANY_LOGO = "../images/sw-logo.png";
private static Font TIME_ROMAN = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
private static Font TIME_ROMAN_SMALL = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD);
private static Font HEADER_WHITE_FONT = new Font(Font.FontFamily.HELVETICA, 10, Font.NORMAL, BaseColor.WHITE);
private static Font TABLE_CELL_FONT = new Font(Font.FontFamily.HELVETICA, 11, Font.NORMAL,
new BaseColor(64, 64, 64));
public void addCompanyLogo(Document document) throws DocumentException{
try {
Image companyLogo = Image.getInstance(COMPANY_LOGO);
document.add(companyLogo);
Paragraph preface = new Paragraph();
creteEmptyLine(preface, 1);
preface.add(new Paragraph("SMART WEIGHTS", TIME_ROMAN));
document.add(preface);
} catch (BadElementException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void addMetaData(Document document, String userName) {
document.addTitle(userName + " PDF");
document.addSubject("SmartWeight Records PDF");
document.addKeywords("SmartWeight, exercise Records, exercise sets, exercicse weight");
document.addAuthor("SmartWeight Application");
document.addCreator("SmartWeight Application");
}
public void addTitlePage(Document document) throws DocumentException {
Paragraph preface = new Paragraph();
creteEmptyLine(preface, 1);
preface.add(new Paragraph("WORKOUT HISTORY BY EXERCISE", TIME_ROMAN));
creteEmptyLine(preface, 1);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
preface.add(new Paragraph("Report created on " + simpleDateFormat.format(new Date()), TIME_ROMAN));
document.add(preface);
}
public void addTitlePageForLiveWorkout(Document document) throws DocumentException {
Paragraph preface = new Paragraph();
creteEmptyLine(preface, 1);
preface.add(new Paragraph("LIVE WORKOUT DETAILS", TIME_ROMAN));
creteEmptyLine(preface, 1);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
preface.add(new Paragraph("Report created on " + simpleDateFormat.format(new Date()), TIME_ROMAN));
document.add(preface);
}
public void creteEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
public void createTableHeader(PdfPTable table) {
PdfPCell c1 = new PdfPCell(new Phrase("SET", HEADER_WHITE_FONT));
HeaderCellStyle(c1);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("WEIGHT", HEADER_WHITE_FONT));
HeaderCellStyle(c1);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("REP", HEADER_WHITE_FONT));
HeaderCellStyle(c1);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("CONTRACT TIME", HEADER_WHITE_FONT));
HeaderCellStyle(c1);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("EXTEND TIME", HEADER_WHITE_FONT));
HeaderCellStyle(c1);
table.addCell(c1);
// table.setHeaderRows(1);
}
public void HeaderCellStyle(PdfPCell cell) {
cell.setPaddingTop(3f);
cell.setPaddingBottom(5f);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setBackgroundColor(new BaseColor(51, 114, 223));
cell.setBorder(0);
}
public PdfPCell BodyCellStyle(String value) {
PdfPCell cell = new PdfPCell(new Phrase(value, TABLE_CELL_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setBackgroundColor(new BaseColor(240, 240, 240));
cell.setBorder(0);
cell.setMinimumHeight(10f);
return cell;
}
public void exerciseHeaderStyle(PdfPCell cell) {
cell.setColspan(5);
cell.setBackgroundColor(new BaseColor(0, 0, 0));
cell.setBorderWidthBottom(1);
cell.setBorderColorBottom(new BaseColor(255, 255, 255));
cell.setPaddingTop(5f);
cell.setPaddingBottom(10f);
cell.setPaddingLeft(15f);
}
}
| UTF-8 | Java | 4,880 | java | PDFTableProperties.java | Java | [
{
"context": "om.itextpdf.text.pdf.PdfPTable;\r\n\r\n/**\r\n * @author Rama\r\n *\r\n */\r\n\r\n@Component(\"pdfTableProperties\")\r\npubli",
"end": 675,
"score": 0.9880540370941162,
"start": 671,
"tag": "NAME",
"value": "Rama"
}
] | null | [] | /**
*
*/
package com.smartweights.mail.pdf;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.stereotype.Component;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
/**
* @author Rama
*
*/
@Component("pdfTableProperties")
public class PDFTableProperties {
public static final String COMPANY_LOGO = "../images/sw-logo.png";
private static Font TIME_ROMAN = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
private static Font TIME_ROMAN_SMALL = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD);
private static Font HEADER_WHITE_FONT = new Font(Font.FontFamily.HELVETICA, 10, Font.NORMAL, BaseColor.WHITE);
private static Font TABLE_CELL_FONT = new Font(Font.FontFamily.HELVETICA, 11, Font.NORMAL,
new BaseColor(64, 64, 64));
public void addCompanyLogo(Document document) throws DocumentException{
try {
Image companyLogo = Image.getInstance(COMPANY_LOGO);
document.add(companyLogo);
Paragraph preface = new Paragraph();
creteEmptyLine(preface, 1);
preface.add(new Paragraph("SMART WEIGHTS", TIME_ROMAN));
document.add(preface);
} catch (BadElementException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void addMetaData(Document document, String userName) {
document.addTitle(userName + " PDF");
document.addSubject("SmartWeight Records PDF");
document.addKeywords("SmartWeight, exercise Records, exercise sets, exercicse weight");
document.addAuthor("SmartWeight Application");
document.addCreator("SmartWeight Application");
}
public void addTitlePage(Document document) throws DocumentException {
Paragraph preface = new Paragraph();
creteEmptyLine(preface, 1);
preface.add(new Paragraph("WORKOUT HISTORY BY EXERCISE", TIME_ROMAN));
creteEmptyLine(preface, 1);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
preface.add(new Paragraph("Report created on " + simpleDateFormat.format(new Date()), TIME_ROMAN));
document.add(preface);
}
public void addTitlePageForLiveWorkout(Document document) throws DocumentException {
Paragraph preface = new Paragraph();
creteEmptyLine(preface, 1);
preface.add(new Paragraph("LIVE WORKOUT DETAILS", TIME_ROMAN));
creteEmptyLine(preface, 1);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
preface.add(new Paragraph("Report created on " + simpleDateFormat.format(new Date()), TIME_ROMAN));
document.add(preface);
}
public void creteEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
public void createTableHeader(PdfPTable table) {
PdfPCell c1 = new PdfPCell(new Phrase("SET", HEADER_WHITE_FONT));
HeaderCellStyle(c1);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("WEIGHT", HEADER_WHITE_FONT));
HeaderCellStyle(c1);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("REP", HEADER_WHITE_FONT));
HeaderCellStyle(c1);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("CONTRACT TIME", HEADER_WHITE_FONT));
HeaderCellStyle(c1);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("EXTEND TIME", HEADER_WHITE_FONT));
HeaderCellStyle(c1);
table.addCell(c1);
// table.setHeaderRows(1);
}
public void HeaderCellStyle(PdfPCell cell) {
cell.setPaddingTop(3f);
cell.setPaddingBottom(5f);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setBackgroundColor(new BaseColor(51, 114, 223));
cell.setBorder(0);
}
public PdfPCell BodyCellStyle(String value) {
PdfPCell cell = new PdfPCell(new Phrase(value, TABLE_CELL_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setBackgroundColor(new BaseColor(240, 240, 240));
cell.setBorder(0);
cell.setMinimumHeight(10f);
return cell;
}
public void exerciseHeaderStyle(PdfPCell cell) {
cell.setColspan(5);
cell.setBackgroundColor(new BaseColor(0, 0, 0));
cell.setBorderWidthBottom(1);
cell.setBorderColorBottom(new BaseColor(255, 255, 255));
cell.setPaddingTop(5f);
cell.setPaddingBottom(10f);
cell.setPaddingLeft(15f);
}
}
| 4,880 | 0.701025 | 0.685041 | 153 | 29.895424 | 26.738913 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.830065 | false | false | 2 |
605685db1b482ab5dd0dfd4762e4b369d108a1f8 | 30,399,778,550,715 | 48464c3cc0d2b880927b9aa8a3c131f8d582e9b3 | /app/src/main/java/com/example/to_dorpg/database/DBAttackHelper.java | 56ea6c116a1519a84949f60990e4790006e6639c | [] | no_license | frejakong/To-Do-RPG | https://github.com/frejakong/To-Do-RPG | eda7932a5ea017666acccee40b34367881f1a4d6 | 7c11700312ae1bcb8535453aa8566f3a1df39939 | refs/heads/master | 2023-08-07T07:45:27.932000 | 2021-09-10T16:38:12 | 2021-09-10T16:38:12 | 405,099,301 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.to_dorpg.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.to_dorpg.model.Attack;
import com.example.to_dorpg.model.Gold;
import java.util.ArrayList;
public class DBAttackHelper extends SQLiteOpenHelper {
private SQLiteDatabase db;
public DBAttackHelper(Context context){
super(context,"attack.db",null,1);
db = getReadableDatabase();
}
// attack value in database
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table attack(" +
"id integer primary key autoincrement," +
"value INTEGER)"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS attack");
onCreate(db);
}
public void init(){
db.execSQL("INSERT INTO attack (value) VALUES(?)",new Object[]{100});
}
public void rewardTime(int value){
value=value-10;
db.execSQL("UPDATE attack SET value = ?",new Object[]{value});
}
public void completeTasks(int value){
value=value+15;
db.execSQL("UPDATE attack SET value = ?",new Object[]{value});
}
public ArrayList<Attack> getAllData(){
ArrayList<Attack> list = new ArrayList<Attack>();
Cursor cursor = db.query("attack",null,null,null,null,null,"value");
while(cursor.moveToNext()){
int attack = cursor.getInt(cursor.getColumnIndex("value"));
list.add(new Attack(attack));
}
return list;
}
}
| UTF-8 | Java | 1,711 | java | DBAttackHelper.java | Java | [] | null | [] | package com.example.to_dorpg.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.to_dorpg.model.Attack;
import com.example.to_dorpg.model.Gold;
import java.util.ArrayList;
public class DBAttackHelper extends SQLiteOpenHelper {
private SQLiteDatabase db;
public DBAttackHelper(Context context){
super(context,"attack.db",null,1);
db = getReadableDatabase();
}
// attack value in database
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table attack(" +
"id integer primary key autoincrement," +
"value INTEGER)"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS attack");
onCreate(db);
}
public void init(){
db.execSQL("INSERT INTO attack (value) VALUES(?)",new Object[]{100});
}
public void rewardTime(int value){
value=value-10;
db.execSQL("UPDATE attack SET value = ?",new Object[]{value});
}
public void completeTasks(int value){
value=value+15;
db.execSQL("UPDATE attack SET value = ?",new Object[]{value});
}
public ArrayList<Attack> getAllData(){
ArrayList<Attack> list = new ArrayList<Attack>();
Cursor cursor = db.query("attack",null,null,null,null,null,"value");
while(cursor.moveToNext()){
int attack = cursor.getInt(cursor.getColumnIndex("value"));
list.add(new Attack(attack));
}
return list;
}
}
| 1,711 | 0.644068 | 0.639392 | 66 | 24.924242 | 23.80114 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.590909 | false | false | 2 |
d8f252cd63f4a3a01309d173b61ecdba148a490d | 4,217,657,955,207 | cf32c0adf690290848f0f1a15e5a573256cd2b20 | /src/main/java/scottjmitchell/drafter/draft/Draft.java | b717ae06a9dc4adaddc95d504d9e21c252fb586e | [] | no_license | scottjmitchell/drafter | https://github.com/scottjmitchell/drafter | f26fb681a9b60362dbbaa74386ca26880e727c0b | 837fed693049a72ecb7e2313a3e2bf2754070c08 | refs/heads/master | 2018-10-20T13:56:53.526000 | 2018-09-01T10:44:06 | 2018-09-01T10:44:06 | 140,862,025 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package scottjmitchell.drafter.draft;
import com.google.common.collect.Lists;
import scottjmitchell.drafter.league.League;
import scottjmitchell.drafter.member.Member;
import scottjmitchell.drafter.sport.players.NFLData;
import scottjmitchell.drafter.sport.players.NFLPlayer;
import scottjmitchell.drafter.sport.scraping.PlayerScraper;
import scottjmitchell.drafter.sport.scraping.ScrapedPlayer;
import scottjmitchell.drafter.sport.teams.NFLTeams;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import static scottjmitchell.drafter.member.Member.printMembersNFLTeam;
import static scottjmitchell.drafter.sport.players.NFLData.*;
@Entity
public class Draft {
@Id
public String draftName;
public int draftYear;
@ManyToOne
private League league;
private int minNoStartingQBs;
private int minNoStartingRBs;
private int minNoStartingWRs;
private int minNoStartingTEs;
private int minNoStartingKs;
private int minNoStartingDSTs;
private int minNoStartingFlex;
private int noOnBench;
public ArrayList<Member> draftMembers;
private int totalNoPicks;
private int pickNo;
private int roundNo;
private ArrayList<NFLPlayer> allNFLPlayers;
private ArrayList<NFLPlayer> remainingNFLPlayers;
private ArrayList<NFLPlayer> tempAllNFLPlayers;
private ArrayList<NFLPlayer> playersDrafted;
private ArrayList<Member> whoHasDraftedAlready;
private ArrayList<Member> draftOrder;
public Draft() {
}
public Draft(String draftName, int draftYear, int minNoStartingQBs, int minNoStartingRBs, int minNoStartingWRs, int minNoStartingTEs, int minNoStartingKs, int minNoStartingDSTs, int minNoStartingFlex, int noOnBench, String leagueName, Member ...members) throws IOException {
super();
this.draftName = draftName;
this.draftYear = draftYear;
this.league = new League(leagueName);
this.draftMembers = new ArrayList<>();
this.minNoStartingQBs = minNoStartingQBs;
this.minNoStartingRBs = minNoStartingRBs;
this.minNoStartingWRs = minNoStartingWRs;
this.minNoStartingTEs = minNoStartingTEs;
this.minNoStartingKs = minNoStartingKs;
this.minNoStartingDSTs = minNoStartingDSTs;
this.minNoStartingFlex = minNoStartingFlex;
this.noOnBench = noOnBench;
this.totalNoPicks = calculateNumberOfPicks();
this.playersDrafted = new ArrayList<>();
this.whoHasDraftedAlready = new ArrayList<>();
this.draftOrder = createDraftOrder(draftMembers);
this.pickNo = 1;
this.roundNo = 1;
loadPlayers(createDraftOrderOfPlayers());
createMembersNewTeamList();
}
//Draft Setup
private void loadPlayers(ArrayList<NFLPlayer> players) {
this.allNFLPlayers = players;
createRemainingPlayers();
}
private void createRemainingPlayers() {
this.remainingNFLPlayers = new ArrayList<>(allNFLPlayers);
}
public ArrayList<Member> createDraftOrder(ArrayList<Member> draftMembers) {
ArrayList<Member> draftOrder = new ArrayList<>();
int totalNoRounds = totalNoPicks / draftMembers.size();
for (int round = 0; round < totalNoRounds; round++) {
List<Member> reversedOrNot = (round % 2 == 0) ? draftMembers : Lists.reverse(draftMembers);
draftOrder.addAll(reversedOrNot);
}
return draftOrder;
}
public void randomiseDraftOrder() {
Collections.shuffle(draftMembers);
}
private int calculateNumberOfPicks() {
return (minNoStartingQBs + minNoStartingRBs + minNoStartingWRs + minNoStartingTEs + minNoStartingKs + minNoStartingDSTs + minNoStartingFlex + noOnBench) * draftMembers.size();
}
public ArrayList<NFLPlayer> getPlayerDataFromDatabase(Connection conn) throws SQLException {
ArrayList<NFLPlayer> nflPlayers = new ArrayList<>();
PreparedStatement playerStmt = conn.prepareStatement("SELECT * FROM nfl_players");
ResultSet playerResultSet = playerStmt.executeQuery();
while (playerResultSet.next()) {
String id = playerResultSet.getString("player_id");
nflPlayers.add(
new NFLPlayer(
playerResultSet.getString("name"),
NFLTeams.getTeamName(playerResultSet.getString("team")),
playerResultSet.getString("position")
)
);
}
for(NFLPlayer player : nflPlayers) {
String id = player.getIdConcat().replaceAll("'","''");
String query = "SELECT * FROM nfl_player_data WHERE player_id='" + id + "'";
PreparedStatement playerDataStmt = conn.prepareStatement(query);
ResultSet playerdataResultSet = playerDataStmt.executeQuery();
player.playerRanks = new HashMap<>();
while (playerdataResultSet.next()) {
Integer year = playerdataResultSet.getInt("year");
NFLData data = NFLData.valueOf(playerdataResultSet.getString("data_type"));
Double value = playerdataResultSet.getDouble("value");
Map<NFLData, Double> playerYearMap = player.playerRanks.getOrDefault(year, new HashMap<>());
playerYearMap.put(data, value);
player.playerRanks.put(year,playerYearMap);
}
}
return nflPlayers;
}
//View, Add & Remove Players
public ArrayList<NFLPlayer> getAllPlayers() {
return allNFLPlayers;
}
public ArrayList<NFLPlayer> showAllRemainingPlayers() {
return remainingNFLPlayers;
}
public void draftPlayer(NFLPlayer player) {
Member member = draftOrder.get(pickNo - 1);
remainingNFLPlayers.remove(player);
member.membersNFLTeams.get(draftName).add(player);
playersDrafted.add(player);
whoHasDraftedAlready.add(member);
pickNo++;
incrementRound();
System.out.println("\n" + member + " has drafted " + player.name + " [" + player.team.teamAbbr() + " - " + player.position + "]");
}
public void undoDraftPick() {
NFLPlayer lastPick = playersDrafted.get(playersDrafted.size() - 1);
Member lastDrafter = draftOrder.get(pickNo - 2);
remainingNFLPlayers.add(lastPick);
lastDrafter.membersNFLTeams.get(draftName).remove(lastPick);
playersDrafted.remove(lastPick);
pickNo--;
System.out.println("\n" + lastPick.name + " was removed from " + lastDrafter.name + "'s team");
}
private void incrementRound() {
if ((pickNo % draftMembers.size()) == 1) {
roundNo++;
}
}
//Member Teams
public Member getMember(String name) {
return draftMembers.stream()
.filter(member -> member.getName().equals(name))
.findFirst()
.get();
}
private void createMembersNewTeamList() {
for (Member member : draftMembers) {
member.membersNFLTeams.put(draftName, new ArrayList<>());
}
}
public static void printAllMembersTeams(Draft draft) {
for (Member member : draft.draftMembers) {
printMembersNFLTeam(draft, member.name);
}
}
//Draft Order
private ArrayList<NFLPlayer> createDraftOrderOfPlayers() throws IOException {
ArrayList<ScrapedPlayer> scrapedPlayers = getPlayersFromFantasyPros();
ArrayList<NFLPlayer> nflPlayers = convertScrapedPlayersToNFLPlayers(scrapedPlayers);
Map<NFLPlayer,Double> draftScores = getPlayerScores(nflPlayers);
return orderByScore(draftScores);
}
private ArrayList<ScrapedPlayer> getPlayersFromFantasyPros() throws IOException {
PlayerScraper ps = new PlayerScraper();
return ps.getFantasyProsData();
}
private ArrayList<NFLPlayer> convertScrapedPlayersToNFLPlayers(ArrayList<ScrapedPlayer> scrapedPlayers) {
ArrayList<NFLPlayer> nflPlayers = new ArrayList<>();
for (ScrapedPlayer player : scrapedPlayers) {
NFLPlayer nflPlayer = new NFLPlayer(
player.getName(),
NFLTeams.getTeamName(player.getTeam()),
player.getPosition()
);
Map<NFLData,Double> data = new HashMap<>();
data.put(FANTASY_PROS_USER_ADP, player.getAvrUserADP());
data.put(FANTASY_PROS_EXPERT_ADP, player.getAvrExpertADP());
data.put(FANTASY_PROS_BEST_EXPERTS_ADP, player.getAvrBest20ExpertsADP());
data.put(CONSISTENCY_SCORE, (double) player.getConsistencyScore());
data.put(GREAT_GAMES_PERCENTAGE, (double) player.getGreatGamesPercentage());
nflPlayer.playerRanks.put(draftYear,data);
nflPlayers.add(nflPlayer);
}
return nflPlayers;
}
private Map<NFLPlayer,Double> getPlayerScores(ArrayList<NFLPlayer> nflPlayers) {
Map<NFLPlayer,Double> draftScores = new HashMap<>();
for (NFLPlayer player : nflPlayers) {
double bestExperts = Double.parseDouble(player.playerRanks.get(draftYear).get(FANTASY_PROS_BEST_EXPERTS_ADP).toString());
double experts = Double.parseDouble(player.playerRanks.get(draftYear).get(FANTASY_PROS_EXPERT_ADP).toString());
double users = Double.parseDouble(player.playerRanks.get(draftYear).get(FANTASY_PROS_USER_ADP).toString());
int numberToAverageBy = 0;
if (bestExperts != 0) {
numberToAverageBy += 1;
} else {
bestExperts = 329;
}
if (experts != 0) {
numberToAverageBy += 1;
} else {
experts = 436;
}
if (users != 0) {numberToAverageBy += 1;}
Double score = ((bestExperts * 6) + (experts * 3) + users)/numberToAverageBy;
draftScores.put(player,score);
}
return draftScores;
}
private ArrayList<NFLPlayer> orderByScore(Map<NFLPlayer, Double> unsortedMap) {
Map<NFLPlayer, Double> sortedMap = new LinkedHashMap<>();
unsortedMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
Map<NFLPlayer, Integer> draftOrder = new LinkedHashMap<>();
ArrayList<NFLPlayer> orderedList = new ArrayList<>(sortedMap.keySet());
double counter = 1;
for (NFLPlayer player : orderedList) {
player.playerRanks.get(draftYear).put(DRAFT_RANK, counter);
counter += 1 ;
}
return orderedList;
}
//Helper methods
public String getDraftName() {
return draftName;
}
public void setDraftName(String draftName) {
this.draftName = draftName;
}
public int getDraftYear() {
return draftYear;
}
public void setDraftYear(int draftYear) {
this.draftYear = draftYear;
}
public int getMinNoStartingQBs() {
return minNoStartingQBs;
}
public void setMinNoStartingQBs(int minNoStartingQBs) {
this.minNoStartingQBs = minNoStartingQBs;
}
public int getMinNoStartingRBs() {
return minNoStartingRBs;
}
public void setMinNoStartingRBs(int minNoStartingRBs) {
this.minNoStartingRBs = minNoStartingRBs;
}
public int getMinNoStartingWRs() {
return minNoStartingWRs;
}
public void setMinNoStartingWRs(int minNoStartingWRs) {
this.minNoStartingWRs = minNoStartingWRs;
}
public int getMinNoStartingTEs() {
return minNoStartingTEs;
}
public void setMinNoStartingTEs(int minNoStartingTEs) {
this.minNoStartingTEs = minNoStartingTEs;
}
public int getMinNoStartingKs() {
return minNoStartingKs;
}
public void setMinNoStartingKs(int minNoStartingKs) {
this.minNoStartingKs = minNoStartingKs;
}
public int getMinNoStartingDSTs() {
return minNoStartingDSTs;
}
public void setMinNoStartingDSTs(int minNoStartingDSTs) {
this.minNoStartingDSTs = minNoStartingDSTs;
}
public int getMinNoStartingFlex() {
return minNoStartingFlex;
}
public void setMinNoStartingFlex(int minNoStartingFlex) {
this.minNoStartingFlex = minNoStartingFlex;
}
public int getNoOnBench() {
return noOnBench;
}
public void setNoOnBench(int noOnBench) {
this.noOnBench = noOnBench;
}
public League getLeague() {
return league;
}
public void setLeague(League league) {
this.league = league;
}
public ArrayList<NFLPlayer> getAllNFLPlayers() {
return allNFLPlayers;
}
public ArrayList<NFLPlayer> getRemainingNFLPlayers() {
return remainingNFLPlayers;
}
} | UTF-8 | Java | 13,189 | java | Draft.java | Java | [] | null | [] | package scottjmitchell.drafter.draft;
import com.google.common.collect.Lists;
import scottjmitchell.drafter.league.League;
import scottjmitchell.drafter.member.Member;
import scottjmitchell.drafter.sport.players.NFLData;
import scottjmitchell.drafter.sport.players.NFLPlayer;
import scottjmitchell.drafter.sport.scraping.PlayerScraper;
import scottjmitchell.drafter.sport.scraping.ScrapedPlayer;
import scottjmitchell.drafter.sport.teams.NFLTeams;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import static scottjmitchell.drafter.member.Member.printMembersNFLTeam;
import static scottjmitchell.drafter.sport.players.NFLData.*;
@Entity
public class Draft {
@Id
public String draftName;
public int draftYear;
@ManyToOne
private League league;
private int minNoStartingQBs;
private int minNoStartingRBs;
private int minNoStartingWRs;
private int minNoStartingTEs;
private int minNoStartingKs;
private int minNoStartingDSTs;
private int minNoStartingFlex;
private int noOnBench;
public ArrayList<Member> draftMembers;
private int totalNoPicks;
private int pickNo;
private int roundNo;
private ArrayList<NFLPlayer> allNFLPlayers;
private ArrayList<NFLPlayer> remainingNFLPlayers;
private ArrayList<NFLPlayer> tempAllNFLPlayers;
private ArrayList<NFLPlayer> playersDrafted;
private ArrayList<Member> whoHasDraftedAlready;
private ArrayList<Member> draftOrder;
public Draft() {
}
public Draft(String draftName, int draftYear, int minNoStartingQBs, int minNoStartingRBs, int minNoStartingWRs, int minNoStartingTEs, int minNoStartingKs, int minNoStartingDSTs, int minNoStartingFlex, int noOnBench, String leagueName, Member ...members) throws IOException {
super();
this.draftName = draftName;
this.draftYear = draftYear;
this.league = new League(leagueName);
this.draftMembers = new ArrayList<>();
this.minNoStartingQBs = minNoStartingQBs;
this.minNoStartingRBs = minNoStartingRBs;
this.minNoStartingWRs = minNoStartingWRs;
this.minNoStartingTEs = minNoStartingTEs;
this.minNoStartingKs = minNoStartingKs;
this.minNoStartingDSTs = minNoStartingDSTs;
this.minNoStartingFlex = minNoStartingFlex;
this.noOnBench = noOnBench;
this.totalNoPicks = calculateNumberOfPicks();
this.playersDrafted = new ArrayList<>();
this.whoHasDraftedAlready = new ArrayList<>();
this.draftOrder = createDraftOrder(draftMembers);
this.pickNo = 1;
this.roundNo = 1;
loadPlayers(createDraftOrderOfPlayers());
createMembersNewTeamList();
}
//Draft Setup
private void loadPlayers(ArrayList<NFLPlayer> players) {
this.allNFLPlayers = players;
createRemainingPlayers();
}
private void createRemainingPlayers() {
this.remainingNFLPlayers = new ArrayList<>(allNFLPlayers);
}
public ArrayList<Member> createDraftOrder(ArrayList<Member> draftMembers) {
ArrayList<Member> draftOrder = new ArrayList<>();
int totalNoRounds = totalNoPicks / draftMembers.size();
for (int round = 0; round < totalNoRounds; round++) {
List<Member> reversedOrNot = (round % 2 == 0) ? draftMembers : Lists.reverse(draftMembers);
draftOrder.addAll(reversedOrNot);
}
return draftOrder;
}
public void randomiseDraftOrder() {
Collections.shuffle(draftMembers);
}
private int calculateNumberOfPicks() {
return (minNoStartingQBs + minNoStartingRBs + minNoStartingWRs + minNoStartingTEs + minNoStartingKs + minNoStartingDSTs + minNoStartingFlex + noOnBench) * draftMembers.size();
}
public ArrayList<NFLPlayer> getPlayerDataFromDatabase(Connection conn) throws SQLException {
ArrayList<NFLPlayer> nflPlayers = new ArrayList<>();
PreparedStatement playerStmt = conn.prepareStatement("SELECT * FROM nfl_players");
ResultSet playerResultSet = playerStmt.executeQuery();
while (playerResultSet.next()) {
String id = playerResultSet.getString("player_id");
nflPlayers.add(
new NFLPlayer(
playerResultSet.getString("name"),
NFLTeams.getTeamName(playerResultSet.getString("team")),
playerResultSet.getString("position")
)
);
}
for(NFLPlayer player : nflPlayers) {
String id = player.getIdConcat().replaceAll("'","''");
String query = "SELECT * FROM nfl_player_data WHERE player_id='" + id + "'";
PreparedStatement playerDataStmt = conn.prepareStatement(query);
ResultSet playerdataResultSet = playerDataStmt.executeQuery();
player.playerRanks = new HashMap<>();
while (playerdataResultSet.next()) {
Integer year = playerdataResultSet.getInt("year");
NFLData data = NFLData.valueOf(playerdataResultSet.getString("data_type"));
Double value = playerdataResultSet.getDouble("value");
Map<NFLData, Double> playerYearMap = player.playerRanks.getOrDefault(year, new HashMap<>());
playerYearMap.put(data, value);
player.playerRanks.put(year,playerYearMap);
}
}
return nflPlayers;
}
//View, Add & Remove Players
public ArrayList<NFLPlayer> getAllPlayers() {
return allNFLPlayers;
}
public ArrayList<NFLPlayer> showAllRemainingPlayers() {
return remainingNFLPlayers;
}
public void draftPlayer(NFLPlayer player) {
Member member = draftOrder.get(pickNo - 1);
remainingNFLPlayers.remove(player);
member.membersNFLTeams.get(draftName).add(player);
playersDrafted.add(player);
whoHasDraftedAlready.add(member);
pickNo++;
incrementRound();
System.out.println("\n" + member + " has drafted " + player.name + " [" + player.team.teamAbbr() + " - " + player.position + "]");
}
public void undoDraftPick() {
NFLPlayer lastPick = playersDrafted.get(playersDrafted.size() - 1);
Member lastDrafter = draftOrder.get(pickNo - 2);
remainingNFLPlayers.add(lastPick);
lastDrafter.membersNFLTeams.get(draftName).remove(lastPick);
playersDrafted.remove(lastPick);
pickNo--;
System.out.println("\n" + lastPick.name + " was removed from " + lastDrafter.name + "'s team");
}
private void incrementRound() {
if ((pickNo % draftMembers.size()) == 1) {
roundNo++;
}
}
//Member Teams
public Member getMember(String name) {
return draftMembers.stream()
.filter(member -> member.getName().equals(name))
.findFirst()
.get();
}
private void createMembersNewTeamList() {
for (Member member : draftMembers) {
member.membersNFLTeams.put(draftName, new ArrayList<>());
}
}
public static void printAllMembersTeams(Draft draft) {
for (Member member : draft.draftMembers) {
printMembersNFLTeam(draft, member.name);
}
}
//Draft Order
private ArrayList<NFLPlayer> createDraftOrderOfPlayers() throws IOException {
ArrayList<ScrapedPlayer> scrapedPlayers = getPlayersFromFantasyPros();
ArrayList<NFLPlayer> nflPlayers = convertScrapedPlayersToNFLPlayers(scrapedPlayers);
Map<NFLPlayer,Double> draftScores = getPlayerScores(nflPlayers);
return orderByScore(draftScores);
}
private ArrayList<ScrapedPlayer> getPlayersFromFantasyPros() throws IOException {
PlayerScraper ps = new PlayerScraper();
return ps.getFantasyProsData();
}
private ArrayList<NFLPlayer> convertScrapedPlayersToNFLPlayers(ArrayList<ScrapedPlayer> scrapedPlayers) {
ArrayList<NFLPlayer> nflPlayers = new ArrayList<>();
for (ScrapedPlayer player : scrapedPlayers) {
NFLPlayer nflPlayer = new NFLPlayer(
player.getName(),
NFLTeams.getTeamName(player.getTeam()),
player.getPosition()
);
Map<NFLData,Double> data = new HashMap<>();
data.put(FANTASY_PROS_USER_ADP, player.getAvrUserADP());
data.put(FANTASY_PROS_EXPERT_ADP, player.getAvrExpertADP());
data.put(FANTASY_PROS_BEST_EXPERTS_ADP, player.getAvrBest20ExpertsADP());
data.put(CONSISTENCY_SCORE, (double) player.getConsistencyScore());
data.put(GREAT_GAMES_PERCENTAGE, (double) player.getGreatGamesPercentage());
nflPlayer.playerRanks.put(draftYear,data);
nflPlayers.add(nflPlayer);
}
return nflPlayers;
}
private Map<NFLPlayer,Double> getPlayerScores(ArrayList<NFLPlayer> nflPlayers) {
Map<NFLPlayer,Double> draftScores = new HashMap<>();
for (NFLPlayer player : nflPlayers) {
double bestExperts = Double.parseDouble(player.playerRanks.get(draftYear).get(FANTASY_PROS_BEST_EXPERTS_ADP).toString());
double experts = Double.parseDouble(player.playerRanks.get(draftYear).get(FANTASY_PROS_EXPERT_ADP).toString());
double users = Double.parseDouble(player.playerRanks.get(draftYear).get(FANTASY_PROS_USER_ADP).toString());
int numberToAverageBy = 0;
if (bestExperts != 0) {
numberToAverageBy += 1;
} else {
bestExperts = 329;
}
if (experts != 0) {
numberToAverageBy += 1;
} else {
experts = 436;
}
if (users != 0) {numberToAverageBy += 1;}
Double score = ((bestExperts * 6) + (experts * 3) + users)/numberToAverageBy;
draftScores.put(player,score);
}
return draftScores;
}
private ArrayList<NFLPlayer> orderByScore(Map<NFLPlayer, Double> unsortedMap) {
Map<NFLPlayer, Double> sortedMap = new LinkedHashMap<>();
unsortedMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
Map<NFLPlayer, Integer> draftOrder = new LinkedHashMap<>();
ArrayList<NFLPlayer> orderedList = new ArrayList<>(sortedMap.keySet());
double counter = 1;
for (NFLPlayer player : orderedList) {
player.playerRanks.get(draftYear).put(DRAFT_RANK, counter);
counter += 1 ;
}
return orderedList;
}
//Helper methods
public String getDraftName() {
return draftName;
}
public void setDraftName(String draftName) {
this.draftName = draftName;
}
public int getDraftYear() {
return draftYear;
}
public void setDraftYear(int draftYear) {
this.draftYear = draftYear;
}
public int getMinNoStartingQBs() {
return minNoStartingQBs;
}
public void setMinNoStartingQBs(int minNoStartingQBs) {
this.minNoStartingQBs = minNoStartingQBs;
}
public int getMinNoStartingRBs() {
return minNoStartingRBs;
}
public void setMinNoStartingRBs(int minNoStartingRBs) {
this.minNoStartingRBs = minNoStartingRBs;
}
public int getMinNoStartingWRs() {
return minNoStartingWRs;
}
public void setMinNoStartingWRs(int minNoStartingWRs) {
this.minNoStartingWRs = minNoStartingWRs;
}
public int getMinNoStartingTEs() {
return minNoStartingTEs;
}
public void setMinNoStartingTEs(int minNoStartingTEs) {
this.minNoStartingTEs = minNoStartingTEs;
}
public int getMinNoStartingKs() {
return minNoStartingKs;
}
public void setMinNoStartingKs(int minNoStartingKs) {
this.minNoStartingKs = minNoStartingKs;
}
public int getMinNoStartingDSTs() {
return minNoStartingDSTs;
}
public void setMinNoStartingDSTs(int minNoStartingDSTs) {
this.minNoStartingDSTs = minNoStartingDSTs;
}
public int getMinNoStartingFlex() {
return minNoStartingFlex;
}
public void setMinNoStartingFlex(int minNoStartingFlex) {
this.minNoStartingFlex = minNoStartingFlex;
}
public int getNoOnBench() {
return noOnBench;
}
public void setNoOnBench(int noOnBench) {
this.noOnBench = noOnBench;
}
public League getLeague() {
return league;
}
public void setLeague(League league) {
this.league = league;
}
public ArrayList<NFLPlayer> getAllNFLPlayers() {
return allNFLPlayers;
}
public ArrayList<NFLPlayer> getRemainingNFLPlayers() {
return remainingNFLPlayers;
}
} | 13,189 | 0.651983 | 0.64986 | 425 | 30.035294 | 31.331791 | 278 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.501176 | false | false | 2 |
a0085c33b42cb71e85beadd583414c630c7cd5ed | 15,341,623,246,813 | 890b7348a6f7b4587e066ba5eeb4608eba93d158 | /src/main/java/chess/board/movesgenerators/legal/MoveFilter.java | 1a3d49f9b440f269c8eb0d9c7962ba35602f90ca | [
"BSD-3-Clause"
] | permissive | mcoria/chess | https://github.com/mcoria/chess | 81721fd970c1ac56e8395175eb4b27609cd41d46 | b874920808938a527b7ccd1edfbffa894635a936 | refs/heads/master | 2022-06-21T21:53:33.594000 | 2022-06-21T02:55:15 | 2022-06-21T02:55:15 | 231,782,401 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chess.board.movesgenerators.legal;
import chess.board.moves.Move;
import chess.board.moves.MoveCastling;
import chess.board.moves.MoveKing;
/**
* @author Mauricio Coria
*
*/
public interface MoveFilter {
boolean filterMove(Move move);
boolean filterMove(MoveKing move) ;
boolean filterMove(MoveCastling moveCastling);
}
| UTF-8 | Java | 348 | java | MoveFilter.java | Java | [
{
"context": "mport chess.board.moves.MoveKing;\n\n\n/**\n * @author Mauricio Coria\n *\n */\npublic interface MoveFilter {\n\n\t\n\tboolean ",
"end": 180,
"score": 0.9998348951339722,
"start": 166,
"tag": "NAME",
"value": "Mauricio Coria"
}
] | null | [] | package chess.board.movesgenerators.legal;
import chess.board.moves.Move;
import chess.board.moves.MoveCastling;
import chess.board.moves.MoveKing;
/**
* @author <NAME>
*
*/
public interface MoveFilter {
boolean filterMove(Move move);
boolean filterMove(MoveKing move) ;
boolean filterMove(MoveCastling moveCastling);
}
| 340 | 0.755747 | 0.755747 | 23 | 14.130435 | 17.098955 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.608696 | false | false | 2 |
8088b71ffb6947b61a6c5a9b41e1412779b821a4 | 16,544,214,025,936 | 5f7c272029194c1dc507088e40932decbe7f9544 | /lightbatis-core/src/main/java/titan/lightbatis/mapper/LightbatisMapper.java | 82bacd564db7e656608ac31adeb075e945d0cbdb | [
"Apache-2.0"
] | permissive | lightbatis/lightbatis | https://github.com/lightbatis/lightbatis | 37ce0483237cdd51deae97793413d6a4071e531f | a4a144c99af6e2ca5b98c0f06373d97600372c5f | refs/heads/master | 2023-06-27T00:20:33.544000 | 2023-05-28T08:30:26 | 2023-05-28T08:30:26 | 224,137,061 | 41 | 2 | Apache-2.0 | false | 2023-06-14T22:31:48 | 2019-11-26T08:11:38 | 2022-11-17T10:31:54 | 2023-06-14T22:31:47 | 7,065 | 52 | 2 | 9 | Java | false | false | package titan.lightbatis.mapper;
import com.querydsl.core.types.Predicate;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.UpdateProvider;
import org.springframework.transaction.annotation.Transactional;
import titan.lightbatis.annotations.LightDelete;
import titan.lightbatis.annotations.LightSave;
import titan.lightbatis.mybatis.provider.impl.BaseMapperProvider;
/**
*
* @author lifei114@126.com
* @param <T>
*/
public interface LightbatisMapper<T> extends QueryMapper<T> {
/**
* 根据实体对象, 往数据库里插入一条记录。
* @param record 属性添加了 @ID 注释,且值为 NULL, 将使用 SnowflakeId 算法自动生成一个,且值赋给该属性
* @return 保存影响的条数
*/
@InsertProvider(type = BaseMapperProvider.class, method = "insert")
@Transactional(readOnly = false)
int insert(T record);
/**
* 如果存在就更新,不存在就插入
* @param record
* @return
*/
@Transactional(readOnly = false)
@LightSave
int save(T record);
@UpdateProvider(type = BaseMapperProvider.class, method="updateByPrimaryKey")
@Transactional(readOnly = false)
int updateByPrimaryKey(T record);
@DeleteProvider(type = BaseMapperProvider.class, method="deleteByPrimaryKey")
@Transactional(readOnly = false)
int deleteByPrimaryKey(T record);
@Transactional(readOnly = false)
@LightDelete
int delete(Predicate... predicates);
}
| UTF-8 | Java | 1,567 | java | LightbatisMapper.java | Java | [
{
"context": "ovider.impl.BaseMapperProvider;\n\n/**\n *\n * @author lifei114@126.com\n * @param <T>\n */\npublic interface LightbatisMapp",
"end": 497,
"score": 0.9999058246612549,
"start": 481,
"tag": "EMAIL",
"value": "lifei114@126.com"
}
] | null | [] | package titan.lightbatis.mapper;
import com.querydsl.core.types.Predicate;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.UpdateProvider;
import org.springframework.transaction.annotation.Transactional;
import titan.lightbatis.annotations.LightDelete;
import titan.lightbatis.annotations.LightSave;
import titan.lightbatis.mybatis.provider.impl.BaseMapperProvider;
/**
*
* @author <EMAIL>
* @param <T>
*/
public interface LightbatisMapper<T> extends QueryMapper<T> {
/**
* 根据实体对象, 往数据库里插入一条记录。
* @param record 属性添加了 @ID 注释,且值为 NULL, 将使用 SnowflakeId 算法自动生成一个,且值赋给该属性
* @return 保存影响的条数
*/
@InsertProvider(type = BaseMapperProvider.class, method = "insert")
@Transactional(readOnly = false)
int insert(T record);
/**
* 如果存在就更新,不存在就插入
* @param record
* @return
*/
@Transactional(readOnly = false)
@LightSave
int save(T record);
@UpdateProvider(type = BaseMapperProvider.class, method="updateByPrimaryKey")
@Transactional(readOnly = false)
int updateByPrimaryKey(T record);
@DeleteProvider(type = BaseMapperProvider.class, method="deleteByPrimaryKey")
@Transactional(readOnly = false)
int deleteByPrimaryKey(T record);
@Transactional(readOnly = false)
@LightDelete
int delete(Predicate... predicates);
}
| 1,558 | 0.729502 | 0.725298 | 48 | 28.729166 | 23.89538 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 2 |
25ab7cdc87d475fe4f2e17c729987c51b0df9687 | 13,675,175,927,628 | c92b2b9fb7b1cd3d9d08b50832d02f560afec8f9 | /turtle-back/src/main/java/com/zz/back/util/markrazi/trans/EmptyLineTranslator.java | cbd4a9173bc187d04f6b1e13b1b68c7d09b1ed96 | [] | no_license | zzpierce/TurtleSite | https://github.com/zzpierce/TurtleSite | 2b817ad8ad16174ecd93dbae8fcb08c6cc64b1c6 | e5ff4f003ecf955440befe21c375e0f8f1e107fe | refs/heads/master | 2020-04-12T06:42:54.096000 | 2018-06-29T11:07:02 | 2018-06-29T11:07:02 | 64,849,815 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zz.back.util.markrazi.trans;
public class EmptyLineTranslator extends AbstractTranslator {
public String translate(String src, TranslatorContext context) {
if(src == null) return null;
if(src.trim().equals("")) {
return src;
}
return null;
}
private String clear(TranslatorContext context) {
StringBuilder buffer = new StringBuilder();
buffer.append(ListTranslator.clearContext(context));
return buffer.toString();
}
}
| UTF-8 | Java | 523 | java | EmptyLineTranslator.java | Java | [] | null | [] | package com.zz.back.util.markrazi.trans;
public class EmptyLineTranslator extends AbstractTranslator {
public String translate(String src, TranslatorContext context) {
if(src == null) return null;
if(src.trim().equals("")) {
return src;
}
return null;
}
private String clear(TranslatorContext context) {
StringBuilder buffer = new StringBuilder();
buffer.append(ListTranslator.clearContext(context));
return buffer.toString();
}
}
| 523 | 0.644359 | 0.644359 | 23 | 21.73913 | 23.550533 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.347826 | false | false | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.