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 |
---|---|---|---|---|---|---|---|---|---|---|---|
ffa1fd37bb56cc8d5303987653d173ba1f1e8cf5
|
Java
|
anurakam/SeedCampaign
|
/app/src/main/java/com/psu/seedcampaign/CreateUser.java
|
UTF-8
| 4,529 | 2.296875 | 2 |
[] |
no_license
|
package com.psu.seedcampaign;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
/**
* Created by อนุรักษ์ on 8/3/2558.
*/
public class CreateUser extends Activity {
EditText FirstName, LastName, Username, Password;
ImageButton btnCreateUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_user);
// Show the Up button in the action bar.
FirstName =(EditText) findViewById(R.id.fisrtname);
LastName = (EditText) findViewById(R.id.lastname);
Username = (EditText) findViewById(R.id.username);
Password = (EditText) findViewById(R.id.password);
btnCreateUser=(ImageButton) findViewById(R.id.btn_createuser);
btnCreateUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String firstname, lastname, username, password;
//String name, surname, username, password;
firstname = FirstName.getText().toString();
lastname = LastName.getText().toString();
username = Username.getText().toString();
password = Password.getText().toString();
UserDetailsTable userDetail = new UserDetailsTable(firstname,
lastname, username, password);
new AsyncCreateUser().execute(userDetail);
}
});
}
protected class AsyncCreateUser extends
AsyncTask<UserDetailsTable, Void, Void> {
@Override
protected Void doInBackground(UserDetailsTable... params) {
RestAPI api = new RestAPI();
try {
api.CreateNewAccount(params[0].getFirstName(),
params[0].getLastName(), params[0].getUserName(),
params[0].getPassword());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncCreateUser", e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(Void result) {
showAlert();
}
}
private void showAlert() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("เสร็จสิ้น")
.setMessage("คุณได้ทำการสมัครสมาชิกเรียบร้อยแล้ว")
.setCancelable(false)
.setPositiveButton("ตกลง", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
Intent i = new Intent(CreateUser.this, Login.class);
startActivity(i);
}
});
AlertDialog alert = builder.create();
alert.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
| true |
84158fc8d49c8190ca7a2ad7504c168dcec5a99a
|
Java
|
iiholod/XelopesFL
|
/Clustering/src/main/java/org/eltech/ddm/clustering/ClusteringMiningModel.java
|
UTF-8
| 1,647 | 2.28125 | 2 |
[] |
no_license
|
package org.eltech.ddm.clustering;
import org.eltech.ddm.clustering.cdbase.Coordinate;
import org.eltech.ddm.miningcore.MiningException;
import org.eltech.ddm.miningcore.miningfunctionsettings.EMiningFunctionSettings;
import org.eltech.ddm.miningcore.miningmodel.EMiningModel;
import org.eltech.ddm.miningcore.miningmodel.MiningModelElement;
import java.util.List;
public abstract class ClusteringMiningModel extends EMiningModel//ClusteringModel
{
static public final int CLUSTERS = 1;
static public final int[] INDEX_CLUSTERS = {1};
public ClusteringMiningModel(EMiningFunctionSettings settings) throws MiningException {
super(settings);
sets.add(CLUSTERS, new ClusterSet("Clusters") {
@Override
public void merge(List<MiningModelElement> elements) {
}
}) ;
}
@Override
public void initModel() throws MiningException {
int numClusters = ((ClusteringFunctionSettings)settings).getMaxNumberOfClusters();
for(int i = 0; i < numClusters; i++){
addElement(index(CLUSTERS), new Cluster("Cluster "+i));
}
}
public Coordinate getClusterCenterCoordinate(int iCurrentCluster, int iAttr) throws MiningException {
return (Coordinate)getElement(index(ClusteringMiningModel.CLUSTERS, iCurrentCluster, iAttr));
}
public int getCurrentClusterIndex() throws MiningException {
return getCurrentElementIndex(EMiningModel.index(ClusteringMiningModel.CLUSTERS));
}
public Cluster getCluster(int iCluster) throws MiningException {
return ((Cluster)getElement(index(CLUSTERS, iCluster)));
}
public ClusterSet getClusterSet() throws MiningException {
return (ClusterSet) getElement(INDEX_CLUSTERS);
}
}
| true |
f8d1b760df7c744d448727d8e93d630fa3f0339e
|
Java
|
Btate712/Fraction-Java
|
/lib/src/test/java/fractions/FractionTest.java
|
UTF-8
| 567 | 3.03125 | 3 |
[] |
no_license
|
package fractions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class FractionTest {
@Test void testLowestCommonDenominator() {
assertEquals(Fraction.lowestCommonDenominator(30, 20), 10, "lowestCommonDenominator of 30 and 20 should be 10");
}
// Made method "isMultiple()" private after testing passed
// @Test void testIsMultiple() {
// assertTrue(Fraction.isMultiple(25, 5), "25 is a multiple of 5");
// assertFalse(Fraction.isMultiple(10, 2), "10 is NOT a multiple of 2");
// }
}
| true |
7d88a1b8b944c78744b2200f441811b05f82315c
|
Java
|
Archeidos/GPCodingChallenge
|
/app/src/main/java/com/example/mbtho/geniusplazachallenge/profiles/GetUserProfileInteractorImpl.java
|
UTF-8
| 2,321 | 2.25 | 2 |
[] |
no_license
|
package com.example.mbtho.geniusplazachallenge.profiles;
import android.util.Log;
import com.example.mbtho.geniusplazachallenge.data.GetUserProfileService;
import com.example.mbtho.geniusplazachallenge.model.UserProfile;
import com.example.mbtho.geniusplazachallenge.model.UserProfileList;
import com.example.mbtho.geniusplazachallenge.network.RetrofitInstance;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class GetUserProfileInteractorImpl implements ProfilesContract.GetUserProfileInteractor {
@Override
public void getUserProfileArrayList(final OnFinishedListener onFinishedListener) {
GetUserProfileService service = RetrofitInstance.getRetrofitInstance().create(GetUserProfileService.class);
Call<UserProfileList> call = service.getUserProfileData();
call.enqueue(new Callback<UserProfileList>() {
@Override
public void onResponse(Call<UserProfileList> call, Response<UserProfileList> response) {
onFinishedListener.onFinished(response.body().getUserProfileArrayList());
Log.d("test1", response.body().getUserProfileArrayList().toString());
}
@Override
public void onFailure(Call<UserProfileList> call, Throwable t) {
onFinishedListener.onFailure(t);
Log.d("test1", "onFailure: " + t.getMessage());
}
});
}
@Override
public void requestNewUserProfile(final OnFinishedListener onFinishedListener) {
GetUserProfileService service = RetrofitInstance.getRetrofitInstance().create(GetUserProfileService.class);
Call<UserProfile> call = service.createUserProfile(new UserProfile("10",
"First",
"Last",
"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"
));
call.enqueue(new Callback<UserProfile>() {
@Override
public void onResponse(Call<UserProfile> call, Response<UserProfile> response) {
onFinishedListener.onFinished(response.body());
}
@Override
public void onFailure(Call<UserProfile> call, Throwable t) {
Log.d("test1","onFailure" + t.toString());
}
});
}
}
| true |
c6460828925279ca47fa7f5ba9b9bda3398f4ad7
|
Java
|
cckmit/erp-4
|
/Maven_Accounting/src/main/java/com/krawler/spring/accounting/dashboard/AccUSDashboardService.java
|
UTF-8
| 878 | 1.570313 | 2 |
[] |
no_license
|
/*
* Copyright (C) 2016 Krawler Information Systems Pvt Ltd
* All rights reserved.
*
*/
package com.krawler.spring.accounting.dashboard;
import com.krawler.common.service.ServiceException;
import com.krawler.common.session.SessionExpiredException;
import com.krawler.utils.json.base.JSONException;
import com.krawler.utils.json.base.JSONObject;
public interface AccUSDashboardService {
public JSONObject saveDashboard(JSONObject paramJobj) throws ServiceException, SessionExpiredException;
public JSONObject getDashboard(JSONObject paramJobj) throws JSONException, ServiceException, SessionExpiredException;
public JSONObject setActiveDashboard(JSONObject paramJobj) throws ServiceException, SessionExpiredException;
public JSONObject getProductViewInvDetails(JSONObject paramJobj) throws ServiceException, SessionExpiredException;
}
| true |
dbbc31010b2799afbbe373a6bb999216cd81beb2
|
Java
|
alicenoknow/GameOfEvolution
|
/src/Simulation/StageInitializer.java
|
UTF-8
| 1,686 | 2.8125 | 3 |
[] |
no_license
|
package Simulation;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
public class StageInitializer {
private final Logger log = Logger.getLogger(this.getClass().getName());
private final Stage stage;
private FXMLLoader fxmlLoader;
private Parent root;
public StageInitializer(Stage stage){
this.stage = stage;
}
public StageInitializer(){
this(new Stage());
}
public void loadFXML(String path){
try {
URL filePath = this.getClass().getResource(path);
this.fxmlLoader = new FXMLLoader(filePath);
this.root = fxmlLoader.load();
}
catch(IOException | NullPointerException | IllegalStateException e){
log.log(Level.SEVERE, "Cannot load fxml file! " + e.getMessage());
System.exit(0);
}
}
public void setStageView(String title, int height, int width){
stage.setTitle(title);
stage.setScene(new Scene(root, width, height));
stage.setResizable(false);
stage.show();
}
public Object getController(){
return fxmlLoader.getController();
}
public void setIcon(String path) {
try {
stage.getIcons().add(new Image(path));
}
catch(NullPointerException | IllegalStateException e){
log.log(Level.WARNING, "Cannot load icon! " + e.getMessage());
}
}
public Stage getStage(){
return this.stage;
}
}
| true |
63baf1506ca29dc027015e59ee403a57ebd41e4f
|
Java
|
lyn-workspace/spring-cloud-example
|
/nacos-config-client/src/main/java/com/spring/cloud/client/User.java
|
UTF-8
| 640 | 1.851563 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.spring.cloud.client;
import com.sun.org.apache.xpath.internal.operations.Or;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotBlank;
/**
* 用户
*
* @author luyanan
* @since 2020/8/11
**/
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
/**
* id
*
* @author luyanan
* @since 2020/8/11
*/
private Integer id;
/**
* 名称
*
* @author luyanan
* @since 2020/8/11
*/
@NotBlank(message = "不能为空")
private String name;
}
| true |
18bf5e674c76651f9bfc10c922afb185ff829da5
|
Java
|
ybanodeveloper2007/Music
|
/app/src/main/java/com/ritmoli/music/activity/HomeActivity.java
|
UTF-8
| 2,181 | 2.046875 | 2 |
[] |
no_license
|
package com.ritmoli.music.activity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.internal.NavigationMenuItemView;
import com.ritmoli.music.R;
import com.ritmoli.music.fragment.HomeFragment;
import com.ritmoli.music.fragment.PlaylistFragment;
import com.ritmoli.music.fragment.ProfileFragment;
public class HomeActivity extends AppCompatActivity {
Fragment fragment = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_navigationbar);
//loading the default fragment
loadFragment(new HomeFragment());
FrameLayout llcustom0 = findViewById(R.id.llcustom0);
FrameLayout llcustom2 = findViewById(R.id.llcustom2);
FrameLayout llcustom3 = findViewById(R.id.llcustom3);
FrameLayout llcustom5 = findViewById(R.id.llcustom5);
llcustom0.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadFragment(new HomeFragment());
}
});
llcustom2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadFragment(new PlaylistFragment());
}
});
llcustom5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadFragment(new ProfileFragment());
}
});
}
private boolean loadFragment(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentContainer, fragment)
.commit();
return true;
}
return false;
}
}
| true |
0ed2eca8a2de5f6320a47e31a24dc21709141550
|
Java
|
TechnionYearlyProject/Cognitivity
|
/code/src/main/java/cognitivity/entities/TestManager.java
|
UTF-8
| 642 | 2.34375 | 2 |
[] |
no_license
|
package cognitivity.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* Created by Guy on 20/1/18.
*
*
* The Test Manager persistent (JPA) representation (tables).
*
*/
@Entity
@Table(name = "testManager")
public class TestManager extends AbstractEntity {
@Column(name = "email", unique = true)
private String email;
public TestManager(String email) {
this.email = email;
}
public TestManager() {}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
| true |
d564bea14937d5cf4d0bd2ed1b874fe26a54b8ce
|
Java
|
EANimesha/Dinning-Philosopher-Problem
|
/Philosopher.java
|
UTF-8
| 2,504 | 3.703125 | 4 |
[] |
no_license
|
package Dine4_v1;
import java.util.Random;
import java.util.concurrent.Semaphore;
class Philosopher implements Runnable {
private int id;
private int eattime;
private int amount=0;
private Semaphore leftChopstick;
private Semaphore rightChopstick;
public Philosopher(int id, Semaphore leftChopstick, Semaphore rightChopstick) {
this.id = id;
this.leftChopstick = leftChopstick;
this.rightChopstick = rightChopstick;
}
public void run() {
try {
while (amount<100){
think();
pickUpLeftChopstick();
pickUpRightChopstick();
eat();
putDownChopsticks();
}
} catch (InterruptedException e) {
System.out.println("Philosopher " + id + " was interrupted.\n");
}
}
private void think() throws InterruptedException {
System.out.println("Philosopher " + id + " is thinking.\n");
System.out.flush();
Thread.sleep(new Random().nextInt(10));
}
private void pickUpLeftChopstick() throws InterruptedException{
if(leftChopstick.availablePermits() ==0){
System.out.println("Philosopher " +id +" is waiting for left chopstick");
}
leftChopstick.acquire();
System.out.println("Philosopher " + id + " is holding left chopstick.\n");
}
private void pickUpRightChopstick() throws InterruptedException{
if(rightChopstick.availablePermits() ==0){
System.out.println("Philosopher " +id +" is waiting for right chopstick");
}
rightChopstick.acquire();
System.out.println("Philosopher " + id + " is holding right chopstick.\n");
}
private void eat() throws InterruptedException {
System.out.println("Philosopher " + id + " is eating.\n");
System.out.flush();
do{
eattime=new Random().nextInt(10);
//generate a random value for eat time which is greater than 0
}while (eattime<=0);
if (amount+eattime*5>100){
eattime=(100-amount)/5;
amount=100;
}else {
amount=amount+eattime*5;
}
Thread.sleep(eattime);
}
private void putDownChopsticks() {
leftChopstick.release();
rightChopstick.release();
System.out.println("Philosopher " + id + " ate "+amount+"% and"+" released left and right sticks \n");
}
}
| true |
0ce1b06c1c332ecf51e4132d13d1b93e3fe47d55
|
Java
|
GS-Consultorio/consultorio-backend
|
/src/main/java/org/bedu/consultorio/controller/PacienteController.java
|
UTF-8
| 2,415 | 2.15625 | 2 |
[] |
no_license
|
package org.bedu.consultorio.controller;
import org.bedu.consultorio.model.persona.Paciente;
import org.bedu.consultorio.services.PacienteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import org.bedu.consultorio.exceptions.RestException;
@RestController
@RequestMapping("/paciente/")
@CrossOrigin(origins = "http://localhost:4200")
public class PacienteController {
@Autowired
private PacienteService pacienteService;
@PostMapping("/savePaciente")
public Paciente savePaciente(@RequestBody Paciente paciente) {
try {
return pacienteService.savePaciente(paciente);
}catch(RestException e) {
throw new ResponseStatusException(HttpStatus.CONFLICT, e.getMessage());
}
}
@GetMapping("/getAllPaciente")
public List<Paciente> getAllPaciente() {
try {
return pacienteService.getAllPaciente();
}catch(RestException e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
}
}
@GetMapping("/getPaciente/{id}")
public Paciente getPaciente(@PathVariable Long id ) {
try {
return pacienteService.getPaciente(id);
}catch(RestException e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
}
}
@PutMapping("/updatePaciente/{id}")
public Paciente updatePaciente(@RequestBody Paciente paciente) {
try {
return pacienteService.updatePaciente(paciente);
}catch(RestException e) {
throw new ResponseStatusException(HttpStatus.CONFLICT, e.getMessage());
}
}
@DeleteMapping("/deletePaciente/{id}")
public void deletePaciente(@PathVariable Long id) {
try {
pacienteService.deletePaciente(id);
}catch(RestException e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
}
}
}
| true |
ff4e4e6cae8d36221991cc772ae6919e196e5271
|
Java
|
rowtn/Granite
|
/src/main/java/org/granitemc/granite/api/plugin/PluginLoader.java
|
UTF-8
| 4,815 | 2.28125 | 2 |
[
"MIT"
] |
permissive
|
package org.granitemc.granite.api.plugin;
import java.lang.reflect.InvocationTargetException;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.granitemc.granite.api.GraniteAPI;
import org.granitemc.granite.utils.Logger;
/**
* License (MIT)
*
* Copyright (c) 2014. Granite Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the
* Software without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
public class PluginLoader {
URLClassLoader loader = (URLClassLoader) java.lang.ClassLoader.getSystemClassLoader();
Logger.PluginLogger log = new Logger.PluginLogger("pluginloader");
JarFile f;
public PluginLoader(JarFile f) throws IllegalArgumentException {
this.f = f;
}
private void doLoading(Class<?> clazz) {
PluginContainer container = GraniteAPI.instance().loadClassPlugin(clazz);
try {
container.setup();
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException | InstantiationException e) {
e.printStackTrace();
}
}
@SuppressWarnings("static-method")
private List<Class<?>> iterateJar(JarFile f) {
List<Class<?>> ret = new ArrayList<Class<?>>();
List<JarEntry> peeked = new ArrayList<JarEntry>();
JarEntry entry;
while ((entry = f.entries().nextElement()) != null) {
log.info("Peeking %s.", entry);
if (entry.getName().toLowerCase().endsWith(".class")) {
log.info("Found class file %s.", entry.getName());
try {
ret.add(loader.loadClass(entry.getName().replace('/', '.').substring(0, entry.getName().lastIndexOf('.'))));
break;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
peeked.add(entry);
}else if(entry.isDirectory() || entry.getName().endsWith(".")){
continue;
}else {
continue;
}
}
return ret;
}
@SuppressWarnings("static-method")
private Class<?>[] findPlugins(Class<?>[] candidates) {
int i = 1;
for(Class<?> clazz : candidates) {
Logger.info("Candidate %s : %s", i, clazz);
i++;
}
List<Class<?>> ret = new ArrayList<Class<?>>();
for (Class<?> clazz : candidates) {
if(clazz.getInterfaces().length == 0 || clazz.getInterfaces() == null) {
Logger.info("Class %s does not have any interfaces present.", clazz);
continue;
}
try {
Logger.info("Searching for interface IPlugin in %s", clazz);
for(Class<?> class1 : clazz.getInterfaces()) {
if(class1.equals(IPlugin.class)) {
ret.add(class1);
Logger.info("Found IPlugin in class %s", clazz);
}else {
Logger.info("Didn't find IPlugin in class %s, but I found %s", clazz, class1);
}
}
} catch (Exception e) {
}
}
return ret.toArray(new Class<?>[10000]);
}
public void run() {
log.info("Finding class candidates");
log.info("Total candidates possible : " + f.size());
Class<?>[] candidates = iterateJar(f).toArray(new Class[f.size()]);
log.info("Finding actual mod classes");
Class<?>[] modClasses = findPlugins(candidates);
log.info("Loading actual mod classes");
if(modClasses.length == 0 || modClasses == null) {
Logger.info("No plugins found in %s.", f);
return;
}
for (Class<?> clazz : modClasses) {
doLoading(clazz);
}
}
}
| true |
7b2f498c82b8131d172c19b54a9894ded3a0cf0d
|
Java
|
JoyRapture/morahaji
|
/src/net/word/action/WordModifyView.java
|
UHC
| 861 | 2.1875 | 2 |
[] |
no_license
|
package net.word.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.Action.Action;
import net.Action.ActionForward;
import net.word.db.WORD;
import net.word.db.WordDAO;
public class WordModifyView implements Action {
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
ActionForward forward = new ActionForward();
WordDAO dao = new WordDAO();
WORD word = new WORD();
int wordKey = Integer.parseInt(request.getParameter("wordKey"));
word = dao.getDetailForModify(wordKey);
System.out.println(" ̵ ");
request.setCharacterEncoding("UTF-8");
request.setAttribute("word", word);
forward.setRedirect(false);
forward.setPath("./word.register/index_modify.jsp");
return forward;
}
}
| true |
1d88adb4b8993206fdf16111d50e8498565de759
|
Java
|
BharathiKannanB/SeleniumProject
|
/src/main/java/pagesPOM/MyFindLeadsPage.java
|
UTF-8
| 1,033 | 2.21875 | 2 |
[] |
no_license
|
package pagesPOM;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import wdMethods.ProjectMethods;
public class MyFindLeadsPage extends ProjectMethods {
public MyFindLeadsPage()
{
PageFactory.initElements(driver, this);
}
@FindBy(xpath = "//div[@style='padding-left:155px']/input")
WebElement eleLeadId;
public MyFindLeadsPage enterLeadId(String leadId)
{
type(eleLeadId, leadId);
return this;
}
@FindBy(xpath = "//div[@style='padding-left:155px']/input")
WebElement eleFLeadsB;
public MyFindLeadsPage clickFindLeadsB() throws InterruptedException
{
click(eleFLeadsB);
Thread.sleep(5000);
return this;
}
@FindBy(xpath = "//table[@class='x-grid3-row-table']/tbody/tr/td/div/a")
WebElement eleClickLeadId;
public ViewLeadPage clickLeadId() throws InterruptedException
{
clickWithNoSnap(eleClickLeadId);
Thread.sleep(5000);
return new ViewLeadPage();
}
}
| true |
91618abd346afad6fe64311cb5dd6eea08fd717a
|
Java
|
L-bin/toutiao
|
/src/main/java/bin/controller/NewsController.java
|
GB18030
| 3,515 | 2.25 | 2 |
[] |
no_license
|
package bin.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import bin.model.Comment;
import bin.model.EntityType;
import bin.model.HostHolder;
import bin.model.News;
import bin.model.ViewObject;
import bin.service.CommentService;
import bin.service.LikeService;
import bin.service.NewsSerivice;
import bin.service.UserService;
import bin.util.ToutiaoUtil;
@Controller
public class NewsController {
@Autowired
private NewsSerivice newsSerivice;
@Autowired
private HostHolder hostHolder;
@Autowired
private UserService userService;
@Autowired
private CommentService commentService;
@Autowired
private LikeService likeService;
@RequestMapping(path={"/news/{newsId}"})
public String newsDetail(@RequestParam("newsId") int newsId,Model model){
News news=newsSerivice.getById(newsId);
if(news!=null){
int localUserId = hostHolder.getUser() != null ? hostHolder.getUser().getId() : 0;
if (localUserId != 0) {
model.addAttribute("like", likeService.getLikeStatus(localUserId, news.getId(),EntityType.ENTITY_NEWS));
} else {
model.addAttribute("like", 0);
}
List<Comment> comments= commentService.getCommentsByEntity(news.getId(), EntityType.ENTITY_NEWS);
List<ViewObject> vos=new ArrayList<ViewObject>();
for(Comment comment:comments){
ViewObject vo=new ViewObject();
vo.set("comment", comment);
vo.set("user", userService.getUser(comment.getUserId()));
vos.add(vo);
}
model.addAttribute("comments",vos);
}
model.addAttribute("news",news);
model.addAttribute("owner",userService.getUser(news.getUserId()));
return "detail";
}
@RequestMapping(path={"/user/addNews"},method={RequestMethod.POST})
@ResponseBody
public String addNews(@RequestParam("image") String image,
@RequestParam("title") String title,
@RequestParam("link") String link){
try{
News news=new News();
if(hostHolder.getUser()!=null){
news.setUserId(hostHolder.getUser().getId());
}else{
//û
news.setUserId(3);
}
news.setImage(image);
news.setLink(link);
news.setTitle(title);
news.setCreatedDate(new Date());
newsSerivice.addNews(news);
return ToutiaoUtil.getJSONString(0);
}catch(Exception e){
return ToutiaoUtil.getJSONString(1, "Ѷʧ");
}
}
@RequestMapping(path={"/addComment"},method={RequestMethod.POST})
public String addComment(@RequestParam("content") String content,
@RequestParam("newsId") int newsId){
try{
Comment comment=new Comment();
comment.setStatus(0);
comment.setEntityId(newsId);
comment.setContent(content);
comment.setUserId(hostHolder.getUser().getId());
comment.setCreatedDate(new Date());
comment.setEntityType(EntityType.ENTITY_NEWS);
commentService.addComment(comment);
int count=commentService.getCommentCount(comment.getEntityId(), comment.getEntityType());
newsSerivice.updateCommentCount(count, comment.getEntityId());
}catch(Exception e){
}
return "redirect:/news/"+String.valueOf(newsId);
}
}
| true |
5237bcaadb3528cb6af95e49951e134ec68874ec
|
Java
|
Leoxinghai/Citiville
|
/app/src/main/java/Display/DialogUI/SpecialsCongratsDialog.java
|
UTF-8
| 2,782 | 1.757813 | 2 |
[] |
no_license
|
package Display.DialogUI;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
import android.graphics.*;
import com.xiyu.util.Array;
import com.xiyu.util.Dictionary;
import Classes.*;
import Display.*;
import Engine.Managers.*;
//import flash.display.*;
//import flash.utils.*;
public class SpecialsCongratsDialog extends GenericDialog
{
private SpecialsCongratsDialogView m_dialogView ;
public static Item specialsItem ;
public SpecialsCongratsDialog (String param1 ,String param2 ="",int param3 =0,Function param4 =null ,String param5 ="",String param6 ="",boolean param7 =true ,int param8 =0,String param9 ="",Function param10 =null ,String param11 ="",boolean param12 =true ,Item param13 =null )
{
specialsItem = param13;
super(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, param11);
return;
}//end
public void setItem (String param1 )
{
specialsItem = Global.gameSettings().getItemByName(param1);
return;
}//end
protected GenericDialogView createDialogView (Dictionary param1 )
{
this.m_dialogView = new SpecialsCongratsDialogView(param1, m_message, m_dialogTitle, m_type, this.closeAndShow, m_icon, m_iconPos, "", null, m_customOk, true, specialsItem);
StatsManager.count("bogo", "congrats_dialog", "view");
return this.m_dialogView;
}//end
public void closeAndShow ()
{
UI.displayInventory(specialsItem.name);
return;
}//end
protected Dictionary createAssetDict ()
{
Dictionary _loc_1 =new Dictionary ();
_loc_1.put("dialog_bg", new (DisplayObject)m_comObject.dialog_bg());
_loc_1.put("extra_dialog_bg", new (DisplayObject)EmbeddedArt.citySam_congratsAward());
_loc_1.put("reward_burst", new (DisplayObject)EmbeddedArt.reward_burst());
return _loc_1;
}//end
}
| true |
56fcb93c35dd2f18b7467e1b529a6b06e52313f1
|
Java
|
amitrew3/financial-v2
|
/src/main/java/com/rew3/billing/payment/command/DepositItemQueryHandler.java
|
UTF-8
| 2,243 | 2.203125 | 2 |
[] |
no_license
|
package com.rew3.billing.payment.command;
import com.rew3.billing.payment.model.BillingAccount;
import com.rew3.billing.payment.model.DepositItem;
import com.rew3.common.application.CommandException;
import com.rew3.common.application.NotFoundException;
import com.rew3.common.cqrs.IQueryHandler;
import com.rew3.common.cqrs.Query;
import com.rew3.common.database.HibernateUtils;
import com.rew3.common.model.Flags;
import com.rew3.common.model.PaginationParams;
import com.rew3.common.utils.Parser;
import java.util.HashMap;
import java.util.List;
public class DepositItemQueryHandler implements IQueryHandler {
@Override
public Object getById(String id) throws CommandException, NotFoundException {
DepositItem rd = (DepositItem) HibernateUtils.get(DepositItem.class, id);
if (rd == null) {
throw new NotFoundException("Normal User id(" + id + ") not found.");
}
if (rd.getStatus() == Flags.EntityStatus.DELETED.toString())
throw new NotFoundException("Normal User id(" + id + ") not found.");
return rd;
}
@Override
public List<Object> get(Query q) {
HashMap<String, Object> sqlParams = new HashMap<String, Object>();
HashMap<String, String> filterParams = new HashMap<>();
String whereSQL = " WHERE 1=1 ";
int page = PaginationParams.PAGE;
int limit = PaginationParams.LIMIT;
int offset = 0;
if (q.has("page")) {
page = Parser.convertObjectToInteger(q.get("page"));
}
if (q.has("limit")) {
limit = Parser.convertObjectToInteger(q.get("limit"));
}
if (q.has("ownerId")) {
whereSQL += " AND ownerId = :ownerId ";
sqlParams.put("ownerId", q.get("ownerId"));
}
if (q.has("depositSlipId")) {
whereSQL += " AND deposit_slip_id = :depositSlipId ";
sqlParams.put("depositSlipId", q.get("depositSlipId"));
}
offset = (limit * (page - 1));
System.out.println(sqlParams.toString());
List<Object> depositItems = HibernateUtils.select("FROM DepositItem " + whereSQL, sqlParams, q.getQuery(), limit, offset);
return depositItems;
}
}
| true |
9cb892d01f7689bce54f020b5cc4fb55ad39fac1
|
Java
|
khl7/Automated_Emails_Generation
|
/Automated_Emails_Generation/src/test/java/edu/neu/ccs/cs5004/assignment9/MainTest.java
|
UTF-8
| 1,049 | 2.5625 | 3 |
[] |
no_license
|
package edu.neu.ccs.cs5004.assignment9;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class MainTest {
private Main MainA;
private Main MainB;
private Main MainC;
private ReadTemplate diffObj;
@Before
public void setUp() throws Exception {
MainA = new Main();
MainB = new Main();
MainC = new Main();
diffObj = new ReadTemplate();
}
@Test
public void testHashCode() {
assertEquals(MainA.hashCode(), MainA.hashCode());
assertEquals(MainA.hashCode(), MainB.hashCode());
assertEquals(MainB.hashCode(), MainC.hashCode());
assertEquals(MainA.hashCode(), MainC.hashCode());
}
@Test
public void testEquals() {
assertEquals(MainA, MainA);
assertEquals(MainA, MainB);
assertEquals(MainB, MainC);
assertEquals(MainA, MainC);
}
@Test
public void testEqualsDiffObj() {
assertNotEquals(MainA, diffObj);
}
@Test
public void testToString() {
String expected = "Main{}";
assertEquals(expected, MainA.toString());
}
}
| true |
7dd3a3824275c6c1a1e56651ffd740b5f2530e7d
|
Java
|
mchirlin/ps-ext-FitNesseForAppian
|
/src/main/java/com/appiancorp/ps/automatedtest/properties/FieldLayoutWaitForReturn.java
|
UTF-8
| 329 | 1.570313 | 2 |
[] |
no_license
|
package com.appiancorp.ps.automatedtest.properties;
import org.openqa.selenium.WebElement;
public interface FieldLayoutWaitForReturn extends FieldLayoutWaitFor {
public boolean waitForReturn(int timeout, WebElement fieldLayout, String... params);
public boolean waitForReturn(WebElement fieldLayout, String... params);
}
| true |
e429f22212c439bd9c69fc8815d9311f3278c853
|
Java
|
Nicolau643/SoftwareValidationAndVerification
|
/Project1/Code/src/test/java/sut/instruction/GetTest.java
|
UTF-8
| 1,696 | 3.203125 | 3 |
[] |
no_license
|
package sut.instruction;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import sut.TST;
/**
* Returns the value associated with the given key.
* @param key the key
* @return the value associated with the given key if the key is in the symbol table
* and {@code null} if the key is not in the symbol table
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
/*public T get(String key) {
if (key == null)
throw new IllegalArgumentException("calls get() with null argument");
if (key.length() == 0)
throw new IllegalArgumentException("key must have length >= 1");
Node<T> x = get(root, key, 0);
if (x == null)
return null;
return x.val;
}*/
public class GetTest {
private static TST<Integer> i;
@BeforeEach
void init() {
i = new TST<>();
String[] data = {"ola","odado","dado","dador","dardo","palha","pala","porta",
"data","dita","oleo","oleado","dadora","ditado"};
for (int j = 0; j < data.length; j++) {
i.put(data[j],j+1);
}
}
/*
* Requisitos de teste: I1, I2
*/
@Test
void test1() {
assertThrows(IllegalArgumentException.class, () ->{i.get(null);});
}
/*
* Requisitos de teste: I1, I3, I4
*/
@Test
void test2() {
assertThrows(IllegalArgumentException.class, () ->{i.get("");});
}
/*
* Requisitos de teste: I1, I3, I5, I6, I8
*/
@Test
void test3() {
assertEquals((Integer)3,i.get("dado"));
}
/*
* Requisitos de teste: I1, I3, I5, I6, I7
*/
@Test
void test4() {
assertEquals(null,i.get("adeus"));
}
}
| true |
54c6514d9003a11df405882e86ec160b7be2ffbb
|
Java
|
WmCodes/architecture
|
/src/main/java/xyz/drafter/architecture/gupao/pattern/template/RowMapper.java
|
UTF-8
| 246 | 2.25 | 2 |
[] |
no_license
|
package xyz.drafter.architecture.gupao.pattern.template;
import java.sql.ResultSet;
/**
* @author wangmeng
* @date 2019/8/25
* @desciption
*/
public interface RowMapper<T> {
public T mapRow(ResultSet rs,int rouNum) throws Exception;
}
| true |
cb45c9870510d81a4d525400c38b37ce1c312d49
|
Java
|
Cognizant-Training-Coimbatore/Lab-Excercise
|
/PearlSerrao/24JAN2020/guess.java
|
UTF-8
| 341 | 3.21875 | 3 |
[] |
no_license
|
package demo;
import java.util.Scanner;
public class guess {
public static void main(String[] args)
{
for(int i=3;i>=1;i--)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
if( n==9)
{
System.out.println("great it is a correct guess");
}
else
{
System.out.println("Ooops its a wrong guess");
}
}
}
}
| true |
764c30665c8e445773c7247697fc450df6a55383
|
Java
|
Lancersaber/First
|
/设计模式/DesignPattherns/src/com/lancer/结构型模式/组合模式/test.java
|
UTF-8
| 326 | 2.90625 | 3 |
[] |
no_license
|
package com.lancer.结构型模式.组合模式;
public class test {
/**
*
* 模式定义:
*
* 组合模式(Composite Pattern),将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
*
*/
}
| true |
8730c11c32dc0b6b128d7178731ea5cb2663666f
|
Java
|
1350574027/trainticketing
|
/src/main/java/com/controller/SeatController.java
|
UTF-8
| 6,935 | 2.125 | 2 |
[] |
no_license
|
package com.controller;
import com.entity.ShowResult;
import com.entity.Traininfo;
import com.entity.Trainseat;
import com.service.IIndexService;
import com.service.IOrderService;
import com.service.ISeatService;
import com.util.Conversion;
import org.omg.CORBA.INTERNAL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Array;
import java.util.*;
@Controller
@RequestMapping(value = "/seat")
public class SeatController {
@Autowired
private ISeatService seatService;
@Autowired
private IIndexService indexService;
@Autowired
private IOrderService orderService;
@RequestMapping("/findSeatnum.do")
public String findSeatnum(HttpServletRequest request){
Integer seatnum = 0;
Integer trainstate = (Integer) request.getSession().getAttribute("trainstate");
List<String> trainid = indexService.findStateid(trainstate);
String id = trainid.get(0);
Traininfo traininfo = seatService.findTraininfo(id);
Trainseat trainseats = seatService.findtrainseat(trainstate);
Conversion conversion =new Conversion();
int[] seat = conversion.tentotwo(trainseats,traininfo,request);
request.getSession().setAttribute("seat",seat);
for(int i = 0;i<seat.length;i++){
if(seat[i]==0){
seatnum++;
}
}
int state = (int)request.getSession().getAttribute("trainstate");
String ss = "needmoney"+state;
Float money = (Float) request.getSession().getAttribute(ss);
String adult = (String)request.getSession().getAttribute("adult");
if(adult.equals("儿童")){
money = money/2;
}
if(adult.equals("学生")){
money = money*(float)0.7;
}
request.getSession().setAttribute("money",money);
request.getSession().setAttribute("seatnum",seatnum);
return "/WEB-INF/index/selectSeat";
}
@RequestMapping("/buyticket.do")
public ModelAndView buyticket(String selectseat,HttpServletRequest request){
ModelAndView modelAndView = new ModelAndView();
int[] seat = (int[]) request.getSession().getAttribute("seat");
Integer carriagenumber = (Integer) request.getSession().getAttribute("carriagenumber");
System.out.println("车厢数量="+carriagenumber);
Integer i = Integer.parseInt(selectseat);
int size = seat.length;
Integer carpeo = size/carriagenumber;
int line = size/5;
int num = 0;
int state = 0;
int[] seats = seat.clone();
for(int j=0;j<line;j++){
num=j*5;
if(seat[num+i]==0){
seat[num+i]=1;
state = num+i;
System.out.println("到了");
break;
}
}
if(Arrays.toString(seats).equals(Arrays.toString(seat))){
for(int x=0;x<size;x++){
if(seat[x]==0){
seat[x]=1;
state=x;
System.out.println("这里");
break;
}
}
}
System.out.println("下标为:"+state);
System.out.println(Arrays.toString(seats));
System.out.println(Arrays.toString(seat));
StringBuilder sb = new StringBuilder();
for(int y = size-1;y>=0;y--){
sb.append(seat[y]);
}
ShowResult showResult = new ShowResult();
String a =""+sb;
System.out.println(a);
String seatresult = Integer.valueOf(a,2).toString();
System.out.println(seatresult);
Integer seatsresult = Integer.valueOf(seatresult);
showResult.setSeatid(seatsresult);
Integer trainstate = (Integer) request.getSession().getAttribute("trainstate");
showResult.setTrainstate(trainstate);
List<String> trainid = indexService.findStateid(trainstate);
String aa = trainid.get(0);
showResult.setTrainid(aa);
float money = (float) request.getSession().getAttribute("money");
showResult.setNeedmoney1(money);
Date chufatime = (Date) request.getSession().getAttribute("chufatime1");
showResult.setChufatime(chufatime);
Date daodatime = (Date) request.getSession().getAttribute("daodatime");
showResult.setDaodatime(daodatime);
String chufa = (String) request.getSession().getAttribute("chufa");
showResult.setChufa(chufa);
String daoda = (String) request.getSession().getAttribute("daoda");
showResult.setDaoda(daoda);
state = state+1;
Integer carnum = 0;
for(int o =1;o<=carriagenumber;o++){
if(state<=o*carpeo){
carnum =o;
break;
}
}
showResult.setCarriageid(carnum);
state=state-1;
Integer seatid = state-(carnum-1)*carpeo;
Integer lines = seatid/5+1;
showResult.setLiness(lines);
Integer c = seatid%5;
String seatss = null;
if(c==0){
seatss="A座左靠窗";
}else if(c==1){
seatss="B座左中间";
}else if(c==2){
seatss="C座左过道";
}else if(c==3){
seatss="D座右过道";
}else if(c==4){
seatss="F座右靠窗";
}
showResult.setSeat(seatss);
String loginName = (String) request.getSession().getAttribute("loginName");
showResult.setLoginName(loginName);
seatService.updateSeatid(showResult);
System.out.println(showResult.getSeatid()+"---"+showResult.getTrainstate());
List<ShowResult>showResultList = new ArrayList<ShowResult>();
System.out.println("login="+showResult.getLoginName());
System.out.println("chufa="+showResult.getChufa());
System.out.println("daoda="+showResult.getDaoda());
System.out.println("chufatime="+showResult.getChufatime());
System.out.println("daodatime="+showResult.getDaodatime());
System.out.println("needmoney"+showResult.getNeedmoney1());
System.out.println("trainid="+showResult.getTrainid());
System.out.println("state="+showResult.getTrainstate());
System.out.println("carrageid="+showResult.getCarriageid());
System.out.println("lines="+showResult.getLiness());
System.out.println("seat="+showResult.getSeat());
orderService.insertorder(showResult);
showResultList.add(showResult);
modelAndView.addObject("showResult1",showResultList);
modelAndView.setViewName("/WEB-INF/index/buyticket");
return modelAndView;
}
}
| true |
548ead126414ccd8000b5e7e3690fae27eae35fa
|
Java
|
985498203/hrsystem
|
/src/main/java/com/hxzy/hrsystem/entity/Over.java
|
UTF-8
| 673 | 2 | 2 |
[] |
no_license
|
package com.hxzy.hrsystem.entity;
import java.io.Serializable;
/**
* 加班表over
*
*/
public class Over implements Serializable {
private static final long serialVersionUID = -8906433778514894583L;
private Integer overId;
private User user;
private String overTime;
public Integer getOverId() {
return overId;
}
public void setOverId(Integer overId) {
this.overId = overId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getOverTime() {
return overTime;
}
public void setOverTime(String overTime) {
this.overTime = overTime;
}
}
| true |
f064df466d6b74525a2c09a20aea5424f1c26c7a
|
Java
|
1475466469/shop
|
/src/main/java/com/shop/shop/service/SysMenuService.java
|
UTF-8
| 349 | 1.765625 | 2 |
[] |
no_license
|
package com.shop.shop.service;
import com.shop.shop.entity.SysMenuEntity;
import java.util.List;
public interface SysMenuService {
SysMenuEntity findone(long id) ;
List<SysMenuEntity> findAll() ;
SysMenuEntity Save(SysMenuEntity sysMenuEntity) throws Exception;
void delete(SysMenuEntity sysMenuEntity) throws Exception;
}
| true |
37775c8109e04b95091e265b481e3b312c742306
|
Java
|
cezarykluczynski/stapi
|
/etl/src/main/java/com/cezarykluczynski/stapi/etl/template/video_game/processor/VideoGameTemplateCompositeEnrichingProcessor.java
|
UTF-8
| 1,463 | 2.09375 | 2 |
[
"MIT"
] |
permissive
|
package com.cezarykluczynski.stapi.etl.template.video_game.processor;
import com.cezarykluczynski.stapi.etl.common.dto.EnrichablePair;
import com.cezarykluczynski.stapi.etl.common.processor.ItemWithTemplateEnrichingProcessor;
import com.cezarykluczynski.stapi.etl.mediawiki.dto.Template;
import com.cezarykluczynski.stapi.etl.template.video_game.dto.VideoGameTemplate;
import org.springframework.stereotype.Service;
@Service
public class VideoGameTemplateCompositeEnrichingProcessor implements ItemWithTemplateEnrichingProcessor<VideoGameTemplate> {
private final VideoGameTemplateContentsEnrichingProcessor videoGameTemplateContentsEnrichingProcessor;
private final VideoGameTemplateRelationsEnrichingProcessor videoGameTemplateRelationsEnrichingProcessor;
public VideoGameTemplateCompositeEnrichingProcessor(VideoGameTemplateContentsEnrichingProcessor videoGameTemplateContentsEnrichingProcessor,
VideoGameTemplateRelationsEnrichingProcessor videoGameTemplateRelationsEnrichingProcessor) {
this.videoGameTemplateContentsEnrichingProcessor = videoGameTemplateContentsEnrichingProcessor;
this.videoGameTemplateRelationsEnrichingProcessor = videoGameTemplateRelationsEnrichingProcessor;
}
@Override
public void enrich(EnrichablePair<Template, VideoGameTemplate> enrichablePair) throws Exception {
videoGameTemplateContentsEnrichingProcessor.enrich(enrichablePair);
videoGameTemplateRelationsEnrichingProcessor.enrich(enrichablePair);
}
}
| true |
7e79b7f868ca8b91791c121b5011929e2542dde4
|
Java
|
manasi517/ordermyfood
|
/ordermanagement/src/main/java/com/mindtree/ordermyfood/ordermanagement/dto/ReviewsResponseDto.java
|
UTF-8
| 1,198 | 2.109375 | 2 |
[] |
no_license
|
package com.mindtree.ordermyfood.ordermanagement.dto;
public class ReviewsResponseDto {
private double rating ;
private String review_text ;
private String review_time_friendly ;
private String rating_text ;
private int likes ;
private String userName;
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
public String getReview_text() {
return review_text;
}
public void setReview_text(String review_text) {
this.review_text = review_text;
}
public String getReview_time_friendly() {
return review_time_friendly;
}
public void setReview_time_friendly(String review_time_friendly) {
this.review_time_friendly = review_time_friendly;
}
public String getRating_text() {
return rating_text;
}
public void setRating_text(String rating_text) {
this.rating_text = rating_text;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
| true |
27963f8b0c89448c7915111794dfa2cad744eb19
|
Java
|
leorian/navi
|
/navi/src/test/java/com/baidu/beidou/navi/zk/TestZooKeeperClient.java
|
UTF-8
| 5,036 | 2.375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.baidu.beidou.navi.zk;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
public class TestZooKeeperClient {
private static CountDownLatch semaphore = new CountDownLatch(1);
public static void main(String[] args) {
new TestZooKeeperClient().simpleClient();
}
private final static String auth = "beidouRd123";
public void simpleClient() {
String connectString = "10.48.56.33:8701,10.48.52.17:8701,10.48.52.31:8701,10.94.37.23:8701,10.94.37.24:8701";
try {
// TestWatcher watcher = new TestWatcher();
ServiceWatcher watcher = new ServiceWatcher();
SimpleZooKeeperClient zkClient = new SimpleZooKeeperClient(connectString, watcher, auth, 20000);
// String path = "/navi";
// System.out.println("before: " + new String(zkClient.getData(path)));
// zkClient.setData(path, String.valueOf(System.currentTimeMillis()).getBytes());
// System.out.println("after: " + new String(zkClient.getData(path)));
//
// String path = "/test";
// zkClient.createNode(path, "123".getBytes());
// zkClient.createNode(path, "123".getBytes());
// String path2 = "/aaa1/bbb1";
// zkClient.createSessionNode(path2, "".getBytes());
// String path3 = "/aaa1/bbb1/ccc1";
// zkClient.createSessionNode(path3, "".getBytes());
// String data = "123";
// zkClient.setData(path3, data.getBytes());
// System.out.println("now: " + new String(zkClient.getData(path3)));
String path = "/navi_rpc/unbiz/soma/bizserv/sync-report/qa";
zkClient.delete(path);
path = "/navi_rpc/unbiz/soma/bizserv/sync-report/qa/ReportUserCostService";
zkClient.delete(path);
path = "/navi_rpc/unbiz/soma/bizserv/sync-report/qa/ReportLiteService";
zkClient.delete(path);
path = "/navi_rpc/unbiz/soma/bizserv/sync-report/qa/ReportBasicService";
zkClient.delete(path);
//zkClient.createSessionNode(path, "".getBytes());
//zkClient.createSessionNode(path + "/uuu", "".getBytes());
// zkClient.delete(path);
// List<String> childs = zkClient.getChildren(path);
// for (String child : childs) {
// System.out.println(child);
// }
// if (zkClient.exists(path) == null) {
// zkClient.createSessionNodeForRecursive(path + "/1.1.1.1", "".getBytes());
// zkClient.createSessionNodeForRecursive(path + "/2.2.2.2", "".getBytes());
// zkClient.createSessionNodeForRecursive(path + "/3.3.3.3", "".getBytes());
// zkClient.createSessionNodeForRecursive(path + "/4.4.4.4", "".getBytes());
// }
// String pathIP1 = path + "/1.1.1.1";
// String pathIP2 = path + "/2.2.2.2";
// zkClient.createSessionNode(pathIP1, NetUtils.getLocalAddress().getAddress());
// zkClient.createSessionNode(pathIP2, NetUtils.getLocalAddress().getAddress());
// System.out.println("children: " + Arrays.toString(zkClient.getChildren(path).toArray()));
// System.out.println("pathIP2: " + new String(zkClient.getData(pathIP2)));
semaphore.await();
// path = "/aaa/bbb3";
// Stat stat = zkClient.exists(path);
Thread.sleep(100000);
} catch (Exception e) {
e.printStackTrace();
}
}
class ServiceWatcher implements Watcher {
/**
* Process when receive watched event
*/
@Override
public void process(WatchedEvent event) {
System.out.println("Receive watched event:" + event);
if (KeeperState.SyncConnected == event.getState()) {
// if( EventType.None == event.getType() && null == event.getPath() ){
// System.out.println("12333333333333333333");
// }else
if (event.getType() == EventType.NodeDataChanged) {
// children list changed
try {
// System.out.println( this.getChildren( event.getPath() ) );
// _semaphore.countDown();
System.out.println("changed!");
semaphore.countDown();
} catch (Exception e) {
}
}
}
}
}
}
class TestWatcher implements Watcher {
@Override
public void process(WatchedEvent arg0) {
System.out.println("TestWatcher - " + arg0.getPath());
}
}
| true |
1cd357b4d5bf8b28bb592bfc8e7a066062ea62dc
|
Java
|
harrisosserman/risc
|
/risc/app/models/Territory.java
|
UTF-8
| 2,275 | 3.015625 | 3 |
[
"Apache-2.0"
] |
permissive
|
package models;
import java.util.*;
import models.Attacker;
public class Territory{
private Player myOwner;
private int myTroops;
private int myPosition;
private int myFood;
private int myTechnology;
private HashMap<Integer, Attacker> attackers;
private Army myArmy;
private HashMap<Player, Army> alliedTroops;
public Territory(int position, Player owner, int food, int technology){
myPosition = position;
myOwner = owner;
myTechnology = technology;
myFood = food;
myArmy = new Army(myOwner);
attackers = new HashMap<Integer, Attacker>();
alliedTroops = new HashMap<Player, Army>();
}
public void addAlly(Player p, Army a){
alliedTroops.put(p, a);
}
public Army getAllyArmy(Player p){
return alliedTroops.get(p);
}
public HashMap<Player, Army> getAllies(){
return alliedTroops;
}
public void setAllies(HashMap<Player, Army> a){
alliedTroops = a;
}
public int getFood(){
return myFood;
}
public int getNumberOfTroops(){
return myArmy.getNumberOfTroops();
}
public int getTechnology(){
return myTechnology;
}
public int getPosition(){
return myPosition;
}
public Player getOwner(){
return myOwner;
}
public void setOwner(Player owner){
myOwner = owner;
}
public Army getDefendingArmy(){
return myArmy;
}
public void removeTroopFromArmy(TroopType type){
myArmy.deleteTroop(type);
}
public void setDefendingArmy(Army army_){
myArmy = army_;
}
public void addTroop(Troop t){
myArmy.addTroop(t.getType());
}
public void addTroop(TroopType type){
myArmy.addTroop(type);
}
public boolean tryToDeleteTroop(TroopType type){
if(myArmy.containsTroop(type)){
myArmy.deleteTroop(type);
return true;
}
else{
return false;
}
}
public void addTrooptoAttacker(Integer position, TroopType t, Player p){
if(attackers.containsKey(position)){
Attacker a = attackers.get(position);
a.addTroop(t);
attackers.put(position, a);
}
else{
Attacker a = new Attacker(p, position);
a.addTroop(t);
attackers.put(position, a);
}
}
public HashMap<Integer, Attacker> getAttackers(){
return attackers;
}
public void clearAttackers(){
attackers = new HashMap<Integer, Attacker>();
}
}
| true |
be7f7f0590e6ead72d26cc72283dbfcd1dbbb862
|
Java
|
DDstar/BleDemo
|
/app/src/main/java/com/example/rqg/bledemo/BongApp.java
|
UTF-8
| 415 | 1.867188 | 2 |
[] |
no_license
|
package com.example.rqg.bledemo;
import android.app.Application;
import cn.ginshell.sdk.BongSdk;
import cn.ginshell.sdk.model.Gender;
/**
* Created by rqg on 17/11/2016.
*/
public class BongApp extends Application {
@Override
public void onCreate() {
super.onCreate();
BongSdk.enableDebug(true);
BongSdk.setUser(175, 25f, Gender.MALE);
BongSdk.initSdk(this);
}
}
| true |
14c23af297de4ba79959c74a1f9f066804a7f4e1
|
Java
|
tgh12/GW
|
/MOBILE_PORTAL/Vendor-Portal-master/src/main/java/edge/portal/vendor/web/user/PendingUser.java
|
UTF-8
| 1,396 | 2.34375 | 2 |
[] |
no_license
|
package edge.portal.vendor.web.user;
import javax.persistence.CascadeType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.OneToOne;
/**
* Represents an account where the vendor
* has been added, but has not yet signed into
* the portal.
*/
@Entity
@DiscriminatorValue(value = "PA")
public class PendingUser extends AccountUser {
public static final String ID_PREFIX = "$pending_";
@OneToOne(cascade = CascadeType.ALL, mappedBy = "pendingUser")
private Token token;
public Token getToken() {
return token;
}
public void setToken(Token token) {
this.token = token;
}
//needed to work around https://bugs.eclipse.org/bugs/show_bug.cgi?id=336731
//--add prefix to ID and remove it when converted to a VendorUser.
@Override
public void setSpecialistId(String vendorId) {
if(vendorId.startsWith(ID_PREFIX)) {
super.setSpecialistId(vendorId);
} else {
super.setSpecialistId(ID_PREFIX + vendorId);
}
}
@Override
public String getSpecialistId() {
String rawId = super.getSpecialistId();
int index = rawId.indexOf(ID_PREFIX);
return index >= 0 ? rawId.substring(index + ID_PREFIX.length()) : rawId;
}
public String getTemporaryId() {
return super.getSpecialistId();
}
}
| true |
9c04a6b0c3f3d36d0864801e21eea07593a2a1e6
|
Java
|
codesbyzhangpeng/javaio-api-demo
|
/java-fileio-api/src/java/fileioapi/path/Pathdemo.java
|
UTF-8
| 918 | 2.984375 | 3 |
[] |
no_license
|
package java.fileioapi.path;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Pathdemo {
public static void main(String[] args) throws IOException{
File file = new File("javanew.txt");
file.createNewFile();
System.out.println(file.exists());
File file2 = new File("java.txt");
Path path1 = Paths.get("java.txt").toAbsolutePath();
Path path2 = Paths.get("javanew.txt");
Path path3 = Paths.get("C:\\Users\\czp\\eclipse-workspace\\oca1\\test.txt");
System.out.println(path3.relativize(path1));
System.out.println(path1);
System.out.println(path1.relativize(path3));
System.out.println(file.getAbsolutePath());
System.out.println(file2.getAbsolutePath());
System.out.println(file2.exists());
File file01 = new File("..\\oca1\\test.txt");
System.out.println(file01.exists());
}
}
| true |
51ec1edc28541a018cfa8ecf11a5d5f174cf8e5b
|
Java
|
Juan-Pablo-EAN/Escuela-de-perros
|
/src/paquete/Perro.java
|
UTF-8
| 1,605 | 2.6875 | 3 |
[] |
no_license
|
package paquete;
public class Perro {
private int codigo;
private String nombreP;
private String raza;
private String localidad;
private int cedula;
private String nombreD;
public Perro() {
}
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public String getNombreP() {
return nombreP;
}
public void setNombreP(String nombreP) {
this.nombreP = nombreP;
}
public String getRaza() {
return raza;
}
public void setRaza(String raza) {
this.raza = raza;
}
public String getLocalidad() {
return localidad;
}
public void setLocalidad(String localidad) {
this.localidad = localidad;
}
public int getCedula() {
return cedula;
}
public void setCedula(int cedula) {
this.cedula = cedula;
}
public String getNombreD() {
return nombreD;
}
public void setNombreD(String nombreD) {
this.nombreD = nombreD;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("\nNombre: ");
sb.append(nombreP);
sb.append("\nCodigo: ");
sb.append(codigo);
sb.append("\nRaza: ");
sb.append(raza);
sb.append("\nLocalidad: ");
sb.append(localidad);
sb.append("\nCedula del dueño: ");
sb.append(cedula);
sb.append("\nNombre del dueño: ");
sb.append(nombreD);
return sb.toString();
}
}
| true |
f21886a1d9840b4c327ae93ed97cd90eb2bcb065
|
Java
|
100328119/MVVM_RestAPI
|
/app/src/main/java/com/example/mvvmrestapi/AddEditPostActivity.java
|
UTF-8
| 3,014 | 2.265625 | 2 |
[] |
no_license
|
package com.example.mvvmrestapi;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import static android.content.Intent.EXTRA_TITLE;
public class AddEditPostActivity extends AppCompatActivity {
public static final String EXTRA_USERID = "COM.EXAMPLE.MVVMRESTAPI.EXTRA.USERID";
public static final String EXTRA_BODY = "COM.EXAMPLE.MVVMRESTAPI.EXTRA.BODY";
public static final String EXTRA_TITLE= "COM.EXAMPLE.MVVMRESTAPI.EXTRA.TITLE";
public static final String EXTRA_ID = "COM.EXAMPLE.MVVMRESTAPI.EXTRA.ID";
private EditText editTextTitle, editTextBody, editTextuserId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_edit_post);
editTextTitle = findViewById(R.id.edit_text_title);
editTextBody = findViewById(R.id.edit_text_body);
editTextuserId = findViewById(R.id.edit_text_userId);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close_post);
setTitle("Add Post");
Intent intent = getIntent();
if (intent.hasExtra(EXTRA_ID)) {
setTitle("Edit Notes");
editTextTitle.setText(intent.getStringExtra(EXTRA_TITLE));
editTextBody.setText(intent.getStringExtra(EXTRA_BODY));
int userId = intent.getIntExtra(EXTRA_ID,1);
editTextuserId .setText(String.valueOf(userId));
}else{
setTitle("Add Notes");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.add_edit_post_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.save_post:
savePost();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void savePost(){
String title = editTextTitle.getText().toString();
String body = editTextBody.getText().toString();
int userId = Integer.valueOf(editTextuserId.getText().toString());
if(title.trim().isEmpty() || body.trim().isEmpty()){
Toast.makeText(this, "Add a Title and Description", Toast.LENGTH_SHORT).show();
return;
}
Intent data = new Intent();
data.putExtra(EXTRA_TITLE, title);
data.putExtra(EXTRA_BODY, body);
data.putExtra(EXTRA_USERID, userId);
int id = getIntent().getIntExtra(EXTRA_ID, -1);
if(id != -1){
data.putExtra(EXTRA_ID,id);
}
setResult(RESULT_OK, data);
finish();
}
}
| true |
868adc4cda6b87dc4fd5a7cb322e44b48ddc8b48
|
Java
|
osakanaya/cdi-producermethods
|
/src/main/java/producermethods/CoderConfig.java
|
UTF-8
| 575 | 2.03125 | 2 |
[] |
no_license
|
package producermethods;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Documented
@Retention(RUNTIME)
@Target({TYPE,METHOD,PARAMETER,FIELD})
public @interface CoderConfig {
CoderType type() default CoderType.PRODUCTION;
}
| true |
66b6818da98a216809e88f7c3831b42945380c22
|
Java
|
pavelcode/Android
|
/src/com/cblue/component/broadcast/MyOrderedBroadcastReceiver03.java
|
UTF-8
| 536 | 2.1875 | 2 |
[] |
no_license
|
package com.cblue.component.broadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyOrderedBroadcastReceiver03 extends BroadcastReceiver {
private static final String TAG= MyOrderedBroadcastReceiver03.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i(TAG, "收到广播");
//停止有序广播
abortBroadcast();
}
}
| true |
715f1d23295814bf2d8b94e1e2f36b2b362d63d9
|
Java
|
DevelopersGuild/Planetbase
|
/core/src/io/developersguild/GuiRenderer.java
|
UTF-8
| 2,328 | 2.109375 | 2 |
[
"MIT"
] |
permissive
|
package io.developersguild;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureWrap;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
public class GuiRenderer {
private static SpriteBatch spriteBatch;
private static TextureRegion[] textureRegions;
private static Texture[] textures;
static{
//TODO not embed the file path into here
int i=0;
String[] textureLocs=new String[]{
"/home/planetguy/dev/3dxGame/core/src/gui.png",
"/home/planetguy/dev/3dxGame/core/src/gui_blank.png",
"/home/planetguy/dev/3dxGame/core/src/power.png",
"/home/planetguy/dev/3dxGame/core/src/ind_base.png",
"/home/planetguy/dev/3dxGame/core/src/ind_bomb.png"
};
textureRegions=new TextureRegion[textureLocs.length];
textures=new Texture[textureLocs.length];
for(String path:textureLocs) {
Texture aimingTex=new Texture(path);
textures[i]=aimingTex;
aimingTex.setWrap(TextureWrap.ClampToEdge, TextureWrap.ClampToEdge);
textureRegions[i++]=new TextureRegion(aimingTex);
}
spriteBatch=new SpriteBatch();
spriteBatch.enableBlending();
}
public static void renderGui(Camera cam, EntityStatic entity, Environment environment, float deltaTime){
spriteBatch.begin();
if(entity!=null) {
spriteBatch.draw(
textureRegions[2].getTexture(),
0,
0,
0,
0,
textureRegions[2].getRegionWidth(),
textureRegions[2].getRegionHeight() * entity.timeHeld, /* Scale output height */
1,
1,
0,
textureRegions[2].getRegionX(),
textureRegions[2].getRegionY(), /* Move input data position */
textureRegions[2].getRegionWidth(),
textureRegions[2].getRegionHeight(), /* Scale input height */
false,
false);
spriteBatch.draw(textureRegions[0], 0, 0);
entity.handleGuiInteraction(deltaTime, cam);
} else {
spriteBatch.draw(textureRegions[1], 0, 0);
}
spriteBatch.draw(textureRegions[3+StrategyGame.selectedProjectile.ordinal()], 0, 0);
spriteBatch.end();
}
}
| true |
f6c9260d1cded4934693f67e97fc1794c8cd001e
|
Java
|
quyphan241/Module-2
|
/Tong quan Spring MVC/UngDungChuyenDoiTienTe/src/controllers/ConvertController.java
|
UTF-8
| 619 | 2.203125 | 2 |
[] |
no_license
|
package controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class ConvertController {
@PostMapping("/convert")
public String convert(@RequestParam String usd, String rate, Model model){
int vnd = Integer.parseInt(usd)*Integer.parseInt(rate);
model.addAttribute("vnd",vnd);
model.addAttribute("usd",usd);
return "convert";
}
}
| true |
ddeb4a2e13792a953208e61269edfa2b0b96eaa2
|
Java
|
guytp/msc
|
/Experiment/app/src/main/java/org/guytp/mscexperiment/Phase1CompleteActivity.java
|
UTF-8
| 673 | 1.976563 | 2 |
[
"BSD-2-Clause"
] |
permissive
|
package org.guytp.mscexperiment;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class Phase1CompleteActivity extends KioskActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phase1_complete);
ExperimentData.getInstance(this).addTimeMarker("Phase1Complete", "Show");
}
public void onContinuePress(View v) {
ExperimentData.getInstance(this).addTimeMarker("Phase1Complete", "Finish");
startActivity(new Intent(Phase1CompleteActivity.this, Phase2IntroductionActivity.class));
}
}
| true |
a91587f9a6b90b0fb4adddc2959deb6d547c9529
|
Java
|
HarperJo12/AdcLikmi
|
/app/src/main/java/com/android/adclikmi/reportFrg.java
|
UTF-8
| 12,641 | 1.710938 | 2 |
[] |
no_license
|
package com.android.adclikmi;
import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.net.ParseException;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.DownloadListener;
import com.androidnetworking.interfaces.DownloadProgressListener;
import com.androidnetworking.interfaces.JSONObjectRequestListener;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import pub.devrel.easypermissions.EasyPermissions;
/**
* A simple {@link Fragment} subclass.
* Marcel 2019 *
*/
public class reportFrg extends Fragment implements EasyPermissions.PermissionCallbacks {
public String title="Report";
private static final int REQUEST_FILE_CODE = 200;
private TextView fileName;
private Spinner jenis, bln, thn;
private Button submit;
private ImageView imgView;
private File filedst = null;
private String dstPath, lmp;
public reportFrg() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.report, parent, false);
AndroidNetworking.initialize(view.getContext());
fileName=(TextView) view.findViewById(R.id.frm_nameFile);
imgView = (ImageView) view.findViewById(R.id.frm_imgView);
jenis = (Spinner) view.findViewById(R.id.frm_jenis_spinner);
bln = (Spinner) view.findViewById(R.id.frm_bln_spinner);
thn = (Spinner) view.findViewById(R.id.frm_thn_spinner);
submit = (Button) view.findViewById((R.id.frm_submit));
((MainActivity) getActivity()).setTitle(title);//untuk menset title pada toolbar
((MainActivity) getActivity()).setSearchState(0);//mengubah state search pada toolbar
((MainActivity) getActivity()).invalidateOptionsMenu();//memanggil method oncreatemenuoption pada mainactivity
fileName.setVisibility(View.GONE);
imgView.setVisibility(View.GONE);
List<String> list1 = new ArrayList<String>();//menambahkan data untuk spinner
list1.add("Izin");
list1.add("Ujian");
list1.add("Perpindahan");
list1.add("Sidang");
List<String> list2 = new ArrayList<String>();
list2.add("Januari");
list2.add("Februari");
list2.add("Maret");
list2.add("April");
list2.add("Mei");
list2.add("Juni");
list2.add("Juli");
list2.add("Agustus");
list2.add("September");
list2.add("Oktober");
list2.add("November");
list2.add("Desember");
List<String> list3 = new ArrayList<String>();
list3.add("2019");
list3.add("2020");
addData(view, list1, jenis);
addData(view, list2, bln);
addData(view, list3, thn);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (EasyPermissions.hasPermissions(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
if (EasyPermissions.hasPermissions(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
((MainActivity) getActivity()).showDProgressDialog();
requestReport();
} else {
EasyPermissions.requestPermissions(getActivity(), getString(R.string.write_file), REQUEST_FILE_CODE, Manifest.permission.READ_EXTERNAL_STORAGE);
}
} else {
EasyPermissions.requestPermissions(getActivity(), getString(R.string.read_file), REQUEST_FILE_CODE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
}
});
imgView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openFile();
}
});
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
AndroidNetworking.cancelAll();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, getActivity());
}
@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
}
@Override
public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
Toast.makeText(getContext(), "Permission has been denied!", Toast.LENGTH_SHORT).show();
}
protected void openFile() {
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT < 24) {
Uri uri = Uri.fromFile(filedst);
Log.d("uri", uri.getPath());
intent.setDataAndType(uri, getMimeType(dstPath));
} else {
Log.d("file open path", filedst.getPath());
Uri uri = FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider", filedst);
intent.setDataAndType(FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider", filedst), getMimeType(dstPath));
Log.d("uri", uri.getPath());
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
startActivity(intent);
}
public String getMimeType(String filePath) {
String mime = null;
String ext = filePath.substring(filePath.lastIndexOf(".") + 1).toLowerCase();
mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
return mime;
}
public void loadImage() {
String mime = null;
filedst = new File(dstPath, lmp.trim());
dstPath += lmp.trim();
Log.d("filepath", dstPath);
mime = getMimeType(dstPath);
Log.d("mime", mime);
if (mime != null && mime.contains("image")) {
BitmapFactory.Options options = new BitmapFactory.Options();
// down sizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 1;
final Bitmap bitmap = BitmapFactory.decodeFile(dstPath, options);
imgView.setVisibility(View.VISIBLE);
imgView.setImageBitmap(bitmap);
} else {
imgView.setVisibility(View.VISIBLE);
fileName.setVisibility(View.VISIBLE);
imgView.setImageResource(R.drawable.ic_action_file);
fileName.setText(lmp);
}
openFile();
}
public void addData(View view, List lst, Spinner spn) {
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(view.getContext(), android.R.layout.simple_spinner_item, lst);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn.setAdapter(dataAdapter);
}
public void requestReport(){
try {
int slc=jenis.getSelectedItemPosition()+1;
JSONObject objk = new JSONObject();
objk.put("jenis", slc);
objk.put("bulan", bln.getSelectedItemPosition()+1);
objk.put("tahun", thn.getSelectedItem().toString());
AndroidNetworking.post(((MainActivity) getActivity()).getBaseUrl() + "report")
.addJSONObjectBody(objk) // posting json
.addHeaders("Authorization", "Bearer " + ((MainActivity) getActivity()).getUs().getToken().trim())
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
((MainActivity) getActivity()).dismissDProgressDialog();
try {
if (!response.getBoolean("error")) {
Toast.makeText(getContext(), "Laporan dibuat!", Toast.LENGTH_SHORT).show();
lmp = response.getString("name");
((MainActivity) getActivity()).showPercentProgressBar();
downloadData();
} else
Toast.makeText(getContext(), response.getString("pesan"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onError(ANError error) {
((MainActivity) getActivity()).dismissDProgressDialog();
}
});
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
public void downloadData() {
String INTERNAL_STORAGE = System.getenv("EXTERNAL_STORAGE");
dstPath = INTERNAL_STORAGE + "/likmimedia/download/report/";
Log.d("INTERNAL STORAGE", INTERNAL_STORAGE);
filedst = new File(dstPath);
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (filedst.exists()) {
File[] dirFiles = filedst.listFiles();
if (dirFiles.length != 0) {
for (int i = 0; i < dirFiles.length; i++) {
dirFiles[i].delete();
}
}
}
// if no directory exists, create new directory
if (!filedst.exists()) {
filedst.mkdir();
}
AndroidNetworking.download(((MainActivity) getActivity()).getBaseUrl() + "reportDown/{file}", dstPath, lmp)
.addHeaders("Authorization", "Bearer " + ((MainActivity) getActivity()).getUs().getToken().trim())
.addPathParameter("file", lmp)
.setTag("downloadTest")
.setPriority(Priority.MEDIUM)
.build()
.setDownloadProgressListener(new DownloadProgressListener() {
@Override
public void onProgress(long bytesDownloaded, long totalBytes) {
if (bytesDownloaded >= 0) {
((MainActivity) getActivity()).setPercentProgressBar(bytesDownloaded, totalBytes);
}
}
})
.startDownload(new DownloadListener() {
@Override
public void onDownloadComplete() {
Log.d("download", "Selesai download!");
((MainActivity) getActivity()).dismissPercentProgressBar();
Toast.makeText(getContext(), "Laporan berhasil disimpan pada "+dstPath+lmp, Toast.LENGTH_LONG).show();
loadImage();
}
@Override
public void onError(ANError error) {
((MainActivity) getActivity()).dismissPercentProgressBar();
Toast.makeText(getContext(), "Laporan gagal di download!", Toast.LENGTH_SHORT).show();
filedst = null;
// handle error
}
});
}
}
| true |
a1b41768d9ba3705c7d1b0a585302f4518692b0d
|
Java
|
shubhamchandak/Titanic-
|
/app/src/main/java/com/example/android/titanic/PopularFragment.java
|
UTF-8
| 2,769 | 2.4375 | 2 |
[] |
no_license
|
package com.example.android.titanic;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class PopularFragment extends Fragment {
public PopularFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_popular, container, false);
ListView listView = view.findViewById(R.id.popular_fragment_list_view);
ArrayList<Movie> popularMovies = QueryUtils.extractMoviesPopular();
final RecommendedMovieAdapter popularMoviesAdapter = new RecommendedMovieAdapter(getActivity(), popularMovies);
listView.setAdapter(popularMoviesAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Movie clickedMovie = popularMoviesAdapter.getItem(i);
Intent intent = new Intent(getActivity(), MovieDetailsActivity.class);
intent.putExtra("title", clickedMovie.getTitle());
String genresString = RecommendedMovieAdapter.convertGenreCodesToStrings(clickedMovie.getGenres());
intent.putExtra("genres", genresString);
intent.putExtra("poster_path", clickedMovie.getPosterPath());
intent.putExtra("backdrop_path", clickedMovie.getBackdropPath());
intent.putExtra("tmdb_rating", clickedMovie.getTmdbRating());
intent.putExtra("popularity", clickedMovie.getPopularity());
intent.putExtra("tagline", clickedMovie.getTagline());
intent.putExtra("overview", clickedMovie.getOverview());
intent.putExtra("release_date", clickedMovie.getReleaseDate());
intent.putExtra("runtime", clickedMovie.getRuntime());
intent.putExtra("budget", clickedMovie.getBudget());
intent.putExtra("homepage_url", clickedMovie.getHomePageUrl());
intent.putExtra("imdb_id", clickedMovie.getImdbId());
intent.putExtra("tmdb_id", clickedMovie.getTmdbId());
intent.putExtra("adult", clickedMovie.isAdult());
intent.putExtra("revenue", clickedMovie.getRevenue());
startActivity(intent);
}
});
return view;
}
}
| true |
7539d4680528be5937ff04745e3504b14357d28c
|
Java
|
ViGarCag/PAW_pr7
|
/src/java/sol/ser/BuscarArticulos.java
|
UTF-8
| 5,036 | 2.3125 | 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 sol.ser;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import paw.bd.CriteriosArticulo;
import paw.bd.GestorBD;
import paw.bd.Paginador;
import paw.model.ExcepcionDeAplicacion;
public class BuscarArticulos extends HttpServlet {
private static int tamanioPagina = 15;
private static GestorBD gd= new GestorBD();
@Override
public void init() throws ServletException {
super.init();
try {
tamanioPagina = Integer.parseInt(this.getInitParameter("tamanioPagina"));
} catch (Exception ex) {
Logger.getLogger(BuscarArticulos.class.getName()).log(Level.WARNING, null, ex);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String tipo = request.getParameter("tipo");
String fabricante = request.getParameter("fabricante");
String precio = request.getParameter("precio");
//TRABAJO BUSQUEDA POR NOMBRE Y CÓDIGO
String nombre = request.getParameter("nombre");
String codigo = request.getParameter("codigo");
try {
int pagina = 0;
if (tipo != null && tipo.trim().length() > 0
|| fabricante != null && fabricante.trim().length() > 0
|| precio != null && precio.trim().length() > 0
|| nombre != null && nombre.trim().length() > 0
|| codigo != null && codigo.trim().length() > 0) {
CriteriosArticulo criterios = new CriteriosArticulo();
criterios.setTipo(tipo);
criterios.setFabricante(fabricante);
criterios.setPrecio(precio);
criterios.setNombre(nombre);
criterios.setCodigo(codigo);
Paginador paginador = this.gd.getPaginadorArticulos(criterios, tamanioPagina);
if (request.getParameter("p") != null && request.getParameter("p").trim().length() != 0) {
try {
pagina = Integer.parseInt(request.getParameter("p"));
} catch (NumberFormatException e) {
e.printStackTrace();
}
if (paginador.getNumPaginas() > 0) {
if (pagina > paginador.getNumPaginas()) {
pagina = paginador.getNumPaginas();
}else{
if (pagina < 1) {
pagina = 1;
}
}
}
} else {
pagina = 1;
}
//TRABAJO
if (gd.getArticulos(criterios, pagina, tamanioPagina).size() == 1) {
RequestDispatcher rd = request.getRequestDispatcher(("FichaArticulo?cart=" + gd.getArticulos(criterios, pagina, tamanioPagina).get(0).getCodigo()));
rd.forward(request, response);
}
//FIN PARTE TRABAJO
request.setAttribute("tipo", tipo);
request.setAttribute("tiposArticulos", gd.getTiposArticulos());
request.setAttribute("fabricante", fabricante);
request.setAttribute("fabricantes", gd.getFabricantes());
request.setAttribute("precio", precio);
request.setAttribute("criterios", criterios);
request.setAttribute("pgdr", paginador);
request.setAttribute("p", pagina);
request.setAttribute("articulos", gd.getArticulos(criterios, pagina, tamanioPagina));
RequestDispatcher r = request.getRequestDispatcher("/catalogo.jsp");
r.forward(request, response);
} else {
request.setAttribute("tiposArticulos", gd.getTiposArticulos());
request.setAttribute("fabricantes", gd.getFabricantes());
RequestDispatcher r = request.getRequestDispatcher("catalogo.jsp");
r.forward(request, response);
}
} catch (ExcepcionDeAplicacion ex) {
Logger.getLogger(BuscarArticulos.class.getName()).log(Level.SEVERE, null, ex);
request.setAttribute("enlaceSalir", "index.html");
throw new ServletException(ex);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
| true |
e8b2086acdadb620a8294256d8aeb06a6a213958
|
Java
|
falalabella-team-browse/hackathon
|
/RnRDataLayer/src/main/java/com/hachathon/reviewNratings/beans/SentimentAnalysisResponse.java
|
UTF-8
| 449 | 1.554688 | 2 |
[
"MIT"
] |
permissive
|
package com.hachathon.reviewNratings.beans;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class SentimentAnalysisResponse {
private String sentimentScore;
private String sentimentFactor;
private String hasAbusiveContent;
private String review_score;
private Words words;
}
| true |
13931d9f028ed6e4197434be8fd571ce33e0598f
|
Java
|
daxiedexu/business
|
/person/src/main/java/com/zhang/person/Person_Register.java
|
UTF-8
| 2,147 | 1.953125 | 2 |
[] |
no_license
|
package com.zhang.person;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.zhang.common.utils.Config;
import com.zhang.common.utils.back.SharedManger;
import com.zhang.mvp_core.view.BaseActivity;
/**
* @ClassName Person_Register
* @Description TODO
* @Author 张溢通
* @Date 2021/9/19 10:05
* @Version 1.0
* Created by Android Studio.
* User: 伊莎贝拉
*/
@Route(path=Person_Config.REGISTER)
public class Person_Register extends BaseActivity {
private EditText registerUserName;
private EditText registerUserPwd;
private Button registerBtn;
@Override
protected void initData() {
registerUserName.addTextChangedListener(new TextChanged());
registerUserPwd.addTextChangedListener(new TextChanged());
registerBtn.setOnClickListener(new View.OnClickListener( ) {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
protected void initView() {
registerUserName = (EditText) findViewById(R.id.register_user_name);
registerUserPwd = (EditText) findViewById(R.id.register_user_pwd);
registerBtn = (Button) findViewById(R.id.register_btn);
}
@Override
protected int bindLayout() {
return R.layout.register;
}
/**
* 判断按钮是否可以点击
*/
public class TextChanged implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(registerUserName.getText().toString().isEmpty()||registerUserPwd.getText().toString().isEmpty()){
registerBtn.setEnabled(false);
}else {
registerBtn.setEnabled(true);
}
}
@Override
public void afterTextChanged(Editable s) {
}
}
}
| true |
ebf34ba8c4df764802ef250cdd457814c7cff5b0
|
Java
|
raymondlam12/transport
|
/transportable-udfs-test/transportable-udfs-test-presto/src/main/java/com/linkedin/transport/test/presto/PrestoTester.java
|
UTF-8
| 2,525 | 1.609375 | 2 |
[
"BSD-2-Clause",
"Apache-2.0"
] |
permissive
|
/**
* Copyright 2018 LinkedIn Corporation. All rights reserved.
* Licensed under the BSD-2 Clause license.
* See LICENSE in the project root for license information.
*/
package com.linkedin.transport.test.presto;
import io.prestosql.metadata.BoundVariables;
import io.prestosql.operator.scalar.AbstractTestFunctions;
import io.prestosql.spi.type.Type;
import com.google.common.collect.ImmutableMap;
import com.linkedin.transport.api.StdFactory;
import com.linkedin.transport.api.udf.StdUDF;
import com.linkedin.transport.api.udf.TopLevelStdUDF;
import com.linkedin.transport.presto.PrestoFactory;
import com.linkedin.transport.test.spi.SqlFunctionCallGenerator;
import com.linkedin.transport.test.spi.SqlStdTester;
import com.linkedin.transport.test.spi.ToPlatformTestOutputConverter;
import java.util.List;
import java.util.Map;
public class PrestoTester extends AbstractTestFunctions implements SqlStdTester {
private StdFactory _stdFactory;
private SqlFunctionCallGenerator _sqlFunctionCallGenerator;
private ToPlatformTestOutputConverter _toPlatformTestOutputConverter;
public PrestoTester() {
_stdFactory = null;
_sqlFunctionCallGenerator = new PrestoSqlFunctionCallGenerator();
_toPlatformTestOutputConverter = new ToPrestoTestOutputConverter();
}
@Override
public void setup(
Map<Class<? extends TopLevelStdUDF>, List<Class<? extends StdUDF>>> topLevelStdUDFClassesAndImplementations) {
// Refresh Presto state during every setup call
initTestFunctions();
for (List<Class<? extends StdUDF>> stdUDFImplementations : topLevelStdUDFClassesAndImplementations.values()) {
for (Class<? extends StdUDF> stdUDF : stdUDFImplementations) {
registerScalarFunction(new PrestoTestStdUDFWrapper(stdUDF));
}
}
}
@Override
public StdFactory getStdFactory() {
if (_stdFactory == null) {
_stdFactory = new PrestoFactory(new BoundVariables(ImmutableMap.of(), ImmutableMap.of()),
this.functionAssertions.getMetadata());
}
return _stdFactory;
}
@Override
public SqlFunctionCallGenerator getSqlFunctionCallGenerator() {
return _sqlFunctionCallGenerator;
}
@Override
public ToPlatformTestOutputConverter getToPlatformTestOutputConverter() {
return _toPlatformTestOutputConverter;
}
@Override
public void assertFunctionCall(String functionCallString, Object expectedOutputData, Object expectedOutputType) {
assertFunction(functionCallString, (Type) expectedOutputType, expectedOutputData);
}
}
| true |
4d598cad28337aa44eca3e6d9999cd85a1db9934
|
Java
|
Azure/azure-sdk-for-java
|
/sdk/mediaservices/azure-resourcemanager-mediaservices/src/test/java/com/azure/resourcemanager/mediaservices/generated/StreamingEndpointsListMockTests.java
|
UTF-8
| 4,867 | 1.65625 | 2 |
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"CC0-1.0",
"BSD-3-Clause",
"UPL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.mediaservices.generated;
import com.azure.core.credential.AccessToken;
import com.azure.core.http.HttpClient;
import com.azure.core.http.HttpHeaders;
import com.azure.core.http.HttpRequest;
import com.azure.core.http.HttpResponse;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.management.AzureEnvironment;
import com.azure.core.management.profile.AzureProfile;
import com.azure.resourcemanager.mediaservices.MediaServicesManager;
import com.azure.resourcemanager.mediaservices.models.StreamingEndpoint;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.OffsetDateTime;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public final class StreamingEndpointsListMockTests {
@Test
public void testList() throws Exception {
HttpClient httpClient = Mockito.mock(HttpClient.class);
HttpResponse httpResponse = Mockito.mock(HttpResponse.class);
ArgumentCaptor<HttpRequest> httpRequest = ArgumentCaptor.forClass(HttpRequest.class);
String responseStr =
"{\"value\":[{\"properties\":{\"description\":\"lwywae\",\"scaleUnits\":665085676,\"availabilitySetName\":\"gfbukklelss\",\"accessControl\":{},\"maxCacheAge\":2996960351334140021,\"customHostNames\":[\"jks\",\"lsmdesqplpvmjc\",\"oewbid\",\"vteo\"],\"hostName\":\"vgp\",\"cdnEnabled\":false,\"cdnProvider\":\"ugfsxzecpaxwk\",\"cdnProfile\":\"ykhv\",\"provisioningState\":\"xepmrut\",\"resourceState\":\"Scaling\",\"crossSiteAccessPolicies\":{\"clientAccessPolicy\":\"obns\",\"crossDomainPolicy\":\"jdjltymkmvgui\"},\"freeTrialEndTime\":\"2021-11-13T17:45:06Z\",\"created\":\"2021-04-21T11:58:54Z\",\"lastModified\":\"2021-05-15T17:05:47Z\"},\"sku\":{\"name\":\"kixkykxdssjpemm\",\"capacity\":1510283924},\"location\":\"xhikkflrmymyin\",\"tags\":{\"s\":\"hr\",\"iiiovgqcgxuugq\":\"sl\"},\"id\":\"ctotiowlx\",\"name\":\"e\",\"type\":\"dptjgwdtgukranb\"}]}";
Mockito.when(httpResponse.getStatusCode()).thenReturn(200);
Mockito.when(httpResponse.getHeaders()).thenReturn(new HttpHeaders());
Mockito
.when(httpResponse.getBody())
.thenReturn(Flux.just(ByteBuffer.wrap(responseStr.getBytes(StandardCharsets.UTF_8))));
Mockito
.when(httpResponse.getBodyAsByteArray())
.thenReturn(Mono.just(responseStr.getBytes(StandardCharsets.UTF_8)));
Mockito
.when(httpClient.send(httpRequest.capture(), Mockito.any()))
.thenReturn(
Mono
.defer(
() -> {
Mockito.when(httpResponse.getRequest()).thenReturn(httpRequest.getValue());
return Mono.just(httpResponse);
}));
MediaServicesManager manager =
MediaServicesManager
.configure()
.withHttpClient(httpClient)
.authenticate(
tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)),
new AzureProfile("", "", AzureEnvironment.AZURE));
PagedIterable<StreamingEndpoint> response =
manager.streamingEndpoints().list("roznnhdrlktgj", "sggux", com.azure.core.util.Context.NONE);
Assertions.assertEquals("xhikkflrmymyin", response.iterator().next().location());
Assertions.assertEquals("hr", response.iterator().next().tags().get("s"));
Assertions.assertEquals(1510283924, response.iterator().next().sku().capacity());
Assertions.assertEquals("lwywae", response.iterator().next().description());
Assertions.assertEquals(665085676, response.iterator().next().scaleUnits());
Assertions.assertEquals("gfbukklelss", response.iterator().next().availabilitySetName());
Assertions.assertEquals(2996960351334140021L, response.iterator().next().maxCacheAge());
Assertions.assertEquals("jks", response.iterator().next().customHostNames().get(0));
Assertions.assertEquals(false, response.iterator().next().cdnEnabled());
Assertions.assertEquals("ugfsxzecpaxwk", response.iterator().next().cdnProvider());
Assertions.assertEquals("ykhv", response.iterator().next().cdnProfile());
Assertions.assertEquals("obns", response.iterator().next().crossSiteAccessPolicies().clientAccessPolicy());
Assertions
.assertEquals("jdjltymkmvgui", response.iterator().next().crossSiteAccessPolicies().crossDomainPolicy());
}
}
| true |
a3480436766a44d647fd042ae48d6ab9240aeb3b
|
Java
|
Lingzhi-Ouyang/Almost-Strong-Consistency-Cassandra
|
/experiment/CASSANDRA/cassandra/src/java/org/apache/cassandra/io/util/LimitingRebufferer.java
|
UTF-8
| 2,486 | 2.59375 | 3 |
[
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] |
permissive
|
package org.apache.cassandra.io.util;
import java.nio.ByteBuffer;
import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.RateLimiter;
/**
* Rebufferer wrapper that applies rate limiting.
*
* Instantiated once per RandomAccessReader, thread-unsafe.
* The instances reuse themselves as the BufferHolder to avoid having to return a new object for each rebuffer call.
*/
public class LimitingRebufferer implements Rebufferer, Rebufferer.BufferHolder
{
final private Rebufferer wrapped;
final private RateLimiter limiter;
final private int limitQuant;
private BufferHolder bufferHolder;
private ByteBuffer buffer;
private long offset;
public LimitingRebufferer(Rebufferer wrapped, RateLimiter limiter, int limitQuant)
{
this.wrapped = wrapped;
this.limiter = limiter;
this.limitQuant = limitQuant;
}
@Override
public BufferHolder rebuffer(long position)
{
bufferHolder = wrapped.rebuffer(position);
buffer = bufferHolder.buffer();
offset = bufferHolder.offset();
int posInBuffer = Ints.checkedCast(position - offset);
int remaining = buffer.limit() - posInBuffer;
if (remaining == 0)
return this;
if (remaining > limitQuant)
{
buffer.limit(posInBuffer + limitQuant); // certainly below current limit
remaining = limitQuant;
}
limiter.acquire(remaining);
return this;
}
@Override
public ChannelProxy channel()
{
return wrapped.channel();
}
@Override
public long fileLength()
{
return wrapped.fileLength();
}
@Override
public double getCrcCheckChance()
{
return wrapped.getCrcCheckChance();
}
@Override
public void close()
{
wrapped.close();
}
@Override
public void closeReader()
{
wrapped.closeReader();
}
@Override
public String toString()
{
return "LimitingRebufferer[" + limiter.toString() + "]:" + wrapped.toString();
}
// BufferHolder methods
@Override
public ByteBuffer buffer()
{
return buffer;
}
@Override
public long offset()
{
return offset;
}
@Override
public void release()
{
bufferHolder.release();
}
}
| true |
1d08b69112828adcfb4b60f2d857d6949a84f3b1
|
Java
|
ThreadNew/book_Liberary
|
/book_Library/src/com/chen/server/IUserServer.java
|
GB18030
| 417 | 2 | 2 |
[] |
no_license
|
package com.chen.server;
import java.util.List;
import com.chen.entity.User;
public interface IUserServer {
public int inserInfo(User user);
public int delete_Info(String username);
public boolean checkInfo(String username,String password);
@SuppressWarnings("rawtypes")
public List getAllInfo();
/*
* õԼϢ
*/
@SuppressWarnings("rawtypes")
public List getInfobyID(String username);
}
| true |
53821a0dccdc3025a6d1f15ba52bc2201cd54de8
|
Java
|
bulentgeckin/HappyCooding
|
/src/main/java/j002_Java_Data_Types/_00_JavaDataTypes.java
|
UTF-8
| 1,566 | 3.90625 | 4 |
[
"Unlicense"
] |
permissive
|
package j002_Java_Data_Types;
public class _00_JavaDataTypes {
/**
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variablesummary.html
https://en.wikibooks.org/wiki/Java_Programming/Primitive_Types
https://www.javatpoint.com/java-data-types
Java has two main data types
1 - primitive
2- non-primitive (reference types/complex/object etc.)
primitive data types
Numbers :
1. byte -127 | +127
2. short -32,768 | +32,768
3. int -2,147,483,648 | +2,147,483,647
4. long -9,223,372,036,854,775,808 | +9,223,372,036,854,775,807
5. float 1.4 E-45 | +1.4 E-45
6. double 4.9 E-324 | 1.797,693,134,862,315,7 E+308
7. char 'a','b','c' ....
8. boolean True | False
*/
public static void main(String[] args) {
byte my_byte =10;
short my_short=1_000;
int my_int = 50_000;
long my_long = 90_000_000_000l; // L
float my_float = 3.141592684f; // or F
double my_double=465465478798718798789798798798798798d; // or d
char my_char='A';
boolean my_boolean=true; // or false // True is not correct
System.out.println(my_byte);
System.out.println(my_short);
System.out.println(my_int);
System.out.println(my_long);
System.out.println(my_float);
System.out.println(my_double);
System.out.println(my_char);
System.out.println(my_boolean);
}
}
| true |
eee34fbb467ed7ef72e5240827ede9b35b28618c
|
Java
|
myotheone/University-of-Utah-Coursework
|
/CS 2420 - Algorithms and Data Structures/src/assignment2/LibraryTest.java
|
UTF-8
| 5,322 | 3.3125 | 3 |
[] |
no_license
|
package assignment2;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Random;
/**
* Testing class for Library. This uses the standard Library and LibraryBook classes for these sets of tests. Some of
* these tests were done by Dr. Meyer and some were written by us.
* @author Robert Weischedel && Makenzie Elliott
*/
public class LibraryTest {
public static void main(String[] args) {
// test an empty library
Library lib = new Library();
if (lib.lookup(978037429279L) != null)
System.err.println("TEST FAILED -- empty library: lookup(isbn)");
ArrayList<LibraryBook> booksCheckedOut = lib.lookup("Jane Doe");
if (booksCheckedOut == null || booksCheckedOut.size() != 0)
System.err.println("TEST FAILED -- empty library: lookup(holder)");
if (lib.checkout(978037429279L, "Jane Doe", 1, 1, 2008))
System.err.println("TEST FAILED -- empty library: checkout");
if (lib.checkin(978037429279L))
System.err.println("TEST FAILED -- empty library: checkin(isbn)");
if (lib.checkin("Jane Doe"))
System.err.println("TEST FAILED -- empty library: checkin(holder)");
System.out.println("Book Lookup Test :" + lib.lookup(978037429279L));
// test a small library
lib.add(9780374292799L, "Thomas L. Friedman", "The World is Flat");
lib.add(9780330351690L, "Jon Krakauer", "Into the Wild");
lib.add(9780446580342L, "David Baldacci", "Simple Genius");
if (lib.lookup(9780330351690L) != null)
System.err.println("TEST FAILED -- small library: lookup(isbn)");
if (!lib.checkout(9780330351690L, "Jane Doe", 1, 1, 2008))
System.err.println("TEST FAILED -- small library: checkout");
booksCheckedOut = lib.lookup("Jane Doe");
System.out.println("The Tests Begin Now!");
System.out.println(booksCheckedOut);
System.out.println(booksCheckedOut.size());
System.out.println(booksCheckedOut.get(0));
System.out.println(booksCheckedOut.get(0).getHolder());
System.out.println(booksCheckedOut.get(0).getDueDate());
if (booksCheckedOut == null
|| booksCheckedOut.size() != 1
|| !booksCheckedOut.get(0).equals(new Book(9780330351690L, "Jon Krakauer", "Into the Wild"))
|| !booksCheckedOut.get(0).getHolder().equals("Jane Doe")
|| !booksCheckedOut.get(0).getDueDate().equals(new GregorianCalendar(2008, 1, 1)))
System.err.println("TEST FAILED -- small library: lookup(holder)");
if (!lib.checkin(9780330351690L))
System.err.println("TEST FAILED -- small library: checkin(isbn)");
if (lib.checkin("Jane Doe"))
System.err.println("TEST FAILED -- small library: checkin(holder)");
// test a medium library
lib.addAll("Mushroom_Publishing.txt");
// FILL IN
System.out.println("Dr. Meyer's Testing done." + "\n");
System.out.println("Our Testing Begins" + "\n");
// The following tests are for looking to see if a book had been checked in, then checking it out, then checking
// back in.
Library lib2 = new Library();
// Add books to library
lib2.add(9780374292799L, "Thomas L. Friedman", "The World is Flat");
lib2.add(9780330351690L, "Jon Krakauer", "Into the Wild");
lib2.add(9780446580342L, "David Baldacci", "Simple Genius");
// Testing the lookup method for book not checked out
System.out.println("\n" + "Testing of the lookup by isbn method : ");
if(lib2.lookup(9780374292799L) == null){
System.out.println("The book has not been checked out by a holder.");
}
// Testing the lookup method for not real book
if(lib2.lookup(9780374292791L) == null){
System.out.println("The book does not exist in lib2.");
}
// Checkout a book
lib2.checkout(9780374292799L, "Meckenzi", 6, 6, 2016);
// Testing the lookup method for a checked out book
if(lib2.lookup(9780374292799L) == "Meckenzi"){
System.out.println("The book has been checked out by Meckenzi.");
}
// Check book back in
lib2.checkin(9780374292799L);
// Test lookup method to ensure book is still not checked out.
if(lib2.lookup(9780374292799L) == null){
System.out.println("The book has not been checked out by a holder.");
}
}
/**
* Returns a library of "dummy" books (random ISBN and placeholders for author
* and title).
*
* Useful for collecting running times for operations on libraries of varying
* size.
*
* @param size --
* size of the library to be generated
*/
public static ArrayList<LibraryBook> generateLibrary(int size) {
ArrayList<LibraryBook> result = new ArrayList<LibraryBook>();
for (int i = 0; i < size; i++) {
// generate random ISBN
Random randomNumGen = new Random();
String isbn = "";
for (int j = 0; j < 13; j++)
isbn += randomNumGen.nextInt(10);
result.add(new LibraryBook(Long.parseLong(isbn), "An author", "A title"));
}
return result;
}
/**
* Returns a randomly-generated ISBN (a long with 13 digits).
*
* Useful for collecting running times for operations on libraries of varying
* size.
*/
public static long generateIsbn() {
Random randomNumGen = new Random();
String isbn = "";
for (int j = 0; j < 13; j++)
isbn += randomNumGen.nextInt(10);
return Long.parseLong(isbn);
}
}
| true |
83601288e560bab20dd55915084eb981fc8e7ec8
|
Java
|
alexyalo/hospital-simulator
|
/src/test/java/core/GetHospitalReportTest.java
|
UTF-8
| 4,548 | 2.40625 | 2 |
[] |
no_license
|
package core;
import core.domain.drug.IDrugStock;
import core.domain.patient.*;
import core.domain.drug.DrugStock;
import core.domain.drug.Antibiotic;
import core.domain.drug.Aspirin;
import core.domain.drug.Insulin;
import core.domain.drug.Paracetamol;
import core.usecase.GetHospitalReport;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
@RunWith(MockitoJUnitRunner.class)
public class GetHospitalReportTest {
private IDrugStock drugStock;
private IPatientsList patients;
private GetHospitalReport getHospitalReport;
@Mock
IDivinityService divinityService;
@Before
public void
setup() {
drugStock = new DrugStock();
patients = new PatientList();
getHospitalReport = new GetHospitalReport();
// No miracle by default
given(divinityService.isResurrectionAllowed()).willReturn(false);
}
@Test
public void
given_two_diabetic_patients_and_no_drugs_then_getReport_should_be_two_dead_and_zero_diabetes(){
patients.add(getDiabetesPatient());
patients.add(getDiabetesPatient());
PatientsReport result = getHospitalReport.execute(patients, drugStock);
assertThat(result.getDeadCount(), is(2));
assertThat(result.getDiabetesCount(), is(0));
}
@Test
public void
given_one_fever_patient_and_paracetamol_then_getReport_should_show_only_one_healthy(){
drugStock.add(new Paracetamol());
patients.add(getFeverPatient());
PatientsReport result = getHospitalReport.execute(patients, drugStock);
assertThat(result.getHealthyCount(), is(1));
assertThat(result.getFeverCount(), is(0));
}
@Test
public void
given_one_fever_and_tuberculosis_patient_and_aspirin_and_antibiotic_then_getReport_should_show_two_healthy(){
drugStock.add(new Paracetamol());
drugStock.add(new Antibiotic());
patients.add(getFeverPatient());
patients.add(getTuberculosisPatient());
PatientsReport result = getHospitalReport.execute(patients, drugStock);
assertThat(result.getHealthyCount(), is(2));
assertThat(result.getFeverCount(), is(0));
assertThat(result.getTuberculosisCount(), is(0));
}
@Test
public void
given_one_diabetic_patient_and_insulin_and_antibiotic_then_getReport_should_show_one_diabetic(){
drugStock.add(new Insulin());
drugStock.add(new Antibiotic());
patients.add(getDiabetesPatient());
PatientsReport result = getHospitalReport.execute(patients, drugStock);
assertThat(result.getHealthyCount(), is(0));
assertThat(result.getFeverCount(), is(0));
assertThat(result.getDiabetesCount(), is(1));
}
@Test
public void
given_one_diabetic_patient_and_one_fever_and_insulin_and_aspirin_then_getReport_should_show_one_diabetic_and_one_healthy(){
drugStock.add(new Insulin());
drugStock.add(new Aspirin());
patients.add(getDiabetesPatient());
patients.add(getFeverPatient());
PatientsReport result = getHospitalReport.execute(patients, drugStock);
assertThat(result.getHealthyCount(), is(1));
assertThat(result.getFeverCount(), is(0));
assertThat(result.getDiabetesCount(), is(1));
}
@Test
public void
given_one_healthy_and_fever_patient_and_paracetamol_and_aspirin_then_getReport_should_show_two_dead(){
drugStock.add(new Aspirin());
drugStock.add(new Paracetamol());
patients.add(getHealthyPatient());
patients.add(getFeverPatient());
PatientsReport result = getHospitalReport.execute(patients, drugStock);
assertThat(result.getHealthyCount(), is(0));
assertThat(result.getFeverCount(), is(0));
assertThat(result.getDeadCount(), is(2));
}
private Patient getDiabetesPatient() {
return new Patient(PatientStatus.Diabetes, divinityService);
}
private Patient getTuberculosisPatient() {
return new Patient(PatientStatus.Tuberculosis, divinityService);
}
private Patient getFeverPatient() {
return new Patient(PatientStatus.Fever, divinityService);
}
private Patient getHealthyPatient() {
return new Patient(PatientStatus.Healthy, divinityService);
}
}
| true |
7d2cb5332c4c0782e6f99a226dc5bb766b3d6b41
|
Java
|
BytecodeEli/API
|
/powercraft/api/gres/PC_GresBaseWithInventory.java
|
UTF-8
| 26,214 | 2.125 | 2 |
[] |
no_license
|
package powercraft.api.gres;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.ICrafting;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import powercraft.api.PC_Utils;
import powercraft.api.block.PC_TileEntity;
import powercraft.api.entity.PC_Entity;
import powercraft.api.gres.slot.PC_Slot;
import powercraft.api.gres.slot.PC_SlotPhantom;
import powercraft.api.inventory.PC_IInventory;
import powercraft.api.inventory.PC_IInventorySizeOverrider;
import powercraft.api.inventory.PC_InventoryUtils;
import powercraft.api.network.PC_PacketHandler;
import powercraft.api.network.packet.PC_PacketSetSlot;
import powercraft.api.network.packet.PC_PacketWindowItems;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class PC_GresBaseWithInventory extends Container implements PC_IInventory, PC_IInventorySizeOverrider {
public static boolean SETTING_OK;
protected final EntityPlayer player;
protected final Slot[][] inventoryPlayerUpper = new Slot[9][3];
protected final Slot[] inventoryPlayerLower = new Slot[9];
protected final IInventory inventory;
protected Slot[] invSlots;
private int dragType = -1;
private int dragState;
private final Set<Slot> dragSlots = new HashSet<Slot>();
public PC_GresBaseWithInventory(EntityPlayer player, IInventory inventory) {
SETTING_OK = PC_Utils.isServer();
this.player = player;
this.inventory = inventory;
inventory.openInventory();
if (inventory instanceof PC_TileEntity) {
((PC_TileEntity) inventory).openContainer(this);
}
if (inventory instanceof PC_Entity) {
((PC_Entity) inventory).openContainer(this);
}
if (player != null) {
for (int i = 0; i < 9; i++) {
this.inventoryPlayerLower[i] = new PC_Slot(player.inventory, i);
addSlotToContainer(this.inventoryPlayerLower[i]);
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 3; j++) {
this.inventoryPlayerUpper[i][j] = new PC_Slot(player.inventory, i + j * 9 + 9);
addSlotToContainer(this.inventoryPlayerUpper[i][j]);
}
}
}
Slot[] sl = getAllSlots();
if (sl != null) {
for (Slot s : sl) {
addSlotToContainer(s);
}
}
}
protected Slot[] getAllSlots() {
this.invSlots = new Slot[this.inventory.getSizeInventory()];
for (int i = 0; i < this.invSlots.length; i++) {
this.invSlots[i] = createSlot(i);
}
return this.invSlots;
}
protected PC_Slot createSlot(int i){
return new PC_Slot(this.inventory, i);
}
@Override
public boolean canInteractWith(EntityPlayer entityplayer) {
return this.inventory instanceof TileEntity ? ((TileEntity) this.inventory).getDistanceFrom(entityplayer.posX, entityplayer.posY, entityplayer.posZ) < 64
: true;
}
public void sendProgressBarUpdate(int key, int value) {
if (this.player instanceof EntityPlayerMP) {
((EntityPlayerMP) this.player).sendProgressBarUpdate(this, key, value);
}
}
@Override
public void onContainerClosed(EntityPlayer par1EntityPlayer) {
super.onContainerClosed(par1EntityPlayer);
closeInventory();
if (this.inventory instanceof PC_TileEntity) {
((PC_TileEntity) this.inventory).closeContainer(this);
}
if (this.inventory instanceof PC_Entity) {
((PC_Entity) this.inventory).closeContainer(this);
}
}
@SuppressWarnings("unchecked")
@Override
public void addCraftingToCrafters(ICrafting crafting) {
if(crafting instanceof EntityPlayerMP){
if (this.crafters.contains(crafting)){
throw new IllegalArgumentException("Listener already listening");
}
this.crafters.add(crafting);
PC_PacketHandler.sendTo(new PC_PacketWindowItems(this.windowId, getInventory()), (EntityPlayerMP)crafting);
PC_PacketHandler.sendTo(new PC_PacketSetSlot(-1, -1, ((EntityPlayerMP)crafting).inventory.getItemStack()), (EntityPlayerMP)crafting);
crafting.sendContainerAndContentsToPlayer(this, this.getInventory());
this.detectAndSendChanges();
}else{
super.addCraftingToCrafters(crafting);
}
if (this.inventory instanceof PC_TileEntity) {
((PC_TileEntity) this.inventory).sendProgressBarUpdates();
}
if (this.inventory instanceof PC_Entity) {
((PC_Entity) this.inventory).sendProgressBarUpdates();
}
}
@Override
@SuppressWarnings("unchecked")
public void detectAndSendChanges(){
for (int i = 0; i < this.inventorySlots.size(); ++i){
ItemStack itemstack = ((Slot)this.inventorySlots.get(i)).getStack();
ItemStack itemstack1 = (ItemStack)this.inventoryItemStacks.get(i);
if (!ItemStack.areItemStacksEqual(itemstack1, itemstack)){
itemstack1 = itemstack == null ? null : itemstack.copy();
this.inventoryItemStacks.set(i, itemstack1);
for (int j = 0; j < this.crafters.size(); ++j){
sendSlotContentsTo((ICrafting) this.crafters.get(j), i, itemstack1);
}
}
}
}
private void sendSlotContentsTo(ICrafting crafting, int i, ItemStack itemstack){
if(crafting instanceof EntityPlayerMP){
if (!((EntityPlayerMP)crafting).isChangingQuantityOnly){
PC_PacketHandler.sendTo(new PC_PacketSetSlot(this.windowId, i, itemstack), (EntityPlayerMP)crafting);
}
}else{
crafting.sendSlotContents(this, i, itemstack);
}
}
@Override
public void putStackInSlot(int slot, ItemStack itemStack){
if(SETTING_OK){
super.putStackInSlot(slot, itemStack);
}
}
@Override
@SideOnly(Side.CLIENT)
public void putStacksInSlots(ItemStack[] itemStacks){
if(SETTING_OK){
super.putStacksInSlots(itemStacks);
}
}
@Override
public boolean canDragIntoSlot(Slot slot){
if(slot instanceof PC_Slot){
return ((PC_Slot)slot).canDragIntoSlot();
}
return true;
}
@Override
public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2) {
Slot slot = (Slot)this.inventorySlots.get(par2);
ItemStack itemstackOut = null;
if (slot != null && slot.getHasStack()){
ItemStack itemstack = slot.getStack();
itemstackOut = itemstack.copy();
if (par2 < 4 * 9){
this.mergeItemStack(itemstack, 4 * 9, this.inventorySlots.size(), true);
}else{
this.mergeItemStack(itemstack, 0, 4 * 9, false);
}
if (itemstack.stackSize == 0){
slot.putStack((ItemStack)null);
}else{
slot.onSlotChanged();
}
if(itemstack.stackSize == itemstackOut.stackSize)
return null;
}
return itemstackOut;
}
@Override
protected boolean mergeItemStack(ItemStack itemStack, int start, int end, boolean par4){
return PC_InventoryUtils.storeItemStackToInventoryFrom(this, itemStack, PC_InventoryUtils.makeIndexList(start, end))==0;
}
@Override
public int getSizeInventory() {
return this.inventorySlots.size();
}
@Override
public ItemStack getStackInSlot(int i) {
return getSlot(i).getStack();
}
@Override
public ItemStack decrStackSize(int i, int j) {
return getSlot(i).decrStackSize(j);
}
@Override
public ItemStack getStackInSlotOnClosing(int i) {
return getSlot(i).getStack();
}
@Override
public void setInventorySlotContents(int i, ItemStack itemstack) {
getSlot(i).putStack(itemstack);
}
@Override
public String getInventoryName() {
return this.inventory.getInventoryName();
}
@Override
public boolean hasCustomInventoryName() {
return this.inventory.hasCustomInventoryName();
}
@Override
public int getInventoryStackLimit() {
return this.inventory.getInventoryStackLimit();
}
@Override
public void markDirty() {
this.inventory.markDirty();
}
@SuppressWarnings("hiding")
@Override
public boolean isUseableByPlayer(EntityPlayer player) {
return this.inventory.isUseableByPlayer(player);
}
@Override
public void openInventory() {
this.inventory.openInventory();
}
@Override
public void closeInventory() {
this.inventory.closeInventory();
}
@Override
public boolean isItemValidForSlot(int i, ItemStack itemstack) {
return getSlot(i).isItemValid(itemstack);
}
@Override
public int[] getAccessibleSlotsFromSide(int var1) {
return null;
}
@Override
public boolean canInsertItem(int var1, ItemStack var2, int var3) {
return false;
}
@Override
public boolean canExtractItem(int var1, ItemStack var2, int var3) {
return false;
}
@Override
public int getSlotStackLimit(int i) {
return getSlot(i).getSlotStackLimit();
}
@Override
public boolean canTakeStack(int i, EntityPlayer entityPlayer) {
return getSlot(i).canTakeStack(entityPlayer);
}
@Override
public boolean canDropStack(int i) {
return false;
}
@Override
public void onTick(World world) {
//
}
@Override
public int[] getAppliedGroups(int i) {
return null;
}
@Override
public int[] getAppliedSides(int i) {
return null;
}
public static boolean checkSlotAndItemStack(Slot slot, ItemStack itemStack, boolean par2){
if (slot != null && slot.getHasStack() && itemStack != null && (slot instanceof PC_SlotPhantom || (itemStack.isItemEqual(slot.getStack()) && ItemStack.areItemStackTagsEqual(slot.getStack(), itemStack))))
{
int i = par2 ? 0 : itemStack.stackSize;
int max = PC_InventoryUtils.getMaxStackSize(itemStack, slot);
return slot.getStack().stackSize + i <= max;
}
return slot == null || !slot.getHasStack();
}
@Override
protected void func_94533_d(){
this.dragState = 0;
this.dragSlots.clear();
}
@SuppressWarnings("hiding")
@Override
public ItemStack slotClick(int slotNumber, int mouseButton, int transfer, EntityPlayer player){
ItemStack itemstack = null;
InventoryPlayer inventoryplayer = player.inventory;
int i1;
ItemStack itemstack3;
if (transfer == 5)
{
int l = this.dragState;
this.dragState = func_94532_c(mouseButton);
if ((l != 1 || this.dragState != 2) && l != this.dragState)
{
this.func_94533_d();
}
else if (inventoryplayer.getItemStack() == null)
{
this.func_94533_d();
}
else if (this.dragState == 0)
{
this.dragType = func_94529_b(mouseButton);
if (func_94528_d(this.dragType))
{
this.dragState = 1;
this.dragSlots.clear();
}
else
{
this.func_94533_d();
}
}
else if (this.dragState == 1)
{
Slot slot = getSlot(slotNumber);
if (slot != null && checkSlotAndItemStack(slot, inventoryplayer.getItemStack(), true) && slot.isItemValid(inventoryplayer.getItemStack()) && inventoryplayer.getItemStack().stackSize > this.dragSlots.size() && this.canDragIntoSlot(slot))
{
this.dragSlots.add(slot);
}
}
else if (this.dragState == 2)
{
if (!this.dragSlots.isEmpty())
{
itemstack3 = inventoryplayer.getItemStack().copy();
i1 = inventoryplayer.getItemStack().stackSize;
Iterator<Slot> iterator = this.dragSlots.iterator();
while (iterator.hasNext())
{
Slot slot1 = iterator.next();
if (slot1 != null && checkSlotAndItemStack(slot1, inventoryplayer.getItemStack(), true) && slot1.isItemValid(inventoryplayer.getItemStack()) && inventoryplayer.getItemStack().stackSize >= this.dragSlots.size() && this.canDragIntoSlot(slot1))
{
ItemStack itemstack1 = itemstack3.copy();
int j1 = slot1.getHasStack() && !(slot1 instanceof PC_SlotPhantom) ? slot1.getStack().stackSize : 0;
func_94525_a(this.dragSlots, this.dragType, itemstack1, j1);
int max = PC_InventoryUtils.getMaxStackSize(itemstack1, slot1);
if (itemstack1.stackSize > max)
{
itemstack1.stackSize = max;
}
i1 -= itemstack1.stackSize - j1;
slot1.putStack(itemstack1);
}
}
itemstack3.stackSize = i1;
if (itemstack3.stackSize <= 0)
{
itemstack3 = null;
}
inventoryplayer.setItemStack(itemstack3);
}
this.func_94533_d();
}
else
{
this.func_94533_d();
}
}
else if (this.dragState != 0)
{
this.func_94533_d();
}
else
{
Slot slot2;
int i2;
ItemStack itemstack5;
if ((transfer == 0 || transfer == 1) && (mouseButton == 0 || mouseButton == 1))
{
if (slotNumber == -999)
{
if (inventoryplayer.getItemStack() != null && slotNumber == -999)
{
if (mouseButton == 0)
{
player.dropPlayerItemWithRandomChoice(inventoryplayer.getItemStack(), true);
inventoryplayer.setItemStack((ItemStack)null);
}
if (mouseButton == 1)
{
player.dropPlayerItemWithRandomChoice(inventoryplayer.getItemStack().splitStack(1), true);
if (inventoryplayer.getItemStack().stackSize == 0)
{
inventoryplayer.setItemStack((ItemStack)null);
}
}
}
}
else if (transfer == 1)
{
if (slotNumber < 0)
{
return null;
}
slot2 = (Slot)this.inventorySlots.get(slotNumber);
if (slot2 != null && canTakeStack(slotNumber, player))
{
itemstack3 = this.transferStackInSlot(player, slotNumber);
if (itemstack3 != null)
{
Item item = itemstack3.getItem();
itemstack = itemstack3.copy();
if (slot2.getStack() != null && slot2.getStack().getItem() == item)
{
this.retrySlotClick(slotNumber, mouseButton, true, player);
}
}
}
}
else
{
if (slotNumber < 0)
{
return null;
}
slot2 = (Slot)this.inventorySlots.get(slotNumber);
if (slot2 != null)
{
itemstack3 = slot2.getStack();
ItemStack itemstack4 = inventoryplayer.getItemStack();
if(slot2 instanceof PC_SlotPhantom){
itemstack3 = null;
slot2.putStack(null);
}
if (itemstack3 != null)
{
itemstack = itemstack3.copy();
}
if (itemstack3 == null)
{
if (itemstack4 != null && slot2.isItemValid(itemstack4))
{
i2 = mouseButton == 0 ? itemstack4.stackSize : 1;
if (i2 > slot2.getSlotStackLimit())
{
i2 = slot2.getSlotStackLimit();
}
if (itemstack4.stackSize >= i2)
{
slot2.putStack(itemstack4.splitStack(i2));
}
if (itemstack4.stackSize == 0)
{
inventoryplayer.setItemStack((ItemStack)null);
}
}
}
else if (canTakeStack(slotNumber, player))
{
if (itemstack4 == null)
{
i2 = mouseButton == 0 ? itemstack3.stackSize : (itemstack3.stackSize + 1) / 2;
if(i2>itemstack3.getMaxStackSize()){
i2 = itemstack3.getMaxStackSize();
}
itemstack5 = slot2.decrStackSize(i2);
inventoryplayer.setItemStack(itemstack5);
if (itemstack3.stackSize == 0)
{
slot2.putStack((ItemStack)null);
}
slot2.onPickupFromSlot(player, inventoryplayer.getItemStack());
}
else if (slot2.isItemValid(itemstack4))
{
if (itemstack3.getItem() == itemstack4.getItem() && itemstack3.getItemDamage() == itemstack4.getItemDamage() && ItemStack.areItemStackTagsEqual(itemstack3, itemstack4))
{
i2 = mouseButton == 0 ? itemstack4.stackSize : 1;
int max = PC_InventoryUtils.getMaxStackSize(itemstack4, slot2);
if(i2 > max - itemstack3.stackSize){
i2 = max - itemstack3.stackSize;
}
itemstack4.splitStack(i2);
if (itemstack4.stackSize == 0)
{
inventoryplayer.setItemStack((ItemStack)null);
}
itemstack3.stackSize += i2;
}
else if (itemstack4.stackSize <= slot2.getSlotStackLimit() && itemstack4.stackSize<=itemstack4.getMaxStackSize())
{
slot2.putStack(itemstack4);
inventoryplayer.setItemStack(itemstack3);
}
}
else if (itemstack3.getItem() == itemstack4.getItem() && itemstack4.getMaxStackSize() > 1 && (!itemstack3.getHasSubtypes() || itemstack3.getItemDamage() == itemstack4.getItemDamage()) && ItemStack.areItemStackTagsEqual(itemstack3, itemstack4))
{
i2 = itemstack3.stackSize;
if (i2 > 0 && i2 + itemstack4.stackSize <= itemstack4.getMaxStackSize())
{
itemstack4.stackSize += i2;
itemstack3 = slot2.decrStackSize(i2);
if (itemstack3.stackSize == 0)
{
slot2.putStack((ItemStack)null);
}
slot2.onPickupFromSlot(player, inventoryplayer.getItemStack());
}
}
}
slot2.onSlotChanged();
}
}
}
else if (transfer == 2 && mouseButton >= 0 && mouseButton < 9)
{
slot2 = (Slot)this.inventorySlots.get(slotNumber);
if (canTakeStack(slotNumber, player))
{
itemstack3 = inventoryplayer.getStackInSlot(mouseButton);
boolean flag = itemstack3 == null || slot2.inventory == inventoryplayer && slot2.isItemValid(itemstack3);
i2 = -1;
if (!flag)
{
i2 = inventoryplayer.getFirstEmptyStack();
flag |= i2 > -1;
}
if (slot2.getHasStack() && flag)
{
itemstack5 = slot2.getStack();
inventoryplayer.setInventorySlotContents(mouseButton, itemstack5.copy());
if ((slot2.inventory != inventoryplayer || !slot2.isItemValid(itemstack3)) && itemstack3 != null)
{
if (i2 > -1)
{
inventoryplayer.addItemStackToInventory(itemstack3);
slot2.decrStackSize(itemstack5.stackSize);
slot2.putStack((ItemStack)null);
slot2.onPickupFromSlot(player, itemstack5);
}
}
else
{
slot2.decrStackSize(itemstack5.stackSize);
slot2.putStack(itemstack3);
slot2.onPickupFromSlot(player, itemstack5);
}
}
else if (!slot2.getHasStack() && itemstack3 != null && slot2.isItemValid(itemstack3))
{
inventoryplayer.setInventorySlotContents(mouseButton, (ItemStack)null);
slot2.putStack(itemstack3);
}
}
}
else if (transfer == 3 && player.capabilities.isCreativeMode && inventoryplayer.getItemStack() == null && slotNumber >= 0)
{
slot2 = (Slot)this.inventorySlots.get(slotNumber);
if (slot2 != null && slot2.getHasStack())
{
itemstack3 = slot2.getStack().copy();
itemstack3.stackSize = itemstack3.getMaxStackSize();
inventoryplayer.setItemStack(itemstack3);
}
}
else if (transfer == 4 && inventoryplayer.getItemStack() == null && slotNumber >= 0)
{
slot2 = (Slot)this.inventorySlots.get(slotNumber);
if (slot2 != null && slot2.getHasStack() && canTakeStack(slotNumber, player))
{
itemstack3 = slot2.decrStackSize(mouseButton == 0 ? 1 : slot2.getStack().stackSize);
slot2.onPickupFromSlot(player, itemstack3);
player.dropPlayerItemWithRandomChoice(itemstack3, true);
}
}
else if (transfer == 6 && slotNumber >= 0)
{
slot2 = (Slot)this.inventorySlots.get(slotNumber);
itemstack3 = inventoryplayer.getItemStack();
if (itemstack3 != null && (slot2 == null || !slot2.getHasStack() || !canTakeStack(slotNumber, player)))
{
i1 = mouseButton == 0 ? 0 : this.inventorySlots.size() - 1;
i2 = mouseButton == 0 ? 1 : -1;
for (int l1 = 0; l1 < 2; ++l1)
{
for (int j2 = i1; j2 >= 0 && j2 < this.inventorySlots.size() && itemstack3.stackSize < itemstack3.getMaxStackSize(); j2 += i2)
{
Slot slot3 = (Slot)this.inventorySlots.get(j2);
if (slot3.getHasStack() && checkSlotAndItemStack(slot3, itemstack3, true) && canTakeStack(j2, player) && this.func_94530_a(itemstack3, slot3) && (l1 != 0 || slot3.getStack().stackSize != slot3.getStack().getMaxStackSize()))
{
int k1 = Math.min(itemstack3.getMaxStackSize() - itemstack3.stackSize, slot3.getStack().stackSize);
ItemStack itemstack2 = slot3.decrStackSize(k1);
itemstack3.stackSize += k1;
if (itemstack2.stackSize <= 0)
{
slot3.putStack((ItemStack)null);
}
slot3.onPickupFromSlot(player, itemstack2);
}
}
}
}
this.detectAndSendChanges();
}
}
return itemstack;
}
@Override
public int getMaxStackSize(ItemStack itemStack, int slot) {
return PC_InventoryUtils.getMaxStackSize(itemStack, getSlot(slot));
}
@Override
public boolean canBeDragged(int i) {
return true;
}
}
| true |
e5cac95e96d3ecc65b065ec6e5ee38012976a43e
|
Java
|
Mozhilka/schoolShag
|
/src/main/java/firm/Position.java
|
UTF-8
| 66 | 1.859375 | 2 |
[] |
no_license
|
package firm;
public enum Position {
DIRECTOR,
EMPLOYEE
}
| true |
a85bdcfbd3164d7c100051b06b056a55009c7ee0
|
Java
|
vishnucg/irm
|
/GIHeatmap/src/data/BeanForecast.java
|
UTF-8
| 3,674 | 1.90625 | 2 |
[] |
no_license
|
package data;
import java.io.Serializable;
public class BeanForecast implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8390399411232723990L;
private String RAW_SERIES_NM;
private String SERIES_NM;
private String SEGMENT_NM;
private String SEGMENT_CATEGORY_NM;
private String RAW_REGION_CD;
private String REGION_AREA_NM;
private String REGION_AREA_CD;
private String REGION_LONG_NM;
private String SALES_GEOG_TYPE_CD;
private String REGION_CHAR_CD;
private String BUSINESS_MONTH;
private String BUSINESS_METRIC;
private String SCORE;
public BeanForecast(String RAW_SERIES_NM, String sERIES_NM, String sEGMENT_NM, String sEGMENT_CATEGORY_NM,
String rAW_REGION_CD, String rEGION_AREA_NM, String rEGION_AREA_CD, String rEGION_LONG_NM,
String sALES_GEOG_TYPE_CD, String rEGION_CHAR_CD, String bUSINESS_MONTH, String bUSINESS_METRIC,
String sCORE) {
super();
this.RAW_SERIES_NM = RAW_SERIES_NM;
this.SERIES_NM = sERIES_NM;
this.SEGMENT_NM = sEGMENT_NM;
this.SEGMENT_CATEGORY_NM = sEGMENT_CATEGORY_NM;
this.RAW_REGION_CD = rAW_REGION_CD;
this.REGION_AREA_NM = rEGION_AREA_NM;
this.REGION_AREA_CD = rEGION_AREA_CD;
this.REGION_LONG_NM = rEGION_LONG_NM;
this.SALES_GEOG_TYPE_CD = sALES_GEOG_TYPE_CD;
this.REGION_CHAR_CD = rEGION_CHAR_CD;
this.BUSINESS_MONTH = bUSINESS_MONTH;
this.BUSINESS_METRIC = bUSINESS_METRIC;
this.SCORE = sCORE;
}
public String getRAW_SERIES_NM() {
return RAW_SERIES_NM;
}
public void setRAW_SERIES_NM(String rAW_SERIES_NM) {
RAW_SERIES_NM = rAW_SERIES_NM;
}
public String getSERIES_NM() {
return SERIES_NM;
}
public void setSERIES_NM(String sERIES_NM) {
SERIES_NM = sERIES_NM;
}
public String getSEGMENT_NM() {
return SEGMENT_NM;
}
public void setSEGMENT_NM(String sEGMENT_NM) {
SEGMENT_NM = sEGMENT_NM;
}
public String getSEGMENT_CATEGORY_NM() {
return SEGMENT_CATEGORY_NM;
}
public void setSEGMENT_CATEGORY_NM(String sEGMENT_CATEGORY_NM) {
SEGMENT_CATEGORY_NM = sEGMENT_CATEGORY_NM;
}
public String getRAW_REGION_CD() {
return RAW_REGION_CD;
}
public void setRAW_REGION_CD(String rAW_REGION_CD) {
RAW_REGION_CD = rAW_REGION_CD;
}
public String getREGION_AREA_NM() {
return REGION_AREA_NM;
}
public void setREGION_AREA_NM(String rEGION_AREA_NM) {
REGION_AREA_NM = rEGION_AREA_NM;
}
public String getREGION_AREA_CD() {
return REGION_AREA_CD;
}
public void setREGION_AREA_CD(String rEGION_AREA_CD) {
REGION_AREA_CD = rEGION_AREA_CD;
}
public String getREGION_LONG_NM() {
return REGION_LONG_NM;
}
public void setREGION_LONG_NM(String rEGION_LONG_NM) {
REGION_LONG_NM = rEGION_LONG_NM;
}
public String getSALES_GEOG_TYPE_CD() {
return SALES_GEOG_TYPE_CD;
}
public void setSALES_GEOG_TYPE_CD(String sALES_GEOG_TYPE_CD) {
SALES_GEOG_TYPE_CD = sALES_GEOG_TYPE_CD;
}
public String getREGION_CHAR_CD() {
return REGION_CHAR_CD;
}
public void setREGION_CHAR_CD(String rEGION_CHAR_CD) {
REGION_CHAR_CD = rEGION_CHAR_CD;
}
public String getBUSINESS_MONTH() {
return BUSINESS_MONTH;
}
public void setBUSINESS_MONTH(String bUSINESS_MONTH) {
BUSINESS_MONTH = bUSINESS_MONTH;
}
public String getBUSINESS_METRIC() {
return BUSINESS_METRIC;
}
public void setBUSINESS_METRIC(String bUSINESS_METRIC) {
BUSINESS_METRIC = bUSINESS_METRIC;
}
public String getSCORE() {
return SCORE;
}
public void setSCORE(String sCORE) {
SCORE = sCORE;
}
}
| true |
d8628d659050310e239962c8bcd04bef88e23325
|
Java
|
Apereo-Learning-Analytics-Initiative/Larissa
|
/src/main/java/nl/uva/larissa/json/model/validate/ValidGroupValidator.java
|
UTF-8
| 672 | 2.171875 | 2 |
[
"Apache-2.0",
"EPL-1.0",
"LGPL-2.0-or-later",
"LGPL-2.1-only",
"CDDL-1.0",
"GPL-2.0-only"
] |
permissive
|
package nl.uva.larissa.json.model.validate;
import java.util.List;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import nl.uva.larissa.json.model.Agent;
import nl.uva.larissa.json.model.Group;
public class ValidGroupValidator implements
ConstraintValidator<ValidGroup, Group> {
@Override
public void initialize(ValidGroup constraintAnnotation) {
}
@Override
public boolean isValid(Group group, ConstraintValidatorContext context) {
if (group.getIdentifier() == null) {
List<Agent> members = group.getMember();
return members != null && members.size() > 0;
}
// not anonymous
return true;
}
}
| true |
7935c5afe665995938bc567026ec41efc6753089
|
Java
|
LetsCloud/hw-gae
|
/hw-gae-shared/src/main/java/hu/hw/cloud/shared/api/UserGroupResource.java
|
UTF-8
| 1,141 | 1.90625 | 2 |
[
"Apache-2.0"
] |
permissive
|
/**
*
*/
package hu.hw.cloud.shared.api;
import static hu.hw.cloud.shared.api.ApiParameters.WEBSAFEKEY;
import static hu.hw.cloud.shared.api.ApiPaths.PATH_WEBSAFEKEY;
import static hu.hw.cloud.shared.api.ApiPaths.SpaV1.ROOT;
import static hu.hw.cloud.shared.api.ApiPaths.SpaV1.USER_GROUP;
import java.util.List;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import hu.hw.cloud.shared.dto.ErrorResponseDto;
import hu.hw.cloud.shared.dto.common.UserGroupDto;
/**
* @author robi
*
*/
@Path(ROOT + USER_GROUP)
@Produces(MediaType.APPLICATION_JSON)
public interface UserGroupResource {
@GET
List<UserGroupDto> list();
@POST
UserGroupDto create(UserGroupDto dto);
@GET
@Path(PATH_WEBSAFEKEY)
UserGroupDto read(@PathParam(WEBSAFEKEY) String webSafeKey);
@PUT
UserGroupDto update(UserGroupDto dto);
@DELETE
@Path(PATH_WEBSAFEKEY)
void delete(@PathParam(WEBSAFEKEY) String webSafeKey);
@HEAD
ErrorResponseDto error();
}
| true |
c4717e1d2457cde1e422f6cc66a40318f10ab781
|
Java
|
Gabrielomn/Praticas-Grafos
|
/ExercicioPratico2/src/main/Main.java
|
UTF-8
| 1,476 | 2.640625 | 3 |
[] |
no_license
|
package main;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
public class Main {
public static void main(String[] args) {
DefaultDirectedGraph<String, DefaultEdge> g = new DefaultDirectedGraph<>(DefaultEdge.class);
g.addVertex("1"); g.addVertex("11");
g.addVertex("2"); g.addVertex("12");
g.addVertex("3"); g.addVertex("13");
g.addVertex("4"); g.addVertex("14");
g.addVertex("5"); g.addVertex("15");
g.addVertex("6"); g.addVertex("16");
g.addVertex("7"); g.addVertex("17");
g.addVertex("8"); g.addVertex("18");
g.addVertex("9"); g.addVertex("19");
g.addVertex("10"); g.addVertex("20");
g.addEdge("1", "2"); g.addEdge("2", "6"); g.addEdge("6", "5");
g.addEdge("5", "1"); g.addEdge("6", "7"); g.addEdge("7", "3");
g.addEdge("3", "2"); g.addEdge("3", "4"); g.addEdge("8", "4");
g.addEdge("8", "7"); g.addEdge("5", "9"); g.addEdge("9", "10");
g.addEdge("6", "10"); g.addEdge("11", "10"); g.addEdge("11", "7");
g.addEdge("12", "11"); g.addEdge("8", "12"); g.addEdge("13", "9");
g.addEdge("13", "14"); g.addEdge("14", "10"); g.addEdge("15", "14");
g.addEdge("11", "15"); g.addEdge("16", "15"); g.addEdge("12", "16");
g.addEdge("17", "13"); g.addEdge("17", "18"); g.addEdge("14", "18");
g.addEdge("19", "18"); g.addEdge("15", "19"); g.addEdge("20", "16");
g.addEdge("20", "19");
Solution sol = new Solution(g);
sol.Questao2();
System.out.println(sol.respostas());
}
}
| true |
03d2dbbb88efdec7ad069178aed76219f8263fd4
|
Java
|
JanisVuls/jg2019a_JanisVuls
|
/src/lv/jg/lesson10/homework1/UserValidationService.java
|
UTF-8
| 1,301 | 2.96875 | 3 |
[] |
no_license
|
package lv.jg.lesson10.homework1;
//šai bija jābūt servisa klasei, kura veic User validāciju
//bija jāizveido arī savas validationException
public class UserValidationService {
public static void main(String[] args) {
shouldCreateUser();
shouldFailIfInputValueToSmall();
shouldFailIfInputValueToLarge();
}
private static void shouldCreateUser() {
User user = new User("Maksims", "Maisins", 1111);
}
private static void shouldFailIfInputValueToSmall() {
System.out.println("================");
boolean result = false;
try {
User user = new User("Ma", "Maisins", 0);
} catch (IllegalArgumentException ex) {
result = true;
}
System.out.println("Test: shouldFailIfInputValueToSmall");
System.out.println(result ? "SUCCESS" : "FAILED");
}
private static void shouldFailIfInputValueToLarge() {
System.out.println("================");
boolean result = false;
try {
User user = new User("Maksims", "Maisins123456789", 120);
} catch (IllegalArgumentException ex) {
result = true;
}
System.out.println("Test: shouldFailIfInputValueToLarge");
System.out.println(result ? "SUCCESS" : "FAILED");
}
}
| true |
545a6d07e9a553514c04daa2edf205c9254a220d
|
Java
|
NSU-SU21-CSE486-1/1711593_SU21_CSE486_1
|
/Project/Version01/Uniclubz/app/src/main/java/com/fahemaSultana/uniclubz/sharedPreference/CredentialPreference.java
|
UTF-8
| 1,476 | 2.28125 | 2 |
[] |
no_license
|
package com.fahemaSultana.uniclubz.sharedPreference;
import android.content.Context;
import android.content.SharedPreferences;
import com.fahemaSultana.uniclubz.MyApplication;
import com.fahemaSultana.uniclubz.dataModel.UserEntity;
import com.google.gson.Gson;
public class CredentialPreference {
private static CredentialPreference credentialPreference;
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor editor;
private CredentialPreference() {
sharedPreferences = MyApplication.getAppContext().getSharedPreferences("credential_preference", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.apply();
}
public static CredentialPreference getInstance() {
if (credentialPreference == null) credentialPreference = new CredentialPreference();
return credentialPreference;
}
public String getUserId() {
return sharedPreferences.getString("user_id", "");
}
public void setUserId(String uid) {
editor.putString("user_id", uid);
editor.apply();
}
public UserEntity getUserDetails() {
String userDetailsJson = sharedPreferences.getString("user_details", "");
return new Gson().fromJson(userDetailsJson, UserEntity.class);
}
public void setUserDetails(UserEntity userEntity) {
editor.putString("user_details", new Gson().toJson(userEntity));
editor.apply();
}
}
| true |
04f730beaf4ab99b9c97767a169350290ed916a2
|
Java
|
danielrp/pulsaGAE
|
/PulsaGAE/src/com/pulsa/persistence/model/Product.java
|
UTF-8
| 1,670 | 2.1875 | 2 |
[] |
no_license
|
package com.pulsa.persistence.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.CascadeType;
import java.util.List;
import java.util.ArrayList;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.pulsa.util.helper.SessionHelper;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key id;
private String code;
private String provider;
private int nominal;
private long cost;
private long price;
private String username;
public Product() {
// setId(KeyFactory.createKey(Customer.class.getSimpleName(), 0));
setUsername(SessionHelper.getUsername());
}
public Product(String id) {
}
public Key getId() {
return id;
}
public void setId(Key id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public long getCost() {
return cost;
}
public void setCost(long cost) {
this.cost = cost;
}
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
public int getNominal() {
return nominal;
}
public void setNominal(int nominal) {
this.nominal = nominal;
}
public long getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
| true |
f14eb201cf759af9f1391751f10e5373f25ed661
|
Java
|
westlakestudent/PicWestlakestudent
|
/src/com/westlakestudent/activity/ImageActivity.java
|
UTF-8
| 1,169 | 2.25 | 2 |
[] |
no_license
|
package com.westlakestudent.activity;
import java.util.ArrayList;
import com.westlakestudent.constants.Constants;
import com.westlakestudent.ui.ImageShow;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.TextView;
/**
*
* ImageActivity
* @author chendong
* 2014年11月28日 上午11:03:56
* @version 1.0.0
*
*/
public class ImageActivity extends Activity {
private static final String TAG = "ImageActivity";
private ImageShow show = null;
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
if(bundle == null){
Log.d(TAG, "bundle = null");
TextView error = new TextView(this);
error.setGravity(Gravity.CENTER);
error.setText("请返回");
setContentView(error);
return;
}
int selected = bundle.getInt(Constants.SELECTED);
ArrayList<String> data = (ArrayList<String>) bundle.get(Constants.DATA);
show = new ImageShow(this, data, selected);
show.setActivity(ImageActivity.this);
setContentView(show);
}
}
| true |
c831521e19ed8d449465b12636b2bf394aac6796
|
Java
|
yiminglao/MahJong
|
/src/RankTile.java
|
UTF-8
| 454 | 3.15625 | 3 |
[] |
no_license
|
public class RankTile extends Tile {
protected int rank;
public RankTile(int rank)
{
this.rank = rank;
}
public boolean matches(Tile other){
if(this == other){
return true;
}
if(this == null){
return false;
}
if(getClass() != other.getClass()){
return false;
}
RankTile T = (RankTile) other;
return (rank == T.rank);
}
}
| true |
c677d64ad8954985d33e7548fb06ba3b5119341c
|
Java
|
sadlay/lambda
|
/src/main/java/com/lay/lambda/function/Fifth.java
|
UTF-8
| 936 | 2.78125 | 3 |
[] |
no_license
|
package com.lay.lambda.function;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Fifth {
private static List<Person> personList=Util.personList();
public static List<Person> findByName(String name){
return find(person -> name.equals(person.getName()));
}
public static List<Person> findBySex(String sex){
return find(person -> sex.equals(person.getSex()));
}
public static List<Person> find(Predicate<Person> predicate){
return personList.stream().filter(predicate).collect(Collectors.toList());
}
public static void main(String[] args){
findByName("zhangsan").stream().forEach(p-> System.out.println(JSONObject.toJSONString(p)));
findBySex("男").stream().forEach(p-> System.out.println(JSONObject.toJSONString(p)));
}
}
| true |
7b28fcd40bee48e23bf66856683dbd251b460350
|
Java
|
BharatiAkella/Man-Power
|
/ManPower/src/com/wise/manpower/dao/AddressDAO.java
|
UTF-8
| 3,400 | 2.703125 | 3 |
[] |
no_license
|
package com.wise.manpower.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.wise.manpower.dto.Address;
import com.wise.manpower.dao.DBUtility;
public class AddressDAO {
public int insert(Address address){
final String QUERY ="insert into Address(User_Id,Door_Number,Street,City,State,Postal_Code,Country) values(?,?,?,?,?,?,?)";
int status = 0;
PreparedStatement preparedStatement = null;
Connection connection = DBUtility.getConnection();
try{
preparedStatement = connection.prepareStatement(QUERY);
preparedStatement.setInt(1 ,address.getUserId());
preparedStatement.setString(2 ,address.getDoorNumber());
preparedStatement.setString(3 ,address.getStreet());
preparedStatement.setString(4 ,address.getCity());
preparedStatement.setString(5 ,address.getState());
preparedStatement.setInt(6, address.getPostalCode());
preparedStatement.setString(7, address.getCountry());
status = preparedStatement.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
}finally{
DBUtility.close(connection, preparedStatement);
}
return status;
}
public Address get(int userId){
ResultSet resultSet = null;
Address address = new Address();
PreparedStatement preparedStatement = null;
final String QUERY = "select * from Address where User_id = ?";
Connection connection = DBUtility.getConnection();
try {
preparedStatement = connection.prepareStatement(QUERY);
preparedStatement.setInt(1, userId);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
address.setUserId(resultSet.getInt(1));
address.setDoorNumber(resultSet.getString(2));
address.setStreet(resultSet.getString(3));
address.setCity(resultSet.getString(4));
address.setState(resultSet.getString(5));
address.setPostalCode(resultSet.getInt(6));
address.setCountry(resultSet.getString(7));
}
}catch(SQLException e){
e.printStackTrace();
}finally{
DBUtility.close(resultSet, preparedStatement);
}
return address;
}
public int updateAddress(int userId,int doorNumber,String street,String city,String state,int postalCode,String country ){
//ResultSet resultSet = null;
//User user = new User();
PreparedStatement preparedStatement = null;
int status = 0;
final String QUERY = "update Address set Door_Number = ?,Street = ?,City = ?,State = ?,Postal_Code = ?,Country = ? where User_Id = ?";
Connection connection = DBUtility.getConnection();
try {
preparedStatement = connection.prepareStatement(QUERY);
preparedStatement.setInt(1, doorNumber );
preparedStatement.setString(2 ,street);
preparedStatement.setString(3 ,city);
preparedStatement.setString(4 ,state);
preparedStatement.setInt(5 ,postalCode);
preparedStatement.setString(6 ,country);
preparedStatement.setInt(7 ,userId);
status = preparedStatement.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
}finally{
DBUtility.close(connection, preparedStatement);
}
return status;
}
public static void main(String args[]){
AddressDAO u = new AddressDAO();
//User r = new User();
//r = u.update(1,987654321);
System.out.println(u.updateAddress(1,9,"street","city","state",99,"country"));
}
}
| true |
4b5559bb006c8cd32ebb325bce39a2363508e678
|
Java
|
MasonNie/LeetCode
|
/src/Solution80.java
|
UTF-8
| 1,040 | 3.328125 | 3 |
[] |
no_license
|
public class Solution80 {
public int removeDuplicates(int[] nums) {
int len = 0,count = 1,pos = 0; //pos代表当前去重后正确数组最后一个位置
if (nums.length == 0) return 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i]==nums[pos]){
count++;
if (count > 2){
nums[pos] = nums[i]; //重复了代表这个数字多余,pos不必要向前
}
else {
pos++;
nums[pos] = nums[i];
}
}
else {
count = 1;
pos++;
nums[pos] = nums[i];
}
}
return pos + 1;
}
public static void main(String[] args) {
int[] a = {0,0,1,1,1,1,2,3,3,3};
int[] b = {};
int[] in = b;
int len = new Solution80().removeDuplicates(in);
for (int i = 0; i < len; i++) {
System.out.print(in[i] + " ");
}
}
}
| true |
6e388438f153a054602170568a5a843be0879f66
|
Java
|
knastnt/JavaRushTasks
|
/3.JavaMultithreading/src/com/javarush/task/task28/task2805/MyThread.java
|
UTF-8
| 1,672 | 3.03125 | 3 |
[] |
no_license
|
package com.javarush.task.task28.task2805;
import java.util.concurrent.atomic.AtomicInteger;
public class MyThread extends Thread {
private static volatile Integer counter = 0;
private int getNewPriority(){
int newPriority;
synchronized (counter) {
newPriority = ++counter;
if (newPriority > 10) {
counter = 1;
newPriority = 1;
}
}
if(Thread.currentThread().getThreadGroup().getMaxPriority() < newPriority) newPriority = Thread.currentThread().getThreadGroup().getMaxPriority();
return newPriority;
}
public MyThread() {
this.setPriority(getNewPriority());
}
public MyThread(Runnable target) {
super(target);
this.setPriority(getNewPriority());
}
public MyThread(ThreadGroup group, Runnable target) {
super(group, target);
this.setPriority(getNewPriority());
}
public MyThread(String name) {
super(name);
this.setPriority(getNewPriority());
}
public MyThread(ThreadGroup group, String name) {
super(group, name);
this.setPriority(getNewPriority());
}
public MyThread(Runnable target, String name) {
super(target, name);
this.setPriority(getNewPriority());
}
public MyThread(ThreadGroup group, Runnable target, String name) {
super(group, target, name);
this.setPriority(getNewPriority());
}
public MyThread(ThreadGroup group, Runnable target, String name, long stackSize) {
super(group, target, name, stackSize);
this.setPriority(getNewPriority());
}
}
| true |
0bd9dda9450afb3ee297718e5860d61514e246be
|
Java
|
equaliser-app/equaliser-api
|
/src/main/java/events/equaliser/java/handlers/Account.java
|
UTF-8
| 7,500 | 2.390625 | 2 |
[] |
no_license
|
package events.equaliser.java.handlers;
import com.fasterxml.jackson.databind.JsonNode;
import events.equaliser.java.auth.Session;
import events.equaliser.java.model.auth.SecurityEvent;
import events.equaliser.java.model.auth.TwoFactorToken;
import events.equaliser.java.model.geography.Country;
import events.equaliser.java.model.user.PublicUser;
import events.equaliser.java.model.user.User;
import events.equaliser.java.util.Json;
import events.equaliser.java.util.Request;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.sql.SQLConnection;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.RoutingContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
/**
* Request handlers related to a user account.
*/
public class Account {
private static final Logger logger = LoggerFactory.getLogger(Account.class);
/**
* Retrieve the logged in user's information.
*
* @param context The routing context.
* @param connection A database connection.
* @param handler The result.
*/
public static void getUser(RoutingContext context,
SQLConnection connection,
Handler<AsyncResult<JsonNode>> handler) {
Session session = context.get("session");
User user = session.getUser();
JsonNode node = Json.MAPPER.convertValue(user, JsonNode.class);
handler.handle(Future.succeededFuture(node));
}
/**
* Retrieve the logged in user's security events.
*
* @param context The routing context.
* @param connection A database connection.
* @param handler The result.
*/
public static void getSecurityEvents(RoutingContext context,
SQLConnection connection,
Handler<AsyncResult<JsonNode>> handler) {
Session session = context.get("session");
User user = session.getUser();
SecurityEvent.retrieveByUser(user, 10, connection, eventsRes -> {
if (eventsRes.failed()) {
handler.handle(Future.failedFuture(eventsRes.cause()));
return;
}
List<SecurityEvent> result = eventsRes.result();
JsonNode node = Json.MAPPER.convertValue(result, JsonNode.class);
handler.handle(Future.succeededFuture(node));
});
}
/**
* Register a new user.
*
* @param context The routing context.
* @param connection A database connection.
* @param handler The result.
*/
public static void postRegister(RoutingContext context,
SQLConnection connection,
Handler<AsyncResult<JsonNode>> handler) {
Set<FileUpload> files = context.fileUploads();
if (files.size() == 0) {
handler.handle(Future.failedFuture("No photo uploaded"));
return;
}
FileUpload photo = files.iterator().next();
if (!photo.contentType().equals("image/jpeg") || !photo.fileName().endsWith(".jpg")) {
handler.handle(Future.failedFuture("Image must be a JPEG"));
return;
}
HttpServerRequest request = context.request();
List<String> fields = Arrays.asList("username", "countryId", "forename", "surname", "email", "areaCode",
"subscriberNumber", "password");
try {
Map<String, String> parsed = Request.parseData(request, fields, Request::getFormAttribute);
int countryId = Integer.parseInt(parsed.get("countryId"));
// parameters are all there; now ensure the image is acceptable
Vertx.currentContext().executeBlocking(code -> {
try {
logger.debug("Uploaded file: {}, {} bytes",
photo.uploadedFileName(), photo.size());
BufferedImage image = ImageIO.read(new File(photo.uploadedFileName()));
Files.delete(Paths.get(photo.uploadedFileName()));
if (image == null) {
code.fail("Unreadable image");
}
else {
User.validateProfilePhoto(image);
code.complete(image);
}
} catch (IOException e) {
code.fail(e);
}
}, codeRes -> {
if (codeRes.failed()) {
handler.handle(Future.failedFuture(codeRes.cause()));
return;
}
BufferedImage image = (BufferedImage)codeRes.result();
Country.retrieveById(countryId, connection, countryRes -> {
if (countryRes.failed()) {
handler.handle(Future.failedFuture(countryRes.cause()));
return;
}
Country country = countryRes.result();
logger.debug("Identified {}", country);
User.register(
parsed.get("username"),
country, parsed.get("forename"), parsed.get("surname"),
parsed.get("email"),
parsed.get("areaCode"), parsed.get("subscriberNumber"),
parsed.get("password"),
image,
connection,
registerRes -> TwoFactorToken.initiateTwoFactor(connection, registerRes, handler));
});
});
} catch (NumberFormatException e) {
handler.handle(Future.failedFuture("'countryId' must be numeric"));
} catch (IllegalArgumentException e) {
handler.handle(Future.failedFuture(e.getMessage()));
}
}
/**
* Retrieve users whose username matches a pattern.
*
* @param context The routing context.
* @param connection A database connection.
* @param handler The result.
*/
public static void getUsernames(RoutingContext context,
SQLConnection connection,
Handler<AsyncResult<JsonNode>> handler) {
HttpServerRequest request = context.request();
List<String> fields = Collections.singletonList("query");
try {
Map<String, String> parsed = Request.parseData(request, fields, Request::getParam);
PublicUser.searchByUsername(parsed.get("query"), 5, connection, queryRes -> {
if (queryRes.succeeded()) {
List<PublicUser> users = queryRes.result();
JsonNode node = Json.MAPPER.convertValue(users, JsonNode.class);
handler.handle(Future.succeededFuture(node));
}
else {
handler.handle(Future.failedFuture(queryRes.cause()));
}
});
} catch (IllegalArgumentException e) {
handler.handle(Future.failedFuture(e.getMessage()));
}
}
}
| true |
a5964e2b9ab07e0be2f302ff48188b8e30e3314e
|
Java
|
MichaelArkh/Space
|
/app/src/main/java/com/example/space_final/ui/dashboard/RocketItem.java
|
UTF-8
| 5,566 | 2.203125 | 2 |
[] |
no_license
|
package com.example.space_final.ui.dashboard;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import com.google.android.gms.maps.model.LatLng;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
/**
* The type Rocket item.
*/
public class RocketItem {
private int itemId;
private Date startTime;
private String name;
private String summary;
private String image;
private String location;
private LatLng cords;
private String rocket;
private String wikiURL;
private int status;
private boolean saved;
/**
* Instantiates a new Rocket item.
*/
public RocketItem(){
itemId = -1;
}
/**
* Instantiates a new Rocket item.
*
* @param startTime the start time
* @param name the name
* @param summary the summary
* @param image the image
* @param location the location
* @param cords the cords
* @param rocket the rocket
* @param wikiURL the wiki url
* @param status the status
*/
public RocketItem(Date startTime, String name, String summary, String image, String location, LatLng cords, String rocket, String wikiURL, int status) {
this.startTime = startTime;
this.name = name;
this.summary = summary;
this.wikiURL = wikiURL;
this.image = image;
this.location = location;
this.cords = cords;
this.rocket = rocket;
this.status = status;
}
/**
* Gets status.
*
* @return the status
*/
public int getStatus() {
return status;
}
/**
* Sets status.
*
* @param status the status
*/
public void setStatus(int status) {
this.status = status;
}
/**
* Gets wiki url.
*
* @return the wiki url
*/
public String getWikiURL() {
return wikiURL;
}
/**
* Sets wiki url.
*
* @param wikiURL the wiki url
*/
public void setWikiURL(String wikiURL) {
this.wikiURL = wikiURL;
}
/**
* Gets item id.
*
* @return the item id
*/
public int getItemId() {
return itemId;
}
/**
* Sets item id.
*
* @param itemId the item id
*/
public void setItemId(int itemId) {
this.itemId = itemId;
}
/**
* Gets start time.
*
* @return the start time
*/
public Date getStartTime() {
return startTime;
}
/**
* Sets start time.
*
* @param startTime the start time
*/
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
/**
* Gets name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Sets name.
*
* @param name the name
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets summary.
*
* @return the summary
*/
public String getSummary() {
return summary;
}
/**
* Sets summary.
*
* @param summary the summary
*/
public void setSummary(String summary) {
this.summary = summary;
}
/**
* Gets image.
*
* @return the image
*/
public String getImage() {
return image;
}
/**
* Sets image.
*
* @param image the image
*/
public void setImage(String image) {
this.image = image;
}
/**
* Gets location.
*
* @return the location
*/
public String getLocation() {
return location;
}
/**
* Sets location.
*
* @param location the location
*/
public void setLocation(String location) {
this.location = location;
}
/**
* Gets cords.
*
* @return the cords
*/
public LatLng getCords() {
return cords;
}
/**
* Sets cords.
*
* @param cords the cords
*/
public void setCords(LatLng cords) {
this.cords = cords;
}
/**
* Is saved boolean.
*
* @return the boolean
*/
public boolean isSaved() {
return saved;
}
/**
* Sets saved.
*
* @param saved the saved
*/
public void setSaved(boolean saved) {
this.saved = saved;
}
/**
* Gets rocket.
*
* @return the rocket
*/
public String getRocket() {
return rocket;
}
/**
* Sets rocket.
*
* @param rocket the rocket
*/
public void setRocket(String rocket) {
this.rocket = rocket;
}
/**
* Used for converting the image link to a bitmap.
* @deprecated
*/
private class SetImageTask extends AsyncTask<String, Void, Bitmap> {
/**
* Instantiates a new Set image task.
*/
public SetImageTask() {
}
@Override
protected Bitmap doInBackground(String... strings) {
String imgurl = strings[0];
Bitmap logo = null;
try {
InputStream is = new URL(imgurl).openStream();
logo = BitmapFactory.decodeStream(is);
} catch (Exception e) {
e.printStackTrace();
}
return logo;
}
}
/**
* Converts this object to a string
* @return the string
*/
public String toString(){
return this.name;
}
}
| true |
d3004938958b388b0a06d1dfa33c20c440b06917
|
Java
|
niuzj/MiniBrain
|
/app/src/main/java/com/niuzj/minibrain/MainActivity.java
|
UTF-8
| 8,077 | 1.796875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.niuzj.minibrain;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ArrayAdapter;
import com.niuzj.corelibrary.base.BaseActivity;
import com.niuzj.corelibrary.utils.JsonUtil;
import com.niuzj.corelibrary.utils.SpUtil;
import com.niuzj.corelibrary.views.DefaultDialog;
import com.niuzj.corelibrary.views.LoadingDialog;
import com.niuzj.corelibrary.views.TitleBar;
import com.niuzj.minibrain.activity.AddActivity;
import com.niuzj.minibrain.activity.SettingActivity;
import com.niuzj.minibrain.activity.UrlListActivity;
import com.niuzj.minibrain.adapter.TypeListAdapter;
import com.niuzj.minibrain.bean.TypeBean;
import com.niuzj.minibrain.bean.TypeBeanHelper;
import com.niuzj.minibrain.bean.TypeBean_;
import com.niuzj.minibrain.bean.UrlBean;
import com.niuzj.minibrain.bean.UrlBeanHelper;
import com.niuzj.minibrain.constant.SPConstant;
import com.niuzj.minibrain.interfaces.OnItemClickListener;
import com.niuzj.minibrain.interfaces.OnItemLongClickListener;
import com.niuzj.minibrain.views.TypeAdapterItemDecoration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import io.objectbox.Box;
import io.objectbox.BoxStore;
import io.objectbox.android.AndroidScheduler;
import io.objectbox.query.Query;
import io.objectbox.query.QueryBuilder;
import io.objectbox.reactive.DataObserver;
import io.objectbox.reactive.DataSubscriptionList;
import io.objectbox.reactive.ErrorObserver;
public class MainActivity extends BaseActivity implements OnItemClickListener, OnItemLongClickListener {
RecyclerView mRecyclerView;
TitleBar mTitleBar;
TypeListAdapter mAdapter;
List<TypeBean> mList;
DataSubscriptionList mDataSubscriptionList = new DataSubscriptionList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initDataAndView();
refreshList();
}
@Override
public int getLayoutId() {
return R.layout.activity_main;
}
private void initDataAndView() {
mList = new ArrayList<>();
mAdapter = new TypeListAdapter(this, mList);
mAdapter.setOnItemClickListener(this);
mAdapter.setOnItemLongClickListener(this);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.addItemDecoration(new TypeAdapterItemDecoration(this));
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
mRecyclerView.setAdapter(mAdapter);
mTitleBar = findViewById(R.id.title_bar);
mTitleBar.setOnTitleBarClickListener(new TitleBar.OnTitleBarClickListener() {
@Override
public void clickLeft() {
}
@Override
public void clickRight() {
Intent intent = new Intent(MainActivity.this, SettingActivity.class);
startActivity(intent);
}
});
}
@Override
protected void onRestart() {
super.onRestart();
}
private void refreshList() {
final LoadingDialog loadingDialog = new LoadingDialog(this);
loadingDialog.show();
BoxStore boxStore = MineApplication.getInstance().getBoxStore();
Box<TypeBean> typeBeanBox = boxStore.boxFor(TypeBean.class);
QueryBuilder<TypeBean> queryBuilder = typeBeanBox.query();
Query<TypeBean> query = queryBuilder.greater(TypeBean_.count, 0)
.orderDesc(TypeBean_.updateTime)
.greater(TypeBean_.count, 0)
.build();
query.subscribe(mDataSubscriptionList)
.on(AndroidScheduler.mainThread())
.onError(new ErrorObserver() {
@Override
public void onError(Throwable th) {
loadingDialog.dismiss();
TypeBean addType = new TypeBean();
addType.setType(getString(R.string.add));
addType.setAddFlag(true);
mList.clear();
mList.add(addType);
mAdapter.notifyDataSetChanged();
}
})
.observer(new DataObserver<List<TypeBean>>() {
@Override
public void onData(List<TypeBean> data) {
loadingDialog.dismiss();
mList.clear();
TypeBean addType = new TypeBean();
addType.setAddFlag(true);
addType.setType(getString(R.string.add));
if (data != null && data.size() > 0) {
mList.addAll(data);
}
mList.add(addType);
mAdapter.notifyDataSetChanged();
TypeBeanHelper.getInstance().printLn(mList);
}
});
}
@Override
public void onItemClick(int position) {
TypeBean typeBean = mList.get(position);
if (typeBean.isAddFlag()) {
Intent intent = new Intent(this, AddActivity.class);
startActivity(intent);
} else {
Intent intent = new Intent(this, UrlListActivity.class);
intent.putExtra("type_bean", typeBean);
startActivity(intent);
}
}
@Override
public void onItemLongClick(int position) {
final TypeBean typeBean = mList.get(position);
if (!typeBean.isAddFlag()) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setAdapter(new ArrayAdapter<String>(this, R.layout.adapter_list_dialog_item, 0, Arrays.asList(getString(R.string.add), getString(R.string.delete), getString(R.string.cancel))), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
//添加
Intent intent = new Intent(MainActivity.this, AddActivity.class);
UrlBean urlBean = new UrlBean();
urlBean.type = typeBean.getType();
intent.putExtra("url_bean", urlBean);
startActivity(intent);
break;
case 1:
//删除
showDeleteDialog(typeBean);
break;
case 2:
break;
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
/**
* 删除确认弹窗
*
* @param typeBean
*/
private void showDeleteDialog(final TypeBean typeBean) {
new DefaultDialog.Builder()
.content(getString(R.string.delete_type_tip, typeBean.getType(), typeBean.getCount()))
.leftTitle(getString(R.string.cancel))
.rightTitle(getString(R.string.confirm))
.clickListener(new DefaultDialog.OnDialogClickListener() {
@Override
public void clickLeft() {
}
@Override
public void clickRight() {
TypeBeanHelper.getInstance().deleteType(typeBean.getType());
UrlBeanHelper.getInstance().deleteUrlByType(typeBean.getType());
}
})
.build(this)
.show();
}
@Override
protected void onDestroy() {
mDataSubscriptionList.cancel();
super.onDestroy();
}
}
| true |
f10d261f79db2cc7d539744188f25495f20d018e
|
Java
|
MoveCraft/MoveCraft
|
/src/com/sycoprime/movecraft/CraftRotator.java
|
UTF-8
| 19,030 | 2.875 | 3 |
[] |
no_license
|
package com.sycoprime.movecraft;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.util.Vector;
import com.sycoprime.movecraft.events.MoveCraftTurnEvent;
public class CraftRotator {
public Craft craft;
//offset between the craft origin and the pivot for rotation
public CraftRotator(Craft c) {
craft = c;
if(craft.offX == 0 || craft.offZ == 0) {
craft.offX = Math.round(craft.sizeX / 2);
craft.offZ = Math.round(craft.sizeZ / 2);
}
}
// Gathering up pivot data as a Location
// This should be how things are stored in Craft.
public Location getPivot(){
double x = craft.minX + craft.offX;
double z = craft.minZ + craft.offZ;
Location pivot = new Location(craft.world, x, craft.minY, z, craft.rotation, 0);
return pivot;
}
public Vector getCraftSize(){
Vector craftSize = new Vector(craft.sizeX,craft.sizeY,craft.sizeZ);
return craftSize;
}
public boolean canGoThrough(int blockId){
/** if the craft can go through this block id */
//all craft types can move through air
if(blockId == 0) return true;
if(!craft.type.canNavigate && !craft.type.canDive)
return false;
//ship on water
if(blockId == 8 || blockId == 9)
if(craft.waterType == 8) return true;
//ship on lava
if(blockId == 10 || blockId == 11)
if(craft.waterType == 10) return true;
//iceBreaker can go through ice :)
if(blockId == 79 && craft.type.iceBreaker)
if(craft.waterType == 8) return true;
return false;
}
public Location rotate(Entity ent, int r){
return rotate(ent.getLocation(),r,true);
}
public Location rotate(Location point, int r){
return rotate(point,r,false);
}
//will replace other rotates
public Location rotate(Location point, int r, boolean isEntity){
@SuppressWarnings("unused")
Location entOffset;
if (isEntity){
entOffset = new Location(craft.world, 0.5, 0.0, 0.5);
}
else entOffset = new Location(craft.world, 0.0, 0.0, 0.0);
//Location pivot = this.getPivot().add(entOffset);
Location newPoint = point.clone();
//newPoint = point.subtract(pivot);// make point relative to pivot
MoveCraft.instance.DebugMessage("r " + r, 2);
MoveCraft.instance.DebugMessage("newPoint1 " + newPoint, 2);
double x, z;
if(r==90){
x = newPoint.getZ() * -1;
z = newPoint.getX();
}
else if(r==180){
x = newPoint.getX() * -1;
z = newPoint.getZ() * -1;
}
else if(r==270){
x = newPoint.getZ();
z = newPoint.getX() * -1;
}
else{
x = newPoint.getX();
z = newPoint.getZ();
}
newPoint.setX(x);
newPoint.setZ(z);
//return(newPoint.add(pivot));// make newPoint relative to world
return newPoint;
}
public static double rotateX(double x, double z, int r){
if(r==0)
return x;
else if(r==90)
return -z;
else if(r==180)
return -x;
else if(r==270)
return z;
else return x;
}
public static double rotateZ(double x, double z, int r){
/** get the corresponding world z coordinate */
if(r==0)
return z;
else if(r == 90)
return x;
else if(r==180)
return -z;
else if(r==270)
return -x;
else
return z;
}
public static int rotateX(int x, int z, int r){
/** get the corresponding world x coordinate */
MoveCraft.instance.DebugMessage("r is " + r +
", x is " + x +
", z is " + z, 4);
if(r==0)
return x;
else if(r==90)
return -z;
else if(r==180)
return -x;
else if(r==270)
return z;
else return x;
}
public static int rotateZ(int x, int z, int r){
/** get the corresponding world z coordinate */
if(r==0)
return z;
else if(r==90)
return x;
else if(r==180)
return -z;
else if(r==270)
return -x;
else
return z;
}
//setblock, SAFE !
public void setBlock(double id, int X, int Y, int Z) {
if(Y < 0 || Y > 127 || id < 0 || id > 255){
return;
}
if((id == 64 || id == 63) && MoveCraft.instance.DebugMode) {
System.out.println("This stack trace is totally expected.");
//Thread.currentThread().getStackTrace();
//new Throwable().getStackTrace();
new Throwable().printStackTrace();
//Exception ex = new Exception();
//ex.printStackTrace();
}
craft.world.getBlockAt(X, Y, Z).setTypeId((int)id);
}
public void setBlock(double id, int x, int y, int z, int dx, int dy, int dz, int r) {
int X = craft.minX + rotateX(x, z, r) + dx;
int Y = craft.minY + y + dy;
int Z = craft.minZ + rotateZ(x, z, r) + dz;
setBlock(id, X, Y, Z);
}
public void setDataBlock(short id, byte data, int X, int Y, int Z) {
if(Y < 0 || Y > 127 || id < 0 || id > 255){
return;
}
craft.world.getBlockAt(X, Y, Z).setTypeId(id);
craft.world.getBlockAt(X, Y, Z).setData(data);
}
public short getWorldBlockId(int x, int y, int z, int r){
/** get world block id with matrix coordinates and rotation */
short blockId;
blockId = (short) craft.world.getBlockTypeIdAt(craft.minX + rotateX(x - craft.offX, z - craft.offZ, r),
craft.minY + y,
craft.minZ + rotateZ(x - craft.offX, z - craft.offZ, r));
return blockId;
}
public short getCraftBlockId(int x, int y, int z, int r){
int nx = rotateX(x - craft.offX, z - craft.offZ , r) + craft.offX;
int ny = y;
int nz = rotateZ(x - craft.offX, z - craft.offZ, r) + craft.offZ;
if(!(nx >= 0 && nx < craft.sizeX &&
ny >= 0 && ny < craft.sizeY &&
nz >= 0 && nz < craft.sizeZ))
return 255;
return craft.matrix[nx][ny][nz];
}
public boolean canMoveBlocks(int dx, int dy, int dz, int dr){
// Do not like the following :(
World world = craft.world;
//new rotation of the craft
//int newRotation = (craft.rotation + dr + 360) % 360;
int newRotation = (dr + 360) % 360;
//int backRotation = (360 - dr) % 360;
//vertical limit
if(craft.minY + dy < 0 || craft.minY + craft.sizeY + dy > 128){
return false;
}
//watch out for the head !
if(craft.isOnCraft(craft.player, false)){
int px = (int)Math.floor(craft.player.getLocation().getX()) - craft.minX;
int pz = (int)Math.floor(craft.player.getLocation().getZ()) - craft.minZ;
int X = craft.minX + rotateX(px + dx, pz + dz, dr);
int Y = (int)Math.floor(craft.player.getLocation().getY()) + dy;
int Z = craft.minZ + rotateZ(px + dx, pz + dz, dr);
if(world.getBlockTypeIdAt(X, Y, Z) != 0 && world.getBlockTypeIdAt(X, Y + 1, Z) != 0){
craft.player.sendMessage("head check !");
return false;
}
}
for(int x=0;x<craft.sizeX;x++){
for(int z=0;z<craft.sizeZ;z++){
for(int y=0;y<craft.sizeY;y++){
//all blocks new craft.positions needs to have a free space before
if(craft.matrix[x][y][z]!=255){ //before move : craft block
if(getCraftBlockId(x + dx, y + dy, z + dz, dr) == 255){
if(!canGoThrough(getWorldBlockId(x + dx, y + dy, z + dz, newRotation))){
return false;
}
}
}
}
}
}
return true;
}
public void turn(int dr) {
dr = (dr + 360) % 360;
MoveCraftTurnEvent event = new MoveCraftTurnEvent(craft, dr);
MoveCraft.instance.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
dr = event.getDegrees();
ArrayList<Entity> craftEntities = craft.getCraftEntities();
HashMap<Entity, Location> entPreLoc = new HashMap<Entity, Location>();
// determine where entities will be placed
for (Entity e : craftEntities) {
entPreLoc.put(e, rotate(e, dr));
}
Vector moveBy = new Vector(0, 0, 0);
moveBlocks(moveBy, dr);
//tp all players in the craft area
for (Entity e : craftEntities) {
if(e != craft.player)
entPreLoc.get(e).setYaw(entPreLoc.get(e).getYaw() + dr);
MoveCraft.instance.DebugMessage("teleporting " + entPreLoc.get(e), 2);
e.teleport(entPreLoc.get(e));
}
craft.rotation += dr;
if(craft.rotation > 360)
craft.rotation -= 360;
else if(craft.rotation < 0)
craft.rotation = 360 - Math.abs(craft.rotation);
}
public void moveBlocks(Vector moveBy, int dr){
/** move the craft according to a vector d
wdx : world delta x
wdy : world delta y
wdz : world delta z
dr : delta rotation (90, -90) */
//temp bridge-up
/*
int dx = moveBy.getBlockX();
int dy = moveBy.getBlockY();
int dz = moveBy.getBlockZ();
*/
dr = (dr + 360) % 360;
CraftMover cm = new CraftMover(craft);
//rotate dimensions
Vector newSize = this.getCraftSize().clone();
//int newSizeX = craft.sizeX;
//int newSizeZ = craft.sizeZ;
if(dr == 90 ||dr == 270){
newSize.setX(this.getCraftSize().getZ());
newSize.setZ(this.getCraftSize().getX());
//newSizeX = craft.sizeZ;
//newSizeZ = craft.sizeX;
}
//new matrix
//short newMatrix[][][] = new short[newSizeX][craft.sizeY][newSizeZ];
short newMatrix[][][] = new short[newSize.getBlockX()][newSize.getBlockY()][newSize.getBlockZ()];
//store data blocks
cm.storeDataBlocks();
cm.storeComplexBlocks();
ArrayList<DataBlock> unMovedDataBlocks = new ArrayList<DataBlock>();
ArrayList<DataBlock> unMovedComplexBlocks = new ArrayList<DataBlock>();
//for(int i = 0; i < craft.dataBlocks.size(); i ++ ) {
while(craft.dataBlocks.size() > 0) {
unMovedDataBlocks.add(craft.dataBlocks.get(0));
craft.dataBlocks.remove(0);
}
//for(int i = 0; i < craft.complexBlocks.size(); i ++ ) {
while(craft.complexBlocks.size() > 0) {
unMovedComplexBlocks.add(craft.complexBlocks.get(0));
craft.complexBlocks.remove(0);
}
//craft.dataBlocks = new ArrayList<DataBlock>();
//craft.complexBlocks = new ArrayList<DataBlock>();
//rotate matrix
for(int x=0; x < newSize.getBlockX(); x++){
for(int y=0; y < newSize.getBlockY(); y++){
for(int z=0; z < newSize.getBlockZ(); z++){
int newX = 0;
int newZ = 0;
if(dr == 90) {
newX = z;
newZ = newSize.getBlockX() - 1 - x;
} else if(dr == 270){
newX = newSize.getBlockZ() - 1 - z;
newZ = x;
} else {
newX = newSize.getBlockX() - 1 - x;
newZ = newSize.getBlockZ() - 1 - z;
}
newMatrix[x][y][z] = craft.matrix[newX][y][newZ];
for(int i = 0; i < unMovedDataBlocks.size(); i ++ ) {
//while(unMovedDataBlocks.size() > 0) {
DataBlock dataBlock = unMovedDataBlocks.get(i);
if(dataBlock.locationMatches(newX, y, newZ)) {
dataBlock.x = x;
dataBlock.z = z;
craft.dataBlocks.add(dataBlock);
unMovedDataBlocks.remove(i);
break;
}
}
for(int i = 0; i < unMovedComplexBlocks.size(); i ++ ) {
//while(unMovedComplexBlocks.size() > 0) {
DataBlock dataBlock = unMovedComplexBlocks.get(i);
if(dataBlock.locationMatches(newX, y, newZ)) {
dataBlock.x = x;
dataBlock.z = z;
craft.complexBlocks.add(dataBlock);
unMovedComplexBlocks.remove(i);
break;
}
}
}
}
}
int blockId;
Block block;
//remove blocks that need support first
for(int x=0;x<craft.sizeX;x++){
for(int z=0;z<craft.sizeZ;z++){
for(int y=0;y<craft.sizeY;y++){
if(craft.matrix[x][y][z] != -1){
blockId = craft.matrix[x][y][z];
block = craft.world.getBlockAt(craft.minX + x, craft.minY + y, craft.minZ + z);
if(BlocksInfo.needsSupport(blockId)) {
if (blockId == 64 || blockId == 71) { // wooden door and steel door
if (block.getData() >= 8) {
//if(belowBlock.getTypeId() == 64 || belowBlock.getTypeId() == 71) {
continue;
}
}
if(blockId == 26 && block.getData() > 4) { //bed
continue;
//if(block.getData() > 4)
}
setBlock(0, craft.minX + x, craft.minY + y, craft.minZ + z);
}
}
}
}
}
//remove all the current blocks
for(int x=0;x<craft.sizeX;x++){
for(int y=0;y<craft.sizeY;y++){
for(int z=0;z<craft.sizeZ;z++){
//int blockId = craft.matrix[x][y][z];
/**
Added to attempt to resolve water issues...
*/
/*
// old block postion (remove)
if (x - dx >= 0 && y - dy >= 0 && z - dz >= 0
&& x - dx < craft.sizeX && y - dy < craft.sizeY
&& z - dz < craft.sizeZ) {
// after moving, this location is not a craft block
// anymore
if (craft.matrix[x - dx][y - dy][z - dz] == -1
|| BlocksInfo.needsSupport(craft.matrix[x - dx][y - dy][z - dz])) {
if (y > craft.waterLevel || !(craft.type.canNavigate || craft.type.canDive)) {
//|| matrix [ x - dx ] [ y - dy ] [ z - dz ] == 0)
setBlock(0, x, y, z);
}
else
setBlock(craft.waterType, x, y, z);
}
// the back of the craft, remove
} else {
*/
if (y > craft.waterLevel
|| !(craft.type.canNavigate || craft.type.canDive))
setBlock(0, craft.minX + x, craft.minY + y, craft.minZ + z);
else
setBlock(craft.waterType, craft.minX + x, craft.minY + y, craft.minZ + z);
//}
/*
if(blockId != -1 && !BlocksInfo.needsSupport(blockId))
setBlock(0, craft.minX + x, craft.minY + y, craft.minZ + z);
//if(craft.matrix[x][y][z] != -1){
//}
*/
}
}
}
craft.matrix = newMatrix;
craft.sizeX = newSize.getBlockX();
craft.sizeZ = newSize.getBlockZ();
//craft pivot
int posX = craft.minX + craft.offX;
int posZ = craft.minZ + craft.offZ;
MoveCraft.instance.DebugMessage("Min vals start " + craft.minX + ", " + craft.minZ, 2);
MoveCraft.instance.DebugMessage("Off was " + craft.offX + ", " + craft.offZ, 2);
//rotate offset
//int newoffX = rotateX(craft.craft.offX, craft.craft.offZ, -dr % 360);
//int newoffZ = rotateZ(craft.craft.offX, craft.craft.offZ, -dr % 360);
int newoffX = rotateX(craft.offX, craft.offZ, dr);
int newoffZ = rotateZ(craft.offX, craft.offZ, dr);
MoveCraft.instance.DebugMessage("New off is " + newoffX + ", " + newoffZ, 2);
if(newoffX < 0)
newoffX = newSize.getBlockX() - 1 - Math.abs(newoffX);
if(newoffZ < 0)
newoffZ = newSize.getBlockZ() - 1 - Math.abs(newoffZ);
craft.offX = newoffX;
craft.offZ = newoffZ;
MoveCraft.instance.DebugMessage("Off is " + craft.offX + ", " + craft.offZ, 2);
//update min/max
craft.minX = posX - craft.offX;
craft.minZ = posZ - craft.offZ;
craft.maxX = craft.minX + craft.sizeX -1;
craft.maxZ = craft.minZ + craft.sizeZ -1;
MoveCraft.instance.DebugMessage("Min vals end " + craft.minX + ", " + craft.minZ, 2);
rotateCardinals(craft.dataBlocks, dr);
rotateCardinals(craft.complexBlocks, dr);
//put craft back
for(int x = 0; x < getCraftSize().getX(); x++){
for(int y = 0; y < getCraftSize().getY(); y++){
for(int z = 0; z < getCraftSize().getZ(); z++){
blockId = newMatrix[x][y][z];
if(blockId != -1
&& !BlocksInfo.needsSupport(blockId))
setBlock(blockId, craft.minX + x, craft.minY + y, craft.minZ + z);
}
}
}
//blocks that need support, but are not data blocks
for(int x = 0; x < getCraftSize().getX(); x++){
for(int y = 0; y < getCraftSize().getY(); y++){
for(int z = 0; z < getCraftSize().getZ(); z++){
blockId = newMatrix[x][y][z];
if (BlocksInfo.needsSupport(blockId)
&& !BlocksInfo.isDataBlock(blockId)) {
setBlock(blockId, craft.minX + x, craft.minY + y, craft.minZ + z);
}
}
}
}
cm.restoreDataBlocks(0, 0, 0);
cm.restoreComplexBlocks(0, 0, 0);
}
public void rotateCardinals(ArrayList<DataBlock> blocksToRotate, int dr) {
//http://www.minecraftwiki.net/wiki/Data_values
//and beds
byte[] cardinals;
int blockId;
for(DataBlock dataBlock: blocksToRotate) {
//Block theBlock = craft.getWorldBlock(dataBlock.x, dataBlock.y, dataBlock.z);
blockId = dataBlock.id;
//torches, skip 'em if they're centered on the tile on the ground
if(blockId == 50 || blockId == 75 || blockId == 76) {
if(dataBlock.data == 5)
continue;
}
if(BlocksInfo.getCardinals(blockId) != null)
cardinals = Arrays.copyOf(BlocksInfo.getCardinals(blockId), 4);
else
cardinals = null;
if(blockId == 63) { //sign post
dataBlock.data = (dataBlock.data + 4) % 16;
//dataBlock.data = dataBlock.data + 4;
//if(dataBlock.data > 14) dataBlock.data -= 16;
continue;
}
if(blockId == 26) { //bed
if(dataBlock.data > 8) {
for(int c = 0; c < 4; c++)
cardinals[c] += 8;
}
}
if(blockId == 64 || blockId == 71 //wooden or steel door
|| blockId == 93 || blockId == 94) { //repeater
if(dataBlock.data > 11) { //if the door is an open top
for(int c = 0; c < 4; c++)
cardinals[c] += 11;
} else if (dataBlock.data > 8) { //if the door is a top
for(int c = 0; c < 4; c++)
cardinals[c] += 8;
} else if (dataBlock.data > 4) { //not a top, but open
for(int c = 0; c < 4; c++)
cardinals[c] += 4;
}
}
if (blockId == 66 ) { // rails
if(dataBlock.data == 0) {
dataBlock.data = 1;
continue;
}
if(dataBlock.data == 1) {
dataBlock.data = 0;
continue;
}
}
if(blockId == 69) { //lever
if(dataBlock.data == 5 || dataBlock.data == 6 || //if it's on the floor
dataBlock.data == 13 || dataBlock.data == 14) {
cardinals = new byte[]{6, 5, 14, 13};
}
else if(dataBlock.data > 4) { //switched on
for(int c = 0; c < 4; c++) {
cardinals[c] += 8;
}
}
}
if(blockId == 93 || blockId == 94) { //repeater
if(dataBlock.data > 11) {
for(int c = 0; c < 4; c++)
cardinals[c] += 12;
}
else if(dataBlock.data > 7) {
for(int c = 0; c < 4; c++)
cardinals[c] += 8;
}
else if(dataBlock.data > 3) {
for(int c = 0; c < 4; c++)
cardinals[c] += 4;
}
}
if(cardinals != null) {
MoveCraft.instance.DebugMessage(Material.getMaterial(blockId) +
" Cardinals are "
+ cardinals[0] + ", "
+ cardinals[1] + ", "
+ cardinals[2] + ", "
+ cardinals[3], 2);
int i = 0;
for(i = 0; i < 3; i++)
if(dataBlock.data == cardinals[i])
break;
MoveCraft.instance.DebugMessage("i starts as " + i + " which is " + cardinals[i], 2);
i += (dr / 90);
if(i > 3)
i = i - 4;
MoveCraft.instance.DebugMessage("i ends as " + i + ", which is " + cardinals[i], 2);
dataBlock.data = cardinals[i];
}
}
}
}
| true |
cec54f0e9841fb5eeecc13deb69d7d731b96dca5
|
Java
|
kimyen/Synapse-Repository-Services
|
/lib/models/src/main/java/org/sagebionetworks/repo/model/ProjectSettingsDAO.java
|
UTF-8
| 1,177 | 2.140625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.sagebionetworks.repo.model;
import java.util.List;
import org.sagebionetworks.repo.model.project.ProjectSetting;
import org.sagebionetworks.repo.model.project.ProjectSettingsType;
import org.sagebionetworks.repo.web.NotFoundException;
public interface ProjectSettingsDAO {
public String create(ProjectSetting settings) throws DatastoreException, InvalidModelException;
public ProjectSetting get(String id) throws DatastoreException, NotFoundException;
public ProjectSetting get(String projectId, ProjectSettingsType projectSettingsType) throws DatastoreException;
public ProjectSetting get(List<Long> parentIds, ProjectSettingsType projectSettingsType) throws DatastoreException;
public List<ProjectSetting> getAllForProject(String projectId) throws DatastoreException, NotFoundException;
public List<ProjectSetting> getByType(ProjectSettingsType projectSettingsType) throws DatastoreException, NotFoundException;
public ProjectSetting update(ProjectSetting settings) throws DatastoreException, InvalidModelException, NotFoundException,
ConflictingUpdateException;
public void delete(String id) throws DatastoreException, NotFoundException;
}
| true |
e9a26298ceaf56eecbddb92f3df75f69be0ab6b0
|
Java
|
AndreiF05/Probleme
|
/app/src/main/java/com/example/andrei/nrprime/DisplayResult.java
|
UTF-8
| 1,592 | 2.671875 | 3 |
[] |
no_license
|
package com.example.andrei.nrprime;
import android.content.Intent;
import android.graphics.Color;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class DisplayResult extends AppCompatActivity {
public String message;
public TextView result;
public ConstraintLayout current;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_result);
result = findViewById(R.id.result);
Intent intent = getIntent();
message = intent.getStringExtra("mesaj");
TextView number = findViewById(R.id.textView);
number.setText(message);
current = findViewById(R.id.the_layout);
prime();
}
public void prime(){
double nr = Double.parseDouble(message);
int nri = (int)nr;
boolean prime = true;
for (int i = 2; i * i <= nr; i++) {
if (nr % i == 0 ) {
prime = false;
break;
}
}
if(nr!=nri)prime=false;
if(nr<0)prime=false;
if(prime){
this.result.setText("nr prim");
current.setBackgroundColor(Color.parseColor("#59ff74"));
}
else{
this.result.setText("nu e nr prim");
current.setBackgroundColor(Color.parseColor("#e01600"));
}
}
}
| true |
8263b2bcc007f96e4055013212448a63bb749d5b
|
Java
|
oreon/sfcode-full
|
/trunk1/src/aero/sita/ads/framework/apis2/AbstractAPISInfoComponent.java
|
UTF-8
| 572 | 2.3125 | 2 |
[] |
no_license
|
package aero.sita.ads.framework.apis2;
import java.util.HashMap;
import java.util.Map;
/**
* This is an abstract implentation of APISInfoComponent to facilitate management of collection
* of missing fields
*
* @author jsingh
* //Little Proof from Colombia. Jhonny
*/
public abstract class AbstractAPISInfoComponent implements APISInfoComponent {
private Map missingFields = new HashMap();
public void addMissingField(String field) {
missingFields.put(field, "");
}
public Map getMissingFields() {
return missingFields;
}
}
| true |
714009d81eee44ad538042339b5043587844fbe1
|
Java
|
ealon2/dds
|
/src/main/java/qmp/repository/RepositorioDeGuardarropas.java
|
UTF-8
| 729 | 2.09375 | 2 |
[] |
no_license
|
package qmp.repository;
import org.uqbarproject.jpa.java8.extras.WithGlobalEntityManager;
import qmp.model.Guardarropas;
import java.util.List;
public class RepositorioDeGuardarropas implements WithGlobalEntityManager {
private final static RepositorioDeGuardarropas INSTANCE = new RepositorioDeGuardarropas();
private RepositorioDeGuardarropas() {
}
public static RepositorioDeGuardarropas instance() {
return INSTANCE;
}
public void agregarGuardarropa(Guardarropas guardarropas) {
entityManager().persist(guardarropas);
}
public List<Guardarropas> obtenerGuardarropa() {
return entityManager()
.createQuery("from Guardarropas", Guardarropas.class)
.getResultList();
}
}
| true |
e3b1f65707b56a5783c3289f8e47a0f5a1106180
|
Java
|
lucasperalta/adopta.me
|
/app/src/main/java/tpfinal/davinci/adoptame/ListarMisMascotasActivity.java
|
UTF-8
| 4,508 | 1.890625 | 2 |
[] |
no_license
|
package tpfinal.davinci.adoptame;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.LoginFilter;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import tpfinal.davinci.adoptame.api.AdoptameAPI;
import tpfinal.davinci.adoptame.model.Mascota;
public class ListarMisMascotasActivity extends AppCompatActivity {
MisMascotasAdapter misMascotasAdapter;
ListView misMascotasLv;
private SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fresco.initialize(this);
setContentView(R.layout.mis_mascotas_lv);
/*
List<Mascota> mascotas= new ArrayList<>();
Mascota mascota= new Mascota();
mascota.setNombre("pirulo");
mascota.setRaza("mestizo");
mascota.setEdad(12);
mascotas.add(mascota);
mascotas.add(mascota);
mascotas.add(mascota);
mascotas.add(mascota);
mascotas.add(mascota);
mascotas.add(mascota);
mascotas.add(mascota);
mascotas.add(mascota);
mascotas.add(mascota);
*/
misMascotasAdapter= new MisMascotasAdapter(getBaseContext());
misMascotasLv = (ListView) findViewById(R.id.misMascota_lv);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(AdoptameAPI.END_POINT_URL)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
AdoptameAPI client = retrofit.create(AdoptameAPI.class);
Call<List<Mascota>> call = client.getMascotasAgregadas("1");
call.enqueue(new Callback<List<Mascota>>() {
@Override
public void onResponse(Call<List<Mascota>> call, Response<List<Mascota>> response) {
List<Mascota> mascotas = response.body();
misMascotasAdapter.setMisMascotas(mascotas);
misMascotasLv.setAdapter(misMascotasAdapter);
}
@Override
public void onFailure(Call<List<Mascota>> call, Throwable t) {
Toast.makeText(ListarMisMascotasActivity.this, "error :(", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// action with ID action_refresh was selected
case R.id.actionFiltros:
Intent filtros = new Intent(this, FiltrosActivity.class);
startActivity(filtros);
break;
// action with ID action_settings was selected
case R.id.actionMisMascotas:
Toast.makeText(this, "Ya estas en Mis Mascotas", Toast.LENGTH_SHORT)
.show();
break;
case R.id.actionLogout:
//persistencia resuelta con SharedPreferences
sharedPreferences = this.getSharedPreferences(getResources().getString(R.string.app_name), MODE_PRIVATE);
//Guardo asincronicamente las credenciales de logueo
sharedPreferences.edit()
.putString("usuario", "")
.putString("password", "")
.apply(); Intent login = new Intent(this, MainActivity.class);
startActivity(login);
finish();
break;
case R.id.actionAgregarMascotas:
Intent agregarMascotas = new Intent(this, AgregarMascotaActivity.class);
startActivity(agregarMascotas);
break;
default:
break;
}
return true;
}
}
| true |
303a98dc97049fe3cc1fe37d51f169d8c35b7515
|
Java
|
M1c17/UBCx-Software-Construction-Data-Abstraction-SoftConst1x
|
/W1-Introduction-to-Software-Construction/Software-Construction/long-form-problem-starters-master/Instrument Project/src/model/Saxophone.java
|
UTF-8
| 205 | 2.046875 | 2 |
[] |
no_license
|
package model;
import ui.Orchestra;
public class Saxophone extends BrassInstrument {
public Saxophone(Orchestra orchestra, String musician, String type) {
super(orchestra, musician, type);
}
}
| true |
75d17fba05bbef319770125da22ab1107eb0e380
|
Java
|
umangd98/ElgamalJavaSocketProgram
|
/MyClient.java
|
UTF-8
| 1,624 | 2.71875 | 3 |
[] |
no_license
|
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
ObjectOutputStream outputStream = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream inStream = new ObjectInputStream(s.getInputStream());
Elgamal receivedScheme = (Elgamal)inStream.readObject();
System.out.println("Received Scheme " + receivedScheme.params.nb_bits);
Elgamal_KeySet kset = receivedScheme.KeyGen();
System.out.println("Secret Key: " );
System.out.println("P: " + kset.skey.p);
System.out.println("d: " + kset.skey.x);
outputStream.writeObject(kset.pkey);
Elgamal_CipherText receivedCText = (Elgamal_CipherText)inStream.readObject();
System.out.println("C Text: ");
System.out.println("C1: " + receivedCText.c1);
System.out.println("C2: " + receivedCText.c2);
Elgamal_PlainText plain2 = receivedScheme.Decrypt(receivedCText, kset.skey);
System.out.println("Decryption...");
System.out.println("Plain text: " + plain2.m);
System.out.println("Plain text in char: ");
String output = plain2.m.toString();
// System.out.println("Plain text: " + output);
if(output.length()%3!=0){
String ascii = output.substring(0,2);
int ascii_int = Integer.parseInt(ascii);
System.out.print((char)ascii_int);
output = output.substring(2,output.length());
}
for(int i=0;i<output.length()-2;i+=3){
String ascii = output.substring(i,i+3);
int ascii_int = Integer.parseInt(ascii);
// System.out.print(ascii_int);
System.out.print((char)ascii_int);
}
System.out.println();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
| true |
88ccd72471d241c9affa86776d37647202c9421e
|
Java
|
Maxtomb/SalesforceToolkit_Runtime
|
/src/test/java/com/maxtomb/com/maxtomb/salesforce/tool/SalesforceSchronizerTool.java
|
UTF-8
| 9,062 | 2.390625 | 2 |
[] |
no_license
|
package com.maxtomb.com.maxtomb.salesforce.tool;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.maxtomb.salesforce.tool.client.HttpClient;
import com.sforce.soap.enterprise.Connector;
import com.sforce.soap.enterprise.DeleteResult;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.Error;
import com.sforce.soap.enterprise.QueryResult;
import com.sforce.soap.enterprise.SaveResult;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.Contact;
import com.sforce.soap.enterprise.sobject.SObject;
import com.sforce.ws.ConnectorConfig;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class SalesforceSchronizerTool {
static final String USERNAME = "[email protected]";
static final String PASSWORD = "xiaohei@0jSixZaFJ5NfJk6XQeWGF8QZ6";
static EnterpriseConnection connection;
public static void main(String[] args) {
ConnectorConfig config = new ConnectorConfig();
config.setUsername(USERNAME);
config.setPassword(PASSWORD);
// config.setTraceMessage(true);
try {
connection = Connector.newConnection(config);
System.out.println("Auth EndPoint: " + config.getAuthEndpoint());
System.out.println("Service EndPoint: " + config.getServiceEndpoint());
System.out.println("Username: " + config.getUsername());
System.out.println("SessionId: " + config.getSessionId());
//定义一个map 管理所有得sobject name 和 记录数
Map<String,List<Map<Object,Object>>> resultDataMap = new HashMap<String,List<Map<Object,Object>>>();
//发http请求 获取json 数据
String jsonDataString = HttpClient.getJsonData();
JSONObject jobj = JSONObject.fromObject(jsonDataString);
Object[] nameSet = jobj.keySet().toArray();
for(int i=0;i<nameSet.length;i++){
//一个map代表一条记录,所有的记录添加到一个list中去
List<Map<Object,Object>> recordList = new ArrayList<Map<Object,Object>>();
System.out.println(nameSet[i]);
JSONArray jobjArr = jobj.getJSONArray(nameSet[i].toString());
//这个it是遍历某一个表里的所有的record
Iterator<JSONObject> it = jobjArr.iterator();
while(it.hasNext()){
//创建一个map管理所有的字段和值
Map<Object,Object> fieldMap = new HashMap<Object,Object>();
JSONObject jsonObj = it.next();
Iterator entryIt = jsonObj.entrySet().iterator();
while(entryIt.hasNext()){
Map.Entry entry = (Map.Entry) entryIt.next();
//遍历所有的字段和值 并添加到管理map 中去
fieldMap.put(entry.getKey(),entry.getValue());
}
//将每条记录的map 存入管理list中去
recordList.add(fieldMap);
}
resultDataMap.put(nameSet[i].toString(), recordList);
}
//Map的key 存的是 table 的名字 也就是sobject 的名字
//Map的value 存的是 记录列表
Iterator iter = resultDataMap.entrySet().iterator();
while(iter.hasNext()){
Map.Entry<String, List<Map<Object,Object>>> entry = (Entry<String, List<Map<Object, Object>>>) iter.next();
createSObject(entry.getKey().toString(),entry.getValue());
}
// createSObject();
// updateAccounts();
// deleteAccounts();
} catch (Exception e1) {
e1.printStackTrace();
}
}
// queries and displays the 5 newest contacts
private static void queryContacts() {
try {
// query for the 5 newest contacts
QueryResult queryResults = connection.query("SELECT Id, FirstName, LastName, Account.Name "
+ "FROM Contact WHERE AccountId != NULL ORDER BY CreatedDate DESC LIMIT 5");
if (queryResults.getSize() > 0) {
for (int i = 0; i < queryResults.getRecords().length; i++) {
// cast the SObject to a strongly-typed Contact
Contact c = (Contact) queryResults.getRecords()[i];
System.out.println("Id: " + c.getId() + " - Name: " + c.getFirstName() + " " + c.getLastName()
+ " - Account: " + c.getAccount().getName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static SObject setupSObject(Class<?> sobj, SObject instance,Map<Object, Object> fieldNameAndValueMap)
throws Exception {
for (Entry<Object, Object> fieldNameAndValue : fieldNameAndValueMap.entrySet()) {
Method m = sobj.getMethod("set" + fieldNameAndValue.getKey(), String.class);
m.invoke(instance, fieldNameAndValue.getValue());
}
return instance;
}
private static void createSObject(String sObjectName, List<Map<Object, Object>> recordsList) throws Exception {
String classNamePrefix = "com.sforce.soap.enterprise.sobject.";
String classFullName = classNamePrefix + sObjectName;
System.out.println("去找class:"+classFullName);
Class<?> sobj = Class.forName(classFullName);
List<SObject> records = new ArrayList<SObject>();
for (Map<Object, Object> recordFieldNameAndValueMap : recordsList) {
SObject sobjInstance = (SObject) sobj.newInstance();
SObject sobject = setupSObject(sobj,sobjInstance, recordFieldNameAndValueMap);
records.add(sobject);
}
SObject[] recordsArray = (SObject[]) records.toArray(new SObject[records.size()]);
SaveResult[] saveResults = connection.create(recordsArray);
for (int j = 0; j < saveResults.length; j++) {
if (saveResults[j].isSuccess()) {
System.out.println(j + ". Successfully created record - Id: " + saveResults[j].getId());
} else {
Error[] errors = saveResults[j].getErrors();
for (int x = 0; x < errors.length; x++) {
System.out.println("ERROR creating record: " + errors[x].getMessage());
}
}
}
}
private static void createSObject(String sObjectName) throws Exception {
Map<Object, Object> valueMap1 = new HashMap<Object, Object>();
valueMap1.put("Name", "测试ccc");
valueMap1.put("TestGreeting__cloth_style__c", "测试款式ccc");
valueMap1.put("TestGreeting__cloth_color__c", "测试颜色ccc");
Map<Object, Object> valueMap2 = new HashMap<Object, Object>();
valueMap2.put("Name", "测试ddd");
valueMap2.put("TestGreeting__cloth_style__c", "测试款式ddd");
valueMap2.put("TestGreeting__cloth_color__c", "测试颜色ddd");
List<Map<Object, Object>> recordsList = new ArrayList<Map<Object, Object>>();
recordsList.add(valueMap1);
recordsList.add(valueMap2);
createSObject(sObjectName, recordsList);
}
// updates the 5 newly created Accounts
private static void updateAccounts() {
System.out.println("Update the 5 new test Accounts...");
Account[] records = new Account[5];
try {
QueryResult queryResults = connection
.query("SELECT Id, Name FROM Account ORDER BY " + "CreatedDate DESC LIMIT 5");
if (queryResults.getSize() > 0) {
for (int i = 0; i < queryResults.getRecords().length; i++) {
// cast the SObject to a strongly-typed Account
Account a = (Account) queryResults.getRecords()[i];
System.out.println("Updating Id: " + a.getId() + " - Name: " + a.getName());
// modify the name of the Account
a.setName(a.getName() + " -- UPDATED");
records[i] = a;
}
}
// update the records in Salesforce.com
SaveResult[] saveResults = connection.update(records);
// check the returned results for any errors
for (int i = 0; i < saveResults.length; i++) {
if (saveResults[i].isSuccess()) {
System.out.println(i + ". Successfully updated record - Id: " + saveResults[i].getId());
} else {
Error[] errors = saveResults[i].getErrors();
for (int j = 0; j < errors.length; j++) {
System.out.println("ERROR updating record: " + errors[j].getMessage());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// delete the 5 newly created Account
private static void deleteAccounts() {
System.out.println("Deleting the 5 new test Accounts...");
String[] ids = new String[5];
try {
QueryResult queryResults = connection
.query("SELECT Id, Name FROM Account ORDER BY " + "CreatedDate DESC LIMIT 5");
if (queryResults.getSize() > 0) {
for (int i = 0; i < queryResults.getRecords().length; i++) {
// cast the SObject to a strongly-typed Account
Account a = (Account) queryResults.getRecords()[i];
// add the Account Id to the array to be deleted
ids[i] = a.getId();
System.out.println("Deleting Id: " + a.getId() + " - Name: " + a.getName());
}
}
// delete the records in Salesforce.com by passing an array of Ids
DeleteResult[] deleteResults = connection.delete(ids);
// check the results for any errors
for (int i = 0; i < deleteResults.length; i++) {
if (deleteResults[i].isSuccess()) {
System.out.println(i + ". Successfully deleted record - Id: " + deleteResults[i].getId());
} else {
Error[] errors = deleteResults[i].getErrors();
for (int j = 0; j < errors.length; j++) {
System.out.println("ERROR deleting record: " + errors[j].getMessage());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
923e0a3228a31cbbab6f4c52592ebdb3b436ac16
|
Java
|
dtytomi/Java
|
/IOThreadTest.java
|
UTF-8
| 450 | 3.4375 | 3 |
[] |
no_license
|
import java.lang.Thread;
public class IOThreadTest {
public static void main(String[] args) {
Thread t1 = Thread.currentThread();
System.out.println(t1.getName() + " started.");
Thread t2 = new IOThread(); // create the IO thread
t2.start();
System.out.println(t1.getName() + " starts " + t2.getName() + ".");
System.out.println(t1.getName() + " finished.");
}
}
| true |
4c1a59eeac4a4e0e32ccb353d02dff73ff21d4b9
|
Java
|
Jumbo-WJB/projectreport
|
/projectreport-modules/projectreport-commons/src/main/java/cn/damai/boss/projectreport/commons/ApplicationException.java
|
UTF-8
| 501 | 2.515625 | 3 |
[] |
no_license
|
package cn.damai.boss.projectreport.commons;
/**
* service抛出此异常,action层进行捕获,然后转化为错误码传给客户端
* @author Administrator
*
*/
public class ApplicationException extends Exception{
private static final long serialVersionUID = -8371603883986887174L;
private int errorCode;
public ApplicationException(int errorCode,String errorMessage) {
super(errorMessage);
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
}
| true |
891f064f4ec91e77f807eeac0be17615cefe96de
|
Java
|
cha63506/taverna-svn
|
/taverna/ui/net.sf.taverna.t2.ui-impl/branches/ui-impl-1.3/file-impl/src/main/java/net/sf/taverna/t2/workbench/file/impl/DataflowFromDataflowPersistenceHandler.java
|
UTF-8
| 2,069 | 2.078125 | 2 |
[] |
no_license
|
/**
*
*/
package net.sf.taverna.t2.workbench.file.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import net.sf.taverna.t2.workbench.file.DataflowInfo;
import net.sf.taverna.t2.workbench.file.FileType;
import net.sf.taverna.t2.workbench.file.exceptions.OpenException;
import net.sf.taverna.t2.workbench.file.exceptions.SaveException;
import net.sf.taverna.t2.workflowmodel.Dataflow;
import net.sf.taverna.t2.workbench.file.impl.FileDataflowInfo;
import net.sf.taverna.t2.workbench.file.impl.T2DataflowOpener;
import net.sf.taverna.t2.workbench.file.impl.T2FlowFileType;
import net.sf.taverna.t2.workbench.file.DataflowPersistenceHandler;
import net.sf.taverna.t2.workbench.file.AbstractDataflowPersistenceHandler;
/**
* @author alanrw
*
*/
public class DataflowFromDataflowPersistenceHandler extends AbstractDataflowPersistenceHandler implements DataflowPersistenceHandler {
private static final T2FlowFileType T2_FLOW_FILE_TYPE = new T2FlowFileType();
private static Logger logger = Logger.getLogger(DataflowFromDataflowPersistenceHandler.class);
@Override
public DataflowInfo openDataflow(FileType fileType, Object source)
throws OpenException {
if (!getOpenFileTypes().contains(fileType)) {
throw new IllegalArgumentException("Unsupported file type "
+ fileType);
}
Dataflow d = (Dataflow) source;
Date lastModified = null;
Object canonicalSource = null;
return new DataflowInfo(T2_FLOW_FILE_TYPE, canonicalSource, d,
lastModified);
}
@Override
public List<FileType> getOpenFileTypes() {
return Arrays.<FileType> asList(T2_FLOW_FILE_TYPE);
}
@Override
public List<Class<?>> getOpenSourceTypes() {
return Arrays.<Class<?>> asList(Dataflow.class);
}
}
| true |
06f923338c78418324232ca2d008b8fe6adefbbc
|
Java
|
ThieffryElisabeth1B2/Web2
|
/src/net/web2/Monstre.java
|
ISO-8859-2
| 836 | 2.53125 | 3 |
[] |
no_license
|
package net.web2;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
public class Monstre {
Chemin chemin;
Bitmap bitmap;
float dDD; // distance Depuis Dbut
float vx=1; // vitesse
float position;
TileView grille;
Paint paint;
Wave wave;
float x;
float y;
public Monstre(Bitmap bitmap, float position, Wave wave){
this.bitmap = bitmap;
this.x = x;
this.y = y;
this.wave = wave;
paint = new Paint();
}
private int getXposition(){
x = chemin.getX(position);
return (int) x;
}
private int getYposition(){
y = chemin.getY(position);
return (int) y;
}
private void move(){
position = position + 1; // ou ++position
}
public void draw(Canvas canvas) {
canvas.drawBitmap(bitmap, x, y, paint);
}
}
| true |
f0a818f2a36005259eb8c9be814094cf971e5738
|
Java
|
DanRutz/pravega
|
/controller/src/main/java/io/pravega/controller/fault/ControllerClusterListenerConfig.java
|
UTF-8
| 1,638 | 2.3125 | 2 |
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright (c) 2017 Dell Inc., or its subsidiaries. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
package io.pravega.controller.fault;
import java.util.concurrent.TimeUnit;
/**
* Controller cluster configuration. This includes configuration parameters for
* the cluster listener's thread pool, including minimum and maximum thread pool
* size, maximum idle time and max queue size.
*/
public interface ControllerClusterListenerConfig {
/**
* Fetches the minimum number of threads in the cluster listener executor.
*
* @return The minimum number of threads in the cluster listener executor.
*/
int getMinThreads();
/**
* Fetches the maximum number of threads in the cluster listener executor.
*
* @return The maximum number of threads in the cluster listener executor.
*/
int getMaxThreads();
/**
* Fetches the maximum idle time for threads in the cluster listener executor.
*
* @return the maximum idle time for threads in the cluster listener executor.
*/
int getIdleTime();
/**
* Fetches the timeunit of idleTime parameter.
*
* @return The timeunit of idleTime parameter.
*/
TimeUnit getIdleTimeUnit();
/**
* Fetches the maximum size of cluster listener executor's queue.
*
* @return The maximum size of cluster listener executor's queue.
*/
int getMaxQueueSize();
}
| true |
3aeba7f579ad0779eadede8e9bc3c3b38f83d51e
|
Java
|
areume/Kitri_Java_Basic
|
/pro04/src/io06/Quiz/IO/Quiz26.java
|
UTF-8
| 1,029 | 3.390625 | 3 |
[] |
no_license
|
package io06.Quiz.IO;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Quiz26 {
public static void main(String[] args) {
File file=null;
FileWriter fw=null;
BufferedWriter bw=null;
Scanner sc=null;
try {
file=new File("C:\\areum\\java\\fileUpDown\\output\\quiz26_test.txt");
fw=new FileWriter(file);
bw=new BufferedWriter(fw,1024);
sc=new Scanner(System.in);
System.out.println("데이터를 입력해주세요. (종료:Q)");
while(true) {
String str=sc.nextLine();
if(str.equalsIgnoreCase("Q")) {
break;
}
bw.write(str+"\n");
System.out.println("종료되었습니다.");
}
bw.flush();
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if (sc != null) sc.close();
if (bw != null) bw.close();
if (fw != null) fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| true |
5b43ca456611cf854403dba655b3c01a2e12eaf6
|
Java
|
Multivacker/WebAbitatDev
|
/src/main/java/com/javamaster/dao/ArticleDao.java
|
UTF-8
| 302 | 1.90625 | 2 |
[] |
no_license
|
package com.javamaster.dao;
import java.util.List;
import com.javamaster.entity.Article;
public interface ArticleDao {
int createArticle(Article article);
int editArticle(Article article);
void deleteArticle(int id);
Article getArticleById(int id);
List<Article> getAllArticles();
}
| true |
0136da3943c62edf18af7c900dcf4145a107a168
|
Java
|
rvz420/prog3Vazquez2018
|
/tp1/ej3/Pila.java
|
UTF-8
| 480 | 2.75 | 3 |
[] |
no_license
|
package ej3;
import ej1.SimpleLinkedList;
public class Pila {
SimpleLinkedList elements;
public Pila (){
elements = new SimpleLinkedList();
}
public void apilar(Object elem){
elements.insertFirst(elem);
}
public Object desapilar(){
return elements.extractFirst();
}
public boolean esVacia(){
return elements.isEmpty();
}
public Object verTope(){
if(!elements.isEmpty()){
return elements.getNode(0).getdata();
}else{
return null;
}
}
}
| true |
5e26c9bc27d6a99a1662818e57d810b8e4efc6fd
|
Java
|
ChueiZuoChen/JavaFxPractice
|
/src/ComboBox/ComboBox.java
|
UTF-8
| 1,472 | 3.25 | 3 |
[] |
no_license
|
package ComboBox;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ComboBox extends Application {
private Stage window;
private VBox layout;
private Scene scene;
private Button button;
private javafx.scene.control.ComboBox<String> comboBox;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
window.setTitle("ComboBox");
button = new Button("Click me");
//ComboBox
comboBox = new javafx.scene.control.ComboBox<>();
comboBox.getItems().addAll(
"Good",
"SC",
"A"
);
comboBox.setPromptText("What is your favorite :");
button.setOnAction(event -> printMovie());
comboBox.setOnAction(event ->
System.out.println("User selected: " + comboBox.getValue()));
comboBox.setEditable(true);
layout = new VBox();
layout.getChildren().addAll(comboBox,button);
layout.setPadding(new Insets(20,20,20,20));
scene = new Scene(layout,300,250);
window.setScene(scene);
window.show();
}
private void printMovie() {
System.out.println(this.comboBox.getValue());
}
}
| true |
d7a57e58cc6123e8ab663e752c7ed2e14fb6bbfb
|
Java
|
shaosen11/project-managment
|
/src/main/java/cn/edu/lingnan/projectmanagment/mapper/ProjectsMessageTypeMapper.java
|
UTF-8
| 487 | 1.820313 | 2 |
[] |
no_license
|
package cn.edu.lingnan.projectmanagment.mapper;
import cn.edu.lingnan.projectmanagment.bean.ProjectsMessageType;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
/**
* @Author shaosen
* @Description //TODO
* @Date 18:54 2020/4/17
*/
@Mapper
@Repository
public interface ProjectsMessageTypeMapper {
/**
* 通过消息码得到消息类型
* @param id
* @return
*/
ProjectsMessageType getById(Integer id);
}
| true |
bdbc03640c7e4f7e863d14536bd6b33a41f8d8d8
|
Java
|
WuQuDeRen/learn_all
|
/concurrent/src/main/java/com/learn/concurrent/communication/PrintSequence3.java
|
UTF-8
| 3,633 | 3.265625 | 3 |
[] |
no_license
|
package com.learn.concurrent.communication;
import lombok.Data;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@Data
class Task {
private static Lock lock = new ReentrantLock();
private static Condition file1Con = lock.newCondition();
private static Condition file2Con = lock.newCondition();
private static Condition file3Con = lock.newCondition();
private static Condition file4Con = lock.newCondition();
private int flag;
private String path;
public Task(String path, int flag) {
this.flag = flag;
this.path = path;
}
public void print(String value) throws IOException {
FileWriter writer = new FileWriter(path, true);
writer.write(value);
writer.flush();
writer.close();
}
public void printFile1() {
lock.lock();
try {
while (flag != 1) {
file1Con.await();
}
flag = 2;
print("1");
file2Con.signal();
} catch(Exception e) {
} finally {
lock.unlock();
}
}
public void printFile2() {
lock.lock();
try {
while (flag != 2) {
file2Con.await();
}
flag = 3;
print("2");
file3Con.signal();
} catch(Exception e) {
} finally {
lock.unlock();
}
}
public void printFile3() {
lock.lock();
try {
while (flag != 3) {
file3Con.await();
}
flag = 4;
print("3");
file4Con.signal();
} catch(Exception e) {
} finally {
lock.unlock();
}
}
public void printFile4() {
lock.lock();
try {
while (flag != 4) {
file4Con.await();
}
flag = 1;
print("4");
file1Con.signal();
} catch(Exception e) {
} finally {
lock.unlock();
}
}
}
public class PrintSequence3 {
public static void main(String[] args) {
Task task1 = new Task("C:\\Users\\Administrator\\Desktop\\tmp\\a.txt", 1);
Task task2 = new Task("C:\\Users\\Administrator\\Desktop\\tmp\\b.txt", 2);
Task task3 = new Task("C:\\Users\\Administrator\\Desktop\\tmp\\c.txt", 3);
Task task4 = new Task("C:\\Users\\Administrator\\Desktop\\tmp\\d.txt", 4);
new Thread(() -> {
for (int i = 0; i < 30; i++) {
task1.printFile1();
task2.printFile1();
task3.printFile1();
task4.printFile1();
}
}).start();
new Thread(() -> {
for (int i = 0; i < 30; i++) {
task1.printFile2();
task2.printFile2();
task3.printFile2();
task4.printFile2();
}
}).start();
new Thread(() -> {
for (int i = 0; i < 30; i++) {
task1.printFile3();
task2.printFile3();
task3.printFile3();
task4.printFile3();
}
}).start();
new Thread(() -> {
for (int i = 0; i < 30; i++) {
task1.printFile4();
task2.printFile4();
task3.printFile4();
task4.printFile4();
}
}).start();
}
}
| true |
0ff8bbbe369b5abac3ae44bb59f2a6bac2d6b16d
|
Java
|
fracz/refactor-extractor
|
/results-java/naver--pinpoint/710edb12ece92b6d8ef7400b9127f57f5f427b8b/before/WebClusterConnectionManager.java
|
UTF-8
| 7,676 | 1.820313 | 2 |
[] |
no_license
|
/*
*
* * Copyright 2014 NAVER Corp.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*
*/
package com.navercorp.pinpoint.web.cluster.connection;
import com.navercorp.pinpoint.common.util.NetUtils;
import com.navercorp.pinpoint.rpc.PinpointSocket;
import com.navercorp.pinpoint.rpc.cluster.ClusterOption;
import com.navercorp.pinpoint.rpc.util.ClassUtils;
import com.navercorp.pinpoint.web.cluster.ClusterManager;
import com.navercorp.pinpoint.web.cluster.zookeeper.ZookeeperClusterManager;
import com.navercorp.pinpoint.web.config.WebConfig;
import com.navercorp.pinpoint.web.vo.AgentInfo;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* @Author Taejin Koo
*/
public class WebClusterConnectionManager {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final Charset charset = Charset.forName("UTF-8");
private final WebConfig config;
private final WebClusterAcceptor clusterAcceptor;
private final WebClusterConnector clusterConnector;
private ClusterManager clusterManager;
public WebClusterConnectionManager(WebConfig config) {
this.config = config;
if (config.isClusterEnable()) {
int bindPort = config.getClusterTcpPort();
if (bindPort > 0) {
clusterAcceptor = new WebClusterAcceptor(getRepresentationLocalV4Ip(), bindPort);
} else {
clusterAcceptor = null;
}
String connectAddress = config.getClusterConnectAddress();
if (connectAddress != null && connectAddress.trim().length() != 0) {
clusterConnector = new WebClusterConnector(config.getClusterConnectAddress());
} else {
clusterConnector = null;
}
} else {
clusterAcceptor = null;
clusterConnector = null;
}
}
@PostConstruct
public void start() throws InterruptedException, IOException, KeeperException {
if (!config.isClusterEnable()) {
return;
}
logger.info("{} initialization started.", ClassUtils.simpleClassName(this));
this.clusterManager = new ZookeeperClusterManager(config.getClusterZookeeperAddress(), config.getClusterZookeeperSessionTimeout(), config.getClusterZookeeperRetryInterval());
if (clusterConnector != null) {
clusterConnector.start();
}
if (clusterAcceptor != null) {
clusterAcceptor.start();
// TODO need modification - storing ip list using \r\n as delimiter since json list is not supported natively
String nodeName = clusterAcceptor.getBindHost() + ":" + clusterAcceptor.getBindPort();
List<String> localIpList = NetUtils.getLocalV4IpList();
this.clusterManager.registerWebCluster(nodeName, convertIpListToBytes(localIpList, "\r\n"));
}
logger.info("{} initialization completed.", ClassUtils.simpleClassName(this));
}
@PreDestroy
public void stop() {
logger.info("{} destroying started.", ClassUtils.simpleClassName(this));
if (clusterManager != null) {
clusterManager.close();
}
if (clusterConnector != null) {
clusterConnector.stop();
}
if (clusterAcceptor!= null) {
clusterAcceptor.stop();
}
logger.info("{} destroying completed.", ClassUtils.simpleClassName(this));
}
private String getRepresentationLocalV4Ip() {
String ip = NetUtils.getLocalV4Ip();
if (!ip.equals(NetUtils.LOOPBACK_ADDRESS_V4)) {
return ip;
}
// local ip addresses with all LOOPBACK addresses removed
List<String> ipList = NetUtils.getLocalV4IpList();
if (ipList.size() > 0) {
return ipList.get(0);
}
return NetUtils.LOOPBACK_ADDRESS_V4;
}
private byte[] convertIpListToBytes(List<String> ipList, String delimiter) {
StringBuilder stringBuilder = new StringBuilder();
Iterator<String> ipIterator = ipList.iterator();
while (ipIterator.hasNext()) {
String eachIp = ipIterator.next();
stringBuilder.append(eachIp);
if (ipIterator.hasNext()) {
stringBuilder.append(delimiter);
}
}
return stringBuilder.toString().getBytes(charset);
}
public PinpointSocket getSocket(AgentInfo agentInfo) {
return getSocket(agentInfo.getApplicationName(), agentInfo.getAgentId(), agentInfo.getStartTimestamp());
}
public PinpointSocket getSocket(String applicationName, String agentId, long startTimeStamp) {
if (!config.isClusterEnable()) {
return null;
}
List<String> clusterIdList = clusterManager.getRegisteredAgentList(applicationName, agentId, startTimeStamp);
// having duplicate AgentName registered is an exceptional case
if (clusterIdList.size() == 0) {
logger.warn("{}/{} couldn't find agent.", applicationName, agentId);
return null;
} else if (clusterIdList.size() > 1) {
logger.warn("{}/{} found duplicate agent {}.", applicationName, agentId, clusterIdList);
return null;
}
String clusterId = clusterIdList.get(0);
return getSocket0(clusterId);
}
private PinpointSocket getSocket0(String clusterId) {
if (clusterAcceptor != null) {
List<PinpointSocket> clusterList = clusterAcceptor.getClusterSocketList();
for (PinpointSocket cluster : clusterList) {
ClusterOption remoteClusterOption = cluster.getRemoteClusterOption();
if (remoteClusterOption != null) {
if (clusterId.equals(remoteClusterOption.getId())) {
return cluster;
}
}
}
}
if (clusterConnector != null) {
List<PinpointSocket> clusterList = clusterConnector.getClusterSocketList();
for (PinpointSocket cluster : clusterList) {
ClusterOption remoteClusterOption = cluster.getRemoteClusterOption();
if (remoteClusterOption != null) {
if (clusterId.equals(remoteClusterOption.getId())) {
return cluster;
}
}
}
}
return null;
}
public List<PinpointSocket> getClusterList() {
List<PinpointSocket> clusterList = new ArrayList<PinpointSocket>();
if (clusterAcceptor != null) {
clusterList.addAll(clusterAcceptor.getClusterSocketList());
}
if (clusterConnector != null) {
clusterList.addAll(clusterConnector.getClusterSocketList());
}
return clusterList;
}
}
| true |
28e79a62793e6d51d014f606387418b34d5d9f67
|
Java
|
X4TKC/PatronesDeDiseno
|
/src/main/java/TercerParcialClase/Bridge/exercise/withPattern/Client.java
|
UTF-8
| 495 | 2.5625 | 3 |
[] |
no_license
|
package TercerParcialClase.Bridge.exercise.withPattern;
public class Client {
public static void main(String[] args){
ArquitecturaX64 arquitecturaX64 = new ArquitecturaX64();
ArquitecturaX86 arquitecturaX86 = new ArquitecturaX86();
Windows windows = new Windows(arquitecturaX64);
Linux linux = new Linux(arquitecturaX86);
Mac mac = new Mac(arquitecturaX64);
mac.plataforma();
windows.plataforma();
linux.plataforma();
}
}
| true |
37a89785f827dbf0a1cd40841b4554401505f184
|
Java
|
dhkim1993/TIL
|
/CodingTest/Programmers/Decimal.java
|
UTF-8
| 498 | 3.21875 | 3 |
[] |
no_license
|
/**
* Created by kimdonghyun on 25/09/2019.
*/
public class Decimal {
public static void main(String[] args) {
int n=10;
Decimal decimal =new Decimal();
System.out.println(decimal.solution(n));
}
public int solution(int n){
int result =0;
for (int j=2; j<=n; j++){
if(j%2==0) continue;
else if(j%3==0) continue;
else if(j%5==0) continue;
else result++;
}
return result;
}
}
| true |
c303a332d7953641cf69d96bc1a23054e80a7fc6
|
Java
|
KananaNanis/Hotel-Management-System
|
/src/StaffService.java
|
UTF-8
| 6,123 | 2.40625 | 2 |
[] |
no_license
|
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/*
* 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.
*/
/**
*
* @author Nanis Kanana
* @author Claire Chemutai
*/
public class StaffService extends javax.swing.JFrame {
UserIdentification user;
Intermediary inter;
/**
* Creates new form StaffService
* @param inter
*/
public StaffService(Intermediary inter) {
initComponents();
this.inter = inter;
}
/**
* 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() {
staffViewTransactions = new javax.swing.JButton();
staffViewFood = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setMaximumSize(new java.awt.Dimension(400, 400));
setMinimumSize(new java.awt.Dimension(400, 400));
setPreferredSize(new java.awt.Dimension(400, 400));
getContentPane().setLayout(null);
staffViewTransactions.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold", 3, 18)); // NOI18N
staffViewTransactions.setText("VIEW TRANSACTIONS");
staffViewTransactions.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
staffViewTransactionsActionPerformed(evt);
}
});
getContentPane().add(staffViewTransactions);
staffViewTransactions.setBounds(101, 65, 230, 40);
staffViewFood.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold", 3, 18)); // NOI18N
staffViewFood.setText("VIEW MENU");
staffViewFood.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
staffViewFoodActionPerformed(evt);
}
});
getContentPane().add(staffViewFood);
staffViewFood.setBounds(101, 141, 230, 29);
jLabel1.setFont(new java.awt.Font("Tahoma", 3, 24)); // NOI18N
jLabel1.setText("ROYAL STAR HOTEL");
getContentPane().add(jLabel1);
jLabel1.setBounds(80, 0, 238, 29);
jButton1.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N
jButton1.setText("BACK");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1);
jButton1.setBounds(130, 210, 160, 30);
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img.jpg"))); // NOI18N
getContentPane().add(jLabel2);
jLabel2.setBounds(0, 0, 400, 300);
pack();
}// </editor-fold>//GEN-END:initComponents
private void staffViewFoodActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_staffViewFoodActionPerformed
// TODO add your handling code here:
ViewMenu viewFood = new ViewMenu (this);
this.setVisible(false);
viewFood.setVisible(true);
}//GEN-LAST:event_staffViewFoodActionPerformed
private void staffViewTransactionsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_staffViewTransactionsActionPerformed
StringBuilder sb =new StringBuilder();
sb.append(String.format("%d foodOrders made!!", inter.names.size()));
sb.append("\n");
sb.append(String.format("%d rooms booked!!", inter.roomNum.size()));
sb.append("\n");
for(int i=0;i<inter.names.size();i++){
sb.append(" Food ordered : ").append(String.format("%s, %s ",inter.names.get(i), inter.price.get(i)));
sb.append("\n");
}
for(int i=0;i<inter.roomNum.size();i++){
sb.append("Rooms booked : ").append(String.format("%s, %s ",inter.roomNum.get(i), inter.roomHall.get(i)));
sb.append("\n");
}
TransactionsMade trans = new TransactionsMade(this);
trans.transactionTextArea.setText(sb.toString());
this.setVisible(false);
trans.setVisible(true);
writeFile(sb.toString());
}//GEN-LAST:event_staffViewTransactionsActionPerformed
public static void writeFile(String arrayValues) {
try {
File file = new File("output.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(arrayValues);
bw.newLine();
bw.close();
} catch (IOException e) {
System.err.println(e.toString());
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
UserIdentification id = new UserIdentification(inter);
this.setVisible(false);
id.setVisible(true);
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JButton staffViewFood;
private javax.swing.JButton staffViewTransactions;
// End of variables declaration//GEN-END:variables
}
| true |
9da89c262b9bbab7f7f67080d40c4e9adb3a535b
|
Java
|
tigratius/CrudConsole
|
/src/main/java/com/tigratius/crud/service/CategoryService.java
|
UTF-8
| 281 | 1.953125 | 2 |
[] |
no_license
|
package main.java.com.tigratius.crud.service;
import main.java.com.tigratius.crud.model.Category;
public interface CategoryService extends GenericService<Category, Long> {
void create(String name) throws Exception;
void update(Long id, String name) throws Exception;
}
| true |
770b2d6f86306cdb629fab63a9878500971c38d2
|
Java
|
maximbu/coding
|
/src/interviewbit/bitManipulation/MinXorValue.java
|
UTF-8
| 2,818 | 3.484375 | 3 |
[] |
no_license
|
package interviewbit.bitManipulation;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Given an array of N integers, find the pair of integers in the array which have minimum XOR value. Report the minimum XOR value.
*
* Examples :
* Input
* 0 2 5 7
* Output
* 2 (0 XOR 2)
* Input
* 0 4 7 9
* Output
* 3 (4 XOR 7)
*
* Constraints:
* 2 <= N <= 100 000
* 0 <= A[i] <= 1 000 000 000
*/
public class MinXorValue {
public int findMinXor(ArrayList<Integer> A) {
return findMinXor(A, 30);
}
public int findMinXor(ArrayList<Integer> A, int msbDigit) {
int minXor = Integer.MAX_VALUE;
if (A.size() < 4 || msbDigit == 0) {
for (int i = 0; i < A.size(); i++) {
for (int j = i + 1; j < A.size(); j++) {
int ans = A.get(i) ^ A.get(j);
if (ans < minXor) {
minXor = ans;
System.out.println("Xor of " + A.get(i) + " and " + A.get(j) + " is the new min: " + ans);
}
}
}
return minXor;
}
ArrayList<Integer> msb1 = new ArrayList<Integer>();
ArrayList<Integer> msb0 = new ArrayList<Integer>();
int d = 1 << msbDigit;
for (Integer aA : A) {
if ((aA & d) == 0) {
msb0.add(aA);
} else {
msb1.add(aA);
}
}
return Math.min(findMinXor(msb0, msbDigit - 1), findMinXor(msb1, msbDigit - 1));
}
public static void main(String[] st) {
MinXorValue q = new MinXorValue();
ArrayList<Integer> X = new ArrayList<>(Arrays.asList(14, 12, 5, 8, 11, 4));
ArrayList<Integer> X2 = new ArrayList<>(Arrays.asList(3, 2, 13, 1, 5, 13, 0, 13, 13));
ArrayList<Integer> X3 = new ArrayList<>(
Arrays.asList(492416, 275153, 684032, 319360, 543232, 804480, 525824, 671825, 1036753, 940625, 909521, 405120, 1076689, 80081, 57856, 1000145, 13649, 596049, 429649, 289489, 907136, 261120, 1247313, 902609, 576465, 1133696, 1128576, 877440, 1058432, 554449, 1206225, 1007953, 1066705,
1237329, 491601, 300753, 789073, 1233408, 513617, 657152, 993664, 93568, 324689, 457169, 254208, 1250560, 217169, 557568, 416896, 256465, 687313, 21888, 433536, 276224, 536145, 466304, 3200, 162176, 341376, 589824, 1075840, 411345, 401873, 52561, 653649, 1077376, 1011456,
339281, 297472, 931200, 869969, 1131601, 326272, 94801, 1246464, 646400, 727040, 1001856, 120192, 1093585, 309632, 313169, 160977, 1102720, 1126993));
//System.out.println(492416 ^ 491601);
System.out.println(q.findMinXor(X));
System.out.println(q.findMinXor(X2));
System.out.println(q.findMinXor(X3));
}
}
| true |
7bd0999146332af8e4abf5713fb9e039e7f7d4a7
|
Java
|
suyx1999/NETS
|
/src/main/Cell.java
|
UTF-8
| 1,544 | 3.109375 | 3 |
[] |
no_license
|
package main;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
public class Cell {
public ArrayList<Short> cellIdx;
public HashMap<ArrayList<Short>,Cell> childCells;
public HashSet<Tuple> tuples;
double[] cellCenter;
public Cell(ArrayList<Short> cellIdx){
this.cellIdx = cellIdx;
this.tuples = new HashSet<Tuple>();
}
public Cell(ArrayList<Short> cellIdx, double[] cellCenter){
this.cellIdx = cellIdx;
this.tuples = new HashSet<Tuple>();
this.cellCenter = cellCenter;
}
public Cell(ArrayList<Short> cellIdx, double[] cellCenter, Boolean subDimFlag){
this.cellIdx = cellIdx;
this.cellCenter = cellCenter;
this.tuples = new HashSet<Tuple>();
if(subDimFlag) this.childCells = new HashMap<ArrayList<Short>,Cell>();
}
public int getNumTuples() {
return this.tuples.size();
}
public void addTuple(Tuple t, double[] fullDimCellCenter, Boolean subDimFlag) {
this.tuples.add(t);
if(subDimFlag) {
if(!this.childCells.containsKey(t.fullDimCellIdx))
this.childCells.put(t.fullDimCellIdx, new Cell(t.fullDimCellIdx, fullDimCellCenter));
this.childCells.get(t.fullDimCellIdx).addTuple(t, fullDimCellCenter, false);
}
}
public void addTuple(Tuple t, Boolean subDimFlag) {
this.tuples.add(t);
if(subDimFlag) {
if(!this.childCells.containsKey(t.fullDimCellIdx))
this.childCells.put(t.fullDimCellIdx, new Cell(t.fullDimCellIdx));
this.childCells.get(t.fullDimCellIdx).addTuple(t, false);
}
}
}
| true |
129f58cfede07dec0e813809518b0a768e1dcf8b
|
Java
|
renzhe-li/spring-cloud-tx
|
/payment/src/main/java/com/demo/tx/payment/config/KafkaConfig.java
|
UTF-8
| 1,787 | 1.882813 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.demo.tx.payment.config;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class KafkaConfig {
@Bean
public KafkaTemplate<String, String> kafkaTemplate(@Autowired ProducerFactory<String, String> producerFactory) {
return new KafkaTemplate<>(producerFactory);
}
@Bean
public ProducerFactory<String, String> producerFactory(@Autowired KafkaConfiguration kafkaConfiguration) {
final Map<String, Object> props = new HashMap<>();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaConfiguration.getBootstrapServers());
props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 40960);
props.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, 6000);
props.put(ProducerConfig.RETRIES_CONFIG, 0);
props.put(ProducerConfig.BATCH_SIZE_CONFIG, 4096);
props.put(ProducerConfig.LINGER_MS_CONFIG, 10);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.springframework.kafka.support.serializer.JsonSerializer");
props.put(ProducerConfig.CLIENT_ID_CONFIG, "producer.client.payment");
props.put(ProducerConfig.ACKS_CONFIG, "all");
return new DefaultKafkaProducerFactory<>(props);
}
}
| true |
30740f85a9480c1935856d9126bd8af1a32b82de
|
Java
|
pCosta99/Masters
|
/MFES/ATS/Project/structuring/projectsPOO_1920/19/Grupo37_POO2020/ProjetoPOO/GPS.java
|
UTF-8
| 1,609 | 2.984375 | 3 |
[] |
no_license
|
import static java.lang.StrictMath.sqrt;
import java.io.Serializable;
public class GPS implements Serializable{
private double latitude;
private double longitude;
public GPS(){
this.latitude = 0;
this.longitude = 0;
}
public GPS(double latitude,double longitude){
this.latitude= latitude;
this.longitude= longitude;
}
public GPS(GPS coordenadas){
this.latitude = coordenadas.getLatitude();
this.longitude = coordenadas.getLongitude();
}
public double getLatitude() {
return this.latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return this.longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GPS coordenadas = (GPS) o;
return this.latitude == coordenadas.getLatitude() && this.longitude == coordenadas.getLongitude();
}
public GPS clone(){
return new GPS(this);
}
public double distEntre(GPS l){
return sqrt(Math.pow((l.getLatitude() - this.getLatitude()), 2) + Math.pow((l.getLongitude() - this.getLongitude()), 2));
}
public boolean inRangeT(Transportadora t){
return t.getRaio() >= this.distEntre(t.getLocalizacao());
}
public boolean inRangeV(Voluntario v) {
return v.getRaio() >= this.distEntre(v.getLocalizacao());
}
}
| true |
e5dc4181acfd45441816ed3fa6d18d44d0f4740c
|
Java
|
sank3t/Learn-Java
|
/Buffer.java
|
UTF-8
| 383 | 3.4375 | 3 |
[] |
no_license
|
import java.util.Scanner;
class Buffer
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s;
int i,j=0;
System.out.print("Enter a string:");
s=sc.next();
char[] a=s.toCharArray();
char[] a1=new char[3];
for(i=a.length;i>0;i--)
{
a1[j]=a[i];
j++;
}
for(i=0;i<3;i++)
System.out.println(a1[i]);
}
}
| true |