blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|
7276c5b7538c4e3927453483890bc228029b6b94
|
Java
|
DavinderSinghKharoud/AlgorithmsAndDataStructures
|
/CSESProblemSet/SubarraySumQueries.java
|
UTF-8
| 10,761 | 3.34375 | 3 |
[] |
no_license
|
import java.io.*;
import java.util.*;
/**
* There is an array consisting of n
* n
* integers. Some values of the array will be updated, and after each update, your task is to report the maximum subarray sum in the array.
*
* Input
*
* The first input line contains integers n
* n
* and m
* m
* : the size of the array and the number of updates. The array is indexed 1,2,…,n
* 1
* ,
* 2
* ,
* …
* ,
* n
* .
*
* The next line has n
* n
* integers: x1,x2,…,xn
* x
* 1
* ,
* x
* 2
* ,
* …
* ,
* x
* n
* : the initial contents of the array.
*
* Then there are m
* m
* lines describing the changes. Each line has two integers k
* k
* and x
* x
* : the value at position k
* k
* becomes x
* x
* .
*
* Output
*
* After each update, print the maximum subarray sum. Empty subarrays (with sum 0
* 0
* ) are allowed.
*
* Constraints
* 1≤n,m≤2⋅105
* 1
* ≤
* n
* ,
* m
* ≤
* 2
* ⋅
* 10
* 5
*
* −109≤xi≤109
* −
* 10
* 9
* ≤
* x
* i
* ≤
* 10
* 9
*
* 1≤k≤n
* 1
* ≤
* k
* ≤
* n
*
* −109≤x≤109
* −
* 10
* 9
* ≤
* x
* ≤
* 10
* 9
*
* Example
*
* Input:
* 5 3
* 1 2 -3 5 -1
* 2 6
* 3 1
* 2 -2
*
* Output:
* 9
* 13
* 6
*/
public class SubarraySumQueries {
static Node[] dp = new Node[1 << 19];
static void solve() throws IOException {
int n = read.intNext(), q = read.intNext();
int[] arr = new int[n];
//dp = new Node[1 << 19];
for (int i = 0; i < dp.length; i++) {
dp[i] = new Node();
}
for (int i = 0; i < n; i++) {
arr[i] = read.intNext();
}
consturctTree(0, n - 1, 0, arr);
// for (int i = 0; i < n; i++) {
// update(0, n - 1, 0, i, read.intNext());
// }
for (int i = 0; i < q; i++) {
int a = read.intNext() - 1, b = read.intNext();
update(0, n - 1, 0, a, b);
long res = query(0, n - 1, 0, 0, n - 1);
println(max(0l, res));
}
}
static void consturctTree(int l, int h, int pos, int[] arr){
if( l == h ){
dp[pos].maxSum = dp[pos].sum = dp[pos].suffix = dp[pos].prefix = arr[l];
}else{
int mid = (h + l) / 2;
consturctTree(l, mid, 2 * pos + 1, arr);
consturctTree(mid + 1, h, 2 * pos + 2, arr);
dp[pos].sum = dp[2 * pos + 1].sum + dp[2 * pos + 2].sum;
dp[pos].prefix = Math.max(dp[2 * pos + 1].prefix, dp[2 * pos + 1].sum + dp[2 * pos + 2].prefix);
dp[pos].suffix = Math.max(dp[2 * pos + 2].suffix, dp[2 * pos + 1].suffix + dp[2 * pos + 2].sum);
dp[pos].maxSum = Math.max(Math.max(dp[2 * pos + 1].maxSum, dp[2 * pos + 2].maxSum), dp[2 * pos + 1].suffix + dp[2 * pos + 2].prefix);
}
}
static long query(int l, int h, int pos, int ql, int qh) {
if (l > qh || h < ql) return Long.MIN_VALUE;
if (l >= ql && h <= qh) return dp[pos].maxSum;
int mid = (h + l) / 2;
return (long) max(query(l, mid, 2 * pos + 1, ql, qh), query(mid + 1, h, 2 * pos + 2, ql, qh));
}
static void update(int l, int h, int pos, int tar, int value) {
if (tar < l || tar > h) return;
if (l == h) {
dp[pos].prefix = value;
dp[pos].suffix = value;
dp[pos].sum = dp[pos].maxSum = value;
return;
}
int mid = (h + l) / 2;
update(l, mid, 2 * pos + 1, tar, value);
update(mid + 1, h, 2 * pos + 2, tar, value);
dp[pos].sum = dp[2 * pos + 1].sum + dp[2 * pos + 2].sum;
dp[pos].prefix = Math.max(dp[2 * pos + 1].prefix, dp[2 * pos + 1].sum + dp[2 * pos + 2].prefix);
dp[pos].suffix = Math.max(dp[2 * pos + 2].suffix, dp[2 * pos + 1].suffix + dp[2 * pos + 2].sum);
dp[pos].maxSum = Math.max(Math.max(dp[2 * pos + 1].maxSum, dp[2 * pos + 2].maxSum), dp[2 * pos + 1].suffix + dp[2 * pos + 2].prefix);
}
static class Node {
long prefix, suffix, sum, maxSum;
public Node() {
prefix = 0;
suffix = 0;
sum = 0;
maxSum = 0;
}
}
/************************************************************************************************************************************************/
public static void main(String[] args) throws IOException {
solve();
out.close();
}
static PrintWriter out = new PrintWriter(System.out);
static Reader read = new Reader();
static StringBuilder sbr = new StringBuilder();
static int mod = (int) 1e9 + 7;
static int dmax = Integer.MAX_VALUE;
static long lmax = Long.MAX_VALUE;
static int dmin = Integer.MIN_VALUE;
static long lmin = Long.MIN_VALUE;
static class Reader {
private byte[] buf = new byte[1024];
private int index;
private InputStream in;
private int total;
public Reader() {
in = System.in;
}
public int scan() throws IOException {
if (total < 0)
throw new InputMismatchException();
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public int intNext() throws IOException {
int integer = 0;
int n = scan();
while (isWhiteSpace(n))
n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
} else throw new InputMismatchException();
}
return neg * integer;
}
public double doubleNext() throws IOException {
double doub = 0;
int n = scan();
while (isWhiteSpace(n))
n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n) && n != '.') {
if (n >= '0' && n <= '9') {
doub *= 10;
doub += n - '0';
n = scan();
} else throw new InputMismatchException();
}
if (n == '.') {
n = scan();
double temp = 1;
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
temp /= 10;
doub += (n - '0') * temp;
n = scan();
} else throw new InputMismatchException();
}
}
return doub * neg;
}
public String read() throws IOException {
StringBuilder sb = new StringBuilder();
int n = scan();
while (isWhiteSpace(n))
n = scan();
while (!isWhiteSpace(n)) {
sb.append((char) n);
n = scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
}
static void shuffle(int[] aa, int n) {
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int tmp = aa[i];
aa[i] = aa[j];
aa[j] = tmp;
}
}
static void shuffle(int[][] aa, int n) {
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int first = aa[i][0];
int second = aa[i][1];
aa[i][0] = aa[j][0];
aa[i][1] = aa[j][1];
aa[j][0] = first;
aa[j][1] = second;
}
}
/**
* Tree Multiset utility class *
*/
static class TMultiset<T extends Number> extends TreeMap<T, Integer> {
private int size = 0;
void add(T value) {
Integer count = get(value);
size++;
if (count == null) {
put(value, 1);
} else {
put(value, count + 1);
}
}
@SuppressWarnings(value = "unchecked")
@Override
public Integer remove(Object key) {
if (!containsKey(key)) {
return null;
}
size--;
Integer value = get(key);
if (value > 1) {
return put((T) key, value - 1);
}
return super.remove(key);
}
@java.lang.Override
public int size() {
return size;
}
}
/**
* It is a HashMap
*/
static class HMap<T> extends HashMap<T, Integer> {
void add(T key) {
Integer count = get(key);
put(key, count == null ? 1 : count + 1);
}
@SuppressWarnings(value = "unchecked")
@Override
public Integer remove(Object key) {
if (!containsKey(key)) return null;
int count = get(key);
if (count > 1) return put((T) key, count - 1);
return super.remove(key);
}
}
static final class Comparators {
public static final Comparator<int[]> pairIntArr =
(x, y) -> x[0] == y[0] ? compare(x[1], y[1]) : compare(x[0], y[0]);
private static final int compare(final int x, final int y) {
return Integer.compare(x, y);
}
}
static void print(Object object) {
out.print(object);
}
static void println(Object object) {
out.println(object);
}
static int min(Object... objects) {
int min = Integer.MAX_VALUE;
for (Object num : objects) {
min = Math.min(min, (Integer) num);
}
return min;
}
static Object max(Object... objects) {
boolean isInteger = objects[0] instanceof Integer;
if (isInteger) {
int max = Integer.MIN_VALUE;
for (Object num : objects) {
max = Math.max(max, (Integer) num);
}
return max;
}else{
long max = Long.MIN_VALUE;
for (Object num : objects) {
max = Math.max(max, (Long) num);
}
return max;
}
}
}
| true |
cb2fbd50306593b707394a77b3b2a9fc3e77b32e
|
Java
|
NotoriousDev/TheHiddenMC
|
/src/main/java/com/notoriousdev/thehiddenmc/commands/HiddenCommands.java
|
UTF-8
| 2,171 | 2.40625 | 2 |
[] |
no_license
|
package com.notoriousdev.thehiddenmc.commands;
import com.notoriousdev.thehiddenmc.TheHiddenMC;
import com.notoriousdev.thehiddenmc.config.TheHiddenConfig;
import com.notoriousdev.thehiddenmc.utils.Locale;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class HiddenCommands implements CommandExecutor
{
private TheHiddenMC plugin;
private TheHiddenConfig config;
private Locale locale;
private String prefix;
public HiddenCommands(TheHiddenMC plugin)
{
this.plugin = plugin;
config = plugin.getHiddenConfig();
locale = plugin.getLocale();
prefix = config.messagePrefix;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
if (label.equalsIgnoreCase("hidden"))
{
if (!sender.hasPermission("hiddenmc.admin"))
{
locale.sendNoPermission((Player) sender);
return true;
}
if (args.length == 0)
{
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', prefix + "&a/hidden reload"));
return true;
}
if (args.length > 1)
{
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', prefix + "&cToo many args!"));
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', prefix + "&a/hidden reload"));
return true;
}
if (args[0].equalsIgnoreCase("reload"))
{
config.reload();
locale.sendCommandReload((Player) sender);
return true;
}
else
{
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', prefix + "&cUnrecognised command!"));
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', prefix + "&a/hidden reload"));
return true;
}
}
return false;
}
}
| true |
0b9df3a8d4b13212818fabff9d5de0014214636c
|
Java
|
Setriakor/travis-example
|
/src/main/java/NaughtyStudent.java
|
UTF-8
| 151 | 2.53125 | 3 |
[] |
no_license
|
public class NaughtyStudent extends Student {
@Override
public Double getAverageGrade() {
return super.getAverageGrade()*1.1;
}
}
| true |
e60bfc9817b25044155bdb0f7cf74d4005aeca80
|
Java
|
Coolgiserz/MyGobang
|
/HelloGeo/src/com/coolcats1209/DataListener.java
|
GB18030
| 2,949 | 3.015625 | 3 |
[] |
no_license
|
package com.coolcats1209;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class DataListener implements ActionListener {
private JTextField textName;
private JComboBox<Character> cbSex;
private JComboBox<Integer> cbAge;
private JTextField textScore;
private JFrame frame;
public DataListener(JFrame frame, JTextField textName, JComboBox<Character> cbSex, JComboBox<Integer> cbAge,
JTextField textScore) {
this.textName = textName;
this.cbSex = cbSex;
this.cbAge = cbAge;
this.textScore = textScore;
this.frame = frame;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("")) {
readData();
} else if (e.getActionCommand().equals("")) {
writerData();
}
}
private void writerData() {
JFileChooser chooser = new JFileChooser("F:\\Learning\\Java\\IO");
chooser.showOpenDialog(frame);
File f = chooser.getSelectedFile();
if (f != null) {
OutputStream out = null;
DataOutputStream dout = null;
try {
out = new FileOutputStream(f);
dout = new DataOutputStream(out);
dout.writeUTF(textName.getText());
dout.writeChar(cbSex.getSelectedItem().toString().charAt(0));
dout.writeInt(Integer.parseInt(cbAge.getSelectedItem().toString()));
dout.writeInt(Integer.parseInt(textScore.getText()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
dout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void readData() {
JFileChooser chooser = new JFileChooser("F:\\Learning\\Java\\IO");
chooser.showOpenDialog(frame);
File f = chooser.getSelectedFile();
if (f != null) {
InputStream in = null;
DataInputStream din = null;
try {
in = new FileInputStream(f);
din = new DataInputStream(in);
String name = din.readUTF();
char sex = din.readChar();
int age = din.readInt();
int score = din.readInt();
textName.setText(name);
cbSex.setSelectedItem(sex);
cbAge.setSelectedItem(age);
textScore.setText(score+"");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
din.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
| true |
0d5dc199a3da8238ee36adfb7f1ce0ead2de0dee
|
Java
|
Qiaogh/Spring
|
/9.Validation_Data_Binding_and_Type_Conversion/9.4.Bean_manipulation_and_the_BeanWrapper/9.4.2.Built-in_PropertyEditor_implementations/Registering_additional_custom_PropertyEditors/src/main/java/com/qiaogh/editors/SimpleStringTrimmerEditor.java
|
UTF-8
| 248 | 1.765625 | 2 |
[] |
no_license
|
package com.qiaogh.editors;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
public class SimpleStringTrimmerEditor extends StringTrimmerEditor {
public SimpleStringTrimmerEditor() {
super( ",", true );
}
}
| true |
3cb47166b8598aac6d7c72c3c809f30b1e8cc803
|
Java
|
alekseivoroshilov/chatter_kursov
|
/app/src/main/java/com/example/chat/Dialog.java
|
UTF-8
| 4,329 | 2.296875 | 2 |
[] |
no_license
|
package com.example.chat;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.chat.R;
import com.example.chat.UserDetails;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import java.io.IOError;
import java.util.HashMap;
import java.util.Map;
public class Dialog extends AppCompatActivity {
//private String channelID = "firebase channel";
//private String roomName = "room-name";
private EditText editText;
LinearLayout layout_1;
RelativeLayout layout_2;
ImageView sendMessage;
EditText messageArea;
ScrollView scrollView;
Firebase reference1, reference2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
layout_1 = findViewById(R.id.layout1);
layout_2 = findViewById(R.id.layout2);
sendMessage = findViewById(R.id.sendMessage);
messageArea = findViewById(R.id.editText);
scrollView = findViewById(R.id.scrollView);
Firebase.setAndroidContext(this);
reference1 = new Firebase("https://chat-371b4.firebaseio.com/messages/" + UserDetails.username + "_" + UserDetails.chatWith);
reference2 = new Firebase("https://chat-371b4.firebaseio.com/messages/" + UserDetails.chatWith + "_" + UserDetails.username);
sendMessage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String messageText = messageArea.getText().toString();
if (!messageText.equals("")) {
Map<String, String> map = new HashMap<String, String>();
map.put("message", messageText);
map.put("user", UserDetails.username);
reference1.push().setValue(map);
reference2.push().setValue(map);
messageArea.setText("");
}
}
});
reference1.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map map = dataSnapshot.getValue(Map.class);
String message = map.get("message").toString();
String userName = map.get("user").toString();
if (userName.equals(UserDetails.username)) {
addMessageBox("You:-\n" + message, 1);
} else {
addMessageBox(UserDetails.chatWith + ":-\n" + message, 2);
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
public void addMessageBox(String message, int type){
TextView textView = new TextView(Dialog.this);
textView.setText(message);
textView.setTextColor(Color.WHITE);
textView.setPadding(19,4,13,7);
LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp2.weight = 1.0f;
if(type == 1) {
lp2.gravity = Gravity.RIGHT;
textView.setBackgroundResource(R.drawable.message_in);
}
else{
lp2.gravity = Gravity.LEFT;
textView.setBackgroundResource(R.drawable.message_out);
}
textView.setLayoutParams(lp2);
layout_1.addView(textView);
scrollView.fullScroll(View.FOCUS_DOWN);
}
}
| true |
c5d604ffda5ff075e491611ae30c3fe0a2cc8ee5
|
Java
|
Brinderjit/Mobile-Development
|
/brinderjitsingh_COMP304Lab2_Ex1/app/src/main/java/com/example/brindersaini/brinderjitsingh_comp304lab2_ex1/CustomerInfo.java
|
UTF-8
| 6,207 | 2.109375 | 2 |
[] |
no_license
|
package com.example.brindersaini.brinderjitsingh_comp304lab2_ex1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.ArrayList;
public class CustomerInfo extends AppCompatActivity {
private RadioGroup radioGroup;
private RadioButton radioButton;
private String cusineType;
private String restaurantName;
private ArrayList<String> selectedChkBx = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer_info);
Intent intent = getIntent();
cusineType = intent.getStringExtra("SelectedCuisine");
restaurantName = intent.getStringExtra("SelectedRestaurant");
selectedChkBx = intent.getStringArrayListExtra("SelectedFood");
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowCustomEnabled(true);
}
EditText creditCard = (EditText)findViewById(R.id.numberEditTxt);
creditCard.addTextChangedListener(new CreditCardNumberFormating());
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
protected void onOrderClick(View view) {
String regExpn = "^([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5})$";
String regExpnnumber = "(?:(?:\\+?1\\s*(?:[.-]\\s*)?)?(?:(\\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]\u200C\u200B)\\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\\s*(?:[.-]\\s*)?)([2-9]1[02-9]\u200C\u200B|[2-9][02-9]1|[2-9][02-9]{2})\\s*(?:[.-]\\s*)?([0-9]{4})\\s*(?:\\s*(?:#|x\\.?|ext\\.?|extension)\\s*(\\d+)\\s*)?$";
String firstname;
String lastname;
String email;
String number;
String address;
String PostelCode;
String favouritecusine;
String chef;
try {
radioGroup = (RadioGroup) findViewById(R.id.deliverRdoGrp);
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
EditText firstedit = (EditText) findViewById(R.id.firstNameEditTxt);
firstname = firstedit.getText().toString();
EditText lastedit = (EditText) findViewById(R.id.lastNameEditTxt);
lastname = lastedit.getText().toString();
EditText emailedit = (EditText) findViewById(R.id.emailEditTxt);
email = emailedit.getText().toString();
EditText numberedit = (EditText) findViewById(R.id.numberEditTxt);
number = numberedit.getText().toString();
EditText addressedit = (EditText) findViewById(R.id.addressAutoComplete);
address = addressedit.getText().toString();
EditText pinedit = (EditText) findViewById(R.id.pinCodeAutoComplete);
PostelCode = pinedit.getText().toString();
EditText cusineedit = (EditText) findViewById(R.id.autoCompleteTextView3);
favouritecusine = cusineedit.getText().toString();
EditText chefedit = (EditText) findViewById(R.id.chefEditView);
chef = chefedit.getText().toString();
if (firstname.length() == 0) {
firstedit.requestFocus();
firstedit.setError("FIELD CANNOT BE EMPTY");
} else if (lastedit.length() == 0) {
lastedit.requestFocus();
lastedit.setError("FIELD CANNOT BE EMPTY");
} else if (!email.matches(regExpn)) {
emailedit.requestFocus();
emailedit.setError("ENTER VALID EMAIL");
}
else if((numberedit.length()<16))
{
numberedit.requestFocus();
numberedit.setError("ENTER VALID NUMBER");
}
else if (addressedit.length() == 0) {
addressedit.requestFocus();
addressedit.setError("FIELD CANNOT BE EMPTY");
} else if (cusineedit.length() == 0) {
lastedit.requestFocus();
lastedit.setError("FIELD CANNOT BE EMPTY");
} else if (pinedit.length() == 0) {
lastedit.requestFocus();
lastedit.setError("FIELD CANNOT BE EMPTY");
} else if (chefedit.length() == 0) {
lastedit.requestFocus();
lastedit.setError("FIELD CANNOT BE EMPTY");
} else if (selectedId == -1) {
radioGroup.requestFocus();
radioButton = (RadioButton) findViewById(R.id.pickRdo);
radioButton.setError("Select delivery type");
} else {
Intent intent1 = new Intent(this, OrderSummery.class);
intent1.putExtra("firstname", firstname);
intent1.putExtra("lastname", lastname);
intent1.putExtra("email", email);
intent1.putExtra("number", number);
intent1.putExtra("address", address);
intent1.putExtra("PostelCode", PostelCode);
intent1.putExtra("favouritecusine", favouritecusine);
intent1.putExtra("chef", chef);
radioButton = (RadioButton) findViewById(selectedId);
String selectedTxt = radioButton.getText().toString();
intent1.putExtra("delivery", selectedTxt);
intent1.putExtra("SelectedFood", selectedChkBx);
intent1.putExtra("SelectedCuisine", cusineType);
intent1.putExtra("SelectedRestaurant", restaurantName);
startActivity(intent1);
}
} catch (Exception e) {
}
}
}
| true |
c97861977551764891897fa594ee053b4f6287b0
|
Java
|
ShirleyYeruta/Renta-Car
|
/renta-car/src/main/java/py/com/rentacar/models/Marca.java
|
UTF-8
| 1,236 | 2.328125 | 2 |
[] |
no_license
|
package py.com.rentacar.models;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
/**
* @author Miguel Martinez
**/
@Entity
@Table(name = "Marca")
public class Marca implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "descripcion")
private String descripcion;
// @OneToMany(mappedBy = "marca", fetch = FetchType.LAZY)
// private List<Vehiculo> vehiculosList;
public Marca(Integer id, String descripcion, List<Vehiculo> vehiculosList) {
this.id = id;
this.descripcion = descripcion;
// this.vehiculosList = vehiculosList;
}
public Marca() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
// public List<Vehiculo> getVehiculosList() {
// return vehiculosList;
// }
//
// public void setVehiculosList(List<Vehiculo> vehiculosList) {
// this.vehiculosList = vehiculosList;
// }
}
| true |
476b80769b98f93c6243058c0cb2181bb45382b2
|
Java
|
hanhanhanxu/RenAiClub
|
/src/cn/renai/pojo/Modular.java
|
UTF-8
| 650 | 2.21875 | 2 |
[] |
no_license
|
package cn.renai.pojo;
public class Modular {
private String mid;
private String name;
private String description;
public String getMid() {
return mid;
}
public void setMid(String mid) {
this.mid = mid == null ? null : mid.trim();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description == null ? null : description.trim();
}
}
| true |
0610c723268bdd9a70d18c22444687d6f813de10
|
Java
|
luciano-coelho/Projeto-Hibernate
|
/Sistema Vendas/src/br/com/vendas/domain/Produto.java
|
ISO-8859-2
| 2,562 | 2.53125 | 3 |
[] |
no_license
|
package br.com.vendas.domain;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/*Criar Tabela Produtos*/
@Entity
@Table(name="tb_produtos")
//Mtodo para listar
@NamedQueries({
@NamedQuery(name = "Produto.listar", query = "SELECT produto FROM Produto produto" ),
//Mtodo para Buscar
@NamedQuery(name = "Produto.buscarPorCodigo", query = "SELECT produto FROM Produto produto WHERE produto.codigo = :codigo" )
})//Fechamento NamedQuery
public class Produto {
/*Criar ID com AutoIncrement Na primeira Coluna*/
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
@Column(name="pro_codigo")
private Long codigo;
/*Gerar Demais Colunas da Tabela*/
@Column(name="pro_descricao", length=50, nullable=false)
private String descricao;
@Column(name="pro_preco", nullable=false, scale = 2, precision = 7)
private BigDecimal preco;
@Column(name="pro_quantidade", nullable=false)
private Integer quantidade;
/*Gerar chave Estrangeira*/
@JoinColumn(name = "tb_fornecedores_for_codigo", referencedColumnName = "for_codigo", nullable = false)
@ManyToOne(fetch = FetchType.EAGER)
/*Primeira Passo - Criar Objeto Fornecedor*/
private Fornecedor fornecedor;
/*Gerar Getters e Setters*/
public Long getCodigo() {
return codigo;
}
public void setCodigo(Long codigo) {
this.codigo = codigo;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public BigDecimal getPreco() {
return preco;
}
public void setPreco(BigDecimal preco) {
this.preco = preco;
}
public Integer getQuantidade() {
return quantidade;
}
public void setQuantidade(Integer quantidade) {
this.quantidade = quantidade;
}
public Fornecedor getFornecedor() {
return fornecedor;
}
public void setFornecedor(Fornecedor fornecedor) {
this.fornecedor = fornecedor;
}
@Override
public String toString() {
return "Produto [codigo=" + codigo + ", descricao=" + descricao + ", preco=" + preco + ", quantidade="
+ quantidade + ", fornecedor=" + fornecedor + "]";
}
}
| true |
dd32a3f95704a6b61dd062d86a40691702d4aa3b
|
Java
|
RenzoMarangon/juegoNaruto_Prog1
|
/ProyectoFinal_P1/src/proyecto/Colision.java
|
UTF-8
| 5,613 | 2.671875 | 3 |
[] |
no_license
|
package proyecto;
public class Colision {
public static boolean colisionRasegan(EnemigoNinja ninja , Rasengan rasengan ) {
int minimoRanseganX = rasengan.getX() - ( rasengan.getAncho()/2 ) ;
int maximoRanseganX = rasengan.getX() + ( rasengan.getAncho()/2 ) ;
int minimoRanseganY = rasengan.getY() - ( rasengan.getAlto()/2 ) ;
int maximoRanseganY = rasengan.getY() + ( rasengan.getAlto()/2 ) ;
boolean x = minimoRanseganX >= ( ninja.getX() - ninja.getAncho()/2 ) && minimoRanseganX <= ( ninja.getX() + ninja.getAncho()/2 ) ||
maximoRanseganX >= ( ninja.getX() - ninja.getAncho()/2 ) && maximoRanseganX <= ( ninja.getX() + ninja.getAncho()/2 );
boolean y= (minimoRanseganY >= (ninja.getY() - ninja.getAlto()/2 ) && minimoRanseganY < (ninja.getY() + ninja.getAlto()/2 ) ) ||
maximoRanseganY >= ( ninja.getY() - ninja.getAlto()/2 ) && maximoRanseganY <= ( ninja.getY() + ninja.getAlto()/2 );;
return x && y ;
}
public static boolean colisionSakura(EnemigoNinja ninja , Sakura sakura ,boolean direccionNinjaHorizontal) {
int minimoSakuraX = sakura.getX() - ( sakura.getAncho()/2 ) ;
int maximoSakuraX = sakura.getX() + ( sakura.getAncho()/2 ) ;
int minimoSakuraY = sakura.getY() - ( sakura.getAlto()/2 ) ;
int maximoSakuraY = sakura.getY() + ( sakura.getAlto()/2 ) ;
int horizontal=0;
int vertical=0;
if ( direccionNinjaHorizontal) {
horizontal=5;
}else {
vertical=5;
}
boolean x = minimoSakuraX >= ( ninja.getX() - ninja.getAncho()/2 ) && minimoSakuraX <= ( ninja.getX() + ninja.getAncho()/2) - horizontal ||
maximoSakuraX >= ( ninja.getX() - ninja.getAncho()/2 + horizontal ) && maximoSakuraX <= ( ninja.getX() + ninja.getAncho()/2 );
boolean y= (minimoSakuraY >= (ninja.getY() - ninja.getAlto()/2 ) && minimoSakuraY <= (ninja.getY() + ninja.getAlto()/2 ) + horizontal - vertical ) ||
(maximoSakuraY >= (ninja.getY() - ninja.getAlto()/2 + vertical) && maximoSakuraY <= (ninja.getY()+ ninja.getAlto()/2) );
return x && y ;
}
public static boolean colisionFloreroSakura(Florero florero, Sakura sakura) {
int minimoFloreroX = florero.getX() - florero.getAncho()/2;
int maximoFloreroX = florero.getX() + florero.getAncho()/2;
int minimoFloreroY = florero.getY() - florero.getAlto()/2;
int maximoFloreroY = florero.getY() + florero.getAlto()/2;
boolean x = minimoFloreroX >= (sakura.getX() - sakura.getAncho()/2) && minimoFloreroX <= (sakura.getX() + sakura.getAncho()/2) ||
maximoFloreroX >= (sakura.getX()- sakura.getAncho()/2) && maximoFloreroX <= (sakura.getX() + sakura.getAncho()/2);
boolean y = (minimoFloreroY >= (sakura.getY() - sakura.getAlto()/2) && minimoFloreroY <= (sakura.getY()+sakura.getAlto()/2) ||
(maximoFloreroY >= (sakura.getY()-sakura.getAlto()/2)) && maximoFloreroY <= (sakura.getY()+sakura.getAlto()/2));
return x && y;
}
public static boolean colisionCasaSakura(Casa casa, Sakura sakura) {
int minimoCasaX = casa.getX() - casa.getAncho()/2;
int maximoCasaX = casa.getX() + casa.getAncho()/2;
int minimoCasaY = casa.getY() - casa.getAlto()/2;
int maximoCasaY = casa.getY() + casa.getAlto()/2;
boolean x = minimoCasaX >= (sakura.getX() - sakura.getAncho()/2) && minimoCasaX <= (sakura.getX() + sakura.getAncho()/2) ||
maximoCasaX >= (sakura.getX()- sakura.getAncho()/2) && maximoCasaX <= (sakura.getX() + sakura.getAncho()/2);
boolean y = (minimoCasaY >= (sakura.getY() - sakura.getAlto()/2) && minimoCasaY <= (sakura.getY()+sakura.getAlto()/2) ||
(maximoCasaY >= (sakura.getY()-sakura.getAlto()/2)) && maximoCasaY <= (sakura.getY()+sakura.getAlto()/2));
return x && y;
}
public static boolean colisionConsumibleSakura(Consumible consumible, Sakura sakura) {
int minimoConsumibleX = consumible.getX() - consumible.getAncho()/2;
int maximoConsumibleX = consumible.getX() + consumible.getAncho()/2;
int minimoConsumibleY = consumible.getY() - consumible.getAlto()/2;
int maximoConsumibleY = consumible.getY() + consumible.getAlto()/2;
boolean x = minimoConsumibleX >= (sakura.getX() - sakura.getAncho()/2) && minimoConsumibleX <= (sakura.getX() + sakura.getAncho()/2) ||
maximoConsumibleX >= (sakura.getX()- sakura.getAncho()/2) && maximoConsumibleX <= (sakura.getX() + sakura.getAncho()/2);
boolean y = (minimoConsumibleY >= (sakura.getY() - sakura.getAlto()/2) && minimoConsumibleY <= (sakura.getY()+sakura.getAlto()/2) ||
(maximoConsumibleY >= (sakura.getY()-sakura.getAlto()/2)) && maximoConsumibleY <= (sakura.getY()+sakura.getAlto()/2));
return x && y;
}
public static boolean colisionEntreNinja(EnemigoNinja ninjaH , EnemigoNinja ninjaV ) {
int minimoNinjaHX = ninjaH.getX() - ( ninjaH.getAncho()/2 ) ;
int maximoNinjaHX = ninjaH.getX() + ( ninjaH.getAncho()/2 ) ;
int minimoNinjaHY = ninjaH.getY() - ( ninjaH.getAlto()/2 ) ;
int maximoNinjaHY = ninjaH.getY() + ( ninjaH.getAlto()/2 ) ;
boolean x = minimoNinjaHX >= ( ninjaV.getX() - ninjaV.getAncho()/2 ) && minimoNinjaHX <= ( ninjaV.getX() + ninjaV.getAncho()/2 ) ||
maximoNinjaHX >= ( ninjaV.getX() - ninjaV.getAncho()/2 ) && maximoNinjaHX <= ( ninjaV.getX() + ninjaV.getAncho()/2 );
boolean y = (minimoNinjaHY >= (ninjaV.getY() - ninjaV.getAlto()/2+20 ) && maximoNinjaHY < (ninjaV.getY() + ninjaV.getAlto()/2+20 ) ) ||
maximoNinjaHY >= ( ninjaV.getY() - ninjaV.getAlto()/2+20) && maximoNinjaHY <= ( ninjaV.getY() + ninjaV.getAlto()/2+20 );
return x && y ;
}
}
| true |
7f9af5a98b3aca9d2436a24b799aff1b16a7add3
|
Java
|
PoirotAGH/yggdrasil
|
/src/main/java/Bet.java
|
UTF-8
| 434 | 1.71875 | 2 |
[] |
no_license
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Bet {
@JsonProperty("wonamount")
String wonamount;
@JsonProperty("eventdata")
EventData eventdata;
@JsonIgnoreProperties(ignoreUnknown = true)
public class EventData {
@JsonProperty("nextCmds")
String nextCmds;
}
}
| true |
9bb4615ccf34b85c04ca392992e4bac9e41f4935
|
Java
|
ZdanovichAnastasia/Distributed-information-systems_P1
|
/lab6/src/main/java/DI/DIContainer.java
|
UTF-8
| 580 | 2.359375 | 2 |
[] |
no_license
|
package DI;
import BusinessLogic.BankService;
import BusinessLogicModels.IBankService;
import javax.xml.rpc.ServiceException;
import java.net.MalformedURLException;
public class DIContainer {
private static DIContainer container;
private DIContainer(){}
public static DIContainer getInstance(){
if(container == null)
container = new DIContainer();
return container;
}
public IBankService createBankService() throws MalformedURLException, ServiceException {
return BankService.getInstance();
}
}
| true |
1e4fb154e06b59ee959bd523631c3650b3e52d0a
|
Java
|
Cocomile97/Assignment8
|
/src/main/java/ac/za/cput/domain/Subject.java
|
UTF-8
| 1,234 | 2.953125 | 3 |
[] |
no_license
|
package ac.za.cput.domain;
public class Subject {
private String subjectId, subjectName;
private Subject(){}
private Subject(Builder builder) {
this.subjectId = builder.subjectId;
this.subjectName = builder.subjectName;
}
public String getSubjectId() {
return subjectId;
}
public String getSubjectName() {
return subjectName;
}
public static class Builder{
private String subjectId, subjectName;
public Builder subjectId(String subjectId) {
this.subjectId = subjectId;
return this;
}
public Builder subjectName(String subjectName) {
this.subjectName = subjectName;
return this;
}
public Subject.Builder copy (Subject subject){
this.subjectId = subject.subjectId;
this.subjectName = subject.subjectName;
return this;
}
public Subject build() {
return new Subject(this);
}
}
@Override
public String toString() {
return "Subject{" +
"subjectId='" + subjectId + '\'' +
", subjectName='" + subjectName + '\'' +
'}';
}
}
| true |
51d3bed76582d47557a78b9fed4bcce6d39590a9
|
Java
|
Lingy12/ip
|
/src/main/java/duke/tool/TaskList.java
|
UTF-8
| 3,213 | 3.5625 | 4 |
[] |
no_license
|
package duke.tool;
import java.util.ArrayList;
import duke.exception.TaskExistException;
import duke.task.Task;
/**
* Represents the task list stored in Duke system.
*/
public class TaskList {
/**
* List of tasks stored in system
*/
private ArrayList<Task> taskList;
/**
* Creates a task list.
*/
public TaskList() {
taskList = new ArrayList<>();
}
/**
* Creates a task list from given list.
*
* @param tasks Task list that have stored tasks.
*/
public TaskList(ArrayList<Task> tasks) {
taskList = tasks;
}
/**
* Returns the list size of task list.
*
* @return Size of current list.
*/
public int getSize() {
return this.taskList.size();
}
/**
* Adds new task into the current list.
*
* @param newTask New task to be added to the list.
* @throws TaskExistException When task's description is the same as some task in list.
*/
public void add(Task newTask) throws TaskExistException {
if (this.containsExactDescription(newTask)) {
throw new TaskExistException();
}
this.taskList.add(newTask);
}
/**
* Deletes the certain task with given index.
*
* @param index Index of task to be deleted.
* @return Task that has been deleted.
*/
public Task delete(int index) {
return this.taskList.remove(index);
}
/**
* Returns a task list.
*
* @return Task list of current object.
*/
public ArrayList<Task> getTasks() {
return this.taskList;
}
/**
* Marks the task with given element to done.
*
* @param index Index of the element.
* @return Task that has been marked as done.
*/
public Task markDone(int index) {
Task targetTask = taskList.get(index);
targetTask.markAsDone();
return targetTask;
}
/**
* Clear all task in current list.
*/
public void clear() {
taskList = new ArrayList<>();
}
/**
* Returns whehter there is exact same task in the list.
*
* @param targetTask Task that user want to add into list.
* @return True if there is a task with exact description, false otherwise.
*/
public boolean containsExactDescription(Task targetTask) {
return taskList.stream()
.anyMatch(task -> task.isExactDescription(targetTask));
}
/**
* Gets the string representation of task list in the system.
*/
public String getTaskListString() {
//Check whether there are any task in the list or not
if (taskList.isEmpty()) {
return "You haven't added any task here !";
}
return taskList.stream()
.reduce("Here are the tasks in your list: \n\t", (string, task) ->
string + buildTaskString(task), (string1, string2) ->
string1 + string2);
}
private String buildTaskString(Task task) {
assert taskList.contains(task);
return (taskList.indexOf(task) + 1) + ". "
+ task.toString() + "\n" + "\t";
}
}
| true |
5f848775b8827090e528c18f7c54a5e3e5d315f7
|
Java
|
Pradeep72767/MyKrishiMall
|
/app/src/main/java/com/example/mykrishimall/ConfirmFinalOrderActivity.java
|
UTF-8
| 5,379 | 2.171875 | 2 |
[] |
no_license
|
package com.example.mykrishimall;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.YuvImage;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.mykrishimall.Prevalent.Prevalent;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
public class ConfirmFinalOrderActivity extends AppCompatActivity {
private EditText nameEditText, phoneEditText, addressEditText, cityEditText;
private Button confirmOrderBtn;
private TextView totalAmountTextView, totalAmountShowingTextView;
private String totalAmount = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirm_final_order);
totalAmount = getIntent().getStringExtra("Total Price");
confirmOrderBtn = findViewById(R.id.confirm_final_button);
nameEditText = findViewById(R.id.shipment_customer_name);
phoneEditText = findViewById(R.id.shipment_customer_phone);
addressEditText = findViewById(R.id.shipment_customer_address);
cityEditText = findViewById(R.id.shipment_customer_city);
totalAmountTextView = findViewById(R.id.txt_total_amount);
totalAmountShowingTextView = findViewById(R.id.txt_total_amount_show);
totalAmountShowingTextView.setText(totalAmount);
confirmOrderBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
Check();
}
});
}
private void Check()
{
if (TextUtils.isEmpty(nameEditText.getText().toString()))
{
Toast.makeText(this,"Please provide your name", Toast.LENGTH_SHORT).show();
}
else if (TextUtils.isEmpty(phoneEditText.getText().toString()))
{
Toast.makeText(this,"Please provide your mobile number", Toast.LENGTH_SHORT).show();
}
else if (TextUtils.isEmpty(addressEditText.getText().toString()))
{
Toast.makeText(this,"Please provide your Address", Toast.LENGTH_SHORT).show();
}
else if (TextUtils.isEmpty(cityEditText.getText().toString()))
{
Toast.makeText(this,"Please provide your City name", Toast.LENGTH_SHORT).show();
}
else
{
ConfirmOrder();
}
}
private void ConfirmOrder()
{
final String saveCurrentTime, saveCurrentDate;
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate = currentDate.format(calForDate.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a");
saveCurrentTime = currentTime.format(calForDate.getTime());
final DatabaseReference orderRef = FirebaseDatabase.getInstance().getReference()
.child("Orders")
.child(Prevalent.currentOnlineUser.getPhone());
final HashMap<String, Object> orderMap = new HashMap<>();
orderMap.put("totalAmount",totalAmount);
orderMap.put("name",nameEditText.getText().toString());
orderMap.put("phone", phoneEditText.getText().toString());
orderMap.put("Address", addressEditText.getText().toString());
orderMap.put("City", cityEditText.getText().toString());
orderMap.put("Date", saveCurrentDate);
orderMap.put("Time", saveCurrentTime);
orderMap.put("State", "not shipped");
orderRef.updateChildren(orderMap).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task)
{
FirebaseDatabase.getInstance().getReference().child("Cart List")
.child("User View")
.child(Prevalent.currentOnlineUser.getPhone())
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(ConfirmFinalOrderActivity.this,"Order placed successfully!!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ConfirmFinalOrderActivity.this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
});
}
});
}
}
| true |
517ca864b591ba9679eabdeeb01234e622864169
|
Java
|
Gauri17k/automation-repository
|
/BasicCoreJava/src/fileHandler/ReadExcel.java
|
UTF-8
| 934 | 2.609375 | 3 |
[] |
no_license
|
package fileHandler;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ReadExcel {
public static void main(String[] args) throws IOException {
String filpath="D:\\automation-repository\\BasicCoreJava\\src\\fileHandler\\TestNG.xls";
FileInputStream file= new FileInputStream(filpath);
HSSFWorkbook wb= new HSSFWorkbook(file);// workbook
wb.getSheet("Sheet1");
HSSFSheet sheet = wb.getSheet("Sheet1"); // sheet
HSSFRow row= sheet.getRow(1);// row
HSSFCell cell= row.getCell(0);// cell
String value= cell.getStringCellValue();
System.out.println(value);
System.out.println(row.getLastCellNum());
System.out.println(sheet.getLastRowNum());
}
}
| true |
4936f07ed8db31561105a32e46282d767e06f2ea
|
Java
|
travel-cloud/java-memcached-client
|
/src/main/java/net/spy/memcached/internal/HttpFuture.java
|
UTF-8
| 4,268 | 2.015625 | 2 |
[
"MIT"
] |
permissive
|
/**
* Copyright (C) 2009-2011 Couchbase, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
* IN THE SOFTWARE.
*/
package net.spy.memcached.internal;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import net.spy.memcached.OperationTimeoutException;
import net.spy.memcached.compat.SpyObject;
import net.spy.memcached.ops.OperationStatus;
import net.spy.memcached.protocol.couch.HttpOperation;
/**
* A future http response.
*/
public class HttpFuture<T> extends SpyObject implements Future<T> {
protected final AtomicReference<T> objRef;
protected final CountDownLatch latch;
protected final long timeout;
protected OperationStatus status;
protected HttpOperation op;
public HttpFuture(CountDownLatch latch, long timeout) {
super();
this.objRef = new AtomicReference<T>(null);
this.latch = latch;
this.timeout = timeout;
this.status = null;
}
public boolean cancel(boolean c) {
op.cancel();
return true;
}
@Override
public T get() throws InterruptedException, ExecutionException {
try {
return get(timeout, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
status = new OperationStatus(false, "Timed out");
throw new RuntimeException("Timed out waiting for operation", e);
}
}
@Override
public T get(long duration, TimeUnit units) throws InterruptedException,
ExecutionException, TimeoutException {
if (!latch.await(duration, units)) {
if (op != null) {
op.timeOut();
}
status = new OperationStatus(false, "Timed out");
throw new TimeoutException("Timed out waiting for operation");
}
if (op != null && op.hasErrored()) {
status = new OperationStatus(false, op.getException().getMessage());
throw new ExecutionException(op.getException());
}
if (op.isCancelled()) {
status = new OperationStatus(false, "Operation Cancelled");
throw new ExecutionException(new RuntimeException("Cancelled"));
}
if (op != null && op.isTimedOut()) {
status = new OperationStatus(false, "Timed out");
throw new ExecutionException(new OperationTimeoutException(
"Operation timed out."));
}
return objRef.get();
}
public OperationStatus getStatus() {
if (status == null) {
try {
get();
} catch (InterruptedException e) {
status = new OperationStatus(false, "Interrupted");
Thread.currentThread().isInterrupted();
} catch (ExecutionException e) {
getLogger().warn("Error getting status of operation", e);
}
}
return status;
}
public void set(T oper, OperationStatus s) {
objRef.set(oper);
status = s;
}
@Override
public boolean isDone() {
assert op != null : "No operation";
return latch.getCount() == 0 || op.isCancelled() || op.hasErrored();
}
public void setOperation(HttpOperation to) {
this.op = to;
}
@Override
public boolean isCancelled() {
assert op != null : "No operation";
return op.isCancelled();
}
}
| true |
e8015292e931b6142ca0f7440b4d9b1052f235c7
|
Java
|
AlexSlow/GSM_SERVER
|
/main/java/nio3/kbs/gsm_scan_server/factory/AlgoritmFactory.java
|
UTF-8
| 263 | 1.734375 | 2 |
[] |
no_license
|
package nio3.kbs.gsm_scan_server.factory;
import nio3.kbs.gsm_scan_server.algoritm.Algoritm;
import org.springframework.stereotype.Component;
@Component
public class AlgoritmFactory {
public Algoritm factory()
{
return null;
}
}
| true |
d781b49550b7b62e5bada36e2f1094330f2c3db1
|
Java
|
Cascading/cascading
|
/cascading-xml/src/test/java/cascading/operation/xml/XPathTest.java
|
UTF-8
| 4,535 | 2.0625 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2007-2017 Xplenty, Inc. All Rights Reserved.
*
* Project and contact information: http://www.cascading.org/
*
* This file is part of the Cascading project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cascading.operation.xml;
import java.io.IOException;
import java.util.Iterator;
import cascading.CascadingTestCase;
import cascading.operation.Filter;
import cascading.operation.Function;
import cascading.tuple.Fields;
import cascading.tuple.Tuple;
import org.junit.Test;
/**
*
*/
public class XPathTest extends CascadingTestCase
{
public XPathTest()
{
}
@Test
public void testParserMultipleXPaths() throws IOException
{
String[][] namespaces = {new String[]{"a", "http://foo.com/a"},
new String[]{"b", "http://bar.com/b"}};
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<document xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:a=\"http://foo.com/a\" xmlns:b=\"http://bar.com/b\" xmlns=\"http://baz.com/c\">" +
" <a:top>" +
" <a:first>first-value</a:first>" +
" <a:second>" +
" <b:top-first>nested-top-first</b:top-first>" +
" <b:top-second>nested-top-second</b:top-second>" +
" </a:second>" +
" </a:top>" +
"</document>";
Function function = new XPathParser( new Fields( "first", "second" ), namespaces, "//a:top/a:first/text()", "//a:second/b:top-second/text()" );
Tuple tuple = invokeFunction( function, new Tuple( xml ), new Fields( "first", "second" ) ).iterator().next();
assertEquals( "first-value", tuple.getString( 0 ) );
assertEquals( "nested-top-second", tuple.getString( 1 ) );
}
@Test
public void testGeneratorMultipleXPaths() throws IOException
{
String[][] namespaces = {new String[]{"a", "http://foo.com/a"},
new String[]{"b", "http://bar.com/b"}};
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<document xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:a=\"http://foo.com/a\" xmlns:b=\"http://bar.com/b\" xmlns=\"http://baz.com/c\">" +
" <a:top>" +
" <a:first>first-value</a:first>" +
" <a:first>first-value</a:first>" +
" <a:second>" +
" <b:top-first>nested-top-first</b:top-first>" +
" <b:top-second>nested-top-second</b:top-second>" +
" </a:second>" +
" </a:top>" +
"</document>";
Function function = new XPathGenerator( new Fields( "first" ), namespaces, "//a:top/a:first/text()", "//a:second/b:top-second/text()" );
Iterator<Tuple> tupleIterator = invokeFunction( function, new Tuple( xml ), new Fields( "first" ) ).iterator();
assertEquals( "first-value", tupleIterator.next().getString( 0 ) );
assertEquals( "first-value", tupleIterator.next().getString( 0 ) );
assertEquals( "nested-top-second", tupleIterator.next().getString( 0 ) );
}
@Test
public void testFilterXPaths()
{
String[][] namespaces = {new String[]{"a", "http://foo.com/a"},
new String[]{"b", "http://bar.com/b"}};
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<document xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:a=\"http://foo.com/a\" xmlns:b=\"http://bar.com/b\" xmlns=\"http://baz.com/c\">" +
" <a:top>" +
" <a:first>first-value</a:first>" +
" <a:second>" +
" <b:top-first>nested-top-first</b:top-first>" +
" <b:top-second>nested-top-second</b:top-second>" +
" </a:second>" +
" </a:top>" +
"</document>";
Filter filter = new XPathFilter( namespaces, "//a:top/a:first/text() != 'first-value'" );
assertTrue( invokeFilter( filter, new Tuple( xml ) ) );
}
}
| true |
6af00452312e295f722acc379a3f822b08b0dc64
|
Java
|
Ahmeda3001/LSP
|
/HelloWorld/src/org/howard/edu/lsp/assignment7/tollbooth/AlleghenyTollBooth.java
|
UTF-8
| 1,740 | 3.3125 | 3 |
[] |
no_license
|
package org.howard.edu.lsp.assignment7.tollbooth;
/**
* AlleghenyTollBooth class which implements the TollBooth interface
* @author ahmed
*
*/
public class AlleghenyTollBooth implements TollBooth {
private int totalTolls = 0;
private int totalTrucks = 0;
/**
* getter for the totalTolls attribute
* @return the integer totalTolls
*/
public int getToll() {
return totalTolls;
}
/**
* getter for the totalTrucks attribute
* @return the integer for totalTrucks
*/
public int getTrucks() {
return totalTrucks;
}
/**
* override for calculateToll method from the tollBooth interface
* @return the calculation message as a string
*/
public String calculateToll(Truck x) {
int truckAxles = x.getAxels();
int truckWeight = x.getWeight();
int axleCost = truckAxles * 5;
int halfTons = truckWeight / 1000;
int totalCost = axleCost + (halfTons * 10);
totalTolls += totalCost;
totalTrucks += 1;
String tollMssg = "Truck arrival - Axels: " + truckAxles + " Total Weight: " + truckWeight + " Toll due: $" + totalCost;
return tollMssg;
}
/**
* override for the displayData method from the tollBooth interface
* @return the display message as a string
*/
public String displayData() {
String displayMssg = "Totals since the last collection - receipts: $" + totalTolls + " Trucks: " + totalTrucks;
return displayMssg;
}
/**
* override for the reset method from the tollBooth interface
* @return the reset message as a string
*/
public String reset() {
String resetMssg = "*** Collecting receipts ***\n Totals since the last collection - receipts: $" + totalTolls + " Trucks: " + totalTrucks;
totalTolls = 0;
totalTrucks = 0;
return resetMssg;
}
}
| true |
2c403dbe964fc1de1c5cfe7561d86a756ec79c62
|
Java
|
Iridium232/settlers-of-catan
|
/src/shared/communication/toServer/moves/BuildRoad.java
|
UTF-8
| 850 | 2.671875 | 3 |
[] |
no_license
|
package shared.communication.toServer.moves;
import shared.communication.EdgeLocation;
/**
* Michael Rhodes
* CS 340
* Section 2
* Team 10
*
* buildRoad command object
*/
public class BuildRoad extends Command {
private EdgeLocation roadLocation;
/** Whether this is placed for free (setup) */
private boolean free;
public BuildRoad(int playerIndex, EdgeLocation roadLocation, boolean free) {
super("buildRoad", playerIndex);
this.roadLocation = roadLocation;
this.free = free;
}
public EdgeLocation getRoadLocation() {
return roadLocation;
}
public void setRoadLocation(EdgeLocation roadLocation) {
this.roadLocation = roadLocation;
}
public boolean isFree() {
return free;
}
public void setFree(boolean free) {
this.free = free;
}
}
| true |
e4c7b6ff25ca502cb966ac3e9864c98dbb809f4f
|
Java
|
lyk1576070851/bytemarket
|
/src/main/java/com/android/bytemarket/common/FileUpload.java
|
UTF-8
| 2,775 | 2.28125 | 2 |
[] |
no_license
|
package com.android.bytemarket.common;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;
import java.util.List;
/**
* @author: 15760
* @Date: 2019/12/1
* @Descripe: 将文件上传到七牛云存储上
*/
@Component
public class FileUpload {
static String accessKey = "6sLzFMI1OuMEabWiej9QZ7p1NRK0OYR5tv808xVn";
static String secretKey = "lmr9I8cQVlPEL8YVFNFkPVqCnkOZ--CHWBNxvj9X";
// 需要上传的空间名
static String bucket = "lequal";
static String key = null;
// 密钥配置
//static Auth auth = Auth.create(accessKey, secretKey);
// 创建上传对象
static UploadManager uploadManager = new UploadManager(new Configuration(Region.autoRegion()));
/**
* @param file
* @return
*/
public static String upLoad(MultipartFile file) throws IOException {
DefaultPutRet putRet = null;
try {
byte[] uploadBytes = file.getBytes();
ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(byteInputStream,key,upToken,null, null);
// 解析上传成功的结果
putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
// ignore
}
}
} catch (UnsupportedEncodingException ex) {
// ignore
}
return String.format("http://q2caan54b.bkt.clouddn.com/%s",putRet==null?"":putRet.hash);
}
public static String[] upLoads(MultipartFile[] files) throws IOException {
if (files.length < 1){
return null;
}
List<String> list = new LinkedList<>();
for (MultipartFile file : files) {
String url = upLoad(file);
list.add(url);
}
return list.toArray(new String[files.length]);
}
}
| true |
b747d0dd54b11ebe0eace3c25f66b24785e957c4
|
Java
|
biubiubiiu/hust
|
/3-大二上/面向对象课设-植物大战僵尸/PVZ/src/game/model/plants/SunSmall.java
|
UTF-8
| 299 | 2.5 | 2 |
[
"MIT"
] |
permissive
|
package game.model.plants;
class SunSmall extends Sun
{
SunSmall(int x, int y_from, int y_to) // size - 阳光的尺寸,0为正常,1为小阳光
{
super(x, y_from, y_to);
//System.out.println("生成小阳光");
setName("sun_s");
contain = 15;
}
}
| true |
b8b8d1a75d154d248f8a49b68c57369ea7e56614
|
Java
|
Kuangcp/java-wheel
|
/spring/src/main/java/com/github/kuangcp/spring/beans/factory/xml/XMLPropertyConstants.java
|
UTF-8
| 708 | 1.632813 | 2 |
[] |
no_license
|
package com.github.kuangcp.spring.beans.factory.xml;
/**
* @author https://github.com/kuangcp on 2019-12-06 07:56
*/
public interface XMLPropertyConstants {
String ID_ATTRIBUTE = "id";
String CLASS_ATTRIBUTE = "class";
String SCOPE_ATTRIBUTE = "scope";
String PROPERTY_ATTRIBUTE = "property";
String REF_ATTRIBUTE = "ref";
String VALUE_ATTRIBUTE = "value";
String NAME_ATTRIBUTE = "name";
String CONSTRUCTOR_ARG_ELEMENT = "constructor-arg";
String TYPE_ATTRIBUTE = "type";
String BEANS_NAMESPACE_URI = "http://www.springframework.org/schema/beans";
String CONTEXT_NAMESPACE_URI = "http://www.springframework.org/schema/context";
String BASE_PACKAGE_ATTRIBUTE = "base-package";
}
| true |
375fcfd3c91b8e37fa226a34ebdaefcbb316e075
|
Java
|
ybz216/juzu
|
/plugins/shiro/src/main/java/juzu/plugin/shiro/impl/common/RememberMeUtil.java
|
UTF-8
| 6,680 | 1.851563 | 2 |
[] |
no_license
|
/*
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package juzu.plugin.shiro.impl.common;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import juzu.impl.bridge.spi.servlet.ServletWebBridge;
import juzu.impl.request.Request;
import juzu.request.HttpContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.crypto.AesCipherService;
import org.apache.shiro.crypto.CipherService;
import org.apache.shiro.io.DefaultSerializer;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
/**
* @author <a href="mailto:[email protected]">Nguyen Thanh Hai</a>
* @version $Id$
*
*/
public class RememberMeUtil {
/**
* The default name of the underlying rememberMe cookie which is
* {@code rememberMe}.
*/
private final static String DEFAULT_REMEMBER_ME_COOKIE_NAME = "rememberMe";
/**
* The value of deleted cookie (with the maxAge 0).
*/
private final static String DELETED_COOKIE_VALUE = "deleteMe";
/**
* The number of seconds in one year (= 60 * 60 * 24 * 365).
*/
private final static int ONE_YEAR = 60 * 60 * 24 * 365;
/** . */
private final static long DAY_MILLIS = 86400000; // 1 day = 86,400,000
// milliseconds
/** . */
private final static String GMT_TIME_ZONE_ID = "GMT";
/** . */
private final static String COOKIE_DATE_FORMAT_STRING = "EEE, dd-MMM-yyyy HH:mm:ss z";
/** . */
private final static String NAME_VALUE_DELIMITER = "=";
/** . */
private final static String ATTRIBUTE_DELIMITER = "; ";
/** . */
private final static String COOKIE_HEADER_NAME = "Set-Cookie";
/** . */
private final static String PATH_ATTRIBUTE_NAME = "Path";
/** . */
private final static String EXPIRES_ATTRIBUTE_NAME = "Expires";
/** . */
private final static String MAXAGE_ATTRIBUTE_NAME = "Max-Age";
/** . */
private final static String DOMAIN_ATTRIBUTE_NAME = "Domain";
public static void rememberSerialized() {
HttpContext context = Request.getCurrent().getHttpContext();
if (context instanceof ServletWebBridge) {
ServletWebBridge bridge = (ServletWebBridge) context;
// base 64 encode it and store as a cookie:
DefaultSerializer<PrincipalCollection> serializer = new DefaultSerializer<PrincipalCollection>();
byte[] serialized = serializer.serialize(SecurityUtils.getSubject().getPrincipals());
serialized = encrypt(serialized);
String base64 = Base64.encodeToString(serialized);
String name = DEFAULT_REMEMBER_ME_COOKIE_NAME;
String value = base64;
String domain = context.getServerName();
String path = context.getContextPath();
int maxAge = ONE_YEAR; // always zero for deletion
final String headerValue = buildHeaderValue(name, value, domain.trim(), path.trim(), maxAge);
bridge.getResponse().setHeader(COOKIE_HEADER_NAME, headerValue);
}
}
public static void forgetIdentity() {
HttpContext context = Request.getCurrent().getHttpContext();
if (context instanceof ServletWebBridge) {
ServletWebBridge bridge = (ServletWebBridge) context;
String name = DEFAULT_REMEMBER_ME_COOKIE_NAME;
String value = DELETED_COOKIE_VALUE;
String domain = context.getServerName();
String path = context.getContextPath();
int maxAge = 0; // always zero for deletion
final String headerValue = buildHeaderValue(name, value, domain.trim(), path.trim(), maxAge);
bridge.getResponse().setHeader(COOKIE_HEADER_NAME, headerValue);
}
}
private static String buildHeaderValue(String name, String value, String domain, String path, int maxAge) {
StringBuilder sb = new StringBuilder(name).append(NAME_VALUE_DELIMITER);
if (value != null && !value.isEmpty()) {
sb.append(value);
}
if (domain != null && !domain.isEmpty()) {
sb.append(ATTRIBUTE_DELIMITER);
sb.append(DOMAIN_ATTRIBUTE_NAME).append(NAME_VALUE_DELIMITER).append(domain);
}
if (path != null && !path.isEmpty()) {
sb.append(ATTRIBUTE_DELIMITER);
sb.append(PATH_ATTRIBUTE_NAME).append(NAME_VALUE_DELIMITER).append(path);
}
if (maxAge >= 0) {
sb.append(ATTRIBUTE_DELIMITER);
sb.append(MAXAGE_ATTRIBUTE_NAME).append(NAME_VALUE_DELIMITER).append(maxAge);
sb.append(ATTRIBUTE_DELIMITER);
Date expires;
if (maxAge == 0) {
// delete the cookie by specifying a time in the past (1 day ago):
expires = new Date(System.currentTimeMillis() - DAY_MILLIS);
} else {
// Value is in seconds. So take 'now' and add that many seconds, and
// that's our expiration date:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, maxAge);
expires = cal.getTime();
}
String formatted = toCookieDate(expires);
sb.append(EXPIRES_ATTRIBUTE_NAME).append(NAME_VALUE_DELIMITER).append(formatted);
}
return sb.toString();
}
/**
* Formats a date into a cookie date compatible string (Netscape's
* specification).
*
* @param date
* the date to format
* @return an HTTP 1.0/1.1 Cookie compatible date string (GMT-based).
*/
private static String toCookieDate(Date date) {
TimeZone tz = TimeZone.getTimeZone(GMT_TIME_ZONE_ID);
DateFormat fmt = new SimpleDateFormat(COOKIE_DATE_FORMAT_STRING, Locale.US);
fmt.setTimeZone(tz);
return fmt.format(date);
}
private static byte[] encrypt(byte[] serialized) {
byte[] value = serialized;
CipherService cipherService = new AesCipherService();
if (cipherService != null) {
ByteSource byteSource = cipherService.encrypt(serialized, Base64.decode("kPH+bIxk5D2deZiIxcaaaA=="));
value = byteSource.getBytes();
}
return value;
}
}
| true |
a2f99f0f7097beab03e290565d9104279c43d5ce
|
Java
|
victorangelo12/dddnac1e2
|
/Nac1e2Ddd/src/br/com/fiap/ads/ddd/dao/VeiculoDAO.java
|
ISO-8859-1
| 3,123 | 2.71875 | 3 |
[] |
no_license
|
package br.com.fiap.ads.ddd.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import br.com.fiap.ads.ddd.to.Veiculo;
/**
*
* @author Victor Angelo RM 77917 e Nicole Bono RM76188
*
*/
public class VeiculoDAO {
// INCLUIR VEICULO
/**
* Inclui um veiculo no banco de dados
* @param veiculo(modelo,placa,ano,motor)
* @throws SQLException
*/
public void incluir(Veiculo veiculo) throws SQLException {
Connection conn = null;
try {
conn = ConnectionManager.getInstance().getConnection();
PreparedStatement stmtInsert = conn.prepareStatement("INSERT INTO TB_VEICULO (id_veiculo,modelo,placa,ano,motor) VALUES (sq_veiculo.NEXTVAL,?,?,?,?)");
// define os valores do parametro
stmtInsert.setString(1, veiculo.getModelo());
stmtInsert.setString(2, veiculo.getPlaca());
stmtInsert.setInt(3, veiculo.getAno());
stmtInsert.setDouble(4, veiculo.getMotor());
stmtInsert.executeUpdate();
} catch (SQLException e) {
throw new SQLException(); // mdf
} finally {
if (conn != null) // condio se tem uma conexo aberta
try {
conn.close(); // fecha
} catch (SQLException e2) {
throw new SQLException();
}
}
}
// EXCLUIR VEICULO
/**
* Exclui um veiculo do banco de dados pela placa
* @param placa
* @exception SQLException
*/
public void excluir(String placa) {
Connection conn = null;
try {
conn = ConnectionManager.getInstance().getConnection();
PreparedStatement stmtDelete = conn.prepareStatement("DELETE FROM TB_VEICULO WHERE PLACA=?");
// define os valores dos parametros, no caso a placa do veiculo
stmtDelete.setString(1, placa);
// Executa o comando de delete
stmtDelete.executeUpdate();
} catch (SQLException e) {
System.err.println("Erro ao deletar veiculo");
} finally {
if (conn != null) // condio se tem uma conexo aberta
try {
conn.close(); // fecha
} catch (SQLException e2) {
System.err.println("Erro ao fechar conexo");
}
}
}
// ALTERAR VEICULO
/**
* Altera a placa do veiculo
* @param placaAntiga
* @param placaNova
* @exception SQLException
*/
public void alterar(String placaAntiga, String placaNova) throws SQLException {
Connection conn = null;
//
// SQL
//
try {
// pega a conexao como banco
conn = ConnectionManager.getInstance().getConnection();
PreparedStatement stmtInsert = conn.prepareStatement("UPDATE TB_VEICULO SET PLACA=? WHERE PLACA=?");
// Define os valores dos parametros
stmtInsert.setString(1, placaNova);
stmtInsert.setString(2, placaAntiga);
// executa a SQL
stmtInsert.executeUpdate();// execucao com commit
} catch (SQLException e) {
throw new SQLException();
} finally {
if (conn != null) {// se ha uma conexao, fecha ela
try {
//
// Fecha a conexao com o SGBDR
//
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
| true |
90556129c0e43482da41af078e9afba11c281255
|
Java
|
bbblu/camping-backend
|
/src/main/java/tw/edu/ntub/imd/camping/dto/file/excel/column/Column.java
|
UTF-8
| 772 | 2.515625 | 3 |
[] |
no_license
|
package tw.edu.ntub.imd.camping.dto.file.excel.column;
import tw.edu.ntub.imd.camping.dto.file.excel.cell.Cell;
import tw.edu.ntub.imd.camping.dto.file.excel.range.Range;
import tw.edu.ntub.imd.camping.dto.file.excel.sheet.Sheet;
import tw.edu.ntub.imd.camping.dto.file.excel.workbook.Workbook;
public interface Column extends Range {
Object getOriginalObject();
Workbook getWorkbook();
Sheet getSheet();
int getIndex();
String getName();
default boolean isNameEquals(String columnName) {
String name = getName();
return name.equals(columnName);
}
Cell getCellByRowIndex(int rowIndex);
default Cell getCellByRowNumber(int rowNumber) {
return getCellByRowIndex(rowNumber - 1);
}
void clear();
}
| true |
40b412ec5cc548f30faec82419200c20d50b3dda
|
Java
|
tesseract-job/scepter
|
/spring-boot-starter-scepter-server/src/main/java/com/kevin/scepter/springboot/server/config/ServerProperties.java
|
UTF-8
| 1,705 | 2.4375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.kevin.scepter.springboot.server.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author: kevin
* @description: 服务端配置项目
* @updateRemark: 修改内容(每次大改都要写修改内容)
* @date: 2019-08-05 14:52
*/
@ConfigurationProperties(prefix = "socket.server")
public class ServerProperties {
/**
* 读空闲时间设定,单位(秒)
*/
private int readerIdleTime = 20;
/**
* 端口号
*/
private int port;
/**
* 默认扫描的包路径
*/
private String basePackages;
/**
* 是否打印慢方法
*/
private boolean slowMethod = false;
/**
* 慢方法的耗时阈值,单位(毫秒)
*/
private long slowMethodMillis = 1000L;
/**
* 序列化协议
*/
private Integer serializeType;
public Integer getSerializeType() {
return serializeType;
}
public void setSerializeType(Integer serializeType) {
this.serializeType = serializeType;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getBasePackages() {
return basePackages;
}
public void setBasePackages(String basePackages) {
this.basePackages = basePackages;
}
public int getReaderIdleTime() {
return readerIdleTime;
}
public void setReaderIdleTime(int readerIdleTime) {
this.readerIdleTime = readerIdleTime;
}
public long getSlowMethodMillis() {
return slowMethodMillis;
}
public void setSlowMethodMillis(long slowMethodMillis) {
this.slowMethodMillis = slowMethodMillis;
}
public boolean isSlowMethod() {
return slowMethod;
}
public void setSlowMethod(boolean slowMethod) {
this.slowMethod = slowMethod;
}
}
| true |
6ea4ba510792fabf505c726ff9c7d5beab2d3046
|
Java
|
lsylive/DataAnalysis
|
/analysisTemplate/src/com/liusy/analysismodel/template/actions/UndoRetargetAction.java
|
UTF-8
| 751 | 1.882813 | 2 |
[] |
no_license
|
package com.liusy.analysismodel.template.actions;
import java.text.MessageFormat;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.LabelRetargetAction;
import com.liusy.analysis.template.model.util.StringUtil;
public class UndoRetargetAction extends LabelRetargetAction {
public UndoRetargetAction() {
super(StringUtil.undoId,MessageFormat.format(ActionMessages.UndoAction_Label,new Object[] {""}).trim()); //$NON-NLS-1$
ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
setImageDescriptor(sharedImages.getImageDescriptor(ISharedImages.IMG_TOOL_UNDO));
setDisabledImageDescriptor(sharedImages.getImageDescriptor(
ISharedImages.IMG_TOOL_UNDO_DISABLED));
}
}
| true |
ebf6eb6f24c8a97c8962ca253fbd934598ddca98
|
Java
|
serhan-yilmaz/sygfx
|
/src/sygfx/ScaledGraphics.java
|
UTF-8
| 13,082 | 2.34375 | 2 |
[] |
no_license
|
/*
* Copyright (C) 2016 Serhan Yılmaz
*
* This file is part of FamilyTree
*
* FamilyTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FamilyTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package sygfx;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.Rectangle2D;
import java.awt.image.ImageObserver;
import sygfx.util.Anchor;
import sygfx.util.Rectangle;
import sygfx.util.RectangleD;
/**
*
* @author Serhan
*/
public class ScaledGraphics {
public static int NORTH_ANCHOR = 1;
public static int NORTHWEST_ANCHOR = 2;
public static int NORTHEAST_ANCHOR = 3;
public static int SOUTH_ANCHOR = 4;
public static int SOUTHWEST_ANCHOR = 5;
public static int SOUTHEAST_ANCHOR = 6;
public static int MIDDLE_ANCHOR = 7;
public static int WEST_ANCHOR = 8;
public static int EAST_ANCHOR = 9;
private Anchor anchor = Anchor.SOUTHWEST;
private final Graphics g;
private final Graphics2D g2;
private final FontRenderContext frc;
private final Scale s;
private boolean dynamicStroke = false;
private BasicStroke baseStroke = null;
private boolean dynamicRectPositioning = false;
private int dynamicStrokeWidth = 0;
// private class ScaledString{
//
// public ScaledString(Font
//
//
// }
public ScaledGraphics(Graphics g, Scale s){
this.g = g;
this.g2 = (Graphics2D) g;
this.frc = g2.getFontRenderContext();
this.s = s;
}
public ScaledGraphics(ScaledGraphics sg, Scale s){
this.g = sg.g;
this.g2 = sg.g2;
this.frc = g2.getFontRenderContext();
this.s = sg.s.scale(s);
}
public void setColor(Color c){
g.setColor(c);
}
public Color getColor(){
return g2.getColor();
}
public void setFont(Font f){
g.setFont(f);
}
public void drawLine(int x1, int y1, int x2, int y2){
g.drawLine(getScale().cX(x1), getScale().cY(y1), getScale().cX(x2), getScale().cY(y2));
}
public void drawRect(int x, int y, int width, int height){
Rectangle r = transform(x, y, width, height, Anchor.NORTHWEST).toRectangle();
if(dynamicStroke && dynamicRectPositioning){
// r = doRectPositioning(r);
drawRectLines(r);
} else {
// Rectangle r = rd.toRectangle();
g.drawRect(r.x, r.y, r.width, r.height);
}
}
private void drawRectLines(Rectangle r){
Stroke s = g2.getStroke();
Color color = g.getColor();
int hstroke = calculateDynamicStroke(baseStroke, 90);
int vstroke = calculateDynamicStroke(baseStroke, 0);
// int hstroke = dynamicStrokeWidth;
// int vstroke = dynamicStrokeWidth;
double hwl = (hstroke) / 2.0 - 1;
// int hwu = hstroke - hwl;
double hwu = hwl;
double vwl = (vstroke) / 2.0 - 1;
// int vwu = vstroke - vwl;
double vwu = vwl;
g.setColor(Color.black);
g.fillRect(r.x - 1, r.y - 1, r.width + 1, vstroke + 1);
g.fillRect(r.x - 1, r.y - 1 + r.height - vstroke, r.width + 1, vstroke + 1);
g.fillRect(r.x - 1, r.y - 1, hstroke + 1, r.height + 1);
g.fillRect(r.x - 1 + r.width - hstroke, r.y - 1, hstroke + 1, r.height + 1);
// adjustDynamicStroke(baseStroke, hstroke);
// g.drawLine(round(x + hwl), round(y + hwl), round(x + width - hwu) , round(y + hwl));
// g.drawLine(round(x + hwl), round(y + height - hwu), round(x + width - hwu) , round(y + height - hwu));
// adjustDynamicStroke(baseStroke, vstroke);
// g.drawLine(round(x + vwl), round(y + vwl), round(x + vwl), round(y + height - vwu));
// g.drawLine(round(x + width - vwu), round(y + vwl), round(x + width - vwu), round(y + height - vwu));
// adjustDynamicStroke(baseStroke, hstroke);
// g.drawLine(floor(x + hwl), floor(y + hwl), ceil(x + width - hwu) , floor(y + hwl));
// g.drawLine(floor(x + hwl), ceil(y + height - hwu), ceil(x + width - hwu) , ceil(y + height - hwu));
// adjustDynamicStroke(baseStroke, vstroke);
// g.drawLine(floor(x + vwl), floor(y + vwl), floor(x + vwl), ceil(y + height - vwu));
// g.drawLine(ceil(x + width - vwu), floor(y + vwl), ceil(x + width - vwu), ceil(y + height - vwu));
g2.setStroke(s);
g2.setColor(color);
}
private int floor(double d){
return (int) Math.floor(d);
}
private int ceil(double d){
return (int) Math.ceil(d);
}
private int round(double d){
return (int) Math.round(d);
}
public void fillRect(int x, int y, int width, int height){
Rectangle r = transform(x, y, width, height, Anchor.NORTHWEST).toRectangle();
g.fillRect(r.x, r.y, r.width, r.height);
}
public void drawOval(int x, int y, int width, int height){
Rectangle r = transform(x, y, width, height, Anchor.NORTHWEST).toRectangle();
g.drawOval(r.x, r.y, r.width, r.height);
}
public void fillOval(int x, int y, int width, int height){
Rectangle r = transform(x, y, width, height, Anchor.NORTHWEST).toRectangle();
g.fillOval(r.x, r.y, r.width, r.height);
}
public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle){
Rectangle r = transform(x, y, width, height, Anchor.NORTHWEST).toRectangle();
g.drawArc(r.x, r.y, r.width, r.height, startAngle, arcAngle);
}
public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle){
Rectangle r = transform(x, y, width, height, Anchor.NORTHWEST).toRectangle();
g.fillArc(r.x, r.y, r.width, r.height, startAngle, arcAngle);
}
public void drawString(String text, int x, int y){
drawString(g, getScale(), text, x, y, anchor);
}
public static void drawString(Graphics g, Scale s, String text, int x, int y, Anchor target_anchor){
Graphics2D g2 = (Graphics2D) g;
Font myfont = g2.getFont();
FontRenderContext frc = g2.getFontRenderContext();
int fx = (int) (myfont.getSize() * s.getXScaling());
int fy = (int) (myfont.getSize() * s.getYScaling());
Font newFont = myfont.deriveFont((float)Math.min(fx, fy));
g.setFont(newFont);
GlyphVector gv = newFont.createGlyphVector(frc, text);
Rectangle2D box = gv.getVisualBounds();
Dimension dim = new Dimension((int) box.getWidth(), (int) box.getHeight());
Point p = new Point(s.cX(x), s.cY(y));
Point p1 = target_anchor.transform(p, dim, Anchor.SOUTHWEST);
// Point p2 = target_anchor.transform(p, dim, Anchor.NORTHWEST);
// Rectangle r = transform(x, y, (int) box.getWidth(), (int) box.getHeight(), Anchor.SOUTHWEST, target_anchor, s).toRectangle();
// Rectangle r2 = transform(x, y, (int) box.getWidth(), (int) box.getHeight(), Anchor.NORTHWEST, target_anchor, s).toRectangle();
// g2.setStroke(new BasicStroke(1));
// g2.drawRect(p2.x, p2.y, dim.width, dim.height);
// g2.setFont(newFont);
g2.drawString(text, p1.x, p1.y);
g2.setFont(myfont);
}
public Rectangle2D getEstimatedTextArea(String text){
Font font = g2.getFont();
GlyphVector gv = font.createGlyphVector(frc, text);
Rectangle2D box = gv.getVisualBounds();
return box;
}
public void drawStringArea(String text, int x, int y, int width, int height){
int w = getScale().cXD(width);
int h = getScale().cYD(height);
Font myfont = g2.getFont();
GlyphVector gv = myfont.createGlyphVector(frc, text);
Rectangle2D box = gv.getVisualBounds();
int fx = (int) (Math.floor(0.9 * myfont.getSize2D() * w / box.getWidth()));
int fy = (int) (Math.floor(0.9 * myfont.getSize2D() * h / box.getHeight()));
float fsize = (float) Math.min(fx, fy);
Font newFont = myfont.deriveFont(fsize);
g.setFont(newFont);
gv = newFont.createGlyphVector(frc, text);
box = gv.getVisualBounds();
if(box.getWidth() > w || box.getHeight() > h){
newFont = myfont.deriveFont(fsize - 1);
g.setFont(newFont);
gv = newFont.createGlyphVector(frc, text);
box = gv.getVisualBounds();
}
Rectangle r = transform(x, y, (int) box.getWidth(), (int) box.getHeight(), Anchor.NORTHWEST).toRectangle();
g2.drawString(text, r.x, r.y);
g2.setFont(myfont);
}
public void setClip(int x, int y, int width, int height){
Rectangle r = transform(x, y, width, height, Anchor.NORTHWEST).toRectangle();
g.setClip(r.x, r.y, r.width, r.height);
}
public void setClip(Rectangle r){
setClip(r.x, r.y, r.width, r.height);
}
public void setClip(Shape clip){
g.setClip(clip);
}
public void clipRect(int x, int y, int width, int height){
Rectangle r = transform(x, y, width, height, Anchor.NORTHWEST).toRectangle();
g.clipRect(r.x - 1, r.y - 1, r.width + 2, r.height + 2);
}
public void clipRect(Rectangle r){
clipRect(r.x, r.y, r.width, r.height);
}
public void clearClip(){
g.setClip(null);
}
public Shape getClip(){
return g.getClip();
}
/**
* @param anchor the anchor to setdynamicRectPositioningset
*/
public void setAnchor(Anchor anchor) {
this.anchor = anchor;
}
public Anchor getAnchor(){
return anchor;
}
public void setStroke(Stroke s){
g2.setStroke(s);
dynamicStrokeWidth = 0;
dynamicStroke = false;
}
public Stroke getStroke(){
return g2.getStroke();
}
public void setDynamicStroke(BasicStroke s){
baseStroke = s;
dynamicStroke = true;
float w = s.getLineWidth();
int m = Math.min(this.getScale().cXD(w) , this.getScale().cYD(w));
adjustDynamicStroke(s, m);
}
private int calculateDynamicStroke(BasicStroke s, double angle){
float w = s.getLineWidth();
double xm = (this.getScale().cXDdouble(w)) * Math.sin(Math.toRadians(angle));
double ym = (this.getScale().cYDdouble(w)) * Math.cos(Math.toRadians(angle));
int m = (int) Math.ceil(Math.sqrt(xm * xm + ym * ym));
return m;
}
private void adjustDynamicStroke(BasicStroke s, int m){
dynamicStrokeWidth = m;
Stroke dynamicStroke = new BasicStroke(m, s.getEndCap(),
s.getLineJoin(), s.getMiterLimit(),
s.getDashArray(), s.getDashPhase());
g2.setStroke(dynamicStroke);
}
public void setComposite(Composite comp){
g2.setComposite(comp);
}
public void drawImage(Image img, int x, int y, int width, int height, ImageObserver io){
Rectangle r = transform(x, y, width, height, Anchor.NORTHWEST).toRectangle();
g.drawImage(img, r.x, r.y, r.width, r.height, io);
}
public void drawImage(Image img, int x, int y, ImageObserver io){
drawImage(img,x,y,img.getWidth(io), img.getHeight(io), io);
}
private RectangleD transform(Rectangle r, Anchor source_anchor){
return transform(r.x, r.y, r.width, r.height, source_anchor);
}
private RectangleD transform(int x, int y, int width, int height, Anchor source_anchor){
return getScale().transform(x, y, width, height, source_anchor, anchor);
}
/**
* @return the dynamicPositioning
*/
public boolean isDynamicRectPositioning() {
return dynamicRectPositioning;
}
/**
* @param dynamicRectPositioning the dynamicRectPositioning to set
*/
public void setDynamicRectPositioning(boolean dynamicRectPositioning) {
this.dynamicRectPositioning = dynamicRectPositioning;
}
public FontRenderContext getFontRenderContext(){
return frc;
}
/**
* @return the scale s
*/
public Scale getScale() {
return s;
}
}
| true |
f9dba64fa97e9d8a9f093258e5218e89f26b2ba4
|
Java
|
arthursakemi/algoritmos2
|
/Algoritmos2/src/recurssion/Factorial.java
|
UTF-8
| 714 | 3.296875 | 3 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package recurssion;
/**
*
* @author arthur.msakemi
*/
public class Factorial {
public static void main(String[] args) {
System.out.println(fib(5));
}
static int fat(int n) {
if (n < 1) {
return 1;
}
return n * fat(n - 1);
}
static int fib(int n) {
if (n < 2) {
return n;
}
return fib(n - 1) + fib(n - 2);
}
static void binario(int n) {
if (n == 2) {
System.out.print(n);
}
}
}
| true |
64d3ac00f63259e4e763e9ff18bbab9c0452763b
|
Java
|
TMlulu/examSystem
|
/src/main/java/bean/ProgramStageDiffsureBase.java
|
UTF-8
| 1,093 | 2.53125 | 3 |
[] |
no_license
|
package bean;
public class ProgramStageDiffsureBase {
public ProgramStageDiffsureBase(){}
public ProgramStageDiffsureBase(String stunum, String title_diff, int getscore) {
this.stunum = stunum;
this.title_diff = title_diff;
this.getscore = getscore;
}
public String getStunum() {
return stunum;
}
public void setStunum(String stunum) {
this.stunum = stunum;
}
public String getTitle_diff() {
return title_diff;
}
public void setTitle_diff(String title_diff) {
this.title_diff = title_diff;
}
public int getGetscore() {
return getscore;
}
public void setGetscore(int getscore) {
this.getscore = getscore;
}
@Override
public String toString() {
return "ProgramStageDiffsureBase{" +
"stunum='" + stunum + '\'' +
", title_diff='" + title_diff + '\'' +
", getscore=" + getscore +
'}';
}
private String stunum;
private String title_diff;
private int getscore;
}
| true |
b2716f20712598058445b82acdafa53d45fd8e7c
|
Java
|
sadaf0106khan/DS-BinaryTrees--Algo
|
/SearchElementInBinaryTree.java
|
UTF-8
| 1,054 | 3.4375 | 3 |
[] |
no_license
|
package trees;
import java.util.LinkedList;
import java.util.Queue;
class SearchInBinaryTree{
public Node getNode(int data) {
Node a=new Node();
a.data=data;
a.left=null;
a.rigth=null;
return a;
}
public boolean isPresent(Node node,int data) {
if(node==null)
return false;
Queue<Node> q=new LinkedList<Node>();
q.offer(node);
while(q.size()>0) {
Node t=q.poll();
if(t.data==data)
return true;
if(t.left!=null)
q.offer(t.left);
if(t.rigth!=null)
q.offer(t.rigth);
}
return false;
}
}
public class SearchElementInBinaryTree {
public static void main(String[] args) {
SearchInBinaryTree bt=new SearchInBinaryTree();
Node root = bt.getNode(2);
root.left = bt.getNode(7);
root.rigth = bt.getNode(5);
root.left.left = bt.getNode(2);
root.left.rigth = bt.getNode(6);
root.left.rigth.left = bt.getNode(5);
root.left.rigth.rigth = bt.getNode(11);
root.rigth.rigth = bt.getNode(9);
root.rigth.rigth.left = bt.getNode(4);
System.out.println(bt.isPresent(root, 20));
}
}
| true |
7d7d8ee5a3c67840268f6b445662f1b277088c90
|
Java
|
yyyyuan/leetcode
|
/src/RemoveDuplicateLetters/Greedy.java
|
UTF-8
| 734 | 3.03125 | 3 |
[] |
no_license
|
class Solution {
public String removeDuplicateLetters(String s) {
char[] chs = s.toCharArray();
return helper(s);
}
private String helper(String s) {
if (s.length() == 0) return "";
StringBuilder sb = new StringBuilder();
int[] cnt = new int[26];
char[] chs = s.toCharArray();
int pos = 0;
for (int i = 0; i < chs.length; i++) {
cnt[chs[i] - 'a']++;
}
for (int i = 0; i < chs.length; i++) {
if (chs[i] < chs[pos]) pos = i;
if (--cnt[chs[i] - 'a'] == 0) break;
}
return sb.append(chs[pos]).append(helper(s.substring(pos + 1).replaceAll("" + chs[pos], ""))).toString();
}
}
| true |
1411f8910f350da5519fa6c2c7be4b0e8cca1c57
|
Java
|
santiago-a-vidal/JSpIRIT
|
/src/spirit/priotization/rankings/agglomerations/RankingBasedOnlyOnHistoryENOM.java
|
UTF-8
| 1,120 | 2.390625 | 2 |
[] |
no_license
|
package spirit.priotization.rankings.agglomerations;
import java.util.Iterator;
import spirit.core.agglomerations.AgglomerationModel;
import spirit.core.smells.CodeSmell;
import spirit.priotization.criteria.HistoryENOMCriteria;
import spirit.priotization.rankings.RankingCalculatorForAgglomerations;
import spirit.priotization.rankings.RankingTypeAgglomerations;
public class RankingBasedOnlyOnHistoryENOM extends RankingCalculatorForAgglomerations {
public RankingBasedOnlyOnHistoryENOM(HistoryENOMCriteria historyBetaCriteria) {
super(RankingTypeAgglomerations.HISTORY_ENOM);
criteria.add(historyBetaCriteria);
}
@Override
protected Double calculateRankingValue(AgglomerationModel agglomeration) {
HistoryENOMCriteria historyBetaCriteria=(HistoryENOMCriteria) criteria.firstElement();
double ret=0.0;
for (Iterator<CodeSmell> iterator = agglomeration.getCodeAnomalies().iterator(); iterator.hasNext();) {
CodeSmell type = (CodeSmell) iterator.next();
ret=ret+historyBetaCriteria.getENOMValue(type.getMainClassName());
}
return ret/agglomeration.getCodeAnomalies().size();
}
}
| true |
193b6290648326f27d4d6f126b0f2b72596b074e
|
Java
|
epamteam6/RestaurantWeb
|
/src/main/java/com/service/LanguageService.java
|
UTF-8
| 3,095 | 2.703125 | 3 |
[] |
no_license
|
package com.service;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Properties;
public class LanguageService {
private static LanguageService instance = new LanguageService();
public static LanguageService getInstance() {
if (instance == null)
instance = new LanguageService();
return instance;
}
private LanguageService() {
}
/**
* Specify language for localisation
*/
public enum Language {
EN, //english
RU, //russian
}
/**
* Add page types, according .jsp file name you've created.
* Place localisations in .properties file with the same name.
*/
public enum PageType {
// General pages
INDEX,
ABOUT,
SUCCESS,
// Session pages
SESSION_ERROR,
SESSION_JOIN,
SESSION_LOGIN,
SESSION_LOGIN_ERROR,
SESSION_LOGOUT,
// Admin pages
ADMIN_BILL_CREATION,
ADMIN_CONFIRMATION,
ADMIN_PAID_ORDERS,
ADMIN_READY_ORDERS,
// User pages
USER_CREATE_ORDER,
USER_CREATED_ORDERS,
USER_DONE_ORDERS,
USER_PAYMENT,
// Services
FOOTER,
HEADER,
HEADER_ALL,
}
/**
* Constructs path where localisation for page placed
*
* @param language
* @param type
* @return
*/
private static Properties getPageProperties(Language language, PageType type) {
try {
Properties properties = new Properties();
properties.load(new InputStreamReader(new FileInputStream("localisations/" +
type.toString().toLowerCase() + ".properties"),
Charset.forName("Windows-1251"))); // Configure it if needed
return properties;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Returns string, specified for element of view
*
* @param language
* @param type
* @param elementType
* @return
*/
public static String elementName(Language language, PageType type, String elementType) {
String elementName;
try {
elementName = getPageProperties(language, type).getProperty(elementType);
if (elementName == null)
throw new IllegalArgumentException();
} catch (NullPointerException | IllegalArgumentException e) {
//todo - Log it
e.printStackTrace();
if (e instanceof NullPointerException) {
elementName = "<-Missing window-> "
+ type + " for "
+ language.toString().toLowerCase();
} else {
elementName = "<-Missing element-> "
+ type + "->" + elementType
+ " for " + language.toString().toLowerCase();
}
}
return elementName;
}
}
| true |
dae6b7007126d89951957f8343d7c111fcc08525
|
Java
|
hasleo/mypojo
|
/javaUtil/2.0/util/erwins/util/guava/ManyToOneStraregy.java
|
UTF-8
| 636 | 2.234375 | 2 |
[] |
no_license
|
package erwins.util.guava;
import java.lang.annotation.Annotation;
import javax.persistence.ManyToOne;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
/**
* ManyToOne의 기본구현.
* @ManyToOne 어노테이션이 있으면 컨버팅하지 않는다.
* */
public class ManyToOneStraregy implements ExclusionStrategy{
@Override
public boolean shouldSkipField(FieldAttributes arg0) {
Annotation manyToOne = arg0.getAnnotation(ManyToOne.class);
return manyToOne != null;
}
@Override
public boolean shouldSkipClass(Class<?> arg0) {
return false;
}
}
| true |
ceafe71788f0b6319c81312b871314f14c16822f
|
Java
|
JinHoooooou/codeWarsChallenge
|
/src/test/java/codeWars/kyu6/numericals_of_a_string_20211012/JomoPipiTest.java
|
UTF-8
| 710 | 2.75 | 3 |
[] |
no_license
|
package codeWars.kyu6.numericals_of_a_string_20211012;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class JomoPipiTest {
@Test
@DisplayName("test should return 1112111121311 when input Hello, World!")
public void test1() {
assertThat(JomoPipi.numericals("Hello, World!"), is("1112111121311"));
}
@Test
@DisplayName("test should return 11121111213112111131224132411122 when input \"Hello, World! It's me, JomoPipi!\"")
public void test2() {
assertThat(JomoPipi.numericals("Hello, World! It's me, JomoPipi!"), is("11121111213112111131224132411122"));
}
}
| true |
dbde704b721a6d8d04b13e59a52f13cbe4684502
|
Java
|
mikemanski/text_to_PDF
|
/src/pdf_doc/PdfDoc.java
|
UTF-8
| 2,274 | 3.09375 | 3 |
[] |
no_license
|
package pdf_doc;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfWriter;
public class PdfDoc
{
private String fileName, title, author, content;
private Document document1;
public PdfDoc(String fileNameIn, String titleIn, String authorIn, String contentIn)
{
fileName = fileNameIn;
title = titleIn;
author = authorIn;
content = contentIn;
createPDF();
}
private void createPDF()
{
document1 = new Document();
try
{
PdfWriter.getInstance(document1, new FileOutputStream(fileName + ".pdf"));
}
catch (FileNotFoundException e)
{
System.out.println("FileNotFoundException");// TODO Auto-generated catch block
e.printStackTrace();
}
catch (DocumentException e)
{
System.out.println("DocumentException while creating document");// TODO Auto-generated catch block
e.printStackTrace();
}
document1.open();
try
{
document1.add(new Phrase("Title: " + title + "\n",
FontFactory.getFont(FontFactory.HELVETICA, (float) 18,
Font.BOLD, new BaseColor(0, 0, 0))));
document1.add(new Phrase("Author: " + author + "\n\n",
FontFactory.getFont(FontFactory.HELVETICA, (float) 14,
Font.BOLD, new BaseColor(0, 0, 0))));
document1.add(new Paragraph(content));
}
catch (DocumentException e)
{
System.out.println("DocumentException while adding text items");
e.printStackTrace();
}
document1.close();
}
//PUBLIC METHODS
public void updateContent(String contentIn)//recreates/overwrites PDF doc, with updated contents
{
content = contentIn;
createPDF();
}
public void updateTitle(String titleIn)//recreates/overwrites PDF doc, with updated title
{
title = titleIn;
createPDF();
}
public void updateAuthor(String authorIn)//recreates/overwrites PDF doc, with updated author
{
author = authorIn;
createPDF();
}
}
| true |
dfc1e6cf0c5a74abff14b6c6270b6abf81efa830
|
Java
|
haiderali007/CheekyMonkey
|
/app/src/main/java/com/entrada/cheekyMonkey/steward/order/FetchOrderTask.java
|
UTF-8
| 4,399 | 1.859375 | 2 |
[] |
no_license
|
package com.entrada.cheekyMonkey.steward.order;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ProgressBar;
import com.entrada.cheekyMonkey.steward.discount.DiscountLayout;
import com.entrada.cheekyMonkey.network.BaseNetwork;
import com.entrada.cheekyMonkey.takeorder.adapter.TakeOrderAdapter;
import com.entrada.cheekyMonkey.takeorder.entity.OrderItem;
import com.entrada.cheekyMonkey.util.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class FetchOrderTask extends AsyncTask<String, OrderItem, OrderItem> {
private TakeOrderAdapter adapter;
private ProgressBar mDialog;
private Context context;
private String parameter;
private String serverIP;
private String response = "";
private DiscountLayout discountLayout;
private ArrayList<String> codeList;
public FetchOrderTask(Context context, TakeOrderAdapter adapter, DiscountLayout discountLayout,
ArrayList<String> codeList, String parameter, String serverIP) {
this.context = context;
this.adapter = adapter;
this.discountLayout = discountLayout;
this.codeList = codeList;
this.parameter = parameter;
this.serverIP = serverIP;
mDialog = new ProgressBar(context);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (mDialog != null)
mDialog.setVisibility(View.VISIBLE);
}
@Override
protected OrderItem doInBackground(String... params) {
response = BaseNetwork.obj().postMethodWay(serverIP, "", BaseNetwork.KEY_ECABS_ORDER_DETAIL, parameter);
try {
JSONObject jsonParam ;
JSONArray jsonArray ;
Logger.d("OrderNumberResponse", "::" + response);
JSONObject obj = new JSONObject(response);
jsonArray = new JSONArray(
obj.getString("ECABS_PullOrderForModifyResult"));
OrderItem obj_order ;
for (int i = 0; i < jsonArray.length(); i++) {
jsonParam = jsonArray.getJSONObject(i);
obj_order = new OrderItem();
/* steward = jsonParam.getString("stw");
ORemark = jsonParam.getString("Orem");
cvr = jsonParam.getString("cover");
GstName = jsonParam.getString("guest");
odtype = jsonParam.getString("rkot_Typ");*/
obj_order.o_code = jsonParam.getString("Code");
obj_order.o_grp_code = jsonParam.getString("Grp");
if (jsonParam.getString("zcomboItem").equals("Y") || jsonParam.getString("zcomboItem").equals(""))
obj_order.o_name = jsonParam.getString("Name");
else
obj_order.o_name = "##" + jsonParam.getString("Name");
obj_order.o_itm_rmrk = jsonParam.getString("remark");
obj_order.o_addon_code = jsonParam.getString("addon");
obj_order.o_mod = jsonParam.getString("modifier");
obj_order.o_combo_code = jsonParam.getString("zcomboItem");
obj_order.o_happy_hour = jsonParam.getString("Name").equals("Free") ? "Y" : "";
obj_order.o_subunit = "";
obj_order.o_quantity = Float.parseFloat(jsonParam.getString("qty"));
obj_order.o_price = Float.parseFloat(jsonParam.getString("dat"));
obj_order.o_amount = obj_order.o_quantity * obj_order.o_price;
obj_order.o_disc = jsonParam.getString("GUEST_DISC");
discountLayout.createDiscList("",obj_order.o_disc,obj_order.o_amount);
if (!codeList.contains(obj_order.o_code))
codeList.add(obj_order.o_code);
publishProgress(obj_order);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onProgressUpdate(OrderItem... values) {
super.onProgressUpdate(values);
adapter.addDataSetItem(values[0]);
}
@Override
protected void onPostExecute(OrderItem result) {
super.onPostExecute(result);
if (mDialog != null)
mDialog.setVisibility(View.GONE);
}
}
| true |
e73b022ecb9cd171111092f2b75425a967adaaae
|
Java
|
AbhishekShrinath/SpringBoot_WebApplication
|
/employee_Management_System/src/main/java/com/employee/services/UserServices.java
|
UTF-8
| 361 | 1.726563 | 2 |
[] |
no_license
|
package com.employee.services;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import com.employee.model.User;
import com.employee.web.dto.UserRegistrationDto;
public interface UserServices extends UserDetailsService {
User save(UserRegistrationDto registrationDto);
}
| true |
74f2a6e0645929b568afff0e49a3e1c78491a17d
|
Java
|
RaidTheWeb/Nexus-Spelunker
|
/src/tech/raidtheweb/java/rogue/HealthEffect.java
|
UTF-8
| 442 | 2.46875 | 2 |
[] |
no_license
|
package tech.raidtheweb.java.rogue;
public class HealthEffect extends Effect {
/**
*
*/
private static final long serialVersionUID = -2901980825039054224L;
public HealthEffect(int duration) {
super(duration);
}
public void start(Creature creature){
if (creature.hp() == creature.maxHp())
return;
creature.modifyHp(15);
creature.doAction("look healthier");
}
}
| true |
1ac39911309d1ffeb5b5dcfffea76890835c91d8
|
Java
|
sureshreddy94/Warranty
|
/app/src/main/java/com/krypto/blocks/warranty/RegisterProductsActivity.java
|
UTF-8
| 1,665 | 1.882813 | 2 |
[] |
no_license
|
package com.krypto.blocks.warranty;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.krypto.blocks.warranty.fragments.HomeFragment;
import com.krypto.blocks.warranty.scanner.FullScannerActivity;
public class RegisterProductsActivity extends AppCompatActivity {
public void HomeFragment() {
HomeFragment homeFragment = new HomeFragment();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.content_frame, homeFragment);
transaction.addToBackStack(null);
transaction.commit();
}
TextView scan;
ImageView bac_btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_products);
bac_btn = findViewById(R.id.back_btn);
scan = findViewById(R.id.scany);
scan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(RegisterProductsActivity.this,FullScannerActivity.class);
startActivity(i);
}
});
bac_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HomeFragment();
}
});
}
}
| true |
96af283fb80d359395e9dbcafac8b382e7a8c17e
|
Java
|
EgorSigolaev/YoutubeExtractor
|
/youtube_extractor/src/main/java/com/yash/youtube_extractor/models/VideoDetails.java
|
UTF-8
| 675 | 2.390625 | 2 |
[
"MIT"
] |
permissive
|
package com.yash.youtube_extractor.models;
public class VideoDetails {
private StreamingData streamingData;
private VideoData videoData;
public VideoDetails(StreamingData streamingData, VideoData videoData) {
this.streamingData = streamingData;
this.videoData = videoData;
}
public VideoData getVideoData() {
return videoData;
}
public void setVideoData(VideoData videoData) {
this.videoData = videoData;
}
public StreamingData getStreamingData() {
return streamingData;
}
public void setStreamingData(StreamingData streamingData) {
this.streamingData = streamingData;
}
}
| true |
d5a906aa3f05882cee65f77384783865c91cf1a6
|
Java
|
webguitoolkit/wgt-ui
|
/src/main/java/org/webguitoolkit/ui/controls/table/renderer/ImageColumnRenderer.java
|
UTF-8
| 4,016 | 2.203125 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
Copyright 2008 Endress+Hauser Infoserve GmbH&Co KG
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing permissions
and limitations under the License.
*/
package org.webguitoolkit.ui.controls.table.renderer;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.webguitoolkit.ui.ajax.IContext;
import org.webguitoolkit.ui.base.IDataBag;
import org.webguitoolkit.ui.controls.table.IColumnRenderer;
import org.webguitoolkit.ui.controls.table.ITableColumn;
import org.webguitoolkit.ui.controls.util.JSUtil;
import org.webguitoolkit.ui.controls.util.PropertyAccessor;
/**
* <pre>
* Cells of a column where the ImageColumnRenderer is assigned display images.
*
* The source of the image is the property of the data object. e.g.: ./images/someimage.gif
*
* The title of the image can be set only if DataBags are used. The property + ImageColumnRenderer.DOT_TITLE
* contains the title.
* eg.: dataBag.addProperty("image"+ ImageColumnRenderer.DOT_TITLE, "Nice Image Title" );
* </pre>
*/
public class ImageColumnRenderer extends AbstractColumRenderer implements IColumnRenderer {
private static final Logger LOGGER = Logger.getLogger(ImageColumnRenderer.class);
public static final String BLANK_IMG = "./images/wgt/1.gif";
public static final String DOT_SRC = ".src";
public static final String DOT_TITLE = ".title"; // attribute for title of image-element
public static final String DOT_IMG = ".img"; // id of img element
/**
* @see org.webguitoolkit.ui.controls.table.IColumnRenderer#generateHTML(ITableColumn, String, int, int)
*/
public String generateHTML(ITableColumn col, String cellId, int idxRow, int idxCol) {
IContext ctx = col.getPage().getContext();
return "<img " + JSUtil.atId(cellId + DOT_IMG)+
JSUtil.at("src", ctx.processValue(cellId + DOT_IMG + DOT_SRC ), BLANK_IMG ) +
JSUtil.atNotEmpty("title", ctx.processValue(cellId + DOT_IMG + DOT_TITLE)) +
JSUtil.atStyleVisible("", ctx.processValue(cellId+ DOT_IMG + IContext.DOT_VIS)) +
">";
}
/**
* @see org.webguitoolkit.ui.controls.table.IColumnRenderer#load(String, Object, ITableColumn, IContext, int, int)
*/
public void load(String whereId, Object data, ITableColumn col, IContext ctx, int idxRow, int idxCol) {
// may be we have to make the html visible again...
String visVal = ctx.getValue(whereId+ DOT_IMG + IContext.DOT_VIS);
if ("false".equals(visVal)) {
ctx.add(whereId+ DOT_IMG + IContext.DOT_VIS, "true", IContext.TYPE_VIS, IContext.STATUS_NOT_EDITABLE);
}
// data must be of type string
Object src = PropertyAccessor.retrieveProperty(data,col.getProperty());
if (src==null) {
//throw new WGTException("img src not set");
LOGGER.warn("img src not set, using ./images/wgt/1.gif");
src = "./images/wgt/1.gif";
}
ctx.add(whereId+DOT_IMG+ DOT_SRC, ""+src, IContext.TYPE_ATT, IContext.STATUS_NOT_EDITABLE);
if( data instanceof IDataBag ){
Object srcTitle = ((IDataBag)data).get( col.getProperty()+DOT_TITLE );
if( !StringUtils.isEmpty( (String)srcTitle ) )
ctx.add(whereId+DOT_IMG+ DOT_TITLE, ""+srcTitle, IContext.TYPE_ATT, IContext.STATUS_NOT_EDITABLE);
}
}
/**
* @see com.endress.infoserve.wgt.controls.table.IColumnRenderer#clear(java.lang.String, com.endress.infoserve.wgt.controls.table.TableColumn, com.endress.infoserve.wgt.ajax.Context, int, int)
*/
public void clear(String whereId, ITableColumn col, IContext ctx, int idxRow, int idxCol) {
ctx.add(whereId+ DOT_IMG + IContext.DOT_VIS, "false", IContext.TYPE_VIS, IContext.STATUS_NOT_EDITABLE);
}
}
| true |
a23a0e45d9cdfc8e261ef1e3f6cd3d1e7f31066f
|
Java
|
LucaMarcellino/Lab09
|
/src/main/java/it/polito/tdp/borders/FXMLController.java
|
UTF-8
| 2,680 | 2.375 | 2 |
[] |
no_license
|
package it.polito.tdp.borders;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import it.polito.tdp.borders.model.Country;
import it.polito.tdp.borders.model.Model;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
public class FXMLController {
private Model model;
@FXML // ResourceBundle that was given to the FXMLLoader
private ResourceBundle resources;
@FXML // URL location of the FXML file that was given to the FXMLLoader
private URL location;
@FXML // fx:id="txtAnno"
private TextField txtAnno; // Value injected by FXMLLoader
@FXML
private ComboBox<Country> cmbStato;
@FXML
private Button btnVicini;
@FXML // fx:id="txtResult"
private TextArea txtResult; // Value injected by FXMLLoader
@FXML
void doCalcolaConfini(ActionEvent event) {
txtResult.clear();
int anno=0;
List<Country> nazioni;
try {
anno= Integer.parseInt(txtAnno.getText());
} catch (NumberFormatException nfe) {
txtResult.appendText("Scegli un numero intero figlio di puttana");
}
if(anno<1816 || anno>2016) {
txtResult.appendText("Un numero compreso tra 1816 e 2016 lurido bastardo");
}
nazioni=new ArrayList<>(model.getListaNazionii(anno));
for(Country c : nazioni ) {
txtResult.appendText("Nazione "+c+" è connesso a "+ model.numeroArchi(anno, c)+" stati\n");
}
txtResult.appendText("Numero stati presenti: "+model.numeroVertex(anno));
cmbStato.getItems().addAll(nazioni);
txtAnno.clear();
}
@FXML
void doVicini(ActionEvent event) {
txtResult.clear();
Country c =cmbStato.getValue();
List<Country> vicini= new ArrayList<>(model.vicini(c));
txtResult.appendText(vicini.toString());
}
@FXML // This method is called by the FXMLLoader when initialization is complete
void initialize() {
assert txtAnno != null : "fx:id=\"txtAnno\" was not injected: check your FXML file 'Scene.fxml'.";
assert cmbStato != null : "fx:id=\"cmbStato\" was not injected: check your FXML file 'Scene.fxml'.";
assert btnVicini != null : "fx:id=\"btnVicini\" was not injected: check your FXML file 'Scene.fxml'.";
assert txtResult != null : "fx:id=\"txtResult\" was not injected: check your FXML file 'Scene.fxml'.";
}
public void setModel(Model model) {
this.model = model;
txtResult.setEditable(false);
}
}
| true |
8ac764b4a8101ada5ec8a0627f4b98afcd53a954
|
Java
|
UnconventionalThinking/hierarchy
|
/Code/Hierarchy/src/net/unconventionalthinking/matrix/metacompiler/codegen/AnnotationHandler_CodeGenerator_AnnotationBlockStmt__Filters.java
|
UTF-8
| 2,733 | 2.046875 | 2 |
[] |
no_license
|
/* Copyright 2012, 2013 Unconventional Thinking
*
* This file is part of Hierarchy.
*
* Hierarchy is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Hierarchy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Hierarchy.
* If not, see <http://www.gnu.org/licenses/>.
*/
package net.unconventionalthinking.matrix.metacompiler.codegen;
import net.unconventionalthinking.compiler.tools.CodeBuilder;
import net.unconventionalthinking.matrix.MatrixControl;
import net.unconventionalthinking.matrix.SchemaControl;
import net.unconventionalthinking.matrix.symbols.SymbolControl;
import net.unconventionalthinking.hierarchy.HierarchySettings;
/**
* NOTE: This is used RECURSIVELY!!
*
* Each annotaton body bock has one! And, the code generated from child AnnoationHandler_CodeBenerator_AnooationBodyBock objects is added to the
* parent's child code.
*
*
* @author peterjoh
*/
public class AnnotationHandler_CodeGenerator_AnnotationBlockStmt__Filters extends AnnotationHandler_CodeGenerator_AnnotationBlockStmt {
public AnnotationHandler_CodeGenerator_AnnotationBlockStmt__Filters(SymbolControl symbolControl, SchemaControl schemaControl, MatrixControl matrixControl,
HierarchySettings hierarchySettings, int baseIndentLevel) {
super(symbolControl, schemaControl, matrixControl, hierarchySettings, baseIndentLevel);
}
/**
* This is a recusive method
*
* @return
* @throws Exception_MetaCompilerError
*/
@Override
public CodeBuilder generate_AnnoteBlockStmt() throws Exception_MetaCompilerError {
String indentOption = (isFirst_AnnotationBlockStmtCodeGen_Sibling) ? baseIndent : "";
String elseOption = (!isFirst_AnnotationBlockStmtCodeGen_Sibling) ? " else " : "";
codeBuilder_AnnoteBlockStmt.append(indentOption);
codeBuilder_AnnoteBlockStmt.append(elseOption).append(
"if (annotationRef == " + hierarchySettings.appSymbols_ClassName + "." + annotationHandlerReference.get_Name_IdentFormat() + ") {\n");
generate_AnnoteBlockStmt__ProcessChildren(false);
codeBuilder_AnnoteBlockStmt.append(baseIndent).append("}");
codeBuilder_AnnoteBlockStmt.append("\n");
return codeBuilder_AnnoteBlockStmt;
}
}
| true |
709d34e8b411ebf473418a9ac0eeb89cded2d3dd
|
Java
|
ALAxHxC/AndroidSQL
|
/app/src/main/java/org/gestioncatalogo/controlador/persistencia/ControladorProducto.java
|
UTF-8
| 4,252 | 2.453125 | 2 |
[] |
no_license
|
package org.gestioncatalogo.controlador.persistencia;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import org.gestioncatalogo.R;
import org.gestioncatalogo.modelo.Producto;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Daniel on 11/07/2016.
*/
public class ControladorProducto {
private Context context;
private BaseDeDatos baseDeDatos;
public ControladorProducto(Context context) {
this.context = context;
baseDeDatos = new BaseDeDatos(context, context.getString(R.string.catalogo), null, 1);
}
public boolean RegistrarProducto(Producto producto) {
SQLiteDatabase sql = baseDeDatos.getWritableDatabase();
ContentValues valores = new ContentValues();
valores.put(Querys.producto_nombre, producto.getNombre());
valores.put(Querys.producto_fecha, producto.getFecha());
valores.put(Querys.producto_inventario, producto.getInventario());
valores.put(Querys.producto_talla, producto.getTalla());
valores.put(Querys.producto_marca, producto.getMarca());
valores.put(Querys.producto_observaciones, producto.getObservaciones());
try {
long ret = sql.insert(Querys.table_producto_name, null, valores);
if (ret > 0) {
return true;
} else {
return false;
}
} catch (Exception ex) {
Log.println(Log.ASSERT, "SQL", ex.toString());
ex.printStackTrace();
return false;
} finally {
sql.close();
}
}
public List<Producto> todosProductos() {
SQLiteDatabase sql = baseDeDatos.getWritableDatabase();
Cursor cursor = sql.rawQuery("SELECT * FROM " + Querys.table_producto_name, null);
return listarProducto(cursor);
}
public List<Producto> filtrarProductos(String nombre, String talla, String marca) {
SQLiteDatabase sql = baseDeDatos.getWritableDatabase();
try {
Cursor fila = sql.rawQuery(consulta(nombre, talla, marca), null);
return listarProducto(fila);
} catch (Exception ex) {
ex.printStackTrace();
Log.println(Log.ASSERT, "sql", ex.toString());
return null;
} finally {
sql.close();
}
}
public String consulta(String nombre, String talla, String marca) {
int contador = 0;
StringBuilder consulta = new StringBuilder("SELECT * FROM " + Querys.table_producto_name + " WHERE ");
if (!(nombre.isEmpty() || nombre.equalsIgnoreCase(""))) {
consulta.append(" " + Querys.producto_nombre + " like '%" + nombre + "%' ");
contador++;
}
if (!(talla.isEmpty() || talla.equalsIgnoreCase(""))) {
if (contador >= 1) {
consulta.append(" OR ");
}
consulta.append(Querys.producto_talla + " like '%" + talla + "%'");
contador++;
}
if (!(marca.isEmpty() || marca.equalsIgnoreCase(""))) {
if (contador >= 1) {
consulta.append(" OR ");
}
consulta.append(Querys.producto_marca + " IN" + " " +
"(SELECT " + Querys.marca_marcaid + " FROM " + Querys.table_marca_name + " WHERE " + Querys.marca_nombre + " like '%" + marca + "%' )");
contador++;
}
return consulta.toString();
}
public List<Producto> listarProducto(Cursor fila) {
List<Producto> lista = new ArrayList<>();
if (fila.moveToFirst()) {
do {
Producto producto = new Producto();
producto.setNombre(fila.getString(0));
producto.setTalla(fila.getString(1));
producto.setMarca(fila.getString(2));
producto.setInventario(Integer.parseInt(fila.getString(3)));
producto.setFecha(fila.getString(4));
producto.setObservaciones(fila.getString(5));
lista.add(producto);
} while (fila.moveToNext());
}
return lista;
}
}
| true |
1332820968875ff906794242973ad373fc2eab4b
|
Java
|
DBrouillet/Clue
|
/src/tests/gameActionTests.java
|
UTF-8
| 14,580 | 3.171875 | 3 |
[] |
no_license
|
package tests;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Map;
import org.junit.BeforeClass;
import org.junit.Test;
import clueGame.Board;
import clueGame.BoardCell;
import clueGame.Card;
import clueGame.CardType;
import clueGame.ComputerPlayer;
import clueGame.Player;
import clueGame.Solution;
/**
* @author Miika Jarvela, Daniel Brouillet, Richard Figueroa Erickson
* Class used to test the basic actions of the game,
* such as choosing a target to move to,
* checking an accusation, creating a suggestion,
* disproving a suggestion, and handling a suggestion.
*
*/
public class gameActionTests {
private static Board board;
@BeforeClass
public static void setUp() {
// Board is singleton, get the only instance
board = Board.getInstance();
board.setConfigFiles("BoardLayout.csv", "Rooms.txt", "Players.txt", "Weapons.txt");
// Initialize will load all config files
board.initialize();
}
/**
* Check target selection
* when there are no rooms in the targets.
* We do this by picking a square where
* the player can only move up or down.
* We check to make sure it is moving up
* and down and nowhere else.
*/
@Test
public void testRoomlessComputerTargetSelection() {
ComputerPlayer testPlayer = new ComputerPlayer("testPlayer", "green", 20, 8);
int numDown = 0;
int numUp = 0;
// Run 100 trials by moving the player from (20,8) with a roll of 1
for (int i = 0; i < 100; i++) {
board.calcTargetsTest(20, 8, 1);
BoardCell destination = testPlayer.pickLocation(board.getTargets());
// Count the number of times that the player goes up and down
if(destination.getRow() == 21 && destination.getColumn() == 8) {
numDown++;
}
else if(destination.getRow() == 19 && destination.getColumn() == 8) {
numUp++;
} // If it ever goes to another BoardCell, fail
else fail();
}
// Make sure each was chosen a reasonable number of times
assertTrue(numDown > 20);
assertTrue(numUp > 20);
}
/**
* Test to check the selected BoardCell when there
* is a room in the targets and it has not been visited.
*/
@Test
public void testRoomNotVistitedComputerTargetSelection() {
ComputerPlayer testPlayer = new ComputerPlayer("testPlayer", "green", 17, 8);
testPlayer.setMostRecentRoom('L');
// Run 100 trials by moving the player at (17,8) (in the Living room) a distance of 1
for (int i = 0; i < 100; i++) {
board.calcTargetsTest(17, 8, 1);
BoardCell destination = testPlayer.pickLocation(board.getTargets());
// Make sure it is picking the doorway every time, otherwise fail
if(destination.getRow() == 17 && destination.getColumn() == 9) {
}
else fail();
}
}
/**
* Test to see if the BoardCells are
* chosen appropriately when there is
* a room in the targets, but it
* also was visited last.
*/
@Test
public void testRoomVistitedComputerTargetSelection() {
ComputerPlayer testPlayer = new ComputerPlayer("testPlayer", "green", 17, 8);
testPlayer.setMostRecentRoom('B');
int numDown = 0;
int numUp = 0;
int numRight = 0;
// Run 100 trials by moving the player from (17, 8) with a roll of 1
for (int i = 0; i < 100; i++) {
board.calcTargetsTest(17, 8, 1);
BoardCell destination = testPlayer.pickLocation(board.getTargets());
// Count the number of times that the player goes up, down, and left
if(destination.getRow() == 18 && destination.getColumn() == 8) {
numDown++;
}
else if(destination.getRow() == 16 && destination.getColumn() == 8) {
numUp++;
}
else if(destination.getRow() == 17 && destination.getColumn() == 9) {
numRight++;
}
else fail();
}
// Make sure each was chosen a reasonable number of times
assertTrue(numDown > 10);
assertTrue(numUp > 10);
assertTrue(numRight > 10);
}
/**
* Test to see if checking the accusation
* is done correctly. We do this by creating
* a solution and setting that as the answer.
* We create a test player, and then check
* the accusation when it is correct and
* then with each individual component incorrect
*/
@Test
public void testCheckAccusation() {
// Create the solution and the test player
Solution solution = new Solution("Bob", "Kitchen", "Knife");
Solution oldAnswer = board.getTheAnswer();
board.setTheAnswer(solution);
ComputerPlayer testPlayer = new ComputerPlayer("testPlayer", "green", 17, 8);
// Check the accusation when it is correct
Solution accusation = testPlayer.makeAccusation("Bob", "Kitchen", "Knife");
assert(board.checkAccusation(accusation));
// Check accusation when the person is incorrect
accusation = testPlayer.makeAccusation("Joe", "Kitchen", "Knife");
assert(board.checkAccusation(accusation) == false);
// Check accusation when the room is incorrect
accusation = testPlayer.makeAccusation("Bob", "Office", "Knife");
assert(board.checkAccusation(accusation) == false);
// Check accusation when the weapon is incorrect
accusation = testPlayer.makeAccusation("Bob", "Kitchen", "Gun");
assert(board.checkAccusation(accusation) == false);
//Reset the solution to the removed cards
board.setTheAnswer(oldAnswer);
}
/**
* Test to make sure that suggestions
* are disproved appropriately. We do
* this by testing the 3 separate cases
* of when there are 0 matching cards,
* 1 matching card, and >1 (2 specifically)
* matching cards.
*/
@Test
public void testDisproveSuggestion() {
/*
* Create the suggestion to test,
* a test player, and a pair of each type
* of card (one that matches the suggestion
* and one that doesn't for each type)
*/
Solution suggestion = new Solution("Joe", "Kitchen", "Knife");
Player testPlayer = new ComputerPlayer("testPlayer", "green", 17, 8);
Card personMatch = new Card("Joe", CardType.PERSON);
Card personNoMatch = new Card("Bob", CardType.PERSON);
Card roomMatch = new Card("Kitchen", CardType.ROOM);
Card roomNoMatch = new Card("Study", CardType.ROOM);
Card weaponMatch = new Card("Knife", CardType.WEAPON);
Card weaponNoMatch = new Card("Gun", CardType.WEAPON);
// Test the case that no cards are matching
ArrayList<Card> noMatching = new ArrayList<Card>();
noMatching.add(weaponNoMatch);
noMatching.add(personNoMatch);
noMatching.add(roomNoMatch);
testPlayer.setMyCards(noMatching);
assertEquals(testPlayer.disproveSuggesstion(suggestion), null);
/*
* Test to make sure that when one
* card matches it returns that card.
* We test for the case that the weapon
* is matching, the person is matching,
* and the room is matching separately.
*/
// Test for matching weapon
ArrayList<Card> oneMatchingWeapon = new ArrayList<Card>();
oneMatchingWeapon.add(weaponMatch);
oneMatchingWeapon.add(personNoMatch);
oneMatchingWeapon.add(roomNoMatch);
testPlayer.setMyCards(oneMatchingWeapon);
assertEquals(testPlayer.disproveSuggesstion(suggestion), weaponMatch);
// Test for matching person
ArrayList<Card> oneMatchingPerson = new ArrayList<Card>();
oneMatchingPerson.add(weaponNoMatch);
oneMatchingPerson.add(personMatch);
oneMatchingPerson.add(roomNoMatch);
testPlayer.setMyCards(oneMatchingPerson);
assertEquals(testPlayer.disproveSuggesstion(suggestion), personMatch);
// Test for matching room
ArrayList<Card> oneMatchingRoom = new ArrayList<Card>();
oneMatchingRoom.add(weaponNoMatch);
oneMatchingRoom.add(personNoMatch);
oneMatchingRoom.add(roomMatch);
testPlayer.setMyCards(oneMatchingRoom);
assertEquals(testPlayer.disproveSuggesstion(suggestion), roomMatch);
/*
* Test to see that when there
* are 2 (> 1) matching Cards
* in the player's hand, they
* choose randomly from the 2
* that match.
*/
ArrayList<Card> twoMatching = new ArrayList<Card>();
twoMatching.add(weaponNoMatch);
twoMatching.add(personMatch);
twoMatching.add(roomMatch);
testPlayer.setMyCards(twoMatching);
int numRoomChosen = 0;
int numPersonChosen = 0;
// Run 100 trials of disproving the suggestion
for (int i = 0; i < 100; i++) {
Card match = testPlayer.disproveSuggesstion(suggestion);
// Count the number of times we choose the person or room match
if (match == personMatch) {
numPersonChosen++;
} else if (match == roomMatch) {
numRoomChosen++;
} else { // But if anything else is ever chosen, fail
fail();
}
}
// Make sure we have a reasonable number of each chosen
assert(numRoomChosen > 20);
assert(numPersonChosen > 20);
}
@Test
public void testCreateSuggestion() {
/*
* Test to see that the suggested room
* and the room the player is in are the same
*/
ComputerPlayer testPlayer = new ComputerPlayer("testPlayer", "green", 3, 3);
testPlayer.initializeSeenCards();
BoardCell location = board.getCellAt(testPlayer.getRow(), testPlayer.getColumn());
Map<Character, String> legend = board.getLegend();
ArrayList<Card> weaponsDeck = board.getWeaponsDeck();
ArrayList<Card> playersDeck = board.getPlayersDeck();
assertTrue(testPlayer.createSuggestion().room.equals(legend.get(location.getInitial())));
/*
* Test to see that if only one weapon/player is unseen
* it will always be in the suggestion.
*/
for(Card c : weaponsDeck) {
testPlayer.addSeenCard(c);
}
for(Card c : playersDeck) {
testPlayer.addSeenCard(c);
}
assertTrue(testPlayer.createSuggestion().weapon.equals(board.getTheAnswer().weapon));
assertTrue(testPlayer.createSuggestion().person.equals(board.getTheAnswer().person));
/*
* Test to see that if multiple weapons/players
* are unseen one is chosen randomly for the suggestion.
*/
ComputerPlayer testPlayer2 = new ComputerPlayer("testPlayer2", "green", 3, 3);
testPlayer2.initializeSeenCards();
for(int i = 0; i < weaponsDeck.size()-1; i++) {
testPlayer2.addSeenCard(weaponsDeck.get(i));
}
for(int i = 0; i < playersDeck.size()-1; i++) {
testPlayer2.addSeenCard(playersDeck.get(i));
}
int unseenPlayer1Chosen = 0;
int unseenPlayer2Chosen = 0;
int unseenWeapon1Chosen = 0;
int unseenWeapon2Chosen = 0;
//Run 100 trials to disprove the suggestion
for(int i = 0; i < 100; i++) {
Solution testSuggestion = testPlayer2.createSuggestion();
// Count the number of times each possible weapon or player is chosen
if(testSuggestion.weapon.equals(board.getTheAnswer().weapon)) {
unseenWeapon1Chosen++;
}
else if(testSuggestion.weapon.equals(weaponsDeck.get(weaponsDeck.size()-1).getCardName())) {
unseenWeapon2Chosen++;
}
if(testSuggestion.person.equals(board.getTheAnswer().person)) {
unseenPlayer1Chosen++;
}
else if(testSuggestion.person.equals(playersDeck.get(playersDeck.size()-1).getCardName())) {
unseenPlayer2Chosen++;
}
else fail();// But if anything else is ever chosen, fail
}
// Make sure we have a reasonable number of each chosen
assert(unseenWeapon1Chosen > 10);
assert(unseenWeapon2Chosen > 10);
assert(unseenPlayer1Chosen > 10);
assert(unseenPlayer2Chosen > 10);
}
@Test
public void testhandleSuggestionTest() {
/*
* Creates the hands of each player.
* The actual solution is Office, Bottle, Greg
*/
ArrayList<Card> p1Cards = new ArrayList<Card>();
p1Cards.add(new Card("Kitchen", CardType.ROOM));
p1Cards.add(new Card("Gun", CardType.WEAPON));
p1Cards.add(new Card("Jack", CardType.PERSON));
ArrayList<Card> p2Cards = new ArrayList<Card>();
p2Cards.add(new Card("Bathroom", CardType.ROOM));
p2Cards.add(new Card("Knife", CardType.WEAPON));
p2Cards.add(new Card("Bob", CardType.PERSON));
ArrayList<Card> p3Cards = new ArrayList<Card>();
p3Cards.add(new Card("Conservatory", CardType.ROOM));
p3Cards.add(new Card("Pipe", CardType.WEAPON));
p3Cards.add(new Card("John", CardType.PERSON));
ArrayList<Card> p4Cards = new ArrayList<Card>();
p4Cards.add(new Card("Game room", CardType.ROOM));
p4Cards.add(new Card("Candlestick", CardType.WEAPON));
p4Cards.add(new Card("Fred", CardType.PERSON));
ArrayList<Card> p5Cards = new ArrayList<Card>();
p5Cards.add(new Card("Dressing room", CardType.ROOM));
p5Cards.add(new Card("Golf Club", CardType.WEAPON));
p5Cards.add(new Card("Joe", CardType.PERSON));
ArrayList<Card> p6Cards = new ArrayList<Card>();
p6Cards.add(new Card("Living room", CardType.ROOM));
p6Cards.add(new Card("Study", CardType.ROOM));
p6Cards.add(new Card("Hall", CardType.ROOM));
int i = 1;
for (Player player : board.getPlayers()) {
switch(i) {
case 1:
player.setMyCards(p1Cards);
break;
case 2:
player.setMyCards(p2Cards);
break;
case 3:
player.setMyCards(p3Cards);
break;
case 4:
player.setMyCards(p4Cards);
break;
case 5:
player.setMyCards(p5Cards);
break;
case 6:
player.setMyCards(p6Cards);
break;
}
i++;
}
// Tests suggestion no one can disprove.
Solution suggestion = new Solution("Greg", "Office", "Bottle");
Card result = board.handleSuggestionTest(suggestion, 0);
assert(result == null);
// Tests suggestion only accusing Player can disprove.
// Player 1 with the hand Kitchen/Gun/Jack is the only one that can disprove this
// Player 1 has index of 0 in players array
Solution suggestion2 = new Solution("Jack", "Office", "Bottle");
Card result2 = board.handleSuggestionTest(suggestion2, 0);
assert (result == null);
// Tests suggestion only human can disprove.
// Player 1 is human with the hand Kitchen/Gun/Jack
// Player 1 has index of 0 in players array - testing that player not being accuser
// result should be the Jack card.
Solution suggestion3 = new Solution("Jack", "Office", "Bottle");
Card result3 = board.handleSuggestionTest(suggestion3, 1);
assert (result3.getCardName() == "Jack");
// Tests suggestion only human can disprove, human is accuser.
// Player 1 is human with the hand Kitchen/Gun/Jack
// Player 1 has index of 0 in players array
// Should null
Solution suggestion4 = new Solution("Jack", "Office", "Bottle");
Card result4 = board.handleSuggestionTest(suggestion4, 0);
assert (result4 == null);
// Tests suggestion two players can disprove.
// Player 3 is asking (index is 2)
// Player 4 and 1 can disprove
// Player 4 should be the one to disprove it
// Result should be Game room
Solution suggestion5 = new Solution("Jack", "Game room", "Bottle");
Card result5 = board.handleSuggestionTest(suggestion5, 2);
assert (result5.getCardName() == "Game room");
}
}
| true |
52f0b8d6ff3e6cb163d755fe10be5a1f7694840b
|
Java
|
yshrdbrn/TeamXMatch
|
/src/BackEnd/AI.java
|
UTF-8
| 2,773 | 3.671875 | 4 |
[] |
no_license
|
package BackEnd;
import java.util.ArrayList;
import java.util.Collections;
/**
* Class used for all the AI features needed for the app
* It provides an API for finding 4 other people to play with for a certain user
*/
public class AI {
/**
* Finds best matches for the user requesting players to play with
* It sorts other users based on their dot product value and gets top users
* @param user the person who wants a match
* @param users potential candidates for the match
* @return a list of the other 4 users
*/
public ArrayList<User> findMatch(User user, ArrayList<User> users) {
ArrayList<User> availableUsers = new ArrayList<>();
//Filtering out all the players who are not available at the moment
for (User candidate : users) {
if(candidate.isFree() && candidate != user)
availableUsers.add(candidate);
}
ArrayList<User> input = new ArrayList<>();
input.add(user);
ArrayList<User> finalList = findBestPeople(input, availableUsers);
finalList.remove(0);
return finalList;
}
/**
* Finds the best people possible given the people that are already in the match
* @param chosenPeople the people that are already in the match
* @param availableUsers potential users to be matched
* @return the list of the whole team containing the user itself
*/
private ArrayList<User> findBestPeople(ArrayList<User> chosenPeople, ArrayList<User> availableUsers) {
if (chosenPeople.size() >= 5) //the match list is full
return chosenPeople;
ArrayList<User> temp = new ArrayList<>();
User user = chosenPeople.get(chosenPeople.size() - 1); //Last person added to the match
for (User availableUser : availableUsers) {
availableUser.calculateVector(user);
user.calculateVector(availableUser);
availableUser.calculateDotProduct(user.getVector());
}
Collections.sort(availableUsers, (a, b) -> (int)(b.getDotProductResult() - a.getDotProductResult()));
chosenPeople.add(availableUsers.get(0)); //Best match possible
availableUsers.remove(0);
if ( (chosenPeople.size() + availableUsers.size()/5 ) > 5 ) {
for (int i = 0; i < availableUsers.size() / 5; i++) { //Reducing the potential people array to 1/5 size
temp.add(availableUsers.get(i));
}
return findBestPeople(chosenPeople, temp);
}
else {
int count = 0;
while (chosenPeople.size() < 5) {
chosenPeople.add(availableUsers.get(count));
count++;
}
return chosenPeople;
}
}
}
| true |
2c089616e43817a58ec4590195b4ba1bdc2d8250
|
Java
|
peterhchen/100-java-adv
|
/src_ch01/StackProj/src/StackDemo.java
|
UTF-8
| 885 | 3.59375 | 4 |
[] |
no_license
|
import java.util.*;
public class StackDemo {
static void showpush (Stack st, int a) {
st.push (new Integer (a));
System.out.println ("push (" + a + ")");
System.out.println ("Stack: " + st);
}
static void showpop (Stack st) {
System.out.print ("pop -> ");
Integer a = (Integer) st.pop();
System.out.println (a);
System.out.println ("Stack: " + st);
}
public static void main (String[] args) {
Stack st = new Stack ();
System.out.println ("Stack: " + st);
showpush (st, 42);
showpush (st, 66);
showpush (st, 99);
showpop (st);
showpop (st);
showpop (st);
try {
showpop(st);
}
catch (EmptyStackException e) {
System.out.println ("Empty Stack: " + e);
}
}
}
| true |
a3658ccf8a18ad01e2916c4f7246c32945f55c25
|
Java
|
Bairei/crudespringmvccrud
|
/src/main/java/com/bairei/crudespringmvccrud/services/VisitServiceImpl.java
|
UTF-8
| 3,482 | 2.5 | 2 |
[] |
no_license
|
package com.bairei.crudespringmvccrud.services;
import com.bairei.crudespringmvccrud.domain.User;
import com.bairei.crudespringmvccrud.domain.Visit;
import com.bairei.crudespringmvccrud.repositories.VisitRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
@Component
public class VisitServiceImpl implements VisitService {
private VisitRepository visitRepository;
private MailingService mailingService;
@Autowired
public VisitServiceImpl(VisitRepository visitRepository, MailingService mailingService) {
this.visitRepository = visitRepository;
this.mailingService = mailingService;
}
private final static Logger log = Logger.getLogger(VisitServiceImpl.class.toString());
@Override
@Async
@Scheduled(cron = "0 0 20 * * *")
public void appointmentReminder() {
log.info("Initiating scheduled appointment reminding service");
for (Visit visit: visitRepository.findAll()){
Long date = new Date().getTime();
Long timeDifference = (visit.getDate().getTime()) - date;
log.info(timeDifference.toString());
if (timeDifference <= 24*3600*1000 && timeDifference > 0
&& (visit.getPatient().getEmail() != null
&& !visit.getPatient().getEmail().equals(""))) {
mailingService.sendSimpleMessage("[email protected]",
"Reminder about your visit on " + visit.getDate() + " with doctor "
+ visit.getDoctor().getName() + " " + visit.getDoctor().getSurname(),
"This email has been sent in order to remind you about your appointment with "
+ visit.getDoctor().getName() + " " + visit.getDoctor().getSurname()
+ " on " + visit.getDate() + ", in room no. " + visit.getConsultingRoom()
+ ".\n\n\nThis email has been sent automatically, please DO NOT respond.");
}
}
}
@Override
public Visit save(Visit visit) {
Visit result = visitRepository.save(visit);
if (result != null
&& result.getPatient().getEmail() != null
&& !result.getPatient().getEmail().equals("")) {
mailingService.sendSimpleMessage("[email protected]", "new visit scheduled on "
+ visit.getDate(), "You have been successfully scheduled on meeting with doctor "
+ visit.getDoctor().getName() + " " + visit.getDoctor().getSurname() + " on " + visit.getDate() + ", in room no. " + visit.getConsultingRoom());
}
return result;
}
@Override
public Visit saveOrUpdate(Visit visit) {
return visitRepository.save(visit);
}
@Override
public List<Visit> findAll() {
return visitRepository.findAll();
}
@Override
public Visit findOne(Integer id) {
return visitRepository.findOne(id);
}
@Override
public void delete(Integer id) {
visitRepository.delete(id);
}
@Override
public List<Visit> findAllByPatient(User patient) {
return visitRepository.findAllByPatient(patient);
}
}
| true |
d567f8e3310244655b5b755da0d01a3f075f580c
|
Java
|
wangshup/EServer
|
/EGameServer/src/main/java/com/dd/game/core/world/map/Point.java
|
UTF-8
| 3,428 | 3.109375 | 3 |
[] |
no_license
|
package com.dd.game.core.world.map;
import static java.lang.Math.max;
import static java.lang.Math.min;
/**
* @program: server
* @description: point
* @author: wangshupeng
* @create: 2019-01-04 17:07
**/
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public static int dot(Point a, Point b) {
return a.x * b.x + a.y * b.y;
}
public static int cross(Point a, Point b) {
return a.x * b.y - a.y * b.x;
}
public static boolean inSegment(Point p, Point a, Point b) {
Point pa = new Point(a.x - p.x, a.y - p.y);
Point pb = new Point(b.x - p.x, b.y - p.y);
return cross(pa, pb) == 0 && dot(pa, pb) <= 0;
}
public static boolean segmentIntersection(Point a1, Point a2, Point b1, Point b2) {
Point a2a1 = new Point(a2.x - a1.x, a2.y - a1.y);
Point b1a1 = new Point(b1.x - a1.x, b1.y - a1.y);
Point b2a1 = new Point(b2.x - a1.x, b2.y - a1.y);
Point b2b1 = new Point(b2.x - b1.x, b2.y - b1.y);
Point a1b1 = new Point(a1.x - b1.x, a1.y - b1.y);
Point a2b1 = new Point(a2.x - b1.x, a2.y - b1.y);
long c1 = cross(a2a1, b1a1), c2 = cross(a2a1, b2a1);
long c3 = cross(b2b1, a1b1), c4 = cross(b2b1, a2b1);
if (c1 * c2 < 0 && c3 * c4 < 0) {
return true;
}
if (c1 == 0 && inSegment(b1, a1, a2)) {
return true;
}
if (c2 == 0 && inSegment(b2, a1, a2)) {
return true;
}
if (c3 == 0 && inSegment(a1, b1, b2)) {
return true;
}
if (c4 == 0 && inSegment(a2, b1, b2)) {
return true;
}
return false;
}
/**
* 判断线段ab是否和矩形相交
*
* @param rectLD 矩形的左下点
* @param rectRU 矩形的右上点
* @param a 线段点a
* @param b 线段点b
* @return
*/
public static boolean rectIntersection(Point rectLD, Point rectRU, Point a, Point b) {
int rect_minX = min(rectLD.x, rectRU.x), rect_maxX = max(rectLD.x, rectRU.x);
int rect_minY = min(rectLD.y, rectRU.y), rect_maxY = max(rectLD.y, rectRU.y);
int line_minX = min(a.x, b.x), line_maxX = max(a.x, b.x);
int line_minY = min(a.y, b.y), line_maxY = max(a.y, b.y);
if (rect_minX <= line_minX && line_maxX <= rect_maxX && rect_minY <= line_minY && line_maxY <= rect_maxY) {
return true;//线段在矩形内
} else {
Point[] p = {new Point(rect_minX, rect_minY), new Point(rect_maxX, rect_minY), new Point(rect_maxX, rect_maxY), new Point(rect_minX, rect_maxY)};
for (int i = 0; i < 4; ++i)
if (segmentIntersection(a, b, p[i], p[(i + 1) % 4])) {
return true;
}
}
return false;
}
public static void main(String[] args) {
Point rLD = new Point(80, 80);
Point rRU = new Point(100, 100);
Point a = new Point(0, 0);
Point b = new Point(195, 244);
boolean bool = rectIntersection(rLD, rRU, a, b);
System.out.println(bool);
}
}
| true |
e1de44b27780d1e051be052594441d843226140d
|
Java
|
P79N6A/parking
|
/zhuyi-parking/zhuyi-parking-modules/zhuyi-parking-tool/zhuyi-parking-tool-api-java/src/main/java/com/zhuyitech/parking/tool/dto/request/notification/NotificationSendRequestDto.java
|
UTF-8
| 1,641 | 1.976563 | 2 |
[] |
no_license
|
package com.zhuyitech.parking.tool.dto.request.notification;
import com.alibaba.fastjson.JSONObject;
import com.scapegoat.infrastructure.core.dto.basic.BaseDto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Map;
/**
* 通知消息发送请求参数
*
* @author walkman
*/
@Data
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "NotificationSendRequestDto", description = "通知消息发送请求参数")
public class NotificationSendRequestDto extends BaseDto {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
/**
* 模板ID
*/
@ApiModelProperty(value = "模板ID")
private String templateId;
/**
* 用户编号
*/
@ApiModelProperty(value = "用户编号")
private Long userId;
/**
* 消息通知类型(1:通知 2:活动 3:互动 4:快报)
*/
@ApiModelProperty(value = "消息通知类型(1:通知 2:活动 3:互动 4:快报)")
private Integer notifyType;
/**
* 业务类型
*/
@ApiModelProperty(value = "业务类型")
private Integer bizType;
/**
* 标题
*/
@ApiModelProperty(value = "标题")
private String title;
/**
* 消息参数(替换模板中的参数)
*/
@ApiModelProperty(value = "parameters", notes = "消息参数")
private Map<Object, Object> parameters;
/**
* JSON形式的消息内容
*/
@ApiModelProperty(value = "JSON形式的消息内容")
private JSONObject data = new JSONObject();
}
| true |
59a8f464205902c34eb50394dc8cd1d1f8b14cde
|
Java
|
lorran-mariuba/test-api-rest-spring-boot
|
/src/main/java/com/example/Car.java
|
UTF-8
| 2,111 | 2.765625 | 3 |
[] |
no_license
|
package com.example;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Car {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String marca;
String modelo;
Integer ano;
public Car() {
}
public Car(Long id, String marca, String modelo, Integer ano) {
this.id = id;
this.marca = marca;
this.modelo = modelo;
this.ano = ano;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getModelo() {
return modelo;
}
public void setModelo(String modelo) {
this.modelo = modelo;
}
public Integer getAno() {
return ano;
}
public void setAno(Integer ano) {
this.ano = ano;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((ano == null) ? 0 : ano.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((marca == null) ? 0 : marca.hashCode());
result = prime * result + ((modelo == null) ? 0 : modelo.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Car other = (Car) obj;
if (ano == null) {
if (other.ano != null)
return false;
} else if (!ano.equals(other.ano))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (marca == null) {
if (other.marca != null)
return false;
} else if (!marca.equals(other.marca))
return false;
if (modelo == null) {
if (other.modelo != null)
return false;
} else if (!modelo.equals(other.modelo))
return false;
return true;
}
}
| true |
765a3d5f812457e50abadf729f29178669c0b00f
|
Java
|
kennethrsps/helwyrrsps
|
/src/com/rs/game/npc/others/CommandZombie.java
|
UTF-8
| 951 | 2.5 | 2 |
[] |
no_license
|
package com.rs.game.npc.others;
import com.rs.game.World;
import com.rs.game.WorldTile;
import com.rs.game.item.Item;
import com.rs.game.npc.Drop;
import com.rs.game.npc.NPC;
import com.rs.game.player.Player;
@SuppressWarnings("serial")
public class CommandZombie extends NPC {
private Item Rareitem;
public CommandZombie(int id, Item Rareitem, WorldTile tile, int mapAreaNameHash, boolean canBeAttackFromOutOfArea,
boolean spawned) {
super(id, tile, mapAreaNameHash, canBeAttackFromOutOfArea, spawned);
this.Rareitem = Rareitem;
}
@Override
public void drop() {
Player killer = getMostDamageReceivedSourcePlayer();
if (killer == null)
return;
super.drop();
if (Rareitem != null) {
World.sendNews(
killer.getDisplayName() + " has recived " + Rareitem.getAmount() + " x " + Rareitem.getName() + ".",
1);
this.sendDrop(killer, new Drop(Rareitem.getId(), Rareitem.getAmount(), Rareitem.getAmount()));
}
}
}
| true |
ff3e29b8bc01a2003c2d346db55ed4c06ff2caf5
|
Java
|
chljapan/KayaSmart
|
/src/main/java/org/isis/gme/bon/JBuilderModelReference.java
|
UTF-8
| 3,695 | 2.296875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.isis.gme.bon;
import java.util.*;
import org.isis.gme.mga.*;
import org.isis.gme.meta.*;
public class JBuilderModelReference extends JBuilderReference
{
protected Hashtable<String, JBuilderReferencePort> objectmap;
protected Vector<JBuilderReferencePort> refPorts;
public JBuilderModelReference(MgaReference iModelRef, JBuilderModel parent)
{ super(iModelRef,parent);
objectmap = new Hashtable<String, JBuilderReferencePort>();
refPorts = new Vector<JBuilderReferencePort>();
createReferencePorts();
}
protected void createReferencePorts()
{ MgaFCOs children;
MgaFCO r = getIModelRef();
while(true)
{
//MgaFCO rr = ((MgaReference)r).getReferred();
MgaReference ref = new MgaReference(r);
MgaFCO rr = ref.getReferred();
r = rr;
if(r==null)
break;
int o = r.getObjType();
if(o==MgaObject.OBJTYPE_MODEL)
break;
//Support.Assert(o==objtype_enum.OBJTYPE_REFERENCE," Not a reference");
}
if(r!=null)
{ children = (new MgaModel(r)).getChildFCOs();
int chCount = children.getCount();
for(int i=0;i<chCount;i++)
{ MgaFCO child = children.getItem(i);
MgaMetaRole role = child.getMetaRole();
MgaMetaParts parts = role.getParts();
int paCount = parts.getCount();
int j;
for(j=0;j<paCount;j++)
{ MgaMetaPart part = parts.getItem(j);
boolean vv = part.getIsLinked();
if(vv)
break;
}
if(j<=paCount)
{
JBuilderReferencePort bPort = new JBuilderReferencePort(child,this);
refPorts.add(bPort);
}
}
}
}
public void resolve()
{
super.resolve();
//Support.Assert(ref!=null,"JBuilderModelReference Resolve");
Class<?> JBuilderModelReferenceClass;
Class<?> JBuilderModelClass;
try
{
JBuilderModelReferenceClass = Class.forName("org.isis.gme.bon.JBuilderModelReference");
JBuilderModelClass = Class.forName("org.isis.gme.bon.JBuilderModel");
}
catch(ClassNotFoundException ex)
{ //Support.Assert(false, "In Model and Reference class not found");
return;
}
JBuilderModelReferenceClass.isAssignableFrom(ref.getClass());
JBuilderModelClass.isAssignableFrom(ref.getClass());
int reCount = refPorts.size();
for(int it=0;it<reCount;it++)
{ ((JBuilderReferencePort)refPorts.elementAt(it)).resolve();
}
}
protected MgaObject getPort(String aspectName, JBuilderReferencePort port)
{ return port.getIObject();
}
protected JBuilderReferencePort findPortRef(MgaFCO i)
{ //Support.Assert(i!=null,"JBuilderModelReference FindPortRef");
MgaFCO ii = i;
JBuilderReferencePort o = (JBuilderReferencePort)objectmap.get(ii.getID());
if(o==null)
{ i.getID();
}
return o;
}
protected void setPortRef(MgaFCO i, JBuilderReferencePort o)
{ //Support.Assert(i!=null && o!=null, "JBuilderModelReference SetPortRef");
JBuilderReferencePort o2 = (JBuilderReferencePort)objectmap.get(i.getID());
if(o2!=null)
{ //Support.Assert(o==o2,"Difference in the object map and provided");
}
else
{ String strId = i.getID();
objectmap.put(strId,o);
}
}
protected void forgetPortRef(MgaFCO i)
{ //Support.Assert(i!=null,"JBuilderModelReference ForgetPortRef");
objectmap.remove(i.getID());
}
public void initialize()
{
}
///////////////////////////////For the users ///////////////////////////////////
public MgaReference getIModelRef()
{ return getIRef();
}
public Vector<JBuilderReferencePort> getReferencePorts()
{ return refPorts;
}
public JBuilderObject getReferred()
{ return ref;
}
}
| true |
7e277d07d8a15d8bc4ee96d9ba4fb2d661df3a08
|
Java
|
daalft/SandhiResolver
|
/SandhiSolver/src/general/Rule.java
|
UTF-8
| 1,804 | 3.703125 | 4 |
[] |
no_license
|
package general;
import java.util.List;
/**
* Represents a replacement rule with a left hand side indicating what to replace (regex)
* and the right hand side indicating with what to replace (regex with back reference)
* @author David
*
*/
public class Rule {
/////////////////////////////////////////////////
// Variables
/////////////////////////////////////////////////
private String left, right;
/////////////////////////////////////////////////
// Constructors
/////////////////////////////////////////////////
public Rule() {}
public Rule(String l, String r) {
left = l;
right = r;
}
public Rule(List<Token> list) {
this(list.get(0).getContent(), list.get(2).getContent());
}
/////////////////////////////////////////////////
// Methods
/////////////////////////////////////////////////
/**
* Applies the rule at the first possible location
* and returns the result
* @param s string
* @return string with this rule applied (if applicable)
* @see #isApplicable(String)
*/
public String applyFirst(String s) {
return s.replaceFirst(left, right);
}
/**
* Applies the rule at every possible location
* and returns the result
* @param s string
* @return string with this rule applied globally (if applicable)
* @see #isApplicable(String)
*/
public String applyAll(String s) {
return s.replaceAll(left, right);
}
/**
* Checks whether this rule can be applied to the given string
* @param s string
* @return <b>true</b> if this rule can be applied to given string, <b>false</b> otherwise
*/
public boolean isApplicable(String s) {
return s.matches(left);
}
@Override
public String toString() {
return left + " -> " + right;
}
}
| true |
dd89959aa70b9a50de98503247f58fcb5fecb68f
|
Java
|
4a256b6b3e7t3e8b7t9q7t/jmitm2
|
/com/sshtools/j2ssh/ui/AuthenticationDialog.java
|
UTF-8
| 8,024 | 2.625 | 3 |
[] |
no_license
|
/*
* Sshtools - Java SSH2 API
*
* Copyright (C) 2002 Lee David Painter.
*
* Written by: 2002 Lee David Painter <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public License
* as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package com.sshtools.j2ssh.ui;
import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.border.*;
import com.sshtools.j2ssh.ui.*;
import com.sshtools.j2ssh.util.*;
import com.sshtools.apps.*;
/**
* <p>
*
* Displays the list of availble authentication methods and allows the user to
* select on or more to authenticate with.</p>
*
*@author Lee David Painter (<A HREF="mailto:[email protected]">
* [email protected]</A> )
*@author Brett Smith
*@created 31 August 2002
*@version $Id: AuthenticationDialog.java,v 1.2 2003/02/23 11:23:29 martianx Exp $
*/
public class AuthenticationDialog extends JDialog {
/**
* The dialog components
*/
JList jListAuths = new JList();
JLabel messageLabel = new JLabel();
boolean cancelled = false;
/**
* The Constructor
*/
public AuthenticationDialog() {
super((Frame)null, "Select Authentication Method(s)", true);
init();
}
/**
* The Constructor
*
*@param frame The parent frame
*/
public AuthenticationDialog(Frame frame) {
super(frame, "Select Authentication Method(s)", true);
init();
}
/**
* The Constructor
*
*@param dialog The parent dialog
*/
public AuthenticationDialog(Dialog dialog) {
super(dialog, "Select Authentication Method(s)", true);
init();
}
/**
* Initialise
*/
void init() {
try {
jbInit();
pack();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Sets the authentication list to be displayed
*
*@param methods A list of methods
*/
private void setMethodList(java.util.List methods) {
jListAuths.setListData(methods.toArray());
if(methods.size() > 0)
jListAuths.setSelectedIndex(0);
}
/**
* Initiates the dialog
*
*@throws Exception
*/
void jbInit() throws Exception {
//
setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
//
messageLabel.setForeground(Color.red);
messageLabel.setHorizontalAlignment(JLabel.CENTER);
// Create the list of available methods and put in in a scroll panel
jListAuths = new JList();
jListAuths.setVisibleRowCount(5);
JPanel listPanel = new JPanel(new GridLayout(1, 1));
listPanel.setBorder(BorderFactory.createEmptyBorder(4, 0, 0, 0));
listPanel.add(new JScrollPane(jListAuths));
// Main panel
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
centerPanel.add(new JLabel(
"Please select an authentication method(s) to continue."),
BorderLayout.NORTH);
centerPanel.add(listPanel, BorderLayout.CENTER);
// Create the bottom button panel
JButton proceed = new JButton("Proceed");
proceed.setMnemonic('p');
proceed.setDefaultCapable(true);
proceed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// I presume this component **is** reused?
hide();
}
});
getRootPane().setDefaultButton(proceed);
JButton cancel = new JButton("Cancel");
cancel.setMnemonic('c');
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
cancelled = true;
hide();
}
});
JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
southPanel.setBorder(BorderFactory.createEmptyBorder(4, 0, 0, 0));
southPanel.add(cancel);
southPanel.add(proceed);
// Create the center banner panel
IconWrapperPanel iconPanel = new IconWrapperPanel(
new ResourceIcon(SshToolsConnectionHostTab.AUTH_ICON), centerPanel);
iconPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
// The main panel contains everything and is surrounded by a border
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
mainPanel.add(messageLabel, BorderLayout.NORTH);
mainPanel.add(iconPanel, BorderLayout.CENTER);
mainPanel.add(southPanel, BorderLayout.SOUTH);
// Build the main panel
getContentPane().setLayout(new GridLayout(1, 1));
getContentPane().add(mainPanel);
}
/**
* Convenience method to work out the parent window given a component and
* show the dialog
*
* @param parent parent component
* @param support support auth. method
* @return list selected auth. methods
*/
public static java.util.List showAuthenticationDialog(Component parent, java.util.List support) {
return showAuthenticationDialog(parent, support, null);
}
/**
* Convenience method to work out the parent window given a component and
* show the dialog
*
* @param parent parent component
* @param support support auth. method
* @param message message
* @return list selected auth. methods
*/
public static java.util.List showAuthenticationDialog(
Component parent, java.util.List support, String message) {
Window w = (Window)SwingUtilities.getAncestorOfClass(Window.class, parent);
AuthenticationDialog dialog = null;
if(w instanceof Frame)
dialog = new AuthenticationDialog((Frame)w);
else if(w instanceof Dialog)
dialog = new AuthenticationDialog((Dialog)w);
else
dialog = new AuthenticationDialog();
UIUtil.positionComponent(SwingConstants.CENTER, dialog);
return dialog.showAuthenticationMethods(support, message);
}
/**
* Call this method to show the dialog and return the list of selected
* methods
*
*@param supported
*@return
*/
public java.util.List showAuthenticationMethods(
java.util.List supported, String message) {
// Set the list
this.setMethodList(supported);
// Show the dialog
UIUtil.positionComponent(SwingConstants.CENTER, this);
if(message != null) {
messageLabel.setVisible(true);
messageLabel.setText(message);
}
else {
messageLabel.setVisible(false);
}
pack();
toFront();
setVisible(true);
// Put the selected values into a new list and return
java.util.List list = new ArrayList();
if(!cancelled) {
Object[] methods = jListAuths.getSelectedValues();
if (methods != null) {
for (int i = 0; i < methods.length; i++) {
list.add(methods[i]);
}
}
}
return list;
}
/**
* Handles the proceed button event
*
*@param e
*/
void jButtonProceed_actionPerformed(ActionEvent e) {
hide();
}
}
| true |
b14781ef220240e4299def697035383d3c7fe010
|
Java
|
FBDC-NTI/Bahiana
|
/br.edu.bahiana.core/src/br/edu/bahiana/core/datainterfaces/AccessDataObjectList.java
|
UTF-8
| 251 | 2.140625 | 2 |
[] |
no_license
|
package br.edu.bahiana.core.datainterfaces;
import java.util.List;
public interface AccessDataObjectList<T> {
List<T> getObjects();
List<T> getObjects(int size);
List<T> getObjects(int start, int size);
T getObject(long id, Class<T> clazz);
}
| true |
bc221addd3cb9ce73085d4358c8078e0dac4db6c
|
Java
|
weimeiche/CustomView
|
/app/src/main/java/com/navyliu/customview/constants/URLs.java
|
UTF-8
| 568 | 1.867188 | 2 |
[] |
no_license
|
package com.navyliu.customview.constants;
/**
*
* @Title: URLs.java
* @Description: 应用所有需要访问的网络URL
* @author: navyLiu
* @data: 2016-6-16 下午5:49:11
* @version: V1.0
*/
public class URLs {
/***访问路径***/
public static final String BASE_PATH = "http://192.168.1.101/";
public static final String URL_PATH = "http://192.168.1.101/";
// /***访问路径***/
// public static final String BASE_PATH = "http://192.168.1.101/freeGift/";
// public static final String URL_PATH = "http://192.168.1.101/freeGift/android/";
}
| true |
ab2c7825f77b645535322e1f15b1daa7bf7bfb49
|
Java
|
mafeosza/alertasTempranas_android
|
/android/src/gnu/kawa/xml/Document$DocReference.java
|
UTF-8
| 599 | 1.695313 | 2 |
[] |
no_license
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package gnu.kawa.xml;
import gnu.text.Path;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
// Referenced classes of package gnu.kawa.xml:
// Document, KDocument
private static class key extends SoftReference
{
static ReferenceQueue queue = new ReferenceQueue();
Path key;
public (Path path, KDocument kdocument)
{
super(kdocument, queue);
key = path;
}
}
| true |
c8cd9fd3bd4bffedc621d1d31cea142ac5c39875
|
Java
|
Schernigin/java-a-to-z
|
/OOP/tracker/src/main/java/ru/schernigin/models/Comments.java
|
UTF-8
| 838 | 2.953125 | 3 |
[
"Apache-2.0"
] |
permissive
|
package ru.schernigin.models;
/**
* the Class Comments.
* @author Schernigin.
* @since 21.01.2017
* @version 1.0
*/
public class Comments {
/*
* the private fild for class Commments.
*/
private String comment;
/**
* Default constructor for the class Comment.
*/
public Comments() {
}
/**
* Constructor for the class Comment.
* @param comment for the Constructor.
*/
public Comments(String comment) {
this.comment = comment;
}
/**
* Getter for the field "comment".
* @return comment
*/
public String getComment() {
return comment;
}
/**
* Setter for the field "comment".
* @param comment of Comment
*/
public void setComment(String comment) {
this.comment = comment;
}
}
| true |
d0dacee854601cf29a9a96470a0adc6751dfaad2
|
Java
|
lucasSaavedra123/programacionOrientadaAObjetos1
|
/Java/unidad3-objetosYClasesEnJava/ejercicio2-piopioMensajero/src/structure/Main.java
|
UTF-8
| 881 | 2.796875 | 3 |
[] |
no_license
|
package structure;
import domain.*;
public class Main {
public static void main(String [] args) {
Lugar lugarUno = new Lugar("Buenos Aires", 0);
Lugar lugarDos = new Lugar("Chascomús", 122);
Lugar lugarTres = new Lugar("Lezama", 156);
Lugar lugarCuatro = new Lugar("Dolores", 210);
Lugar lugarCinco = new Lugar("Las Armas", 300);
Lugar lugarSeis = new Lugar("Mar Del Plata", 400);
Ave piopio = new Ave("Piopio", lugarTres);
System.out.println(piopio);
piopio.comer(10);
System.out.println(piopio.getEnergia());
System.out.println(piopio.volarAUnLugar(lugarCinco));
System.out.println(piopio.volarAUnLugar(lugarDos));
System.out.println(piopio.volarAUnLugar(lugarTres));
System.out.println(piopio.volarAUnLugar(lugarDos));
System.out.println(piopio.volarAUnLugar(lugarSeis));
System.out.println(piopio.sePuedeVolarAlLugar(lugarSeis));
}
}
| true |
0297619ccb7af5821dff8242ccac3a77960e4485
|
Java
|
ldramirez/transparencia
|
/transparencia/src/modelo/Gestionador.java
|
UTF-8
| 4,492 | 1.9375 | 2 |
[] |
no_license
|
package modelo;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the gestionador database table.
*
*/
@Entity
@Table(name="GESTIONADOR")
@NamedQueries({
@NamedQuery(name="Gestionador.findAll", query="SELECT g FROM Gestionador g"),
@NamedQuery(name = "Gestionador.findByCedulaGestionador", query = "SELECT g FROM Gestionador g WHERE g.cedulaGestionador = :cedulaGestionador"),
@NamedQuery(name = "Gestionador.findByCedulaPasswordGestionador", query = "SELECT g FROM Gestionador g WHERE g.cedulaGestionador = :cedulaGestionador and g.contrasenaGestionador=:contrasenaGestionador")})
public class Gestionador implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private int cedulaGestionador;
private String apellidoGestionador;
private String contrasenaGestionador;
private String emailGestionador;
private boolean estadoGestionado;
private String nombreGestionador;
//bi-directional many-to-one association to Empresa
@ManyToOne
@JoinColumns({
@JoinColumn(name="Empresa_Ciudad_Departamento_idDepartamento", referencedColumnName="Ciudad_Departamento_idDepartamento"),
@JoinColumn(name="Empresa_Ciudad_idCiudad", referencedColumnName="Ciudad_idCiudad"),
@JoinColumn(name="Empresa_idEmpresa", referencedColumnName="idEmpresa")
})
private Empresa empresa;
public Gestionador() {
}
public String getApellidoGestionador() {
return this.apellidoGestionador;
}
public void setApellidoGestionador(String apellidoGestionador) {
this.apellidoGestionador = apellidoGestionador;
}
public String getContrasenaGestionador() {
return this.contrasenaGestionador;
}
public void setContrasenaGestionador(String contrasenaGestionador) {
this.contrasenaGestionador = contrasenaGestionador;
}
public String getEmailGestionador() {
return this.emailGestionador;
}
public void setEmailGestionador(String emailGestionador) {
this.emailGestionador = emailGestionador;
}
public boolean getEstadoGestionado() {
return this.estadoGestionado;
}
public void setEstadoGestionado(boolean estadoGestionado) {
this.estadoGestionado = estadoGestionado;
}
public String getNombreGestionador() {
return this.nombreGestionador;
}
public void setNombreGestionador(String nombreGestionador) {
this.nombreGestionador = nombreGestionador;
}
public Empresa getEmpresa() {
return this.empresa;
}
public void setEmpresa(Empresa empresa) {
this.empresa = empresa;
}
@Column(insertable=false, updatable=false)
private int empresa_idEmpresa;
@Column(insertable=false, updatable=false)
private int empresa_Ciudad_idCiudad;
@Column(insertable=false, updatable=false)
private int empresa_Ciudad_Departamento_idDepartamento;
public int getCedulaGestionador() {
return this.cedulaGestionador;
}
public void setCedulaGestionador(int cedulaGestionador) {
this.cedulaGestionador = cedulaGestionador;
}
public int getEmpresa_idEmpresa() {
return this.empresa_idEmpresa;
}
public void setEmpresa_idEmpresa(int empresa_idEmpresa) {
this.empresa_idEmpresa = empresa_idEmpresa;
}
public int getEmpresa_Ciudad_idCiudad() {
return this.empresa_Ciudad_idCiudad;
}
public void setEmpresa_Ciudad_idCiudad(int empresa_Ciudad_idCiudad) {
this.empresa_Ciudad_idCiudad = empresa_Ciudad_idCiudad;
}
public int getEmpresa_Ciudad_Departamento_idDepartamento() {
return this.empresa_Ciudad_Departamento_idDepartamento;
}
public void setEmpresa_Ciudad_Departamento_idDepartamento(int empresa_Ciudad_Departamento_idDepartamento) {
this.empresa_Ciudad_Departamento_idDepartamento = empresa_Ciudad_Departamento_idDepartamento;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Gestionador)) {
return false;
}
Gestionador castOther = (Gestionador)other;
return
(this.cedulaGestionador == castOther.cedulaGestionador)
&& (this.empresa_idEmpresa == castOther.empresa_idEmpresa)
&& (this.empresa_Ciudad_idCiudad == castOther.empresa_Ciudad_idCiudad)
&& (this.empresa_Ciudad_Departamento_idDepartamento == castOther.empresa_Ciudad_Departamento_idDepartamento);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.cedulaGestionador;
hash = hash * prime + this.empresa_idEmpresa;
hash = hash * prime + this.empresa_Ciudad_idCiudad;
hash = hash * prime + this.empresa_Ciudad_Departamento_idDepartamento;
return hash;
}
}
| true |
57ee4926034c0bf241ef9776373c9121280d9185
|
Java
|
zhongxingyu/Seer
|
/Diff-Raw-Data/6/6_514381e107e48007a95c1beaffee0446b0dc092f/ImportLibrariesListTest/6_514381e107e48007a95c1beaffee0446b0dc092f_ImportLibrariesListTest_t.java
|
UTF-8
| 1,562 | 2.078125 | 2 |
[] |
no_license
|
package net.sf.eclipsefp.haskell.core.test.project;
import java.io.File;
import org.eclipse.core.resources.IProject;
import org.osgi.service.prefs.Preferences;
import junit.framework.TestCase;
import static org.easymock.EasyMock.*;
import net.sf.eclipsefp.haskell.core.project.IProjectPropertiesEvent;
import net.sf.eclipsefp.haskell.core.project.ImportLibrariesList;
import net.sf.eclipsefp.haskell.core.test.project.util.NullProjectPropertiesEvent;
import net.sf.eclipsefp.haskell.core.test.project.util.PreferencesStub;
public class ImportLibrariesListTest extends TestCase {
public void testSavesToOsgiPreferences() {
TestingLibrariesList list = new TestingLibrariesList();
list.add(list.createLibrary("/usr/lib", true));
list.save();
Preferences prefs = list.getPreferences();
assertEquals("/usr/lib,t".replace('/', File.separatorChar),
prefs.get("PROJECT_IMPORT_LIBRARIES", ""));
}
}
class TestingLibrariesList extends ImportLibrariesList {
private Preferences fPreferences;
public TestingLibrariesList() {
super(createNiceMock(IProject.class));
}
@Override protected Preferences createPrefs() {
return getPreferences();
}
@Override protected IProjectPropertiesEvent createProjectPropertiesEvent() {
return new NullProjectPropertiesEvent();
}
@Override protected String haskellCorePluginId() {
return "testing.plugin";
}
public Preferences getPreferences() {
if (fPreferences == null) fPreferences = new PreferencesStub();
return fPreferences;
}
}
| true |
769c480c4726aa83628f65c8942945a165f3264f
|
Java
|
ronanwatkins/Princeton_StdLib_2D_Side_Scroller
|
/src/Game.java
|
UTF-8
| 2,848 | 2.984375 | 3 |
[] |
no_license
|
import java.util.Random;
/**
* Created by lxn on 30/12/2016.
*/
public class Game{
static Bob bob;
static int bobx = 100, boby = 125, bobCount = 0, bobStage = 0, playerX = 0, playerX2 = 0;
static int backgroundX1 = 600, backgroundX2 = 0;
static int[] bottomblockx = new int[9];
static boolean goingBack = false;
public static void main(String[] args) {
Random random = new Random();
bob = new Bob(bobx, boby);
StdDraw.setCanvasSize(600,400);
StdDraw.setXscale(0,600);
StdDraw.setYscale(0,400);
StdDraw.enableDoubleBuffering();
StdDraw.picture(400,200,"/images/background.png",800,400);
int bottomCoords = 0;
for (int i = 8; i >= 0; i--) {
bottomblockx[i] = bottomCoords;
bottomCoords -= 100;
}
for (int i = 0; i <= 8; i++) {
System.out.println(bottomblockx[i]);
}
while (true) {
buttonPressed();
bob.update();
drawBackground();
bob.draw(bobx, bobStage);
StdDraw.show();
}
}
static void buttonPressed(){
if(StdDraw.isKeyPressed(68)){
goingBack = false;
bobCount++;
if(bobCount % 8 == 0){
if(bobStage < 4)
bobStage += 1;
else bobStage = 0;
bobCount = 0;
}
if(bobx <= 100)
bobx++;
else{
for (int i = 0; i < 9; i++) {
bottomblockx[i]++;
}
backgroundX1++;
backgroundX2++;
playerX+=2;
playerX2++;
}
} else if(StdDraw.isKeyPressed(65)){
goingBack = true;
bobCount--;
if(bobCount == 0)
bobCount = 8;
if(bobCount % 8 == 0 && bobx > 10){
if(bobStage > 0)
bobStage -= 1;
else bobStage = 4;
bobCount = 4;
}
if(bobx > 10) {
bobx--;
}
bob.draw(bobx, bobStage);
}
}
static void drawBackground(){
if(playerX != 0 && ((playerX - 400) % 3200 == 0))
backgroundX2 = 0;
if(playerX != 0 && ((playerX - 1600) % 3200 == 0))
backgroundX1 = -200;
StdDraw.picture((600 - backgroundX1)+400,200,"/images/background.png",800,400);
StdDraw.picture((600 - backgroundX1)+400,50,"/images/bottomblock.png",800,100);
if(playerX >= 400) {
StdDraw.picture((600 - backgroundX2) + 400, 200, "/images/background.png", 800, 400);
StdDraw.picture((600 - backgroundX2)+400,50,"/images/bottomblock.png",800,100);
}
}
}
| true |
ddefae181f4c63e4ebe2a5a66ac65db97ee98297
|
Java
|
fashionzzZ/fashion-study
|
/fashion-redis/src/main/java/com/fashion/redis/FashionRedisApplication.java
|
UTF-8
| 334 | 1.507813 | 2 |
[] |
no_license
|
package com.fashion.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class FashionRedisApplication {
public static void main(String[] args) {
SpringApplication.run(FashionRedisApplication.class, args);
}
}
| true |
28ad0714169b4220d994e609b80e0e3be18e9a3d
|
Java
|
keval02/OneSidedCab
|
/app/src/main/java/com/onesidedcabs/FeedbackFormActivity.java
|
UTF-8
| 11,551 | 1.742188 | 2 |
[] |
no_license
|
package com.onesidedcabs;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.onesidedcabs.helper.PrefUtils;
import com.onesidedcabs.helper.RetrfitInterface;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class FeedbackFormActivity extends AppCompatActivity {
Toolbar toolbar;
Custom_ProgressDialog loadingView;
RadioGroup rg_que1, rg_que2, rg_que3, rg_que4, rg_que5;
RadioButton rb_good1, rb_better1, rb_excellent1, rb_good2, rb_better2, rb_excellent2, rb_good3, rb_better3, rb_excellent3, rb_good4, rb_better4, rb_excellent4, rb_good5, rb_better5, rb_excellent5;
String json = "";
String answer1 = "";
String answer2 = "";
String answer3 = "";
String answer4 = "";
String answer5 = "";
Button btn_submit;
RadioButton rbAnswer1;
RadioButton rbAnswer2;
RadioButton rbAnswer3;
RadioButton rbAnswer4;
RadioButton rbAnswer5;
private ProgressDialog loading;
String orderID = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feedback_form);
Intent intent = getIntent();
orderID = intent.getStringExtra("orderID");
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
rg_que1 = (RadioGroup) findViewById(R.id.rg_que1);
rg_que2 = (RadioGroup) findViewById(R.id.rg_que2);
rg_que3 = (RadioGroup) findViewById(R.id.rg_que3);
rg_que4 = (RadioGroup) findViewById(R.id.rg_que4);
rg_que5 = (RadioGroup) findViewById(R.id.rg_que5);
rb_good1 = (RadioButton) findViewById(R.id.rb_good1);
rb_good2 = (RadioButton) findViewById(R.id.rb_good2);
rb_good3 = (RadioButton) findViewById(R.id.rb_good3);
rb_good4 = (RadioButton) findViewById(R.id.rb_good4);
rb_good5 = (RadioButton) findViewById(R.id.rb_good5);
rb_better1 = (RadioButton) findViewById(R.id.rb_better1);
rb_better2 = (RadioButton) findViewById(R.id.rb_better2);
rb_better3 = (RadioButton) findViewById(R.id.rb_better3);
rb_better4 = (RadioButton) findViewById(R.id.rb_better4);
rb_better5 = (RadioButton) findViewById(R.id.rb_better5);
rb_excellent1 = (RadioButton) findViewById(R.id.rb_excellent1);
rb_excellent2 = (RadioButton) findViewById(R.id.rb_excellent2);
rb_excellent3 = (RadioButton) findViewById(R.id.rb_excellent3);
rb_excellent4 = (RadioButton) findViewById(R.id.rb_excellent4);
rb_excellent5 = (RadioButton) findViewById(R.id.rb_excellent5);
rb_better1.setChecked(true);
rb_better2.setChecked(true);
rb_better3.setChecked(true);
rb_better4.setChecked(true);
rb_better5.setChecked(true);
btn_submit = (Button) findViewById(R.id.btn_done);
rg_que1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
int pos = rg_que1.indexOfChild(findViewById(checkedId));
int pos1 = rg_que1.indexOfChild(findViewById(rg_que1.getCheckedRadioButtonId()));
switch (pos) {
case R.id.rb_good1:
break;
case R.id.rb_better1:
break;
case R.id.rb_excellent1:
break;
default:
break;
}
}
});
rg_que2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
int pos = rg_que2.indexOfChild(findViewById(checkedId));
int pos1 = rg_que2.indexOfChild(findViewById(rg_que2.getCheckedRadioButtonId()));
switch (pos) {
case R.id.rb_good2:
break;
case R.id.rb_better2:
break;
case R.id.rb_excellent2:
break;
default:
break;
}
}
});
rg_que3.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
int pos = rg_que3.indexOfChild(findViewById(checkedId));
int pos1 = rg_que3.indexOfChild(findViewById(rg_que3.getCheckedRadioButtonId()));
switch (pos) {
case R.id.rb_good3:
break;
case R.id.rb_better3:
break;
case R.id.rb_excellent3:
break;
default:
break;
}
}
});
rg_que4.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
int pos = rg_que1.indexOfChild(findViewById(checkedId));
int pos1 = rg_que1.indexOfChild(findViewById(rg_que4.getCheckedRadioButtonId()));
switch (pos) {
case R.id.rb_good4:
break;
case R.id.rb_better4:
break;
case R.id.rb_excellent4:
break;
default:
break;
}
}
});
rg_que5.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
int pos = rg_que1.indexOfChild(findViewById(checkedId));
int pos1 = rg_que1.indexOfChild(findViewById(rg_que5.getCheckedRadioButtonId()));
switch (pos) {
case R.id.rb_good5:
break;
case R.id.rb_better5:
break;
case R.id.rb_excellent5:
break;
default:
break;
}
}
});
btn_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!Internet.isConnectingToInternet(getApplicationContext())) {
Internet.noInternet(getApplicationContext());
} else {
RadioButton radioButton1 = (RadioButton) rg_que1.findViewById(rg_que1.getCheckedRadioButtonId());
answer1 =radioButton1.getText().toString();
RadioButton radioButton2 = (RadioButton) rg_que2.findViewById(rg_que2.getCheckedRadioButtonId());
answer2 =radioButton2.getText().toString();
RadioButton radioButton3 = (RadioButton) rg_que3.findViewById(rg_que3.getCheckedRadioButtonId());
answer3 =radioButton3.getText().toString();
RadioButton radioButton4 = (RadioButton) rg_que4.findViewById(rg_que4.getCheckedRadioButtonId());
answer4 =radioButton4.getText().toString();
RadioButton radioButton5 = (RadioButton) rg_que5.findViewById(rg_que5.getCheckedRadioButtonId());
answer5 =radioButton5.getText().toString();
new SendFeedBackDetails().execute();
}
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
public class SendFeedBackDetails extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
try {
loadingView = new Custom_ProgressDialog(FeedbackFormActivity.this, "");
loadingView.setCancelable(false);
loadingView.show();
// loading = new ProgressDialog(FeedbackFormActivity.this);
// loading.setMessage("Please Wait Loading data ....");
// loading.show();
// loading.setCancelable(false);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected String doInBackground(Void... params) {
String userID = PrefUtils.getUser(FeedbackFormActivity.this).getUser().get(0).getUserid();
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("order_id", orderID));
pairs.add(new BasicNameValuePair("feedback1", answer1));
pairs.add(new BasicNameValuePair("feedback2", answer2));
pairs.add(new BasicNameValuePair("feedback3", answer3));
pairs.add(new BasicNameValuePair("feedback4", answer4));
pairs.add(new BasicNameValuePair("feedback5", answer5));
pairs.add(new BasicNameValuePair("userid", userID));
pairs.add(new BasicNameValuePair("key", "go"));
json = new ServiceHandler().makeServiceCall(RetrfitInterface.url + "feedback.php", ServiceHandler.POST, pairs);
Log.e("parameters", "" + pairs);
Log.e("json", json);
return json;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loadingView.dismiss();
try {
JSONObject mainObject = new JSONObject(s);
String status = "", message = "";
status = mainObject.getString("status");
message = mainObject.getString("message");
if (status.equalsIgnoreCase("1")) {
Toast.makeText(FeedbackFormActivity.this, "Thank you for your valuable Feedback !" , Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MenuActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}else {
Toast.makeText(FeedbackFormActivity.this, "" + message, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| true |
7829e7505287d14d45423a425e0ee397838bf1d7
|
Java
|
rmpestano/swagger-addon
|
/src/main/java/org/jboss/swagger/addon/ui/SwaggerGenerateCommand.java
|
UTF-8
| 1,941 | 1.976563 | 2 |
[] |
no_license
|
/**
* Copyright 2014 Red Hat, Inc. and/or its affiliates.
* <p/>
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.swagger.addon.ui;
import javax.inject.Inject;
import org.jboss.forge.addon.facets.constraints.FacetConstraint;
import org.jboss.forge.addon.projects.ProjectFactory;
import org.jboss.forge.addon.projects.ui.AbstractProjectCommand;
import org.jboss.forge.addon.ui.context.UIBuilder;
import org.jboss.forge.addon.ui.context.UIContext;
import org.jboss.forge.addon.ui.context.UIExecutionContext;
import org.jboss.forge.addon.ui.metadata.UICommandMetadata;
import org.jboss.forge.addon.ui.result.Result;
import org.jboss.forge.addon.ui.result.Results;
import org.jboss.forge.addon.ui.util.Categories;
import org.jboss.forge.addon.ui.util.Metadata;
import org.jboss.swagger.addon.facet.SwaggerFacet;
/**
* Swagger: Generate command
*
* @author <a href="[email protected]">Rafael Pestano</a>
*/
@FacetConstraint({ SwaggerFacet.class })
public class SwaggerGenerateCommand extends AbstractProjectCommand {
@Inject
private ProjectFactory projectFactory;
@Override
public UICommandMetadata getMetadata(UIContext context) {
return Metadata.forCommand(SwaggerGenerateCommand.class).name("Swagger: Generate")
.category(Categories.create("Swagger")).description(
"Generate Swagger spec files (in /target/resourcesDir) for JAX-RS endpoints in the current project");
}
@Override
public void initializeUI(UIBuilder uiBuilder) throws Exception {
}
@Override
public Result execute(UIExecutionContext context) {
getSelectedProject(context).getFacet(SwaggerFacet.class).generateSwaggerResources();
return Results.success("Swagger generate command executed successfuly!");
}
@Override
protected ProjectFactory getProjectFactory() {
return projectFactory;
}
@Override
protected boolean isProjectRequired() {
return true;
}
}
| true |
44e4644883a0bc05e5a0a67510b9634558425f16
|
Java
|
MauricioAguilera11/Proyecto-EDDII
|
/src/proyecto/eddii/ProyectoEDDII.java
|
UTF-8
| 895 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
/*
* 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 proyecto.eddii;
import java.util.Scanner;
/**
*
* @author migue
*/
public class ProyectoEDDII {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner leer = new Scanner(System.in);
System.out.println("Calculadora Simple");
System.out.println("Ingrese su primer numero: ");
int x = leer.nextInt();
System.out.println("Ingrese su segundo numero: ");
int p = leer.nextInt();
String j = "";
j += x;
j += p;
System.out.println("La respuesta es " + j);
System.out.println("PROGRAMAR ES MI PASION");
// TODO code application logic here
}
}
| true |
6e316cfa1b7f508132d298ff8ff864d3ec05426f
|
Java
|
vickysongang/Founder
|
/AdminPlatformApplication/ViewController/src/com/zypg/cms/admin/view/bean/UserManageManagedBean.java
|
UTF-8
| 15,687 | 1.648438 | 2 |
[] |
no_license
|
package com.zypg.cms.admin.view.bean;
import com.zypg.cms.admin.view.util.CustomManagedBean;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.event.ActionEvent;
import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.view.rich.component.rich.RichPopup;
import oracle.adf.view.rich.component.rich.data.RichTable;
import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.layout.RichPanelGroupLayout;
import oracle.adf.view.rich.context.AdfFacesContext;
import oracle.adf.view.rich.event.DialogEvent;
import oracle.adf.view.rich.event.PopupCanceledEvent;
import oracle.binding.OperationBinding;
import oracle.jbo.Key;
import oracle.jbo.Row;
import oracle.jbo.RowIterator;
import oracle.jbo.ViewObject;
import oracle.jbo.domain.Number;
import oracle.jbo.uicli.binding.JUCtrlHierBinding;
import oracle.jbo.uicli.binding.JUCtrlHierNodeBinding;
import oracle.jbo.domain.Number;
import org.apache.myfaces.trinidad.event.ReturnEvent;
import org.apache.myfaces.trinidad.event.SelectionEvent;
import org.apache.myfaces.trinidad.model.CollectionModel;
public class UserManageManagedBean extends CustomManagedBean {
private RichPanelGroupLayout userManageBtnPanelGroupLayout;
private RichPopup selectRolePopup;
private RichPopup deleteCompPopup;
private RichPopup deleteUserPopup;
private RichPopup userManagePopup;
private RichInputText userNameInput;
private RichInputText diplayNameInput;
public UserManageManagedBean() {
}
public void compSelectListener(SelectionEvent selectionEvent) {
RichTable rt = (RichTable)selectionEvent.getSource();
CollectionModel cm = (CollectionModel)rt.getValue();
JUCtrlHierBinding tableBinding = (JUCtrlHierBinding)cm.getWrappedData();
DCIteratorBinding iter = tableBinding.getDCIteratorBinding();
JUCtrlHierNodeBinding selectedRowData = (JUCtrlHierNodeBinding)rt.getSelectedRowData();
Key rowKey = selectedRowData.getRowKey();
iter.setCurrentRowWithKey(rowKey.toStringFormat(true));
Row row = selectedRowData.getCurrentRow();
this.setExpressionValue("#{pageFlowScope.compCode}", row.getAttribute("CompCode"));
this.setExpressionValue("#{pageFlowScope.compName}", row.getAttribute("CompName"));
this.findOperation("findUserByComp").execute();
this.getAdminAM().getDBTransaction().rollback();
AdfFacesContext.getCurrentInstance().addPartialTarget(this.getUserManageBtnPanelGroupLayout());
}
public void createUserActionListener(ActionEvent actionEvent) {
this.setExpressionValue("#{pageFlowScope.operType}", "NEW");
this.findOperation("createUser").execute();
this.showPopup(this.getUserManagePopup().getClientId());
}
public void editUserActionListenter(ActionEvent actionEvent) {
this.setExpressionValue("#{pageFlowScope.operType}", "EDIT");
Number userId = (Number)actionEvent.getComponent().getAttributes().get("userId");
this.getAdminAM().editUser(userId);
this.showPopup(this.getUserManagePopup().getClientId());
}
public void deleteUserActionListener(ActionEvent actionEvent) {
this.setExpressionValue("#{pageFlowScope.userId}", actionEvent.getComponent().getAttributes().get("userId"));
this.setExpressionValue("#{pageFlowScope.userName}",
actionEvent.getComponent().getAttributes().get("userName"));
RichPopup.PopupHints hints = new RichPopup.PopupHints();
this.getDeleteUserPopup().show(hints);
}
public void resetPasswordActionListener(ActionEvent actionEvent) {
this.setExpressionValue("#{pageFlowScope.userId}", actionEvent.getComponent().getAttributes().get("userId"));
this.findOperation("resetPassword").execute();
this.getAdminAM().getDBTransaction().commit();
this.getAdminAM().createAdminOperLog("用户:" + actionEvent.getComponent().getAttributes().get("userName") +
" 密码重置成功", (String)this.resolveExpression("#{pageFlowScope.compCode}"));
this.showLongMessage("重置成功!");
}
public boolean isUserManageFlag() {
String compCode = (String)this.resolveExpression("#{pageFlowScope.compCode}");
if (compCode == null) {
DCIteratorBinding dcib = this.findIterator("CmsCompVO4CommonIterator");
Row compCurrRow = dcib.getCurrentRow();
if (compCurrRow != null) {
compCode = (String)compCurrRow.getAttribute("CompCode");
}
}
String compStr = (String)this.resolveExpression("#{pageFlowScope.compStr}");
if ("ALL".equals(compStr)) {
return true;
} else if (compStr != null && !"".equals(compStr)) {
for (String s : compStr.split(",")) {
if (s.equals(compCode)) {
return true;
}
}
} else {
return false;
}
return false;
}
public void showSelectRolePopup(ActionEvent actionEvent) {
Number userId = (Number)actionEvent.getComponent().getAttributes().get("userId");
// 获取当前人
Map<String, Object> map = this.getAdminAM().getCurrentSelectedUserInfo(userId);
if (map != null) {
String userName = (String)map.get("userName");
String displayName = (String)map.get("displayName");
if (userId != null) {
this.setExpressionValue("#{pageFlowScope.userId}", userId);
this.setExpressionValue("#{pageFlowScope.userName}", userName);
this.setExpressionValue("#{pageFlowScope.displayName}", displayName);
this.setExpressionValue("#{pageFlowScope.refreshTime}", new Date().getTime() + "");
this.showPopup(this.getSelectRolePopup().getClientId());
}
AdfFacesContext.getCurrentInstance().addPartialTarget(this.getSelectRolePopup());
}
}
public void setUserRoleDialogListener(DialogEvent dialogEvent) {
if ("OK".equalsIgnoreCase(dialogEvent.getOutcome().toString())) {
Number userId = (Number)this.resolveExpression("#{pageFlowScope.userId}");
if (userId != null) {
OperationBinding ob = this.findOperation("setUserRole");
ob.getParamsMap().put("userId", userId);
ob.execute();
//设置成功 刷新表格
this.findIterator("CmsUserTVOIterator").executeQuery();
this.getAdminAM().createAdminOperLog("角色设置..",
(String)this.resolveExpression("#{pageFlowScope.compCode}"));
this.showMessage("设置成功");
}
}
}
public void switchCompActionListener(ActionEvent actionEvent) {
String compCode = (String)actionEvent.getComponent().getAttributes().get("compCode");
String compName = (String)actionEvent.getComponent().getAttributes().get("compName");
String groupFlag = (String)actionEvent.getComponent().getAttributes().get("groupFlag");
this.setExpressionValue("#{pageFlowScope.compCode}", compCode);
this.setExpressionValue("#{pageFlowScope.compName}", compName);
this.setExpressionValue("#{pageFlowScope.groupFlag}", groupFlag);
this.findOperation("findUserByComp").execute();
this.refreshUIComponent(actionEvent.getComponent().getParent());
this.refreshUIComponent(this.getUserManageBtnPanelGroupLayout());
}
public void deleteCompDialogListener(DialogEvent dialogEvent) {
String compCode = (String)this.resolveExpression("#{pageFlowScope.compCode}");
String compName = (String)this.resolveExpression("#{pageFlowScope.compName}");
String result = this.getAdminAM().deleteComp(compCode);
if ("S".equals(result)) {
this.showMessage("删除成功");
this.findIterator("CmsCompVO4CommonIterator").executeQuery();
this.getAdminAM().createAdminOperLog("出版社:\"" + compName + "\" 删除操作成功", null);
} else {
this.addFormattedMessage(null, result, FacesMessage.SEVERITY_ERROR);
this.getAdminAM().createAdminOperLog("出版社:\"" + compName + "\" 删除操作失败", null);
}
}
public void newOrEditReturnListener(ReturnEvent returnEvent) {
this.findIterator("CmsCompVO4CommonIterator").executeQuery();
}
public void deleteCompActionListener(ActionEvent actionEvent) {
this.showPopup(this.getDeleteCompPopup().getClientId());
}
public void setDeleteCompPopup(RichPopup deleteCompPopup) {
this.deleteCompPopup = deleteCompPopup;
}
public RichPopup getDeleteCompPopup() {
return deleteCompPopup;
}
public void setUserManageBtnPanelGroupLayout(RichPanelGroupLayout userManageBtnPanelGroupLayout) {
this.userManageBtnPanelGroupLayout = userManageBtnPanelGroupLayout;
}
public RichPanelGroupLayout getUserManageBtnPanelGroupLayout() {
return userManageBtnPanelGroupLayout;
}
public void setSelectRolePopup(RichPopup selectRolePopup) {
this.selectRolePopup = selectRolePopup;
}
public RichPopup getSelectRolePopup() {
return selectRolePopup;
}
public void initUserManage() {
this.getAdminAM().findUserByComp(null);
this.getAdminAM().findComp4Common((String)this.resolveExpression("#{pageFlowScope.compStr}"));
if ("SYSADMIN".equalsIgnoreCase(this.getAdminAM().getCustomDBTransaction().getUserName())) {
this.setExpressionValue("#{pageFlowScope.sysadminFlag}", "Y");
} else {
this.setExpressionValue("#{pageFlowScope.sysadminFlag}", "N");
}
AdfFacesContext.getCurrentInstance().getPageFlowScope().put("roleUserID", this.getAdminAM().getUserID());
}
public void deleteUserDialogListener(DialogEvent dialogEvent) {
if (dialogEvent.getOutcome().equals(DialogEvent.Outcome.ok)) {
this.findOperation("deleteUser").execute();
this.getAdminAM().getDBTransaction().commit();
this.findIterator("CmsUserTVO4DisplayIterator").executeQuery();
this.showMessage("删除成功");
this.getAdminAM().createAdminOperLog("用户:" +
AdfFacesContext.getCurrentInstance().getPageFlowScope().get("userName") +
" 删除成功", (String)this.resolveExpression("#{pageFlowScope.compCode}"));
}
}
public void userManagePopupCanceledListener(PopupCanceledEvent popupCanceledEvent) {
this.getAdminAM().getDBTransaction().rollback();
}
public boolean userValidator() {
String userName = (String)this.getUserNameInput().getValue();
byte[] gbkLength = this.getGBKbyte(userName);
byte[] utfLength = this.getUTFbyte(userName);
String type = (String)this.resolveExpression("#{pageFlowScope.operType}");
System.out.println("type:" + type);
System.out.println("userName:" + userName + this.getAdminAM().isUserExist(userName));
if (userName == null || userName.length() == 0) {
this.addFormattedMessage(this.getUserNameInput().getClientId(), "用户名不能为空", FacesMessage.SEVERITY_WARN);
return false;
} else if (gbkLength.length > 40 || utfLength.length > 40) {
this.addFormattedMessage(this.getUserNameInput().getClientId(), "用户名不能超过40个字符",
FacesMessage.SEVERITY_WARN);
return false;
} else if (!userName.matches("^[a-zA-Z]\\w{0,}$")) {
this.addFormattedMessage(this.getUserNameInput().getClientId(), "用户名应以字母开头,只能包括字母数字与下划线",
FacesMessage.SEVERITY_WARN);
return false;
} else if ("NEW".equals(type) && this.getAdminAM().isUserExist(userName)) {
this.addFormattedMessage(this.getUserNameInput().getClientId(), "用户名在该社或其他社中已存在",
FacesMessage.SEVERITY_WARN);
return false;
} else if (this.getDiplayNameInput().getValue() == null || "".equals(this.getDiplayNameInput().getValue())) {
this.addFormattedMessage(this.getDiplayNameInput().getClientId(), "显示名不能为空", FacesMessage.SEVERITY_WARN);
return false;
}
return true;
}
public void comfirmActionListener(ActionEvent actionEvent) {
if (userValidator()) {
this.getAdminAM().getDBTransaction().commit();
this.getUserManagePopup().hide();
this.getUserManagePopup().cancel();
this.findIterator("CmsUserTVO4DisplayIterator").executeQuery();
String type = (String)this.resolveExpression("#{pageFlowScope.operType}");
if (type.equals("NEW")) {
this.getAdminAM().createAdminOperLog("新增用户:\"" +
this.resolveExpression("#{bindings.UserName.inputValue}") +
"\" 成功!",
(String)this.resolveExpression("#{pageFlowScope.compCode}"));
} else if (type.equals("EDIT")) {
this.getAdminAM().createAdminOperLog("修改用户:\"" +
this.resolveExpression("#{bindings.UserName.inputValue}") +
"\" 成功!",
(String)this.resolveExpression("#{pageFlowScope.compCode}"));
}
}
}
public void cancelActionListener(ActionEvent actionEvent) {
this.getAdminAM().getDBTransaction().rollback();
this.getUserManagePopup().hide();
this.getUserManagePopup().cancel();
}
public void setDeleteUserPopup(RichPopup deleteUserPopup) {
this.deleteUserPopup = deleteUserPopup;
}
public RichPopup getDeleteUserPopup() {
return deleteUserPopup;
}
public static byte[] getGBKbyte(String str) {
String CHARACTER_CODE = "GBK";
try {
return str.getBytes(CHARACTER_CODE);
} catch (UnsupportedEncodingException e) {
return str.getBytes();
}
}
public static byte[] getUTFbyte(String str) {
String CHARACTER_CODE = "UTF-8";
try {
return str.getBytes(CHARACTER_CODE);
} catch (UnsupportedEncodingException e) {
return str.getBytes();
}
}
public void setUserManagePopup(RichPopup userManagePopup) {
this.userManagePopup = userManagePopup;
}
public RichPopup getUserManagePopup() {
return userManagePopup;
}
public void setUserNameInput(RichInputText userNameInput) {
this.userNameInput = userNameInput;
}
public RichInputText getUserNameInput() {
return userNameInput;
}
public void setDiplayNameInput(RichInputText diplayNameInput) {
this.diplayNameInput = diplayNameInput;
}
public RichInputText getDiplayNameInput() {
return diplayNameInput;
}
}
| true |
e20c3078f32f165fbe14bd6eea951deee4293512
|
Java
|
giampieer/proyectoventas_jsp
|
/src/java/JPA/Factura.java
|
UTF-8
| 3,984 | 2.21875 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package JPA;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
*
* @author Jhonk
*/
@Entity
@Table(name = "factura", catalog = "compras", schema = "")
@NamedQueries({
@NamedQuery(name = "Factura.findAll", query = "SELECT f FROM Factura f")})
public class Factura implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "numfactura")
private Integer numfactura;
@Basic(optional = false)
@Column(name = "fecha")
private String fecha;
@Basic(optional = false)
@Column(name = "cantidad")
private int cantidad;
@Basic(optional = false)
@Column(name = "precio")
private double precio;
@JoinColumn(name = "Administrador_idAdministrador", referencedColumnName = "idAdministrador")
@ManyToOne(optional = false)
private Administrador administrador;
@JoinColumn(name = "cliente_idcliente", referencedColumnName = "idcliente")
@ManyToOne(optional = false)
private Cliente cliente;
@JoinColumn(name = "producto_idproducto", referencedColumnName = "idproducto")
@ManyToOne(optional = false)
private Producto producto;
public Factura() {
}
public Factura(Integer numfactura) {
this.numfactura = numfactura;
}
public Factura(Integer numfactura, String fecha, int cantidad, double precio) {
this.numfactura = numfactura;
this.fecha = fecha;
this.cantidad = cantidad;
this.precio = precio;
}
public Integer getNumfactura() {
return numfactura;
}
public void setNumfactura(Integer numfactura) {
this.numfactura = numfactura;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
public double getPrecio() {
return precio;
}
public void setPrecio(double precio) {
this.precio = precio;
}
public Administrador getAdministrador() {
return administrador;
}
public void setAdministrador(Administrador administrador) {
this.administrador = administrador;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public Producto getProducto() {
return producto;
}
public void setProducto(Producto producto) {
this.producto = producto;
}
@Override
public int hashCode() {
int hash = 0;
hash += (numfactura != null ? numfactura.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Factura)) {
return false;
}
Factura other = (Factura) object;
if ((this.numfactura == null && other.numfactura != null) || (this.numfactura != null && !this.numfactura.equals(other.numfactura))) {
return false;
}
return true;
}
@Override
public String toString() {
return "JPA.Factura[ numfactura=" + numfactura + " ]";
}
}
| true |
a6e2125e91bf9224a632e3ad2b71ff1ab308d0e7
|
Java
|
itaf790/electronicapp
|
/app/src/main/java/com/app/electronicapp/ImageListAdapter.java
|
UTF-8
| 3,376 | 2.34375 | 2 |
[] |
no_license
|
package com.app.electronicapp;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.RequiresApi;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.Objects;
public class ImageListAdapter extends ArrayAdapter<uploadinfo> {
private static final String TAG = "ImageListAdapter";
private Context mContext;
private int mResource;
public ImageListAdapter(Context context, int resource, ArrayList<uploadinfo> list) {
super(context, resource, list);
mContext = context;
mResource = resource;
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@SuppressLint("ViewHolder")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//get the image information
String TempImagefirstname= Objects.requireNonNull(getItem(position)).getImagefirstname();
String TempImagelastname= Objects.requireNonNull(getItem(position)).getImagelastname();
String TempImagephone = Objects.requireNonNull(getItem(position)).getImagephone();
String TempImageadress = Objects.requireNonNull(getItem(position)).getImageadress();
String TempImagegender = Objects.requireNonNull(getItem(position)).getImageagender();
String TempImagetime = Objects.requireNonNull(getItem(position)).getImagetime();
String TempImagedate = Objects.requireNonNull(getItem(position)).getImagedate();
String TempImageduration = Objects.requireNonNull(getItem(position)).getImageduration();
String imageUrl = Objects.requireNonNull(getItem(position)).getImageURL();
//Create the employee object with the information
uploadinfo ImageInfo = new uploadinfo(TempImagefirstname,TempImagelastname,TempImagephone,TempImageadress,TempImagegender,TempImagetime,TempImagedate,TempImageduration,imageUrl);
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(this.mResource, parent,false);
TextView imgfname = convertView.findViewById(R.id.ffname);
TextView imglast= convertView.findViewById(R.id.lname);
TextView imgphone = convertView.findViewById(R.id.phoneeee);
TextView imgadress = convertView.findViewById(R.id.adress);
TextView imggender= convertView.findViewById(R.id.gender);
TextView imgtime= convertView.findViewById(R.id.TIME);
TextView imgdate= convertView.findViewById(R.id.DATE);
TextView imgduration= convertView.findViewById(R.id.DURRATION);
ImageView imgView= convertView.findViewById(R.id.image_View);
imgfname.setText(TempImagefirstname);
imglast.setText(TempImagelastname);
imgphone.setText(TempImagephone);
imgadress.setText(TempImageadress);
imggender.setText(TempImagegender);
imgtime.setText(TempImagetime);
imgdate.setText(TempImagedate);
imgduration.setText(TempImageduration);
//Loading image from Glide library.
Glide.with(convertView.getContext()).load(imageUrl).dontAnimate().into(imgView);
return convertView;
}
}
| true |
bcd0c315e38abb91c044c8ff4fc7cf7ea2bf3b27
|
Java
|
cha63506/CompSecurity
|
/facebook-messenger/src/com/facebook/common/executors/d.java
|
UTF-8
| 969 | 1.601563 | 2 |
[] |
no_license
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.facebook.common.executors;
import android.app.ProgressDialog;
import android.content.Context;
import com.google.common.d.a.i;
import com.google.common.d.a.u;
import java.util.concurrent.Executor;
// Referenced classes of package com.facebook.common.executors:
// e
public class d
{
private final Context a;
private final u b;
private final Executor c;
public d(Context context, u u1, Executor executor)
{
a = context;
b = u1;
c = executor;
}
public void a(int j, int k, Runnable runnable)
{
a(a.getString(j), a.getString(k), runnable);
}
public void a(String s, String s1, Runnable runnable)
{
s = ProgressDialog.show(a, s, s1, true);
i.a(b.b(runnable), new e(this, s), c);
}
}
| true |
66af30d620d9f5a248258649b374351256fef220
|
Java
|
7373/enterprise-information-exchange-and-sharing-system
|
/src/main/java/com/src/xt/yr/model/Subcapital.java
|
UTF-8
| 7,602 | 2.15625 | 2 |
[] |
no_license
|
/**
* Copyright© 2003-2016 浙江汇信科技有限公司, All Rights Reserved. <br/>
*/
package com.icinfo.cs.yr.model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonFormat;
/**
* 描述: cs_subcapital 对应的实体类.<br>
* WARNING:不是表中字段的属性必须加@Transient注解
* @author framework generator
* @date 2016年09月09日
*/
@Table(name = "cs_subcapital")
public class Subcapital implements Serializable {
/**
* 主键ID
*/
@Id
@Column(name = "id")
private Integer id;
/**
* 股东/发起人名称
*/
@Column(name = "Inv")
private String inv;
/**
* UUID
*/
@Column(name = "InvID")
private String invID;
/**
* 实缴出资日期
*/
@Column(name = "AcConDate")
@JsonFormat(pattern = "yyyy-MM-dd",timezone="GMT+8")
private Date acConDate;
/**
* 时间戳
*/
@Column(name = "CreateTime")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date createTime;
/**
* 认缴出资方式(中文名称)
*/
@Column(name = "ConFormCN")
private String conFormCN;
/**
* 实缴出资方式(中文名称)
*/
@Column(name = "AcConFormCn")
private String acConFormCn;
/**
* 年报ID
*/
@Column(name = "AnCheID")
private String anCheID;
/**
* 累计实缴额
*/
@Column(name = "LIACCONAM")
private BigDecimal liacconam;
/**
* 累计认缴额
*/
@Column(name = "LISUBCONAM")
private BigDecimal lisubconam;
/**
* 统一代码、注册号/身份证件号码
*/
@Column(name = "InvRegNO")
private String invRegNO;
/**
* 实缴出资方式
*/
@Column(name = "AcConForm")
private String acConForm;
/**
* 认缴出资方式
*/
@Column(name = "SubConForm")
private String subConForm;
/**
* 认缴出资日期
*/
@Column(name = "SubConDate")
@JsonFormat(pattern = "yyyy-MM-dd",timezone="GMT+8")
private Date subConDate;
private static final long serialVersionUID = 1L;
/**
* 获取主键ID
*
* @return id - 主键ID
*/
public Integer getId() {
return id;
}
/**
* 设置主键ID
*
* @param id 主键ID
*/
public void setId(Integer id) {
this.id = id;
}
/**
* 获取股东/发起人名称
*
* @return Inv - 股东/发起人名称
*/
public String getInv() {
return inv;
}
/**
* 设置股东/发起人名称
*
* @param inv 股东/发起人名称
*/
public void setInv(String inv) {
this.inv = inv;
}
/**
* 获取UUID
*
* @return InvID - UUID
*/
public String getInvID() {
return invID;
}
/**
* 设置UUID
*
* @param invID UUID
*/
public void setInvID(String invID) {
this.invID = invID;
}
/**
* 获取实缴出资日期
*
* @return AcConDate - 实缴出资日期
*/
public Date getAcConDate() {
return acConDate;
}
/**
* 设置实缴出资日期
*
* @param acConDate 实缴出资日期
*/
public void setAcConDate(Date acConDate) {
this.acConDate = acConDate;
}
/**
* 获取时间戳
*
* @return CreateTime - 时间戳
*/
public Date getCreateTime() {
return createTime;
}
/**
* 设置时间戳
*
* @param createTime 时间戳
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* 获取认缴出资方式(中文名称)
*
* @return ConFormCN - 认缴出资方式(中文名称)
*/
public String getConFormCN() {
return conFormCN;
}
/**
* 设置认缴出资方式(中文名称)
*
* @param conFormCN 认缴出资方式(中文名称)
*/
public void setConFormCN(String conFormCN) {
this.conFormCN = conFormCN;
}
/**
* 获取实缴出资方式(中文名称)
*
* @return AcConFormCn - 实缴出资方式(中文名称)
*/
public String getAcConFormCn() {
return acConFormCn;
}
/**
* 设置实缴出资方式(中文名称)
*
* @param acConFormCn 实缴出资方式(中文名称)
*/
public void setAcConFormCn(String acConFormCn) {
this.acConFormCn = acConFormCn;
}
/**
* 获取年报ID
*
* @return AnCheID - 年报ID
*/
public String getAnCheID() {
return anCheID;
}
/**
* 设置年报ID
*
* @param anCheID 年报ID
*/
public void setAnCheID(String anCheID) {
this.anCheID = anCheID;
}
/**
* 获取累计实缴额
*
* @return liacconam - 累计实缴额
*/
public BigDecimal getLiacconam() {
return liacconam;
}
/**
* 设置累计实缴额
*
* @param liacconam 累计实缴额
*/
public void setLiacconam(BigDecimal liacconam) {
this.liacconam = liacconam;
}
/**
* 获取累计认缴额
*
* @return lisubconam - 累计认缴额
*/
public BigDecimal getLisubconam() {
return lisubconam;
}
/**
* 设置累计认缴额
*
* @param lisubconam 累计认缴额
*/
public void setLisubconam(BigDecimal lisubconam) {
this.lisubconam = lisubconam;
}
/**
* 获取统一代码、注册号/身份证件号码
*
* @return InvRegNO - 统一代码、注册号/身份证件号码
*/
public String getInvRegNO() {
return invRegNO;
}
/**
* 设置统一代码、注册号/身份证件号码
*
* @param invRegNO 统一代码、注册号/身份证件号码
*/
public void setInvRegNO(String invRegNO) {
this.invRegNO = invRegNO;
}
/**
* 获取实缴出资方式
*
* @return AcConForm - 实缴出资方式
*/
public String getAcConForm() {
return acConForm;
}
/**
* 设置实缴出资方式
*
* @param acConForm 实缴出资方式
*/
public void setAcConForm(String acConForm) {
this.acConForm = acConForm;
}
/**
* 获取认缴出资方式
*
* @return SubConForm - 认缴出资方式
*/
public String getSubConForm() {
return subConForm;
}
/**
* 设置认缴出资方式
*
* @param subConForm 认缴出资方式
*/
public void setSubConForm(String subConForm) {
this.subConForm = subConForm;
}
/**
* 获取认缴出资日期
*
* @return SubConDate - 认缴出资日期
*/
public Date getSubConDate() {
return subConDate;
}
/**
* 设置认缴出资日期
*
* @param subConDate 认缴出资日期
*/
public void setSubConDate(Date subConDate) {
this.subConDate = subConDate;
}
/**
* 描述: 公示敏感词校验字符串
* @auther ZhouYan
* @date 2016年9月14日
* @return
*/
public String getPubForbidInfo() {
return "投资人及出资信息 [股东(发起人)姓名或名称=" + inv + ",注册号或者身份证=" + invID + "]";
}
}
| true |
103992b5191425bce04bdd9d97fbce8d9941017d
|
Java
|
alexdinisor98/VCS
|
/vcs/Vcs.java
|
UTF-8
| 2,793 | 2.46875 | 2 |
[] |
no_license
|
package vcs;
import filesystem.FileSystemOperation;
import filesystem.FileSystemSnapshot;
import utils.OutputWriter;
import utils.Visitor;
import java.util.LinkedList;
public final class Vcs implements Visitor {
private final OutputWriter outputWriter;
public OutputWriter getOutputWriter() {
return outputWriter;
}
public void setActiveSnapshot(FileSystemSnapshot activeSnapshot) {
this.activeSnapshot = activeSnapshot;
}
private FileSystemSnapshot activeSnapshot;
public FileSystemSnapshot getActiveSnapshot() {
return activeSnapshot;
}
public LinkedList<String> getStagedChanges() {
return stagedChanges;
}
private LinkedList<String> stagedChanges;
public LinkedList<Branch> getBranches() {
return branches;
}
private LinkedList<Branch> branches;
public Staging getStaging() {
return staging;
}
private Staging staging;
public LinkedList<Branch> getCheckoutBranches() {
return checkoutBranches;
}
private LinkedList<Branch> checkoutBranches;
private String invalidBranchName = "";
public void setInvalidBranchName(String invalidBranchName) {
this.invalidBranchName = invalidBranchName;
}
/**
* Vcs constructor.
*
* @param outputWriter the output writer
*/
public Vcs(OutputWriter outputWriter) {
this.outputWriter = outputWriter;
}
/**
* Does initialisations.
*/
public void init() {
this.activeSnapshot = new FileSystemSnapshot(outputWriter);
this.stagedChanges = new LinkedList<String>();
this.branches = new LinkedList<Branch>();
this.checkoutBranches = new LinkedList<>();
Branch branchMaster = new Branch();
branchMaster.setName("master");
Commit firstCommit = new Commit();
firstCommit.setSnapshot(this.getActiveSnapshot().cloneFileSystem());
branchMaster.getCommits().add(firstCommit);
// adding branch 'master' to branch list
this.branches.add(branchMaster);
// add branch 'master' to branch list for checkout
this.checkoutBranches.add(branchMaster);
this.staging = new Staging();
}
/**
* Visits a file system operation.
*
* @param fileSystemOperation the file system operation
* @return the return code
*/
public int visit(FileSystemOperation fileSystemOperation) {
return fileSystemOperation.execute(this.activeSnapshot);
}
/**
* Visits a vcs operation.
*
* @param vcsOperation the vcs operation
* @return return code
*/
@Override
public int visit(VcsOperation vcsOperation) {
//TODO
return vcsOperation.execute(this);
}
}
| true |
a4bd691daf0935e48c182d567893bfb53882c659
|
Java
|
sidhd8203/TRUTS2_Web_Project
|
/PetProduct/src/controller/Pet_PdDAO.java
|
UTF-8
| 3,894 | 2.453125 | 2 |
[] |
no_license
|
package controller;
import static controller.JdbcUtils.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import dto.Pet_PdDTO;
public class Pet_PdDAO {
public int insertPet_Pd(Pet_PdDTO dto) {
String sql = "insert into pet_Pd values(p_num.nextval,?,?,?,?,?,0,?)";
int res = 0;
PreparedStatement pstmt = null;
Connection conn = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, dto.getP_price());
pstmt.setString(2, dto.getP_name());
pstmt.setString(3, dto.getP_img());
pstmt.setString(4, dto.getP_address());
pstmt.setString(5, dto.getP_content());
pstmt.setString(6, dto.getM_id());
res = pstmt.executeUpdate();
}catch(SQLException e) {
e.printStackTrace();
}finally {
close(conn,pstmt,null);
}
return res;
}
public ArrayList<Pet_PdDTO> selectPet() {
String sql = "select * from pet_pd";
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList<Pet_PdDTO> pet_PdList = null;
Connection conn = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
if(rs.next()) {
pet_PdList = new ArrayList<Pet_PdDTO>();
do {
pet_PdList.add(new Pet_PdDTO(rs.getInt("p_num"),
rs.getInt("p_price"),
rs.getString("p_name"),
rs.getString("p_img"),
rs.getString("p_address"),
rs.getString("p_content"),
rs.getString("m_id")));
}while(rs.next());
}
}catch(SQLException e) {
e.printStackTrace();
}finally {
close(conn, pstmt, rs);
}
return pet_PdList;
}
public Pet_PdDTO selectPet_Pd(int p_num) {
String sql = "select * from pet_pd where p_num=?";
PreparedStatement pstmt = null;
ResultSet rs = null;
Pet_PdDTO pet = null;
Connection conn = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, p_num);
rs = pstmt.executeQuery();
if(rs.next()) {
pet = new Pet_PdDTO(rs.getInt("p_num"),
rs.getInt("p_price"),
rs.getString("p_name"),
rs.getString("p_img"),
rs.getString("p_address"),
rs.getString("p_content"),
rs.getString("m_id"));
}
}catch(SQLException e) {
e.printStackTrace();
}finally {
close(conn,pstmt,rs);
}
return pet;
}
public int deletePet_pd(int p_num) {
String sql = "delete from pet_pd where p_num = ?";
PreparedStatement pstmt = null;
Pet_PdDTO pet = null;
Connection conn = null;
int num = 0;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, p_num);
num = pstmt.executeUpdate();
}catch (Exception e) {
e.printStackTrace();
}finally {
close(conn,pstmt,null);
}
return num;
}
public int updatePet(Pet_PdDTO dto) {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "update pet_pd set p_price=?, p_name=?, p_img=?, p_address=?, p_content=?, m_id=? where p_num=?";
int num = 0;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, dto.getP_price());
pstmt.setString(2, dto.getP_name());
pstmt.setString(3, dto.getP_img());
pstmt.setString(4, dto.getP_address());
pstmt.setString(5, dto.getP_content());
pstmt.setString(6, dto.getM_id());
pstmt.setInt(7, dto.getP_num());
num = pstmt.executeUpdate();
if(num>0) {
commit(conn);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(conn, pstmt, null);
}
return num;
}
}
| true |
cef19e3e5ceef380cd88c6c61ab484f15f84d5b4
|
Java
|
GabrielDiasgd/Store
|
/src/main/java/com/store/cashier/controller/CashierController.java
|
UTF-8
| 924 | 1.960938 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.store.cashier.controller;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.store.cashier.model.Cashier;
import com.store.cashier.repository.CashierRepository;
import com.store.cashier.service.CashierService;
@RestController
@RequestMapping("/cashiers")
public class CashierController {
@Autowired
private CashierService cashierService;
@Autowired
private CashierRepository cashierRepository;
@GetMapping
public Optional<Cashier> listCashiers () {
return cashierRepository.findByStatusOpen();
}
@PostMapping
public Cashier openingCashier () {
return cashierService.openCashier();
}
}
| true |
156aba4092836e1b63e328ec5c892a3732fa5cb6
|
Java
|
kalnee/trivor
|
/gateway/src/main/java/org/kalnee/trivor/gateway/repository/TranscriptRepository.java
|
UTF-8
| 437 | 1.992188 | 2 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package org.kalnee.trivor.gateway.repository;
import org.kalnee.trivor.gateway.domain.Transcript;
import org.springframework.stereotype.Repository;
import org.springframework.data.jpa.repository.*;
/**
* Spring Data JPA repository for the Transcript entity.
*/
@SuppressWarnings("unused")
@Repository
public interface TranscriptRepository extends JpaRepository<Transcript, Long> {
Transcript findOneByImdbId(String imdbId);
}
| true |
26784d8df2f94637b981f03e32f17f2d739ac172
|
Java
|
acabaud1/MyConfinementApp
|
/app/src/main/java/com/ynov/myconfinement/ui/agenda/AgendaFragment.java
|
UTF-8
| 3,700 | 2.078125 | 2 |
[] |
no_license
|
package com.ynov.myconfinement.ui.agenda;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.ynov.myconfinement.R;
import com.ynov.myconfinement.ui.DatabaseManager;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
public class AgendaFragment extends Fragment {
private DatabaseManager databaseManager;
private ArrayList<Picture> pictures;
private PictureAdapter adapter;
String currentPhotoPath;
static final int REQUEST_TAKE_PHOTO = 1;
private void updateList() {
adapter.updatePicturesList((ArrayList<Picture>) databaseManager.getPictures());
}
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View root = inflater.inflate(R.layout.fragment_agenda, container, false);
databaseManager = new DatabaseManager(getContext());
FloatingActionButton fabAgenda = root.findViewById(R.id.fabAgenda);
ListView listViewAgenda = root.findViewById(R.id.listViewAgenda);
pictures = (ArrayList<Picture>) databaseManager.getPictures();
adapter = new PictureAdapter(getActivity().getApplicationContext(), R.layout.fragment_picture_item, pictures);
listViewAgenda.setAdapter(adapter);
fabAgenda.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});
return root;
}
private File createImageFile() throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
currentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent()
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.e("TAKE_PICTURE", "Error while taking picture");
}
if (photoFile != null)
{
String currentDate = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault()).format(new Date());
Uri photoURI = FileProvider.getUriForFile(getContext(), "com.ynov.myconfinement.fileprovider", photoFile);
databaseManager.insertPicture(new Picture(photoURI, currentDate, "Lyon"));
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
Toast.makeText(getContext(), "Agenda : image ajoutée.", Toast.LENGTH_SHORT).show();
updateList();
}
}
}
}
| true |
f2daa51550badd1c9eaad40de5f8e9191a7eae45
|
Java
|
wumaoland/ms
|
/src/main/java/mybatis/entity/SysUser.java
|
UTF-8
| 2,978 | 2.390625 | 2 |
[] |
no_license
|
package mybatis.entity;
import java.util.Date;
import javax.persistence.*;
@Table(name = "sys_user")
public class SysUser {
/**
* 用户id
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* 用户名
*/
@Column(name = "user_name")
private String userName;
/**
* 密码
*/
@Column(name = "user_password")
private String userPassword;
/**
* 邮箱
*/
@Column(name = "user_email")
private String userEmail;
/**
* 创建时间
*/
@Column(name = "create_time")
private Date createTime;
/**
* 简介
*/
@Column(name = "user_info")
private String userInfo;
/**
* 头像
*/
@Column(name = "head_img")
private byte[] headImg;
/**
* 获取用户id
*
* @return id - 用户id
*/
public Long getId() {
return id;
}
/**
* 设置用户id
*
* @param id 用户id
*/
public void setId(Long id) {
this.id = id;
}
/**
* 获取用户名
*
* @return user_name - 用户名
*/
public String getUserName() {
return userName;
}
/**
* 设置用户名
*
* @param userName 用户名
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* 获取密码
*
* @return user_password - 密码
*/
public String getUserPassword() {
return userPassword;
}
/**
* 设置密码
*
* @param userPassword 密码
*/
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
/**
* 获取邮箱
*
* @return user_email - 邮箱
*/
public String getUserEmail() {
return userEmail;
}
/**
* 设置邮箱
*
* @param userEmail 邮箱
*/
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
/**
* 获取创建时间
*
* @return create_time - 创建时间
*/
public Date getCreateTime() {
return createTime;
}
/**
* 设置创建时间
*
* @param createTime 创建时间
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* 获取简介
*
* @return user_info - 简介
*/
public String getUserInfo() {
return userInfo;
}
/**
* 设置简介
*
* @param userInfo 简介
*/
public void setUserInfo(String userInfo) {
this.userInfo = userInfo;
}
/**
* 获取头像
*
* @return head_img - 头像
*/
public byte[] getHeadImg() {
return headImg;
}
/**
* 设置头像
*
* @param headImg 头像
*/
public void setHeadImg(byte[] headImg) {
this.headImg = headImg;
}
}
| true |
965b912784a952b16c775e71091b288738ac11c5
|
Java
|
ZHENGJerry/tyhdistributor
|
/src/main/java/cn/tongyouhui/control/dao/RegisterMapper.java
|
UTF-8
| 1,010 | 2.0625 | 2 |
[] |
no_license
|
package cn.tongyouhui.control.dao;
import cn.tongyouhui.control.vo.ControlRegister;
import cn.tongyouhui.control.vo.LoginVo;
public interface RegisterMapper {
//向登陆表中插入信息
public void register_base_info(ControlRegister controlRegister);
//向企业表中插入数据
public void register_company_info(ControlRegister controlRegister);
//向个人表中插入数据
public void register_person_info(ControlRegister controlRegister);
//根据用户名和密码判断用户是否存在
public LoginVo login(LoginVo loginVo);
//通过id查询信息_企业表
public ControlRegister selectInfoByCompany(String log_username);
//通过id查询信息_个人表
public ControlRegister selectInfoByPerson(String log_username);
//通过id查询login表
public LoginVo getUserByUsername(String reg_username);
//查询所有供应商的个数,公司和企业
public Integer getNumByType();
//查询所有供应商的个数,个人的供销商
public Integer getNumByTypePerson();
}
| true |
05c2bf4e37c3832925ce7a6dc61b3a08f6b09ffe
|
Java
|
actor168/DesignPattern
|
/com/github/actor168/designpattern/structure/interceptor/TargetInvocation.java
|
UTF-8
| 840 | 2.828125 | 3 |
[] |
no_license
|
package com.github.actor168.designpattern.structure.interceptor;
import java.util.ArrayList;
import java.util.Iterator;
public class TargetInvocation {
private ArrayList<Interceptor> interceptorList = new ArrayList<>();
private Target target;
private Iterator<Interceptor> iterator = interceptorList.iterator();
public void invoke() {
// invoke by order
if (iterator.hasNext()) {
Interceptor i = iterator.next();
i.before(this);
i.intercept(this);
i.after(this);
} else {
target.execute("request");
}
}
public void setTarget(Target t) {
target = t;
}
public void addInterceptor(Interceptor interceptor) {
interceptorList.add(interceptor);
iterator = interceptorList.iterator();
}
}
| true |
3decb1532d481821d57eb469a5df16537bdf8f02
|
Java
|
akhtyamovpavel/PatternsCollection
|
/JavaSource/src/main/java/ru/akhcheck/patterns/bridge/MainBridge.java
|
UTF-8
| 1,205 | 3.03125 | 3 |
[] |
no_license
|
package ru.akhcheck.patterns.bridge;
import ru.akhcheck.patterns.bridge.chassis.CarChassis;
import ru.akhcheck.patterns.bridge.chassis.PlaneChassis;
import ru.akhcheck.patterns.bridge.wheels.Gamepad;
import ru.akhcheck.patterns.bridge.wheels.PlaneWheel;
public class MainBridge {
public static void main(String[] args) {
CarChassis carChassis = new CarChassis();
Gamepad gamepad = new Gamepad(carChassis);
gamepad.pressUpButton();
for (int i = 0; i < 10; ++i) {
gamepad.pressGasPedal();
gamepad.pressDownButton();
gamepad.pressGasPedal();
}
gamepad.pushWheel();
gamepad.printInfo();
CarChassis planeCarChassis = new CarChassis();
PlaneWheel planeWheel = new PlaneWheel(planeCarChassis);
for (int index = 0; index < 10; ++index) {
planeWheel.pullWheel();
}
planeWheel.printInfo();
PlaneChassis planeChassis = new PlaneChassis();
PlaneWheel realPlaneWheel = new PlaneWheel(planeChassis);
for (int index = 0; index < 10; ++index) {
realPlaneWheel.pullWheel();
}
realPlaneWheel.printInfo();
}
}
| true |
db340f5c9a5f1cfe62531147cd8999db2d5d9cd4
|
Java
|
Lianite/wurm-server-reference
|
/org/kohsuke/rngom/digested/DOMPrinter.java
|
UTF-8
| 4,510 | 2.28125 | 2 |
[] |
no_license
|
//
// Decompiled by Procyon v0.5.30
//
package org.kohsuke.rngom.digested;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Attr;
import org.w3c.dom.NodeList;
import javax.xml.stream.XMLStreamException;
import org.w3c.dom.Comment;
import org.w3c.dom.EntityReference;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Text;
import org.w3c.dom.Element;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import javax.xml.stream.XMLStreamWriter;
class DOMPrinter
{
protected XMLStreamWriter out;
public DOMPrinter(final XMLStreamWriter out) {
this.out = out;
}
public void print(final Node node) throws XMLStreamException {
switch (node.getNodeType()) {
case 9: {
this.visitDocument((Document)node);
break;
}
case 11: {
this.visitDocumentFragment((DocumentFragment)node);
break;
}
case 1: {
this.visitElement((Element)node);
break;
}
case 3: {
this.visitText((Text)node);
break;
}
case 4: {
this.visitCDATASection((CDATASection)node);
break;
}
case 7: {
this.visitProcessingInstruction((ProcessingInstruction)node);
break;
}
case 5: {
this.visitReference((EntityReference)node);
break;
}
case 8: {
this.visitComment((Comment)node);
break;
}
case 10: {
break;
}
default: {
throw new XMLStreamException("Unexpected DOM Node Type " + node.getNodeType());
}
}
}
protected void visitChildren(final Node node) throws XMLStreamException {
final NodeList nodeList = node.getChildNodes();
if (nodeList != null) {
for (int i = 0; i < nodeList.getLength(); ++i) {
this.print(nodeList.item(i));
}
}
}
protected void visitDocument(final Document document) throws XMLStreamException {
this.out.writeStartDocument();
this.print(document.getDocumentElement());
this.out.writeEndDocument();
}
protected void visitDocumentFragment(final DocumentFragment documentFragment) throws XMLStreamException {
this.visitChildren(documentFragment);
}
protected void visitElement(final Element node) throws XMLStreamException {
this.out.writeStartElement(node.getPrefix(), node.getLocalName(), node.getNamespaceURI());
final NamedNodeMap attrs = node.getAttributes();
for (int i = 0; i < attrs.getLength(); ++i) {
this.visitAttr((Attr)attrs.item(i));
}
this.visitChildren(node);
this.out.writeEndElement();
}
protected void visitAttr(final Attr node) throws XMLStreamException {
final String name = node.getLocalName();
if (name.equals("xmlns")) {
this.out.writeDefaultNamespace(node.getNamespaceURI());
}
else {
final String prefix = node.getPrefix();
if (prefix != null && prefix.equals("xmlns")) {
this.out.writeNamespace(prefix, node.getNamespaceURI());
}
else {
this.out.writeAttribute(prefix, node.getNamespaceURI(), name, node.getNodeValue());
}
}
}
protected void visitComment(final Comment comment) throws XMLStreamException {
this.out.writeComment(comment.getData());
}
protected void visitText(final Text node) throws XMLStreamException {
this.out.writeCharacters(node.getNodeValue());
}
protected void visitCDATASection(final CDATASection cdata) throws XMLStreamException {
this.out.writeCData(cdata.getNodeValue());
}
protected void visitProcessingInstruction(final ProcessingInstruction processingInstruction) throws XMLStreamException {
this.out.writeProcessingInstruction(processingInstruction.getNodeName(), processingInstruction.getData());
}
protected void visitReference(final EntityReference entityReference) throws XMLStreamException {
this.visitChildren(entityReference);
}
}
| true |
386492256e70b8d65e5ea4d7819a4822657aa8ef
|
Java
|
avasaris/JavaMarathon2020
|
/src/day16/Task1.java
|
UTF-8
| 1,549 | 3.75 | 4 |
[] |
no_license
|
package day16;
/*
* Реализовать программу, которая на вход принимает txt файл с целыми числами (можно использовать
* файл из задания 1 дня 14) и в качестве ответа выводит в консоль среднее арифметическое этих чисел.
* Ответ будет являться вещественным числом. В консоль необходимо вывести полную запись вещественного
* числа (со всеми знаками после запятой) и сокращенную запись (с 3 знаками после запятой).
* Пример:
* Числа в txt файле: 5 2 8 34 1 36 77
* Ответ: 23.285714285714285 --> 23,286
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import static java.lang.Math.round;
public class Task1 {
public static final String FILE = "./src/day16/digits.txt";
public static void main(String[] args) throws FileNotFoundException {
File file = new File(FILE);
Scanner scanner = new Scanner(file);
String[] strDigits = scanner.nextLine().split(" ");
scanner.close();
double sum = 0;
for (String strDigit : strDigits) {
sum += Integer.parseInt(strDigit);
}
sum /= strDigits.length;
System.out.println(sum);
System.out.println(round(sum * 1000) / 1000.0);
}
}
| true |
7c82b1a149aeacb78a5df85bda5c238bc60fd4db
|
Java
|
OAndriiovych/Blog-Servlet-API-Java
|
/src/main/java/db/DAO/UserDAO.java
|
UTF-8
| 374 | 2.34375 | 2 |
[] |
no_license
|
package db.DAO;
import db.database.User;
import java.sql.SQLException;
import java.util.List;
public interface UserDAO {
void add(User users) throws SQLException;
List<User> getAll() throws SQLException;
User getByID(int id) throws SQLException;
void update(int id, User users) throws SQLException;
void delete(User users) throws SQLException;
}
| true |
4225c46be0156b4c712dafdf53850ed204c8a0bf
|
Java
|
theBaldSoprano/practice2016
|
/steps-module/src/main/java/ru/qatools/school/steps/websteps/DefaultSteps.java
|
UTF-8
| 3,322 | 2.453125 | 2 |
[] |
no_license
|
package ru.qatools.school.steps.websteps;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import ru.qatools.school.pages.MainPage;
import ru.qatools.school.pages.blocks.NewWeatherWidgetCard;
import ru.qatools.school.pages.blocks.WeatherWidget;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.htmlelements.element.Button;
import java.util.ArrayList;
import java.util.List;
import static java.lang.String.format;
import static org.hamcrest.core.Every.everyItem;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static ru.yandex.qatools.htmlelements.matchers.WebElementMatchers.isDisplayed;
/**
* Created by kurau.
*/
public class DefaultSteps {
public static final String MAIN_PAGE = "http://weather.lanwen.ru/#?cities=%s";
private WebDriver driver;
public DefaultSteps(WebDriver driver) {
this.driver = driver;
}
@Step("Open main page with weather of {0}")
public void openMainPageWithCity(String city) {
driver.get(format(MAIN_PAGE, city));
}
@Step("Should see weather widget")
public void shouldSeeWidget(WeatherWidget element) {
assertThat("Should see element", element, isDisplayed());
}
@Step("Should see \"add new widget\" button")
public void shouldSeeAddWidgetButton(NewWeatherWidgetCard element) {
assertThat("Should see button", element, isDisplayed());
}
@Step("Should see \"remove widget\" button")
public void shouldSeeRemoveWidgetButton(WebElement button) {
assertThat("Should see button", button, isDisplayed());
}
@Step("Should see all widgets")
public void shouldSeeWidget(List<WeatherWidget> elements) {
assertThat("Should see elements", new ArrayList<>(elements), everyItem(isDisplayed()));
}
@Step("Should see {0} widgets")
public void shouldSeeNumWidgets(int num, List<WeatherWidget> elements) {
assertThat("Must be " + num + " elements", elements.size(), is(num));
shouldSeeWidget(elements);
}
@Step("Widget city should be {0}")
public void shouldBeWeatherOfLinkCity(String linkCity, WebElement widgetCity) {
assertThat("Should be same city, that was in URL", linkCity, is(widgetCity.getText()));
}
@Step("Push \"add new weather widget\" button")
public void pushAddWidgetButton() {
onMainPage().getNewWeatherWidgetCard().get(0).getAddWidgetButton().click();
}
@Step("Push \"remove widget\" button")
public void pushRemoveWidgetButton() {
onMainPage().getWeatherWidgetList().get(0).getWidgetActions().getRemoveWidgetButton().click();
}
@Step("Remove {0} first widgets")
public void removeNWidgets(int n){
for(int i=0;i<n;i++){
pushRemoveWidgetButton();
}
}
@Step("Push \"add new weather widget\" button {0} times")
public void pushNewWeatherButtonNTimes(int n) {
for (int i = 0; i < n; i++) {
pushAddWidgetButton();
}
}
@Step("Should be no widgets")
public void shouldBeNoWidgets(List<WeatherWidget> widgets){
assertEquals(0,widgets.size());
}
private MainPage onMainPage() {
return new MainPage(driver);
}
}
| true |
bc337aaa00c5f8a3bf91e5b0989a7eb9c7907020
|
Java
|
mmwebaze/openFarm
|
/src/main/java/org/bashemera/openfarm/service/ConfigManager.java
|
UTF-8
| 689 | 2.203125 | 2 |
[] |
no_license
|
package org.bashemera.openfarm.service;
import java.util.List;
import org.bashemera.openfarm.model.Config;
import org.bashemera.openfarm.repository.ConfigRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ConfigManager implements ConfigService {
@Autowired
ConfigRepository configRepository;
@Override
public Config getConfig() {
List<Config> configs = configRepository.findAll();
if (configs.size() == 0)
return null;
else
return configRepository.findAll().get(0);
}
@Override
public Config save(Config config) {
return configRepository.save(config);
}
}
| true |
3554dbb8773f368e31bcecb7dec9be582e224043
|
Java
|
forcedotcom/phoenix
|
/phoenix-core/src/main/java/com/salesforce/phoenix/expression/function/CeilDateExpression.java
|
UTF-8
| 3,501 | 2.078125 | 2 |
[] |
no_license
|
/*******************************************************************************
* Copyright (c) 2013, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of Salesforce.com 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 HOLDER 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 com.salesforce.phoenix.expression.function;
import java.sql.SQLException;
import java.util.List;
import com.google.common.collect.Lists;
import com.salesforce.phoenix.expression.Expression;
/**
*
* Class encapsulating ceil operation on {@link com.salesforce.phoenix.schema.PDataType#DATE}.
*
* @author samarth.jain
* @since 3.0.0
*/
public class CeilDateExpression extends RoundDateExpression {
public CeilDateExpression() {}
/**
* @param timeUnit - unit of time to round up to.
* Creates a {@link CeilDateExpression} with default multiplier of 1.
*/
public static Expression create(Expression expr, TimeUnit timeUnit) throws SQLException {
return create(expr, timeUnit, 1);
}
/**
* @param timeUnit - unit of time to round up to
* @param multiplier - determines the roll up window size.
* Create a {@link CeilDateExpression}.
*/
public static Expression create(Expression expr, TimeUnit timeUnit, int multiplier) throws SQLException {
Expression timeUnitExpr = getTimeUnitExpr(timeUnit);
Expression defaultMultiplierExpr = getMultiplierExpr(multiplier);
List<Expression> expressions = Lists.newArrayList(expr, timeUnitExpr, defaultMultiplierExpr);
return CeilDateExpression.create(expressions);
}
public static Expression create(List<Expression> children) throws SQLException {
return new CeilDateExpression(children);
}
CeilDateExpression(List<Expression> children) {
super(children);
}
@Override
protected long getRoundUpAmount() {
return divBy - 1;
}
@Override
public String getName() {
return CeilFunction.NAME;
}
}
| true |
d51303d9bcd436a76621fd453059f0fd6415346f
|
Java
|
h616016784/similarwx
|
/app/src/main/java/com/android/similarwx/beans/response/RspGroup.java
|
UTF-8
| 441 | 1.59375 | 2 |
[] |
no_license
|
package com.android.similarwx.beans.response;
import com.android.similarwx.beans.GroupMessageBean;
import com.android.similarwx.beans.User;
import java.util.List;
/**
* Created by Administrator on 2018/5/22.
*/
public class RspGroup extends BaseResponse {
GroupMessageBean data;
public GroupMessageBean getData() {
return data;
}
public void setData(GroupMessageBean data) {
this.data = data;
}
}
| true |
583b9703210d08685e57dad9a25ebd533a9da21a
|
Java
|
michaelpoluektov/cw-ai
|
/src/main/java/uk/ac/bris/cs/scotlandyard/ui/ai/MoveDestinationVisitor.java
|
UTF-8
| 368 | 2.359375 | 2 |
[] |
no_license
|
package uk.ac.bris.cs.scotlandyard.ui.ai;
import uk.ac.bris.cs.scotlandyard.model.Move;
public class MoveDestinationVisitor implements Move.Visitor<Integer>{
@Override
public Integer visit(Move.SingleMove move) {
return move.destination;
}
@Override
public Integer visit(Move.DoubleMove move) {
return move.destination2;
}
}
| true |
5d14a0f7e9dc58de5537b18e1f7efcf2e9cc4ab0
|
Java
|
jcsobrino/sharetool
|
/app/src/main/java/jcsobrino/tddm/uoc/sharetool/common/ApiFactory.java
|
UTF-8
| 568 | 2.21875 | 2 |
[] |
no_license
|
package jcsobrino.tddm.uoc.sharetool.common;
import jcsobrino.tddm.uoc.sharetool.service.ApiService;
import jcsobrino.tddm.uoc.sharetool.service.impl.ApiServiceImpl;
/**
* Factoría de creación de servicios que implementan la API con las funciones de gestión de entidades de dominio
* Contiene una única implementación basada en SQLite
* Created by JoséCarlos on 13/11/2015.
*/
public enum ApiFactory {
INSTANCE;
private ApiService[] listServices = {new ApiServiceImpl()};
public ApiService getApi() {
return listServices[0];
}
}
| true |
fea37c82909ae5424859aa7b113d080781ff5d85
|
Java
|
1658544535/java
|
/src/com/tzmb2c/web/service/ProductService.java
|
UTF-8
| 5,281 | 1.75 | 2 |
[] |
no_license
|
package com.tzmb2c.web.service;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import com.tzmb2c.common.Pager;
import com.tzmb2c.web.pojo.ProductExcelPojo;
import com.tzmb2c.web.pojo.ProductPojo;
/**
* @author EricChen
*/
public interface ProductService {
public int getAllCount(ProductPojo productPojo);
public int getCount(ProductPojo product, Pager page);
public List<ProductPojo> getProductAll(ProductPojo product, Pager page) throws SQLException;
public List<ProductPojo> getProductAllSeller(ProductPojo product, Pager page) throws SQLException;
public List<ProductExcelPojo> getProductAll2(ProductExcelPojo product, Pager page)
throws SQLException;
public List<ProductPojo> getAgencyProductAll(ProductPojo product, Pager page) throws SQLException;
public int getProductStock(ProductPojo productPojo) throws SQLException;
public List<ProductPojo> getProductAllIds(ProductPojo product) throws SQLException;
public ProductPojo findProduct(ProductPojo product);
public ProductPojo findProductSeller(ProductPojo product);
public Long addProduct(ProductPojo product);
public Long addProductSeller(ProductPojo product);
void productUpdateIng(ProductPojo product);
public void productUpdate(ProductPojo product);
public void productUpdateSeller(ProductPojo product);
public ProductPojo findProductContent(Long id) throws SQLException;
public int productContentUpdate(ProductPojo productPojo) throws SQLException;
public ProductPojo findProductName(Long id) throws SQLException;
public int productNameUpdate(ProductPojo productPojo) throws SQLException;
public int productStatusUpdate(ProductPojo productPojo) throws SQLException;
public void deleProduct(Long id) throws SQLException;
public void productDeleteId(String[] tids);
public void checkProduct(Long id) throws SQLException;
public void checkProductSeller(Long id) throws SQLException;
List<ProductPojo> productForUserNew(Long id);
List<ProductPojo> productForUserYes(Long id);
List<ProductPojo> productForShopId(Long id);
List<ProductPojo> productForShopId1(Map<String, Object> map);
List<ProductPojo> productForHot(ProductPojo product);
List<ProductPojo> productAll() throws SQLException;
List<ProductPojo> productForHotSupplyWeb(ProductPojo product);
List<ProductPojo> productForType(Long id);
public List<ProductPojo> getProductAllByParameter(ProductPojo product, Pager page)
throws SQLException;
List<ProductPojo> productSellCountSupplyWeb(ProductPojo product);
/**
* 根据限制数获取产品列表(by EricChen)
*/
List<ProductPojo> getProductLimit(ProductPojo productPojo, Integer limit);
List<ProductPojo> productForUser(ProductPojo product, Pager page) throws SQLException;
List<ProductPojo> productForUserYes5(Long id);
void updateHits(Long id);
void uncheckProduct(Long id) throws SQLException;
void uncheckProductSeller(Long id) throws SQLException;
List<ProductPojo> getProductAllByName(ProductPojo product, Pager page) throws SQLException;
public List<ProductPojo> getProductAllStatus(ProductPojo product, Pager page) throws SQLException;
public int getCountStatus(ProductPojo productPojo);
List<ProductPojo> getProductByBrandName(String productBrand, Pager page);
void updateProductStatus(Long id) throws SQLException;
List<ProductPojo> productByUserIdSort(ProductPojo product, Pager page);
void updateProductsellNumber(Map<String, Object> map) throws SQLException;
List<ProductPojo> getProductApi(ProductPojo product, Pager page);
List<ProductPojo> getProductByActivity(ProductPojo product, Pager page);
int getProductByActivityCount(Map<String, Object> map);
List<ProductPojo> indexProductTopFive();
void indexProductTopFiveUpdate(ProductPojo product);
void indexProductTopFiveUpdateNew(ProductPojo product);
List<ProductPojo> indexShowByFloor(String productTypeIds);
void indexProductFloorUpdateNew(ProductPojo product);
int indexProductListsCount(String productTypeIds) throws SQLException;
List<ProductPojo> indexProductLists(String productTypeIds, Pager page);
/**
* 每日10件
*
* @return
* @throws SQLException
*/
List<ProductPojo> tenOfEveryDay() throws SQLException;
List<ProductPojo> productCollectAdd(Map<String, Object> map);
public void updateProductBaseNumber() throws SQLException;
public Integer imagesCount(Long id) throws SQLException;
public Integer focusImageCount(Long id) throws SQLException;
public int getAgencyProductAllCount(ProductPojo product) throws SQLException;
/**
* 查询商品所属专场是否为排期完成
*
* @return
*/
public int findSpecialProductByPid(long productId) throws SQLException;
/**
* 商品库存
*/
public List<ProductPojo> findProductStockList(Long id) throws SQLException;
public int findProductStockCount(Long id) throws SQLException;
public int productStockUpdate(String stock, String stockSkuId) throws SQLException;
public ProductPojo getById(Long id) throws SQLException;
}
| true |
844742bbf2982dc933161f8a5b731d62b38b3a16
|
Java
|
veroborges/distProject3
|
/GeoServer/src/edu/cmu/eventtracker/actionhandler/DisableSlaveFailoverHandler.java
|
UTF-8
| 430 | 2.046875 | 2 |
[] |
no_license
|
package edu.cmu.eventtracker.actionhandler;
import edu.cmu.eventtracker.action.DisableSlaveFailover;
public class DisableSlaveFailoverHandler
implements
ActionHandler<DisableSlaveFailover, Void> {
@Override
public Void performAction(DisableSlaveFailover action, ActionContext context) {
GeoServiceContext geoContext = (GeoServiceContext) context;
geoContext.getService().disableSlaveFailover();
return null;
}
}
| true |
0a81b573ab2bfb8d8d1b8e42747b05b2b339d23e
|
Java
|
sunkaiiii/Concurrency_Programming_in_Java9
|
/src/cp5/find_string/serial/BestMatchingSerialCalculation.java
|
UTF-8
| 936 | 2.765625 | 3 |
[] |
no_license
|
package cp5.find_string.serial;
import cp5.find_string.basic.BestMatchingData;
import cp5.find_string.basic.LevenshteinDistance;
import java.util.ArrayList;
import java.util.List;
public class BestMatchingSerialCalculation {
public static BestMatchingData getBestMatchingWords(String word, List<String>dictionary){
List<String> results=new ArrayList<>();
int minDistance=Integer.MAX_VALUE;
int distance;
//处理字典中的所有单词
for(String str:dictionary){
distance= LevenshteinDistance.calculate(word,str);
if(distance<minDistance){
results.clear();
minDistance=distance;
}else if(distance==minDistance){
results.add(str);
}
}
var result=new BestMatchingData();
result.setWords(results);
result.setDistance(minDistance);
return result;
}
}
| true |
bcc332606fba8b18471511a9f22a4efa2165ea25
|
Java
|
Xannosz/veneos
|
/src/main/java/hu/xannosz/veneos/core/html/media/Param.java
|
UTF-8
| 364 | 2.109375 | 2 |
[] |
no_license
|
package hu.xannosz.veneos.core.html.media;
import hu.xannosz.veneos.core.html.SingleHtmlComponent;
public class Param extends SingleHtmlComponent {
public Param(String name, String value) {
putMeta("name", name);
putMeta("value", value);
}
@Override
protected String getTag() {
return "param";
}
}
| true |
e9871eff1d7792558c2c2b0671a5c76163e070b9
|
Java
|
Thpffcj/DataStructures-and-Algorithms
|
/Java/src/algorithms/leetcodecn/dynamicProgramming/BurstBalloons.java
|
UTF-8
| 2,466 | 3.875 | 4 |
[] |
no_license
|
package algorithms.leetcodecn.dynamicProgramming;
/**
* Created by thpffcj on 2020/2/5.
*
* 有 n 个气球,编号为0 到 n-1,每个气球上都标有一个数字,这些数字存在数组 nums 中。
* 现在要求你戳破所有的气球。每当你戳破一个气球 i 时,你可以获得 nums[left] * nums[i] * nums[right] 个硬币。 这里的 left 和
* right 代表和 i 相邻的两个气球的序号。注意当你戳破了气球 i 后,气球 left 和气球 right 就变成了相邻的气球。
* 求所能获得硬币的最大数量。
*
* 说明:
* 你可以假设 nums[-1] = nums[n] = 1,但注意它们不是真实存在的所以并不能被戳破。
* 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100
*
* 示例:
* 输入: [3,1,5,8]
* 输出: 167
* 解释: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
* coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
*/
public class BurstBalloons {
/**
* dp[i][j]代表扎破i+1号气球~j-1号气球能获得的金币数,i和j是不能被扎破的,因为是两端,并且当前气球k不能被扎破,要分别考
* 虑k的左侧(i~k-1)和右侧(k+1~j),
*
* 状态转移方程为:
* dp[i][j] = max{dp[i][k] + dp[k][j] + a[i] * a[k] * a[j]},k∈(i,j)
* dp[i][k]代表扎破i+1~k-1号气球,dp[k][j]代表扎破k+1~j-1号气球,再加上扎破这个气球获得的金币数
*
* 初始条件:没有气球要扎破就获得0个金币
* dp[0][1] = dp[1][2] = ... = dp[n-2][n-1] = 0
*/
public int maxCoins(int[] nums) {
int n = nums.length;
// 生成新数组
int[] A = new int[n + 2];
A[0] = A[n + 1] = 1;
for (int i = 0; i < n; i++) {
A[i + 1] = nums[i];
}
n += 2;
int[][] dp = new int[n][n];
// 初始化
for (int i = 0; i < n - 1; i++) {
dp[i][i + 1] = 0;
}
// 区间型dp标准格式
for (int len = 3; len <= n; len++) {
for (int i = 0; i <= n - len; i++) {
int j = i + len - 1;
dp[i][j] = Integer.MIN_VALUE;
// 枚举中间的气球
for (int k = i + 1; k <= j - 1; k++) {
dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[k][j] + A[i] * A[k] * A[j]);
}
}
}
return dp[0][n - 1];
}
}
| true |