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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
3477490644f4d06eb211bc8ca50aee593b21a02c | Java | Caaarlowsz/PremiumPvP | /src/net/miraclepvp/kitpvp/commands/subcommands/anvil/AddAnvil.java | UTF-8 | 1,268 | 2.6875 | 3 | [
"Unlicense"
] | permissive | package net.miraclepvp.kitpvp.commands.subcommands.anvil;
import net.miraclepvp.kitpvp.bukkit.FileManager;
import net.miraclepvp.kitpvp.data.Config;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Set;
import static net.miraclepvp.kitpvp.bukkit.Text.color;
public class AddAnvil implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = (Player)sender;
if(!player.getTargetBlock((Set)null, 5).getType().equals(Material.ANVIL)){
player.sendMessage(color("&cYou have to be looking at a anvil to do this."));
return true;
}
if(Config.getAnvils().contains(FileManager.serialize(player.getTargetBlock((Set)null, 5).getLocation()))){
player.sendMessage(color("&cThis anvil is already in the list."));
return true;
}
Config.getAnvils().add(FileManager.serialize(player.getTargetBlock((Set)null, 5).getLocation()));
player.sendMessage(color("&aThe anvil is successfully added in the list."));
return true;
}
}
| true |
81a0a347d3002497abee53b6d13632217e6f42fb | Java | Object173/GeoTwitter-Client | /app/src/main/java/com/object173/geotwitter/gui/messenger/ProfileToolbar.java | UTF-8 | 3,997 | 2.1875 | 2 | [] | no_license | package com.object173.geotwitter.gui.messenger;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.object173.geotwitter.R;
import com.object173.geotwitter.database.entities.Image;
import com.object173.geotwitter.database.entities.Profile;
import com.object173.geotwitter.database.service.ProfileService;
import com.object173.geotwitter.gui.profile.ProfileActivity;
import com.object173.geotwitter.util.resources.ImagesManager;
public final class ProfileToolbar {
private final long profileId;
private Context context;
private Toolbar toolbar;
private String username;
private Image avatar;
private static final String KEY_USERNAME = "username";
private static final String KEY_AVATAR_LOCAL = "avatar_local";
private static final String KEY_AVATAR_ONLINE = "avatar_online";
public ProfileToolbar(final long profileId) {
this.profileId = profileId;
}
public void onCreate(final Context context, final Bundle saveInstanceState, final Toolbar toolbar) {
if(context == null || toolbar == null) {
return;
}
this.context = context;
this.toolbar = toolbar;
if(saveInstanceState != null) {
username = saveInstanceState.getString(KEY_USERNAME);
final String localPath = saveInstanceState.getString(KEY_AVATAR_LOCAL);
final String onlineUrl = saveInstanceState.getString(KEY_AVATAR_ONLINE);
if(localPath != null || onlineUrl != null) {
avatar = new Image(localPath, onlineUrl);
}
}
if(username != null) {
setProfile(username, avatar);
}
else {
final LoadProfileTask task = new LoadProfileTask();
task.execute(profileId);
}
}
private void setProfile(final String username, final Image avatar) {
if(username == null) {
return;
}
this.username = username;
this.avatar = avatar;
if(toolbar != null) {
final TextView usernameField = (TextView) toolbar.findViewById(R.id.toolbar_title);
if(usernameField != null) {
usernameField.setText(this.username);
}
final ImageView avatarView = (ImageView) toolbar.findViewById(R.id.toolbar_icon);
ImagesManager.setImageViewCache(context, avatarView, R.mipmap.avatar, avatar);
final LinearLayout layout = (LinearLayout) toolbar.findViewById(R.id.toolbar_action);
if(layout != null) {
layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ProfileActivity.startActivity(context, profileId);
}
});
}
}
}
public void onSaveInstanceState(final Bundle outState) {
if(outState != null) {
outState.putString(KEY_USERNAME, username);
if(avatar != null) {
outState.putString(KEY_AVATAR_LOCAL, avatar.getLocalPath());
outState.putString(KEY_AVATAR_ONLINE, avatar.getOnlineUrl());
}
}
}
private class LoadProfileTask extends AsyncTask<Long, Void, Profile> {
@Override
protected Profile doInBackground(Long... args) {
if(args != null && args.length > 0) {
return ProfileService.getProfile(context, args[0]);
}
return null;
}
@Override
protected void onPostExecute(Profile profile) {
super.onPostExecute(profile);
if(profile != null) {
setProfile(profile.getUsername(), profile.getAvatarMini());
}
}
}
}
| true |
d6252de753df4ded71276095f1433d1ede46a29c | Java | pmanvi/practice | /src/sorts/Sorts.java | UTF-8 | 2,394 | 3.28125 | 3 | [] | no_license | package sorts;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
/**
* Created with IntelliJ IDEA.
* User: U0117190
* Date: 2/13/13
* Time: 9:32 PM
* To change this template use File | Settings | File Templates.
*/
public class Sorts {
public static void main(String[] args) {
}
public static <T extends Comparable<? super T>> void sort(List<T> list) {
Object[] a = list.toArray();
Arrays.sort(a);
ListIterator<T> i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set((T)a[j]);
}
}
public static void sort(Object[] a) {
Object[] aux = (Object[])a.clone();
mergeSort(aux, a, 0, a.length, 0);
}
private static void swap(Object[] x, int a, int b) {
Object t = x[a];
x[a] = x[b];
x[b] = t;
}
private static void mergeSort(Object[] src,
Object[] dest,
int low,
int high,
int off) {
int length = high - low;
// Insertion sort on smallest arrays
if (length < 7) {
for (int i=low; i<high; i++)
for (int j=i; j>low &&
((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)
swap(dest, j, j-1);
return;
}
// Recursively sort halves of dest into src
int destLow = low;
int destHigh = high;
low += off;
high += off;
int mid = (low + high) >>> 1;
mergeSort(dest, src, low, mid, -off);
mergeSort(dest, src, mid, high, -off);
// If list is already sorted, just copy from src to dest. This is an
// optimization that results in faster sorts for nearly ordered lists.
if (((Comparable)src[mid-1]).compareTo(src[mid]) <= 0) {
System.arraycopy(src, low, dest, destLow, length);
return;
}
// Merge sorted halves (now in src) into dest
for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
if (q >= high || p < mid && ((Comparable)src[p]).compareTo(src[q])<=0)
dest[i] = src[p++];
else
dest[i] = src[q++];
}
}
}
| true |
beb5f23881d19e9893fdda7385484c8bd4534dc9 | Java | 4Kamei/NavierStokes_Naive | /src/main/java/Simulation.java | UTF-8 | 12,154 | 2.703125 | 3 | [] | no_license | import processing.core.PConstants;
/**
* Created by Aleksander on 12:50, 02/07/2018.
*/
public class Simulation {
private float[][][] u, v;
private float[][] p;
private float[][] speeds;
private boolean[][] bounds;
private int arrIndex = 0;
private int numElementsX, numElementsY;
private float deltaX, deltaY, deltaT;
private float deltaX2, deltaY2;
private float rho;
private float nu;
private int frame = 0;
private float maxSpeed, maxP, minP;
private int width, height;
enum DisplayMode {
SPEED,
PRESSURE
}
private DisplayMode displayMode = DisplayMode.SPEED;
public Simulation(float deltaX, float deltaY, float deltaT, final int numElementsX, final int numElementsY) {
frame = 0;
rho = 1;
nu = 8.9e-4f; //Pa * s;
this.deltaX = deltaX;
this.deltaX2 = deltaX * deltaX;
this.deltaY = deltaY;
this.deltaY2 = deltaY * deltaY;
this.deltaT = deltaT;
this.numElementsX = numElementsX;
this.numElementsY = numElementsY;
System.out.println("numElementsX = " + numElementsX);
System.out.println("numElementsY = " + numElementsY);
u = new float[2][numElementsX][numElementsY];
v = new float[2][numElementsX][numElementsY];
p = new float[numElementsX][numElementsY];
speeds = new float[numElementsX][numElementsY];
bounds = new boolean[numElementsX][numElementsY];
for (int i = 0; i < numElementsX; i++) {
for (int j = 0; j < numElementsY; j++) {
bounds[i][j] = false;
}
}
int rad = 2;
for (int i = -rad; i <= rad; i++) {
for (int j = -rad; j <= rad; j++) {
if (Math.hypot(i, j) <= rad + 0.5f)
bounds[i + numElementsX/2][j + numElementsY/2] = false;
}
}
for (int i = 0; i < 3; i++) {
bounds[i + numElementsX/2][numElementsY/2] = false;
}
for (int i = 0; i < numElementsX; i++) {
bounds[i][0] = true;
bounds[i][numElementsY - 1] = true;
}
}
public float getMax() {
switch (displayMode) {
case SPEED:
return maxSpeed;
case PRESSURE:
return maxP;
}
return 0;
}
public float getMin() {
switch (displayMode) {
case PRESSURE:
return minP;
case SPEED:
return 0;
}
return 0;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public float getTime() {
return frame * deltaT;
}
public void render(Main main) {
float scale = Math.min(width / numElementsX, height / numElementsY);
int xOffset = (int) (width - scale * numElementsX);
int yOffset = (int) (height - scale * numElementsY);
main.pushMatrix();
main.translate(0, (yOffset) /2);
main.fill(255);
main.stroke(0, 40);
main.colorMode(PConstants.HSB);
for (int x = 0; x < numElementsX; x++) {
for (int y = 0; y < numElementsY; y++) {
switch (displayMode) {
case SPEED:
main.fill(85 * (speeds[x][numElementsY - y - 1]/maxSpeed) + 170, 150, 250);
break;
case PRESSURE:
main.fill(getPressureColour(x, y), 150, 250);
break;
}
main.rect(scale * x, scale * y, scale, scale);
}
}
main.colorMode(PConstants.RGB);
main.pushMatrix();
main.translate(scale/2, scale/2);
main.fill(0);
main.stroke(0);
for (int x = 0; x < numElementsX; x++) {
for (int y = 0; y < numElementsY; y++) {
float norm = maxSpeed * 2f;
if (norm < Float.MIN_VALUE) {
continue;
}
main.line(scale * x, scale * y, scale * (x + u[arrIndex][x][numElementsY - y - 1] / norm), scale * (y - v[arrIndex][x][numElementsY - y - 1] / norm));
}
}
main.popMatrix();
for (int x = 0; x < numElementsX; x++) {
for (int y = 0; y < numElementsY; y++) {
if (bounds[x][numElementsY - y - 1]) {
main.rect(scale * x, scale * y, scale, scale);
}
}
}
main.noFill();
main.rect(0, 0, numElementsX * scale, numElementsY * scale);
main.popMatrix();
main.rect(0, 0, width, height);
}
private float getPressureColour(int x, int y) {
float val = (p[x][numElementsY - y - 1] - minP) / (maxP - minP);
return 85 * val + 170;
}
public void toggleMode() {
for (int i = 0; i < DisplayMode.values().length; i++) {
if (DisplayMode.values()[i] == displayMode) {
displayMode = DisplayMode.values()[(i + 1) % DisplayMode.values().length];
return;
}
}
}
//All of the CFD code nobody cares about
public void update() {
long startTime = System.currentTimeMillis();
maxP = -Float.MAX_VALUE;
minP = Float.MAX_VALUE;
maxSpeed = 0;
for (int x = 0; x < numElementsX; x++) {
for (int y = 0; y < numElementsY; y++) {
if (bounds[x][y])
continue;
for (int i = 0; i < 10; i++) {
p[x][y] = updateP(x, y);
}
float newU = updateU(x, y);
float newV = updateV(x, y);
u[1 - arrIndex][x][y] = newU;
v[1 - arrIndex][x][y] = newV;
speeds[x][y] = (float) Math.hypot(newU, newV);
if (speeds[x][y] > maxSpeed)
maxSpeed = speeds[x][y];
}
}
for (int x = 0; x < numElementsX; x++) {
for (int y = 0; y < numElementsY; y++) {
if (p[x][y] > maxP)
maxP = p[x][y];
if (p[x][y] < minP)
minP = p[x][y];
if (speeds[x][y] > maxSpeed)
maxSpeed = speeds[x][y];
}
}
frame++;
arrIndex = frame % 2;
System.out.printf("\tTook %d ms to render\n", System.currentTimeMillis() - startTime);
}
private float updateU(int x, int y) {
return getU(x, y) - deltaT * (getU(x,y) * getdUdX(x, y) + getV(x, y) * getdUdY(x, y) + 1/rho * getdPdX(x, y) - nu * getGradU(x, y)) + deltaT * 1f;
}
private float updateV(int x, int y) {
return getV(x, y) - deltaT * (getV(x, y) * getdVdY(x, y) + getU(x, y) * getdVdX(x, y) + 1/rho * getdPdY(x, y) - nu * getGradV(x, y));
}
private float updateP(int x, int y) {
float val = 1 / deltaT;
val *= (getU(x + 1, y) - getU(x - 1, y))/ (2 * deltaX) + (getV(x, y + 1) - getV(x, y - 1))/(2 * deltaY);
float du = getdUdX(x, y);
val += - du * du;
du = getdUdY(x, y) * getdVdX(x, y);
val += -2 * du;
du = getdVdY(x, y);
val += - du * du;
val += (getP(x + 1, y) - getP(x - 1, y)) * deltaY2 + (getP(x, y + 1) - getP(x, y - 1)) * deltaX2;
val *= - (rho * deltaX2 * deltaY2);
return val / (2 * (deltaX2 + deltaY2));
}
private float getdVdX(int x, int y) {
if (getBounds(x + 1, y))
return getV(x, y) - getV(x - 1, y)/deltaX;
if (getBounds(x - 1, y))
return getV(x + 1, y) - getV(x, y)/deltaX;
return (getV(x + 1, y) - getV(x - 1, y)) / (2 * deltaX);
}
private float getdVdY(int x, int y) {
if (getBounds(x, y + 1))
return getV(x, y) - getV(x, y - 1)/deltaY;
if (getBounds(x, y - 1))
return getV(x, y + 1) - getV(x, y) / deltaY;
return (getV(x, y + 1) - getV(x, y - 1)) / (2 * deltaY);
}
private float getdUdX(int x, int y) {
if (getBounds(x + 1, y))
return getU(x, y) - getU(x - 1, y)/deltaX;
if (getBounds(x - 1, y))
return getU(x + 1, y) - getU(x, y)/deltaX;
return (getU(x + 1, y) - getU(x - 1, y)) / (2 * deltaX);
}
private float getdUdY(int x, int y) {
if (getBounds(x, y + 1))
return getU(x, y) - getU(x, y - 1)/deltaY;
if (getBounds(x, y - 1))
return getU(x, y + 1) - getU(x, y) / deltaY;
return (getU(x, y + 1) - getU(x, y - 1)) / (2 * deltaY);
}
private float getGradU(int x, int y) {
return (getU(x + 1, y ) + getU(x - 1, y ) - 2 * getU(x ,y)) / deltaX2
+ (getU(x , y + 1) + getU(x , y - 1) - 2 * getU(x ,y)) / deltaY2;
}
private float getGradV(int x, int y) {
return (getV(x + 1, y ) + getV(x - 1, y ) - 2 * getV(x, y)) / deltaX2
+ (getV(x , y + 1) + getV(x , y - 1) - 2 * getV(x, y)) / deltaY2;
}
private float getdPdX(int x, int y) {
if (getBounds(x + 1, y))
return getP(x, y) - getP(x - 1, y)/deltaX;
if (getBounds(x - 1, y)) {
return getP(x + 1, y) - getP(x, y)/deltaX;
}
return (getP(x + 1, y) - getP(x - 1, y)) / (2 * deltaX);
}
private float getdPdY(int x, int y) {
if (y == 0 || y == numElementsY - 1)
return 0;
if (getBounds(x, y + 1))
return getP(x, y) - getP(x, y - 1)/deltaY;
if (getBounds(x, y - 1))
return getP(x, y + 1) - getP(x, y) / deltaY;
return (getP(x, y + 1) - getP(x, y - 1)) / (2 * deltaY);
}
private float getU(int x, int y) {
x = (x + numElementsX) % numElementsX;
/*
if (y == 0)
return 0;
if (y == numElementsY - 1)
return 0;*/
if (x >= numElementsX)
return 0;
if (x < 0)
return 0;
if (y >= numElementsY)
return 0;
if (y < 0)
return 0;
if (getBounds(x, y)) {
if ((x >= numElementsX || getBounds(x + 1, y)) || (x < 0 || getBounds(x - 1, y)))
return 0;
}
return u[arrIndex][x][y];
}
private float getV(int x, int y) {
if (y == 0 || y == numElementsY - 1)
return 0;
x = (x + numElementsX) % numElementsX;
if (x >= numElementsX)
return 0;
if (x < 0)
return 0;
if (y >= numElementsY)
return 0;
if (y < 0)
return 0;
if (getBounds(x, y)) {
if ((y >= numElementsY || getBounds(x, y + 1)) || (y < 0 || getBounds(x, y - 1)))
return 0;
}
return v[arrIndex][x][y];
}
private float getP(int x, int y) {
if (y == 0 || y == numElementsY - 1)
return 0;
x = (x + numElementsX) % numElementsX;
if (x >= numElementsX)
return 0;
if (x < 0)
return 0;
if (y >= numElementsY)
return 0;
if (y < 0)
return 0;
if (getBounds(x, y)) {
if ((x >= numElementsX || getBounds(x + 1, y)) && (x < 0 || getBounds(x - 1, y)))
return 0;
}
if (getBounds(x, y)) {
if ((y >= numElementsY || getBounds(x, y + 1)) && (y < 0 || getBounds(x, y - 1)))
return 0;
}
return p[x][y];
}
private boolean getBounds(int x, int y) {
if (x >= numElementsX)
return false;
if (x < 0)
return false;
if (y >= numElementsY)
return true;
if (y < 0)
return true;
return bounds[x][y];
}
}
| true |
ea9c940cb8ed1af9896c57f99cfa712868b7807f | Java | kevinSong2017/Spring-project | /src/main/java/com/kevin/controller/UserController.java | UTF-8 | 124 | 1.890625 | 2 | [] | no_license | package com.kevin.controller;
import com.kevin.entity.User;
public interface UserController {
User getUser(int id);
}
| true |
b5627c54966d322282dc1f73100818c1f37477b9 | Java | juanmendez/android_dev | /12.alarms/03.snoozeWithAwakeAlarm/app/src/main/java/info/juanmendez/android/simplealarm/MainActivity.java | UTF-8 | 1,529 | 2.328125 | 2 | [] | no_license | package info.juanmendez.android.simplealarm;
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
/**
* This is a demo created from COMMONSWARE book as Simple alarm.
* There have been additional code to test if an alarm is retained to one instance
* or many upon creating several times.
*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch ( item.getItemId() ){
case R.id.start_alarm:
WakeReceiver.startAlarm( this );
break;
case R.id.cancel_alarm:
WakeReceiver.cancelAlarm(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
| true |
d7e55a254f97d8b74795e50b41d2941b26fe31fe | Java | kgw0t/competitive-programming | /atcoder/1.AtCoder Beginners Selection/5.ABC087B - Coins/Main.java | UTF-8 | 2,678 | 3.25 | 3 | [] | no_license | import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
public class Main {
private static int INPUT_LINE = 4;
public static void main(String[] args) throws Exception {
Input input = InputParser.perse();
int A = input.getInt(1, 1);
int B = input.getInt(2, 1);
int C = input.getInt(3, 1);
int X = input.getInt(4, 1);
int count = 0;
for (int a = 0; a <= A; a++) {
int priceA = a * 500;
if (priceA > X) {
break;
}
if (priceA == X) {
count++;
break;
}
for (int b = 0; b <= B; b++) {
int priceAB = priceA + b * 100;
if (priceAB > X) {
break;
}
if (priceAB == X) {
count++;
break;
}
int need50 = (X - priceAB) / 50;
if (need50 <= C) {
count++;
}
}
}
System.out.println(count);
}
private static class InputParser {
static Input perse() {
Input result = new Input();
Scanner sn = new Scanner(System.in);
while (INPUT_LINE-- > 0) {
String[] args = sn.nextLine().split(" ");
result.addAll(args);
}
sn.close();
return result;
}
}
private static class Input {
private Map<Integer, Map<Integer, String>> inputs;
private int now = 1;
private int innerNext = 1;
Input() {
inputs = new HashMap<>();
inputs.put(now, new HashMap<>());
}
void addAll(String[] args) {
for (String str : args) {
add(str);
}
next();
}
void add(String str) {
inputs.get(now).put(innerNext++, str);
}
void next() {
inputs.put(++now, new HashMap<>());
innerNext = 1;
}
String getString(int i, int j) {
return inputs.get(i).get(j);
}
int getInt(int i, int j) {
return Integer.parseInt(getString(i, j));
}
double getDouble(int i, int j) {
return Double.parseDouble(getString(i, j));
}
List<Integer> getIntLine(int i) {
return inputs.get(i).entrySet().stream().map(e -> Integer.parseInt(e.getValue()))
.collect(Collectors.toList());
}
}
}
| true |
6fc453ac2a92959757271ea1b0eea09d11f76b58 | Java | nateg5/Android | /P90neXt/app/src/main/java/com/p90next/p90next/MainActivity.java | UTF-8 | 3,157 | 2.09375 | 2 | [] | no_license | package com.p90next.p90next;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
final List<String> workoutList = new ArrayList<String>() {{
add(getString(R.string.chest_back));
add(getString(R.string.plyometrics));
add(getString(R.string.shoulders_arms));
add(getString(R.string.yoga_x));
add(getString(R.string.legs_back));
add(getString(R.string.kenpo_x));
}};
final Map<String, String> workoutMap = new HashMap<String, String>() {{
put(workoutList.get(0), "https://photos.app.goo.gl/kYNqYfDxFBIqMpus2");
put(workoutList.get(1), "https://photos.app.goo.gl/ZMLRt7kUHIzXw1di1");
put(workoutList.get(2), "https://photos.app.goo.gl/4Zww388Rh2oEz06i2");
put(workoutList.get(3), "https://photos.app.goo.gl/ZZGfW3z6jyMNd2DX2");
put(workoutList.get(4), "https://photos.app.goo.gl/JdRJdWsBDW9x7ASS8");
put(workoutList.get(5), "https://photos.app.goo.gl/BZH7LumfYrvpTBE58");
}};
final TextView textView = (TextView)findViewById(R.id.textView);
textView.setText(getWorkout());
final Button buttonPlay = (Button)findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(workoutMap.get(getWorkout())));
startActivity(intent);
}
});
final Button buttonFinish = (Button)findViewById(R.id.buttonFinish);
buttonFinish.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int workoutIndex = workoutList.indexOf(getWorkout());
workoutIndex++;
if(workoutIndex > 5) {
workoutIndex = 0;
}
setWorkout(workoutList.get(workoutIndex));
textView.setText(getWorkout());
}
});
editor.apply();
}
private String getWorkout() {
return sharedPreferences.getString("workout", getString(R.string.chest_back));
}
private void setWorkout(String workout) {
editor.putString("workout", workout);
editor.commit();
}
}
| true |
bc56354aa9fd0ff059f5e502017233a59d8c3a8f | Java | qiumg/mall | /mall-manager/mall-manager-dao/src/main/java/com/mall/ICategoryDAO.java | UTF-8 | 524 | 2.125 | 2 | [] | no_license | package com.mall;
import java.util.List;
public interface ICategoryDAO {
//搜索全部商品类别
List<Category> selectAllCategory();
//搜索Category根据id;
Category selectCategoryById(int id);
//在Category插入一条信息
void insertCategory(Category category);
//更新Category中的信息
void updateCategory(Category category);
//通过记id删除一条记录
void deleteCategoryByID(int id);
//根据类别名搜索类别id
int selectIdByName(String name);
}
| true |
a43666418f766dbd1f6dafc015472b7e7bf228da | Java | alexknipfer/CSC490 | /Project8/project8.java | UTF-8 | 39,037 | 2.828125 | 3 | [] | no_license | %{
import java.lang.Math;
import java.io.*;
import java.util.*;
import java.util.StringTokenizer;
%}
/* YACC Declarations */
%token ADDOP
%token AND
%token ASSIGNOP
%token COMMA
%token CURLL
%token CURLR
%token ELSE
%token FUNCTION
%token ID
%token IF
%token MULOP
%token NOT
%token NUMBER
%token OR
%token PARENL
%token PARENR
%token RELOP
%token SEMICOLON
%token STRING
%token VAR
%token WHILE
%left ADDOP
%left MULOP
/* Grammar follows */
%%
start: pgm
{
//System.out.println(globalTable);
//System.out.println("The program is correct, and contains:");
//System.out.printf("%5d statements\n",stmtCount);
//System.out.printf("%5d function definitions\n",funcCount);
}
;
pgm: pgmpart pgm
| pgmpart
;
pgmpart: vardecl
| function {funcCount++;}
;
vardecl: VAR varlist SEMICOLON
;
varlist: ID COMMA varlist
{
//add variable to variable "stack"
varStack.addLast($1.sval);
}
| ID
{
//add variable to variable stack
varStack.addLast($1.sval);
}
;
function: FUNCTION ID PARENL PARENR
{
//add function definition to global table
globalTable.add($2.sval, "function");
//add label for new funtion
ICode stmt = new ICode("NOP");
stmt.addLabel($2.sval);
stmt.emit();
currTable = new SymbolTable($2.sval);
myTables.push(currTable);
}
body
{
//done with function body, "RETURN"
ICode returnOp = new ICode("RET");
returnOp.emit();
//go through variable stack and add to table
for(int x = 0; x < varStack.size(); x++){
currTable.add(varStack.get(x), "int");
}
//clear for next function
varStack.clear();
System.out.println(currTable);
}
| FUNCTION ID PARENL
{
currTable = new SymbolTable($2.sval);
myTables.push(currTable);
}
fplist PARENR
{
//add function definition to global table
globalTable.add($2.sval, "function");
//add label for new function
ICode stmt = new ICode("NOP");
stmt.addLabel($2.sval);
stmt.emit();
ICode paramList = new ICode("PLIST", $5.sval);
paramList.emit();
}
body
{
//done with function body, "RETURN"
ICode returnOp = new ICode("RET");
returnOp.emit();
//go through variable staack and add to table
for(int x = 0; x < varStack.size(); x++){
currTable.add(varStack.get(x), "int");
}
//clear for next function
varStack.clear();
System.out.println(currTable);
}
;
body: CURLL bodylist CURLR
;
fplist: ID COMMA
{
currTable.add($1.sval, "int");
$$.sval = $1.sval;
}
fplist
| ID
{
currTable.add($1.sval, "int");
$$.sval = $1.sval;
}
;
bodylist: vardecl bodylist
| stmt bodylist
| /* epsilon */
;
stmt: assign SEMICOLON {stmtCount++;}
| fcall SEMICOLON {stmtCount++;}
| while {stmtCount++;}
| if {stmtCount++;}
| body
;
assign: ID ASSIGNOP expr
{
//generate intermediate code for assignment operator
//and emit the code
String tempAssignOp = ICode.genTemp();
currTable.add(tempAssignOp, "int");
ICode assignStmt = new ICode("MOV", $3.sval, tempAssignOp);
ICode assignStmt2 = new ICode("MOV", tempAssignOp, $1.sval);
assignStmt.emit();
assignStmt2.emit();
}
;
expr: factor
| expr ADDOP factor
{
//create temp for result
String tempAddOp = ICode.genTemp();
currTable.add(tempAddOp, "int");
//if the ADDOP is a subtraction, emit the code
if($2.sval.equals("-")){
ICode subt = new ICode("SUB", $1.sval, $3.sval, tempAddOp);
subt.emit();
}
//if the ADDOP is an addition, emit the code
else if($2.sval.equals("+")){
ICode add = new ICode("ADD", $1.sval, $3.sval, tempAddOp);
add.emit();
}
//return the result (stored in the temp)
$$.sval = tempAddOp;
}
;
factor: term
| factor MULOP term
{
//generate temp for result of MULOP
String tempMulOp = ICode.genTemp();
currTable.add(tempMulOp, "int");
//check to see if token is multiplication
if($2.sval.equals("*")){
ICode multiply = new ICode("MUL", $1.sval, $3.sval, tempMulOp);
multiply.emit();
}
//check to see if token is division
else if($2.sval.equals("/")){
ICode divide = new ICode("DIV", $1.sval, $3.sval, tempMulOp);
divide.emit();
}
//return the result
$$.sval = tempMulOp;
}
;
term: ID {$$.sval = $1.sval;}
| NUMBER
{
//convert numbers to string
String numberString = String.format("%d", $1.ival);
$$.sval = numberString;
}
| PARENL expr PARENR {$$.sval = $2.sval;}
| ADDOP term
{
//generate temp for negative value
String negTemp = ICode.genTemp();
currTable.add(negTemp, "int");
//convert number to string
//String tempNumber = String.format("%d", $2.ival);
ICode negValue = new ICode("NEG", $2.sval, negTemp);
negValue.emit();
//return the value
$$.sval = negTemp;
}
| fcall
;
bexpr: bfactor
| bexpr OR bfactor
{
//compare the two temps from for the comparison to branch
ICode andCmp = new ICode("CMP", cmpStack.pop(), cmpStack.pop());
andCmp.emit();
String newLabel = ICode.genLabel();
//if false, branch out
ICode branchOnEqual = new ICode("BE", newLabel);
branchOnEqual.emit();
}
;
bfactor: bneg
| bfactor AND bneg
{
//compare the two temps from for the comparison to branch
ICode andCmp = new ICode("CMP", cmpStack.pop(), cmpStack.pop());
andCmp.emit();
//if false, branch out
ICode branchOnEqual = new ICode("BE", genLabelStack.pop());
branchOnEqual.emit();
}
;
bneg: bterm
| NOT bterm
{
//peform a logical NOT
String notTemp = ICode.genTemp();
ICode logicalNot = new ICode("MOV", "NOT", notTemp, notTemp);
logicalNot.emit();
}
;
bterm: expr RELOP expr
{
String temp, temp2;
//generate comparison intermediate code
String newTemp = ICode.genTemp();
cmpStack.push(newTemp);
String newLabel = ICode.genLabel();
genLabelStack.push(newLabel);
//add temp to table
currTable.add(newTemp, "int");
//generate code for less than comparison
if($2.sval.equals("<")){
ICode lessThan = new ICode("LT", $1.sval, $3.sval, newLabel);
lessThan.emit();
}
//generate code for greater than comparison
else if($2.sval.equals(">")){
ICode greaterThan = new ICode("GT", $1.sval, $3.sval, newLabel);
greaterThan.emit();
}
//generate code for less than equal comparison
else if($2.sval.equals("<=")){
ICode lessThanEqual = new ICode("LE", $1.sval, $3.sval, newLabel);
lessThanEqual.emit();
}
//generate code for greater than equal
else if($2.sval.equals(">=")){
ICode greaterThanEqual = new ICode("GE", $1.sval, $3.sval, newLabel);
greaterThanEqual.emit();
}
//generate code for equal to
else if($2.sval.equals("==")){
ICode equalTo = new ICode("EQ", $1.sval, $3.sval, newLabel);
equalTo.emit();
}
//generate code for NOT equal
else if($2.sval.equals("!=")){
ICode notEqual = new ICode("NEQ", $1.sval, $3.sval, newLabel);
notEqual.emit();
}
//compare the results
/*ICode compare = new ICode("CMP", newTemp, "0");
compare.emit();
String newLabel = ICode.genLabel();
genLabelStack.push(newLabel);
//branch if result is true
ICode branchOnEqual = new ICode("BE", newLabel);
branchOnEqual.emit();*/
}
| PARENL bterm PARENR
fcall: ID PARENL PARENR
{
//generate intermediate code for function
//with no parameters
ICode callSimpleFunction = new ICode("CALL", $1.sval);
callSimpleFunction.emit();
String stretTemp = ICode.genTemp();
currTable.add(stretTemp, "int");
ICode stret = new ICode("STRET", stretTemp);
stret.emit();
//return the result
$$.sval = stretTemp;
}
| ID PARENL aplist PARENR
{
//generate intermediate code for function with parameters
String stretTemp = ICode.genTemp();
currTable.add(stretTemp, "int");
//if there is no values currently stored, generate the intermediate code
ICode fCallParameters = new ICode("PARAM", $3.sval);
fCallParameters.emit();
//generate CALL intermediate code and print
ICode callSimpleFunction = new ICode("CALL", $1.sval);
callSimpleFunction.emit();
ICode stret = new ICode("STRET", stretTemp);
stret.emit();
//return temp variable
$$.sval = stretTemp;
}
;
aplist:expr COMMA aplist
| expr
| STRING
;
while: WHILE
{
//generate label for while loop
String topLabel = ICode.genLabel();
ICode topStatement = new ICode("NOPWHILE");
topStatement.addLabel(topLabel);
topStatement.emit();
//add the label to the stack
whileLabelStack.push(topLabel);
}
PARENL bexpr PARENR
stmt
{
//jump back to the top
ICode jump = new ICode("JMP", whileLabelStack.pop());
jump.emit();
//get past the while loop
ICode pastWhileLoop = new ICode("NOP");
pastWhileLoop.addLabel(genLabelStack.pop());
pastWhileLoop.emit();
}
;
if: IF PARENL bexpr PARENR stmt elsepart
;
elsepart: ELSE
{
//generate label for branching to else
String branchAlwaysIfLbl = ICode.genLabel();
branchAlwaysStack.push(branchAlwaysIfLbl);
//there is always a branch to get to else statement
ICode branchAlwaysIf = new ICode("BA", branchAlwaysIfLbl);
branchAlwaysIf.emit();
//branch to get to ELSE
String elseLabel = genLabelStack.pop();
ICode elseBranch = new ICode("NOPELSE");
elseBranch.addLabel(elseLabel);
elseBranch.emit();
}
stmt
{
//create a branch to get past the IF statement
ICode afterElse = new ICode("NOP");
afterElse.addLabel(branchAlwaysStack.pop());
afterElse.emit();
}
| /*Epsilon*/
{
String afterIfLbl = ICode.genLabel();
ICode afterIf = new ICode("NOPIF");
afterIf.addLabel(genLabelStack.pop());
afterIf.emit();
}
%%
//##############################################################################
public int stmtCount;
public int funcCount;
public SymbolTable currTable;
public SymbolTable globalTable;
public LinkedList<String> whileLabelStack;
public LinkedList<String> genLabelStack;
public LinkedList<String> branchAlwaysStack;
public LinkedList<String> varStack;
public LinkedList<String> cmpStack;
public static LinkedList<SymbolTable> myTables;
private MyLexer yylexer;
private Token t;
//##############################################################################
public void setup(String fname)
{
yylexer = new MyLexer(fname);
stmtCount = 0;
funcCount = 0;
//intialize gobal table
globalTable = new SymbolTable("__GLOBAL__");
whileLabelStack = new LinkedList<String>();
genLabelStack = new LinkedList<String>();
branchAlwaysStack = new LinkedList<String>();
varStack = new LinkedList<String>();
cmpStack = new LinkedList<String>();
myTables = new LinkedList<SymbolTable>();
}
//##############################################################################
public void yyerror(String s)
{
System.out.println("error found near line:"+t.getLine());
System.out.println(" token:"+t.getValue());
System.out.println(s);
}
//##############################################################################
public int yylex()
{
try
{
t = yylexer.nextToken();
}
catch (Exception e)
{
System.err.println("yylex unable to aquire token");
return -1;
}
if (t==null)
return -1;
String tVal = t.getValue();
switch(t.getType())
{
case Token.NUMBER:
yylval = new ParserVal(Integer.parseInt(tVal));
return NUMBER;
case Token.ADDOP:
yylval = new ParserVal(tVal);
return ADDOP;
case Token.MULOP:
yylval = new ParserVal(tVal);
return MULOP;
case Token.RELOP:
yylval = new ParserVal(tVal);
return RELOP;
case Token.ID:
yylval = new ParserVal(tVal);
return ID;
case Token.PARENL:
return PARENL;
case Token.PARENR:
return PARENR;
case Token.COMMA:
return COMMA;
case Token.ASSIGNOP:
return ASSIGNOP;
case Token.SEMICOLON:
return SEMICOLON;
case Token.IF:
return IF;
case Token.WHILE:
return WHILE;
case Token.ELSE:
return ELSE;
case Token.CURLL:
return CURLL;
case Token.CURLR:
return CURLR;
case Token.VAR:
return VAR;
case Token.FUNCTION:
return FUNCTION;
case Token.OR:
return OR;
case Token.AND:
return AND;
case Token.NOT:
return NOT;
case Token.STRING:
yylval = new ParserVal(tVal);
return STRING;
default:
return -1;
}
}
//##############################################################################
//check to see if current operator is a number or NOT
public boolean isNumber(String currentOp){
try{
Integer.parseInt(currentOp);
return true;
}
catch(NumberFormatException ex){
return false;
}
}
//##############################################################################
public void printHeader(){
//print the header from the preamble
ICode section = new ICode(".section", ".rodata");
ICode printL = new ICode(".string", "\"%d\\n\"");
printL.addLabel("_printL");
ICode readL = new ICode(".string", "\"%d\"");
readL.addLabel("_readL");
ICode text = new ICode(".text");
ICode globl = new ICode(".globl", "main");
section.print();
printL.print();
readL.print();
text.print();
globl.print();
}
//##############################################################################
public void printRead(){
//print the read function from the built in preamble
System.out.print("read:");
ICode pushq = new ICode("pushq", "%rbp");
ICode movq = new ICode("movq", "%rsp", "%rbp");
ICode subq = new ICode("subq", "$16", "%rsp");
ICode leaq = new ICode("leaq", "-4(%rbp)", "%rsi");
ICode movq2 = new ICode("movq", "$_readL", "%rdi");
ICode movl = new ICode("movl", "$0", "%eax");
ICode call = new ICode("call", "scanf");
ICode movl2 = new ICode("movl", "-4(%rbp)", "%eax");
ICode leave = new ICode("leave");
ICode ret = new ICode("ret");
pushq.print();
movq.print();
subq.print();
System.out.println();
leaq.print();
movq2.print();
movl.print();
call.print();
movl2.print();
System.out.println();
leave.print();
ret.print();
}
//##############################################################################
public void printPrint(){
//print the built in print function from preamble
System.out.print("print:");
ICode pushq = new ICode("pushq", "%rbp");
ICode movq = new ICode("movq", "%rsp", "%rbp");
ICode movl = new ICode("movl", "%eax", "%esi");
ICode movl2 = new ICode("movl", "$_printL", "%edi");
ICode movl3 = new ICode("movl", "$0", "%eax");
ICode call = new ICode("call", "printf");
ICode leave = new ICode("leave");
ICode ret = new ICode("ret");
pushq.print();
movq.print();
System.out.println();
movl.print();
movl2.print();
movl3.print();
call.print();
System.out.println();
leave.print();
ret.print();
}
//##############################################################################
public static void main(String args[])
{
Parser par = new Parser(false);
par.setup(args[0]);
par.yyparse();
par.printHeader();
par.printPrint();
par.printRead();
//go through all intermediate code statements
for(ICode c: ICode.stmtList){
String currentOp = "";
String currentOp2 = "";
String currentOp3 = "";
//get the current table
SymbolTable currentTable = myTables.getLast();
String tableSize = String.format("%d", currentTable.getSize());
//print the intermediate code as a comment
System.out.print("#");
c.print();
List<String> operands = c.getOperands();
//current intermediate code has 1 operand
if(operands.size()>=1){
currentOp = operands.get(0);
}
//current intermediate code has 2 operands
if(operands.size()>=2){
currentOp = operands.get(0);
currentOp2 = operands.get(1);
}
//current intermediate code has 3 operands
if(operands.size()>=3){
currentOp = operands.get(0);
currentOp2 = operands.get(1);
currentOp3 = operands.get(2);
}
//********************* NOP ******************************************
//hit a new function / label
if(c.getOpCode() == "NOP"){
System.out.println(c.getLabel() + ":");
ICode newReg = new ICode("pushq", "%rbp");
ICode newFunc = new ICode("movq", "%rsp", "%rbp");
ICode subq = new ICode("subq", "$" + tableSize, "%rsp");
newReg.print();
newFunc.print();
subq.print();
}
//************************** NOP-IF *************************************
//reached end of if statement label
if(c.getOpCode() == "NOPIF"){
System.out.println(c.getLabel() + ":");
}
//************************** NOP-WHILE *************************************
//reached end of if statement label
if(c.getOpCode() == "NOPWHILE"){
System.out.println(c.getLabel() + ":");
}
//************************** JMP *************************************
//always jump
if(c.getOpCode() == "JMP"){
ICode jump = new ICode("jmp", currentOp);
jump.print();
}
//************************** MUL *************************************
//handle multiplication
if(c.getOpCode() == "MUL"){
if(par.isNumber(currentOp) && par.isNumber(currentOp2)){
ICode movl = new ICode("movl", "$" + currentOp, "%eax");
ICode imull = new ICode("imull", "$" + currentOp2, "%eax");
movl.print();
imull.print();
}
else if(par.isNumber(currentOp) && !par.isNumber(currentOp2)){
//get the op offset
Symbol currSymbol = currentTable.find(currentOp2);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
ICode movl = new ICode("movl", doOffset, "%eax");
ICode imull = new ICode("imull", "$" + currentOp, "%eax");
movl.print();
imull.print();
}
else if(!par.isNumber(currentOp) && par.isNumber(currentOp2)){
//get the op offset
Symbol currSymbol = currentTable.find(currentOp);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
ICode movl = new ICode("movl", doOffset, "%eax");
ICode imull = new ICode("imull", "$" + currentOp2, "%eax");
movl.print();
imull.print();
}
else if(!par.isNumber(currentOp) && !par.isNumber(currentOp2)){
//get the op offset
Symbol currSymbol = currentTable.find(currentOp);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
//get the op offset
Symbol currSymbol2 = currentTable.find(currentOp2);
String currOffset2 = String.format("%d", currSymbol2.getOffset());
String doOffset2 = "-" + currOffset2 + "(%rbp)";
ICode movl = new ICode("movl", doOffset, "%eax");
ICode imull = new ICode("imull", doOffset2, "%eax");
movl.print();
imull.print();
}
//get the temp offset to store result
Symbol currSymbol = currentTable.find(currentOp3);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
ICode movl = new ICode("movl", "%eax", doOffset);
movl.print();
}
//************************** DIV *************************************
//handle multiplication
if(c.getOpCode() == "DIV"){
if(par.isNumber(currentOp) && par.isNumber(currentOp2)){
ICode movl = new ICode("movl", "$" + currentOp, "%eax");
ICode cltd = new ICode("cltd");
ICode imull = new ICode("idivl", "$" + currentOp2, "%eax");
movl.print();
cltd.print();
imull.print();
}
else if(par.isNumber(currentOp) && !par.isNumber(currentOp2)){
//get the op offset
Symbol currSymbol = currentTable.find(currentOp2);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
ICode movl = new ICode("movl", doOffset, "%eax");
ICode cltd = new ICode("cltd");
ICode imull = new ICode("idivl", "$" + currentOp, "%eax");
movl.print();
cltd.print();
imull.print();
}
else if(!par.isNumber(currentOp) && par.isNumber(currentOp2)){
//get the op offset
Symbol currSymbol = currentTable.find(currentOp);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
ICode movl = new ICode("movl", doOffset, "%eax");
ICode cltd = new ICode("cltd");
ICode imull = new ICode("idivl", "$" + currentOp2, "%eax");
movl.print();
cltd.print();
imull.print();
}
else if(!par.isNumber(currentOp) && !par.isNumber(currentOp2)){
//get the op offset
Symbol currSymbol = currentTable.find(currentOp);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
//get the op offset
Symbol currSymbol2 = currentTable.find(currentOp2);
String currOffset2 = String.format("%d", currSymbol2.getOffset());
String doOffset2 = "-" + currOffset2 + "(%rbp)";
ICode movl = new ICode("movl", doOffset, "%eax");
ICode cltd = new ICode("cltd");
ICode imull = new ICode("idivl", doOffset2, "%eax");
movl.print();
cltd.print();
imull.print();
}
//get the temp offset to store result
Symbol currSymbol = currentTable.find(currentOp3);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
ICode movl = new ICode("movl", "%eax", doOffset);
movl.print();
}
//************************** NEG *************************************
//reached a negative value
if(c.getOpCode() == "NEG"){
//get the temp offset for negative value to be stored
Symbol currTemp = currentTable.find(currentOp2);
String currTempOffset = String.format("%d", currTemp.getOffset());
String tempDoOffset = "-" + currTempOffset + "(%rbp)";
//see if operator is a number
if(par.isNumber(currentOp2)){
ICode movNumber = new ICode("movl", "$" + currentOp2, "%eax");
movNumber.print();
}
//operator is not a number
else{
//get the offset of the value to be stored as negative
Symbol currSymbol = currentTable.find(currentOp);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
ICode movl = new ICode("movl", doOffset, "%eax");
movl.print();
}
//move the negative value into register then store into temp
ICode neg = new ICode("neg", "%eax");
ICode movl2 = new ICode("movl", "%eax", tempDoOffset);
neg.print();
movl2.print();
}
//********************** PARAM *****************************************
//process parameters
else if(c.getOpCode() == "PARAM"){
if(par.isNumber(currentOp)){
//move parameter value into register
ICode param = new ICode("movl", "$" + currentOp, "%eax");
param.print();
}
else{
Symbol currSymbol = currentTable.find(currentOp);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
ICode paramVar = new ICode("movl", doOffset, "%eax");
paramVar.print();
}
}
//*********************** MOV ***************************************
//move values into registers appropriately
else if(c.getOpCode() == "MOV"){
//see if operator is a number
if(par.isNumber(currentOp)){
//get the operators offset
Symbol currSymbol = currentTable.find(currentOp2);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
//move value into register
ICode movlNumber = new ICode("movl", "$" + currentOp, "%eax");
ICode movlTemp = new ICode("movl", "%eax", doOffset);
movlNumber.print();
movlTemp.print();
}
//operator is NOT a number
else{
//get offset of operator
Symbol currSymbol = currentTable.find(currentOp);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
//get offset of second operator
Symbol currSymbol2 = currentTable.find(currentOp2);
String currOffset2 = String.format("%d", currSymbol2.getOffset());
String doOffset2 = "-" + currOffset2 + "(%rbp)";
//move into register
ICode move = new ICode("movl", doOffset, "%eax");
ICode move2 = new ICode("movl", "%eax", doOffset2);
move.print();
move2.print();
}
}
//************************** LT *************************************
else if(c.getOpCode() == "LT"){
//1st operator is a number
if(par.isNumber(currentOp)){
//1st number is operator, 2nd number is operator
if(par.isNumber(currentOp2)){
ICode cmp3 = new ICode("cmp", "$" + currentOp2, "$" + currentOp);
cmp3.print();
}
//1st operator is number, 2nd is NOT
else{
Symbol currSymbol3 = currentTable.find(currentOp2);
String currOffset3 = String.format("%d", currSymbol3.getOffset());
String doOffset3 = "-" + currOffset3 + "(%rbp)";
ICode cmp4 = new ICode("cmp", doOffset3, "$" + currentOp);
cmp4.print();
}
}
//1st operator is not a number
else{
//get the 1st operator's offset
Symbol currSymbol = currentTable.find(currentOp);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
//1st operator is not an number, 2nd is a number
if(par.isNumber(currentOp2)){
ICode cmp1 = new ICode("cmp", "$" + currentOp2, doOffset);
cmp1.print();
}
//1st operator is not a number, 2nd is not a number
else{
Symbol currSymbol2 = currentTable.find(currentOp2);
String currOffset2 = String.format("%d", currSymbol2.getOffset());
String doOffset2 = "-" + currOffset2 + "(%rbp)";
ICode cmp2 = new ICode("cmp", doOffset2, doOffset);
cmp2.print();
}
}
ICode jump = new ICode("jg", currentOp3);
jump.print();
}
//************************** GT *************************************
else if(c.getOpCode() == "GT"){
//1st operator is a number
if(par.isNumber(currentOp)){
//1st number is operator, 2nd number is operator
if(par.isNumber(currentOp2)){
ICode cmp3 = new ICode("cmp", "$" + currentOp2, "$" + currentOp);
cmp3.print();
}
//1st operator is number, 2nd is NOT
else{
Symbol currSymbol3 = currentTable.find(currentOp2);
String currOffset3 = String.format("%d", currSymbol3.getOffset());
String doOffset3 = "-" + currOffset3 + "(%rbp)";
ICode cmp4 = new ICode("cmp", doOffset3, "$" + currentOp);
cmp4.print();
}
}
//1st operator is not a number
else{
//get the 1st operator's offset
Symbol currSymbol = currentTable.find(currentOp);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
//1st operator is not an number, 2nd is a number
if(par.isNumber(currentOp2)){
ICode cmp1 = new ICode("cmp", "$" + currentOp2, doOffset);
cmp1.print();
}
//1st operator is not a number, 2nd is not a number
else{
Symbol currSymbol2 = currentTable.find(currentOp2);
String currOffset2 = String.format("%d", currSymbol2.getOffset());
String doOffset2 = "-" + currOffset2 + "(%rbp)";
ICode cmp2 = new ICode("cmp", doOffset2, doOffset);
cmp2.print();
}
}
ICode jump = new ICode("jl", currentOp3);
jump.print();
}
//************************** LE *************************************
else if(c.getOpCode() == "LE"){
//1st operator is a number
if(par.isNumber(currentOp)){
//1st number is operator, 2nd number is operator
if(par.isNumber(currentOp2)){
ICode cmp3 = new ICode("cmpl", "$" + currentOp2, "$" + currentOp);
cmp3.print();
}
//1st operator is number, 2nd is NOT
else{
Symbol currSymbol3 = currentTable.find(currentOp2);
String currOffset3 = String.format("%d", currSymbol3.getOffset());
String doOffset3 = "-" + currOffset3 + "(%rbp)";
ICode cmp4 = new ICode("cmpl", doOffset3, "$" + currentOp);
cmp4.print();
}
}
//1st operator is not a number
else{
//get the 1st operator's offset
Symbol currSymbol = currentTable.find(currentOp);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
//1st operator is not an number, 2nd is a number
if(par.isNumber(currentOp2)){
ICode cmp1 = new ICode("cmpl", "$" + currentOp2, doOffset);
cmp1.print();
}
//1st operator is not a number, 2nd is not a number
else{
Symbol currSymbol2 = currentTable.find(currentOp2);
String currOffset2 = String.format("%d", currSymbol2.getOffset());
String doOffset2 = "-" + currOffset2 + "(%rbp)";
ICode cmp2 = new ICode("cmpl", doOffset2, doOffset);
cmp2.print();
}
}
ICode jump = new ICode("jle", currentOp3);
jump.print();
}
//************************** GE *************************************
else if(c.getOpCode() == "GE"){
//1st operator is a number
if(par.isNumber(currentOp)){
//1st number is operator, 2nd number is operator
if(par.isNumber(currentOp2)){
ICode cmp3 = new ICode("cmpl", "$" + currentOp2, "$" + currentOp);
cmp3.print();
}
//1st operator is number, 2nd is NOT
else{
Symbol currSymbol3 = currentTable.find(currentOp2);
String currOffset3 = String.format("%d", currSymbol3.getOffset());
String doOffset3 = "-" + currOffset3 + "(%rbp)";
ICode cmp4 = new ICode("cmpl", doOffset3, "$" + currentOp);
cmp4.print();
}
}
//1st operator is not a number
else{
//get the 1st operator's offset
Symbol currSymbol = currentTable.find(currentOp);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
//1st operator is not an number, 2nd is a number
if(par.isNumber(currentOp2)){
ICode cmp1 = new ICode("cmpl", "$" + currentOp2, doOffset);
cmp1.print();
}
//1st operator is not a number, 2nd is not a number
else{
Symbol currSymbol2 = currentTable.find(currentOp2);
String currOffset2 = String.format("%d", currSymbol2.getOffset());
String doOffset2 = "-" + currOffset2 + "(%rbp)";
ICode cmp2 = new ICode("cmpl", doOffset2, doOffset);
cmp2.print();
}
}
ICode jump = new ICode("jge", currentOp3);
jump.print();
}
//************************** ADD *************************************
else if(c.getOpCode() == "ADD"){
//both ops are numbers
if(par.isNumber(currentOp) && par.isNumber(currentOp2)){
//move the values into registers
ICode movl = new ICode("movl", "$" + currentOp, "%edx");
ICode movl2 = new ICode("movl", "$" + currentOp2, "%eax");
movl.print();
movl2.print();
}
//1st and 2nd ops are not numbers
else if(!par.isNumber(currentOp) && !par.isNumber(currentOp2)){
//get the offset for op1
Symbol currSymbol = currentTable.find(currentOp);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
//get the offset for op2
Symbol currSymbol2 = currentTable.find(currentOp2);
String currOffset2 = String.format("%d", currSymbol2.getOffset());
String doOffset2 = "-" + currOffset2 + "(%rbp)";
//move the values into registers
ICode movl = new ICode("movl", doOffset, "%edx");
ICode movl2 = new ICode("movl", doOffset2, "%eax");
movl.print();
movl2.print();
}
//1st op is number 2nd is NOT
else if(par.isNumber(currentOp) && !par.isNumber(currentOp2)){
//get offset of 2nd op
Symbol currSymbol = currentTable.find(currentOp2);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
//move values into registers
ICode movl = new ICode("movl", "$" + currentOp, "%edx");
ICode movl2 = new ICode("movl", doOffset, "%eax");
movl.print();
movl2.print();
}
//1st op is NOT a number and 2nd is
else if(!par.isNumber(currentOp) && par.isNumber(currentOp2)){
Symbol currSymbol = currentTable.find(currentOp);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
//move values into registers
ICode movl = new ICode("movl", doOffset, "%edx");
ICode movl2 = new ICode("movl", "$" + currentOp2, "%eax");
movl.print();
movl2.print();
}
//get offset of temp to store SUM
Symbol currSymbol = currentTable.find(currentOp3);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
//add the values
ICode addl = new ICode("addl", "%edx", "%eax");
//move TOTAL into temp
ICode movel = new ICode("movl", "%eax", doOffset);
addl.print();
movel.print();
}
//************************** SUB *************************************
else if(c.getOpCode() == "SUB"){
//both ops are numbers
if(par.isNumber(currentOp) && par.isNumber(currentOp2)){
//move the values into registers
ICode movl = new ICode("movl", "$" + currentOp, "%edx");
ICode movl2 = new ICode("movl", "$" + currentOp2, "%eax");
movl.print();
movl2.print();
}
//1st and 2nd ops are not numbers
else if(!par.isNumber(currentOp) && !par.isNumber(currentOp2)){
//get the offset for op1
Symbol currSymbol = currentTable.find(currentOp);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
//get the offset for op2
Symbol currSymbol2 = currentTable.find(currentOp2);
String currOffset2 = String.format("%d", currSymbol2.getOffset());
String doOffset2 = "-" + currOffset2 + "(%rbp)";
//move the values into registers
ICode movl = new ICode("movl", doOffset, "%edx");
ICode movl2 = new ICode("movl", doOffset2, "%eax");
movl.print();
movl2.print();
}
//1st op is number 2nd is NOT
else if(par.isNumber(currentOp) && !par.isNumber(currentOp2)){
//get offset of 2nd op
Symbol currSymbol = currentTable.find(currentOp2);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
//move values into registers
ICode movl = new ICode("movl", "$" + currentOp, "%edx");
ICode movl2 = new ICode("movl", doOffset, "%eax");
movl.print();
movl2.print();
}
//1st op is NOT a number and 2nd is
else if(!par.isNumber(currentOp) && par.isNumber(currentOp2)){
Symbol currSymbol = currentTable.find(currentOp2);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
//move values into registers
ICode movl = new ICode("movl", doOffset, "%edx");
ICode movl2 = new ICode("movl", "$" + currentOp2, "%eax");
movl.print();
movl2.print();
}
//get offset of temp to store SUM
Symbol currSymbol = currentTable.find(currentOp3);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
//add the values
ICode subl = new ICode("subl", "%eax", "%edx");
//move TOTAL into temp
ICode movel = new ICode("movl", "%edx", doOffset);
subl.print();
movel.print();
}
//************************** CALL *************************************
//call the current function
else if(c.getOpCode() == "CALL"){
ICode callFunc = new ICode("call", currentOp);
callFunc.print();
}
//************************** STRET *************************************
else if(c.getOpCode() == "STRET"){
Symbol currSymbol = currentTable.find(currentOp);
String currOffset = String.format("%d", currSymbol.getOffset());
String doOffset = "-" + currOffset + "(%rbp)";
ICode storet = new ICode("movl", "%eax", doOffset);
storet.print();
}
//************************ RET *************************************
//end of function reached, return!
else if(c.getOpCode() == "RET"){
ICode leave = new ICode("leave");
ICode ret = new ICode("retq");
leave.print();
ret.print();
myTables.removeLast();
}
System.out.println();
}
}
| true |
7d1f1f71c69e4e24e766d785bf4466ff3d81efda | Java | avijayanhwx/incubator-ratis | /ratis-logservice/src/main/java/org/apache/ratis/logservice/server/LogStateMachine.java | UTF-8 | 17,581 | 1.507813 | 2 | [
"Apache-2.0",
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ratis.logservice.server;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.apache.ratis.logservice.metrics.LogServiceMetricsRegistry;
import org.apache.ratis.logservice.proto.LogServiceProtos.AppendLogEntryRequestProto;
import org.apache.ratis.logservice.proto.LogServiceProtos.CloseLogReplyProto;
import org.apache.ratis.logservice.proto.LogServiceProtos.CloseLogRequestProto;
import org.apache.ratis.logservice.proto.LogServiceProtos.GetLogLengthRequestProto;
import org.apache.ratis.logservice.proto.LogServiceProtos.GetLogSizeRequestProto;
import org.apache.ratis.logservice.proto.LogServiceProtos.GetStateRequestProto;
import org.apache.ratis.logservice.proto.LogServiceProtos.LogServiceRequestProto;
import org.apache.ratis.logservice.proto.LogServiceProtos.ReadLogRequestProto;
import org.apache.ratis.logservice.util.LogServiceProtoUtil;
import org.apache.ratis.metrics.impl.RatisMetricRegistry;
import org.apache.ratis.proto.RaftProtos;
import org.apache.ratis.proto.RaftProtos.LogEntryProto;
import org.apache.ratis.protocol.Message;
import org.apache.ratis.protocol.RaftGroupId;
import org.apache.ratis.server.RaftServer;
import org.apache.ratis.server.impl.RaftServerConstants;
import org.apache.ratis.server.impl.RaftServerProxy;
import org.apache.ratis.server.impl.ServerState;
import org.apache.ratis.server.protocol.TermIndex;
import org.apache.ratis.server.raftlog.RaftLog;
import org.apache.ratis.server.storage.RaftStorage;
import org.apache.ratis.statemachine.StateMachineStorage;
import org.apache.ratis.statemachine.TransactionContext;
import org.apache.ratis.statemachine.impl.BaseStateMachine;
import org.apache.ratis.statemachine.impl.SimpleStateMachineStorage;
import org.apache.ratis.statemachine.impl.SingleFileSnapshotInfo;
import org.apache.ratis.thirdparty.com.google.protobuf.TextFormat;
import org.apache.ratis.util.AutoCloseableLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogStateMachine extends BaseStateMachine {
public static final Logger LOG = LoggerFactory.getLogger(LogStateMachine.class);
private RatisMetricRegistry metricRegistry;
private Timer sizeRequestTimer;
private Timer readNextQueryTimer;
private Timer getStateTimer;
private Timer lastIndexQueryTimer;
private Timer lengthQueryTimer;
private Timer startIndexTimer;
private Timer appendRequestTimer;
private Timer syncRequesTimer;
private Timer getCloseLogTimer;
public static enum State {
OPEN, CLOSED
}
/*
* State is a log's length, size, and state (closed/open);
*/
private long length;
/**
* The size (number of bytes) of the log records. Does not include Ratis storage overhead
*/
private long dataRecordsSize;
private State state = State.OPEN;
private final SimpleStateMachineStorage storage = new SimpleStateMachineStorage();
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
private RaftLog log;
private RaftGroupId groupId;
private RaftServerProxy proxy ;
private AutoCloseableLock readLock() {
return AutoCloseableLock.acquire(lock.readLock());
}
private AutoCloseableLock writeLock() {
return AutoCloseableLock.acquire(lock.writeLock());
}
/**
* Reset state machine
*/
void reset() {
this.length = 0;
this.dataRecordsSize = 0;
setLastAppliedTermIndex(null);
}
@Override
public void initialize(RaftServer server, RaftGroupId groupId,
RaftStorage raftStorage) throws IOException {
super.initialize(server, groupId, raftStorage);
this.storage.init(raftStorage);
this.proxy = (RaftServerProxy) server;
this.groupId = groupId;
//TODO: using groupId for metric now but better to tag it with LogName
this.metricRegistry =
LogServiceMetricsRegistry.createMetricRegistryForLogService(groupId.toString());
this.readNextQueryTimer = metricRegistry.timer("readNextQueryTime");
this.startIndexTimer= metricRegistry.timer("startIndexTime");
this.sizeRequestTimer = metricRegistry.timer("sizeRequestTime");
this.getStateTimer = metricRegistry.timer("getStateTime");
this.lastIndexQueryTimer = metricRegistry.timer("lastIndexQueryTime");
this.lengthQueryTimer = metricRegistry.timer("lengthQueryTime");
this.syncRequesTimer = metricRegistry.timer("syncRequesTime");
this.appendRequestTimer = metricRegistry.timer("appendRequestTime");
this.getCloseLogTimer = metricRegistry.timer("getCloseLogTime");
loadSnapshot(storage.getLatestSnapshot());
}
private void checkInitialization() throws IOException {
if (this.log == null) {
ServerState state = proxy.getImpl(groupId).getState();
this.log = state.getLog();
}
}
@Override
public void reinitialize() throws IOException {
close();
loadSnapshot(storage.getLatestSnapshot());
}
@Override
public long takeSnapshot() {
final TermIndex last;
try(final AutoCloseableLock readLock = readLock()) {
last = getLastAppliedTermIndex();
}
final File snapshotFile = storage.getSnapshotFile(last.getTerm(), last.getIndex());
LOG.info("Taking a snapshot to file {}", snapshotFile);
try(final AutoCloseableLock readLock = readLock();
final ObjectOutputStream out = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(snapshotFile)))) {
out.writeLong(length);
out.writeLong(dataRecordsSize);
out.writeObject(state);
} catch(IOException ioe) {
LOG.warn("Failed to write snapshot file \"" + snapshotFile
+ "\", last applied index=" + last);
}
return last.getIndex();
}
private long loadSnapshot(SingleFileSnapshotInfo snapshot) throws IOException {
return load(snapshot, false);
}
private long load(SingleFileSnapshotInfo snapshot, boolean reload) throws IOException {
if (snapshot == null) {
LOG.warn("The snapshot info is null.");
return RaftServerConstants.INVALID_LOG_INDEX;
}
final File snapshotFile = snapshot.getFile().getPath().toFile();
if (!snapshotFile.exists()) {
LOG.warn("The snapshot file {} does not exist for snapshot {}", snapshotFile, snapshot);
return RaftServerConstants.INVALID_LOG_INDEX;
}
final TermIndex last = SimpleStateMachineStorage.getTermIndexFromSnapshotFile(snapshotFile);
try(final AutoCloseableLock writeLock = writeLock();
final ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(new FileInputStream(snapshotFile)))) {
if (reload) {
reset();
}
setLastAppliedTermIndex(last);
this.length = in.readLong();
this.dataRecordsSize = in.readLong();
this.state = (State) in.readObject();
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
}
return last.getIndex();
}
@Override
public StateMachineStorage getStateMachineStorage() {
return storage;
}
@Override
public CompletableFuture<Message> query(Message request) {
try {
checkInitialization();
LogServiceRequestProto logServiceRequestProto =
LogServiceRequestProto.parseFrom(request.getContent());
if (LOG.isTraceEnabled()) {
LOG.trace("Processing LogService query: {}", TextFormat.shortDebugString(logServiceRequestProto));
}
switch (logServiceRequestProto.getRequestCase()) {
case READNEXTQUERY:
return recordTime(readNextQueryTimer, new Task(){
@Override public CompletableFuture<Message> run() {
return processReadRequest(logServiceRequestProto);
}
});
case SIZEREQUEST:
return recordTime(sizeRequestTimer, new Task(){
@Override public CompletableFuture<Message> run() {
return processGetSizeRequest(logServiceRequestProto);
}
});
case STARTINDEXQUERY:
return recordTime(startIndexTimer, new Task(){
@Override public CompletableFuture<Message> run() {
return processGetStartIndexRequest(logServiceRequestProto);
}
});
case GETSTATE:
return recordTime(getStateTimer, new Task(){
@Override public CompletableFuture<Message> run() {
return processGetStateRequest(logServiceRequestProto);
}
});
case LASTINDEXQUERY:
return recordTime(lastIndexQueryTimer, new Task(){
@Override public CompletableFuture<Message> run() {
return processGetLastCommittedIndexRequest(logServiceRequestProto);
}
});
case LENGTHQUERY:
return recordTime(lengthQueryTimer, new Task(){
@Override public CompletableFuture<Message> run() {
return processGetLengthRequest(logServiceRequestProto);
}
});
default:
// TODO
throw new RuntimeException(
"Wrong message type for query: " + logServiceRequestProto.getRequestCase());
}
} catch (IOException e) {
// TODO exception handling
throw new RuntimeException(e);
}
}
/**
* Process get start index request
* @param proto message
* @return reply message
*/
private CompletableFuture<Message>
processGetStartIndexRequest(LogServiceRequestProto proto)
{
Throwable t = verifyState(State.OPEN);
long startIndex = log.getStartIndex();
return CompletableFuture.completedFuture(Message
.valueOf(LogServiceProtoUtil.toGetLogStartIndexReplyProto(startIndex, t).toByteString()));
}
/**
* Process get last committed record index
* @param proto message
* @return reply message
*/
private CompletableFuture<Message>
processGetLastCommittedIndexRequest(LogServiceRequestProto proto)
{
Throwable t = verifyState(State.OPEN);
long lastIndex = log.getLastCommittedIndex();
return CompletableFuture.completedFuture(Message
.valueOf(LogServiceProtoUtil.toGetLogLastIndexReplyProto(lastIndex, t).toByteString()));
}
/**
* Process get length request
* @param proto message
* @return reply message
*/
private CompletableFuture<Message> processGetSizeRequest(LogServiceRequestProto proto) {
GetLogSizeRequestProto msgProto = proto.getSizeRequest();
Throwable t = verifyState(State.OPEN);
LOG.trace("Size query: {}, Result: {}", msgProto, this.dataRecordsSize);
return CompletableFuture.completedFuture(Message
.valueOf(LogServiceProtoUtil.toGetLogSizeReplyProto(this.dataRecordsSize, t).toByteString()));
}
private CompletableFuture<Message> processGetLengthRequest(LogServiceRequestProto proto) {
GetLogLengthRequestProto msgProto = proto.getLengthQuery();
Throwable t = verifyState(State.OPEN);
LOG.trace("Length query: {}, Result: {}", msgProto, this.length);
return CompletableFuture.completedFuture(Message
.valueOf(LogServiceProtoUtil.toGetLogLengthReplyProto(this.length, t).toByteString()));
}
/**
* Process read log entries request
* @param proto message
* @return reply message
*/
private CompletableFuture<Message> processReadRequest(LogServiceRequestProto proto) {
ReadLogRequestProto msgProto = proto.getReadNextQuery();
// Get the recordId the user wants to start reading at
long startRecordId = msgProto.getStartRecordId();
// And the number of records they want to read
int numRecordsToRead = msgProto.getNumRecords();
Throwable t = verifyState(State.OPEN);
List<byte[]> list = null;
if (t == null) {
LogServiceRaftLogReader reader = new LogServiceRaftLogReader(log);
list = new ArrayList<byte[]>();
try {
reader.seek(startRecordId);
for (int i = 0; i < numRecordsToRead; i++) {
if (!reader.hasNext()) {
break;
}
list.add(reader.next().toByteArray());
}
} catch (Exception e) {
LOG.error("Failed to execute ReadNextQuery", e);
t = e;
list = null;
}
}
return CompletableFuture.completedFuture(
Message.valueOf(LogServiceProtoUtil.toReadLogReplyProto(list, t).toByteString()));
}
/**
* Process sync request
* @param trx transaction
* @param logMessage message
* @return reply message
*/
private CompletableFuture<Message> processSyncRequest(TransactionContext trx,
LogServiceRequestProto logMessage) {
long index = trx.getLogEntry().getIndex();
// TODO: Do we really need this call?
return CompletableFuture.completedFuture(Message
.valueOf(LogServiceProtoUtil.toSyncLogReplyProto(index, null).toByteString()));
}
private CompletableFuture<Message> processAppendRequest(TransactionContext trx,
LogServiceRequestProto logProto) {
final LogEntryProto entry = trx.getLogEntry();
AppendLogEntryRequestProto proto = logProto.getAppendRequest();
final long index = entry.getIndex();
long newSize = 0;
Throwable t = verifyState(State.OPEN);
final List<Long> ids = new ArrayList<Long>();
if (t == null) {
try (final AutoCloseableLock writeLock = writeLock()) {
List<byte[]> entries = LogServiceProtoUtil.toListByteArray(proto.getDataList());
for (byte[] bb : entries) {
ids.add(this.length);
newSize += bb.length;
this.length++;
}
this.dataRecordsSize += newSize;
// TODO do we need this for other write request (close, sync)
updateLastAppliedTermIndex(entry.getTerm(), index);
}
}
final CompletableFuture<Message> f =
CompletableFuture.completedFuture(
Message.valueOf(LogServiceProtoUtil.toAppendLogReplyProto(ids, t).toByteString()));
final RaftProtos.RaftPeerRole role = trx.getServerRole();
if (LOG.isTraceEnabled()) {
LOG.trace("{}:{}-{}: {} new length {}", role, getId(), index,
TextFormat.shortDebugString(proto), dataRecordsSize);
}
return f;
}
@Override
public void close() {
reset();
}
@Override
public CompletableFuture<Message> applyTransaction(TransactionContext trx) {
try {
checkInitialization();
final LogEntryProto entry = trx.getLogEntry();
LogServiceRequestProto logServiceRequestProto =
LogServiceRequestProto.parseFrom(entry.getStateMachineLogEntry().getLogData());
switch (logServiceRequestProto.getRequestCase()) {
case CLOSELOG:
return recordTime(getCloseLogTimer, new Task(){
@Override public CompletableFuture<Message> run() {
return processCloseLog(logServiceRequestProto);
}});
case APPENDREQUEST:
return recordTime(appendRequestTimer, new Task(){
@Override public CompletableFuture<Message> run() {
return processAppendRequest(trx, logServiceRequestProto);
}});
case SYNCREQUEST:
return recordTime(syncRequesTimer, new Task(){
@Override public CompletableFuture<Message> run() {
return processSyncRequest(trx, logServiceRequestProto);
}});
default:
//TODO
return null;
}
} catch (IOException e) {
// TODO exception handling
throw new RuntimeException(e);
}
}
private CompletableFuture<Message> processCloseLog(LogServiceRequestProto logServiceRequestProto) {
CloseLogRequestProto closeLog = logServiceRequestProto.getCloseLog();
// Need to check whether the file is opened if opened close it.
// TODO need to handle exceptions while operating with files.
return CompletableFuture.completedFuture(Message
.valueOf(CloseLogReplyProto.newBuilder().build().toByteString()));
}
private CompletableFuture<Message> processGetStateRequest(
LogServiceRequestProto logServiceRequestProto) {
GetStateRequestProto getState = logServiceRequestProto.getGetState();
return CompletableFuture.completedFuture(Message.valueOf(LogServiceProtoUtil
.toGetStateReplyProto(state == State.OPEN).toByteString()));
}
private Throwable verifyState(State state) {
if (this.state != state) {
return new IOException("Wrong state: " + this.state);
}
return null;
}
}
| true |
64a44fb749954c2dd92f070924945b3963ee19f6 | Java | kakukosaku/design-pattern | /src/main/java/com/github/kakusosaku/designpattern/creational/singleton/ThreadSafeOnInstance.java | UTF-8 | 2,005 | 3.546875 | 4 | [] | no_license | package com.github.kakusosaku.designpattern.creational.singleton;
import java.io.Serializable;
/**
* 利用双重检验锁(Double-Checked Locking idiom)机制的线程安全"懒加载"的 单例模式
*
* @author kaku
* Date 2020-01-30
*/
class ThreadSafeOnInstance implements Serializable {
private static volatile ThreadSafeOnInstance instance;
private static boolean unInitialized = true;
private ThreadSafeOnInstance() {
if (unInitialized) {
unInitialized = false;
} else {
throw new IllegalStateException("Already initialized.");
}
}
public static ThreadSafeOnInstance getInstance() {
// local variable increases performance by 25 percent
var result = instance;
if (result == null) {
synchronized (ThreadSafeOnInstance.class) {
result = instance;
if (result == null) {
instance = result = new ThreadSafeOnInstance();
}
}
}
return result;
}
/**
* 反序列化时, 解析返回object时调用, 返回已初始化好的"单例对象"
*
* @return singleton instance of ThreadCareSingleton
*/
@SuppressWarnings("unused")
private Object readResolve() {
return instance;
}
/**
* 提供统一的"类加载", 避免因不同容器类加载导致类存在不同空间, 影响单例模式
*
* @param className returns the runtime class of this object.
* @return the class of ThreadCareSingleton.
* @throws ClassNotFoundException 类未找到异常
*/
@SuppressWarnings("unused")
private static Class getClass(String className) throws ClassNotFoundException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null)
classLoader = ThreadSafeOnInstance.class.getClassLoader();
return (classLoader.loadClass(className));
}
}
| true |
de45dd7c7835505246145842180ee62479ccb2d4 | Java | nagpalShaurya/Explore | /app/src/main/java/com/example/explore/results.java | UTF-8 | 2,949 | 2.078125 | 2 | [] | no_license | package com.example.explore;
import android.content.Intent;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class results extends AppCompatActivity {
// FireBase stuff
private FirebaseDatabase database;
private FirebaseAuth mAuth;
private DatabaseReference databaseReference;
private String UserID;
private ListView mListView;
String title;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fetchlist);
mAuth = FirebaseAuth.getInstance();
mListView = findViewById(R.id.listview);
database = FirebaseDatabase.getInstance();
databaseReference = database.getReference().child("Published Forms");
final FirebaseUser user = mAuth.getCurrentUser();
UserID = user.getUid();
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
final ArrayList<String> array = new ArrayList<>();
for (DataSnapshot ds: dataSnapshot.getChildren())
{
/* USER user1 = new USER();
user1.setName(ds.getValue(USER.class).getName());
user1.setID(ds.getValue(USER.class).getID());
array.add("Employee Name: "+ user1.getName()+"\n"+"Employee ID: "+user1.getID());*/
final Poll_Model pm = new Poll_Model();
pm.setTitle(ds.getValue(Poll_Model.class).getTitle());
title = pm.getTitle();
long yesVotes = (Long) ds.child("Yes").getValue();
long noVotes = (Long) ds.child("No").getValue();
long maybeVotes = (Long) ds.child("Maybe").getValue();
array.add("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"+pm.getTitle()+"\n\n"+"Total Yes : "+yesVotes+"\nTotal No : "+noVotes+"\nTotal Maybe : "+maybeVotes+"\n" );
}
ArrayAdapter adapter = new ArrayAdapter(results.this,android.R.layout.simple_list_item_1,array);
mListView.setAdapter(adapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
| true |
0deaf001c2a9f7d816e9e6fed0a16b2c7f133f48 | Java | xuning2516/AndroidTestDemos | /persistencetest/src/main/java/com/example/persistencetest/MainActivity.java | UTF-8 | 3,557 | 2.15625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
* Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
* Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
* Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
* Vestibulum commodo. Ut rhoncus gravida arcu.
*/
package com.example.persistencetest;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private EditText editText;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.inputContent);
textView = (TextView)findViewById(R.id.showContent);
}
public void onClick(View view){
switch (view.getId()){
case R.id.saveContent:
saveToFile();
break;
case R.id.getContent:
showFileContent();
case R.id.toSharedActivity:
Intent intent = new Intent(MainActivity.this,SharePreferenceActivity.class);
startActivity(intent);
default:
break;
}
}
private void saveToFile(){
String text = editText.getText().toString();
FileOutputStream outs = null;
BufferedWriter bufferWriter = null;
if(!TextUtils.isEmpty(text)){
try {
outs = openFileOutput("data",MODE_PRIVATE);
bufferWriter = new BufferedWriter(new OutputStreamWriter(outs));
bufferWriter.write(text);
editText.setText("");
}catch (FileNotFoundException ex){
}catch (IOException e){
} finally{
if(bufferWriter!= null){
try {
bufferWriter.close();
}catch (IOException e){
}
}
}
}
}
public void showFileContent(){
FileInputStream fileInputSteam;
BufferedReader reader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
fileInputSteam = openFileInput("data");
reader = new BufferedReader(new InputStreamReader(fileInputSteam));
String line = "";
do {
line = reader.readLine();
if(!TextUtils.isEmpty(line)) {
stringBuilder.append(line);
}
}while(!TextUtils.isEmpty(line));
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException ex){
}finally {
if(reader != null){
try {
reader.close();
}catch (IOException e){
}
}
}
textView.setText(stringBuilder.toString());
}
}
| true |
07a89530f289297cda4c248eaeeebe35e77f5909 | Java | martyybu/PrivateHireCars | /src/uk/ac/gre/ma8521e/privatehirecars/GUI/Views/MainView.java | UTF-8 | 14,808 | 1.90625 | 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 uk.ac.gre.ma8521e.privatehirecars.GUI.Views;
import javax.swing.JPanel;
/**
*
* @author ma8521e
*/
public class MainView extends javax.swing.JFrame {
/**
* Creates new form MainView1
*/
public MainView() {
initComponents();
this.setIconImage(new javax.swing.ImageIcon(getClass().getResource("/uk/ac/gre/ma8521e/privatehirecars/GUI/Images/taxi_128x.png")).getImage());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
bg = new javax.swing.JPanel();
sideMenu = new javax.swing.JPanel();
btn_enquiries = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
btn_profile = new javax.swing.JPanel();
jLabel11 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
btn_bookings = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
btn_createbookings = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
btn_createEnquiries = new javax.swing.JPanel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setMinimumSize(new java.awt.Dimension(1155, 575));
setPreferredSize(new java.awt.Dimension(1155, 575));
setResizable(false);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
bg.setBackground(new java.awt.Color(255, 255, 255));
bg.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
bg.setMaximumSize(new java.awt.Dimension(1283, 550));
bg.setMinimumSize(new java.awt.Dimension(1283, 550));
bg.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
sideMenu.setBackground(new java.awt.Color(54, 33, 89));
sideMenu.setAutoscrolls(true);
sideMenu.setRequestFocusEnabled(false);
sideMenu.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
btn_enquiries.setBackground(new java.awt.Color(64, 43, 100));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/uk/ac/gre/ma8521e/privatehirecars/GUI/Images/icons8_Speech_Bubble_15px_1.png"))); // NOI18N
jLabel12.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
jLabel12.setForeground(new java.awt.Color(204, 204, 204));
jLabel12.setText("Enquiries");
javax.swing.GroupLayout btn_enquiriesLayout = new javax.swing.GroupLayout(btn_enquiries);
btn_enquiries.setLayout(btn_enquiriesLayout);
btn_enquiriesLayout.setHorizontalGroup(
btn_enquiriesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(btn_enquiriesLayout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel12)
.addContainerGap(120, Short.MAX_VALUE))
);
btn_enquiriesLayout.setVerticalGroup(
btn_enquiriesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(btn_enquiriesLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel12)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
sideMenu.add(btn_enquiries, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 310, 240, 40));
btn_profile.setBackground(new java.awt.Color(85, 65, 118));
jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/uk/ac/gre/ma8521e/privatehirecars/GUI/Images/icons8_User_Account_15px.png"))); // NOI18N
jLabel14.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
jLabel14.setForeground(new java.awt.Color(204, 204, 204));
jLabel14.setText("Profile");
javax.swing.GroupLayout btn_profileLayout = new javax.swing.GroupLayout(btn_profile);
btn_profile.setLayout(btn_profileLayout);
btn_profileLayout.setHorizontalGroup(
btn_profileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(btn_profileLayout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel14)
.addContainerGap(135, Short.MAX_VALUE))
);
btn_profileLayout.setVerticalGroup(
btn_profileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(btn_profileLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel14)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
sideMenu.add(btn_profile, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 230, 240, 40));
btn_bookings.setBackground(new java.awt.Color(64, 43, 100));
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/uk/ac/gre/ma8521e/privatehirecars/GUI/Images/icons8_Booking_15px.png"))); // NOI18N
jLabel4.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
jLabel4.setForeground(new java.awt.Color(204, 204, 204));
jLabel4.setText("Bookings");
javax.swing.GroupLayout btn_bookingsLayout = new javax.swing.GroupLayout(btn_bookings);
btn_bookings.setLayout(btn_bookingsLayout);
btn_bookingsLayout.setHorizontalGroup(
btn_bookingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(btn_bookingsLayout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addContainerGap(122, Short.MAX_VALUE))
);
btn_bookingsLayout.setVerticalGroup(
btn_bookingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(btn_bookingsLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
sideMenu.add(btn_bookings, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 270, 240, 40));
btn_createbookings.setBackground(new java.awt.Color(64, 43, 100));
jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/uk/ac/gre/ma8521e/privatehirecars/GUI/Images/icons8_Plus_15px_2.png"))); // NOI18N
jLabel6.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
jLabel6.setForeground(new java.awt.Color(204, 204, 204));
jLabel6.setText("Create a Booking");
javax.swing.GroupLayout btn_createbookingsLayout = new javax.swing.GroupLayout(btn_createbookings);
btn_createbookings.setLayout(btn_createbookingsLayout);
btn_createbookingsLayout.setHorizontalGroup(
btn_createbookingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(btn_createbookingsLayout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6)
.addContainerGap(124, Short.MAX_VALUE))
);
btn_createbookingsLayout.setVerticalGroup(
btn_createbookingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(btn_createbookingsLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel6)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
sideMenu.add(btn_createbookings, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 350, -1, 40));
btn_createEnquiries.setBackground(new java.awt.Color(64, 43, 100));
jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/uk/ac/gre/ma8521e/privatehirecars/GUI/Images/icons8_Plus_15px_2.png"))); // NOI18N
jLabel8.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
jLabel8.setForeground(new java.awt.Color(204, 204, 204));
jLabel8.setText("Create Enquiry");
javax.swing.GroupLayout btn_createEnquiriesLayout = new javax.swing.GroupLayout(btn_createEnquiries);
btn_createEnquiries.setLayout(btn_createEnquiriesLayout);
btn_createEnquiriesLayout.setHorizontalGroup(
btn_createEnquiriesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(btn_createEnquiriesLayout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel8)
.addContainerGap(124, Short.MAX_VALUE))
);
btn_createEnquiriesLayout.setVerticalGroup(
btn_createEnquiriesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(btn_createEnquiriesLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel8)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
sideMenu.add(btn_createEnquiries, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 390, -1, 40));
jLabel9.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
jLabel9.setForeground(new java.awt.Color(204, 204, 204));
jLabel9.setText("PrivateHire Cars");
sideMenu.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 30, -1, -1));
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/uk/ac/gre/ma8521e/privatehirecars/GUI/Images/taxi_128x.png"))); // NOI18N
sideMenu.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 70, 140, 140));
bg.add(sideMenu, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 240, 550));
jPanel2.setLayout(new java.awt.CardLayout());
bg.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 0, 930, 550));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(bg, javax.swing.GroupLayout.PREFERRED_SIZE, 1170, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(bg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1));
pack();
}// </editor-fold>//GEN-END:initComponents
public JPanel getBookings() {
return btn_bookings;
}
public JPanel getCreateEnquiries() {
return this.btn_createEnquiries;
}
public JPanel getCreateBookings() {
return this.btn_createbookings;
}
public JPanel getProfile() {
return this.btn_profile;
}
public JPanel getLeftPanel() {
return this.jPanel2;
}
public JPanel getEnquiries(){
return this.btn_enquiries;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel bg;
private javax.swing.JPanel btn_bookings;
private javax.swing.JPanel btn_createEnquiries;
private javax.swing.JPanel btn_createbookings;
private javax.swing.JPanel btn_enquiries;
private javax.swing.JPanel btn_profile;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel sideMenu;
// End of variables declaration//GEN-END:variables
}
| true |
45ff46618ac5fce802c86a36001171195189ce54 | Java | sagar777-bit/healthweb | /app/src/main/java/com/example/esp_health_monitor/registerActivity.java | UTF-8 | 890 | 2.09375 | 2 | [] | no_license | package com.example.esp_health_monitor;
import android.os.Bundle;
import android.widget.FrameLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
public class registerActivity extends AppCompatActivity {
private FrameLayout fragmentlayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
fragmentlayout = findViewById(R.id.register_frame);
setDefaultFragment(new signinFragment());
}
private void setDefaultFragment(Fragment fragment){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(fragmentlayout.getId(),fragment);
fragmentTransaction.commit();
}
}
| true |
65b8cf890adf93d8a0ef84ab222d071736e15cd8 | Java | Maitin96/TheClub | /MyClub/src/main/java/com/martin/myclub/activity/FindFriendActivity.java | UTF-8 | 478 | 1.703125 | 2 | [] | no_license | package com.martin.myclub.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import com.martin.myclub.R;
/**
* Created by Martin on 2017/7/17.
*/
public class FindFriendActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_friend);
}
}
| true |
5e2a02fb47afa8a65924617493972c5c0b2c053e | Java | stelar7/JavaBottyMcBotface | /src/main/java/no/stelar7/botty/command/handlers/ToggleCommand.java | UTF-8 | 1,185 | 2.890625 | 3 | [] | no_license | package no.stelar7.botty.command.handlers;
import no.stelar7.botty.command.*;
import java.util.*;
public class ToggleCommand extends Command
{
public ToggleCommand()
{
this.setAdminOnly(true);
}
@Override
public void execute(CommandParameters params)
{
if (params.getParameters().size() != 1)
{
params.getMessage()
.getChannel().block()
.createMessage("Invalid command: Needs 1 parameter").block();
return;
}
String key = params.getParameters().get(0);
List<Command> commands = CommandHandler.handlers.getOrDefault(key, new ArrayList<>());
for (Command command : commands)
{
command.setDisabled(!command.isDisabled());
String output = command.getCommands().get(0) + " is now " + (command.isDisabled() ? "disabled" : "enabled");
params.getMessage()
.getChannel().block()
.createMessage(output).block();
}
}
@Override
public List<String> getCommands()
{
return List.of("toggle");
}
}
| true |
ac720ce68ee1a93d42117dde28a03e37a8d80434 | Java | qiaolunzhang/logistics | /module-client/src/main/java/org/module/client/businesslogicservice/statisticBLService_stub/AccountManageBLService_stub.java | UTF-8 | 1,371 | 1.703125 | 2 | [] | no_license | package org.module.client.businesslogicservice.statisticBLService_stub;
import java.util.ArrayList;
import org.module.client.businesslogicservice.statisticBLservice.AccountManageBLService;
import org.module.client.vo.AccountVO;
import org.module.common.dataservice.MyList;
public class AccountManageBLService_stub implements AccountManageBLService {
public boolean add(String id, String rest) {
// TODO Auto-generated method stub
return false;
}
public boolean delete(String id) {
// TODO Auto-generated method stub
return false;
}
public boolean delete(ArrayList<String> a) {
// TODO Auto-generated method stub
return false;
}
public boolean update(String id, String rest) {
// TODO Auto-generated method stub
return false;
}
public boolean income(String id, double rest) {
// TODO Auto-generated method stub
return false;
}
public boolean pay(String id, double b) {
// TODO Auto-generated method stub
return false;
}
public ArrayList<AccountVO> showAll() {
// TODO Auto-generated method stub
return null;
}
public ArrayList<AccountVO> fuzzySearch(String s) {
// TODO Auto-generated method stub
return null;
}
public boolean delete(MyList<String> a) {
// TODO Auto-generated method stub
return false;
}
public boolean delete(int[] a) {
// TODO Auto-generated method stub
return false;
}
}
| true |
86d69a7e32482f3adbb30b5bb04798c28bbe0384 | Java | chiexuna/wewewe | /src/main/java/com/chiexuna/wewewe/controllers/PageController.java | UTF-8 | 387 | 1.851563 | 2 | [] | no_license | package com.chiexuna.wewewe.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class PageController {
@RequestMapping("/")
public String mainPage() {
return "app.home";
}
@RequestMapping("/about")
public String about() {
return "app.about";
}
}
| true |
3d879c3933e946d4c94cce931e3ea408c72862bc | Java | gneliana/MeritBankServices | /src/main/java/com/meritamerica/CapstoneBankApp/models/IRAAccount.java | UTF-8 | 2,283 | 3.015625 | 3 | [] | no_license | package com.meritamerica.CapstoneBankApp.models;
import com.meritamerica.CapstoneBankApp.exceptions.NegativeBalanceException;
import com.meritamerica.CapstoneBankApp.services.TransactionService;
// *** add closeAccount override method
public abstract class IRAAccount extends BankAccount {
TransactionService transactionService;
@Override
public Transaction simpleTransaction(BankAccount targetAccount, Transaction transaction) throws NegativeBalanceException {
if(transaction.getAmount() > 0){
this.deposit(targetAccount, transaction.getAmount());
}
if(transaction.getAmount() < 0) {
this.withdraw(targetAccount, transaction.getAmount() * -1);
//pay 20% to IRS when withdrawing from any IRA account
double irsDeduction = (transaction.getAmount() * -1) * .2;
// get a whole double
irsDeduction = (Math.floor(irsDeduction * 100)/100);
}
// transactionService.save(transaction);
return transaction;
}
// NEED TO ADD 20% TAX
@Override
public Transaction transferTransaction(BankAccount sourceAccount, BankAccount targetAccount,
Transaction transaction) {
if(transaction.getAmount() > 0){
this.deposit(targetAccount, transaction.getAmount());
}
if(transaction.getAmount() < 0) {
try {
this.withdraw(targetAccount, transaction.getAmount() * -1);
} catch (NegativeBalanceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return transaction;
}
// need to ensure you can cover cost of penalties before withdrawing from any ira account
@Override
public void withdraw(BankAccount targetAccount, double amount) throws NegativeBalanceException {
// withdraw amount + penalty must be greater than the amount available for withdraw
double penatlyCoverage = Math.floor((amount * 1.2) * 100)/100; // must use to get a whole, rounded double
if(penatlyCoverage > super.getBalance())
throw new NegativeBalanceException("Available balance must cover withdraw amount and 20% IRS fee");
if(amount > super.getBalance())
throw new NegativeBalanceException("Withdraw amount exceeds availabe balance");
if(amount < 0)
throw new NegativeBalanceException("Cannot withdraw negative amount");
transactionService.withdraw(targetAccount, amount);
}
}
| true |
feb043090b073a6b1cd69071f9f0844866ec6dde | Java | camilleblanche/shaojing520 | /src/main/java/com/camille/shaojing/dao/impl/UserDaoImpl.java | UTF-8 | 1,133 | 2.125 | 2 | [] | no_license | package com.camille.shaojing.dao.impl;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.camille.shaojing.dao.IUserDao;
import com.camille.shaojing.mapper.UserMapper;
import com.camille.shaojing.model.User;
@Repository
public class UserDaoImpl implements IUserDao{
@Autowired
private UserMapper userMapper;
@Override
public int addUser(User user) {
return userMapper.insertSelective(user);
}
@Override
public int deleteUser(Long[] userIds) {
return userMapper.deleteBatch(userIds);
}
@Override
public int updateUser(User user) {
return userMapper.updateByPrimaryKeySelective(user);
}
@Override
public User getUserByAccount(String account) {
return userMapper.getUserByAccount(account);
}
@Override
public Set<String> getRoleSetByUserId(Long userId) {
return userMapper.getRoleSetByUserId(userId);
}
@Override
public List<String> getPermissionListByUserId(Long userId) {
return userMapper.getPermissionListByUserId(userId);
}
}
| true |
cba900c2440bc7171b651bc78853933a7a608718 | Java | splitio/android-client | /src/main/java/io/split/android/client/telemetry/model/RefreshRates.java | UTF-8 | 1,166 | 1.882813 | 2 | [
"Apache-2.0"
] | permissive | package io.split.android.client.telemetry.model;
import com.google.gson.annotations.SerializedName;
public class RefreshRates {
@SerializedName("sp")
private long splits;
@SerializedName("ms")
private long mySegments;
@SerializedName("im")
private long impressions;
@SerializedName("ev")
private long events;
@SerializedName("te")
private long telemetry;
public long getSplits() {
return splits;
}
public void setSplits(long splits) {
this.splits = splits;
}
public long getMySegments() {
return mySegments;
}
public void setMySegments(long mySegments) {
this.mySegments = mySegments;
}
public long getImpressions() {
return impressions;
}
public void setImpressions(long impressions) {
this.impressions = impressions;
}
public long getEvents() {
return events;
}
public void setEvents(long events) {
this.events = events;
}
public long getTelemetry() {
return telemetry;
}
public void setTelemetry(long telemetry) {
this.telemetry = telemetry;
}
}
| true |
9857badb2119a0d8aab6be300fa128a7e18f6016 | Java | cnuwyl/springboot | /springboot-services/src/main/java/springboot/service/impl/Register.java | UTF-8 | 87 | 1.648438 | 2 | [
"Apache-2.0"
] | permissive | package springboot.service.impl;
public interface Register {
String register();
}
| true |
6a927b9f168159dbf418e6f6cef91bf5df973093 | Java | arturojcn/assessmentAvantrip | /src/main/java/ar/com/avantrip/service/FraudulentFlightService.java | UTF-8 | 3,234 | 2.28125 | 2 | [] | no_license | package ar.com.avantrip.service;
import java.sql.SQLException;
import java.util.logging.Logger;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.core.DefaultRulesEngine;
import org.jeasy.rules.mvel.MVELRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ar.com.avantrip.binding.CalculateScoringRequest;
import ar.com.avantrip.binding.FraudulentFlightRequest;
import ar.com.avantrip.binding.RulesResquest;
import ar.com.avantrip.binding.ScoreResquest;
import ar.com.avantrip.repository.FraudulentFlightRepository;
@Service
public class FraudulentFlightService implements FraudulentFlightRepository {
private static Logger logger = Logger.getLogger(FraudulentFlightService.class.getCanonicalName());
@Autowired
private ScoreService scoreService;
@Autowired
private RulesService rulesService;
@Autowired
BlacklistService blacklistService;
@Override
public boolean fraudFlight(FraudulentFlightRequest request) {
logger.info("fraudFlight()");
boolean fraud = false;
int score = 0;
ScoreResquest scoreResquest = scoreService.findScore();
score = scoreResquest.getScore();
logger.info("score config is: " + score);
int scoring = calculateScoring(request);
logger.info("score config is: " + score + " > " + scoring + " :calculate scoring?");
if(scoring >= score)
fraud = true;
return fraud;
}
@Override
public Integer calculateScoring(FraudulentFlightRequest request) {
int scoring = 0;
int maxScoreFraud = 0;
ScoreResquest scoreResquest = scoreService.findScore();
maxScoreFraud = scoreResquest.getScoreMaxFraud();
try {
if(isBlackList(request.getDetailPaymentOption().getCardNumberFront())) {
logger.info("tarjeta encontrada en la blacklist retorno el maximo score de fraude");
return (maxScoreFraud);
}
CalculateScoringRequest calculateSCoring = new CalculateScoringRequest(0, request);
Facts fact = new Facts();
fact.put("fraudulentFlightRequest", calculateSCoring);
Iterable<RulesResquest> rules = rulesService.listAllActivesRules();
for (RulesResquest rulesResquest : rules) {
calculateSCoring.setScoring(0);
MVELRule evaluateRule = new MVELRule().name(rulesResquest.getNameRule())
.description(rulesResquest.getDescriptionRule()).priority(rulesResquest.getPriorityRule())
.when(rulesResquest.getConditionRule()).then(rulesResquest.getActionRule());
Rules rulesRule = new Rules();
rulesRule.register(evaluateRule);
RulesEngine rulesEngine = new DefaultRulesEngine();
logger.info("Ejecutando regla");
rulesEngine.fire(rulesRule, fact);
scoring += calculateSCoring.getScoring();
///Si el escoring calculado es hasta acá es mayor o igual al maxscore fraude devuuelvo el maxScoreFraud
if(scoring >= maxScoreFraud )
return (maxScoreFraud);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return scoring;
}
@Override
public boolean isBlackList(String cardNumber) throws SQLException {
logger.info("isBlackList()");
return blacklistService.findCardBlackList(cardNumber);
}
}
| true |
bedde21ef87aab3435ca4e164ec28ad71649ecf5 | Java | aosp-mirror/platform_frameworks_base | /core/java/android/app/ambientcontext/AmbientContextManager.java | UTF-8 | 15,910 | 1.835938 | 2 | [
"LicenseRef-scancode-unicode",
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2022 The Android Open Source 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 android.app.ambientcontext;
import android.Manifest;
import android.annotation.CallbackExecutor;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.RemoteCallback;
import android.os.RemoteException;
import com.android.internal.util.Preconditions;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
/**
* Allows granted apps to register for event types defined in {@link AmbientContextEvent}.
* After registration, the app receives a Consumer callback of the service status.
* If it is {@link STATUS_SUCCESSFUL}, when the requested events are detected, the provided
* {@link PendingIntent} callback will receive the list of detected {@link AmbientContextEvent}s.
* If it is {@link STATUS_ACCESS_DENIED}, the app can call {@link #startConsentActivity}
* to load the consent screen.
*
* @hide
*/
@SystemApi
@SystemService(Context.AMBIENT_CONTEXT_SERVICE)
public final class AmbientContextManager {
/**
* The bundle key for the service status query result, used in
* {@code RemoteCallback#sendResult}.
*
* @hide
*/
public static final String STATUS_RESPONSE_BUNDLE_KEY =
"android.app.ambientcontext.AmbientContextStatusBundleKey";
/**
* The key of an intent extra indicating a list of detected {@link AmbientContextEvent}s.
* The intent is sent to the app in the app's registered {@link PendingIntent}.
*/
public static final String EXTRA_AMBIENT_CONTEXT_EVENTS =
"android.app.ambientcontext.extra.AMBIENT_CONTEXT_EVENTS";
/**
* An unknown status.
*/
public static final int STATUS_UNKNOWN = 0;
/**
* The value of the status code that indicates success.
*/
public static final int STATUS_SUCCESS = 1;
/**
* The value of the status code that indicates one or more of the
* requested events are not supported.
*/
public static final int STATUS_NOT_SUPPORTED = 2;
/**
* The value of the status code that indicates service not available.
*/
public static final int STATUS_SERVICE_UNAVAILABLE = 3;
/**
* The value of the status code that microphone is disabled.
*/
public static final int STATUS_MICROPHONE_DISABLED = 4;
/**
* The value of the status code that the app is not granted access.
*/
public static final int STATUS_ACCESS_DENIED = 5;
/** @hide */
@IntDef(prefix = { "STATUS_" }, value = {
STATUS_UNKNOWN,
STATUS_SUCCESS,
STATUS_NOT_SUPPORTED,
STATUS_SERVICE_UNAVAILABLE,
STATUS_MICROPHONE_DISABLED,
STATUS_ACCESS_DENIED
}) public @interface StatusCode {}
/**
* Allows clients to retrieve the list of {@link AmbientContextEvent}s from the intent.
*
* @param intent received from the PendingIntent callback
*
* @return the list of events, or an empty list if the intent doesn't have such events.
*/
@NonNull public static List<AmbientContextEvent> getEventsFromIntent(@NonNull Intent intent) {
if (intent.hasExtra(AmbientContextManager.EXTRA_AMBIENT_CONTEXT_EVENTS)) {
return intent.getParcelableArrayListExtra(EXTRA_AMBIENT_CONTEXT_EVENTS);
} else {
return new ArrayList<>();
}
}
private final Context mContext;
private final IAmbientContextManager mService;
/**
* {@hide}
*/
public AmbientContextManager(Context context, IAmbientContextManager service) {
mContext = context;
mService = service;
}
/**
* Queries the {@link AmbientContextEvent} service status for the calling package, and
* sends the result to the {@link Consumer} right after the call. This is used by foreground
* apps to check whether the requested events are enabled for detection on the device.
* If all events are enabled for detection, the response has
* {@link AmbientContextManager#STATUS_SUCCESS}.
* If any of the events are not consented by user, the response has
* {@link AmbientContextManager#STATUS_ACCESS_DENIED}, and the app can
* call {@link #startConsentActivity} to redirect the user to the consent screen.
* <p />
*
* Example:
*
* <pre><code>
* Set<Integer> eventTypes = new HashSet<>();
* eventTypes.add(AmbientContextEvent.EVENT_COUGH);
* eventTypes.add(AmbientContextEvent.EVENT_SNORE);
*
* // Create Consumer
* Consumer<Integer> statusConsumer = status -> {
* int status = status.getStatusCode();
* if (status == AmbientContextManager.STATUS_SUCCESS) {
* // Show user it's enabled
* } else if (status == AmbientContextManager.STATUS_ACCESS_DENIED) {
* // Send user to grant access
* startConsentActivity(eventTypes);
* }
* };
*
* // Query status
* AmbientContextManager ambientContextManager =
* context.getSystemService(AmbientContextManager.class);
* ambientContextManager.queryAmbientContextStatus(eventTypes, executor, statusConsumer);
* </code></pre>
*
* @param eventTypes The set of event codes to check status on.
* @param executor Executor on which to run the consumer callback.
* @param consumer The consumer that handles the status code.
*/
@RequiresPermission(Manifest.permission.ACCESS_AMBIENT_CONTEXT_EVENT)
public void queryAmbientContextServiceStatus(
@NonNull @AmbientContextEvent.EventCode Set<Integer> eventTypes,
@NonNull @CallbackExecutor Executor executor,
@NonNull @StatusCode Consumer<Integer> consumer) {
try {
RemoteCallback callback = new RemoteCallback(result -> {
int status = result.getInt(STATUS_RESPONSE_BUNDLE_KEY);
final long identity = Binder.clearCallingIdentity();
try {
executor.execute(() -> consumer.accept(status));
} finally {
Binder.restoreCallingIdentity(identity);
}
});
mService.queryServiceStatus(integerSetToIntArray(eventTypes),
mContext.getOpPackageName(), callback);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Requests the consent data host to open an activity that allows users to modify consent.
*
* @param eventTypes The set of event codes to be consented.
*/
@RequiresPermission(Manifest.permission.ACCESS_AMBIENT_CONTEXT_EVENT)
public void startConsentActivity(
@NonNull @AmbientContextEvent.EventCode Set<Integer> eventTypes) {
try {
mService.startConsentActivity(
integerSetToIntArray(eventTypes), mContext.getOpPackageName());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
@NonNull
private static int[] integerSetToIntArray(@NonNull Set<Integer> integerSet) {
int[] intArray = new int[integerSet.size()];
int i = 0;
for (Integer type : integerSet) {
intArray[i++] = type;
}
return intArray;
}
/**
* Allows app to register as a {@link AmbientContextEvent} observer. The
* observer receives a callback on the provided {@link PendingIntent} when the requested
* event is detected. Registering another observer from the same package that has already been
* registered will override the previous observer.
* <p />
*
* Example:
*
* <pre><code>
* // Create request
* AmbientContextEventRequest request = new AmbientContextEventRequest.Builder()
* .addEventType(AmbientContextEvent.EVENT_COUGH)
* .addEventType(AmbientContextEvent.EVENT_SNORE)
* .build();
*
* // Create PendingIntent for delivering detection results to my receiver
* Intent intent = new Intent(actionString, null, context, MyBroadcastReceiver.class)
* .addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
* PendingIntent pendingIntent =
* PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
*
* // Create Consumer of service status
* Consumer<Integer> statusConsumer = status -> {
* if (status == AmbientContextManager.STATUS_ACCESS_DENIED) {
* // User did not consent event detection. See #queryAmbientContextServiceStatus and
* // #startConsentActivity
* }
* };
*
* // Register as observer
* AmbientContextManager ambientContextManager =
* context.getSystemService(AmbientContextManager.class);
* ambientContextManager.registerObserver(request, pendingIntent, executor, statusConsumer);
*
* // Handle the list of {@link AmbientContextEvent}s in your receiver
* {@literal @}Override
* protected void onReceive(Context context, Intent intent) {
* List<AmbientContextEvent> events = AmbientContextManager.getEventsFromIntent(intent);
* if (!events.isEmpty()) {
* // Do something useful with the events.
* }
* }
* </code></pre>
*
* @param request The request with events to observe.
* @param resultPendingIntent A mutable {@link PendingIntent} that will be dispatched after the
* requested events are detected.
* @param executor Executor on which to run the consumer callback.
* @param statusConsumer A consumer that handles the status code, which is returned
* right after the call.
*/
@RequiresPermission(Manifest.permission.ACCESS_AMBIENT_CONTEXT_EVENT)
public void registerObserver(
@NonNull AmbientContextEventRequest request,
@NonNull PendingIntent resultPendingIntent,
@NonNull @CallbackExecutor Executor executor,
@NonNull @StatusCode Consumer<Integer> statusConsumer) {
Preconditions.checkArgument(!resultPendingIntent.isImmutable());
try {
RemoteCallback callback = new RemoteCallback(result -> {
int statusCode = result.getInt(STATUS_RESPONSE_BUNDLE_KEY);
final long identity = Binder.clearCallingIdentity();
try {
executor.execute(() -> statusConsumer.accept(statusCode));
} finally {
Binder.restoreCallingIdentity(identity);
}
});
mService.registerObserver(request, resultPendingIntent, callback);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Allows app to register as a {@link AmbientContextEvent} observer. Same as {@link
* #registerObserver(AmbientContextEventRequest, PendingIntent, Executor, Consumer)},
* but use {@link AmbientContextCallback} instead of {@link PendingIntent} as a callback on
* detected events.
* Registering another observer from the same package that has already been
* registered will override the previous observer. If the same app previously calls
* {@link #registerObserver(AmbientContextEventRequest, AmbientContextCallback, Executor)},
* and now calls
* {@link #registerObserver(AmbientContextEventRequest, PendingIntent, Executor, Consumer)},
* the previous observer will be replaced with the new observer with the PendingIntent callback.
* Or vice versa.
*
* When the registration completes, a status will be returned to client through
* {@link AmbientContextCallback#onRegistrationComplete(int)}.
* If the AmbientContextManager service is not enabled yet, or the underlying detection service
* is not running yet, {@link AmbientContextManager#STATUS_SERVICE_UNAVAILABLE} will be
* returned, and the detection won't be really started.
* If the underlying detection service feature is not enabled, or the requested event type is
* not enabled yet, {@link AmbientContextManager#STATUS_NOT_SUPPORTED} will be returned, and the
* detection won't be really started.
* If there is no user consent, {@link AmbientContextManager#STATUS_ACCESS_DENIED} will be
* returned, and the detection won't be really started.
* Otherwise, it will try to start the detection. And if it starts successfully, it will return
* {@link AmbientContextManager#STATUS_SUCCESS}. If it fails to start the detection, then
* it will return {@link AmbientContextManager#STATUS_SERVICE_UNAVAILABLE}
* After registerObserver succeeds and when the service detects an event, the service will
* trigger {@link AmbientContextCallback#onEvents(List)}.
*
* @hide
*/
@RequiresPermission(Manifest.permission.ACCESS_AMBIENT_CONTEXT_EVENT)
public void registerObserver(
@NonNull AmbientContextEventRequest request,
@NonNull @CallbackExecutor Executor executor,
@NonNull AmbientContextCallback ambientContextCallback) {
try {
IAmbientContextObserver observer = new IAmbientContextObserver.Stub() {
@Override
public void onEvents(List<AmbientContextEvent> events) throws RemoteException {
final long identity = Binder.clearCallingIdentity();
try {
executor.execute(() -> ambientContextCallback.onEvents(events));
} finally {
Binder.restoreCallingIdentity(identity);
}
}
@Override
public void onRegistrationComplete(int statusCode) throws RemoteException {
final long identity = Binder.clearCallingIdentity();
try {
executor.execute(
() -> ambientContextCallback.onRegistrationComplete(statusCode));
} finally {
Binder.restoreCallingIdentity(identity);
}
}
};
mService.registerObserverWithCallback(request, mContext.getPackageName(), observer);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Unregisters the requesting app as an {@code AmbientContextEvent} observer. Unregistering an
* observer that was already unregistered or never registered will have no effect.
*/
@RequiresPermission(Manifest.permission.ACCESS_AMBIENT_CONTEXT_EVENT)
public void unregisterObserver() {
try {
mService.unregisterObserver(mContext.getOpPackageName());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
}
| true |
1e2a778f4122f058ebfa0b6ae8d79457179ddf72 | Java | bhagatali/MicroPetStore | /Service/Counter/src/main/java/com/petstore/counter/controller/CounterController.java | UTF-8 | 2,027 | 2.21875 | 2 | [] | no_license | package com.petstore.counter.controller;
import static org.springframework.data.mongodb.core.FindAndModifyOptions.options;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.petstore.counter.domain.Counter;
import com.petstore.counter.repository.CounterRepository;
@RestController
@RequestMapping("/counter")
@CrossOrigin
public class CounterController {
private MongoOperations mongo;
private CounterRepository counterRepository;
@Autowired
public CounterController(MongoOperations mongo, CounterRepository counterRepository) {
this.mongo = mongo;
this.counterRepository = counterRepository;
}
@RequestMapping(value="/", method=RequestMethod.GET)
public Iterable<Counter> getAllCounters(){
return counterRepository.findAll();
}
@RequestMapping(value="/{collectionName}", method=RequestMethod.GET)
public int getNextSequence(@PathVariable String collectionName) {
Counter counter = mongo.findAndModify
(
query(where("_id").is(collectionName)),
new Update().inc("seq", 1),
options().returnNew(true),
Counter.class
);
return counter.getSeq();
}
@RequestMapping(value="/", method=RequestMethod.POST)
public Counter insertSequence(@RequestBody Counter counter){
return counterRepository.save(counter);
}
}
| true |
b648420cc3ef75940b79ad62b6536aa96fe3d035 | Java | ShivaramPrasad/Advanced-WebTechnology | /Web/hello/src/main/java/ex01D/C.java | UTF-8 | 415 | 3.53125 | 4 | [] | no_license | package ex01D;
public class C
{
public static void method1(int i, StringBuffer s)
{
i++;
s.append("d"); //append will add 'd' to that stringBuffer
}
public static void main(String [] args)
{
int i = 0;
StringBuffer s = new StringBuffer("abc");
method1(i, s); //calling method func.
System.out.println("i=" + i + ", s=" + s); //Output: i=0, s=abcd
}
} | true |
8f198acaca9f83f4a6828391c649f849b573ba78 | Java | yl940127/mall | /mall-core/src/main/java/com/rhinoceros/mall/core/utils/StringUtils.java | UTF-8 | 1,368 | 3.046875 | 3 | [] | no_license | package com.rhinoceros.mall.core.utils;
/**
* @author Rhys Xia
* <p>
* 2018/03/02 09:37
* <p>
* 字符串工具类
*/
public class StringUtils {
/**
* 下划线转驼峰法
*
* @param str
* @return
*/
public static String underline2Camel(String str) {
if (str == null || str.trim().length() == 0) {
return "";
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '_') {
i++;
if (i < str.length()) {
sb.append(Character.toUpperCase(str.charAt(i)));
}
} else {
sb.append(str.charAt(i));
}
}
return sb.toString();
}
/**
* 驼峰法转下划线
*
* @param str
* @return
*/
public static String camel2Underline(String str) {
if (str == null || str.trim().length() == 0) {
return "";
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(str.charAt(i))) {
sb.append("_").append(Character.toLowerCase(str.charAt(i)));
} else {
sb.append(str.charAt(i));
}
}
return sb.toString();
}
}
| true |
96a349b9cd30d54da47a9e202bf88e0246b6132b | Java | xqkjTeam/myPrpject | /OCRS/src/com/minit/aeap/modules/cs/forms/TelrecordForm.java | UTF-8 | 2,209 | 1.898438 | 2 | [] | no_license | package com.minit.aeap.modules.cs.forms;
import org.frames.commons.utils.DateUtil;
import com.minit.aeap.bases.ModulesBaseBeanForm;
import com.minit.aeap.modules.cs.models.Telrecord;
public class TelrecordForm extends ModulesBaseBeanForm {
/**
*
*/
private static final long serialVersionUID = 5386797053038403692L;
private Telrecord telrecord = new Telrecord();
public Telrecord getTelrecord() {
return telrecord;
}
public void setTelrecord(Telrecord telrecord) {
this.telrecord = telrecord;
}
public String getTelrecordid() {
return telrecord.getTelrecordid();
}
public void setTelrecordid(String telrecordid) {
telrecord.setTelrecordid(telrecordid);
}
public String getCallorg() {
return telrecord.getCallorg();
}
public void setCallorg(String callorg) {
telrecord.setCallorg(callorg);
}
public String getCalltel() {
return telrecord.getCalltel();
}
public void setCalltel(String calltel) {
telrecord.setCalltel(calltel);
}
public String getFilename() {
return telrecord.getFilename();
}
public void setFilename(String filename) {
telrecord.setFilename(filename);
}
public String getCallstarttime() {
return DateUtil.getDateWithHm(telrecord.getCallstarttime());
}
public void setCallstarttime(String callstarttime) {
telrecord.setCallstarttime(DateUtil.convertStringToDate("yyyy-MM-dd HH:mm", callstarttime));
}
public String getCallendtime() {
return DateUtil.getDateWithHm(telrecord.getCallendtime());
}
public void setCallendtime(String callendtime) {
telrecord.setCallendtime(DateUtil.convertStringToDate("yyyy-MM-dd HH:mm", callendtime));
}
public String getUserid() {
return telrecord.getUserid();
}
public void setUserid(String userid) {
telrecord.setUserid(userid);
}
public String getUsername() {
return telrecord.getUsername();
}
public void setUsername(String username) {
telrecord.setUsername(username);
}
public String getRecordcontent() {
return telrecord.getRecordcontent();
}
public void setRecordcontent(String recordcontent) {
telrecord.setRecordcontent(recordcontent);
}
}
| true |
375d4f98b95b2bfef695312c72968242464e6b01 | Java | lywme/javaReview | /doublyLinkedList.java | UTF-8 | 3,996 | 3.390625 | 3 | [] | no_license | package com.company;
public class Main{
public static void main(String[] args)
{
doublyLinkedListHead dl=new doublyLinkedListHead();
System.out.println(dl.isEmpty());
dl.addInFront("China");
dl.addInFront("Canada");
System.out.println(dl.size());
dl.printAllFromFront();
dl.addInFront("USA");
System.out.println(dl.size());
dl.printAllFromFront();
System.out.println(dl.removeFromFront().getName());
dl.printAllFromFront();
System.out.println(dl.size());
System.out.println(dl.isEmpty());
dl.printAllFromEnd();
dl.addIntheEnd("Japan");
dl.addIntheEnd("Korea");
dl.printAllFromFront();
dl.printAllFromEnd();
System.out.println(dl.size());
dl.removeFromEnd();
dl.printAllFromFront();
dl.printAllFromEnd();
System.out.println(dl.size());
dl.addAfterName("Canada","Brazil");
dl.printAllFromFront();
dl.printAllFromEnd();
System.out.println(dl.size());
dl.addAfterName("Brazil","New Zealand");
dl.printAllFromFront();
dl.printAllFromEnd();
System.out.println(dl.size());
}
}
class doublyLinkedListHead
{
private int count=0;
doublyLinkedListNode head;
doublyLinkedListNode tail;
void addInFront(String name)
{
doublyLinkedListNode newNode=new doublyLinkedListNode(name);
if(head==null)
{
//add the 1st item in list
newNode.setPrevious(null);
newNode.setNext(null);
head=newNode;
tail=newNode;
}
else
{
head.setPrevious(newNode);
newNode.setNext(head);
head=newNode;
newNode.setPrevious(null);
}
count++;
}
void addIntheEnd(String name)
{
doublyLinkedListNode newNode=new doublyLinkedListNode(name);
if(head==null)
{
//The same as add the 1st item in list
newNode.setPrevious(null);
newNode.setNext(null);
head=newNode;
tail=newNode;
}
else
{
newNode.setPrevious(tail);
newNode.setNext(null);
tail.setNext(newNode);
tail=newNode;
}
count++;
}
void addAfterName(String name,String newStringName)
{
doublyLinkedListNode current=head;
while(current!=null)
{
if(current.getName().equals(name))
break;
current=current.getNext();
}
System.out.println("Quit");
System.out.println(current!=null);
if(current!=null)
{
//found item
doublyLinkedListNode newNode=new doublyLinkedListNode(newStringName);
current.getNext().setPrevious(newNode);
newNode.setNext(current.getNext());
newNode.setPrevious(current);
current.setNext(newNode);
count++;
}
}
boolean isEmpty()
{
return head==null;
}
doublyLinkedListNode removeFromFront()
{
if(isEmpty())
return null;
doublyLinkedListNode temp=head;
head=head.getNext();
head.setPrevious(null);
count--;
return temp;
}
doublyLinkedListNode removeFromEnd()
{
if(isEmpty())
return null;
doublyLinkedListNode temp=tail;
tail.getPrevious().setNext(null);
tail=tail.getPrevious();
count--;
return temp;
}
int size()
{
return count;
}
void printAllFromFront()
{
System.out.print("Head :");
doublyLinkedListNode current=head;
while(current!=null)
{
System.out.print(" --> "+current.getName());
current=current.getNext();
}
System.out.println("-> Tail");
}
void printAllFromEnd()
{
System.out.print("Tail :");
doublyLinkedListNode current=tail;
while(current!=null)
{
System.out.print(" --> "+current.getName());
current=current.getPrevious();
}
System.out.println("-> Head");
}
}
class doublyLinkedListNode
{
private String Name;
private doublyLinkedListNode previous;
private doublyLinkedListNode next;
doublyLinkedListNode(String name)
{
this.Name=name;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public doublyLinkedListNode getNext() {
return next;
}
public void setNext(doublyLinkedListNode next) {
this.next = next;
}
public doublyLinkedListNode getPrevious() {
return previous;
}
public void setPrevious(doublyLinkedListNode previous) {
this.previous = previous;
}
}
| true |
f8ee1efa74b94f0a22985fa1dd76aed5f38a3964 | Java | aerdei/openshift-bamboo | /src/main/java/com/redhat/openshift/plugins/DeploymentConfigTask.java | UTF-8 | 7,066 | 1.796875 | 2 | [] | no_license | package com.redhat.openshift.plugins;
import static com.redhat.openshift.plugins.Constants.BAMBOO_VAR_OCP_SERVER;
import static com.redhat.openshift.plugins.Constants.BAMBOO_VAR_OCP_TOKEN;
import static com.redhat.openshift.plugins.Constants.FAILED_TO_SET_UP_HTTP_CLIENT;
import static com.redhat.openshift.plugins.Constants.OPENSHIFT_DEPLOYMENTCONFIG_EXISTS;
import static com.redhat.openshift.plugins.Constants.OPENSHIFT_DEPLOYMENTCONFIG_NAME;
import static com.redhat.openshift.plugins.Constants.OPENSHIFT_DEPLOYMENT_REPLICAS;
import static com.redhat.openshift.plugins.Constants.OPENSHIFT_DEPLOYMENT_STRATEGY;
import static com.redhat.openshift.plugins.Constants.OPENSHIFT_NAMESPACE;
import static com.redhat.openshift.plugins.Constants.OPENSHIFT_SERVER_ADDRESS;
import static org.apache.http.HttpStatus.SC_CONFLICT;
import static org.apache.http.HttpStatus.SC_CREATED;
import com.atlassian.bamboo.build.logger.BuildLogger;
import com.atlassian.bamboo.task.TaskContext;
import com.atlassian.bamboo.task.TaskResult;
import com.atlassian.bamboo.task.TaskResultBuilder;
import com.atlassian.bamboo.task.TaskType;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import java.util.Objects;
public class DeploymentConfigTask implements TaskType {
@Override
@NotNull
public TaskResult execute(@NotNull TaskContext taskContext) {
final BuildLogger buildLogger = taskContext.getBuildLogger();
String ocpToken;
String ocpServer;
// Set Unirest HTTP client to trust all certificates. Required temporarily to work with self
// signed OCP certs.
try {
Unirest.setHttpClient(Utils.setHttpClient());
} catch (java.security.NoSuchAlgorithmException | java.security.KeyManagementException secEx) {
Utils.sendLog(buildLogger, false, FAILED_TO_SET_UP_HTTP_CLIENT);
return TaskResultBuilder.newBuilder(taskContext).failed().build();
}
DeploymentConfig deploymentConfig = new DeploymentConfig(taskContext);
deploymentConfig.configureContainers();
deploymentConfig.setReplicas(
taskContext.getConfigurationMap().get(OPENSHIFT_DEPLOYMENT_REPLICAS));
if (Objects.equals(
taskContext.getConfigurationMap().get(OPENSHIFT_DEPLOYMENT_STRATEGY),
Constants.OCP_DEPLOYMENT_STRATEGY_RECREATE)) {
deploymentConfig.setDeploymentStrategyRecreate();
} else if (Objects.equals(
taskContext.getConfigurationMap().get(OPENSHIFT_DEPLOYMENT_STRATEGY),
Constants.OCP_DEPLOYMENT_STRATEGY_ROLLING)) {
deploymentConfig.setDeploymentStrategyRolling();
}
try {
ocpServer =
taskContext
.getBuildContext()
.getVariableContext()
.getEffectiveVariables()
.get(BAMBOO_VAR_OCP_SERVER)
.getValue();
ocpToken =
taskContext
.getBuildContext()
.getVariableContext()
.getEffectiveVariables()
.get(BAMBOO_VAR_OCP_TOKEN)
.getValue();
} catch (NullPointerException npe) {
ocpServer = Constants.EMPTY_STRING;
ocpToken = Constants.EMPTY_STRING;
}
if (ocpServer.isEmpty() || ocpToken.isEmpty()) {
ocpToken = Utils.getToken(taskContext, buildLogger);
ocpServer = taskContext.getConfigurationMap().get(OPENSHIFT_SERVER_ADDRESS);
}
if (sendJsonRequest(
taskContext, deploymentConfig.getJsonObject(), buildLogger, ocpToken, ocpServer)) {
return TaskResultBuilder.newBuilder(taskContext).success().build();
} else {
return TaskResultBuilder.newBuilder(taskContext).failed().build();
}
}
private boolean sendJsonRequest(
@NotNull TaskContext taskContext,
@NotNull JSONObject deploymentconfigJsonObject,
BuildLogger buildLogger,
@NotNull String token,
@NotNull String server) {
boolean result = false;
// Send REST API POST to the OCP server, create a deployment config
try {
HttpResponse<JsonNode> jsonResponse =
Unirest.post(
server
+ Constants.OAPI_V_1_NAMESPACES
+ taskContext.getConfigurationMap().get(OPENSHIFT_NAMESPACE)
+ "/deploymentconfigs/")
.header(Constants.ACCEPT, Constants.APPLICATION_JSON)
.header(Constants.AUTHORIZATION, Constants.BEARER + token)
.header(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON)
.body(deploymentconfigJsonObject.toString())
.asJson();
Utils.sendLog(buildLogger, jsonResponse);
if (jsonResponse.getStatus() == SC_CREATED) {
Utils.sendLog(buildLogger, false, "DeploymentConfig successfully created.");
result = true;
} else if (jsonResponse.getStatus() == SC_CONFLICT) {
if (Objects.equals(
taskContext.getConfigurationMap().get(OPENSHIFT_DEPLOYMENTCONFIG_EXISTS),
Constants.BAMBOO_DC_EXISTS_OVERWRITE)) {
Utils.sendLog(
buildLogger,
true,
"spec:" + deploymentconfigJsonObject.getJSONObject(Constants.SPEC).toString());
HttpResponse<JsonNode> jsonResponsePatch =
Unirest.patch(
server
+ Constants.OAPI_V_1_NAMESPACES
+ taskContext.getConfigurationMap().get(OPENSHIFT_NAMESPACE)
+ "/deploymentconfigs/"
+ taskContext.getConfigurationMap().get(OPENSHIFT_DEPLOYMENTCONFIG_NAME))
.header(Constants.ACCEPT, Constants.APPLICATION_JSON)
.header(Constants.AUTHORIZATION, Constants.BEARER + token)
.header(Constants.CONTENT_TYPE, "application/merge-patch+json")
.body(
new JSONObject()
.put(
Constants.SPEC,
deploymentconfigJsonObject.getJSONObject(Constants.SPEC))
.toString())
.asJson();
Utils.sendLog(buildLogger, jsonResponsePatch);
result = true;
} else if (Objects.equals(
taskContext.getConfigurationMap().get(OPENSHIFT_DEPLOYMENTCONFIG_EXISTS),
Constants.BAMBOO_DC_EXISTS_IGNORE)) {
result = true;
}
} else {
buildLogger.addErrorLogEntry(
Constants.OPEN_SHIFT + " Error while creating the deployment config.");
buildLogger.addErrorLogEntry(Constants.OPEN_SHIFT + jsonResponse.getBody().toString());
}
} catch (UnirestException uniEx) {
buildLogger.addErrorLogEntry(
Constants.OPEN_SHIFT + " Error while creating the deployment config.");
buildLogger.addErrorLogEntry(Constants.OPEN_SHIFT + uniEx.getMessage());
}
return result;
}
}
| true |
3d2cdc569a9dcddda28f6920ecb91e199b6d54e2 | Java | luocong2013/luoc-imooc | /basic-part/src/main/java/com/imooc/pattern/observer/common/ConcreteObserver.java | UTF-8 | 618 | 3.328125 | 3 | [] | no_license | package com.imooc.pattern.observer.common;
/**
* @author luoc
* @version V0.0.1
* @package com.imooc.pattern.observer.common
* @description: 具体的观察者对象,实现更新的方法,使自身的状态和目标的状态保持一致
* @date 2017/11/10 20:40
*/
public class ConcreteObserver implements Observer {
/**
* 观察者的状态
*/
private String observerState;
/**
* 获取目标类的状态同步到观察者的状态中
*/
@Override
public void update(Subject subject) {
observerState = ((ConcreteSubject) subject).getSubjectState();
}
}
| true |
182757bb222f64967d79ed1f32b491316099899c | Java | magic-coder/DiyCode-3 | /app/src/main/java/com/xshengcn/diycode/util/customtabs/CustomTabFallback.java | UTF-8 | 188 | 1.578125 | 2 | [] | no_license | package com.xshengcn.diycode.util.customtabs;
import android.app.Activity;
import android.net.Uri;
public interface CustomTabFallback {
void openUri(Activity activity, Uri uri);
}
| true |
a2dc2d58522faf4772f3c662699b829ae9681efd | Java | gavin-ao/Card_Certification_Service | /src/main/java/data/driven/cm/entity/reward/RewardActCommandHelpMappingEntity.java | UTF-8 | 1,941 | 1.929688 | 2 | [] | no_license | package data.driven.cm.entity.reward;
import java.util.Date;
/**
* 活动助力奖励关联表Entity
* @author lxl
* @date 2018/11/7
*/
public class RewardActCommandHelpMappingEntity {
/**
* 活动助力奖励关联表 唯一id
*/
private String mapId;
/**
* 助力id
*/
private String helpId;
/**
* 奖励口令id
*/
private String commandId;
/**
*活动id
*/
private String actId;
/**
* 门店id
*/
private String storeId;
/**
* 小程序id
*/
private String appInfoId;
/**
* 微信用户id
*/
private String wechatUserId;
/**
* 创建时间
*/
private Date createAt;
public String getMapId() {
return mapId;
}
public void setMapId(String mapId) {
this.mapId = mapId;
}
public String getHelpId() {
return helpId;
}
public void setHelpId(String helpId) {
this.helpId = helpId;
}
public String getCommandId() {
return commandId;
}
public void setCommandId(String commandId) {
this.commandId = commandId;
}
public String getActId() {
return actId;
}
public void setActId(String actId) {
this.actId = actId;
}
public String getStoreId() {
return storeId;
}
public void setStoreId(String storeId) {
this.storeId = storeId;
}
public String getAppInfoId() {
return appInfoId;
}
public void setAppInfoId(String appInfoId) {
this.appInfoId = appInfoId;
}
public String getWechatUserId() {
return wechatUserId;
}
public void setWechatUserId(String wechatUserId) {
this.wechatUserId = wechatUserId;
}
public Date getCreateAt() {
return createAt;
}
public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
}
| true |
aa1f0ded35ed2ea78f5af030e3b3d13777e29a58 | Java | cavac96/apiChallenge | /src/test/java/steps/GetTrelloSteps.java | UTF-8 | 5,151 | 2.265625 | 2 | [] | no_license | package steps;
import controllers.GetTestController;
import controllers.PostTestController;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import net.thucydides.core.annotations.Steps;
import org.hamcrest.Matchers;
import org.junit.Assert;
import utils.Constants;
import java.util.logging.Level;
import java.util.logging.Logger;
public class GetTrelloSteps {
private Logger logger = Logger.getLogger("GetTrelloSteps.class");
@Steps
private GetTestController testControllerInstance = GetTestController.GetTestControllerInstance();
private RequestSpecification requestSpecification;
private Response response;
String userId;
String boardId;
String listId;
String listName;
@Given("^the user wants to get their boards$")
public void theUserWantsToGetTheirBoards() {
requestSpecification = testControllerInstance.authenticate();
}
@When("^the user sends the request to get the boards$")
public void theUserSendsTheRequestToGetTheBoards() {
userId = testControllerInstance.getUserId(requestSpecification);
response = testControllerInstance.getBoards(requestSpecification, userId);
}
@Then("^the Trello API should response with their list of boards$")
public void theTrelloAPIShouldResponseWithTheirListOfBoards() {
writeOnLog("boards > "+response.getBody().asString());
Assert.assertThat("Error: The status code is not <200>", response.getStatusCode(), Matchers.equalTo(200));
Assert.assertThat("Error: Could not get the boards.", response.getBody().asString(), Matchers.not(Matchers.equalTo("model not found")));
}
@Given("^the user wants to get the lists of a board$")
public void theUserWantsToGetTheListsOfABoard() {
requestSpecification = testControllerInstance.authenticate();
userId = testControllerInstance.getUserId(requestSpecification);
response = testControllerInstance.getBoards(requestSpecification, userId);
}
@When("^the user sends the request to get the lists of a board$")
public void theUserSendsTheRequestToGetTheListsOfABoard() {
boardId = testControllerInstance.getBoardId(requestSpecification, Constants.BOARD);
response = testControllerInstance.getListsOfBoard(requestSpecification, boardId);
}
@Then("^the Trello API should response with the lists of a board$")
public void theTrelloAPIShouldResponseWithTheListOfABoard() {
writeOnLog("lists > "+response.getBody().asString());
Assert.assertThat("Error: The status code is not <200>", response.getStatusCode(), Matchers.equalTo(200));
Assert.assertThat("Error: Could not get the lists.", response.getBody().asString(), Matchers.not(Matchers.equalTo("model not found")));
Assert.assertThat("Error: Could not get the lists.", response.getBody().asString(), Matchers.not(Matchers.equalTo("The requested resource was not found.")));
}
@Given("^the user wants to get their cards of the list \"([^\"]*)\"$")
public void theUserWantsToGetTheirCardsOfAList(String listName) {
this.listName = listName;
requestSpecification = testControllerInstance.authenticate();
userId = testControllerInstance.getUserId(requestSpecification);
response = testControllerInstance.getBoards(requestSpecification, userId);
boardId = testControllerInstance.getBoardId(requestSpecification, Constants.BOARD);
response = testControllerInstance.getListsOfBoard(requestSpecification, boardId);
listId = testControllerInstance.getListId(requestSpecification, listName);
//verify if the list exists. if not, create it
requestSpecification = PostTestController.PostTestControllerInstance().verifyListId(requestSpecification, listId, listName);
listId = GetTestController.GetTestControllerInstance().getListId(requestSpecification, listName);
}
@When("^the user sends the request to get the cards")
public void theUserSendsTheRequestToGetTheCardsOfTheList() {
response = testControllerInstance.getCards(requestSpecification, listId);
}
@Then("^the Trello API should response with the list of cards$")
public void theTrelloAPIShouldResponseWithTheListOfCards() {
writeOnLog("cards > "+response.getBody().asString());
Assert.assertThat("Error: The status code is not <200>", response.getStatusCode(), Matchers.equalTo(200));
Assert.assertThat("Error: Could not get the cards.", response.getBody().asString(), Matchers.not(Matchers.equalTo("invalid id")));
Assert.assertThat("Error: Could not get the cards.", response.getBody().asString(), Matchers.not(Matchers.equalTo("model not found")));
Assert.assertThat("Error: Could not get the cards.", response.getBody().asString(), Matchers.not(Matchers.equalTo("The requested resource was not found.")));
}
private void writeOnLog(String message){
logger.log(Level.INFO, "\n"+message);
}
}
| true |
e572e4ac5312f0d285649bc8fac30c4e74a70b11 | Java | anvesha209/GitHub-Assignment | /src/com/test/action/TestClass.java | UTF-8 | 1,679 | 1.984375 | 2 | [] | no_license | package com.test.action;
import org.testng.annotations.Test;
import com.test.PageObject.HomePageObject;
import com.test.PageObject.NewRepoObject;
import com.test.PageObject.ShellScript;
import com.test.git.TestInitiator;
import org.testng.annotations.BeforeClass;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterClass;
public class TestClass{
WebDriver driver;
TestInitiator test;
HomePageObject homePage;
NewRepoObject newRepoPage;
/*
@FindBy (css="a[class='btn site-header-actions-btn mr-2']")
WebElement signInButton;
*/
@BeforeClass
public void beforeClass() {
driver = new FirefoxDriver();
homePage=new HomePageObject(driver);
newRepoPage = new NewRepoObject(driver);
//test = new TestInitiator(driver);
PageFactory.initElements(driver, this);
driver.get("https://github.com/");
}
@Test
public void Step01_Click_Sign_In(){
homePage.GoToSignInPage();
}
@Test
public void Step02_Enter_Credentials(){
homePage.sendCredentials();
homePage.ClickLoginButton();
}
@Test
public void Step03_Create_Repository(){
newRepoPage.createNewRepository();
newRepoPage.enterNewRepoName();
}
@Test
public void Step04_Run_Shell_Script() throws IOException, InterruptedException{
ShellScript script = new ShellScript(driver);
script.createShellFile();
script.execute();
}
@AfterClass
public void afterClass() {
}
}
| true |
2e9e19315bdaac11fb0bf18107dca0e1131d7567 | Java | AmirMusairov/TravelAgency | /src/main/java/agency/dao/HotelDao.java | UTF-8 | 464 | 2.109375 | 2 | [] | no_license | package agency.dao;
import java.util.List;
import agency.models.HotelData;
public interface HotelDao {
HotelData getHotelById(int hotelId);
List<HotelData> getAllHotels();
List<HotelData> getHotelsByCity(String cityName);
boolean deleteHotelData(int hotelId);
boolean createHotelData(String name, String address, int price, String city);
boolean updateHotelData(int hotelId, String name, String address, int price, String city);
} | true |
f188b901289295e0768d5e2111512fe40af52e71 | Java | zenith391/PowerHigh | /powerhigh-core/src/org/powerhigh/graphics/renderers/lightning/Lightning.java | UTF-8 | 1,591 | 2.625 | 3 | [
"MIT"
] | permissive | package org.powerhigh.graphics.renderers.lightning;
import org.powerhigh.graphics.Drawer;
import org.powerhigh.graphics.Interface;
import org.powerhigh.graphics.renderers.IRenderer;
import org.powerhigh.objects.GameObject;
import org.powerhigh.utils.Area;
public final class Lightning implements IRenderer {
private boolean pp = false;
private void render(Interface win, Drawer g, Area rect) {
g.setColor(win.getBackground());
g.fillRect(0, 0, rect.getWidth(), rect.getHeight());
g.localRotate(Math.toRadians(win.getCamera().getRotation()), win.getWidth() / 2, win.getHeight() / 2);
g.translate(win.getCamera().getXOffset(), win.getCamera().getYOffset());
for (GameObject obj : win.getObjects()) {
if (obj.isVisible() && shouldRender(rect, obj)) {
g.saveState();
g.localRotate(Math.toRadians(obj.getRotation()), obj.getX() + (obj.getWidth() / 2),
obj.getY() + (obj.getHeight() / 2));
obj.paint(g, win);
g.restoreState();
}
}
}
@Override
public void render(Interface win, Drawer g) {
render(win, g, win.getViewport());
}
@Override
public boolean shouldRender(Interface w, GameObject obj) {
Area area = w.getViewport();
return shouldRender(area, obj);
}
private boolean shouldRender(Area rect, GameObject obj) {
return obj.isVisible() && obj.getX() + obj.getWidth() >= 0 && obj.getY() + obj.getHeight() >= 0
&& obj.getX() <= rect.getWidth() && obj.getY() <= rect.getHeight();
}
public void setUsePostProcessing(boolean enable) {
pp = enable;
}
@Override
public boolean isUsingPostProcessing() {
return pp;
}
}
| true |
c90ff963fcb263e068fa3eb6255ea68777f8c487 | Java | takanimo/PizzaDeliveryHP | /src/taka/PlacedOrder.java | UTF-8 | 1,740 | 2.375 | 2 | [] | no_license | package taka;
import java.util.Date;
public class PlacedOrder {
private int order_id;
private int c_id;
private String c_fname;
private String c_lname;
private int p_id;
private String p_name;
private int p_price;
private String order_date;
public PlacedOrder(){
order_id=0;
c_id=0;
c_fname=null;
c_lname=null;
p_id=0;
p_name=null;
p_price=0;
order_date=null;
}
public PlacedOrder(int order_id, int c_id, String c_fname,String c_lname,int p_id, String p_name, int p_price, String order_date){
this.order_id=order_id;
this.c_id=c_id;
this.c_fname=c_fname;
this.c_lname=c_lname;
this.p_id=p_id;
this.p_name=p_name;
this.p_price=p_price;
this.order_date=order_date;
}
public int getOrder_id() {
return order_id;
}
public void setOrder_id(int order_id) {
this.order_id = order_id;
}
public int getC_id() {
return c_id;
}
public void setC_id(int c_id) {
this.c_id = c_id;
}
public String getC_fname() {
return c_fname;
}
public void setC_fname(String c_fname) {
this.c_fname = c_fname;
}
public String getC_lname() {
return c_lname;
}
public void setC_lname(String c_lname) {
this.c_lname = c_lname;
}
public int getP_id() {
return p_id;
}
public void setP_id(int p_id) {
this.p_id = p_id;
}
public String getP_name() {
return p_name;
}
public void setP_name(String p_name) {
this.p_name = p_name;
}
public int getP_price() {
return p_price;
}
public void setP_price(int p_price) {
this.p_price = p_price;
}
public String getOrder_date() {
return order_date;
}
public void setOrder_date(String order_date) {
this.order_date = order_date;
}
}
| true |
fb57bc1decfe18ab8c9f22b3bd86329ad87b091d | Java | TINF15B4/VerteilteSysteme | /commons/src/main/java/de/tinf15b4/quizduell/db/Points.java | UTF-8 | 878 | 3.078125 | 3 | [] | no_license | package de.tinf15b4.quizduell.db;
public class Points {
private int myPoints;
private int otherPoints;
public Points() { /* JSON ONLY */ }
public Points(int myPoints, int otherPoints) {
this.myPoints = myPoints;
this.otherPoints = otherPoints;
}
public int getMyPoints() {
return myPoints;
}
public int getOtherPoints() {
return otherPoints;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + myPoints;
result = prime * result + otherPoints;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Points other = (Points) obj;
if (myPoints != other.myPoints)
return false;
if (otherPoints != other.otherPoints)
return false;
return true;
}
}
| true |
a1956799d8054ef4105704b10004c8f6c523ead6 | Java | WANGZijian1994/Java | /Test/src/StringMethods/StringBuilderDemo.java | UTF-8 | 429 | 3.453125 | 3 | [] | no_license | package StringMethods;
public class StringBuilderDemo {
public static void main(String[] args) {
String s = "This is just a jok";
StringBuilder sb = new StringBuilder(s);
sb.append("e.");
System.out.println(sb.toString());
int i = sb.indexOf("is j");
sb.insert(i+2, " never ");
System.out.println(sb.toString());
sb.delete(sb.indexOf(" just"), sb.indexOf(" just")+5);
System.out.println(sb.toString());
}
}
| true |
b433b3d25f4cea11cb4878bb5167d406b8766beb | Java | EastSunrise/oj-java | /src/main/java/cn/wsg/oj/leetcode/problems/p1600/Solution1616.java | UTF-8 | 473 | 2.296875 | 2 | [] | no_license | package cn.wsg.oj.leetcode.problems.p1600;
import cn.wsg.oj.leetcode.problems.base.Solution;
/**
* 1616. Split Two Strings to Make Palindrome (MEDIUM)
*
* @author Kingen
* @see <a href="https://leetcode-cn.com/problems/split-two-strings-to-make-palindrome/">Split Two
* Strings to Make Palindrome</a>
*/
public class Solution1616 implements Solution {
public boolean checkPalindromeFormation(String a, String b) {
// todo
return false;
}
}
| true |
cfe4e20b498df63215ef42b12de423d76dc2f833 | Java | NabeelGef/MultiNumbers | /src/main/java/com/example/multinumbers/Randomly.java | UTF-8 | 272 | 2.9375 | 3 | [] | no_license | package com.example.multinumbers;
import java.util.Random;
public class Randomly {
int x;
Randomly(){this.x=0;}
void set(int X)
{
this.x=X;
}
int getRand()
{
Random random=new Random();
return random.nextInt(x);
}
}
| true |
2a2798d1e82b9861f6cee8ee6bcdc284c413a5b5 | Java | oneliang/third-party-lib | /jdom/org/jdom/input/JAXPParserFactory.java | UTF-8 | 7,097 | 1.828125 | 2 | [
"Apache-2.0"
] | permissive | /*--
$Id: JAXPParserFactory.java,v 1.1 2012/03/26 04:33:57 lv Exp $
Copyright (C) 2000-2007 Jason Hunter & Brett McLaughlin.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions, and the disclaimer that follows
these conditions in the documentation and/or other materials
provided with the distribution.
3. The name "JDOM" must not be used to endorse or promote products
derived from this software without prior written permission. For
written permission, please contact <request_AT_jdom_DOT_org>.
4. Products derived from this software may not be called "JDOM", nor
may "JDOM" appear in their name, without prior written permission
from the JDOM Project Management <request_AT_jdom_DOT_org>.
In addition, we request (but do not require) that you include in the
end-user documentation provided with the redistribution and/or in the
software itself an acknowledgement equivalent to the following:
"This product includes software developed by the
JDOM Project (http://www.jdom.org/)."
Alternatively, the acknowledgment may be graphical using the logos
available at http://www.jdom.org/images/logos.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JDOM AUTHORS OR THE PROJECT
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.
This software consists of voluntary contributions made by many
individuals on behalf of the JDOM Project and was originally
created by Jason Hunter <jhunter_AT_jdom_DOT_org> and
Brett McLaughlin <brett_AT_jdom_DOT_org>. For more information
on the JDOM Project, please see <http://www.jdom.org/>.
*/
package org.jdom.input;
import java.util.*;
import javax.xml.parsers.*;
import org.jdom.*;
import org.xml.sax.*;
/**
* A non-public utility class to allocate JAXP SAX parsers.
*
* @version $Revision: 1.1 $, $Date: 2012/03/26 04:33:57 $
* @author Laurent Bihanic
*/
class JAXPParserFactory { // package protected
private static final String CVS_ID =
"@(#) $RCSfile: JAXPParserFactory.java,v $ $Revision: 1.1 $ $Date: 2012/03/26 04:33:57 $ $Name: $";
/** JAXP 1.2 schema language property id. */
private static final String JAXP_SCHEMA_LANGUAGE_PROPERTY =
"http://java.sun.com/xml/jaxp/properties/schemaLanguage";
/** JAXP 1.2 schema location property id. */
private static final String JAXP_SCHEMA_LOCATION_PROPERTY =
"http://java.sun.com/xml/jaxp/properties/schemaSource";
/**
* Private constructor to forbid allocating instances of this utility
* class.
*/
private JAXPParserFactory() {
// Never called.
}
/* Implementor's note regarding createParser() design: The features and
properties are normally set in SAXBuilder, but we take them in
createParser() as well because some features or properties may need to be
applied during the JAXP parser construction. Today, for example, properties
is used as it's the only way to configure schema validation: JAXP defines
schema validation properties but SAX does not. This reflects in the Apache
Xerces implementation where the SAXParser implementation supports the JAXP
properties but the XMLReader does not. Hence, configuring schema validation
must be done on the SAXParser object which is only visible in
JAXParserFactory. Features is also passed in case some future JAXP release
defines JAXP-specific features.
*/
/**
* Creates a SAX parser allocated through the configured JAXP SAX
* parser factory.
*
* @param validating whether a validating parser is requested.
* @param features the user-defined SAX features.
* @param properties the user-defined SAX properties.
*
* @return a configured XMLReader.
*
* @throws JDOMException if any error occurred when allocating or
* configuring the JAXP SAX parser.
*/
public static XMLReader createParser(boolean validating,
Map features, Map properties) throws JDOMException {
try {
SAXParser parser = null;
// Allocate and configure JAXP SAX parser factory.
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(validating);
factory.setNamespaceAware(true);
try {
// Allocate parser.
parser = factory.newSAXParser();
}
catch (ParserConfigurationException e) {
throw new JDOMException("Could not allocate JAXP SAX Parser", e);
}
// Set user-defined JAXP properties (if any)
setProperty(parser, properties, JAXP_SCHEMA_LANGUAGE_PROPERTY);
setProperty(parser, properties, JAXP_SCHEMA_LOCATION_PROPERTY);
// Return configured SAX XMLReader.
return parser.getXMLReader();
}
catch (SAXException e) {
throw new JDOMException("Could not allocate JAXP SAX Parser", e);
}
}
/**
* Sets a property on a JAXP SAX parser object if and only if it
* is declared in the user-defined properties.
*
* @param parser the JAXP SAX parser to configure.
* @param properties the user-defined SAX properties.
* @param name the name of the property to set.
*
* @throws JDOMException if any error occurred while configuring
* the property.
*/
private static void setProperty(SAXParser parser,
Map properties, String name) throws JDOMException {
try {
if (properties.containsKey(name)) {
parser.setProperty(name, properties.get(name));
}
}
catch (SAXNotSupportedException e) {
throw new JDOMException(
name + " property not supported for JAXP parser " +
parser.getClass().getName());
}
catch (SAXNotRecognizedException e) {
throw new JDOMException(
name + " property not recognized for JAXP parser " +
parser.getClass().getName());
}
}
}
| true |
fa9b1eec928b8d92b0ac285a877eccdb8c37dc1c | Java | xuexuexuexiao/devtools | /src/main/java/work/devtools/modules/DEV/mappers/Dev_queryMapper.java | UTF-8 | 535 | 1.835938 | 2 | [] | no_license | package work.devtools.modules.DEV.mappers;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import work.devtools.modules.DEV.pojo.dto.Dev_query;
import work.devtools.modules.DEV.pojo.po.T_query;
/**
* @author Huxiaoxue
* @version V1.0
* @ClassName
* @desc:
* @create: 2019-04-17
**/
@Mapper
public interface Dev_queryMapper {
Dev_queryMapper INSTANCE = Mappers.getMapper(Dev_queryMapper.class );
Dev_query t_queryToDev_query(T_query t_query);
T_query dev_queryToT_query(Dev_query dev_query);
}
| true |
653fa27b1c581c2e7f19ba371070c77080fbbc6d | Java | dkvz/DoradeBlogEngineSpring | /src/main/java/eu/dkvz/BlogAuthoring/model/ArticleStat.java | UTF-8 | 1,247 | 2.015625 | 2 | [] | no_license | package eu.dkvz.BlogAuthoring.model;
import java.util.*;
public class ArticleStat {
private long id = -1;
private long articleId;
private String pseudoUa;
private String pseudoIp;
private String clientUa;
private String clientIp;
private GeoInfo geoInfo;
private Date date;
public long getArticleId() {
return articleId;
}
public void setArticleId(long articleId) {
this.articleId = articleId;
}
public String getPseudoUa() {
return pseudoUa;
}
public void setPseudoUa(String pseudoUa) {
this.pseudoUa = pseudoUa;
}
public String getPseudoIp() {
return pseudoIp;
}
public void setPseudoIp(String pseudoIp) {
this.pseudoIp = pseudoIp;
}
public String getClientUa() {
return clientUa;
}
public void setClientUa(String clientUa) {
this.clientUa = clientUa;
}
public String getClientIp() {
return clientIp;
}
public void setClientIp(String clientIp) {
this.clientIp = clientIp;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public GeoInfo getGeoInfo() {
return geoInfo;
}
public void setGeoInfo(GeoInfo geoInfo) {
this.geoInfo = geoInfo;
}
}
| true |
1f5b80569e0007def12ad933e168a21bdd8a6dc3 | Java | dudoslav/Adventure | /src/main/java/sk/dudoslav/adventure/engine/graphics/TextureManager.java | UTF-8 | 1,237 | 2.640625 | 3 | [] | no_license | package sk.dudoslav.adventure.engine.graphics;
import java.nio.ByteBuffer;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL13.*;
import static org.lwjgl.opengl.GL30.glGenerateMipmap;
/**
* Created by dusan on 14.08.2015.
*/
public class TextureManager {
private int textures[];
public TextureManager(int num){
textures = new int[num];
for(int i = 0; i < num; i++){
textures[i] = glGenTextures();
}
}
public void activateTexture(int num){
glActiveTexture(GL_TEXTURE0+num);
}
public void bindTexture(int num){
glBindTexture(GL_TEXTURE_2D, textures[num]);
}
public void loadTexture(Image image){
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL_RGBA,
GL_UNSIGNED_BYTE, image.getPixels());
glGenerateMipmap(GL_TEXTURE_2D);
}
}
| true |
496204fb5e558cc4e97f7f27925fc72e65a37421 | Java | kamilmucik/tradesystem | /project/backend/src/main/java/com/gft/model/User.java | UTF-8 | 4,081 | 2.28125 | 2 | [] | no_license | package com.gft.model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.*;
/**
* Created by kamu on 8/16/2016.
*/
@Entity
@Table(name="TBL_USER")
public class User implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column( name = "ID" )
private Long id;
@Column(name = "FIRST_NAME", nullable = false)
private String firstName;
@Column(name = "LAST_NAME", nullable = false)
private String lastName;
@Column(name = "EMAIL", nullable = false)
private String email;
@Column(name = "LAST_LOGIN", nullable = false)
private Date lastLogin;
@Column(name = "PASSWORD", nullable = false)
private String password;
@Column(name = "CREATED", nullable = false)
private Date created;
@Column(name = "AMOUNT", nullable = false)
private BigDecimal amount;
@ManyToMany( fetch = FetchType.LAZY, cascade = CascadeType.ALL )
@JoinTable(
name = "TBL_USER_AUTHORITY",
joinColumns = {@JoinColumn(name = "USER_ID")},
inverseJoinColumns = {@JoinColumn(name = "AUTHORITY_ID")}
)
private List<Authority> authorities;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "contractor1")
private List<UserAsset> contractor1Assets = new ArrayList<>(0);
@OneToMany(fetch = FetchType.LAZY, mappedBy = "contractor2")
private List<UserAsset> contractor2Assets = new ArrayList<>(0);
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Date getLastLogin() {return lastLogin;}
public void setLastLogin(Date lastLogin) {this.lastLogin = lastLogin;}
public List<Authority> getAuthorities() {return authorities;}
public void setAuthorities(List<Authority> authorities) {this.authorities = authorities;}
public List<UserAsset> getContractor1Assets() {return contractor1Assets;}
public void setContractor1Assets(List<UserAsset> contractor1Assets) {this.contractor1Assets = contractor1Assets;}
public List<UserAsset> getContractor2Assets() {return contractor2Assets;}
public void setContractor2Assets(List<UserAsset> contractor2Assets) {this.contractor2Assets = contractor2Assets;}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id.intValue();
result = prime * result + ((id.equals(null)) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof User))
return false;
User other = (User) obj;
if (id != other.id)
return false;
if (id == null) {
if (!other.id.equals(null))
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return "User [id=" + id + ", firsName=" + firstName + "]";
}
}
| true |
9b53d1438393f475b5f9ec5ffd99097c3af8aaef | Java | ersatzhero/mapstruct-polymorphism | /src/main/java/dto/InteriorDto.java | UTF-8 | 236 | 1.929688 | 2 | [] | no_license | package dto;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import lombok.experimental.SuperBuilder;
@SuperBuilder
@Getter
@EqualsAndHashCode
@ToString
public abstract class InteriorDto {
int seats;
}
| true |
31f48a0efcf15b067d9872fb926b63edef809bc9 | Java | slank0110/Waitins | /waitins/RestaurantActivity.java | UTF-8 | 35,155 | 1.640625 | 2 | [] | no_license | package logicreat.waitins;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationManager;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.RequestFuture;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class RestaurantActivity extends AppCompatActivity {
private MyApp myInstance = MyApp.getOurInstance();
private final String INFO_SEPARATOR = "\\|";
private final String LOAD_BACKGROUND_OPERATION = "3";
private final String LOAD_FULL_OPERATION = "4";
private final String LOAD_STATUS_OPERATION = "5";
private final String ADD_FAVOURITE_OPERATION = "1";
private final String DEL_FAVOURITE_OPERATION = "2";
// status view
private TextView tvSmallStatus;
private TextView tvMediumStatus;
private TextView tvLargeStatus;
// info view
private TextView tvResAddress;
private TextView tvResAddress2;
private TextView tvResPhoneNumber;
private TextView tvHourOperation;
private TextView tvSmallSize;
private TextView tvMediumSize;
private TextView tvLargeSize;
private TextView tvEstimatedSmall;
private TextView tvEstimatedMedium;
private TextView tvEstimatedLarge;
private ImageView ivFavourite;
private ImageView ivBackGround;
private ImageView ivGps;
private Button button;
private Dialog d;
// show view
private TextView tvTableSize;
private TextView tvWaitingParty;
private TextView tvEstimatedTime;
private TextView tvOptionList;
private TextView tvAddress;
// promotion
private ListView promotionList;
private Activity activity = this;
private Restaurant curRes;
private String comId;
private String resName;
private boolean favourite;
private int small;
private int medium;
private int large;
private boolean guest;
private Location location;
private String phoneNumber = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_restaurant_card);
// status info
tvSmallStatus = (TextView) findViewById(R.id.restaurant_card_waiting_parties_small);
tvMediumStatus = (TextView) findViewById(R.id.restaurant_card_waiting_parties_medium);
tvLargeStatus = (TextView) findViewById(R.id.restaurant_card_waiting_parties_large);
tvEstimatedSmall = (TextView) findViewById(R.id.restaurant_card_estimated_wait_time_small);
tvEstimatedMedium = (TextView) findViewById(R.id.restaurant_card_estimated_wait_time_medium);
tvEstimatedLarge = (TextView) findViewById(R.id.restaurant_card_estimated_wait_time_large);
// info view
tvResAddress = (TextView) findViewById(R.id.new_res_card_address);
tvResAddress2 = (TextView) findViewById(R.id.new_res_card_gps_distance);
tvHourOperation = (TextView) findViewById(R.id.new_res_card_open_hours);
tvSmallSize = (TextView) findViewById(R.id.restaurant_card_table_size_small);
tvMediumSize = (TextView) findViewById(R.id.restaurant_card_table_size_medium);
tvLargeSize = (TextView) findViewById(R.id.restaurant_card_table_size_large);
ivFavourite = (ImageView) findViewById(R.id.new_res_card_favourite);
ivBackGround = (ImageView) findViewById(R.id.new_res_card_res_image);
ivGps = (ImageView) findViewById(R.id.new_res_card_gps);
promotionList = (ListView) findViewById(R.id.new_res_card_listview);
// show view
tvTableSize = (TextView) findViewById(R.id.restaurant_card_table_size);
tvWaitingParty = (TextView) findViewById(R.id.restaurant_card_waiting_parties);
tvEstimatedTime = (TextView) findViewById(R.id.restaurant_card_estimated_wait_time);
//tvOptionList = (TextView) findViewById(R.id.restaurantCardOptionList);
//tvAddress = (TextView) findViewById(R.id.restaurantCardAddress);
guest = myInstance.isGuest();
ivFavourite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onFavouriteClick();
}
});
// ticket related
button = (Button) findViewById(R.id.new_res_card_get_in_line_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getInLineOnClick();
}
});
ivGps.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Thread loadLatLongThread = new Thread(new Runnable() {
@Override
public void run() {
double[] temp = myInstance.getResLatLng(curRes.getComId());
final Intent intent = new Intent(MyApp.getCurActivity(), MapsActivity.class);
intent.putExtra("Lat", temp[0]);
intent.putExtra("Lon", temp[1]);
intent.putExtra("comId", curRes.getComId());
MyApp.getCurActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
MyApp.getCurActivity().startActivity(intent);
}
});
}
});
loadLatLongThread.start();
}
});
button.setText(R.string.restaurant_card_button);
if (!MyApp.getTicketNum().equals("0")){
button.setClickable(false);
button.setBackgroundResource(R.color.colorLightGrey);
}
d = new Dialog(RestaurantActivity.this);
// back navigation
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
// used to know which restaurant is selected
Intent intent = getIntent();
comId = (String) intent.getSerializableExtra("comId");
myInstance.setCurRes(comId);
resName = myInstance.
getAllResManager().getRestaurant(comId).getName();
setTitle(resName);
MyApp.setCurActivity(activity);
curRes = myInstance.getCurRes();
setDistance();
//myInstance.showLoading();
// operation hour
tvHourOperation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setNegativeButton(getString(R.string.ok), null)
.setMessage(curRes.getHourOperation())
.setTitle(R.string.restaurant_card_hour_of_operation)
.create()
.show();
}
});
if (!curRes.isFullInfoSet()) {
Thread loadFullThread = new Thread(new Runnable() {
@Override
public void run() {
final Map<String, String> params = new HashMap<>();
params.put("operation", LOAD_BACKGROUND_OPERATION);
params.put("comId", comId);
final Bitmap imageResponse = myInstance.sendSynchronousImageRequest(MyApp.LOADRES_URL, params);
params.put("operation", LOAD_FULL_OPERATION);
params.put("comId", comId);
String response = myInstance.sendSynchronousStringRequest(MyApp.LOADRES_URL, params);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
ivBackGround.setImageBitmap(imageResponse);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(MyApp.width, (int)(MyApp.RESTAURANTPICTURERATIO * MyApp.width));
ivBackGround.setLayoutParams(params);
curRes.setBackGroundImage(imageResponse);
}
});
if (!response.equals("@") && !response.equals(MyApp.NETWORK_ERROR)) {
final String[] info = response.split(INFO_SEPARATOR);
curRes.setFullResInfo(info);
final String address = info[0] + " " + info[3];
phoneNumber = info[2];
String[] hours = curRes.getTodayHour();
final String hourOperation = getString(R.string.restaurant_card_open_today_from_text) + hours[0] + " - " + hours[1];
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
tvResAddress.setText(address);
tvHourOperation.setText(hourOperation);
}
});
final String small = getString(R.string.restaurant_card_table_size_small) + (Integer.parseInt(info[4]) - 1) + ")";
final String medium = getString(R.string.restaurant_card_table_size_medium) + info[4] + " - " + (Integer.parseInt(info[5]) - 1) + ")";
final String large = getString(R.string.restaurant_card_table_size_large) + (Integer.parseInt(info[5]) - 1) + "+)";
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
tvSmallSize.setText(small);
tvMediumSize.setText(medium);
tvLargeSize.setText(large);
}
});
setStatus();
if (!guest) {
setFavourite();
}
}else{
MyApp.getCurActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, "Failed to load restaurant info",
Toast.LENGTH_LONG).show();
}
});
}
}
});
loadFullThread.setPriority(Thread.MAX_PRIORITY);
loadFullThread.start();
}else{
ivBackGround.setImageBitmap(curRes.getBackGroundImage());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(MyApp.width, (int)(MyApp.RESTAURANTPICTURERATIO * MyApp.width));
ivBackGround.setLayoutParams(params);
tvResAddress.setText(curRes.getAddress() + " " + curRes.getPostalCode());
phoneNumber = curRes.getPhoneNumber();
String hourOperation = getString(R.string.restaurant_card_open_today_from_text);
String[] hours = curRes.getTodayHour();
hourOperation += hours[0] + " - " + hours[1];
tvHourOperation.setText(hourOperation);
String small = getString(R.string.restaurant_card_table_size_small) + "1 - " + (Integer.parseInt(curRes.getTableSize1()) - 1) + ")";
String medium = getString(R.string.restaurant_card_table_size_medium) + curRes.getTableSize1() + " - " + (Integer.parseInt(curRes.getTableSize2()) - 1) + ")";
String large = getString(R.string.restaurant_card_table_size_large) + (Integer.parseInt(curRes.getTableSize2()) - 1) + "+)";
tvSmallSize.setText(small);
tvMediumSize.setText(medium);
tvLargeSize.setText(large);
Thread loadStatus = new Thread(new Runnable() {
@Override
public void run() {
setStatus();
}
});
loadStatus.start();
if (!guest) {
setFavourite();
}
}
}
// setting the status of this restaurant
public void setStatus(){
final Map<String, String> params = new HashMap<>();
params.put("operation", LOAD_STATUS_OPERATION);
params.put("comId", comId);
String response = myInstance.sendSynchronousStringRequest(MyApp.LOADRES_URL, params);
if (!response.equals("@") && !response.equals(MyApp.NETWORK_ERROR)) {
final String[] status = response.split(INFO_SEPARATOR);
if (status[3].equals("0")){
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
button.setClickable(false);
button.setBackgroundResource(R.color.colorLightGrey);
button.setText(R.string.restaurant_card_button_unavailable);
}
});
}
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
tvSmallStatus.setText(status[0]);
tvMediumStatus.setText(status[1]);
tvLargeStatus.setText(status[2]);
setEstimatedTime(status);
}
});
}else{
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, "Failed to load status",
Toast.LENGTH_LONG).show();
}
});
}
}
// setting the favourite symbol
public void setFavourite(){
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (myInstance.getFavouriteList().contains(comId)){
ivFavourite.setImageResource(R.drawable.like_filled_24);
favourite = true;
}else{
ivFavourite.setImageResource(R.drawable.like_24);
favourite = false;
}
}
});
}
// this is what happens when favourite is clicked
public void onFavouriteClick(){
// change the restaurant manager in MyApp accordingly
if (!guest) {
Thread favouriteThread = new Thread(new Runnable() {
@Override
public void run() {
String response;
if (!favourite) {
Map<String, String> params = new HashMap<>();
params.put("operation", ADD_FAVOURITE_OPERATION);
params.put("comId", comId);
response = myInstance.sendSynchronousStringRequest(MyApp.LOAD_FAVOURITE_URL, params);
if (response.equals(MyApp.NETWORK_ERROR)){
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, "Network problem, please try again later", Toast.LENGTH_LONG).show();
}
});
return;
}
if (response.equals("$")){
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, "Success", Toast.LENGTH_LONG).show();
setFavourite();
}
});
myInstance.getFavouriteList().add(0, comId);
myInstance.getFavouriteResList().add(0, curRes);
myInstance.getAllResManager().addPriority(comId);
}else{
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, "Fail", Toast.LENGTH_LONG).show();
}
});
}
} else {
Map<String, String> params = new HashMap<>();
params.put("operation", DEL_FAVOURITE_OPERATION);
params.put("comId", comId);
response = myInstance.sendSynchronousStringRequest(MyApp.LOAD_FAVOURITE_URL, params);
if (response.equals(MyApp.NETWORK_ERROR)){
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, "Network problem, please try again later", Toast.LENGTH_LONG).show();;
}
});
return;
}
if (response.equals("$")){
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, "Success", Toast.LENGTH_LONG).show();
setFavourite();
}
});
myInstance.getFavouriteList().remove(comId);
myInstance.getFavouriteResList().remove(curRes);
myInstance.getAllResManager().removePriority(comId);
}else{
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, "Fail", Toast.LENGTH_LONG).show();
}
});
}
}
if (response.equals("%&!#")){
if (myInstance.reLogin()){
onFavouriteClick();
}else{
myInstance.disconnect();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(activity, LoginActivity.class);
intent.putExtra("New", false);
activity.startActivity(intent);
Toast.makeText(activity, "Your session has expire, please reLogin", Toast.LENGTH_LONG).show();
}
});
}
}
}
});
favouriteThread.start();
}else{
myInstance.returnToLogin();
}
}
public void getInLineOnClick(){
if (!guest) {
d.setContentView(R.layout.rescard_dialog);
final Button b = (Button) d.findViewById(R.id.dialog_button);
TextView tv = (TextView) d.findViewById(R.id.dialog_title);
final NumberPicker np = (NumberPicker) d.findViewById(R.id.numberPicker);
np.setMaxValue(30);
np.setMinValue(1);
String title = "Number of people";
tv.setText(title);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread submitThread = new Thread(new Runnable() {
@Override
public void run() {
b.setClickable(false);
submit(np.getValue());
b.setClickable(true);
}
});
submitThread.start();
}
});
d.show();
}else{
myInstance.returnToLogin();
}
}
public void setEstimatedTime(String[] status){
small = Integer.parseInt(status[0]);
medium = Integer.parseInt(status[1]);
large = Integer.parseInt(status[2]);
Thread setEstimatedThread = new Thread(new Runnable() {
@Override
public void run() {
if (curRes.isEstimatedTimeUpdated()) {
// getting estimated time for small
Map<String, String> params = new HashMap<>();
params.put("numberPeople", "" + (Integer.parseInt(curRes.getTableSize1()) - 1));
params.put("comId", comId);
String response = myInstance.sendSynchronousStringRequest(MyApp.LOAD_ESTIMATED_URL, params);
if (response.equals("$") && !response.equals(MyApp.NETWORK_ERROR)) {
small = -1;
curRes.setSmall(small);
} else if (response.equals("@")) {
small = -1;
curRes.setSmall(small);
} else {
curRes.setSmall(Integer.parseInt(response));
small = Integer.parseInt(response) * small;
}
params = new HashMap<>();
params.put("numberPeople", "" + (Integer.parseInt(curRes.getTableSize1())));
params.put("comId", comId);
response = myInstance.sendSynchronousStringRequest(MyApp.LOAD_ESTIMATED_URL, params);
if (response.equals("$") && !response.equals(MyApp.NETWORK_ERROR)) {
medium = -1;
curRes.setMedium(medium);
} else if (response.equals("@")) {
medium = -1;
curRes.setMedium(medium);
} else {
curRes.setMedium(Integer.parseInt(response));
medium = Integer.parseInt(response) * medium;
}
params = new HashMap<>();
params.put("numberPeople", "" + (Integer.parseInt(curRes.getTableSize2())));
params.put("comId", comId);
response = myInstance.sendSynchronousStringRequest(MyApp.LOAD_ESTIMATED_URL, params);
if (response.equals("$") && !response.equals(MyApp.NETWORK_ERROR)) {
large = -1;
curRes.setLarge(large);
} else if (response.equals("@")) {
large = -1;
curRes.setLarge(large);
} else {
curRes.setLarge(Integer.parseInt(response));
large = Integer.parseInt(response) * large;
}
curRes.setLastEstimatedUpdate(System.currentTimeMillis());
}else{
if (curRes.getSmall() == -1){
small = -1;
}else {
small = curRes.getSmall() * small;
}
if (curRes.getMedium() == -1){
medium = -1;
}else {
medium = curRes.getMedium() * medium;
}
if (curRes.getLarge() == -1) {
large = -1;
}else {
large = curRes.getLarge() * large;
}
}
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (small <= -1) {
tvEstimatedSmall.setText("N/A");
}else {
tvEstimatedSmall.setText("" + small);
}
if (medium <= -1) {
tvEstimatedMedium.setText("N/A");
}else {
tvEstimatedMedium.setText("" + medium);
}
if (large <= -1){
tvEstimatedLarge.setText("N/A");
}else {
tvEstimatedLarge.setText("" + large);
}
setPromotionList();
}
});
}
});
setEstimatedThread.start();
}
public void setPromotionList(){
Thread setPromotionThread = new Thread(new Runnable() {
@Override
public void run() {
final ArrayList<Promotion> tempList = new ArrayList<>();
Map<String, String> params = new HashMap<>();
params.put("operation", "11");
params.put("comId", comId);
String response = myInstance.sendSynchronousStringRequest(MyApp.LOADRES_URL, params);
if (!response.equals("$") && !response.equals(MyApp.NETWORK_ERROR)){
String[] promotions = response.split("\\|");
for (int i = 0; i < promotions.length; i++){
String[] info = promotions[i].split("&");
if (myInstance.getPromotionManager().ifExist(info[0])){
tempList.add(myInstance.getPromotionManager().getPromotion(info[0]));
}else{
Promotion newPromotion = new Promotion(info[0], info[1], info[2],
Integer.parseInt(info[3]), Integer.parseInt(info[4]),
info[6], info[7], info[8]);
newPromotion.setNumberSold(Integer.parseInt(info[5]));
myInstance.getPromotionManager().addPromotion(newPromotion);
tempList.add(newPromotion);
}
}
}
final ResPromotionAdapter resPromotionAdapter = new ResPromotionAdapter(activity, tempList);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
promotionList.setAdapter(resPromotionAdapter);
setListViewHeightBasedOnChildren(promotionList);
setVisible();
promotionList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String promotionId = tempList.get(i).getPromotionId();
Intent intent = new Intent(MyApp.getCurActivity(), NewPlateActivity.class);
intent.putExtra("promotionId", promotionId);
MyApp.getCurActivity().startActivity(intent);
}
});
}
});
}
});
setPromotionThread.start();
}
public void setDistance(){
location = null;
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
try{
location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}catch(SecurityException e){
e.printStackTrace();
}
if (location == null){
tvResAddress2.setText(phoneNumber + " N/A");
}else {
Thread loadDistance = new Thread(new Runnable() {
@Override
public void run() {
Map<String, String> params = new HashMap<>();
params.put("operation", "8");
params.put("comId", comId);
params.put("longitude", "" + location.getLongitude());
params.put("latitude", "" + location.getLatitude());
final String message = myInstance.sendSynchronousStringRequest(MyApp.LOADRES_URL, params);
if (message.equals(MyApp.NETWORK_ERROR) || message.equals("$") || message.equals("@")){
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
tvResAddress2.setText(phoneNumber + " " + "-");
}
});
}
else if (message.equals("@")){
}else {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
tvResAddress2.setText(phoneNumber + " " + message);
}
});
}
}
});
loadDistance.start();
}
}
// submit on click
public void submit(int numPeople){
final int numPpl = numPeople;
myInstance.writeSocket(String.
format("User Submit %s %s",
curRes.getComId(), ""+numPpl));
//String message = myInstance.readSocket()[1];
String curType = myInstance.getCurType();
while(!curType.equals("UserSubmit") && !curType.equals(MyApp.SOCKET_NETWORK_ERROR)){
curType = myInstance.getCurType();
}
if (curType.equals(MyApp.SOCKET_NETWORK_ERROR)) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, "Network Error, Please try again later", Toast.LENGTH_LONG).show();
myInstance.resetCurType();
}
});
return;
}
myInstance.resetCurType();
String message = myInstance.getCurMessage();
if (message.equals("@")){
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, "Fail to submit Ticket", Toast.LENGTH_LONG).show();
}
});
}else{
String[] messageInfo = message.split("\\|");
String[] info = String.format("%s|%s|%s|%s|%s",
curRes.getComId(),
messageInfo[0], messageInfo[1],
System.currentTimeMillis(), numPpl).split("\\|");
myInstance.setTicketInfo(info);
d.dismiss();
Intent intent = new Intent(activity, MainActivity.class);
MainActivity.intent.putExtra("goTo", 2);
startActivity(intent);
}
}
public void setVisible(){
findViewById(R.id.restaurant_card_progress_bar).setVisibility(View.GONE);
findViewById(R.id.activity_temp_restaurant).setVisibility(View.VISIBLE);
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
finish();
return true;
}
@Override
protected void onResume(){
super.onResume();
MyApp.setCurActivity(activity);
}
/**** Method for Setting the Height of the ListView dynamically.
**** Hack to fix the issue of not showing all the items of the ListView
**** when placed inside a ScrollView ****/
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
// calculating the total height by adding the height of every view inside listview
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0)
// setting up for measure
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, ViewGroup.LayoutParams.WRAP_CONTENT));
view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
// change the height of list view
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}
| true |
620a0f123e7d2e92f5c4dab60c96fab632b3e98f | Java | Tranglezyx/test | /src/main/java/com/test/thread/consumer/ConsumerReentrantLockApp.java | UTF-8 | 3,047 | 3.78125 | 4 | [] | no_license | package com.test.thread.consumer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author trangle
* <p>
* 生产者消费者ReentrantLock实现
*/
public class ConsumerReentrantLockApp {
public static void main(String[] args) {
Number number = new Number();
new Thread(() -> {
for (int i = 0; i < 20; i++) {
try {
number.mod3();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 20; i++) {
try {
number.mod5();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 20; i++) {
try {
number.mod7();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "C").start();
}
public static class Number {
private Lock lock = new ReentrantLock();
private Condition condition3 = lock.newCondition();
private Condition condition5 = lock.newCondition();
private Condition condition7 = lock.newCondition();
private int number = 3;
public void mod3() throws InterruptedException {
try {
lock.lock();
while (number % 3 != 0) {
condition3.await();
}
System.out.println(Thread.currentThread().getName() + " --- " + number);
number += 2;
condition5.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void mod5() throws InterruptedException {
try {
lock.lock();
while (number % 5 != 0) {
condition5.await();
}
System.out.println(Thread.currentThread().getName() + " --- " + number);
number += 2;
condition7.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void mod7() throws InterruptedException {
try {
lock.lock();
while (number % 7 != 0) {
condition7.await();
}
System.out.println(Thread.currentThread().getName() + " --- " + number);
number = 3;
condition3.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
| true |
823d490570f6a0a419ee8dbc1d8d66da8d8e78a8 | Java | gee-whiz/PreampedBw | /app/src/main/java/za/co/empirestate/botspost/preamped/PaymentDetailsActivity.java | UTF-8 | 8,525 | 1.984375 | 2 | [] | no_license | package za.co.empirestate.botspost.preamped;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.Spinner;
import za.co.empirestate.botspost.model.Payment;
import za.co.empirestate.botspost.sqlite.MySQLiteFunctions;
public class PaymentDetailsActivity extends Activity
{
private static final String LOG = "Hey Gee" ;
int spnMonthPos;
int spnYearPos;
EditText txtInitial;
EditText txtCvv;
EditText txtNumber;
EditText txtSurname;
ImageButton back;
Time localTime;
private String amount;
private String cardType;
private String meterNumber;
private String month;
private MySQLiteFunctions mysqliteFunction;
private Payment payment;
private String year,groupId,voucherValue,ls_transactionFee,PaidUntil;
protected void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
setContentView(R.layout.activity_payment_details);
Intent localIntent = getIntent();
this.meterNumber = localIntent.getStringExtra("meter_number");
this.amount = localIntent.getStringExtra("amount");
this.groupId = localIntent.getStringExtra("groupId");
voucherValue = localIntent.getStringExtra("voucherValue");
ls_transactionFee = localIntent.getStringExtra("transactionFee");
PaidUntil = localIntent.getStringExtra("PaidUntil");
this.mysqliteFunction = new MySQLiteFunctions(this);
final Spinner spnMonths = (Spinner) findViewById(R.id.month);
final Spinner spnYears = (Spinner) findViewById(R.id.year);
Button btnNext = (Button) findViewById(R.id.btn_next);
txtInitial = (EditText) findViewById(R.id.initial);
txtCvv = (EditText) findViewById(R.id.cvv);
txtNumber = (EditText) findViewById(R.id.card_number);
txtSurname = (EditText) findViewById(R.id.surname);
final RadioButton rdoMasterCard = (RadioButton) findViewById(R.id.master_card);
localTime = new Time(Time.getCurrentTimezone());
localTime.setToNow();
back = (ImageButton)findViewById(R.id.bck_btn);
// Create an ArrayAdapter using the string array and a default spinner
// layout
ArrayAdapter<CharSequence> adapterMonths = ArrayAdapter
.createFromResource(this, R.array.months_array,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapterMonths
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spnMonths.setAdapter(adapterMonths);
// Create an ArrayAdapter using the string array and a default spinner
// layout
ArrayAdapter<CharSequence> adapterYears = ArrayAdapter
.createFromResource(this, R.array.years_array,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapterYears
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spnYears.setAdapter(adapterYears);
spnMonths.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> paramAnonymousAdapterView, View paramAnonymousView, int paramAnonymousInt, long paramAnonymousLong) {
PaymentDetailsActivity.this.month = spnMonths.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> paramAnonymousAdapterView) {
}
});
spnYears.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> paramAnonymousAdapterView, View paramAnonymousView, int paramAnonymousInt, long paramAnonymousLong) {
year = spnYears.getSelectedItem().toString();
year = year.substring(2);
}
public void onNothingSelected(AdapterView<?> paramAnonymousAdapterView) {
}
});
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(PaymentDetailsActivity.this, MainActivity.class);
startActivity(intent);
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView) {
String cardHolderInitial = txtInitial.getText().toString();
String cardHolderSurname = txtSurname.getText().toString();
String cardNumber;
String strExpMonth;
String strExpYear;
String strCvv;
int currentMonth = localTime.month;
int usrMonth = Integer.parseInt(month);
if (rdoMasterCard.isChecked()) {
PaymentDetailsActivity.this.cardType = "master card";
} else {
PaymentDetailsActivity.this.cardType = "visa";
}
cardNumber = txtNumber.getText().toString();
strExpMonth = PaymentDetailsActivity.this.month;
strExpYear = PaymentDetailsActivity.this.year;
strCvv = txtCvv.getText().toString();
if ((cardHolderInitial.isEmpty()) || (cardHolderInitial.isEmpty()) || cardNumber.isEmpty()) {
if (cardHolderInitial.isEmpty())
txtInitial.setError("please enter the card holder initial");
if (cardHolderSurname.isEmpty())
txtSurname.setError("please enter the card holder surname");
if (cardNumber.isEmpty())
txtNumber.setError("please enter the card holder surname");
return;
} else {
Log.d("currentMonth",""+currentMonth);
Log.d("usrMonth",""+usrMonth);
if (!(cardNumber.length() == 16) || !(strCvv.length() == 3)) {
if (strCvv.length() != 3)
txtCvv.setError("cvv must be 3 digits");
if (cardNumber.length() != 16)
txtNumber.setError("card number must be 16 digits");
return;
}
}
Intent localIntent = new Intent(PaymentDetailsActivity.this, ConfirmPurchaseActivity.class);
PaymentDetailsActivity.this.payment = new Payment(cardHolderInitial, cardHolderSurname, PaymentDetailsActivity.this.cardType, cardNumber, strExpMonth, strExpYear, PaymentDetailsActivity.this.meterNumber, PaymentDetailsActivity.this.amount, strCvv);
// PaymentDetailsActivity.this.mysqliteFunction.deletePayment();
PaymentDetailsActivity.this.mysqliteFunction.createPaymentTable(cardNumber, cardHolderInitial, cardHolderSurname, strCvv, PaymentDetailsActivity.this.month, PaymentDetailsActivity.this.year, cardNumber.substring(13));
localIntent.putExtra("payment_details", PaymentDetailsActivity.this.payment);
localIntent.putExtra("isNew", true);
localIntent.putExtra("voucherValue",voucherValue);
localIntent.putExtra("meter_number", PaymentDetailsActivity.this.meterNumber);
localIntent.putExtra("transactionFee", ls_transactionFee);
Log.d(LOG, "I'm sending this " + ls_transactionFee);
localIntent.putExtra("groupId", groupId);
localIntent.putExtra("PaidUntil",PaidUntil);
Log.d(LOG,"transaction fee"+ls_transactionFee);
//Intent encryptIntent = new Intent();
//encryptIntent.putExtra("card_number",cardNumber);
//encryptIntent.putExtra("card_cvv",strCvv);
//startService(encryptIntent);
PaymentDetailsActivity.this.startActivity(localIntent);
}
});
}
} | true |
51dfb5b555d39df3e22a05a2174f6a986c160de1 | Java | roroclaw/wyedu | /src/main/java/com/cloud9/biz/services/ScoSubjectScoresService.java | UTF-8 | 17,662 | 1.898438 | 2 | [
"CC0-1.0"
] | permissive | package com.cloud9.biz.services;
import com.cloud9.biz.dao.mybatis.ScoSubjectScoresMapper;
import com.cloud9.biz.dao.mybatis.SysImportLogMapper;
import com.cloud9.biz.dao.mybatis.TchClassInfoMapper;
import com.cloud9.biz.models.ScoSubjectScores;
import com.cloud9.biz.models.SysImportLog;
import com.cloud9.biz.models.TchClassInfo;
import com.cloud9.biz.models.vo.VFileObj;
import com.cloud9.biz.models.vo.VUserInfo;
import com.cloud9.biz.util.BizConstants;
import com.cloud9.biz.util.ImportKit;
import com.roroclaw.base.bean.MemoryCache;
import com.roroclaw.base.bean.PageBean;
import com.roroclaw.base.handler.BizException;
import com.roroclaw.base.service.BaseService;
import com.roroclaw.base.utils.POIExcelUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by roroclaw on 2017/8/16.
*/
@Service("subjectScoresService")
@Transactional
public class ScoSubjectScoresService extends BaseService {
private static Logger logger = LoggerFactory.getLogger(ScoSubjectScoresService.class);
@Autowired
private CommonService commonService;
@Autowired
private ScoSubjectScoresMapper scoSubjectScoresMapper;
@Autowired
private SysImportLogMapper sysImportLogMapper;
@Autowired
private TchClassInfoMapper classInfoMapper;
public PageBean getSubjectScoresPageData(PageBean pageBean) {
List resList = scoSubjectScoresMapper.selectSubjectScoresPageData(pageBean);
pageBean.setData(resList);
return pageBean;
}
/**
* 导入科目成绩信息
*
* @return
*/
public String importSubjectScores(String fileName,MultipartFile file,VUserInfo userInfo) throws BizException, IOException {
//保存文件到文件系统
VFileObj fileObj = this.commonService.writeFile(file,"subjectScoresFiles");
InputStream inputStream = file.getInputStream();
int batchCommitCount = Integer.valueOf(MemoryCache.getSysConfigKey("IMPORT_COMMIT_COUNT"));
String importInfo = "";
Sheet sheet = POIExcelUtil.getExcelSheet(fileName, inputStream);
if (sheet == null) {
throw new BizException("excel数据为空!");
}
// //获取每行成绩数据
int begin = sheet.getFirstRowNum() + 1;
int end = sheet.getLastRowNum();
List<ScoSubjectScores> subjectScoresList = new ArrayList<ScoSubjectScores>();
int k = 0;
int totalCommitNum = 0;
int errorNum = 0;
//单文件重复验证
Map<String,Object> selfMap = new HashMap<String, Object>();
//错误日志记录
String excelDataErr = "";
for (int i = begin; i <= end; i++) {
Row row = sheet.getRow(i);
if (null != row) {
if(POIExcelUtil.isEmptyRow(row)){
continue;
}
k++;
try {
ScoSubjectScores scoSubjectScores = this.getSubjectScoresByRow(row,selfMap);
scoSubjectScores.setCreator(userInfo.getId());
scoSubjectScores.setCreateTime(new Date());
// scoSubjectScores.setFlag(BizConstants.SUBJECT_SCORE_FLAG.IMP);
scoSubjectScores.setRemark("通过文件["+fileName+"]导入");
scoSubjectScores.setStatus(BizConstants.SCORES_SUBJECT_STATUS.UNPUBLISH);
scoSubjectScores.setFlag(Integer.valueOf(BizConstants.SCORES_SUBJECT_STATUS.NORMAL));
subjectScoresList.add(scoSubjectScores);
totalCommitNum += 1;
} catch (Exception e) {
e.printStackTrace();
errorNum += 1;
String errorMsg = "第["+i+"]行数据发生错误:"+e.getMessage();
excelDataErr += "</br>"+errorMsg;
logger.debug(errorMsg);
}
if (k >= batchCommitCount) {
this.batchAddSubjectScores(subjectScoresList);
k = 0 ;
subjectScoresList.clear();
}
}
}
if (k > 0) {
this.batchAddSubjectScores(subjectScoresList);
}
if (errorNum > 0) {
importInfo += "导入错误数据[" + errorNum + "]条!" + importInfo;
}
importInfo = "已导入[" + totalCommitNum + "]成绩数据!" + importInfo;
if(!"".equals(excelDataErr)){
excelDataErr = importInfo + ":</br>"+excelDataErr;
}
//记录日志表
SysImportLog sysImportLog = new SysImportLog();
sysImportLog.setCreateTime(new Date());
sysImportLog.setCreator(userInfo.getId());
sysImportLog.setSrcFile(fileName);
sysImportLog.setFile(fileObj.getFileName());
sysImportLog.setType(BizConstants.IMP_TYPE.SUBJECT_SCORES_INFO);
sysImportLog.setComment(excelDataErr);
this.sysImportLogMapper.insertSelective(sysImportLog);
return importInfo;
}
/**
* 获取excel成绩行数据
* @param row
* @param selfMap
* @return
*/
private ScoSubjectScores getSubjectScoresByRow(Row row,Map<String,Object> selfMap) throws ParseException {
//校验信息
String errorMsg = "";
//验证学籍信息重复性(统一用一个方法来判断) 1.学籍姓名是否存在 科目是否存在
Cell stuNumCell = row.getCell(0);
String stuNum = POIExcelUtil.getStringCellValue(stuNumCell);
errorMsg += ImportKit.isValEmpty(stuNum,"学号");
Cell nameCell = row.getCell(1);
String stuName = POIExcelUtil.getStringCellValue(nameCell);
errorMsg += ImportKit.isValEmpty(stuName, "姓名");
Cell subjectCell = row.getCell(2);
String subjectName = POIExcelUtil.getStringCellValue(subjectCell);
errorMsg += ImportKit.isValEmpty(subjectName, "科目");
Cell termCell = row.getCell(5);
String termCode =String.valueOf(Double.valueOf(POIExcelUtil.getStringCellValue(termCell)).intValue());
errorMsg += ImportKit.isValEmpty(termCode, "学期");
Cell gradeCell = row.getCell(6);
String gradeId = POIExcelUtil.getStringCellValue(gradeCell);
errorMsg += ImportKit.isValEmpty(gradeId, "年级");
Cell schoolYearCell = row.getCell(4);
String schoolYear = POIExcelUtil.getStringCellValue(schoolYearCell);
//校验学年格式
if(!validateSchoolYear(schoolYear)){
errorMsg += "学年非法";
}
Map paramAttr = new HashMap();
paramAttr.put("stuNum", stuNum);
paramAttr.put("stuName",stuName);
paramAttr.put("subjectName",subjectName);
paramAttr.put("term",termCode);
schoolYear = schoolYear.substring(0,4);
paramAttr.put("schoolYear",schoolYear);
Map resInfo = this.scoSubjectScoresMapper.selectExistInfo(paramAttr);
String stuId = null;
String subjectId = null;
// String gradeId = null;
String selfKey = null;
if(resInfo != null){
stuId = resInfo.get("stuId") != null ? (String)resInfo.get("stuId") : null;
subjectId = resInfo.get("subjectId") != null ? (String)resInfo.get("subjectId") : null;
// gradeId = resInfo.get("gradeId") != null ? (String)resInfo.get("gradeId") : null;
int repeatNum = resInfo.get("repeatNum") != null ? ((Long)resInfo.get("repeatNum")).intValue() : 0;
if(subjectId == null){
errorMsg += "科目信息不存在,";
}
// if(gradeId == null){
// errorMsg += "年级不存在,";
// }
if(repeatNum > 0){
errorMsg += "此学生科目成绩已存在,";
}else{
selfKey = stuId+"-"+subjectId+"-"+schoolYear;
if(selfMap.get(selfKey) != null){
throw new BizException("重复数据!");
}
}
}else{
errorMsg += "学籍信息不存在,";
}
ScoSubjectScores scoSubjectScores = new ScoSubjectScores();
scoSubjectScores.setId(BizConstants.generatorPid());
scoSubjectScores.setStuId(stuId);
scoSubjectScores.setSubjectId(subjectId);
scoSubjectScores.setGradeId(gradeId);
scoSubjectScores.setSchoolYear(schoolYear);
scoSubjectScores.setTerm(termCode);
Cell scoreCell = row.getCell(3);
String score = POIExcelUtil.getStringCellValue(scoreCell);
try {
scoSubjectScores.setScore(new BigDecimal(score));
} catch (NumberFormatException e) {
errorMsg += "分数格式非法,";
}
Cell classNameCell = row.getCell(7);
String className= POIExcelUtil.getStringCellValue(classNameCell);
scoSubjectScores.setClassName(className);
if(!"".equals(errorMsg)){
throw new BizException(errorMsg);
}
selfMap.put(selfKey,true);
return scoSubjectScores;
}
// private boolean validateSchoolYear(String schoolYear) {
// boolean bol = true;
// String[] years = schoolYear.split("-");
// if(years.length != 2){
// bol = false;
// }
// try {
// int starYear = Integer.valueOf(years[0]);
// int endYear = Integer.valueOf(years[1]);
// if( (endYear - starYear) != 1 ){
// bol = false;
// }
// } catch (NumberFormatException e) {
// e.printStackTrace();
// bol = false;
// }
// return bol;
// }
private boolean validateSchoolYear(String schoolYear) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
// 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
format.setLenient(false);
format.parse(schoolYear);
} catch (ParseException e) {
return false;
}
return true;
}
/**
* 批量新增科目成绩信息
* @param subjectScoresList
*/
private void batchAddSubjectScores(List<ScoSubjectScores> subjectScoresList) {
if(subjectScoresList.size() > 0){
this.scoSubjectScoresMapper.batchAddSubjectScores(subjectScoresList);
}
}
/**
* 新增科目成绩信息
* @param subjectScores
* @return
*/
public boolean addSubjectScore(ScoSubjectScores subjectScores,String userId) {
boolean bol = true;
//获取学员班级信息
String stuId = subjectScores.getStuId();
if(stuId == null || "".equals(stuId)){
throw new BizException("缺少学员信息!");
}
TchClassInfo classInfo = this.classInfoMapper.selectClassInfoByStuId(stuId);
if(classInfo == null){
throw new BizException("该学员所在班级未知!");
}
//驗證重複性
String subjectId = subjectScores.getSubjectId();
String schoolYear = subjectScores.getSchoolYear();
int count = this.scoSubjectScoresMapper.selectScoresRepeat(stuId,subjectId,schoolYear,null);
if(count > 0){
throw new BizException("科目成绩已存在不可再重复添加!");
}
subjectScores.setClassId(classInfo.getId());
subjectScores.setClassName(classInfo.getName());
subjectScores.setGradeId(classInfo.getGrade());
subjectScores.setCreateTime(new Date());
subjectScores.setCreator(userId);
subjectScores.setId(BizConstants.generatorPid());
this.scoSubjectScoresMapper.insertSelective(subjectScores);
return bol;
}
/**
* 刪除科目成績信息
* @param id
* @return
*/
public boolean delSubjectScores(String id) {
boolean bol = true;
this.scoSubjectScoresMapper.deleteByPrimaryKey(id);
return bol;
}
/**
* 通过id获取科目成绩信息
* @param id
* @return
*/
public ScoSubjectScores selectSubjectSocresById(String id) {
ScoSubjectScores scoSubjectScores = null;
scoSubjectScores = this.scoSubjectScoresMapper.selectSubjectSocresById(id);
return scoSubjectScores;
}
/**
* 修改科目成绩信息
* @param subjectScores
* @param userId
* @return
*/
public boolean modSubjectScore(ScoSubjectScores subjectScores, String userId) {
boolean bol = false;
//获取学员班级信息
String stuId = subjectScores.getStuId();
if(stuId == null || "".equals(stuId)){
throw new BizException("缺少学员信息!");
}
TchClassInfo classInfo = this.classInfoMapper.selectClassInfoByStuId(stuId);
if(classInfo == null){
throw new BizException("该学员所在班级未知!");
}
//驗證重複性
String subjectId = subjectScores.getSubjectId();
String schoolYear = subjectScores.getSchoolYear();
int count = this.scoSubjectScoresMapper.selectScoresRepeat(stuId,subjectId,schoolYear,subjectScores.getId());
// if(count > 0){
// throw new BizException("科目成绩已存在不可再重复添加!");
// }
subjectScores.setClassId(classInfo.getId());
subjectScores.setClassName(classInfo.getName());
subjectScores.setGradeId(classInfo.getGrade());
subjectScores.setUpdateTime(new Date());
subjectScores.setUpdater(userId);
subjectScores.setStatus(BizConstants.SCORES_SUBJECT_STATUS.UNPUBLISH);
int i = this.scoSubjectScoresMapper.updateByPrimaryKeySelective(subjectScores);
if(i > 0){
bol = true;
}
return bol;
}
// public static void main(String[] args) {
// System.out.println(Float.valueOf("85.0").longValue());
// }
public List<ScoSubjectScores> getStuScoreCertificateInfoByParam(String grades,String stuId,String status) {
List<ScoSubjectScores> resList = this.scoSubjectScoresMapper.selectStuScoreCertificateInfoByParam(grades,stuId,status);
return resList;
}
public List<ScoSubjectScores> getStuSubjectScoreByParam(ScoSubjectScores subjectScores) {
List<ScoSubjectScores> resList = this.scoSubjectScoresMapper.selectStuSubjectScoreInfoByParam(subjectScores);
return resList;
}
public List<ScoSubjectScores> getStuSubjectInfoListByParam(ScoSubjectScores subjectScores) {
List<ScoSubjectScores> resList = this.scoSubjectScoresMapper.selectStuSubjectInfoListByParam(subjectScores);
return resList;
}
public List<ScoSubjectScores> getStuScoreCertificateHeadInfoByParam(String grades,String stuId,String status) {
List<ScoSubjectScores> resList = this.scoSubjectScoresMapper.selectStuScoreCertificateInfoHeadByParam(grades, stuId,status);
return resList;
}
// public boolean publishScore(String id) {
// ScoSubjectScores scoSubjectScores = new ScoSubjectScores();
// scoSubjectScores.setId(id);
// scoSubjectScores.setStatus(BizConstants.SCORES_SUBJECT_STATUS.NORMAL);
// this.scoSubjectScoresMapper.updateByPrimaryKeySelective(scoSubjectScores);
// return true;
// }
/**
* 批量发布
* @param idArr
* @return
*/
public boolean batchPublishScore(String[] idArr) {
List<ScoSubjectScores> scoreList = new ArrayList<ScoSubjectScores>();
for (int i = 0; i < idArr.length; i++){
String id = idArr[i];
ScoSubjectScores scoSubjectScores = new ScoSubjectScores();
scoSubjectScores.setId(id);
scoSubjectScores.setStatus(BizConstants.SCORES_SUBJECT_STATUS.NORMAL);
scoreList.add(scoSubjectScores);
}
this.scoSubjectScoresMapper.batchScoreStatus(scoreList);
return true;
}
/**
* 整体发布科目成绩
* @param subjectScores
* @param userId
* @return
*/
public boolean batchPublishAllScoreByParam(ScoSubjectScores subjectScores) {
String schoolYear = subjectScores.getSchoolYear();
String subId = subjectScores.getSubjectId();
if(schoolYear == null || "".equals(schoolYear) || subId == null || "".equals(subId)){
throw new BizException("缺少学年或者科目信息!");
}
subjectScores.setStatus(BizConstants.SCORES_SUBJECT_STATUS.UNPUBLISH);////只修改未发布状态的数据
this.scoSubjectScoresMapper.batchAllScoreStatusByParam(subId,schoolYear,BizConstants.SCORES_SUBJECT_STATUS.NORMAL,BizConstants.SCORES_SUBJECT_STATUS.UNPUBLISH);
return true;
}
// public PageBean getSubjectScoreClassPageData(PageBean pageBean) {
// List resList = scoSubjectScoresMapper.selectSubjectScoresPageData(pageBean);
// pageBean.setData(resList);
// return pageBean;
// }
}
| true |
56c5170c4c23ec0200baa5b314822eee9b5bc36c | Java | jonm8116/Undergrad_Coursework | /CSE_114/TextbookExcercises_2/src/chp10Problems/TestQueue.java | UTF-8 | 338 | 2.5 | 2 | [] | no_license | package chp10Problems;
public class TestQueue {
public static void main(String[] args) {
Queue queue1 = new Queue();
for(int i=1; i<7; i++)
queue1.enqueue(i);
queue1.dequeue();
queue1.dequeue();
queue1.dequeue();
queue1.dequeue();
queue1.dequeue();
queue1.dequeue();
queue1.dequeue();
queue1.dequeue();
}
}
| true |
958af66d46a686b33a51698cc712ec5895874b8d | Java | chenxingxing6/pms | /src/main/java/com/peace/pms/util/Properties.java | UTF-8 | 597 | 2.25 | 2 | [] | no_license | package com.peace.pms.util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Properties {
@Value("#{APP_PROP['jdbc.driver']}")
private String productName;
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public static void main(String[] args) {
Properties properties = new Properties();
System.out.println(properties.productName);
}
}
| true |
ef5ee744f285aa806f058a1a96b0ff7c75fe2029 | Java | chowssand/AutomationF | /src/main/java/com/qa/PageObjects/LoginPage.java | UTF-8 | 911 | 2.234375 | 2 | [] | no_license | package com.qa.PageObjects;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;
public class LoginPage {
public WebDriver driver;
public LoginPage(WebDriver driver){
this.driver = driver;
PageFactory.initElements(driver,this);
}
@FindBy(id="email")
public WebElement userName;
@FindBy(id="pass")
public WebElement password;
@FindBy(id="loginbutton")
public WebElement loginButton;
@FindBy(xpath="//a[text()='Home']")
public WebElement lnkHome;
public void login(String uname, String pass){
userName.sendKeys(uname);
password.sendKeys(pass);
loginButton.click();
}
public void verifyLoginSuccessful(){
Assert.assertTrue(lnkHome.isDisplayed());
}
}
| true |
fe9b1ea914cb14c3b72568f2c3a8d4b131b44f17 | Java | saksham2599/GoalManagementApp | /goalapp/src/main/java/com/goalapp/goalapp/repositoryservices/UserRepositoryServiceImpl.java | UTF-8 | 2,973 | 2.375 | 2 | [] | no_license | package com.goalapp.goalapp.repositoryservices;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.goalapp.goalapp.dto.Goal;
import com.goalapp.goalapp.dto.User;
import com.goalapp.goalapp.exceptions.UserNotFoundException;
import com.goalapp.goalapp.exchanges.AddUserRequest;
import com.goalapp.goalapp.models.GoalEntity;
import com.goalapp.goalapp.models.UserEntity;
import com.goalapp.goalapp.repositories.UserRepository;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserRepositoryServiceImpl implements UserRepositoryService {
@Autowired
private UserRepository userRepository;
public User mapUserEntityToUser(UserEntity userEntity) {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STANDARD);
User user = modelMapper.map(userEntity, User.class);
Set<GoalEntity> goalEntities = userEntity.getGoals();
Set<Goal> goals = new HashSet<Goal>();
for(GoalEntity goalEntity : goalEntities) {
goals.add(modelMapper.map(goalEntity, Goal.class));
}
user.setGoals(goals);
return user;
}
public UserEntity getUserEntity(Long userId) {
UserEntity userEntity = userRepository.findById(userId)
.orElseThrow(() -> new UserNotFoundException(userId));
return userEntity;
}
@Override
public User getUser(Long userId) {
UserEntity userEntity = userRepository.findById(userId)
.orElseThrow(() -> new UserNotFoundException(userId));
User user = mapUserEntityToUser(userEntity);
return user;
}
@Override
public User createUser(AddUserRequest addUser) {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STANDARD);
UserEntity userEntity = modelMapper.map(addUser, UserEntity.class);
userEntity.setGoals(new HashSet<GoalEntity>());
UserEntity userCreated = userRepository.save(userEntity);
User user = mapUserEntityToUser(userCreated);
return user;
}
@Override
public List<User> getAllUsers() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STANDARD);
List<UserEntity> allUsers = userRepository.findAll();
List<User> users = new ArrayList<User>();
for(UserEntity userEntity : allUsers) {
users.add(mapUserEntityToUser(userEntity));
}
return users;
}
}
| true |
54ebf2b9dc8e36a8dc6f8021d4c6597d8c2d3430 | Java | wubin823/cwmp4acs | /cwmp4acs/src/com/tr069/cpe/message/request/GetParameterNames.java | UTF-8 | 447 | 1.976563 | 2 | [] | no_license | package com.tr069.cpe.message.request;
public class GetParameterNames {
private String parameterPath;
private boolean nextLevel;
public String getParameterPath() {
return parameterPath;
}
public void setParameterPath(String parameterPath) {
this.parameterPath = parameterPath;
}
public boolean isNextLevel() {
return nextLevel;
}
public void setNextLevel(boolean nextLevel) {
this.nextLevel = nextLevel;
}
}
| true |
d88dd3834946473eefdb9c439b1b604df2949e35 | Java | wp594458910/DailyManagement | /src/main/java/com/daily/controller/IndexController.java | UTF-8 | 1,886 | 2.0625 | 2 | [] | no_license | package com.daily.controller;
import com.daily.model.Page;
import com.daily.model.Url;
import com.daily.service.UrlService;
import com.daily.util.ListUtils;
import com.daily.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
* Created by IntelliJ IDEA.
* Creator : peng
* Date : 2018-03-19
* Time : 14:35
*/
@Controller
public class IndexController {
@Autowired
private UrlService urlService;
private static final Integer MENU_TYPE = 1;
private static final Integer URL_TYPE = 2;
@RequestMapping("index.do")
public String index(Url url, Page page, ModelMap model) {
page.setMaxRows(8);
url.setTypeid(URL_TYPE);
List<Url> list = urlService.queryByUrl(url);
page.setStart(PageUtils.getPage(page.getPageNumber(), page.getTotalPage(), list.size(), page.getMaxRows()));
page.setTotalPage(PageUtils.getTotalPage(page.getPageNumber(), page.getTotalPage(), list.size(), page.getMaxRows()));
List<Url> urlList = urlService.queryByList(page, url);
List<Url> menuList = urlService.queryByType(MENU_TYPE);
List<Url> normalList = ListUtils.getListByNum(urlService.queryByType(URL_TYPE), 4);
model.put("menuList", menuList);
model.put("urlList", urlList);
model.put("normalList", normalList);
model.put("page", page);
model.put("url", url);
return "front";
}
@RequestMapping("enterSite.do")
@ResponseBody
public void enterSite(Url url) {
url = urlService.queryById(url.getId());
url.setTimes(url.getTimes() + 1);
urlService.update(url);
}
}
| true |
b69c6c4b9d6303455279e98b737d472970a45311 | Java | sharryhong/java93-hs | /java01/src/step18/Test06_2.java | UTF-8 | 1,211 | 3.046875 | 3 | [] | no_license | /* 소켓 프로그래밍 응용 : Echo 클라이언트 만들기
* => echo할 때마다 서버주소주고 출력
*/
package step18;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Test06_2 {
public static void main(String[] args) throws Exception {
if (args.length < 3) {
System.out.println("[사용법] > java -cp bin step18.Test06_2 서버 포트 메시지");
return;
}
try (
Socket socket = new Socket(args[0], Integer.parseInt(args[1]));
Scanner in = new Scanner(socket.getInputStream());
PrintStream out = new PrintStream(socket.getOutputStream());
) {
out.println(args[2]); // 읽어서
System.out.println(in.nextLine()); // 바로 출력
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
9c1e3a6a43d11e31272e9c5c0aad68791432aaa0 | Java | NicolasGuary/BattleshipIA | /IABattleship/src/fr/igpolytech/guary/exceptions/OrientationException.java | UTF-8 | 271 | 2.453125 | 2 | [] | no_license | package fr.igpolytech.guary.exceptions;
public class OrientationException extends Exception {
private static final long serialVersionUID = 1L;
public OrientationException(){
}
public String toString() {
return "This Ship is not horizontal or vertical.";
}
}
| true |
6051d2341ee823ead5b0b4b5ad8b6f841c8cfa65 | Java | P79N6A/speedx | /reverse_engineered/sources/io/rong/imlib/LibHandlerStub.java | UTF-8 | 60,727 | 1.71875 | 2 | [] | no_license | package io.rong.imlib;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Parcelable;
import android.os.RemoteException;
import io.rong.common.RLog;
import io.rong.common.WakeLockUtils;
import io.rong.imlib.IHandler.Stub;
import io.rong.imlib.NativeClient.BlacklistStatus;
import io.rong.imlib.NativeClient.GetNotificationQuietHoursCallback;
import io.rong.imlib.NativeClient.ICodeListener;
import io.rong.imlib.NativeClient.IResultCallback;
import io.rong.imlib.NativeClient.IResultProgressCallback;
import io.rong.imlib.NativeClient.ISendMessageCallback;
import io.rong.imlib.NativeClient.OnReceiveMessageListener;
import io.rong.imlib.NativeClient.RealTimeLocationListener;
import io.rong.imlib.location.RealTimeLocationConstant.RealTimeLocationErrorCode;
import io.rong.imlib.location.RealTimeLocationConstant.RealTimeLocationStatus;
import io.rong.imlib.model.ChatRoomInfo;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Conversation.ConversationNotificationStatus;
import io.rong.imlib.model.Conversation.ConversationType;
import io.rong.imlib.model.Discussion;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.Message$ReceivedStatus;
import io.rong.imlib.model.Message$SentStatus;
import io.rong.imlib.model.PublicServiceProfile;
import io.rong.imlib.model.PublicServiceProfileList;
import io.rong.imlib.model.RemoteModelWrap;
import io.rong.imlib.model.RongListWrap;
import io.rong.imlib.model.UserData;
import io.rong.imlib.navigation.NavigationClient;
import java.util.List;
public class LibHandlerStub extends Stub {
private static final String TAG = "LibHandlerStub";
Handler mCallbackHandler;
HandlerThread mCallbackThread = new HandlerThread("Rong_SDK_Callback");
NativeClient mClient;
Context mContext;
String mCurrentUserId;
private class OperationCallback implements io.rong.imlib.NativeClient.OperationCallback {
IOperationCallback callback;
/* renamed from: io.rong.imlib.LibHandlerStub$OperationCallback$1 */
class C52631 implements Runnable {
C52631() {
}
public void run() {
try {
OperationCallback.this.callback.onComplete();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
public OperationCallback(IOperationCallback iOperationCallback) {
this.callback = iOperationCallback;
}
public void onSuccess() {
if (this.callback != null) {
LibHandlerStub.this.mCallbackHandler.post(new C52631());
}
}
public void onError(final int i) {
if (this.callback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
OperationCallback.this.callback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
}
public LibHandlerStub(Context context, String str, String str2) {
this.mContext = context;
this.mCallbackThread.start();
this.mCallbackHandler = new Handler(this.mCallbackThread.getLooper());
this.mClient = NativeClient.getInstance();
this.mClient.init(this.mContext, str, str2);
}
public String getCurrentUserId() {
return this.mClient.getCurrentUserId();
}
public void connect(String str, final IStringCallback iStringCallback) throws RemoteException {
try {
RLog.m19422i(TAG, "connect");
this.mClient.connect(str, new IResultCallback<String>() {
public void onSuccess(final String str) {
if (iStringCallback != null) {
LibHandlerStub.this.mCurrentUserId = str;
WakeLockUtils.startNextHeartbeat(LibHandlerStub.this.mContext);
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
Exception e;
try {
iStringCallback.onComplete(str);
return;
} catch (RemoteException e2) {
e = e2;
} catch (NullPointerException e3) {
e = e3;
}
e.printStackTrace();
}
});
}
}
public void onError(final int i) {
WakeLockUtils.cancelHeartbeat(LibHandlerStub.this.mContext);
if (iStringCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iStringCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
});
} catch (Exception e) {
e.printStackTrace();
if (iStringCallback != null) {
this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iStringCallback.onFailure(-1);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
}
public void disconnect(boolean z, IOperationCallback iOperationCallback) throws RemoteException {
if (this.mClient != null) {
WakeLockUtils.cancelHeartbeat(this.mContext);
this.mClient.disconnect(z);
if (iOperationCallback != null) {
try {
iOperationCallback.onComplete();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
}
public void registerMessageType(String str) {
Class cls = null;
try {
cls = Class.forName(str);
} catch (Throwable e) {
RLog.m19421e(TAG, "registerMessageType ClassNotFoundException", e);
e.printStackTrace();
}
try {
NativeClient nativeClient = this.mClient;
NativeClient.registerMessageType(cls);
} catch (Throwable e2) {
RLog.m19421e(TAG, "registerMessageType AnnotationNotFoundException", e2);
}
}
public void setConnectionStatusListener(final IConnectionStatusListener iConnectionStatusListener) {
NativeClient.setConnectionStatusListener(new ICodeListener() {
public void onChanged(int i) {
try {
RLog.m19419d(LibHandlerStub.TAG, "setConnectionStatusListener : onChanged status:" + i);
if (!(i == 33005 || i == 0)) {
WakeLockUtils.cancelHeartbeat(LibHandlerStub.this.mContext);
}
if (iConnectionStatusListener != null) {
iConnectionStatusListener.onChanged(i);
}
} catch (Throwable e) {
e.printStackTrace();
RLog.m19421e(LibHandlerStub.TAG, "setConnectionStatusListener : onChanged RemoteException", e);
}
}
});
}
public int getTotalUnreadCount() throws RemoteException {
return this.mClient.getTotalUnreadCount();
}
public int getUnreadCount(int[] iArr) {
int i = 0;
if (iArr == null || iArr.length == 0) {
return 0;
}
ConversationType[] conversationTypeArr = new ConversationType[iArr.length];
while (i < iArr.length) {
conversationTypeArr[i] = ConversationType.setValue(iArr[i]);
i++;
}
return this.mClient.getUnreadCount(conversationTypeArr);
}
public int getUnreadCountById(int i, String str) {
ConversationType value = ConversationType.setValue(i);
if (value == null || str == null) {
return 0;
}
return this.mClient.getUnreadCount(value, str);
}
public void setOnReceiveMessageListener(final OnReceiveMessageListener onReceiveMessageListener) {
if (onReceiveMessageListener != null) {
this.mClient.setOnReceiveMessageListener(new OnReceiveMessageListener() {
public void onReceived(Message message, int i, boolean z) {
RLog.m19419d(LibHandlerStub.TAG, "setOnReceiveMessageListener onReceived : " + message.getObjectName());
try {
onReceiveMessageListener.onReceived(message, i, z);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
public Message insertMessage(Message message) throws RemoteException {
return this.mClient.insertMessage(message.getConversationType(), message.getTargetId(), message.getSenderUserId(), message.getContent());
}
public Message getMessage(int i) {
return this.mClient.getMessage(i);
}
public Message getMessageByUid(String str) {
return this.mClient.getMessageByUid(str);
}
public void sendMessage(Message message, String str, String str2, final ISendMessageCallback iSendMessageCallback) throws RemoteException {
this.mClient.sendMessage(message, str, str2, new ISendMessageCallback<Message>() {
public void onAttached(final Message message) {
if (iSendMessageCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iSendMessageCallback.onAttached(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
public void onSuccess(final Message message) {
if (iSendMessageCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iSendMessageCallback.onSuccess(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
public void onError(final Message message, final int i) {
if (iSendMessageCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iSendMessageCallback.onError(message, i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
});
}
public void sendLocationMessage(Message message, String str, String str2, final ISendMessageCallback iSendMessageCallback) throws RemoteException {
this.mClient.sendLocationMessage(message, str, str2, new ISendMessageCallback<Message>() {
public void onAttached(final Message message) {
if (iSendMessageCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iSendMessageCallback.onAttached(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
public void onSuccess(final Message message) {
if (iSendMessageCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iSendMessageCallback.onSuccess(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
public void onError(final Message message, final int i) {
if (iSendMessageCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iSendMessageCallback.onError(message, i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
});
}
public Message sendStatusMessage(Message message, final ILongCallback iLongCallback) throws RemoteException {
Message sendStatusMessage = this.mClient.sendStatusMessage(message.getConversationType(), message.getTargetId(), message.getContent(), 1, new IResultCallback<Integer>() {
public void onSuccess(final Integer num) {
if (iLongCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iLongCallback.onComplete((long) num.intValue());
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
public void onError(final int i) {
if (iLongCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iLongCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
});
sendStatusMessage.setSenderUserId(this.mCurrentUserId);
return sendStatusMessage;
}
public List<Message> getNewestMessages(Conversation conversation, int i) throws RemoteException {
List<Message> latestMessages = this.mClient.getLatestMessages(conversation.getConversationType(), conversation.getTargetId(), i);
if (latestMessages == null || latestMessages.size() == 0) {
return null;
}
return latestMessages;
}
public List<Message> getOlderMessages(Conversation conversation, long j, int i) throws RemoteException {
List<Message> historyMessages = this.mClient.getHistoryMessages(conversation.getConversationType(), conversation.getTargetId(), (int) j, i);
if (historyMessages == null || historyMessages.size() == 0) {
return null;
}
return historyMessages;
}
public void getRemoteHistoryMessages(Conversation conversation, long j, int i, final IResultCallback iResultCallback) throws RemoteException {
this.mClient.getRemoteHistoryMessages(conversation.getConversationType(), conversation.getTargetId(), j, i, new IResultCallback<List<Message>>() {
public void onError(int i) {
if (iResultCallback != null) {
try {
iResultCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
public void onSuccess(List<Message> list) {
if (iResultCallback != null) {
if (list != null) {
try {
if (list.size() != 0) {
iResultCallback.onComplete(new RemoteModelWrap(RongListWrap.obtain(list, Message.class)));
return;
}
} catch (RemoteException e) {
e.printStackTrace();
return;
}
}
iResultCallback.onComplete(null);
}
}
});
}
public List<Message> getOlderMessagesByObjectName(Conversation conversation, String str, long j, int i, boolean z) throws RemoteException {
List<Message> historyMessages = this.mClient.getHistoryMessages(conversation.getConversationType(), conversation.getTargetId(), str, (int) j, i, z);
if (historyMessages == null || historyMessages.size() == 0) {
return null;
}
return historyMessages;
}
public boolean deleteMessage(int[] iArr) throws RemoteException {
if (iArr == null || iArr.length == 0) {
return false;
}
return this.mClient.deleteMessages(iArr);
}
public boolean deleteConversationMessage(int i, String str) throws RemoteException {
return this.mClient.deleteMessage(ConversationType.setValue(i), str);
}
public boolean clearMessages(Conversation conversation) throws RemoteException {
return this.mClient.clearMessages(conversation.getConversationType(), conversation.getTargetId());
}
public boolean clearMessagesUnreadStatus(Conversation conversation) throws RemoteException {
return this.mClient.clearMessagesUnreadStatus(conversation.getConversationType(), conversation.getTargetId());
}
public boolean setMessageExtra(int i, String str) throws RemoteException {
return this.mClient.setMessageExtra(i, str);
}
public boolean setMessageReceivedStatus(int i, int i2) throws RemoteException {
return this.mClient.setMessageReceivedStatus(i, new Message$ReceivedStatus(i2));
}
public boolean setMessageSentStatus(int i, int i2) throws RemoteException {
return this.mClient.setMessageSentStatus(i, Message$SentStatus.setValue(i2));
}
public List<Conversation> getConversationList() throws RemoteException {
List<Conversation> conversationList = this.mClient.getConversationList();
if (conversationList == null || conversationList.size() == 0) {
return null;
}
return conversationList;
}
public boolean updateConversationInfo(int i, String str, String str2, String str3) {
return this.mClient.updateConversationInfo(ConversationType.setValue(i), str, str2, str3);
}
public List<Conversation> getConversationListByType(int[] iArr) throws RemoteException {
List<Conversation> conversationList = this.mClient.getConversationList(iArr);
if (conversationList == null || conversationList.size() == 0) {
return null;
}
return conversationList;
}
public Conversation getConversation(int i, String str) throws RemoteException {
return this.mClient.getConversation(ConversationType.setValue(i), str);
}
public boolean removeConversation(int i, String str) throws RemoteException {
ConversationType value = ConversationType.setValue(i);
if (value != null) {
return this.mClient.removeConversation(value, str);
}
RLog.m19422i(TAG, "removeConversation the conversation type is null");
return false;
}
public boolean clearConversations(int[] iArr) throws RemoteException {
int i = 0;
if (iArr == null || iArr.length == 0) {
return false;
}
ConversationType[] conversationTypeArr = new ConversationType[iArr.length];
while (i < iArr.length) {
conversationTypeArr[i] = ConversationType.setValue(iArr[i]);
i++;
}
return this.mClient.clearConversations(conversationTypeArr);
}
public boolean saveConversationDraft(Conversation conversation, String str) throws RemoteException {
RLog.m19422i(TAG, "saveConversationDraft " + str);
return this.mClient.saveTextMessageDraft(conversation.getConversationType(), conversation.getTargetId(), str);
}
public String getConversationDraft(Conversation conversation) throws RemoteException {
return this.mClient.getTextMessageDraft(conversation.getConversationType(), conversation.getTargetId());
}
public boolean cleanConversationDraft(Conversation conversation) throws RemoteException {
return this.mClient.clearTextMessageDraft(conversation.getConversationType(), conversation.getTargetId());
}
public void getConversationNotificationStatus(int i, String str, final ILongCallback iLongCallback) throws RemoteException {
this.mClient.getConversationNotificationStatus(ConversationType.setValue(i), str, new IResultCallback<Integer>() {
public void onSuccess(final Integer num) {
if (iLongCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iLongCallback.onComplete((long) num.intValue());
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
public void onError(final int i) {
if (iLongCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iLongCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
});
}
public void setConversationNotificationStatus(int i, String str, int i2, final ILongCallback iLongCallback) throws RemoteException {
this.mClient.setConversationNotificationStatus(ConversationType.setValue(i), str, ConversationNotificationStatus.setValue(i2), new IResultCallback<Integer>() {
public void onSuccess(final Integer num) {
if (iLongCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iLongCallback.onComplete((long) num.intValue());
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
public void onError(final int i) {
if (iLongCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iLongCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
});
}
public boolean setConversationTopStatus(int i, String str, boolean z) {
ConversationType value = ConversationType.setValue(i);
if (value != null) {
return this.mClient.setConversationToTop(value, str, z);
}
RLog.m19420e(TAG, "setConversationTopStatus ConversationType is null");
return false;
}
public int getConversationUnreadCount(Conversation conversation) {
return this.mClient.getUnreadCount(conversation.getConversationType(), conversation.getTargetId());
}
public void getDiscussion(String str, final IResultCallback iResultCallback) throws RemoteException {
this.mClient.getDiscussion(str, new IResultCallback<Discussion>() {
public void onSuccess(final Discussion discussion) {
if (iResultCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iResultCallback.onComplete(new RemoteModelWrap(discussion));
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
public void onError(final int i) {
if (iResultCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iResultCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
});
}
public void setDiscussionName(String str, String str2, IOperationCallback iOperationCallback) throws RemoteException {
this.mClient.setDiscussionName(str, str2, new OperationCallback(iOperationCallback));
}
public void createDiscussion(final String str, final List<String> list, final IResultCallback iResultCallback) throws RemoteException {
this.mClient.createDiscussion(str, list, new IResultCallback<String>() {
public void onSuccess(final String str) {
if (iResultCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iResultCallback.onComplete(new RemoteModelWrap(new Discussion(str, str, LibHandlerStub.this.mCurrentUserId, true, list)));
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
public void onError(final int i) {
if (iResultCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iResultCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
});
}
public void searchPublicService(String str, int i, int i2, final IResultCallback iResultCallback) {
this.mClient.searchPublicService(str, i, i2, new IResultCallback<PublicServiceProfileList>() {
public void onSuccess(PublicServiceProfileList publicServiceProfileList) {
final RemoteModelWrap remoteModelWrap = new RemoteModelWrap((Parcelable) publicServiceProfileList);
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iResultCallback.onComplete(remoteModelWrap);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iResultCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public void subscribePublicService(String str, int i, boolean z, final IOperationCallback iOperationCallback) {
this.mClient.subscribePublicService(str, i, z, new io.rong.imlib.NativeClient.OperationCallback() {
/* renamed from: io.rong.imlib.LibHandlerStub$14$1 */
class C52041 implements Runnable {
C52041() {
}
public void run() {
try {
iOperationCallback.onComplete();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
public void onSuccess() {
LibHandlerStub.this.mCallbackHandler.post(new C52041());
}
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iOperationCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public void getPublicServiceProfile(String str, int i, final IResultCallback iResultCallback) {
this.mClient.getPublicServiceProfile(str, i, new IResultCallback<PublicServiceProfile>() {
public void onSuccess(final PublicServiceProfile publicServiceProfile) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
RemoteModelWrap remoteModelWrap = null;
if (publicServiceProfile != null) {
remoteModelWrap = new RemoteModelWrap(publicServiceProfile);
}
try {
iResultCallback.onComplete(remoteModelWrap);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iResultCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public void getPublicServiceList(final IResultCallback iResultCallback) {
this.mClient.getPublicServiceList(new IResultCallback<PublicServiceProfileList>() {
public void onSuccess(final PublicServiceProfileList publicServiceProfileList) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iResultCallback.onComplete(new RemoteModelWrap(publicServiceProfileList));
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iResultCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public void addMemberToDiscussion(String str, List<String> list, IOperationCallback iOperationCallback) throws RemoteException {
this.mClient.addMemberToDiscussion(str, list, new OperationCallback(iOperationCallback));
}
public void removeDiscussionMember(String str, String str2, IOperationCallback iOperationCallback) throws RemoteException {
this.mClient.removeMemberFromDiscussion(str, str2, new OperationCallback(iOperationCallback));
}
public void quitDiscussion(String str, IOperationCallback iOperationCallback) throws RemoteException {
this.mClient.quitDiscussion(str, new OperationCallback(iOperationCallback));
}
public void syncGroup(List<Group> list, IOperationCallback iOperationCallback) throws RemoteException {
this.mClient.syncGroup(list, new OperationCallback(iOperationCallback));
}
public void joinGroup(String str, String str2, IOperationCallback iOperationCallback) throws RemoteException {
this.mClient.joinGroup(str, str2, new OperationCallback(iOperationCallback));
}
public void quitGroup(String str, IOperationCallback iOperationCallback) throws RemoteException {
this.mClient.quitGroup(str, new OperationCallback(iOperationCallback));
}
public void getChatRoomInfo(String str, int i, int i2, final IResultCallback iResultCallback) {
this.mClient.queryChatRoomInfo(str, i, i2, new IResultCallback<ChatRoomInfo>() {
public void onSuccess(ChatRoomInfo chatRoomInfo) {
try {
iResultCallback.onComplete(new RemoteModelWrap((Parcelable) chatRoomInfo));
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void onError(int i) {
try {
iResultCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
public void joinChatRoom(String str, int i, final IOperationCallback iOperationCallback) throws RemoteException {
this.mClient.joinChatRoom(str, i, new io.rong.imlib.NativeClient.OperationCallback() {
/* renamed from: io.rong.imlib.LibHandlerStub$18$1 */
class C52101 implements Runnable {
C52101() {
}
public void run() {
try {
iOperationCallback.onComplete();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
public void onSuccess() {
LibHandlerStub.this.mCallbackHandler.post(new C52101());
}
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iOperationCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public void reJoinChatRoom(String str, int i, final IOperationCallback iOperationCallback) throws RemoteException {
this.mClient.reJoinChatRoom(str, i, new io.rong.imlib.NativeClient.OperationCallback() {
/* renamed from: io.rong.imlib.LibHandlerStub$19$1 */
class C52121 implements Runnable {
C52121() {
}
public void run() {
try {
iOperationCallback.onComplete();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
public void onSuccess() {
LibHandlerStub.this.mCallbackHandler.post(new C52121());
}
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iOperationCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public void joinExistChatRoom(String str, int i, final IOperationCallback iOperationCallback) throws RemoteException {
this.mClient.joinExistChatRoom(str, i, new io.rong.imlib.NativeClient.OperationCallback() {
/* renamed from: io.rong.imlib.LibHandlerStub$20$1 */
class C52151 implements Runnable {
C52151() {
}
public void run() {
try {
iOperationCallback.onComplete();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
public void onSuccess() {
LibHandlerStub.this.mCallbackHandler.post(new C52151());
}
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iOperationCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public void quitChatRoom(String str, final IOperationCallback iOperationCallback) throws RemoteException {
this.mClient.quitChatRoom(str, new io.rong.imlib.NativeClient.OperationCallback() {
/* renamed from: io.rong.imlib.LibHandlerStub$21$1 */
class C52171 implements Runnable {
C52171() {
}
public void run() {
try {
iOperationCallback.onComplete();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
public void onSuccess() {
LibHandlerStub.this.mCallbackHandler.post(new C52171());
}
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iOperationCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public void setNotificationQuietHours(String str, int i, final IOperationCallback iOperationCallback) {
this.mClient.setNotificationQuietHours(str, i, new io.rong.imlib.NativeClient.OperationCallback() {
/* renamed from: io.rong.imlib.LibHandlerStub$22$1 */
class C52191 implements Runnable {
C52191() {
}
public void run() {
try {
iOperationCallback.onComplete();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
public void onSuccess() {
LibHandlerStub.this.mCallbackHandler.post(new C52191());
}
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iOperationCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public void removeNotificationQuietHours(final IOperationCallback iOperationCallback) {
this.mClient.removeNotificationQuietHours(new io.rong.imlib.NativeClient.OperationCallback() {
/* renamed from: io.rong.imlib.LibHandlerStub$23$2 */
class C52222 implements Runnable {
C52222() {
}
public void run() {
try {
iOperationCallback.onComplete();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iOperationCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
public void onSuccess() {
LibHandlerStub.this.mCallbackHandler.post(new C52222());
}
});
}
public void getNotificationQuietHours(final IGetNotificationQuietHoursCallback iGetNotificationQuietHoursCallback) {
this.mClient.getNotificationQuietHours(new GetNotificationQuietHoursCallback() {
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iGetNotificationQuietHoursCallback.onError(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
public void onSuccess(final String str, final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iGetNotificationQuietHoursCallback.onSuccess(str, i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public boolean validateAuth(String str) {
return false;
}
public void uploadMedia(Conversation conversation, String str, int i, final IUploadCallback iUploadCallback) {
this.mClient.uploadMedia(conversation.getConversationType(), conversation.getTargetId(), str, i, new IResultProgressCallback<String>() {
public void onProgress(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iUploadCallback.onProgress(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
public void onSuccess(final String str) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iUploadCallback.onComplete(str);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iUploadCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public void downloadMedia(Conversation conversation, int i, String str, final IDownloadMediaCallback iDownloadMediaCallback) throws RemoteException {
this.mClient.downloadMedia(conversation.getConversationType(), conversation.getTargetId(), i, str, new IResultProgressCallback<String>() {
public void onProgress(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iDownloadMediaCallback.onProgress(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
public void onSuccess(final String str) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
RLog.m19422i(LibHandlerStub.TAG, "onSuccess " + iDownloadMediaCallback.toString());
iDownloadMediaCallback.onComplete(str);
RLog.m19422i(LibHandlerStub.TAG, "onComplete " + str);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iDownloadMediaCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public long getDeltaTime() {
return this.mClient.getDeltaTime();
}
public void setDiscussionInviteStatus(String str, int i, final IOperationCallback iOperationCallback) {
this.mClient.setDiscussionInviteStatus(str, i, new io.rong.imlib.NativeClient.OperationCallback() {
/* renamed from: io.rong.imlib.LibHandlerStub$27$1 */
class C52311 implements Runnable {
C52311() {
}
public void run() {
try {
iOperationCallback.onComplete();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
public void onSuccess() {
LibHandlerStub.this.mCallbackHandler.post(new C52311());
}
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iOperationCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public void addToBlacklist(String str, final IOperationCallback iOperationCallback) {
this.mClient.addToBlacklist(str, new io.rong.imlib.NativeClient.OperationCallback() {
/* renamed from: io.rong.imlib.LibHandlerStub$28$1 */
class C52331 implements Runnable {
C52331() {
}
public void run() {
try {
iOperationCallback.onComplete();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
public void onSuccess() {
LibHandlerStub.this.mCallbackHandler.post(new C52331());
}
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iOperationCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public void removeFromBlacklist(String str, final IOperationCallback iOperationCallback) {
this.mClient.removeFromBlacklist(str, new io.rong.imlib.NativeClient.OperationCallback() {
/* renamed from: io.rong.imlib.LibHandlerStub$29$1 */
class C52351 implements Runnable {
C52351() {
}
public void run() {
try {
iOperationCallback.onComplete();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
public void onSuccess() {
LibHandlerStub.this.mCallbackHandler.post(new C52351());
}
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iOperationCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public void getBlacklistStatus(String str, final IIntegerCallback iIntegerCallback) {
this.mClient.getBlacklistStatus(str, new IResultCallback<BlacklistStatus>() {
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iIntegerCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
public void onSuccess(final BlacklistStatus blacklistStatus) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iIntegerCallback.onComplete(blacklistStatus.getValue());
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public void getBlacklist(final IStringCallback iStringCallback) {
this.mClient.getBlacklist(new IResultCallback<String>() {
public void onSuccess(final String str) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iStringCallback.onComplete(str);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iStringCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public String getTextMessageDraft(Conversation conversation) {
return this.mClient.getTextMessageDraft(conversation.getConversationType(), conversation.getTargetId());
}
public boolean saveTextMessageDraft(Conversation conversation, String str) {
return this.mClient.saveTextMessageDraft(conversation.getConversationType(), conversation.getTargetId(), str);
}
public boolean clearTextMessageDraft(Conversation conversation) {
return this.mClient.clearTextMessageDraft(conversation.getConversationType(), conversation.getTargetId());
}
public void setUserData(UserData userData, final IOperationCallback iOperationCallback) {
this.mClient.setUserData(userData, new io.rong.imlib.NativeClient.OperationCallback() {
/* renamed from: io.rong.imlib.LibHandlerStub$32$1 */
class C52421 implements Runnable {
C52421() {
}
public void run() {
try {
iOperationCallback.onComplete();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
public void onSuccess() {
LibHandlerStub.this.mCallbackHandler.post(new C52421());
}
public void onError(final int i) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iOperationCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
});
}
public int setupRealTimeLocation(int i, String str) {
return this.mClient.setupRealTimeLocation(this.mContext, i, str);
}
public int startRealTimeLocation(int i, String str) {
return this.mClient.startRealTimeLocation(i, str);
}
public int joinRealTimeLocation(int i, String str) {
return this.mClient.joinRealTimeLocation(i, str);
}
public void quitRealTimeLocation(int i, String str) {
this.mClient.quitRealTimeLocation(i, str);
}
public List<String> getRealTimeLocationParticipants(int i, String str) {
return this.mClient.getRealTimeLocationParticipants(i, str);
}
public int getRealTimeLocationCurrentState(int i, String str) {
return this.mClient.getRealTimeLocationCurrentState(i, str).getValue();
}
public void addRealTimeLocationListener(int i, String str, final IRealTimeLocationListener iRealTimeLocationListener) {
this.mClient.addListener(i, str, new RealTimeLocationListener() {
public void onStatusChange(RealTimeLocationStatus realTimeLocationStatus) {
try {
iRealTimeLocationListener.onStatusChange(realTimeLocationStatus.getValue());
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void onReceiveLocation(double d, double d2, String str) {
try {
iRealTimeLocationListener.onReceiveLocation(d, d2, str);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void onParticipantsJoin(String str) {
try {
iRealTimeLocationListener.onParticipantsJoin(str);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void onParticipantsQuit(String str) {
try {
iRealTimeLocationListener.onParticipantsQuit(str);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void onError(RealTimeLocationErrorCode realTimeLocationErrorCode) {
try {
iRealTimeLocationListener.onError(realTimeLocationErrorCode.getValue());
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
public void updateRealTimeLocationStatus(int i, String str, double d, double d2) {
this.mClient.updateRealTimeLocationStatus(i, str, d, d2);
}
public boolean updateMessageReceiptStatus(String str, int i, long j) {
return this.mClient.updateMessageReceiptStatus(str, i, j);
}
public long getSendTimeByMessageId(int i) {
return this.mClient.getSendTimeByMessageId(i);
}
public void getVoIPKey(int i, String str, String str2, final IStringCallback iStringCallback) {
this.mClient.getVoIPKey(i, str, str2, new IResultCallback<String>() {
public void onSuccess(final String str) {
if (iStringCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
Exception e;
try {
iStringCallback.onComplete(str);
return;
} catch (RemoteException e2) {
e = e2;
} catch (NullPointerException e3) {
e = e3;
}
e.printStackTrace();
}
});
}
}
public void onError(final int i) {
if (iStringCallback != null) {
LibHandlerStub.this.mCallbackHandler.post(new Runnable() {
public void run() {
try {
iStringCallback.onFailure(i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
});
}
public String getVoIPCallInfo() {
return this.mClient.getVoIPCallInfo();
}
public void setServerInfo(String str, String str2) {
this.mClient.setServerInfo(str, str2);
}
public long getNaviCachedTime() {
return NavigationClient.getInstance().getLastCachedTime();
}
public String getCMPServer() {
return NavigationClient.getInstance().getCMPServer();
}
public void getPCAuthConfig(final IStringCallback iStringCallback) {
this.mClient.getPCAuthConfig(new IResultCallback<String>() {
public void onSuccess(String str) {
try {
iStringCallback.onComplete(str);
} catch (RemoteException e) {
}
}
public void onError(int i) {
try {
iStringCallback.onFailure(i);
} catch (RemoteException e) {
}
}
});
}
public boolean setMessageContent(int i, byte[] bArr, String str) {
return this.mClient.setMessageContent(i, bArr, str);
}
public List<Message> getUnreadMentionedMessages(int i, String str) {
List<Message> unreadMentionedMessages = this.mClient.getUnreadMentionedMessages(ConversationType.setValue(i), str);
if (unreadMentionedMessages == null || unreadMentionedMessages.size() == 0) {
return null;
}
return unreadMentionedMessages;
}
}
| true |
6565b80a3d40c05538201f9d47280bceed6a7326 | Java | eri-tri89/integration_ju14 | /scrumboard/src/main/java/se/ju14/scrumboard/service/TeamService.java | UTF-8 | 3,361 | 2.765625 | 3 | [] | no_license | package se.ju14.scrumboard.service;
import java.net.URI;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.Response;
import se.ju14.scrumboard.model.Member;
import se.ju14.scrumboard.model.Team;
/**
* This class manages the team functions and service
*
* @author Erik Pérez
**/
@Path("/team")
//@Consumes(MediaType.APPLICATION_JSON)
//@Produces(MediaType.APPLICATION_JSON)
public class TeamService extends ScrumService {
/**
* Creates a team
*
* @param team
* the team to be consumed as a JSON object
* @return a 200 response if it creates successfully, 404 otherwise
**/
@POST
public Response createTeam(Team team) {
Team teamToSave = teamRepository.save(team);
URI location = uriInfo.getAbsolutePathBuilder().path(teamToSave.getName()).build();
return Response.created(location).entity(teamToSave).build();
}
/**
* Updates a team's information
*
* @param teamID
* the id of the team to be updated
*/
@PUT
@Path("{name}")
public Response updateTeamInfo(@PathParam("name") String name) {
Team teamToSave = teamRepository.update(teamRepository.getTeamByName(name));
URI location = uriInfo.getAbsolutePathBuilder().path(teamToSave.getName()).build();
return Response.created(location).entity(teamToSave).build();
}
/**
* Adds a new member to a team
*
* @param teamID
* the id of the team to be updated
*/
@POST
@Path("{name}")
public Response addMembertoTeam(@PathParam("name") String name, Member member) {
Team team = teamRepository.getTeamByName(name);
teamRepository.addMemberToTeam(member, team);
URI location = uriInfo.getAbsolutePathBuilder().path(team.getName()).build();
return Response.created(location).entity(team).build();
}
/**
* updates a team status to DELETED
*
* @param teamID
* the id of the team to be deleted
**/
@DELETE
@Path("{name}")
public Response deleteTeam(@PathParam("name") String name) {
Team team = teamRepository.getTeamByName(name);
teamRepository.delete(team);
URI location = uriInfo.getAbsolutePathBuilder().path(team.getName()).build();
return Response.created(location).entity(team).build();
}
/**
* Get all the registered teams in DB
*
* @param teamID
* the id of the team to be deleted
**/
@GET
public Response getAllTeams() {
List<Team> teamList = teamRepository.getAll();
Collection<Team> teams = new HashSet<Team>(teamList);
GenericEntity<Collection<Team>> result =
new GenericEntity<Collection<Team>>(teams){};
return Response.ok(result).build();
}
/**
* Get the members of a specific team
*
* @param teamID
* the id of the team
* @return a collection of users that are part of the team and a 200
* response
**/
@GET
@Path("{name}")
public Response getAllTeamMembers(@PathParam("name") String name){
List<Member> teamMembers = memberRepository.getTeamMembers(teamRepository.getTeamByName(name));
GenericEntity<Collection<Member>> result =
new GenericEntity<Collection<Member>>(teamMembers){};
return Response.ok(result).build();
}
}
| true |
8ed1f5cd7b9da98b860ba46745d80036e7aea84b | Java | ksinght86/masters-thesis-lsframework | /test/tum/dss/thesis/lsframework/EllipsoidMethodTestdata3.java | UTF-8 | 501 | 1.9375 | 2 | [
"CC-BY-4.0"
] | permissive | package tum.dss.thesis.lsframework;
import tum.dss.thesis.MatrixHelper;
public class EllipsoidMethodTestdata3 extends EllipsoidMethodDataMock {
private double[][] constraints = {{-1, -3, -4},{-8, -2, -3},{-1, 0, 0},{0, -1, 0},{0, 0, -1}};
private double[] values = {-4,-7,0,0,0};
private double[] objective = {-1,-2,-3};
public EllipsoidMethodTestdata3() {
C = MatrixHelper.createMatrix(constraints);
d = MatrixHelper.createVector(values);
o = MatrixHelper.createVector(objective);
}
}
| true |
bd7e189e4705ed9f4a839a6ea706e582c14b9fb4 | Java | Wei-Changsha/MyMusic | /app/src/main/java/com/example/musicandroid/bean/SongList.java | UTF-8 | 712 | 2.21875 | 2 | [] | no_license | package com.example.musicandroid.bean;
import java.util.List;
public class SongList {
private int id;
private String listName;
private List<Integer> listId;
public SongList(String listName) {
this.listName = listName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getListName() {
return listName;
}
public void setListName(String listName) {
this.listName = listName;
}
public List<Integer> getListId() {
return listId;
}
public void setListId(List<Integer> listId) {
this.listId = listId;
}
}
| true |
59df23387322b9165b30d2803b22d80adc1c6ec3 | Java | soldiers1989/proXX | /pinyougou/pinyougou-dao/src/main/java/com/pinyougou/mapper/SpecificationMapper.java | UTF-8 | 430 | 2 | 2 | [] | no_license | package com.pinyougou.mapper;
import com.pinyougou.pojo.TbSpecification;
import tk.mybatis.mapper.common.Mapper;
import java.util.List;
import java.util.Map;
public interface SpecificationMapper extends Mapper<TbSpecification> {
/**
* 查询规格列表;结构如:[{"id":27,"text":"网络"},{"id":32,"text":"机身内存"}]
* @return 规格列表
*/
List<Map<String, String>> selectOptionList();
}
| true |
a47074aac5fc1eab5ee3e08dc43ec310c6935341 | Java | nicolake/Gestion-de-Alumnos-Spring | /src/main/java/dev/nicolake/sistemaalumnos/service/api/CursoServiceAPI.java | UTF-8 | 398 | 1.90625 | 2 | [] | no_license | package dev.nicolake.sistemaalumnos.service.api;
import dev.nicolake.sistemaalumnos.commons.GenericServiceAPI;
import dev.nicolake.sistemaalumnos.model.Carrera;
import dev.nicolake.sistemaalumnos.model.Curso;
import java.util.List;
public interface CursoServiceAPI extends GenericServiceAPI<Curso, Integer> {
List<Curso> getCursosDisponibles(List<Integer> cursos, List<Carrera> carreras);
}
| true |
bc3ccc3d427a5213264c89aef0fa9bedae84d2a1 | Java | alpha-pluto/AlibabaSDK-java | /src/me/dan/alibabasdk/serialize/DefaultSerializerProvider.java | UTF-8 | 1,282 | 1.882813 | 2 | [] | no_license | package me.dan.alibabasdk.serialize;
import me.dan.alibabasdk.serialize.impl.HttpDeserializer;
import me.dan.alibabasdk.serialize.impl.HttpRequestSerializer;
import me.dan.alibabasdk.serialize.impl.Json2Deserializer;
import me.dan.alibabasdk.serialize.impl.JsonDeserializer;
import me.dan.alibabasdk.serialize.impl.Param2Deserializer;
import me.dan.alibabasdk.serialize.impl.Param2RequestSerializer;
import me.dan.alibabasdk.serialize.impl.ParamDeserializer;
import me.dan.alibabasdk.serialize.impl.ParamRequestSerializer;
import me.dan.alibabasdk.serialize.impl.Xml2Deserializer;
/**
* @Title: DefaultSerializerProvider.java
* @Package me.dan.alibabasdk.serialize
* @Description: TODO
* @author daniel
* @email daniel.zhang.china#hotmail.com
* @date 2018-07-04 下午4:33:47
* @version 0.0.1
*/
public class DefaultSerializerProvider extends SerializerProvider {
public DefaultSerializerProvider() {
register(new Xml2Deserializer());
register(new JsonDeserializer());
register(new ParamDeserializer());
register(new Param2Deserializer());
register(new Json2Deserializer());
register(new HttpDeserializer());
register(new HttpRequestSerializer());
register(new ParamRequestSerializer());
register(new Param2RequestSerializer());
}
}
| true |
090a2dcb6afaae822f60b2187aec2ef295358f67 | Java | tengtcai/wxguanjia | /app/src/main/java/com/android/hjq/wxmanager/utils/SpUtils.java | UTF-8 | 3,185 | 2.140625 | 2 | [] | no_license | package com.android.hjq.wxmanager.utils;
import android.text.TextUtils;
import com.android.hjq.wxmanager.model.QunInfo;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.Utils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
/**
* SharedPreferences使用工具类
*/
public class SpUtils {
static SPUtils mSPUtils = SPUtils.getInstance(Utils.getApp().getPackageName());
public static boolean isFirstStart() {
return mSPUtils.getBoolean("FirstStart", false);
}
public static boolean isDestory(){
return mSPUtils.getBoolean("isDestory",false);
}
public static void setFirstStart(boolean isFirst){
mSPUtils.put("FirstStart",isFirst);
}
public static void setDestory(boolean isDestory){
mSPUtils.put("isDestory",isDestory);
}
public static void saveBiaoQian(String biaoqian){
mSPUtils.put("biaoqian",biaoqian);
}
public static String getBiaoQian(){
return mSPUtils.getString("biaoqian");
}
public static void saveType(int type){
mSPUtils.put("type",type);
}
public static int getType(){
return mSPUtils.getInt("type");
}
public static void saveImage(String img){
mSPUtils.put("image",img);
}
public static String getImage(){
return mSPUtils.getString("image");
}
public static void saveSay(List<String> list){
mSPUtils.put("say_hello",new Gson().toJson(list));
}
public static List<String> getSay(){
String str = mSPUtils.getString("say_hello");
List<String> strings = new Gson().fromJson(str,new TypeToken<List<String>>(){}.getType());
if(strings == null){
strings = new ArrayList<>();
}
return strings;
}
public static void saveQunList(List<QunInfo> list){
mSPUtils.put("qun_list",new Gson().toJson(list));
}
public static List<QunInfo> getQunList(){
String str = mSPUtils.getString("qun_list");
List<QunInfo> qunInfos = new Gson().fromJson(str,new TypeToken<List<QunInfo>>(){}.getType());
if(qunInfos == null){
qunInfos = new ArrayList<>();
}
return qunInfos;
}
public static void saveSelectQunList(List<QunInfo> list){
mSPUtils.put("select_qun_list",new Gson().toJson(list));
}
public static List<QunInfo> getSelectQunList(){
String str = mSPUtils.getString("select_qun_list");
List<QunInfo> qunInfos = new Gson().fromJson(str,new TypeToken<List<QunInfo>>(){}.getType());
if(qunInfos == null){
qunInfos = new ArrayList<>();
}
return qunInfos;
}
public static void saveIsTimeTask(boolean isTimeTask){
mSPUtils.put("isTimeTask",isTimeTask);
}
public static boolean getIsTimeTask(){
return mSPUtils.getBoolean("isTimeTask");
}
}
| true |
1c3e4d44338c2c64702abe0c1614c414bd09cec2 | Java | TextappOrg/FriendManagementService | /src/main/java/UtilityPackage/MongoDbConnectionClass.java | UTF-8 | 1,679 | 2.421875 | 2 | [] | no_license | package UtilityPackage;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;
public class MongoDbConnectionClass {
public static MongoCollection getMongoDocUsers()throws NamingException{
return getMongoDoc("RestServiceAuthMongoDbConnDetails","Collection_Name","Database_Name","Connection_String");
}
public static MongoCollection getMongoDocFriendsOfUsers() throws NamingException {
return getMongoDoc("RestServiceGroupMongoDbConnDetails","Friends_Collection_Name","Friends_Database_Name","Friends_Connection_String");
}
public static MongoCollection getMongoDocFriendsOfUsersCached() throws NamingException {
return getMongoDoc("RestServiceGroupMongoDbConnDetails","Friends_Cached_Collection_Name","Friends_Database_Name","Friends_Connection_String");
}
private static MongoCollection getMongoDoc(String propertiesName, String collectionName, String dbName,
String connectionString) throws NamingException {
InitialContext context = new InitialContext();
Properties properties = (Properties) context.lookup(propertiesName);
String connection_string = properties.getProperty(connectionString);
String collection_name = properties.getProperty(collectionName);
String db_name = properties.getProperty(dbName);
return new MongoClient(new MongoClientURI(connection_string))
.getDatabase(db_name).
getCollection(collection_name);
}
}
| true |
3d059f114389c4af216562c9a18529be5c2aa1cb | Java | pranathirayala/pranathi_e6 | /src/src/StudentGroup.java | UTF-8 | 9,796 | 3.515625 | 4 | [] | no_license | import java.util.Date;
import java.lang.Exception;
import java.util.*;
import java.util.ArrayList;
/**
* A fix-sized array of students
* array length should always be equal to the number of stored elements
* after the element was removed the size of the array should be equal to the number of stored elements
* after the element was added the size of the array should be equal to the number of stored elements
* null elements are not allowed to be stored in the array
* <p>
* You may add new methods, fields to this class, but DO NOT RENAME any given class, interface or method
* DO NOT PUT any classes into packages
*/
public class StudentGroup implements StudentArrayOperation {
private Student[] students;
private static int noOfStudents = 0;
/**
* DO NOT remove or change this constructor, it will be used during task check
*
* @param length
*/
public StudentGroup(int length) {
this.students = new Student[length];
}
@Override
public Student[] getStudents() {
// Add your implementation here
return students;
}
@Override
public void setStudents(Student[] students) {
// Add your implementation here
if (students == null)
throw new IllegalArgumentException();
for (int i = 0; i < students.length; i++)
this.students[i] = students[i];
}
@Override
public Student getStudent(int index) {
// Add your implementation here
if (index < 0 || index >= students.length)
throw new IllegalArgumentException();
else
return students[index];
}
@Override
public void setStudent(Student student, int index) {
// Add your implementation here
if (student == null || index < 0 || index >= students.length)
throw new IllegalArgumentException();
else
students[index] = student;
}
@Override
public void addFirst(Student student) {
// Add your implementation here
if (student == null || students.length == noOfStudents)
throw new IllegalArgumentException();
for (int i = noOfStudents; i > 0; i--) {
students[i] = students[i-1];
}
students[0] = student;
noOfStudents++;
}
@Override
public void addLast(Student student) {
// Add your implementation here
if (student == null || students.length == noOfStudents)
throw new IllegalArgumentException();
students[noOfStudents] = student;
noOfStudents++;
}
@Override
public void add(Student student, int index) {
// Add your implementation here
if (student == null || index < 0 || index >= students.length)
throw new IllegalArgumentException();
students[index] = student;
noOfStudents++;
}
@Override
public void remove(int index) {
// Add your implementation here
if (index < 0 || index >= students.length)
throw new IllegalArgumentException();
for(int i=index; i < noOfStudents ;i++) {
students[i] = students[i+1];
}
students[noOfStudents] = null;
noOfStudents--;
}
@Override
public void remove(Student student) {
// Add your implementation here
if (student == null)
throw new IllegalArgumentException();
for (int i = 0; i < noOfStudents; i++) {
if (students[i].equals(student)) {
remove(i);
break;
}
}
}
@Override
public void removeFromIndex(int index) {
// Add your implementation here
if (index < 0 || index >= students.length)
throw new IllegalArgumentException();
else {
for (int i = index; i < noOfStudents; i++) {
students[i] = null;
noOfStudents--;
}
}
}
@Override
public void removeFromElement(Student student) {
// Add your implementation here
int pos = 0;
if (student == null)
throw new IllegalArgumentException();
for (int i = 0; i < noOfStudents; i++) {
if (students[i].equals(student)) {
removeFromIndex(i);
break;
}
}
}
@Override
public void removeToIndex(int index) {
// Add your implementation here
if (index < 0 || index >= students.length)
throw new IllegalArgumentException();
for (int i = 0; i <= index; i++) {
remove(i);
}
}
@Override
public void removeToElement(Student student) {
// Add your implementation here
int pos = 0;
if (student == null)
throw new IllegalArgumentException();
for (int i = 0; i < noOfStudents; i++) {
if (students[i].equals(student)) {
removeToIndex(i);
}
}
}
@Override
public void bubbleSort() {
// Add your implementation here
int n = students.length;
Student temp;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (students[j - 1].id > students[j].id) {
temp = students[j - 1].id;
students[j - 1].id = students[j].id;
students[j].id = temp;
}
}
}
}
@Override
public Student[] getByBirthDate(Date date) {
// Add your implementation here
Student[] st3 = new Student[students.length];
if (date == null)
throw new IllegalArgumentException();
int j = 0;
for (int i = 0; i < noOfStudents; i++) {
if (students[i].getBirthDate().equals(date)) {
st3[j] = students[i];
j++;
}
}
return st3;
}
@Override
public Student[] getBetweenBirthDates(Date firstDate, Date lastDate) {
// Add your implementation here
Student[] st1;
if (firstDate == null || lastDate == null)
throw new IllegalArgumentException();
else {
for (int i = 0; i < students.length; i++) {
if (((students[i].getBirthDate()) >= firstDate) ||((students[i].getBirthDate()) <= lastDate))
st1.set(students[i]);
}
}
return st1;
}
@Override
public Student[] getNearBirthDate(Date date, int days) {
// Add your implementation here
Student[] st2 = new Student[students.length];
if (date.equals(null))
throw new IllegalArgumentException();
else {
for (int i = 0; i < students.length; i++) {
if(((students[i].getBirthDate()).equals(date)) || ((students[i].getBirthDate()).equals(date.getDay() + days)))
st2.add(students[i]);
}
}
return st2;
}
@Override
public int getCurrentAgeByDate(int indexOfStudent) {
// Add your implementation here
int age;
if (indexOfStudent == 0)
throw new IllegalArgumentException();
else {
Calendar t = Calendar.getInstance();
int cy = t.get(Calendar.YEAR);
int dy = students[indexOfStudent].getBirthDate().get(Calendar.YEAR);
age = cy - dy;
int cm = t.get(Calendar.MONTH);
int dm = students[indexOfStudent].getBirthDate().get(Calendar.MONTH);
if (dm > cm)
age--;
else if (dm == cm) {
int cd = t.get(Calendar.DAY_OF_MONTH);
int dd = students[indexOfStudent].getBirthDate().get(Calendar.DAY_OF_MONTH);
if (dd > cd)
age--;
}
}
return age;
}
@Override
public Student[] getStudentsByAge(int age) {
// Add your implementation here
Student[] st;
for (int i = 0; i < students.length; i++) {
int reqage = getCurrentAgeByDate(i);
if (reqage == age)
st.add(students[i]);
return st;
}
}
@Override
public Student[] getStudentsWithMaxAvgMark() {
// Add your implementation here
Student[] temp = new Student[students.length];
Student[] st;
for (int i = 0; i < temp.length; i++) {
int index = i;
for (int j = i + 1; j < temp.length; j++) {
if (temp[j].compareTo(temp[index]) == 1) {
index = j;
}
}
Student small = temp[index];
temp[index] = temp[i];
temp[i] = small;
}
for (int i = 0; i < temp.length; i++) {
if ((temp[temp.length - 1]).getAvgMark() == temp[i].getAvgMark())
st.add(temp[i]);
}
return st;
}
@Override
public Student getNextStudent(Student student) {
// Add your implementation here
Student[] st8;
if (student == null)
throw new IllegalArgumentException();
else {
for (int i = 0; i < students.length; i++) {
if (students[i].getId() == student.getId()) {
student = students[i + 1];
return student;
}
}
}
}
}
| true |
1313fd6215dfe20440c1b12c517cdc4c4f2e6c18 | Java | yihanw/JAVA-Program | /src/IOAssingment1_Jane.java | UTF-8 | 5,273 | 3.9375 | 4 | [] | no_license | /*Jane Wang
May 2, 2014
ICS3U1-01
This program generates 20 random numbers from 35 to 95, print them on a file named "data01", then copies the numbers to a file named "data02",
and then adds first name and last name for every 4 numbers, and prints them on a single line, use tokenizer to calculate the average for each student*/
// The "IOAssingment1_Jane" class.
import java.awt.*;
import java.io.*;
import java.util.*;
import hsa.Console;
public class IOAssingment1_Jane
{
static Console c; // The output console
public static void main (String[] args)
{
c = new Console ();
int total = 0; //total of the 20 numbers
int totalAverage = 0; //average for the 20 numbers
int[] number = new int [20]; //20 random numbers
//PART A
try
{
FileWriter fw1 = new FileWriter ("data01.txt"); //create a file named data01
PrintWriter pw1 = new PrintWriter (fw1); //set up the print writer for data01
for (int i = 0 ; i < 20 ; i++)
{
number [i] = (int) (Math.random () * 60 + 35); //generate 20 integers
pw1.println (number [i]); //print the integers on the file
c.println (number [i]);
total = total + number [i]; //add up all the integers
}
totalAverage = total / 20; //calculate the average
c.println ("average for all 20 integer is " + totalAverage);
pw1.println ("average = " + totalAverage); //print the overall average ont the file
pw1.close ();
}
catch (IOException e)
{
} //end of data01
//PART B&C
//assign first name and last name
String[] firstName = new String [5];
firstName [0] = "abcd ";
firstName [1] = "efgh ";
firstName [2] = "ijkl ";
firstName [3] = "mnop ";
firstName [4] = "qrst ";
String[] lastName = new String [5];
lastName [0] = "ABCD";
lastName [1] = "EFGH";
lastName [2] = "IJKL";
lastName [3] = "MNOP";
lastName [4] = "QRST";
//print first names, last names and marks on a line
try //create a file writer for data02
{
FileWriter fw2 = new FileWriter ("data02.txt"); //set up file writer for data02
PrintWriter pw2 = new PrintWriter (fw2); //set up print writer for data02
//information about first student
pw2.print (firstName [0] + lastName [0] + " ");
for (int i = 0 ; i < 4 ; i++)
{
pw2.print (number [i] + " ");
}
pw2.println ();
//information about second student
pw2.print (firstName [1] + lastName [1] + " ");
for (int i = 4 ; i < 8 ; i++)
{
pw2.print (number [i] + " ");
}
pw2.println ();
//information about third student
pw2.print (firstName [2] + lastName [2] + " ");
for (int i = 8 ; i < 12 ; i++)
{
pw2.print (number [i] + " ");
}
pw2.println ();
//information about forth student
pw2.print (firstName [3] + lastName [3] + " ");
for (int i = 12 ; i < 16 ; i++)
{
pw2.print (number [i] + " ");
}
pw2.println ();
//information about fifth student
pw2.print (firstName [4] + lastName [4] + " ");
for (int i = 16 ; i < 20 ; i++)
{
pw2.print (number [i] + " ");
}
pw2.println ();
pw2.close (); //end of file printer for data02
//PART D
String fName = null, lName = null; //used to store the names
int sum = 0; //sum for each student
int average = 0; //average for each student
try //create a file reader for data02
{
FileReader fr = new FileReader ("data02.txt"); //set up the file reader for data02
BufferedReader br = new BufferedReader (fr); //set up the buffered reader for data02
String line = null; //string that read in values in data02
line = br.readLine (); //used to store data from data02
while (line != null) //read the value to file reader
{
int i = 0;
//use tokenizer to find the average for each student
StringTokenizer st = new StringTokenizer (line); //tokenize the string from data02
while (st.hasMoreTokens ())
{
if (i == 0) //the first token is the first name
{
fName = st.nextToken (); //store the first name
}
else if (i == 1) //the second token is the last name
{
lName = st.nextToken (); //store the last name
}
else
{
for (int j = 0 ; j < 4 ; j++) //for loop is used for calculate the sum for each student
{
int nextNumber = Integer.parseInt (st.nextToken ()); //parse string into integer
sum = sum + nextNumber; //calculate the sum for each student
}
average = sum / 4; //calculate the average for each student
c.println ("average of " + fName + " " + lName + " is " + average); //print the result on the screen
}
i++; //allow the loop to run again for the next student
sum = 0; //set sum to zero in order to calculate the average for next student
}
line = br.readLine (); //read the second string from data02 and repeat the loop to calculate and diaplay the results
}
br.close (); //end of file reader
} //end of file reader for data02
catch (IOException e)
{
}
} //end of file writer for data02
catch (IOException e)
{
}
} // main method
} // IOAssingment1_Jane class
| true |
b7b039527c33bd537a0313d05c41e1c33956a998 | Java | lujunlj/yiyoushop | /yiyou-shop-common/beetlsql/src/main/java/org/beetl/sql/core/orm/LazyEntity.java | UTF-8 | 110 | 1.609375 | 2 | [] | no_license | package org.beetl.sql.core.orm;
public interface LazyEntity extends java.io.Serializable {
Object get();
}
| true |
0bb1716146263ef2831f8c43f11ff22ece17a1cd | Java | AlenPan/AndroidStudioTestProject | /ActivityLifeCycleTest/app/src/main/java/com/example/activitylifecycletest/DialogActivity.java | UTF-8 | 673 | 2.078125 | 2 | [] | no_license | package com.example.activitylifecycletest;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class DialogActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_layout);
}
public void actionStart(Context context, String data1, String data2) {
Intent intent = new Intent(context, this.getClass());
intent.putExtra("param1", data1);
intent.putExtra("param2", data2);
context.startActivity(intent);
}
}
| true |
437ef8ae1e484a95a4f2219fc6eccfbdd3b2323a | Java | chipster/chipster | /src/main/web/admin-web/src/fi/csc/chipster/web/adminweb/data/JobsContainer.java | UTF-8 | 2,324 | 2.0625 | 2 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package fi.csc.chipster.web.adminweb.data;
import java.io.IOException;
import java.io.Serializable;
import java.util.Collection;
import javax.jms.JMSException;
import org.apache.log4j.Logger;
import com.vaadin.data.util.BeanItemContainer;
import fi.csc.chipster.web.adminweb.ui.JobsView;
import fi.csc.microarray.config.ConfigurationLoader.IllegalConfigurationException;
import fi.csc.microarray.exception.MicroarrayException;
import fi.csc.microarray.messaging.AuthCancelledException;
import fi.csc.microarray.messaging.admin.JobmanagerAdminAPI;
import fi.csc.microarray.messaging.admin.JobmanagerAdminAPI.JobsListener;
import fi.csc.microarray.messaging.admin.JobsEntry;
public class JobsContainer extends BeanItemContainer<JobsEntry> implements Serializable, JobsListener {
private static final Logger logger = Logger.getLogger(JobsContainer.class);
public static final String USERNAME = "username";
public static final String OPERATION = "operation";
public static final String STATUS = "status";
public static final String COMPHOST = "compHost";
public static final String START_TIME = "startTime";
public static final String CANCEL_LINK = "cancelLink";
public static final Object[] NATURAL_COL_ORDER = new String[] {
USERNAME, OPERATION, STATUS, COMPHOST, START_TIME, CANCEL_LINK };
public static final String[] COL_HEADERS_ENGLISH = new String[] {
"Username", "Operation", "Status", "Comp host", "Start time", "" };
private JobmanagerAdminAPI jobmanagerAdminAPI;
private JobsView view;
public JobsContainer(JobsView view, JobmanagerAdminAPI jobmanagerAdminAPI) throws IOException, IllegalConfigurationException, MicroarrayException, JMSException {
super(JobsEntry.class);
this.view = view;
this.jobmanagerAdminAPI = jobmanagerAdminAPI;
}
public void update() {
try {
Collection<JobsEntry> list = jobmanagerAdminAPI.queryRunningJobs().values();
statusUpdated(list);
} catch (JMSException | InterruptedException | MicroarrayException | AuthCancelledException e) {
logger.error(e);
}
}
@Override
public void statusUpdated(final Collection<JobsEntry> jobs) {
view.updateUI(new Runnable() {
@Override
public void run() {
removeAllItems();
for (JobsEntry entry : jobs) {
addBean(entry);
}
}
});
}
} | true |
deda374c7e14466191aef969ceff7a459ea203de | Java | kwt1326/shoppingmall_spring_boot | /src/main/java/com/kwtproject/shoppingmall/domain/ProductReviewEntity.java | UTF-8 | 908 | 2.171875 | 2 | [] | no_license | package com.kwtproject.shoppingmall.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Getter;
import org.hibernate.annotations.CreationTimestamp;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.List;
@Entity
@Getter
@Table(name = "product_review")
public class ProductReviewEntity extends EntityBase {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "product_id")
private ProductEntity product;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_review_id")
private ProductReviewEntity parent;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "parent")
private List<ProductReviewEntity> reviews;
private String content;
@Column(name = "rating")
private short starRating;
@JsonFormat(pattern = "yyyy-MM-dd")
@Column(name = "published_at")
private LocalDateTime publishedAt;
}
| true |
6d36fc5496ed8b87daeec8e8f71a2874b4546dd9 | Java | YunitaAmelia/SI2040-Proyek2 | /Page.java | UTF-8 | 1,332 | 1.96875 | 2 | [] | no_license | package com.example.huffaznote;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
public class Page extends AppCompatActivity {
private Button tambah_bacaan;
private Button logout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page);
tambah_bacaan = findViewById(R.id.tambah_bacaan);
logout = findViewById(R.id.logout);
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Toast.makeText(Page.this, "Berhasil Logout", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Page.this, StartActivity.class));
}
});
tambah_bacaan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Page.this, MainActivity.class));
finish();
}
});
}
} | true |
a39a073b9beb9aadff775a05f9b522d87b9a7e6d | Java | 995270418L/java_learn | /src/main/java/com/steve/designModule/ProxyModule/Classes/Logger.java | UTF-8 | 741 | 3.015625 | 3 | [] | no_license | package com.steve.designModule.ProxyModule.Classes;
import java.text.SimpleDateFormat;
/**
* Created by liu on 4/1/17.
* 日志记录类(代理过程中需要添加的内容) 代理模式关键类
*/
public class Logger{
public void beforeMethod(String name) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(System.currentTimeMillis());
System.out.println("方法: " +name + "() 被调用,调用时间为: "+time);
}
public void afterMethod(String name) {
System.out.println("方法: "+ name + "() 调用成功");
}
public void afterMethodError(String name) {
System.out.println("方法: " +name + "() 调用失败");
}
}
| true |
a3f88ecf73249cdb53ba49a034875c3aed4b341f | Java | pszerszen/projekt-programistyczny | /src/miniGames/ships/MyInfoFrame.java | UTF-8 | 4,857 | 2.59375 | 3 | [
"MIT"
] | permissive | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package miniGames.ships;
import javax.swing.JLabel;
/**
* Information Frame
*
* @author Wojtek
*/
@SuppressWarnings("serial")
public class MyInfoFrame extends javax.swing.JFrame {
/**
* @param args
* the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
// <editor-fold defaultstate="collapsed"
// desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase
* /tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException
| javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MyInfoFrame.class.getName())
.log(java.util.logging.Level.SEVERE, null, ex);
}
// </editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MyInfoFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel Message;
private javax.swing.JButton Ok;
private javax.swing.JLabel Title;
// End of variables declaration//GEN-END:variables
/**
* Creates new form MyInfoFrame
*/
public MyInfoFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed"
// desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
Ok = new javax.swing.JButton();
Title = new javax.swing.JLabel();
Message = new javax.swing.JLabel();
setMinimumSize(new java.awt.Dimension(200, 150));
setResizable(false);
Ok.setText("OK");
Ok.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OkActionPerformed(evt);
}
});
Title.setText("Informacja");
Message.setText("jLabel2");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addContainerGap()
.addGroup(
layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(
Message,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(
Title,
javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addGroup(
layout.createSequentialGroup()
.addGap(0,
106,
Short.MAX_VALUE)
.addComponent(
Ok,
javax.swing.GroupLayout.PREFERRED_SIZE,
74,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap()));
layout.setVerticalGroup(layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addContainerGap()
.addComponent(Title,
javax.swing.GroupLayout.PREFERRED_SIZE,
24,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Message,
javax.swing.GroupLayout.PREFERRED_SIZE,
23,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Ok)
.addContainerGap(57, Short.MAX_VALUE)));
pack();
}// </editor-fold>//GEN-END:initComponents
private void OkActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_OkActionPerformed
this.setVisible(false);
}
public JLabel getMessage() {
return Message;
}// GEN-LAST:event_OkActionPerformed
}
| true |
6bf5fd7d438cf9b442fa701eeb580c3cf50f4a03 | Java | amanraihot/Discuss | /src/main/java/com/example/Discuss/Controller/QuestionController.java | UTF-8 | 1,151 | 2.234375 | 2 | [] | no_license | package com.example.Discuss.Controller;
import com.example.Discuss.service.QuestionCreateService;
import com.example.Discuss.dto.QuestionDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/Question")
public class QuestionController {
static int hit = 0;
@Autowired
private QuestionCreateService questionCreateService;
@PostMapping("/ask")
public ResponseEntity<?> addQuestion(@RequestBody QuestionDto questionDto)
{
hit++;
System.out.println("hit");
return questionCreateService.addQuestion(questionDto);
}
@PostMapping("/update/{id}")
public ResponseEntity<?> update(@PathVariable String id, @RequestBody QuestionDto questionDto)
{
return questionCreateService.update(Long.parseLong(id), questionDto);
}
@PostMapping("/delete/{id}")
public ResponseEntity<?> delete(@PathVariable String id, @RequestBody QuestionDto questionDto)
{
return questionCreateService.delete(Long.parseLong(id));
}
}
| true |
a149e35c30de8b08430ec1e0d99db2e3d61bb07e | Java | Dorisliy/ssmpro | /src/main/java/cn/ssm/project/pojo/MProductWithBLOBs.java | UTF-8 | 4,031 | 2.078125 | 2 | [] | no_license | package cn.ssm.project.pojo;
public class MProductWithBLOBs extends MProduct {
private String documentnote;
private String help;
private String bulletPoint1;
private String bulletPoint2;
private String bulletPoint3;
private String bulletPoint4;
private String bulletPoint5;
private String genericKeywords1;
private String genericKeywords2;
private String genericKeywords3;
private String genericKeywords4;
private String genericKeywords5;
private String targetAudienceKeywords;
private String productDescription;
private String moreDetails;
public String getDocumentnote() {
return documentnote;
}
public void setDocumentnote(String documentnote) {
this.documentnote = documentnote == null ? null : documentnote.trim();
}
public String getHelp() {
return help;
}
public void setHelp(String help) {
this.help = help == null ? null : help.trim();
}
public String getBulletPoint1() {
return bulletPoint1;
}
public void setBulletPoint1(String bulletPoint1) {
this.bulletPoint1 = bulletPoint1 == null ? null : bulletPoint1.trim();
}
public String getBulletPoint2() {
return bulletPoint2;
}
public void setBulletPoint2(String bulletPoint2) {
this.bulletPoint2 = bulletPoint2 == null ? null : bulletPoint2.trim();
}
public String getBulletPoint3() {
return bulletPoint3;
}
public void setBulletPoint3(String bulletPoint3) {
this.bulletPoint3 = bulletPoint3 == null ? null : bulletPoint3.trim();
}
public String getBulletPoint4() {
return bulletPoint4;
}
public void setBulletPoint4(String bulletPoint4) {
this.bulletPoint4 = bulletPoint4 == null ? null : bulletPoint4.trim();
}
public String getBulletPoint5() {
return bulletPoint5;
}
public void setBulletPoint5(String bulletPoint5) {
this.bulletPoint5 = bulletPoint5 == null ? null : bulletPoint5.trim();
}
public String getGenericKeywords1() {
return genericKeywords1;
}
public void setGenericKeywords1(String genericKeywords1) {
this.genericKeywords1 = genericKeywords1 == null ? null : genericKeywords1.trim();
}
public String getGenericKeywords2() {
return genericKeywords2;
}
public void setGenericKeywords2(String genericKeywords2) {
this.genericKeywords2 = genericKeywords2 == null ? null : genericKeywords2.trim();
}
public String getGenericKeywords3() {
return genericKeywords3;
}
public void setGenericKeywords3(String genericKeywords3) {
this.genericKeywords3 = genericKeywords3 == null ? null : genericKeywords3.trim();
}
public String getGenericKeywords4() {
return genericKeywords4;
}
public void setGenericKeywords4(String genericKeywords4) {
this.genericKeywords4 = genericKeywords4 == null ? null : genericKeywords4.trim();
}
public String getGenericKeywords5() {
return genericKeywords5;
}
public void setGenericKeywords5(String genericKeywords5) {
this.genericKeywords5 = genericKeywords5 == null ? null : genericKeywords5.trim();
}
public String getTargetAudienceKeywords() {
return targetAudienceKeywords;
}
public void setTargetAudienceKeywords(String targetAudienceKeywords) {
this.targetAudienceKeywords = targetAudienceKeywords == null ? null : targetAudienceKeywords.trim();
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription == null ? null : productDescription.trim();
}
public String getMoreDetails() {
return moreDetails;
}
public void setMoreDetails(String moreDetails) {
this.moreDetails = moreDetails == null ? null : moreDetails.trim();
}
} | true |
0778f3a56c170ce23cf4805d95f2aa1f53a14ce6 | Java | cmdream/springboot-example | /spring-api/src/main/java/com/spring/application/Application.java | UTF-8 | 914 | 1.804688 | 2 | [] | no_license | package com.spring.application;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableSwagger2
public class Application {
public static void main(String[] args) {
// SpringApplication.run(Application.class, args);
//关闭Springboot的console打印
SpringApplication springApplication = new SpringApplication(Application.class);
springApplication.setBannerMode(Banner.Mode.OFF);
springApplication.run(args);
// System.out.println("springboot");
// String name = ParamController.class.getPackage().getName();
// System.out.println(name);
}
}
| true |
82cd0e2f9b0e72d4d9893b52fce65e4a3869c002 | Java | ederphil/curso_programacao | /src/entities/PessoalFisica_131.java | UTF-8 | 624 | 2.703125 | 3 | [] | no_license | package entities;
public class PessoalFisica_131 extends Pessoa_132 {
private double gastosSaude;
public PessoalFisica_131(String nome, double rendaAnual, double gastosSaude) {
super(nome, rendaAnual);
this.gastosSaude = gastosSaude;
}
public double getGastosSaude() {
return gastosSaude;
}
public void setGastosSaude(double gastosSaude) {
this.gastosSaude = gastosSaude;
}
@Override
public double calculaImposto() {
double percImp = super.rendaAnual < 20000 ? 15 : 25;
return (super.rendaAnual * percImp / 100) - (gastosSaude > 0 ? (gastosSaude * 50 / 100) : 0);
};
}
| true |
5c47371b55c1f1baa7c70dd0f4a8544ad32fc9fa | Java | Beata-Ficek/w6_d3_card_game_lab | /src/test/java/CardTest.java | UTF-8 | 710 | 2.828125 | 3 | [] | no_license | import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CardTest {
Card aceOfSpades;
@Before
public void before(){
aceOfSpades = new Card(SuiteType.SPADES, NumberType.ACE);
}
@Test
public void cardHasSuite(){
assertEquals(SuiteType.SPADES, aceOfSpades.getSuite());
}
@Test
public void cardHasNumber(){
assertEquals(NumberType.ACE, aceOfSpades.getNumber());
}
@Test
public void cardHasNumberValue() {
assertEquals(12, aceOfSpades.getNumber().getRank());
}
@Test
public void cardHasSuiteValue(){
assertEquals(3, aceOfSpades.getSuite().getRank());
}
}
| true |
36aa6ce9ef83686826a610cb2adf6db8703ab716 | Java | angeloBerlin/MIDI-Automator | /Midi Automator/src/main/java/com/midi_automator/view/windows/PreferencesDialog/GUIAutomationPanel/GUIAutomationTable/JTableKeyTextRenderer.java | UTF-8 | 773 | 2.421875 | 2 | [
"MIT"
] | permissive | package com.midi_automator.view.windows.PreferencesDialog.GUIAutomationPanel.GUIAutomationTable;
import java.util.regex.Pattern;
import com.midi_automator.utils.CommonUtils;
/**
* CellRenderer for key code representation
*
* @author aguelle
*
*/
class JTableKeyTextRenderer extends JTableNonEditableRenderer {
private static final long serialVersionUID = 1L;
@Override
public void setText(String text) {
String keys = "";
if (text != null) {
if (!text.equals("")) {
String[] keyCodeStrings = text.split(Pattern
.quote(GUIAutomationTable.KEYS_DELIMITER));
int[] keyCodes = CommonUtils
.stringArrayToIntArray(keyCodeStrings);
keys = GUIAutomationTable
.keyCodesToString(keyCodes);
}
}
super.setText(keys);
}
} | true |
912cd24c3e703458dc612ba7a3ef1a4711f05718 | Java | Mapsred/ESGI4_JavaEE-Dressing | /src/utils/Manager.java | UTF-8 | 966 | 2.578125 | 3 | [] | no_license | package utils;
import entity.ClotheEntity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
@SuppressWarnings({"WeakerAccess", "UnusedReturnValue"})
public class Manager {
private EntityManager em;
public Manager() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("JavaEE-Clothes");
em = emf.createEntityManager();
em.getTransaction().begin();
}
public static Manager init() {
return new Manager();
}
public ClotheEntity createTestClothe() {
ClotheEntity clotheEntity = new ClotheEntity();
clotheEntity.setDescription("Thorben");
clotheEntity.setPrice(10.2);
clotheEntity.setSellerCode("FMA");
clotheEntity.setSize("Medium");
em.persist(clotheEntity);
return clotheEntity;
}
public void flush() {
em.getTransaction().commit();
}
}
| true |
ddac7326f9e70b8f97fd57cf3782df520713aab8 | Java | devigrenadine/hotelboooking | /src/test/java/com/evi/hotelbooking/controller/BookingControllerTest.java | UTF-8 | 2,283 | 2.171875 | 2 | [] | no_license | package com.evi.hotelbooking.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import java.math.BigDecimal;
import java.util.Optional;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.evi.hotelbooking.model.Booking;
import com.evi.hotelbooking.model.Hotel;
import com.evi.hotelbooking.repository.BookingRepository;
import com.evi.hotelbooking.repository.HotelRepository;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class BookingControllerTest {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@MockBean
BookingRepository bookRepo;
@Before
public void setUp() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
@Test
public void testCreateBooking() throws Exception {
Long id = (long) 1;
String customerName = "Batida";
String customerSurname = "deCoco";
Integer numberOfPax = 6;
double amount = 123.56;
String currency = "Eur";
mvc.perform(post("/hotels/1/bookings")
.param("id", Long.toString(id))
.param("customerName", customerName)
.param("customerSurname", customerSurname)
.param("numberOfPax", Integer.toString(numberOfPax))
.param("amount", Double.toString(amount))
.param("currency", currency));;
Optional<Booking> booking = bookRepo.findById(id);
Assert.assertTrue(booking != null);
}
@Test
public void testdeleteBooking() throws Exception {
Long id = (long) 1;
mvc.perform(delete("/hotels/1/bookings/")
.param("id", Long.toString(id)));;
Optional<Booking> booking = bookRepo.findById(id);
Assert.assertTrue(booking.isPresent() == false);
}
} | true |
43a797f9357d63b22cc4ed64444b6075d403b705 | Java | i5possible/spring-snippet | /src/main/java/concurrency/container/DemoProducer.java | UTF-8 | 961 | 3.109375 | 3 | [
"Apache-2.0"
] | permissive | package concurrency.container;
import java.util.concurrent.BlockingQueue;
/**
* @author lianghong
* @date 2019/3/25
*/
public class DemoProducer implements Runnable{
private final BlockingQueue<DemoMessage> blockingQueue;
public DemoProducer(BlockingQueue<DemoMessage> blockingQueue) {
this.blockingQueue = blockingQueue;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
DemoMessage msg = new DemoMessage("" + i);
try {
blockingQueue.put(msg);
System.out.println("Produced:" + i);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Produce Interrupted");
}
}
DemoMessage exit = new DemoMessage("exit");
try {
blockingQueue.put(exit);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| true |
fd65a8287f73b7fe970f94340f40f06b0515f42d | Java | jicheol-shin/himediaMesB | /src/main/java/com/mes/dao/BomDAO.java | UTF-8 | 3,809 | 2.96875 | 3 | [] | no_license | package com.mes.dao;
import static com.mes.db.JDBCUtility.close;
import static com.mes.db.JDBCUtility.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.sql.DataSource;
import com.mes.vo.Bom;
public class BomDAO {
private BomDAO() {}
private static BomDAO bomDAO;
// 하나의 객체생성을 위한 getInstance
public static BomDAO getInstance() {
if(bomDAO == null) bomDAO = new BomDAO();
return bomDAO;
}
// DB연결
Connection conn = null;
DataSource ds = null;
public void setConnection(Connection conn) {
this.conn = conn;
}
// 리스트를 불러오기
public ArrayList<Bom> selectBomList(int page, int limit, String productCd){
ArrayList<Bom> bomList = new ArrayList<Bom>();
Bom bom = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "select * from bom";
if(productCd != null) sql += " where product_cd = '"+productCd +"'";
sql += " limit ?," + limit;
int startRow = (page-1) * limit;
System.out.println("BomDAO = productCd: " + productCd);
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, startRow);
rs = pstmt.executeQuery();
while (rs.next()) {
bom = new Bom();
bom.setProductCd(rs.getString("product_cd"));// 제품코드
bom.setItemCd(rs.getString("item_cd"));// 부품코드
bom.setItemName(rs.getString("item_name"));// 부품명
bom.setItemCnt(rs.getInt("item_cnt"));// 소요량
bom.setUnit(rs.getString("unit"));// 단위
bom.setUnitPrice(rs.getDouble("unit_price"));// 단가
bom.setVendorCd(rs.getString("vendor_cd"));// 거래처코드
bom.setRemark(rs.getString("remark"));// 비고
bomList.add(bom);
}
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Bom리스트 조회 실패!!" + e.getMessage());
} finally {
close(pstmt, rs);
}
return bomList;
}
// Bom 등록
public int insertBom(Bom bom) {
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "insert into bom(product_cd, item_cd, item_name, item_cnt, unit, unit_price, vendor_cd, remark) " +
" values(?, ?, ?, ?, ?, ?, ?, ?)";
// insertCount - 입력되는 행을 위한 변수
int insertCount = 0;
try {
// prepareStatement - sql문 호출
pstmt = conn.prepareStatement(sql);
// 값 넣기
pstmt.setString(1, bom.getProductCd());// 제품코드
pstmt.setString(2, bom.getItemCd());// 부품코드
pstmt.setString(3, bom.getItemName());// 부품명
pstmt.setInt(4, bom.getItemCnt());// 소요량
pstmt.setString(5, bom.getUnit());// 단위
pstmt.setDouble(6, bom.getUnitPrice());// 단가
pstmt.setString(7, bom.getVendorCd());// 거래처코드
pstmt.setString(8, bom.getRemark());// 비고
// executeUpdate - 리턴값이 int(n행을 리턴)
insertCount = pstmt.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Bom 입력 실패!!" + e.getMessage());
} finally {
close(pstmt,rs);
}
return insertCount;
}
// Bom 글 갯수 구하기
public int selectListCount(String productCd) {
int listCount = 0;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "select count(*) from bom";
if(productCd != null) sql += " where product_cd = '"+productCd +"'";
try {
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
if(rs.next()) listCount = rs.getInt(1);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Bom갯수 가져오기 실패!! " + e.getMessage());
} finally {
close(pstmt, rs);
}
return listCount;
}
}
| true |
1c3901e909bd9a25435fe02747dcb17f6ffb2637 | Java | vmmelnikov/ixora-rms | /AgentWeblogic/src/com/ixora/rms/agents/weblogic/exception/CommunicationError.java | UTF-8 | 477 | 1.882813 | 2 | [] | no_license | /*
* Created on 13-Jan-2005
*/
package com.ixora.rms.agents.weblogic.exception;
import com.ixora.rms.agents.weblogic.messages.Msg;
import com.ixora.rms.exception.RMSException;
/**
* @author Daniel Moraru
*/
public final class CommunicationError extends RMSException {
private static final long serialVersionUID = -4174754389463689908L;
/**
* Constructor.
*/
public CommunicationError() {
super(Msg.NAME, Msg.ERROR_COMMUNICATION_ERROR, true);
}
}
| true |
82226d12d3bb150dc7a6b8d270e6d0446dc13d5d | Java | fadada-tech/fadada-java-sdk-api3 | /src/main/java/com/fadada/api/client/IsspLocalClient.java | UTF-8 | 3,151 | 2.265625 | 2 | [] | no_license | package com.fadada.api.client;
import com.fadada.api.DefaultFadadaApiServiceImpl;
import com.fadada.api.FadadaApiConfig;
import com.fadada.api.FadadaApiService;
import com.fadada.api.bean.req.issp.DownloadFileReq;
import com.fadada.api.bean.req.issp.UploadFileReq;
import com.fadada.api.bean.rsp.BaseRsp;
import com.fadada.api.bean.rsp.document.DownLoadFileRsp;
import com.fadada.api.bean.rsp.issp.UploadFileRsp;
import com.fadada.api.exception.ApiException;
import com.fadada.api.utils.PreconditionsUtil;
import com.fadada.api.utils.json.ParameterizedTypeBaseRsp;
import com.fadada.api.utils.string.StringUtil;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* @author yh128
* @version 1.0.0
* @ClassName IsspLocalClient.java
* @Description ISSP local接口
* @Param
* @createTime 2020年11月07日 09:24:00
*/
public class IsspLocalClient {
private static final String UPLOAD_FILE = "issp/intranet/uploadFile";
private static final String DOWNLOAD_FILE = "issp/intranet/downloadFile";
/**
* issp服务请求地址
*/
private String isspServerUrl = "";
private static FadadaApiService fadadaApiService = new DefaultFadadaApiServiceImpl();
public IsspLocalClient(String isspServerUrl) {
if (StringUtil.isBlank(isspServerUrl)) {
PreconditionsUtil.checkArgument(true, "isspServerUrl不能为空");
}
this.isspServerUrl = isspServerUrl;
}
public static void setFadadaApiService(FadadaApiService fadadaApiService) {
IsspLocalClient.fadadaApiService = fadadaApiService;
}
/**
* 文件上传
*
* @param file
* @param req
* @return
* @throws ApiException
*/
public BaseRsp<UploadFileRsp> uploadFile(File file, UploadFileReq req) throws ApiException {
PreconditionsUtil.checkObject(req);
Map<String, File> fileMap = new HashMap<>();
fileMap.put("file", file);
Map<String, String> bodyMap = new HashMap<>();
bodyMap.put("bizContent", fadadaApiService.toJson(req));
String resultStr = fadadaApiService.http(isspServerUrl + UPLOAD_FILE, "POST", null, bodyMap, fileMap);
return fadadaApiService.toJavaBean(resultStr, new ParameterizedTypeBaseRsp(UploadFileRsp.class));
}
/**
* 文件下载
*
* @param req
* @return
* @throws ApiException
*/
public BaseRsp<DownLoadFileRsp> downloadFile(DownloadFileReq req) throws ApiException {
PreconditionsUtil.checkObject(req);
Map<String, String> bodyMap = new HashMap<>();
bodyMap.put("bizContent", fadadaApiService.toJson(req));
Object result = fadadaApiService.httpDownLoad(isspServerUrl + DOWNLOAD_FILE, "POST", null, bodyMap);
String resultString = null;
if (result instanceof String) {
resultString = result.toString();
} else {
resultString = FadadaApiConfig.getFadadaApiService().toJson(result);
}
return FadadaApiConfig.getFadadaApiService().toJavaBean(resultString,
new ParameterizedTypeBaseRsp(DownLoadFileRsp.class));
}
}
| true |
d41111b16bebf557146266448ffadcf603cc43cb | Java | mjrockzzz/tms-source | /src/main/java/com/ge/tms/dto/BillChargeConfigurationDTO.java | UTF-8 | 548 | 2.03125 | 2 | [] | no_license | package com.ge.tms.dto;
/**
* This class is used to send the BillChargeConfiguration response.
* @author Nitin K.
*/
public class BillChargeConfigurationDTO {
private String tarrifPlan;
private BillingChargesDTO charges;
public String getTarrifPlan() {
return tarrifPlan;
}
public void setTarrifPlan(String tarrifPlan) {
this.tarrifPlan = tarrifPlan;
}
public BillingChargesDTO getCharges() {
return charges;
}
public void setCharges(BillingChargesDTO charges) {
this.charges = charges;
}
}
| true |
f87bf195b89eb1f45a0c0c315e890767daed6bff | Java | fandfisf/rheastteos | /src/main/java/com/github/fandfisf/rheastteos/model/Painter.java | UTF-8 | 1,160 | 2.359375 | 2 | [] | no_license | package com.github.fandfisf.rheastteos.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
import javax.persistence.*;
import static org.springframework.data.jpa.domain.AbstractPersistable_.id;
/**
* Created by Prashant S Khanwale @ Suveda LLC on 7/16/16.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@Table(name = "painters")
public class Painter {
/**
* Created by Prashant S Khanwale @ Suveda LLC on 7/16/16.
*/
@Id
@Column(name = "painter_id", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "PSEUDONYM")
private String pseudonym;
@Column(name = "birth_date")
@Temporal(TemporalType.DATE)
private Date birthDate;
@Column(name = "date_of_death")
@Temporal(TemporalType.DATE)
private Date dateOfDeath;
@Column(name = "picture")
private String picture;
@Column(name = "version")
private int version;
}
| true |
bfa06baa45d1c8ec6f3dd1ad2397439fe1eeb3ba | Java | szr22/java-console-app | /test-console-app/src/com/company/LC470/ImplementRand10UsingRand7.java | UTF-8 | 823 | 3.078125 | 3 | [] | no_license | package com.company.LC470;
import java.util.Random;
public class ImplementRand10UsingRand7 {
static int[] mem = new int[10];
static int max = 0;
public int rand10() {
int randNum = rand7();
if (mem[randNum-1]+1 <= max) {
max = Math.max(++mem[randNum-1], max);
return randNum;
} else {
int i = 1;
while(i<=3) {
if (mem[6+i] < max) {
max = Math.max(++mem[6+i], max);
return 7+i;
}
i++;
}
}
max = Math.max(++mem[randNum-1], max);
return randNum;
}
private int rand7() {
Random random = new Random();
return random.ints(1, 7)
.findFirst()
.getAsInt();
}
}
| true |
6c2c96d886741e8a985f5422a080609729771233 | Java | Faeemmansuri/authentication-service | /src/main/java/com/faeem/authenticationservice/user/service/UserServiceImpl.java | UTF-8 | 7,743 | 1.90625 | 2 | [] | no_license | package com.faeem.authenticationservice.user.service;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.thymeleaf.context.Context;
import com.faeem.authenticationservice.email.EmailTemplate;
import com.faeem.authenticationservice.email.EmailUtil;
import com.faeem.authenticationservice.entity.UserEntity;
import com.faeem.authenticationservice.enums.VerificationType;
import com.faeem.authenticationservice.exception.BadRequestException;
import com.faeem.authenticationservice.jwt.utils.JwtUtils;
import com.faeem.authenticationservice.repository.UserRepository;
import com.faeem.authenticationservice.request.LoginRequest;
import com.faeem.authenticationservice.request.RegisterRequest;
import com.faeem.authenticationservice.request.ResetPasswordRequest;
import com.faeem.authenticationservice.response.LoginResponse;
import com.faeem.authenticationservice.service.BaseService;
import com.faeem.authenticationservice.verification.service.VerificationService;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class UserServiceImpl extends BaseService implements UserService {
private static final String PASSWORD_VALIDATION_PATTERN = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*(\\W|_)).{8,}$";
private static final String EMAIL_VALIDATION_PATTERN = "^[-a-z0-9~!$%^&*_=+}{\\'?]+(\\.[-a-z0-9~!$%^&*_=+}{\\'?]+)*@([a-z0-9_][-a-z0-9_]*(\\.[-a-z0-9_]+)*\\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,5})?$";
private static final String ROLE_USER = "ROLE_USER";
@Autowired private JwtUtils jwtUtils;
@Autowired private UserRepository userRepository;
@Autowired private PasswordEncoder passwordEncoder;
@Autowired private AuthenticationManager authenticationManager;
@Autowired private VerificationService verificationService;
@Autowired private EmailUtil emailUtil;
@Value("spring.mail.username") private String mailFrom;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserEntity user = userRepository.findByUsername(username);
if(Objects.isNull(user)) {
throw new UsernameNotFoundException("Invalid username/password");
}
List<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority(ROLE_USER));
return new User(user.getUsername(), user.getPassword(), authorities);
}
@Override
public void registerUser(RegisterRequest request) {
boolean isValidPassword = Pattern.matches(PASSWORD_VALIDATION_PATTERN, request.getPassword());
if(!isValidPassword) {
throw new BadRequestException(i18nMessages.get("rest.error.invalid.password"));
}
boolean isValidEmail = Pattern.matches(EMAIL_VALIDATION_PATTERN, request.getEmail());
if(!isValidEmail) {
throw new BadRequestException(i18nMessages.get("rest.error.invalid.email"));
}
Optional<UserEntity> userOptional = userRepository.findByUsernameOrEmail(request.getUsername(), request.getEmail());
if(userOptional.isPresent()) {
throw new BadRequestException(i18nMessages.get("rest.error.user-pass.exists"));
}
UserEntity user = new UserEntity();
user.setUsername(request.getUsername());
user.setPassword(passwordEncoder.encode(request.getPassword()));
user.setEmail(request.getEmail());
user.setCreatedOn(new Date(System.currentTimeMillis()));
user = userRepository.save(user);
String vetificationLink = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString()
+ "/verify?token=" + verificationService.generateToken(user, VerificationType.REGISTER);
String subject = i18nMessages.get("email.subject.registered", user.getUsername());
Context context = new Context();
context.setVariable("name", user.getUsername());
context.setVariable("subject", subject);
context.setVariable("vetificationLink", vetificationLink);
EmailTemplate template = new EmailTemplate();
template.setSubject(subject);
template.setFrom(mailFrom);
template.setTo(user.getEmail());
template.setProps(context);
template.setTemplateName("email_verification");
emailUtil.sendEmail(template);
}
@Override
public LoginResponse loginUser(LoginRequest request) {
UserDetails userDetails = loadUserByUsername(request.getUsername());
if (Objects.isNull(userDetails)) {
throw new BadRequestException(i18nMessages.get("rest.error.user-pass.invalid"));
}
authenticate(request.getUsername(), request.getPassword());
String jwtToken = jwtUtils.generateJwt(userDetails);
return new LoginResponse(jwtToken);
}
@Override
public void forgetPassword(String email) {
Optional<UserEntity> userOptional = userRepository.findByEmail(email);
userOptional.orElseThrow(() -> new BadRequestException(i18nMessages.get("rest.error.invalid.email")));
UserEntity user = userOptional.get();
String vetificationLink = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString()
+ "/verify?token=" + verificationService.generateToken(user, VerificationType.FORGET_PASSWORD);
String subject = i18nMessages.get("email.subject.forget-password", user.getUsername());
Context context = new Context();
context.setVariable("name", user.getUsername());
context.setVariable("subject", subject);
context.setVariable("vetificationLink", vetificationLink);
EmailTemplate template = new EmailTemplate();
template.setSubject(subject);
template.setFrom(mailFrom);
template.setTo(user.getEmail());
template.setProps(context);
template.setTemplateName("forget-password");
emailUtil.sendEmail(template);
}
@Override
public void resetPassword(ResetPasswordRequest request) {
boolean isValidPassword = Pattern.matches(PASSWORD_VALIDATION_PATTERN, request.getPassword());
if(!isValidPassword) {
throw new BadRequestException(i18nMessages.get("rest.error.invalid.password"));
}
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
UserEntity user = userRepository.findByUsername(userDetails.getUsername());
user.setPassword(passwordEncoder.encode(request.getPassword()));
userRepository.save(user);
}
private void authenticate(String username, String password) throws BadRequestException {
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
} catch (DisabledException e) {
throw new BadRequestException("User Is Disabled");
} catch (BadCredentialsException e) {
throw new BadRequestException("INVALID_CREDENTIALS", e);
}
}
}
| true |
e619802b62007c1af4600b58f5fa695c8b29eb8e | Java | unshorn-forks/STAC | /Engagement_Challenges/Engagement_4/bidpal_1/source/edu/computerapex/dialogs/Communicator.java | UTF-8 | 172 | 1.671875 | 2 | [] | no_license | package edu.computerapex.dialogs;
public interface Communicator {
public void deliver(CommunicationsPublicIdentity dest, byte[] msg) throws CommunicationsDeviation;
}
| true |
ffceb5aa718cb39643dd353295573aae65fe4dd7 | Java | Combergniot/xtm_dictionary | /src/main/java/com/xtm/dictionary/DictionaryProviderService.java | UTF-8 | 989 | 2.34375 | 2 | [] | no_license | package com.xtm.dictionary;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
@Service
class DictionaryProviderService {
@SneakyThrows
protected Map<String, String> getDictionaryFromFile() {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(Objects.requireNonNull(classLoader.getResource(DictionaryVersion.POLISH_TO_ENGLISH.getPath())).getFile());
String data = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
return convertJsonToMap(data);
}
private Map<String, String> convertJsonToMap(String jsonString) {
Gson gson = new Gson();
return gson.fromJson((jsonString), new TypeToken<Map<String, Object>>() {
}.getType());
}
}
| true |
647d0ea24f27fde6c388ace08f8325e2677a62c9 | Java | tsbonev/jdbc | /src/main/java/com/clouway/jdbc/foreignkey/TripRepository.java | UTF-8 | 7,691 | 3.03125 | 3 | [] | no_license | package com.clouway.jdbc.foreignkey;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collector;
@SuppressWarnings("Duplicates")
public class TripRepository {
private Connection conn;
private static TripRepository instance;
public static TripRepository instanceOf(Connection conn){
if(instance == null) instance = new TripRepository(conn);
instance.conn = conn;
return instance;
}
public static void clearInstance(){
instance = null;
}
private TripRepository(Connection conn){
this.conn = conn;
}
public List<Person> getPeopleInCity(String city){
List<Person> personList = new ArrayList<>();
this.getAll().stream()
.filter(t -> t.getCity().equalsIgnoreCase(city)).collect(SameTime.collector())
.forEach(t -> personList.add(this.getPersonInTrip(t)));
return personList;
}
private static final class SameTime {
private Set<Trip> set = new HashSet<>();
private Trip first, second;
public void accept(Trip trip){
first = second;
second = trip;
if(first != null && first.getArrival().before(second.getDeparture())
&& first.getDeparture().after(second.getArrival())){
set.add(first);
set.add(second);
}
}
public SameTime combine(SameTime other) {
throw new UnsupportedOperationException("Parallel Stream not supported");
}
public List<Trip> finish() {
List<Trip> tripList = new ArrayList<>();
tripList.addAll(set);
return tripList;
}
public static Collector<Trip, ?, List<Trip>> collector() {
return Collector.of(SameTime::new, SameTime::accept, SameTime::combine, SameTime::finish);
}
}
private Person getPersonInTrip(Trip trip){
Person person = new Person();
try{
PreparedStatement select = conn.prepareStatement("SELECT * FROM person" +
" WHERE egn LIKE ?");
select.setString(1, trip.getEgn());
ResultSet result = select.executeQuery();
while (result.next()){
person.setId(result.getInt("id"));
person.setAge(result.getInt("age"));
person.setFname(result.getString("fname"));
person.setEmail(result.getString("email"));
person.setEgn(result.getString("egn"));
}
return person;
}catch (SQLException e){
e.printStackTrace();
}
return null;
}
public List<Trip> getAll(){
try {
PreparedStatement select = conn.prepareStatement("SELECT * FROM trip");
ResultSet result = select.executeQuery();
List<Trip> list = new ArrayList<Trip>();
while (result.next()){
Trip trip = new Trip();
trip.setId(result.getInt("id"));
trip.setCity(result.getString("city"));
trip.setEgn(result.getString("personEgn"));
trip.setArrival(result.getDate("arrival"));
trip.setDeparture(result.getDate("departure"));
list.add(trip);
}
return list;
}catch (SQLException e){
e.printStackTrace();
}
return null;
}
public void dropTable(){
try {
PreparedStatement drop = conn.prepareStatement("DROP TABLE trip");
drop.execute();
}catch (SQLException e){
e.printStackTrace();
}
}
public void dropTableContent(){
try {
PreparedStatement delete = conn.prepareStatement("DELETE FROM trip");
delete.execute();
}catch (SQLException e){
e.printStackTrace();
}
}
public List<String> getMostVisitedDescending(){
try {
List<String> list = new LinkedList<>();
PreparedStatement select = conn.prepareStatement("SELECT city, COUNT(*) occurence FROM trip" +
" GROUP BY city" +
" ORDER BY occurence DESC");
ResultSet result = select.executeQuery();
while (result.next()){
list.add(result.getString("city"));
}
return list;
}catch (SQLException e){
e.printStackTrace();
}
return null;
}
public void updateTrip(Trip trip){
try {
PreparedStatement update = conn.prepareStatement("UPDATE trip " +
"SET city = ?, arrival = ?, departure = ?, personEgn = ?" +
" WHERE id = ?");
update.setString(1, trip.getCity());
update.setDate(2, trip.getArrival());
update.setDate(3, trip.getDeparture());
update.setString(4, trip.getEgn());
update.setInt(5, trip.getId());
update.execute();
}catch (SQLException e){
e.printStackTrace();
}
}
public void deleteTripById(int id){
try {
PreparedStatement delete = conn.prepareStatement("DELETE FROM trip" +
" WHERE id = ?");
delete.setInt(1, id);
delete.execute();
}catch (SQLException e){
e.printStackTrace();
}
}
public Trip getTripById(int id){
try {
PreparedStatement select = conn.prepareStatement("SELECT * FROM trip" +
" WHERE id = ?");
select.setInt(1, id);
ResultSet result = select.executeQuery();
Trip trip = new Trip();
while (result.next()){
trip.setId(result.getInt("id"));
trip.setCity(result.getString("city"));
trip.setEgn(result.getString("personEgn"));
trip.setArrival(result.getDate("arrival"));
trip.setDeparture(result.getDate("departure"));
}
return trip;
}catch (SQLException e){
e.printStackTrace();
}
return null;
}
public void createTripTable(){
try {
PreparedStatement create = conn.prepareStatement(
"CREATE TABLE IF NOT EXISTS trip(" +
"id int NOT NULL AUTO_INCREMENT," +
"city varchar(255) NOT NULL," +
"arrival date NOT NULL," +
"departure date NOT NULL," +
"personEgn varchar(10) NOT NULL," +
"PRIMARY KEY(id)," +
"FOREIGN KEY (personEgn) REFERENCES person(egn) ON DELETE CASCADE ON UPDATE CASCADE)"
);
create.execute();
}catch (SQLException e){
e.printStackTrace();
}
}
public void addTrip(Trip trip){
try {
PreparedStatement add = conn.prepareStatement("INSERT INTO trip(" +
"city, personEgn, arrival, departure)" +
" VALUES (?, ?, ?, ?)");
add.setString(1, trip.getCity());
add.setString(2, trip.getEgn());
add.setDate(3, trip.getArrival());
add.setDate(4, trip.getDeparture());
add.execute();
}catch (SQLException e){
e.printStackTrace();
}
}
}
| true |
09b3da35e127db32f2c5c67dd67536ebf7e8e33c | Java | biojava/biojava-legacy | /core/src/main/java/org/biojavax/RichAnnotation.java | UTF-8 | 3,572 | 2.40625 | 2 | [] | no_license | /*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojavax;
import java.util.NoSuchElementException;
import java.util.Set;
import org.biojava.bio.Annotation;
import org.biojava.utils.ChangeVetoException;
/**
* An annotation collection which stores annotations as Note objects.
* @author Richard Holland
* @author Mark Schreiber
* @see Note
* @see RichAnnotatable
* @since 1.5
*/
public interface RichAnnotation extends Annotation {
public static final RichAnnotation EMPTY_ANNOTATION = new EmptyRichAnnotation();
/**
* Removes all notes from this annotation object.
* @throws ChangeVetoException if it couldn't do it.
*/
public void clear() throws ChangeVetoException;
/**
* Adds a note to this annotation. Must not be null.
* If the note is already in the annotation, nothing happens.
* @param note note to add
* @throws ChangeVetoException if it doesn't like this.
*/
public void addNote(Note note) throws ChangeVetoException;
/**
* Removes a note from this annotation. Must not be null.
* If the note wasn't in the annotation, nothing happens.
* @param note note to remove
* @throws ChangeVetoException if it doesn't like this.
*/
public void removeNote(Note note) throws ChangeVetoException;
/**
* Uses the term and rank to lookup a note in this annotation.
* @param note note to lookup, using term and rank.
* @return the matching note.
* @throws ChangeVetoException if it doesn't like this.
* @throws NoSuchElementException if it couldn't be found.
*/
public Note getNote(Note note) throws NoSuchElementException;
/**
* Returns true if the given note exists in this annotation.
* The lookup is done using the term and rank of the note.
* @param note note to lookup
* @return true if it is in this annotation, false if not.
*/
public boolean contains(Note note);
/**
* Returns an immutable set of all notes in this annotation.
* @return a set of notes.
* @see Note
*/
public Set<Note> getNoteSet();
/**
* Clears the notes from this annotation and replaces them with
* those from the given set. The set cannot be null.
* @param notes a set of Note objects to use from now on.
* @throws ChangeVetoException if it doesn't like any of them.
* @see Note
*/
public void setNoteSet(Set<Note> notes) throws ChangeVetoException;
/**
* Find all the <code>Note</code>s with any rank that match the key.
* @param key either a <code>String</code> identifier of a term from the
* default ontology or a <code>ComparableTerm</code>
* @return an array of matching <code>Notes</code> in order of rank or an
* empty array if there are no matches. No implementation should ever
* return null!
* @see Note
* @see org.biojavax.ontology.ComparableTerm
*/
public Note[] getProperties(Object key);
}
| true |