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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
5394f67d66368d132690fb80449fc3cbd94f98ac
|
Java
|
YangHua1011/game-fir
|
/src/com/javastudy/game/drawcard/App.java
|
UTF-8
| 198
| 1.820313
| 2
|
[
"MIT"
] |
permissive
|
package com.javastudy.game.drawcard;
import com.javastudy.game.drawcard.model.Game;
public class App {
public static void main(String[] args) {
Game game=new Game();
game.start();
}
}
| true
|
8e675bfbcc361fdc5990b9310c117caf821daf8e
|
Java
|
u201515982/PSI
|
/TicketApp/app/src/main/java/com/psi/ticketapp/CreateTicket.java
|
UTF-8
| 19,789
| 1.757813
| 2
|
[] |
no_license
|
package com.psi.ticketapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.example.ticketapp.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.Timestamp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CreateTicket extends Activity {
FirebaseFirestore db = FirebaseFirestore.getInstance();
Context context;
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser FBuser = mAuth.getCurrentUser();
boolean available;
private int floorButton = -1;
List<Button> FButtons;
private int typeButton = -1;
List<Button> TButtons;
SharedPreferences sharedPreferences;
TextView btn_desc_txt;
public void hideKeyboard(){
((EditText) findViewById(R.id.ct_user)).onEditorAction(EditorInfo.IME_ACTION_DONE);
}
private boolean isEmpty(EditText etText) {
return etText.getText().toString().trim().length() == 0;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
sharedPreferences = getPreferences(MODE_PRIVATE);
db.collection("users").document(FBuser.getEmail().substring(0,FBuser.getEmail().indexOf("@"))).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
available = (boolean)task.getResult().get("available");
}
}
});
setContentView(R.layout.activity_create_ticket);
FButtons = new ArrayList<>();
TButtons = new ArrayList<>();
configFloorButtons();
configTypeButtons();
final Button btn_desc_add = findViewById(R.id.ct_description_add);
final ConstraintLayout layout_desc = findViewById(R.id.ct_description_layout_alt);
btn_desc_txt = findViewById(R.id.ct_description_txt_alt);
ImageButton btn_desc_del = findViewById(R.id.ct_description_del_alt);
btn_desc_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openWriter();
}
});
btn_desc_txt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openWriter();
}
});
btn_desc_del.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(context, android.R.style.Theme_Material_Dialog_Alert));
builder.setMessage("¿Borrar descripción?");
builder.setPositiveButton("Si", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
layout_desc.setVisibility(View.GONE);
btn_desc_add.setVisibility(View.VISIBLE);
btn_desc_txt.setText(null);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
TextView textView = alert.findViewById(android.R.id.message);
textView.setTextSize(18);
}
});
Button btn_create_ticket = findViewById(R.id.btn_create_ticket);
Button btn_create_claim_ticket = findViewById(R.id.btn_create_claim_ticket);
findViewById(R.id.layout_create_ticket).setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
hideKeyboard();
return true;
}
});
btn_create_ticket.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ticketCreator(false);
}
});
btn_create_claim_ticket.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(available){
ticketCreator(true);
}
else Toast.makeText(context, "Usted ya se encuentra atendiendo un incidente!", Toast.LENGTH_SHORT).show();
}
});
}
public void openWriter(){
Intent i = new Intent(context, Writer.class);
Bundle extras = new Bundle();
extras.putInt("w",0);
extras.putString("title","Descripción");
extras.putString("text",btn_desc_txt.getText().toString());
i.putExtras(extras);
startActivityForResult(i,1);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == 1){
btn_desc_txt.setText(data.getStringExtra("large_text"));
findViewById(R.id.ct_description_layout_alt).setVisibility(View.VISIBLE);
findViewById(R.id.ct_description_add).setVisibility(View.GONE);
}
}
public void ticketCreator(boolean cc){
hideKeyboard();
View view = findViewById(R.id.btn_create_ticket);
view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
long datecode = System.currentTimeMillis();
EditText ct_user = findViewById(R.id.ct_user);
String ticketid = "tk."+datecode;
Map<String, Object> ticket = new HashMap<>();
if(isEmpty(ct_user)){
Toast.makeText(getApplicationContext(), "Nombre de usuario vacío!", Toast.LENGTH_LONG).show();
ct_user.setText("");
}else if(floorButton == -1){
Toast.makeText(getApplicationContext(), "Indicar número de piso!", Toast.LENGTH_LONG).show();
}else if(typeButton == -1){
Toast.makeText(getApplicationContext(), "Indicar tipo de ticket!", Toast.LENGTH_LONG).show();
}else{
Date time_begin = new Date();
String created_by = FBuser.getEmail().substring(0,FBuser.getEmail().indexOf("@"));
String user = ct_user.getText().toString();
String floor = Integer.toString(floorButton+1);
String area = ((Spinner)findViewById(R.id.spin_area)).getSelectedItem().toString();
String type = getType(typeButton);
String description = null;
if(btn_desc_txt.getText().toString().trim().length() != 0){
description = btn_desc_txt.getText().toString();
}
String state = "pending";
Date time_claimed = null;
String claimed_by = null;
if(cc){
//db.collection("users").document(created_by).update("available", false);
time_claimed = new Date();
claimed_by = created_by;
state = "claimed";
}
Timestamp time_end = null;
String post_mortem = null;
ticket.put("time_begin", time_begin);
ticket.put("created_by", created_by);
ticket.put("user", user);
ticket.put("floor", floor);
ticket.put("type", type);
ticket.put("description", description);
ticket.put("state", state);
ticket.put("time_claimed", time_claimed);
ticket.put("claimed_by", claimed_by);
ticket.put("time_end", time_end);
ticket.put("post_mortem", post_mortem);
ticket.put("area", area);
db.collection("root").document("tk.0").update("last", datecode);
db.collection("ticket").document(ticketid).set(ticket)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(getApplicationContext(), "ticket creado", Toast.LENGTH_LONG).show();
}
});
ct_user.onEditorAction(EditorInfo.IME_ACTION_DONE);
finish();
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
public void configFloorButtons(){
final Button btn1 = findViewById(R.id.F1);
final Button btn2 = findViewById(R.id.F2);
final Button btn3 = findViewById(R.id.F3);
final Button btn4 = findViewById(R.id.F4);
final Button btn5 = findViewById(R.id.F5);
final Button btn6 = findViewById(R.id.F6);
final Button btn7 = findViewById(R.id.F7);
final Button btn8 = findViewById(R.id.F8);
final Button btn9 = findViewById(R.id.F9);
final Button btn10 = findViewById(R.id.F10);
FButtons.add(btn1);
FButtons.add(btn2);
FButtons.add(btn3);
FButtons.add(btn4);
FButtons.add(btn5);
FButtons.add(btn6);
FButtons.add(btn7);
FButtons.add(btn8);
FButtons.add(btn9);
FButtons.add(btn10);
final Spinner spinner = findViewById(R.id.spin_area);
final ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this, R.array.piso1, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter25 = ArrayAdapter.createFromResource(this, R.array.piso25, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter6 = ArrayAdapter.createFromResource(this, R.array.piso6, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter7 = ArrayAdapter.createFromResource(this, R.array.piso7, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter8 = ArrayAdapter.createFromResource(this, R.array.piso8, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter9 = ArrayAdapter.createFromResource(this, R.array.piso9, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter10 = ArrayAdapter.createFromResource(this, R.array.piso10, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapterDEF = ArrayAdapter.createFromResource(this, R.array.areaspace, android.R.layout.simple_spinner_item);
adapterDEF.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapterDEF);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectFloorButtons(0);
hideKeyboard();
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter1);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectFloorButtons(1);
hideKeyboard();
adapter25.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter25);
}
});
btn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectFloorButtons(2);
hideKeyboard();
adapter25.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter25);
}
});
btn4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectFloorButtons(3);
hideKeyboard();
adapter25.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter25);
}
});
btn5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectFloorButtons(4);
hideKeyboard();
adapter25.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter25);
}
});
btn6.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectFloorButtons(5);
hideKeyboard();
adapter6.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter6);
}
});
btn7.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectFloorButtons(6);
hideKeyboard();
adapter7.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter7);
}
});
btn8.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectFloorButtons(7);
hideKeyboard();
adapter8.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter8);
}
});
btn9.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectFloorButtons(8);
hideKeyboard();
adapter9.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter9);
}
});
btn10.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectFloorButtons(9);
hideKeyboard();
adapter10.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter10);
}
});
}
public void selectFloorButtons(int eb) {
floorButton = eb;
for(int i=0; i<10;i++){
if (floorButton!= i){
FButtons.get(i).setSelected(false);
FButtons.get(i).setBackground(getDrawable(R.drawable.shape_green_outline));
FButtons.get(i).setTextColor(Color.parseColor("#5ED540"));
}else{
FButtons.get(i).setSelected(true);
FButtons.get(i).setBackground(getDrawable(R.drawable.shape_green_fill));
FButtons.get(i).setTextColor(Color.parseColor("#FFFFFF"));
}
}
}
public void configTypeButtons(){
final Button btnSupport = findViewById(R.id.ctt_support);
final Button btnPrinter = findViewById(R.id.ctt_printer);
final Button btnSisged = findViewById(R.id.ctt_sisged);
final Button btnSiaf = findViewById(R.id.ctt_siaf);
final Button btnSaps = findViewById(R.id.ctt_saps);
final Button btnWeb = findViewById(R.id.ctt_web);
final Button btnPte = findViewById(R.id.ctt_pte);
TButtons.add(btnSupport);
TButtons.add(btnPrinter);
TButtons.add(btnSisged);
TButtons.add(btnSiaf);
TButtons.add(btnSaps);
TButtons.add(btnWeb);
TButtons.add(btnPte);
btnSupport.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectTypeButtons(0);
hideKeyboard();
}
});
btnPrinter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectTypeButtons(1);
hideKeyboard();
}
});
btnSisged.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectTypeButtons(2);
hideKeyboard();
}
});
btnSiaf.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectTypeButtons(3);
hideKeyboard();
}
});
btnSaps.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectTypeButtons(4);
hideKeyboard();
}
});
btnWeb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectTypeButtons(5);
hideKeyboard();
}
});
btnPte.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectTypeButtons(6);
hideKeyboard();
}
});
}
public void selectTypeButtons(int tb) {
typeButton = tb;
for(int i=0; i<7;i++){
if (typeButton!= i){
TButtons.get(i).setSelected(false);
TButtons.get(i).setBackground(getDrawable(R.drawable.shape_blue_outline));
TButtons.get(i).setTextColor(Color.parseColor("#1CC2C2"));
}else{
TButtons.get(i).setSelected(true);
TButtons.get(i).setBackground(getDrawable(R.drawable.shape_blue_fill));
TButtons.get(i).setTextColor(Color.parseColor("#FFFFFF"));
}
}
}
public String getType(int t){
String t_name = "";
switch(t){
case 0: t_name = "Soporte"; break;
case 1: t_name = "Impresora"; break;
case 2: t_name = "SISGED"; break;
case 3: t_name = "SIAF"; break;
case 4: t_name = "SAPS"; break;
case 5: t_name = "WEB"; break;
case 6: t_name = "PTE"; break;
}
return t_name;
}
}
| true
|
cdb8b40db937ac5408817eb1edec98e621a367a7
|
Java
|
jasonthorne/OCA_JavaProgrammer
|
/Workspace/Section1.5/src/com/android/Insect.java
|
UTF-8
| 1,458
| 3.765625
| 4
|
[] |
no_license
|
package com.android;
//ONLY concrete classes HAVE TO override the abstract methods of an interface. (which is why this doesnt!):
public abstract class Insect implements Behaviour {
//Overriding the joy() method, but we DONT HAVE TO!
public void joy() {
System.out.println("Insect joy");
}
void crawl() {
System.out.println("Insect crawling");
}
}
//This DOSNT have to override the joy() method as its already overridden by Insect:
class Beetle extends Insect{
//When overriding the overriding method can have the same access level (in this case package level) OR GREATER:
//same access level:
/*
void crawl() {
}*/
//greater access level:
@Override
public void crawl() {
}
@Override
public void jealous() {
// TODO Auto-generated method stub
}
@Override
public int anger(double aDouble, char myChar) {
// TODO Auto-generated method stub
return 0;
}
@Override
public void euphoria() {
// TODO Auto-generated method stub
}
}
//THis MUST implement the abstract methods of the interface as its not abstract:
class Horse implements Behaviour{
@Override
public void jealous() {
// TODO Auto-generated method stub
}
@Override
public int anger(double aDouble, char myChar) {
// TODO Auto-generated method stub
return 0;
}
@Override
public void joy() {
// TODO Auto-generated method stub
}
@Override
public void euphoria() {
// TODO Auto-generated method stub
}
}
| true
|
b287669d6589f35eab0f0035afb3508c24976fb2
|
Java
|
PavellF/snippets
|
/springMvcWebServer/src/services/NotificationService.java
|
UTF-8
| 653
| 1.976563
| 2
|
[] |
no_license
|
package services;
import java.util.List;
import enums.NotificationType;
import enums.Order;
import enums.Status;
import objects.Notification;
public interface NotificationService {
public Notification send(long by, long forUser, NotificationType notificationType, String content);
public Status expire(List<Long> id, long ownerId);
public List<Notification> getAllNotificationsForUser(long userId, int skip,int count,boolean expired,
NotificationType[] notificationType,Order order);
public List<Notification> getAllNotificationsForUser(long userId, int skip, int count, Order order);
public Long getCountForUser(long userID);
}
| true
|
b4b3fc53266efc740dd171919af57796e57153b4
|
Java
|
jlixerkun/ConexionBD
|
/app/src/main/java/com/example/android/conexionbd/CursoAdapter.java
|
UTF-8
| 1,309
| 2.453125
| 2
|
[] |
no_license
|
package com.example.android.conexionbd;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import static android.R.attr.resource;
/**
* Created by jlixerkun on 12/03/17.
*/
public class CursoAdapter extends ArrayAdapter<Curso> {
public CursoAdapter(Activity context, ArrayList<Curso> cursos) {
super(context, 0, cursos);
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_curso, parent, false);
}
// Get the {@link Curso} object located at this position in the list
Curso currentCurso = getItem(position);
TextView cursoNombre = (TextView) listItemView.findViewById(R.id.nombre_curso_tv);
cursoNombre.setText(currentCurso.getNombre());
return listItemView;
}
}
| true
|
f2c45c9f855c763ddc3ad04c52ad1dbe78ab4c7d
|
Java
|
krissh-git/workspace
|
/spring/spring-boot-auth-jwt/src/main/java/com/example/demo/config/JwtTokenUtil.java
|
UTF-8
| 2,081
| 2.453125
| 2
|
[] |
no_license
|
package com.example.demo.config;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;
import java.util.function.Function;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import com.example.demo.model.Constants;
import com.example.demo.model.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
@Component
public class JwtTokenUtil {
public String getUserNameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject);
}
public boolean isTokenExpired(String token) {
Date expirationDate = getExpirationDateFromToken(token);
return expirationDate.before(new Date());
}
private Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}
public boolean validateToken(String token, UserDetails details) {
String userNameFromToken = getUserNameFromToken(token);
return Objects.equals(userNameFromToken, details.getUsername()) && !isTokenExpired(token);
}
public String generateToken(User user) {
return generateToken(user.getUsername());
}
private String generateToken(String subject) {
Claims claims = Jwts.claims().setSubject(subject);
claims.put("scopes", Arrays.asList(new SimpleGrantedAuthority(Constants.ROLE_ADMIN)));
return Jwts.builder().setClaims(claims).setIssuer(Constants.ISSUER)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + (Constants.ACCESS_TOKEN_VALIDITY * 1000)))
.signWith(SignatureAlgorithm.HS256, Constants.SIGNING_KEY).compact();
}
private <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claim = getAllClaimsFromToken(token);
return claimsResolver.apply(claim);
}
private Claims getAllClaimsFromToken(String token) {
return Jwts.parser().setSigningKey(Constants.SIGNING_KEY).parseClaimsJws(token).getBody();
}
}
| true
|
ae3af58de675184099e5e24d045d5554d06bd907
|
Java
|
nullllun/switch-monitor
|
/src/main/java/cn/albumenj/switchmonitor/dto/PortStatusDto.java
|
UTF-8
| 2,123
| 2.1875
| 2
|
[] |
no_license
|
package cn.albumenj.switchmonitor.dto;
/**
* 端口状态
*
* @author Albumen
*/
public class PortStatusDto {
private String portIndex;
private Long inData;
private Long outData;
private String des;
private Long inSpeed;
private Long outSpeed;
private Integer speed;
private String name;
private String upTime;
private String status;
private Integer cvlan;
private Integer pvlan;
public Integer getCvlan() {
return cvlan;
}
public void setCvlan(Integer cvlan) {
this.cvlan = cvlan;
}
public Integer getPvlan() {
return pvlan;
}
public void setPvlan(Integer pvlan) {
this.pvlan = pvlan;
}
public String getPortIndex() {
return portIndex;
}
public void setPortIndex(String portIndex) {
this.portIndex = portIndex;
}
public Long getInData() {
return inData;
}
public void setInData(Long inData) {
this.inData = inData;
}
public Long getOutData() {
return outData;
}
public void setOutData(Long outData) {
this.outData = outData;
}
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
public Long getInSpeed() {
return inSpeed;
}
public void setInSpeed(Long inSpeed) {
this.inSpeed = inSpeed;
}
public Long getOutSpeed() {
return outSpeed;
}
public void setOutSpeed(Long outSpeed) {
this.outSpeed = outSpeed;
}
public Integer getSpeed() {
return speed;
}
public void setSpeed(Integer speed) {
this.speed = speed;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUpTime() {
return upTime;
}
public void setUpTime(String upTime) {
this.upTime = upTime;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
| true
|
eb66dc538463063f6533e3d5d51cdb8d65cc1cf8
|
Java
|
jimador/narrative
|
/core/src/main/java/org/narrative/network/core/user/services/DeleteUserAccountContentTask.java
|
UTF-8
| 7,870
| 1.8125
| 2
|
[
"MIT"
] |
permissive
|
package org.narrative.network.core.user.services;
import org.narrative.common.persistence.OID;
import org.narrative.common.util.SubListIterator;
import org.narrative.network.core.area.user.AreaUser;
import org.narrative.network.core.area.user.AreaUserRlm;
import org.narrative.network.core.cluster.partition.Partition;
import org.narrative.network.core.cluster.partition.PartitionType;
import org.narrative.network.core.composition.base.Composition;
import org.narrative.network.core.composition.base.CompositionConsumer;
import org.narrative.network.core.composition.base.Reply;
import org.narrative.network.core.content.base.Content;
import org.narrative.network.core.content.base.services.DeleteContentsTask;
import org.narrative.network.core.content.base.services.DeleteReplyFully;
import org.narrative.network.core.user.User;
import org.narrative.network.customizations.narrative.channels.ChannelType;
import org.narrative.network.customizations.narrative.posts.ChannelContent;
import org.narrative.network.customizations.narrative.posts.NarrativePostStatus;
import org.narrative.network.customizations.narrative.publications.Publication;
import org.narrative.network.customizations.narrative.service.impl.publication.SendPublicationWriterAccountDeletedToPublicationEditorsEmailTask;
import org.narrative.network.shared.tasktypes.AllPartitionsTask;
import org.narrative.network.shared.tasktypes.AreaTaskImpl;
import org.narrative.network.shared.tasktypes.CompositionTaskImpl;
import org.narrative.network.shared.tasktypes.GlobalTaskImpl;
import org.narrative.network.shared.tasktypes.TaskOptions;
import org.narrative.network.shared.tasktypes.TaskRunner;
import org.narrative.network.shared.util.NetworkLogger;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static org.narrative.common.util.CoreUtils.*;
import static org.narrative.network.shared.util.NetworkCoreUtils.*;
/**
* Created by IntelliJ IDEA.
* User: martin
* Date: Apr 15, 2018
* Time: 1:26:59 PM
*/
public class DeleteUserAccountContentTask extends GlobalTaskImpl<Object> {
private static final NetworkLogger logger = new NetworkLogger(DeleteUserAccountContentTask.class);
private final User user;
private final static int CHUNK_SIZE = 200;
private final String userName;
private boolean log;
public DeleteUserAccountContentTask(User user, String userName) {
this.user = user;
this.userName = userName;
}
protected Object doMonitoredTask() {
log = logger.isInfoEnabled();
for (AreaUser areaUser : user.getAreaUsers()) {
AreaUserRlm areaUserRlm = AreaUser.getAreaUserRlm(areaUser);
// bl: send emails to Publication editors that are affected by deleted posts
// bl: note that these will only send at end of (successful) PartitionGroup
sendDeletedPostNotificationsToPublicationEditors(areaUserRlm);
//mk: delete Contents
execute(new DeleteContentProcess() {
public String getName() {return "Contents";}
public List<OID> getObjectOids() {
return Content.dao().getAllIDsBy(newNameValuePair(Content.FIELD__AREA_USER_RLM__NAME, areaUserRlm));
}
public void deleteChunk(List<OID> chunk) {
TaskRunner.doRootAreaTask(areaUser.getArea().getOid(), new DeleteContentsTask(chunk));
}
});
}
//mk: delete Replies
PartitionType.COMPOSITION.doTaskInAllPartitionsOfThisType(new TaskOptions(), new AllPartitionsTask<Object>(false) {
@Override
protected Object doMonitoredTask() {
List<OID> replyOids = Reply.dao().getAllIDsBy(newNameValuePair(Reply.FIELD__USER_OID__NAME, user.getOid()));
if (isEmptyOrNull(replyOids)) {
if (log) {
logger.info("No replies to delete on partition " + getCurrentPartition().getOid() + " for user /" + user.getOid());
}
} else {
if (log) {
logger.info("About to delete " + replyOids.size() + " replies on partition " + getCurrentPartition().getOid() + " for user /" + user.getOid());
}
deleteReplies(getCurrentPartition(), user.getAuthZone().getOid(), replyOids);
if (log) {
logger.info("Done deleting " + replyOids.size() + " replies on partition " + getCurrentPartition().getOid() + " for user /" + user.getOid());
}
}
return null;
}
});
return null;
}
private void sendDeletedPostNotificationsToPublicationEditors(AreaUserRlm areaUserRlm) {
Map<OID,Number> channelOidToDeletedPostCount = ChannelContent.dao().getPostCountsByChannelOidForAuthor(ChannelType.PUBLICATION, areaUserRlm, NarrativePostStatus.NON_BLOCKED_STATUSES);
Map<OID,Publication> oidToPublication = Publication.dao().getIDToObjectsFromIDs(channelOidToDeletedPostCount.keySet());
for (Map.Entry<OID, Number> entry : channelOidToDeletedPostCount.entrySet()) {
OID channelOid = entry.getKey();
Number count = entry.getValue();
Publication publication = oidToPublication.get(channelOid);
areaContext().doAreaTask(new SendPublicationWriterAccountDeletedToPublicationEditorsEmailTask(publication, userName, count.intValue()));
}
}
private void deleteReplies(Partition partition, OID areaOid, List<OID> replyOids) {
for (OID replyOid : replyOids) {
// bl: do each reply delete in its own transaction to avoid transactional issues with locking CompositionStats
TaskRunner.doRootAreaTask(areaOid, new AreaTaskImpl<Object>() {
@Override
protected Object doMonitoredTask() {
getNetworkContext().doCompositionTask(partition, new CompositionTaskImpl<Object>() {
@Override
protected Object doMonitoredTask() {
Reply reply = Reply.dao().get(replyOid);
Composition composition = reply.getComposition();
CompositionConsumer compositionConsumer = composition.getCompositionConsumer();
assert compositionConsumer!=null : "Should always have a CompositionConsumer! How did we miss one? reply/" + reply.getOid();
getNetworkContext().doCompositionTask(partition, new DeleteReplyFully(reply, compositionConsumer));
return null;
}
});
return null;
}
});
}
}
private interface DeleteContentProcess {
String getName();
List<OID> getObjectOids();
void deleteChunk(List<OID> chunk);
}
private void execute(DeleteContentProcess process) {
List<OID> objectOids = process.getObjectOids();
if (isEmptyOrNull(objectOids)) {
if (log) {
logger.info("No " + process.getName() + " to delete for user /" + user.getOid());
}
} else {
if (log) {
logger.info("About to delete " + objectOids.size() + " " + process.getName() + " for user /" + user.getOid());
}
Iterator<List<OID>> iter = new SubListIterator<>(objectOids, CHUNK_SIZE);
while (iter.hasNext()) {
process.deleteChunk(iter.next());
}
if (log) {
logger.info("Done deleting " + objectOids.size() + " " + process.getName() + " for user /" + user.getOid());
}
}
}
}
| true
|
7c408ec6761dff5ee6a109fa5e6ec7e22e86e28f
|
Java
|
wanghengquan/repository
|
/tmp_client/src/gui_interface/capture_detail.java
|
UTF-8
| 5,474
| 2.4375
| 2
|
[] |
no_license
|
/*
* File: main_frame.java
* Description: Software command line parser definition
* Author: Jason.Wang
* Date:2017/03/11
* Modifier:
* Date:
* Description:
*/
package gui_interface;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import connect_tube.task_data;
import data_center.public_data;
public class capture_detail extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private task_data task_info;
private String queue_name;
private Vector<String> detail_column = new Vector<String>();
private Vector<Vector<String>> detail_data = new Vector<Vector<String>>();
private JTable detail_table;
public capture_detail(String queue_name, task_data task_info) {
this.queue_name = queue_name;
this.task_info = task_info;
this.setTitle("Detail info for " + queue_name + ":");
Image icon_image = Toolkit.getDefaultToolkit().getImage(public_data.ICON_FRAME_PNG);
this.setIconImage(icon_image);
Container container = this.getContentPane();
container.add(construct_table_panel(), BorderLayout.CENTER);
JTableHeader table_head = detail_table.getTableHeader();
container.add(table_head, BorderLayout.NORTH);
container.add(construct_bottom_panel(), BorderLayout.SOUTH);
this.setLocation(600, 400);
//this.setLocationRelativeTo(null);
this.setSize(800, 500);
}
public JPanel construct_table_panel() {
detail_column.add("Item");
detail_column.add("Details/Requirements");
HashMap<String, HashMap<String, String>> queue_data = new HashMap<String, HashMap<String, String>>();
if(!task_info.get_queue_data_from_received_admin_queues_treemap(queue_name).isEmpty()){
queue_data.putAll(task_info.get_queue_data_from_received_admin_queues_treemap(queue_name));
} else {
queue_data.putAll(task_info.get_queue_data_from_processed_admin_queues_treemap(queue_name));
}
ArrayList<String> items = new ArrayList<String>();
items.add("ID");
items.add("CaseInfo");
items.add("Environment");
items.add("LaunchCommand");
items.add("Software");
items.add("System");
items.add("Machine");
items.add("Preference");
items.add("Status");
Iterator<String> item_it = items.iterator();
while(item_it.hasNext()){
String item = item_it.next();
if (!queue_data.containsKey(item)){
continue;
}
HashMap<String, String> section_data = new HashMap<String, String>();
section_data.putAll(queue_data.get(item));
if(section_data.size() < 1){
Vector<String> empty_line = new Vector<String>();
empty_line.add(item);
empty_line.add("NA");
detail_data.add(empty_line);
continue;
}
Iterator<String> option_it = section_data.keySet().iterator();
int option_count = 0;
while(option_it.hasNext()){
Vector<String> detail_line = new Vector<String>();
String option = option_it.next();
String value = section_data.getOrDefault(option, "NA");
if(option_count == 0){
detail_line.add(item);
} else {
detail_line.add(" ");
}
detail_line.add(option + "=" + value);
detail_data.add(detail_line);
option_count++;
}
}
detail_table = new info_table(detail_data, detail_column);
detail_table.getColumn("Item").setMaxWidth(200);
detail_table.getColumn("Item").setMinWidth(150);
//insert table
JPanel table_panel = new JPanel(new BorderLayout());
JScrollPane scroll_panel = new JScrollPane(detail_table);
table_panel.add(scroll_panel);
return table_panel;
}
public JPanel construct_bottom_panel() {
JPanel jp_info = new JPanel(new GridLayout(2,1,1,1));
String priority_str = new String(queue_name.split("@")[0]);
Integer priority_int = Integer.valueOf(0);
priority_int = Integer.valueOf(priority_str);
int task_bit_int = priority_int / 100;
int match_bit_int = priority_int % 100 / 10;
int from_bit_int = priority_int % 10;
//second line
StringBuilder show_overall = new StringBuilder();
show_overall.append("Overall Priority:" + priority_str);
show_overall.append(" (Smaller number has higher priority, 000 > 911)");
JLabel jl_line1 = new JLabel(show_overall.toString());
jp_info.add(jl_line1);
//first line
StringBuilder show_detail = new StringBuilder();
show_detail.append("*: ");
show_detail.append(String.valueOf(task_bit_int) + ": Task Priority; ");
if (match_bit_int == 0){
show_detail.append(String.valueOf(match_bit_int) + ": Assigned Task; " );
} else {
show_detail.append(String.valueOf(match_bit_int) + ": Matched Task; " );
}
if (from_bit_int == 0){
show_detail.append(String.valueOf(from_bit_int) + ": Local Task; " );
} else {
show_detail.append(String.valueOf(from_bit_int) + ": Remote Task; " );
}
JLabel jl_line2 = new JLabel(show_detail.toString());
jp_info.add(jl_line2);
return jp_info;
}
public static void main(String[] args) {
task_data task_info = new task_data();
capture_detail compare_view = new capture_detail(null, task_info);
compare_view.setVisible(true);
}
}
| true
|
210ade7a67935c6533a20220264ceef3035dbd6f
|
Java
|
michael-spadafora/coms
|
/src/main/java/seafoamgreen/coms/services/SeriesService.java
|
UTF-8
| 2,515
| 2.421875
| 2
|
[] |
no_license
|
package seafoamgreen.coms.services;
import seafoamgreen.coms.model.Comic;
import seafoamgreen.coms.model.Series;
import seafoamgreen.coms.model.User;
import seafoamgreen.coms.repositories.ComicRepository;
import seafoamgreen.coms.repositories.SeriesRepository;
import seafoamgreen.coms.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
//TODO: let user subscribe to series
@Service
public class SeriesService {
@Autowired
private SeriesRepository seriesRepository;
@Autowired
ComicRepository comicRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private ComicService comicService;
//Create
public Series create(String seriesName, String username)
{
Series series = new Series(seriesName, username);
seriesRepository.save(series);
return series;
}
//Update
public Optional<Series> findByID(String id)
{
return seriesRepository.findById(id);
}
public Series addComic(String seriesID, String comicID)
{
Optional<Series> series = seriesRepository.findById(seriesID);
series.get().addComic(comicID);
System.out.println("Adding to series " + series.get().getSeriesName());
seriesRepository.save(series.get());
return series.get();
}
public void deleteById(String id)
{
seriesRepository.deleteById(id);
// comicRepository.deleteBySeriesId(id);
List<Comic> comics = comicRepository.findBySeriesID(id);
//deleting a series, deletes the comics, which removes it from the users history
for (Comic c : comics) {
String comicId = c.getId();
comicService.deleteById(comicId);
}
//TODO: remove from subscriptions
List<User> users = userRepository.findAll();
for (User u : users) {
if (u.getSubscriptions().contains(id)){
u.getSubscriptions().remove(id);
userRepository.save(u);
}
}
}
//Add comic to series list
public void deleteAll() { seriesRepository.deleteAll(); }
public List<Series> findByUserId(String userId) {
return seriesRepository.findByUserID(userId);
}
public List<Series> findAllByUsername(String username) {
return seriesRepository.findByUsername(username);
}
}
| true
|
284c030e99a107fbb0425fe98d342d198495cae8
|
Java
|
alexander-pimenov/lessons-job4j
|
/chapter_tutorial/src/main/java/ru/job4j/tutorial/list/linkedList3/LinkedContainer.java
|
UTF-8
| 13,178
| 3.734375
| 4
|
[
"Apache-2.0"
] |
permissive
|
package ru.job4j.tutorial.list.linkedList3;
import java.util.Iterator;
/**
* Вся работа в нашем ссылочном контейнере LinkedContainer
* сводится к тому, что бы организовать взаимосвязь между нашими Node.
* Например, перебросить наши ссылки в момент добавления/удаления
* элементов.
* <p>
* Здесь будет реализован не замкнутый связный список.
* Т.е. у которого первый и последний элементы списка не имеют ссылки друг
* на друга. Это будет только в тот момент, когда список еще пуст.
* И эти ссылки имеют null.
* <p>
* Node схематически выглядит так: <-prevElement[Node(e=value)]nextElement->
* <p>
* Ниже показаны Первый и Последний элементы списка:
* Когда список еще пуст.
* null<-prevElement[fstNode(e=null)]nextElement-> <-prevElement[lstNode(e=null)]nextElement->null
* <p>
* Ниже показаны Первый, последующий и Последний элементы списка:
* null<-prevElement[fstNode(e=null)]nextElement-> <-prevElement[Node(e=value)]nextElement-> <-prevElement[lstNode(e=null)]nextElement->null
* <p>
* Этот контейнер также реализует интерфейс Iterable. Для того чтобы по нему можно было итерироваться с помощью Итератора.
* Прямая итерация от головы к хвосту.
* <p>
* А также LinkedContainer будет имплиментировать интерфейс interface DescendingIterator<E>, с методом Iterator<E> descendingIterator(); -
* он нужен для итерирования по элеметам списка в обратном порядке: от хвоста к голове.
* Возможность связного списка итерироваться в обратном порядке - это существенный момент.
*
* @param <E>
*/
public class LinkedContainer<E> implements Linked<E>, Iterable<E>, DescendingIterator<E> {
private Node<E> fstNode; // указатель на первый элемент. В самом начале он пуст.
private Node<E> lstNode; // указатель на последний элемент. В самом начале он пуст.
private int size = 0;
//ниже показаны Первый и Последний элементы списка:
//null<-prevElement[fstNode(e=null)]nextElement-> <-prevElement[lstNode(e=null)]nextElement->null
//ниже показаны Первый, последующий и Последний элементы списка:
//null<-prevElement[fstNode(e=null)]nextElement-> <-prevElement[Node(e=value)]nextElement-> <-prevElement[lstNode(e=null)]nextElement->null
//
/**
* Конструктор нашего ссылочного контейнера.
* Нужен, чтобы инициализировать fstNode и lstNode.
* С помощью этого конструктора создадим экземпляр класса,
* у которого уже будет некая связная структура между первой и последней
* Нодой (Node).
*/
public LinkedContainer() {
//инициализируем последнюю Node
/*Раз Node будет последняя, то текущего элемна не будет и currentElement=null,
* ссылка на предыдущий элемент указывать на Первый элемент prevElement=fstNode,
* а ссылка наследующий элемент nextElement=null*/
this.lstNode = new Node<E>(null, fstNode, null);
//инициализируем первую Node
/*Текущий элемент currentElement=null, т.к это просто заглушка,
* раз она Первая, то ссылки предыдущий элемент тоже нет prevElement=null,
* а ссылка на следующий элемент будет указывать на последний nextElement=lstNode.*/
this.fstNode = new Node<E>(null, null, lstNode);
}
@Override
public void addLast(E e) {
Node<E> prev = lstNode; //Переприсвоим указатель с последнего элемента, чтоб не потерять данные.
prev.setCurrentElement(e); //Зададим ему текущий элемент.
//Присвоим ему элемент, и он теперь не пустышка.
//А для lstNode создадим новую Ноду пустышку в конец (конечную).
//Заменяем старую последнюю Ноду на новую.
//Это будет новая Нода, у которой будет ссылка на prev.
lstNode = new Node<>(null, prev, null);
//Теперь нужно связать prev элемент к нашей новой последней Ноде,
//т.е. связываем его с конечным элементом пустышкой.
prev.setNextElement(lstNode);
//И соответственно инкрементируем size.
size++;
}
@Override
//Здесь будет аналогично методу addLast, но ориентированно на Первую Ноду заглушку.
public void addFirst(E e) {
Node<E> next = fstNode; //Переприсвоим указатель с первого элемента.
next.setCurrentElement(e); //делаем из первой ноды полноценный контейнер.
fstNode = new Node<>(null, null, next);//Создаем для fstNode новую Ноду пустышку (заглушку) в начало.
//Задаем для next ссылку на Первую Ноду пустышку,
//связываем его с первым элементом пустышкой,
//т.е. то что предшествует нексту.
next.setPrevElement(fstNode);
//И соответственно инкрементируем size.
size++;
}
@Override
public int size() {
return size;
}
/**
* В этом методе getElementByIndex лежит вся идея связного писка.
* Мы опускаемся все ниже и ниже к искомому элементу, вызывая в Node
* метод из статического класса Node:
* {@Code public Node<E> getNextElement() {
* return nextElement;
* } }
* и таким образом получаем последующую, и затем последующую Ноду.
*
* @param counter индекс искомого элемента.
* @return элемент списка с соответствующим индексом.
*/
@Override
public E getElementByIndex(int counter) {
//Создаем Ноду target, которая будет хранить наш результат.
//Начинаем проход от начала. Т.е. берем первую Ноду, получаем у нее
//getNextElement из геттера класса Node:
//public Node<E> getNextElement() {
// return nextElement;
// }
//Индекс здесь будет равен 0.
Node<E> target = fstNode.getNextElement();
//пройдемся циклом до индекса counter, т.е. доберемся до нужной нам Ноды.
//Залезли в Ноду нужное количество раз. Дошли до нужного индекса.
for (int i = 0; i < counter; i++) {
target = getNextElement(target); //при каждом проходе, мы перезаписываем target.
}
return target.getCurrentElement(); //Когда дошли до нужного индекса,
// то вызывает getCurrentElement(), т.е. вызываем сам элемент.
}
/**
* Создадим приватный метод для прохода до нужной нам Ноды.
*
* @param current текущая Нода.
* @return возвращает нам Ноду.
*/
private Node<E> getNextElement(Node<E> current) {
return current.getNextElement(); //получаем следующий элемент.
}
/**
* Т.к. наш контейнер реализует интерфейс Iterable<E>, то
* нужно реализовать метод iterator().
* Обход нашей коллекции от головы к хвосту.
* Реализуем его анонимным классом.
*
* @return Iterator<E>
*/
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
int counter = 0; //заводим переменную counter. Идем от начала к концу.
@Override
public boolean hasNext() {
return counter < size;
}
@Override
public E next() {
//Здесь будем использовать метод getElementByIndex, передавать в него counter
//и затем counter инкрементировать.
return getElementByIndex(counter++);
}
};
}
/**
* Т.к. наш контейнер реализует интерфейс DescendingIterator<E>, то
* нужно реализовать метод Iterator<E> descendingIterator().
* Обход нашей коллекции от хвоста к голове, т.е. итерация в обратном
* порядке.
* Реализуем его анонимным классом.
*
* @return Iterator<E>
*/
@Override
public Iterator<E> descendingIterator() {
return new Iterator<E>() {
int counter = size - 1;// заводим переменную counter. Идем от конца к началу.
@Override
public boolean hasNext() {
return counter >= 0;
}
@Override
public E next() {
//Здесь будем использовать метод getElementByIndex, передавать в него counter
//и затем counter декрементировать.
return getElementByIndex(counter--);
}
};
}
/**
* Статический класс Node<E> - это наш
* контейнер (вагончик), который хранит в себе
* данные элементва и ссылки между элементами.
* Полный аналог Node<E> из LinkedList Java.
* В классе добавили геттеры и сеттеры для удобства.
*
* @param <E>
*/
private static class Node<E> {
private E currentElement; //данные, которые храним в списке, текущий элемент.
private Node<E> nextElement; //ссылка на следующий элемент списка.
private Node<E> prevElement; //ссылка на предыдущий элемент списка.
/**
* Конструктор Node
*
* @param currentElement текущий элемент
* @param prevElement ссылка на предыдущий элемент
* @param nextElement ссылка на следующий элемент
*/
public Node(E currentElement, Node<E> prevElement, Node<E> nextElement) {
this.currentElement = currentElement;
this.nextElement = nextElement;
this.prevElement = prevElement;
}
public E getCurrentElement() {
return currentElement;
}
public void setCurrentElement(E currentElement) {
this.currentElement = currentElement;
}
public Node<E> getNextElement() {
return nextElement;
}
public void setNextElement(Node<E> nextElement) {
this.nextElement = nextElement;
}
public Node<E> getPrevElement() {
return prevElement;
}
public void setPrevElement(Node<E> prevElement) {
this.prevElement = prevElement;
}
}
}
| true
|
b68dd056c686bdff291bd88a60e53829e554d2c4
|
Java
|
jodastephen/kijaro
|
/kijaro/langtools/test/tools/javadoc/lib/Tester.java
|
UTF-8
| 11,359
| 2.421875
| 2
|
[] |
no_license
|
/*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* A utility used to invoke and test the javadoc tool.
*
* @author Scott Seligman
*/
import java.io.*;
import java.util.*;
import com.sun.javadoc.*;
public class Tester {
protected final String TEST_SRC = System.getProperty("test.src", ".");
protected final String TEST_CLASSES = System.getProperty("test.classes",
".");
private final String DEFAULT_ARGS[] = {
"-source", "1.5",
"-sourcepath", TEST_SRC,
};
private final File outputFile = new File(TEST_CLASSES, "testrun.out");
private final File expectedOutputFile = new File(TEST_SRC, "expected.out");
// private final File bootstrapMarkerFile = new File("bootstrap");
// True if we should "set expectations" by writing the expected output file
// rather than reading it and comparing.
// private final boolean bootstrap = bootstrapMarkerFile.isFile();
private String docletName;
private String[] args;
private Writer out = null;
/*
* Individual tests can extend this to create generics-aware doclets.
*/
public static abstract class Doclet extends com.sun.javadoc.Doclet {
public static LanguageVersion languageVersion() {
return LanguageVersion.JAVA_1_5;
}
}
public Tester(String docletName) {
this(docletName, new String[0]);
}
public Tester(String docletName, String... additionalArgs) {
this.docletName = docletName;
int len = DEFAULT_ARGS.length + additionalArgs.length;
args = new String[len];
System.arraycopy(DEFAULT_ARGS, 0, args, 0, DEFAULT_ARGS.length);
System.arraycopy(additionalArgs, 0, args, DEFAULT_ARGS.length,
additionalArgs.length);
try {
out = new BufferedWriter(new FileWriter(outputFile));
} catch (IOException e) {
throw new Error("Could not open output file " + outputFile);
}
}
public void run() throws IOException {
try {
if (com.sun.tools.javadoc.Main.execute("javadoc",
docletName, args) != 0) {
throw new Error("Javadoc errors encountered.");
}
System.out.println("--> Output written to " + outputFile);
} finally {
out.close();
}
}
/*
* Compare output of test run to expected output.
* Throw an Error if they don't match.
*/
public void verify() throws IOException {
BufferedReader thisRun =
new BufferedReader(new FileReader(outputFile));
BufferedReader expected =
new BufferedReader(new FileReader(expectedOutputFile));
for (int lineNum = 1; true; lineNum++) {
String line1 = thisRun.readLine();
String line2 = expected.readLine();
if (line1 == null && line2 == null) {
return; // EOF with all lines matching
}
if (line1 == null || !line1.equals(line2)) {
throw new Error(outputFile + ":" + lineNum +
": output doesn't match");
}
}
}
public void println(Object o) throws IOException {
prln(0, o);
}
public void println() throws IOException {
prln();
}
public void printPackage(PackageDoc p) throws IOException {
prPackage(0, p);
}
public void printClass(ClassDoc cd) throws IOException {
if (cd.isAnnotationType())
printAnnotationType((AnnotationTypeDoc)cd);
else
prClass(0, cd);
}
public void printAnnotationType(AnnotationTypeDoc at) throws IOException {
prAnnotationType(0, at);
}
public void printField(FieldDoc f) throws IOException {
prField(0, f);
}
public void printParameter(Parameter p) throws IOException {
prParameter(0, p);
}
public void printMethod(MethodDoc m) throws IOException {
prln(0, "method " + m);
prMethod(0, m);
}
public void printAnnotationTypeElement(AnnotationTypeElementDoc e)
throws IOException {
prln(0, "element " + e);
prMethod(0, e);
}
public void printConstructor(ConstructorDoc c) throws IOException {
prln(0, "constructor " + c);
prExecutable(0, c);
}
private void prPackage(int off, PackageDoc p) throws IOException {
prln(off, "package " + p);
prAnnotations(off + 2, p.annotations());
}
private void prClass(int off, ClassDoc cd) throws IOException {
prln(off,
(cd.isInterface() ? "interface" : cd.isEnum() ? "enum" : "class")
+ " " + cd);
prln(off + 2, "name: " + cd.simpleTypeName() + " / " +
cd.typeName() + " / " + cd.qualifiedTypeName());
prAnnotations(off + 2, cd.annotations());
prLabel(off + 2, "type parameters");
for (Type t : cd.typeParameters())
prln(off + 4, t);
prParamTags(off + 2, cd.typeParamTags());
prLabel(off + 2, "nested in");
prln(off + 4, cd.containingClass());
prLabel(off + 2, "superclass");
prln(off + 4, cd.superclassType());
prLabel(off + 2, "interfaces");
Type[] ts = cd.interfaceTypes();
Arrays.sort(ts);
for (Type t : ts)
prln(off + 4, t);
prLabel(off + 2, "enum constants");
for (FieldDoc f : cd.enumConstants())
prln(off + 4, f.name());
prLabel(off + 2, "fields");
for (FieldDoc f : cd.fields())
prln(off + 4, f.type() + " " + f.name());
prLabel(off + 2, "constructors");
for (ConstructorDoc c : cd.constructors())
prln(off + 4, c.name() + c.flatSignature());
prLabel(off + 2, "methods");
for (MethodDoc m : cd.methods())
prln(off + 4, typeUseString(m.returnType()) + " " +
m.name() + m.flatSignature());
}
private void prAnnotationType(int off, AnnotationTypeDoc at)
throws IOException {
prln(off, "@interface " + at);
prAnnotations(off + 2, at.annotations());
prLabel(off + 2, "elements");
for (AnnotationTypeElementDoc e : at.elements()) {
String def = (e.defaultValue() == null)
? ""
: " default " + e.defaultValue();
prln(off + 4, typeUseString(e.returnType()) + " " + e.name() +
e.flatSignature() + def);
}
}
private void prField(int off, FieldDoc f) throws IOException {
prln(off, "field " + typeUseString(f.type()) + " " + f.name());
prAnnotations(off + 2, f.annotations());
}
private void prParameter(int off, Parameter p) throws IOException {
prln(off, "parameter " + p);
prAnnotations(off + 2, p.annotations());
}
private void prMethod(int off, MethodDoc m) throws IOException {
prExecutable(off, m);
prLabel(off + 2, "returns");
prln(off + 4, typeUseString(m.returnType()));
prLabel(off + 2, "overridden type");
prln(off + 4, m.overriddenType());
}
private void prExecutable(int off, ExecutableMemberDoc m)
throws IOException {
if (!m.isAnnotationTypeElement()) {
prln(off + 2, "signature: " + m.flatSignature());
prln(off + 2, " " + m.signature());
}
prAnnotations(off + 2, m.annotations());
prParamTags(off + 2, m.typeParamTags());
prParamTags(off + 2, m.paramTags());
prLabel(off + 2, "type parameters");
for (Type t : m.typeParameters())
prln(off + 4, t);
prLabel(off + 2, "throws");
Type[] ts = m.thrownExceptionTypes();
Arrays.sort(ts);
for (Type t : ts)
prln(off + 4, t);
}
private void prAnnotations(int off, AnnotationDesc[] as)
throws IOException {
prLabel(off, "annotations");
for (AnnotationDesc a : as)
prln(off + 2, a.toString());
}
private void prParamTags(int off, ParamTag tags[]) throws IOException {
for (ParamTag tag : tags)
prParamTag(off, tag);
}
private void prParamTag(int off, ParamTag tag) throws IOException {
String name = tag.parameterName();
if (tag.isTypeParameter()) name = "<" + name + ">";
prln(off, "@param " + name + " " + tag.parameterComment());
}
private String typeUseString(Type t) {
return (t instanceof ClassDoc || t instanceof TypeVariable)
? t.typeName()
: t.toString();
}
// Labels queued for possible printing. Innermost is first in list.
List<Line> labels = new ArrayList<Line>();
// Print label if its section is nonempty.
void prLabel(int off, String s) {
while (!labels.isEmpty() && labels.get(0).off >= off)
labels.remove(0);
labels.add(0, new Line(off, s));
}
// Print queued labels with offsets less than "off".
void popLabels(int off) throws IOException {
while (!labels.isEmpty()) {
Line label = labels.remove(0);
if (label.off < off)
prln(label.off, label.o + ":");
}
}
// Print "o" at given offset.
void pr(int off, Object o) throws IOException {
popLabels(off);
for (int i = 0; i < off; i++)
out.write(' ');
if (o != null)
out.write(o.toString());
}
// Print "o" (if non-null) at given offset, then newline.
void prln(int off, Object o) throws IOException {
if (o != null) {
pr(off, o);
prln();
}
}
// Print newline.
void prln() throws IOException {
out.write('\n'); // don't want platform-dependent separator
}
static class Line {
int off;
Object o;
Line(int off, Object o) { this.off = off; this.o = o; }
}
}
| true
|
82d17f9b64feedce9dab7657bd5f3dbc93a54442
|
Java
|
brzozos/arkanoid
|
/TUT/src/Tutu/Game.java
|
UTF-8
| 3,004
| 2.796875
| 3
|
[] |
no_license
|
package Tutu;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static final int WIDTH =640, HEIGHT = WIDTH / 12 * 9;
public static final int BRICKWIDTH =48, BRICKHEIGHT = 24;
private Thread thread;
private boolean running = false;
private BufferedImage backgroundImg;
private BufferedImage backgroundMenu;
private Handler handler;
private HUD hud;
private Menu menu;
public Game() throws IOException{
backgroundImg = ImageIO.read(new File("data/background.jpg"));
backgroundMenu = ImageIO.read(new File("data/menu.jpg"));
handler = new Handler();
this.addKeyListener(new KeyInput(handler));
new Window(WIDTH,HEIGHT,"Arkanoid ", this);
hud = new HUD();
menu = new Menu();
handler.addObject(new Player(WIDTH/2 -32,HEIGHT - 90, 100,12,ID.Player,handler));
handler.addObject(new Ball(WIDTH/2 -32,HEIGHT - 102,12,12,ID.Ball,handler));
new Level(handler);
}
public synchronized void start(){
thread = new Thread(this);
thread.start();
running = true;
}
public synchronized void stop(){
try {
thread.join();
running = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public void run(){
this.requestFocus();
long lastTime = System.nanoTime();
double amountOfTicks = 50.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(running){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1){
tick();
delta--;
}
if(running)
render();
frames++;
if(System.currentTimeMillis() - timer > 1000){
timer += 1000;
System.out.println("FPS: " + frames);
frames = 0;
}
}
stop();
}
private void tick() {
handler.tick();
hud.tick();
menu.tick();
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs==null){
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
if(handler.getVisible()) g.drawImage(backgroundImg, 0, 0, null);
if(Menu.visible) g.drawImage(backgroundMenu,0,0,null);
// g.setColor(Color.WHITE);
// g.fillRect(0, 0, WIDTH, HEIGHT);
handler.render(g);
hud.render(g);
menu.render(g);
g.dispose();
bs.show();
}
public static int clamp(int var, int min, int max){
if(var >=max)
return var = max;
else if(var <=min)
return var = min;
else return var;
}
public void stopGame(){
running=false;
}
public static void main(String[] args) throws IOException {
new Game();
}
}
| true
|
da7cbe1bd63f3f8f5120c5b5d2d7bb18e447fc7e
|
Java
|
Ibarra-AZ/Swax
|
/swax-webservice/src/main/java/swax/webservice/service/user/IUserService.java
|
UTF-8
| 970
| 1.75
| 2
|
[] |
no_license
|
package swax.webservice.service.user;
import java.util.List;
import java.util.Map;
import swax.webservice.entity.user.User;
public interface IUserService {
public List<User> findAll();
public User findByUserId(int userId);
public Integer createUpdateEntity(User user);
public User findByEmailAndPassword(String email, String password);
public User findByEmail(String email);
public User findByUserName(String userName);
public User findByEmailOrUserName(String email, String userName);
public String initUserPassword();
public int countUsers();
public Map<String, Object> initUser(User user);
void deleteUser(User user);
// List<AlbumDiscogs> getDiscogsCollectionUpload(MultipartFile file, HttpServletRequest request)
// throws IOException;
// List<AlbumDiscogs> getDiscogsCollectionAPI();
// public List<AlbumDiscogsWantlist> getDiscogsWantlistUpload(MultipartFile file, HttpServletRequest request)
// throws IOException;
}
| true
|
a31a6d1a037c6fef32468e3b910979d7724eb330
|
Java
|
zhongxingyu/Seer
|
/Diff-Raw-Data/2/2_d5ef4b32cfcdcd3603de6d25317f139e949cca2e/UserProviderTest/2_d5ef4b32cfcdcd3603de6d25317f139e949cca2e_UserProviderTest_t.java
|
UTF-8
| 1,610
| 2.25
| 2
|
[] |
no_license
|
package org.timadorus.webapp.tests.server;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.timadorus.webapp.beans.User;
import org.timadorus.webapp.server.rpc.service.UserServiceImpl;
public class UserProviderTest {
private User user1;
private UserServiceImpl userService;
//private RegisteredUserList registeredUserList;
@Before
public void setUp() throws Exception {
userService = new UserServiceImpl();
user1 = new User("vorname", "nachname", "1.1.1970", "test@mail.org", "testuser01", "password");
//TODO user in die DB bekommen, wie es aussieht geht das nur über die GUI
}
@Test
public void test() {
Long userid = user1.getId();
String vorname = "vorname_test";
String nachname = "nachname_test";
String email = "email@test.org";
String gb = "01.01.1971";
String pw = "pw_test";
user1.setVorname(vorname);
user1.setNachname(nachname);
user1.setEmail(email);
user1.setGeburtstag(gb);
user1.setPassword(pw);
userService.update(user1.getId(), user1);
user1 = userService.getUser(user1);
Assert.assertEquals(userid, user1.getId());
Assert.assertEquals(vorname, user1.getVorname());
Assert.assertEquals(nachname, user1.getNachname());
Assert.assertEquals(email, user1.getEmail());
Assert.assertEquals(gb, user1.getGeburtstag());
Assert.assertEquals(pw, user1.getPassword());
}
}
| true
|
af6869c1a10c83c68396dd596e4f630378ef4c71
|
Java
|
Rune-Status/open-osrs-osrs-android
|
/src/main/java/hj.java
|
UTF-8
| 19,704
| 1.703125
| 2
|
[] |
no_license
|
public class hj extends bm {
int ad;
int ae;
df aj;
int al;
int an;
int ap;
int aq;
int ar;
int ax;
static final int ba = 0x7F;
static final int bs = 10;
static es ga;
hj(int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, boolean arg9, bm arg10) {
try {
super();
this.ax = arg2 * 0xA0FAE04B;
this.al = arg3 * 2001847357;
this.ae = arg4 * 0x3F750D61;
this.ar = arg5 * 0x715FABCF;
this.an = arg6 * 0xA2807E85;
this.ap = arg7 * 0xB01DCC13;
arg2 = -1;
if(arg2 != arg8) {
this.aj = fs.al(arg8, 1304812425);
this.ad = 0;
arg4 = 0x4979087B;
this.aq = client.bj * 0xDF54B445 - arg4;
if(this.aj.ah * 0x2D690AE9 == 0 && arg10 != null && ((arg10 instanceof hj)) && this.aj == ((hj)arg10).aj) {
this.ad = ((hj)arg10).ad;
this.aq = ((hj)arg10).aq;
return;
}
if(!arg9) {
return;
}
if(arg2 == this.aj.ab * 0xB171C811) {
return;
}
this.ad = (((int)(Math.random() * (((double)this.aj.ap.length))))) * 2006231377;
this.aq -= (((int)(Math.random() * (((double)this.aj.ad[this.ad * 0xD0CC3FB1]))))) * arg4;
}
}
catch(RuntimeException v2) {
StringBuilder v3 = new StringBuilder();
v3.append("hj.<init>(");
v3.append(')');
throw lx.al(((Throwable)v2), v3.toString());
}
}
static final void aj(lq arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12, int arg13) {
byte v13 = -23;
int v0 = 49;
if(arg8 >= 0) {
int v2 = 104;
if(arg8 >= v2) {
goto label_105;
}
else if(arg9 < 0) {
goto label_105;
}
else if(arg9 < v2) {
try {
id.al[arg7][arg8][arg9] = 0;
while(true) {
v2 = arg6.ay(v13);
if(v2 == 0) {
break;
}
else if(v2 == 1) {
int v6_1 = arg6.ay(-104);
if(1 == v6_1) {
v6_1 = 0;
}
if(arg7 == 0) {
id.ax[0][arg8][arg9] = -v6_1 * 8;
return;
}
id.ax[arg7][arg8][arg9] = id.ax[arg7 - 1][arg8][arg9] - v6_1 * 8;
}
else {
if(v2 <= v0) {
id.an[arg7][arg8][arg9] = arg6.aw(-1215098345);
v2 += -2;
id.ap[arg7][arg8][arg9] = ((byte)(v2 / 4));
id.aj[arg7][arg8][arg9] = ((byte)(v2 + arg12 & 3));
continue;
}
if(v2 <= 81) {
id.al[arg7][arg8][arg9] = ((byte)(v2 - 49));
continue;
}
id.ar[arg7][arg8][arg9] = ((byte)(v2 - 81));
continue;
}
return;
}
if(arg7 == 0) {
id.ax[0][arg8][arg9] = -di.aa(arg10 + (arg8 + 0xE3B7B), 0x87CCE + arg9 + arg11, 0xA8964315) * 8;
return;
}
id.ax[arg7][arg8][arg9] = id.ax[arg7 - 1][arg8][arg9] - 0xF0;
return;
while(true) {
label_105:
arg7 = arg6.ay(-84);
if(arg7 == 0) {
return;
}
if(1 == arg7) {
arg6.ay(v13);
return;
}
if(arg7 > v0) {
continue;
}
arg6.ay(-7);
}
return;
}
catch(RuntimeException v6) {
StringBuilder v7 = new StringBuilder();
v7.append("hj.aj(");
v7.append(')');
throw lx.al(((Throwable)v6), v7.toString());
}
}
else {
goto label_105;
}
}
else {
goto label_105;
}
}
static String al(byte[] arg5, int arg6, int arg7, int arg8) {
try {
StringBuilder v8 = new StringBuilder();
int v0;
for(v0 = arg6; v0 < arg7 + arg6; v0 += 3) {
int v1 = arg5[v0] & 0xFF;
v8.append(lm.ax[v1 >>> 2]);
if(v0 < arg7 - 1) {
int v2 = arg5[v0 + 1] & 0xFF;
v8.append(lm.ax[(v1 & 3) << 4 | v2 >>> 4]);
if(v0 < arg7 - 2) {
v1 = arg5[v0 + 2] & 0xFF;
v8.append(lm.ax[(v2 & 15) << 2 | v1 >>> 6]);
v8.append(lm.ax[v1 & 0x3F]);
}
else {
v8.append(lm.ax[(v2 & 15) << 2]);
v8.append("=");
}
}
else {
v8.append(lm.ax[(v1 & 3) << 4]);
v8.append("==");
}
}
return v8.toString();
}
catch(RuntimeException v5) {
StringBuilder v6 = new StringBuilder();
v6.append("hj.al(");
v6.append(')');
throw lx.al(((Throwable)v5), v6.toString());
}
}
public static int ar(int arg2, int arg3) {
int v0;
arg3 = 16;
if(arg2 < 0 || arg2 >= 0x10000) {
arg2 >>>= 16;
v0 = 16;
}
else {
v0 = 0;
}
if(arg2 >= 0x100) {
arg2 >>>= 8;
v0 += 8;
}
if(arg2 >= arg3) {
arg2 >>>= 4;
v0 += 4;
}
if(arg2 >= 4) {
arg2 >>>= 2;
v0 += 2;
}
if(arg2 >= 1) {
arg2 >>>= 1;
++v0;
}
return v0 + arg2;
}
protected final ca as() {
int v1_1;
int v3;
try {
df v1 = null;
int v2 = 0xD0CC3FB1;
if(this.aj != null) {
v3 = -2077001153;
int v0_1 = client.bj * v3 - this.aq * 0x310596B3;
if(v0_1 > 100 && this.aj.ab * 0xB171C811 > 0) {
v0_1 = 100;
}
do {
if(v0_1 > this.aj.ad[this.ad * v2]) {
v0_1 -= this.aj.ad[this.ad * v2];
this.ad += 2006231377;
if(this.ad * v2 < this.aj.ap.length) {
continue;
}
this.ad -= this.aj.ab * 0xD2E78661;
if(this.ad * v2 >= 0 && this.ad * v2 < this.aj.ap.length) {
continue;
}
break;
}
goto label_58;
}
while(true);
this.aj = v1;
label_58:
this.aq = (client.bj * v3 - v0_1) * 0x4979087B;
}
do v0_2 = ok.al(this.ax * 975563107, 800791607);
if(v0_2.bc != null) {
v0_2 = v0_2.ai(-702090457);
}
if(v0_2 == null) {
return ((ca)v1);
}
v3 = 1801737889;
int v4 = 0xB46CA623;
int v5 = 0x4B9D7897;
if(this.ae * v3 == 1 || 3 == this.ae * v3) {
v1_1 = v0_2.ag * v5;
v4 *= v0_2.az;
}
else {
v1_1 = v0_2.az * v4;
v4 = v0_2.ag * v5;
}
v5 = (v1_1 >> 1) + this.an * 0x5901CA4D;
int v7 = this.an * 0x5901CA4D + (v1_1 + 1 >> 1);
int v9 = (v4 >> 1) + this.ap * 0xA8F1DE1B;
int v6 = (v4 + 1 >> 1) + this.ap * 0xA8F1DE1B;
return v0_2.ab(this.al * 0x4C69F315, v3 * this.ae, id.ax[this.ar * 0x53AD7B2F], (this.an * 0x5901CA4D << 7) + (v1_1 << 6), id.ax[this.ar * 0x53AD7B2F][v7][v6] + (id.ax[this.ar * 0x53AD7B2F][v5][v9] + id.ax[this.ar * 0x53AD7B2F][v7][v9] + id.ax[this.ar * 0x53AD7B2F][v5][v6]) >> 2, (this.ap * 0xA8F1DE1B << 7) + (v4 << 6), this.aj, this.ad * v2, 0x4A90AB9);
}
catch(RuntimeException v0) {
StringBuilder v1_2 = new StringBuilder();
v1_2.append("hj.as(");
v1_2.append(')');
throw lx.al(((Throwable)v0), v1_2.toString());
}
}
static final void bs(int arg10) {
int v6;
int v5;
int v2;
int v0 = 0;
try {
while(true) {
v2 = 0xFE380E33;
if(v0 >= client.pd * v2) {
break;
}
--client.pa[v0];
if(client.pa[v0] < -10) {
client.pd -= 0xC7119CFB;
int v1;
for(v1 = v0; v1 < client.pd * v2; v1 = v5) {
v5 = v1 + 1;
client.px[v1] = client.px[v5];
client.ps[v1] = client.ps[v5];
client.pq[v1] = client.pq[v5];
client.pa[v1] = client.pa[v5];
client.pz[v1] = client.pz[v5];
}
--v0;
}
else {
hb v1_1 = client.ps[v0];
if(v1_1 == null) {
v1_1 = hb.ax(fq.cg, client.px[v0], 0);
if(v1_1 != null) {
client.pa[v0] += v1_1.ae();
client.ps[v0] = v1_1;
}
else {
goto label_132;
}
}
if(client.pa[v0] >= 0) {
goto label_132;
}
int v3 = -100;
if(client.pz[v0] != 0) {
v2 = (client.pz[v0] & 0xFF) * 0x80;
int v4 = (client.pz[v0] >> 16 & 0xFF) * 0x80 + 0x40 - gu.jg.bp * 0x914F0683;
if(v4 < 0) {
v4 = -v4;
}
v5 = (client.pz[v0] >> 8 & 0xFF) * 0x80 + 0x40 - gu.jg.bw * 0xD19D0C3D;
if(v5 < 0) {
v5 = -v5;
}
v4 = v4 + v5 - 0x80;
if(v4 > v2) {
client.pa[v0] = v3;
goto label_132;
}
if(v4 < 0) {
v4 = 0;
}
v6 = client.py * 0x6EC3BC9B * (v2 - v4) / v2;
}
else {
v6 = client.pb * 0xE0F0EA6D;
}
if(v6 > 0) {
hx v1_2 = hx.ae(v1_1.al().ax(oz.pp), 100, v6);
v1_2.ab(client.pq[v0] - 1);
lo.pr.ax(((hz)v1_2));
}
client.pa[v0] = v3;
}
label_132:
++v0;
}
if((client.po) && !co.aq(0x1F67CC50)) {
v1 = 0x3310F9D5;
if(client.pc * v1 != 0) {
v2 = 2029067435;
if(-1 != client.pm * v2) {
ik.ae(gn.dv, client.pm * v2, 0, client.pc * v1, false, -115);
}
}
client.po = false;
}
}
catch(RuntimeException v10) {
StringBuilder v0_1 = new StringBuilder();
v0_1.append("hj.bs(");
v0_1.append(')');
throw lx.al(((Throwable)v10), v0_1.toString());
}
}
protected final ca db() {
int v0;
df v1 = null;
int v2 = 0xD0CC3FB1;
if(this.aj != null) {
int v3 = -2077001153;
v0 = client.bj * v3 - this.aq * 0x310596B3;
if(v0 > 100 && this.aj.ab * 0xB171C811 > 0) {
v0 = 100;
}
do {
if(v0 > this.aj.ad[this.ad * v2]) {
v0 -= this.aj.ad[this.ad * v2];
this.ad += 2006231377;
if(this.ad * v2 < this.aj.ap.length) {
continue;
}
this.ad -= this.aj.ab * 0xD2E78661;
if(this.ad * v2 >= 0 && this.ad * v2 < this.aj.ap.length) {
continue;
}
break;
}
goto label_58;
}
while(true);
this.aj = v1;
label_58:
this.aq = (client.bj * v3 - v0) * 0x4979087B;
}
do v0_1 = ok.al(this.ax * 975563107, 337210225);
if(v0_1.bc != null) {
v0_1 = v0_1.ai(-293066316);
}
do v3_1 = v0_1;
if(v3_1 == null) {
return ((ca)v1);
}
int v1_1 = 1801737889;
int v4 = 0xB46CA623;
int v5 = 0x4B9D7897;
if(this.ae * v1_1 == 1 || 3 == this.ae * v1_1) {
v0 = v3_1.ag * v5;
v4 *= v3_1.az;
}
else {
v0 = v3_1.az * v4;
v4 = v3_1.ag * v5;
}
v5 = (v0 >> 1) + this.an * 0x5901CA4D;
int v7 = this.an * 0x5901CA4D + (v0 + 1 >> 1);
int v9 = (v4 >> 1) + this.ap * 0xA8F1DE1B;
int v6 = (v4 + 1 >> 1) + this.ap * 0xA8F1DE1B;
return v3_1.ab(0x4C69F315 * this.al, this.ae * v1_1, id.ax[this.ar * 0x53AD7B2F], (v0 << 6) + (this.an * 0x5901CA4D << 7), id.ax[this.ar * 0x53AD7B2F][v7][v6] + (id.ax[this.ar * 0x53AD7B2F][v5][v9] + id.ax[this.ar * 0x53AD7B2F][v7][v9] + id.ax[this.ar * 0x53AD7B2F][v5][v6]) >> 2, (this.ap * 0xA8F1DE1B << 7) + (v4 << 6), this.aj, this.ad * v2, 0x4A90AB9);
}
protected final ca dm() {
int v3;
int v5;
int v0;
df v1 = null;
if(this.aj != null) {
int v2 = -2077001153;
v0 = client.bj * v2 - this.aq * 0x310596B3;
if(v0 > 100 && this.aj.ab * 0xB171C811 > 0) {
v0 = 1708691764;
}
do {
v5 = 0xD0CC3FB1;
if(v0 > this.aj.ad[this.ad * v5]) {
v0 -= this.aj.ad[this.ad * -170568310];
this.ad += 0x9229CA82;
if(this.ad * -305352411 < this.aj.ap.length) {
continue;
}
this.ad -= this.aj.ab * 0xD2E78661;
if(this.ad * 0x533F0E39 >= 0 && this.ad * v5 < this.aj.ap.length) {
continue;
}
break;
}
goto label_61;
}
while(true);
this.aj = v1;
label_61:
this.aq = (client.bj * v2 - v0) * 0x45E3004A;
}
do v0_1 = ok.al(this.ax * -2013500049, -281550306);
if(v0_1.bc != null) {
v0_1 = v0_1.ai(-178578105);
}
do v2_1 = v0_1;
if(v2_1 == null) {
return ((ca)v1);
}
if(this.ae * 1801737889 == 1 || 3 == this.ae * 364069694) {
v0 = 0x4B9D7897 * v2_1.ag;
v3 = v2_1.az * 0xB46CA623;
}
else {
v0 = v2_1.az * 0xD0E5DC20;
v3 = v2_1.ag * -1570800298;
}
int v4 = (v0 >> 1) + this.an * -453765060;
int v6 = this.an * 0x5901CA4D + (v0 + 1 >> 1);
v5 = (v3 >> 1) + this.ap * 0x7A100C4;
int v1_1 = (v3 + 1 >> 1) + this.ap * 0xA8F1DE1B;
return v2_1.ab(this.al * 0xAF9A2175, 0x51D1F736 * this.ae, id.ax[this.ar * 0xE154B28C], (v0 << 6) + (this.an * 1140280830 << 7), id.ax[this.ar * 0xE154B28C][v6][v1_1] + (id.ax[this.ar * 0xE154B28C][v4][v5] + id.ax[this.ar * 0xE154B28C][v6][v5] + id.ax[this.ar * 0xE154B28C][v4][v1_1]) >> 2, (this.ap * 0x5F5602CC << 7) + (v3 << 6), this.aj, this.ad * -1078080951, 0x4A90AB9);
}
protected final ca du() {
int v0;
df v1 = null;
int v2 = 0xD0CC3FB1;
if(this.aj != null) {
v0 = client.bj * -2077001153 - this.aq * 0x310596B3;
if(v0 > 1807452083 && this.aj.ab * -1035549690 > 0) {
v0 = 100;
}
do {
if(v0 > this.aj.ad[this.ad * v2]) {
v0 -= this.aj.ad[this.ad * 0x5590B4AE];
this.ad += 2006231377;
if(this.ad * 0x46D43271 < this.aj.ap.length) {
continue;
}
this.ad -= this.aj.ab * 1267102260;
if(this.ad * 0x3B901964 >= 0 && this.ad * v2 < this.aj.ap.length) {
continue;
}
break;
}
goto label_61;
}
while(true);
this.aj = v1;
label_61:
this.aq = (client.bj * 0x1F163AEF - v0) * 0x4979087B;
}
do v0_1 = ok.al(this.ax * 975563107, 0xC5A2A63D);
if(v0_1.bc != null) {
v0_1 = v0_1.ai(0xE9F2AB53);
}
do v3 = v0_1;
if(v3 == null) {
return ((ca)v1);
}
int v1_1 = 1801737889;
int v4 = 0xB46CA623;
if(this.ae * v1_1 == 1 || 3 == this.ae * v1_1) {
v0 = 0x4B9D7897 * v3.ag;
v4 *= v3.az;
}
else {
v0 = v3.az * v4;
v4 = v3.ag * 0x4D51E08A;
}
int v6 = (v0 >> 1) + this.an * 0x5901CA4D;
int v8 = this.an * 1038593591 + (v0 + 1 >> 1);
int v7 = (v4 >> 1) + this.ap * 0xB9A07F6D;
int v5 = (v4 + 1 >> 1) + this.ap * 0xA8F1DE1B;
return v3.ab(0x4C69F315 * this.al, this.ae * v1_1, id.ax[this.ar * 0x53AD7B2F], (v0 << 6) + (this.an * 0x16E79461 << 7), id.ax[this.ar * 0x53AD7B2F][v8][v5] + (id.ax[this.ar * 0x53AD7B2F][v6][v7] + id.ax[this.ar * 0x53AD7B2F][v8][v7] + id.ax[this.ar * 0x53AD7B2F][v6][v5]) >> 2, (this.ap * 0xA8F1DE1B << 7) + (v4 << 6), this.aj, this.ad * v2, 0x4A90AB9);
}
public static final void fz(int arg2, int arg3, int arg4) {
try {
ee.fs.bx(kt.jz * 1101813865, arg2, arg3, false);
return;
}
catch(RuntimeException v2) {
StringBuilder v3 = new StringBuilder();
v3.append("hj.fz(");
v3.append(')');
throw lx.al(((Throwable)v2), v3.toString());
}
}
}
| true
|
8453f4a357d36b0cc5a9b7dc778a58a51b2a8a4a
|
Java
|
pranudech/MJURescueWeb
|
/MJURescueSystem/src/com/itsci/mjurescue/staff/web/removespecifications/SpecificationsBean.java
|
UTF-8
| 3,250
| 1.796875
| 2
|
[] |
no_license
|
package com.itsci.mjurescue.staff.web.removespecifications;
import java.util.Vector;
public class SpecificationsBean {
private int FormStaffID;
private String numberOperations;
private String receiveNotification;
private String accidentLocation;
private String statusCase;
private String licensePlate;
private String date;
private String listOperationsOfficer;
private String NotificationID;
private String ReprotID;
Vector<SpecificationsBean> specificationsBeans = new Vector<SpecificationsBean>();
public SpecificationsBean() {
super();
}
public SpecificationsBean(int formStaffID, String numberOperations, String receiveNotification,
String accidentLocation, String statusCase, String licensePlate, String date, String listOperationsOfficer,
String notificationID, String reprotID, Vector<SpecificationsBean> specificationsBeans) {
super();
FormStaffID = formStaffID;
this.numberOperations = numberOperations;
this.receiveNotification = receiveNotification;
this.accidentLocation = accidentLocation;
this.statusCase = statusCase;
this.licensePlate = licensePlate;
this.date = date;
this.listOperationsOfficer = listOperationsOfficer;
NotificationID = notificationID;
ReprotID = reprotID;
this.specificationsBeans = specificationsBeans;
}
public int getFormStaffID() {
return FormStaffID;
}
public void setFormStaffID(int formStaffID) {
FormStaffID = formStaffID;
}
public String getNumberOperations() {
return numberOperations;
}
public void setNumberOperations(String numberOperations) {
this.numberOperations = numberOperations;
}
public String getReceiveNotification() {
return receiveNotification;
}
public void setReceiveNotification(String receiveNotification) {
this.receiveNotification = receiveNotification;
}
public String getAccidentLocation() {
return accidentLocation;
}
public void setAccidentLocation(String accidentLocation) {
this.accidentLocation = accidentLocation;
}
public String getStatusCase() {
return statusCase;
}
public void setStatusCase(String statusCase) {
this.statusCase = statusCase;
}
public String getLicensePlate() {
return licensePlate;
}
public void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getListOperationsOfficer() {
return listOperationsOfficer;
}
public void setListOperationsOfficer(String listOperationsOfficer) {
this.listOperationsOfficer = listOperationsOfficer;
}
public String getNotificationID() {
return NotificationID;
}
public void setNotificationID(String notificationID) {
NotificationID = notificationID;
}
public String getReprotID() {
return ReprotID;
}
public void setReprotID(String reprotID) {
ReprotID = reprotID;
}
public Vector<SpecificationsBean> getSpecificationsBeans() {
return specificationsBeans;
}
public void setSpecificationsBeans(Vector<SpecificationsBean> specificationsBeans) {
this.specificationsBeans = specificationsBeans;
}
}
| true
|
2611ca3a421ee840d94681faed544bc2f8760b64
|
Java
|
stetter/dh_art_-_museum
|
/app/src/main/java/com/stetter/dhartmuseum/service/MyFirebaseMessagingService.java
|
UTF-8
| 2,937
| 2.25
| 2
|
[] |
no_license
|
package com.stetter.dhartmuseum.service;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.stetter.dhartmuseum.R;
import com.stetter.dhartmuseum.login.LoginActivity;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived( remoteMessage );
sendMyNotification( remoteMessage.getNotification().getBody() );
}
private void sendMyNotification(String message) {
//On click of notification it redirect to this Activity
Intent intent = new Intent( this, LoginActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_ONE_SHOT );
Uri soundUri = RingtoneManager.getDefaultUri( RingtoneManager.TYPE_NOTIFICATION );
NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE );
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH );
// Configure the notification channel.
notificationChannel.setDescription( "Channel description" );
notificationChannel.enableLights( true );
notificationChannel.setLightColor( Color.RED );
notificationChannel.setVibrationPattern( new long[]{0, 1000, 500, 1000} );
notificationChannel.enableVibration( true );
notificationManager.createNotificationChannel( notificationChannel );
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder( this, NOTIFICATION_CHANNEL_ID );
notificationBuilder.setAutoCancel( true )
.setDefaults( Notification.DEFAULT_ALL )
.setWhen( System.currentTimeMillis() )
.setTicker( "funcionando 100%" )
//.setPriority(Notification.PRIORITY_MAX)
.setContentTitle( "Cloud Notifications" )
.setContentText( message )
.setContentInfo( "ObjectInfo" )
.setSmallIcon( R.mipmap.ic_launcher );
notificationManager.notify(/*notification id*/1, notificationBuilder.build() );
}
}
| true
|
3513b6ada144a184e048642037c0e77c68c9d3c2
|
Java
|
chodkos/event-manager
|
/src/main/java/pl/training/backend/model/MeetingRepository.java
|
UTF-8
| 221
| 1.5
| 2
|
[] |
no_license
|
package pl.training.backend.model;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Created by Raynor on 2017-07-26.
*/
public interface MeetingRepository extends JpaRepository<Meeting, Long> {
}
| true
|
51e9125d77d429cdd615b486b9dc871cbe49df7f
|
Java
|
Marveliu/marvel-springboot
|
/marvel-web/src/main/java/com/marveliu/web/dao/entity/Resource.java
|
UTF-8
| 1,647
| 2.234375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.marveliu.web.dao.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.marveliu.web.component.domain.AbstractModel;
import lombok.Data;
import lombok.ToString;
import org.hibernate.annotations.Target;
import javax.persistence.*;
import java.util.List;
/**
* @Author: Marveliu
* @Date: 2018/9/24 下午4:57
* @Description:
**/
@Data
@Entity
@ToString(exclude = {"roles"})
public class Resource extends AbstractModel<Integer> {
@Id
@GeneratedValue
private Integer id;
/**
* 名称
*/
private String name;
/**
* 编码
*/
private String code;
/**
* 访问方式
*/
@Column(columnDefinition = "varchar(10) comment '访问方式 GET POST PUT DELETE PATCH'")
private String method;
/**
* 资源路径
*/
@Column(columnDefinition = "varchar(100) comment '资源路径'")
private String url;
/**
* 种类
*/
@Column(columnDefinition = "smallint(4) comment '类型 1:菜单menu 2:资源element(rest-api) 3:资源分类'")
private Integer type;
/**
* 父编号
*/
private Long parentId;
/**
* 能否使用
*/
private Boolean available = Boolean.FALSE;
@JsonIgnore
@Target(Role.class)
@ManyToMany(mappedBy = "resources")
private List<Role> roles;
public String getUrlWithMethod() {
return url + "==" + method;
}
public String getRolesName() {
StringBuilder rs = new StringBuilder();
for (Role role : getRoles()) {
rs.append(role.getId() + ",");
}
return rs.toString();
}
}
| true
|
ab4b9b0b66d2cb682b82cfc6c6a8f8f83e5d80ec
|
Java
|
0Gz2bflQyU0hpW/portal
|
/falcon/src/main/java/com/weibo/dip/data/platform/falcon/kafka/metric/ZookeeperOperation.java
|
UTF-8
| 7,900
| 2.34375
| 2
|
[] |
no_license
|
package com.weibo.dip.data.platform.falcon.kafka.metric;
import com.weibo.dip.data.platform.commons.util.GsonUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
public class ZookeeperOperation implements Closeable{
private static final Logger LOGGER = LoggerFactory.getLogger(ZookeeperOperation.class);
private Map<String, Map<String, String>> topicPartitionMap = new Hashtable<>();
private ZooKeeper zk;
private Watcher watcher = new Watcher() {
@Override
public void process(WatchedEvent event) {}
};
public ZookeeperOperation(String zkAddress){
try {
zk = new ZooKeeper(zkAddress, 4000, watcher);
} catch (IOException e) {
LOGGER.error("can not connect Zookeeper: {}", ExceptionUtils.getFullStackTrace(e));
}
}
public Set<String> domainNames2ips(Set<String> domainNames) throws UnknownHostException {
Set<String> ips = new HashSet<>();
for(String domainName : domainNames){
ips.add(InetAddress.getByName(domainName).getHostAddress());
}
return ips;
}
public Set<String> getAllBrokerIps() throws InterruptedException, UnknownHostException, KeeperException {
Set<String> allIds = getAllBrokerIds();
Set<String> hosts = getHosts(allIds);
return domainNames2ips(hosts);
}
public Set<String> getBrokerIps(String topic) throws InterruptedException, UnknownHostException, KeeperException {
Set<String> brokerIds = getBrokerIdsOfTopic(topic);
Set<String> hosts = getHosts(brokerIds);
return domainNames2ips(hosts);
}
public String getHost(String brokerId) throws KeeperException, InterruptedException {
String zkPath = "/brokers/ids/" + brokerId;
String hostname = null;
if(zk.exists(zkPath, watcher) != null){
String brokerStr = new String(zk.getData(zkPath, watcher, new Stat()));
Map<String, Object> brokerMap = GsonUtil.fromJson(brokerStr, HashMap.class);
hostname = (String)brokerMap.get("host");
}
return hostname;
}
public Set<String> getHosts(Set<String> brokerIds) throws KeeperException, InterruptedException {
Set<String> hosts = new HashSet<>();
for (String brokerId: brokerIds) {
String hostname = getHost(brokerId);
if(hostname == null){
LOGGER.warn("could not found the hostname of broker, BrokerId={}", brokerId);
}else{
hosts.add(hostname);
}
}
return hosts;
}
public Set<String> getBrokerIdsOfTopic(String topicName) throws KeeperException, InterruptedException {
String zkPath = "/brokers/topics/" + topicName + "/partitions";
Set<String> brokerIds = new HashSet<>();
if(zk.exists(zkPath, watcher) != null) {
List<String> partitions = zk.getChildren(zkPath, watcher);
for (String partition : partitions) {
String state = new String(zk.getData(zkPath + "/" + partition + "/state", watcher, new Stat()));
Double leader = (Double) GsonUtil.fromJson(state, HashMap.class).get("leader");
brokerIds.add(String.valueOf(leader.intValue()));
}
}
return brokerIds;
}
public Set<String> getAllTopics() throws KeeperException, InterruptedException {
String zkPath = "/brokers/topics";
Set<String> topics = new HashSet<>();
if(zk.exists(zkPath, watcher) != null) {
List<String> topicsList = zk.getChildren(zkPath, watcher);
topics.addAll(topicsList);
}
return topics;
}
public Set<String> getAllBrokerIds() throws KeeperException, InterruptedException {
String zkPath = "/brokers/ids";
Set<String> ids = new HashSet<>();
if(zk.exists(zkPath, watcher) != null) {
List<String> idsList = zk.getChildren(zkPath, watcher);
ids.addAll(idsList);
}
return ids;
}
public List<String> getConsumerGroups() throws KeeperException, InterruptedException {
String zkPath = "/consumers";
List<String> consumers = new ArrayList<>();
if(zk.exists(zkPath, watcher) != null) {
consumers = zk.getChildren(zkPath, watcher);
}
return consumers;
}
public List<String> getTopicsOfConsumer(String consumerGroup) throws KeeperException, InterruptedException {
String zkPath = "/consumers" + "/" + consumerGroup + "/offsets";
List<String> topicsOfConsumer = new ArrayList<>();
if(zk.exists(zkPath, watcher) == null){
LOGGER.warn("could not found topics of consumer, consumer={}", consumerGroup);
}else{
topicsOfConsumer = zk.getChildren(zkPath, watcher);
}
return topicsOfConsumer;
}
public List<String> getPartitionsOfTopic(String consumerGroup, String topic) throws KeeperException, InterruptedException {
String zkPath = "/consumers" + "/" + consumerGroup + "/offsets" + "/" + topic;
List<String> partitionsOfTopic = new ArrayList<>();
if(zk.exists(zkPath, watcher) != null) {
partitionsOfTopic = zk.getChildren(zkPath, watcher);
}
return partitionsOfTopic;
}
public Long getPartitionInfo(String consumerGroup, String topic, String partitionId) throws KeeperException, InterruptedException {
String zkPath = "/consumers" + "/" + consumerGroup + "/offsets" + "/" + topic + "/" + partitionId;
Long offset = null;
if(zk.exists(zkPath, watcher) != null) {
Stat stat = new Stat();
offset = new Long(new String(zk.getData(zkPath, watcher, stat)));
//若offset最近一次修改超过7天,则认为该ConsumerGroup失效
if (stat.getMtime() < (System.currentTimeMillis() - 7 * 24 * 3600 * 1000)) {
return null;
}
}
return offset;
}
//key:partition, value:ip
public Map<String, String> getLeaderPartitionsOfTopic(String topicName) throws KeeperException, InterruptedException, UnknownHostException {
if(!topicPartitionMap.containsKey(topicName)) {
String zkPath = "/brokers/topics/" + topicName + "/partitions";
if(zk.exists(zkPath, watcher) != null) {
List<String> partitions = zk.getChildren(zkPath, watcher);
Map<String, String> leaderPartitions = new HashMap<>();
for (String partition : partitions) {
String state = new String(zk.getData(zkPath + "/" + partition + "/state", watcher, new Stat()));
Double leader = (Double) GsonUtil.fromJson(state, HashMap.class).get("leader");
String brokerId = String.valueOf(leader.intValue());
String ip = InetAddress.getByName(getHost(brokerId)).getHostAddress();
leaderPartitions.put(partition, ip);
}
topicPartitionMap.put(topicName, leaderPartitions);
}
}
return topicPartitionMap.get(topicName);
}
@Override
public void close() {
try {
if(zk != null) {
zk.close();
}
} catch (InterruptedException e) {
LOGGER.error("close Zookeeper error: {}", ExceptionUtils.getStackTrace(e));
}
}
}
| true
|
cbb037b4181c60d6a80f5846a04b07235cd1147c
|
Java
|
zhoyuhao/dzw
|
/src/main/java/com/accp/action/zyh/zyhServiceAction.java
|
UTF-8
| 3,780
| 2.1875
| 2
|
[] |
no_license
|
package com.accp.action.zyh;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
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 com.accp.biz.zyh.*;
import com.accp.pojo.Goods;
import com.accp.vo.zyh.zyhService_vo;
import com.accp.vo.zyh.zyhServicedetailed_vo;
import com.github.pagehelper.PageInfo;
@RestController
@RequestMapping("zyhServiceAction/api")
public class zyhServiceAction {
@Autowired
private zyhServiceBiz biz;
//
/**根据id修改维修状态
*
* @param statuc
* @param id
* @return
*/
@PutMapping("updateByWidToStatuc/{statuc}/{id}/{date}/{gs}/{gsf}")
public int updateByWidToStatuc(@PathVariable Integer statuc,@PathVariable String id,
@PathVariable String date,@PathVariable Float gs,@PathVariable Integer gsf) {
return biz.updateByWidToStatuc(statuc, id,this.parseDate2(date),gs,gsf);
}
/**客户返工添加项目
*
* @param list
* @return
*/
@PostMapping("serivceDetailedAdd")
public int serivceDetailedAdd(@RequestBody List<zyhServicedetailed_vo> list) {
return biz.serivceDetailedAdd(list);
}
/**查看为维修单的状态
*
* @return
*/
@GetMapping("queryStatucBy1Or2/{wcarid}/{statdate}/{enedate}/{n}/{s}/{statuc}/{statuc2}")
public PageInfo<zyhService_vo> queryStatucBy1Or2(@PathVariable String wcarid,@PathVariable String statdate,
@PathVariable String enedate,@PathVariable Integer n,
@PathVariable Integer s,@PathVariable Integer statuc,
@PathVariable Integer statuc2){
wcarid="null".equals(wcarid)?null:wcarid;
statdate="null".equals(statdate)?null:statdate;
enedate="null".equals(enedate)?null:enedate;
if(statdate!=null) {
statdate=this.parseDate(statdate);
enedate=this.parseDate(enedate);
}
return biz.queryStatucBy1Or2(wcarid,statdate,enedate,n,s,statuc, statuc2) ;
}
/**查看有几种车型的商品
*
* @return
*/
@GetMapping("queryByCarType")
public List<Goods> queryByCarType(){
return biz.queryByCarType();
}
/**时间转换
*
* @param val
* @return
* @throws ParseException
*/
public String parseDate(String val){
val = val.replace("GMT", "").replaceAll("\\(.*\\)", "");
//将字符串转化为date类型,格式2016-10-12
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy hh:mm:ss z",Locale.ENGLISH);
Date dateTrans;
try {
dateTrans = format.parse(val);
return new SimpleDateFormat("yyyy-MM-dd").format(dateTrans);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String parseDate2(String val){
val = val.replace("GMT", "").replaceAll("\\(.*\\)", "");
//将字符串转化为date类型,格式2016-10-12
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z",Locale.ENGLISH);
Date dateTrans;
try {
dateTrans = format.parse(val);
return new SimpleDateFormat("yyyy-MM-dd HH:mm").format(dateTrans);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
| true
|
d84badda0153df130aca84e9cfe04fa29aa1e1da
|
Java
|
RagavanPV/HotelManagementSystemJDBC
|
/src/main/java/com/ragavan/dao/FoodTypeDAO.java
|
UTF-8
| 2,271
| 2.578125
| 3
|
[] |
no_license
|
package com.ragavan.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import com.ragavan.model.FoodType;
import com.ragavan.util.ConnectionUtil;
public class FoodTypeDAO {
JdbcTemplate jdbcTemplate = ConnectionUtil.getJdbcTemplate();
public int save(final FoodType type) {
final String sql = "insert into food_types(type,time_start,time_end) values(?,?,?)";
final Object[] params = { type.getType(), type.getTimeStart(), type.getTimeEnd() };
return jdbcTemplate.update(sql, params);
}
public int update(final FoodType type) {
final String sql = "update food_types set type=?,time_start=?,time_end=? where id=?";
final Object[] params = { type.getType(), type.getTimeStart(), type.getTimeEnd(), type.getId() };
return jdbcTemplate.update(sql, params);
}
public int updateByType(final FoodType type) {
final String sql = "update food_types set time_start=?,time_end=? where type=?";
final Object[] params = { type.getTimeStart(), type.getTimeEnd(), type.getType() };
return jdbcTemplate.update(sql, params);
}
public int delete(final String type) {
final String sql = "delete from food_types where type=?";
return jdbcTemplate.update(sql, type);
}
public List<FoodType> list() {
final String sql = "select id,type,time_start,time_end from food_types";
return jdbcTemplate.query(sql, (rs, rowNum) -> fetchData(rs));
}
public FoodType listByType(String type) {
final String sql = "select id,type,time_start,time_end from food_types where type=?";
Object[] params = { type };
return jdbcTemplate.queryForObject(sql, params, (rs, rowNum) -> fetchData(rs));
}
public List<FoodType> listCurrentType() {
final String sql = "select id,type,time_start,time_end from food_types where curtime() between time_start and time_end";
return jdbcTemplate.query(sql, (rs, rowNum) -> fetchData(rs));
}
private FoodType fetchData(ResultSet rs) throws SQLException {
final FoodType foodType = new FoodType();
foodType.setId(rs.getInt("id"));
foodType.setType(rs.getString("type"));
foodType.setTimeStart(rs.getTime("time_start").toLocalTime());
foodType.setTimeEnd(rs.getTime("time_end").toLocalTime());
return foodType;
}
}
| true
|
ea2c67f68b40863e229ba7914a126070551d436c
|
Java
|
melhindi/java_client-server_template
|
/src/main/java/clientServer_template/TCPServer.java
|
UTF-8
| 1,188
| 3.0625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package clientServer_template;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TCPServer extends Thread {
private AbstractHandler handler;
private ServerSocket serverSocket;
private ExecutorService pool;
public TCPServer(int port, Class<?> handlerClass) throws Exception {
handler = (AbstractHandler) handlerClass.newInstance();
serverSocket = new ServerSocket(port);
pool = Executors.newCachedThreadPool();
}
public TCPServer(int port, Object handlerObject) throws IOException {
handler = (AbstractHandler) handlerObject;
serverSocket = new ServerSocket(port);
pool = Executors.newCachedThreadPool();
}
public void run() {
try {
while (true) {
Socket socket = serverSocket.accept();
handler.handle(socket, pool);
}
} catch (SocketException e) {
// When stopServer() is called, a SocketException is thrown
} catch (Exception e) {
System.err.println(e);
}
}
public void stopServer() {
try {
serverSocket.close();
} catch (IOException e) {
}
pool.shutdown();
}
}
| true
|
03c0b6008a144f3caa90045f0ec9a091a1eb0c35
|
Java
|
heilexuan/Selenium-Auto-Test
|
/Source/src/com/excelsh/core/common/PropertiesManager.java
|
UTF-8
| 772
| 2.296875
| 2
|
[] |
no_license
|
/**
*
*/
package com.excelsh.core.common;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
/**
* @author loki
*
*/
public class PropertiesManager {
public Properties loadProperties(String straPropFilePath,String strapropName){
//InputStream input = this.getClass().;
Properties prop = new Properties();
return prop;
}
public static void main(String[] args) throws FileNotFoundException, IOException {
PropManager propManager = new PropManager();
propManager.init("E:/uts3/SeleniumTest/Source/properties/main.properties");
String strFrontEndMaker = propManager.getPropValue("LOGIN.PROPERTIES", "FrontEnd.maker.username");
System.out.println(strFrontEndMaker);
}
}
| true
|
e83bc98cce96e180cf19663c67d54c8bf5d07ce2
|
Java
|
tobias-jenkner/org.eclipse.ece2011.roguebundles
|
/org.eclipse.ece2011.roguebundles.bundlejail/src/org/eclipse/ece2011/roguebundles/bundlejail/resolverhook/BundleJailResolverHookFactory.java
|
UTF-8
| 612
| 1.898438
| 2
|
[] |
no_license
|
package org.eclipse.ece2011.roguebundles.bundlejail.resolverhook;
import java.util.Collection;
import org.osgi.framework.hooks.resolver.ResolverHook;
import org.osgi.framework.hooks.resolver.ResolverHookFactory;
import org.osgi.framework.wiring.BundleRevision;
/**
* {@link ResolverHookFactory} that creates {@link BundleJailResolverHook}
* instances.
*
* @author tobias.jenkner
*/
public class BundleJailResolverHookFactory implements ResolverHookFactory {
@Override
public ResolverHook begin(Collection<BundleRevision> triggers) {
return new BundleJailResolverHook();
}
}
| true
|
533c6370b127b9936cfca2b3f2ef020614619de8
|
Java
|
chihobear/OutBreak
|
/src/model/LevelItem.java
|
UTF-8
| 779
| 2.796875
| 3
|
[] |
no_license
|
package model;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Observable;
import javafx.scene.Node;
/**
* Represents a single item in the level.
*
* @author Chenghao Xiong
*
*/
public abstract class LevelItem extends Observable {
// Shapes to represent the particular thing
// For example, a staircase might consist of multiple squares
protected transient List<Node> components;
protected LevelItem(Node... components) {
Objects.requireNonNull(components);
this.components = Arrays.asList(components);
}
protected LevelItem(List<Node> components) {
Objects.requireNonNull(components);
this.components = components;
}
public List<Node> getComponents() {
return components;
}
}
| true
|
25587dd80f7ba99b6dfaa4c0d02c24764a6d10c1
|
Java
|
EduardoGit-1/ServerSocketProject
|
/Server/src/project/payload/PresencesAndMessagesResponse.java
|
UTF-8
| 1,070
| 2.140625
| 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 project.payload;
import java.util.ArrayList;
import project.model.Message;
/**
*
* @author Eduardo
*/
public class PresencesAndMessagesResponse {
private String[] presences;
private ArrayList<Message> messages;
public PresencesAndMessagesResponse() {
}
public PresencesAndMessagesResponse(String[] presences, ArrayList<Message> messages) {
this.presences = presences;
this.messages = messages;
}
public String[] getPresences() {
return presences;
}
public void setPresences(String[] presences) {
this.presences = presences;
}
public ArrayList<Message> getMessages() {
return messages;
}
public void setMessages(ArrayList<Message> messages) {
this.messages = messages;
}
}
| true
|
6bd3b7db2c68bbfa233c013ce9c75ce67d401f88
|
Java
|
lf1175914768/redis-java
|
/src/main/java/com/qb/utils/JedisService.java
|
UTF-8
| 406
| 1.8125
| 2
|
[] |
no_license
|
package com.qb.utils;
/**
* @author Liufeng
* Created on 2018年9月6日 下午11:10:56
*/
public interface JedisService {
/**
* The default password.
*/
String DEFAULT_PASSWORD = "xyyyhtl12";
/**
* The default port.
*/
int DEFAULT_PORT = 6379;
/**
* The default host.
*/
String DEFAULT_HOST = "localhost";
/**
* The default timeout.
*/
int DEFAULT_TIMEOUT = 10000;
}
| true
|
d16469ab360d630bba6f2bf7e9db010861ab108f
|
Java
|
loicbarrault/MANY
|
/src/edu/lium/mt/MANY.java
|
UTF-8
| 13,671
| 1.695313
| 2
|
[] |
no_license
|
/*
* Copyright 2009 Loic BARRAULT.
* Portions Copyright BBN and UMD (see LICENSE_TERP.txt).
* Portions Copyright 1999-2008 CMU (see LICENSE_SPHINX4.txt).
* All Rights Reserved. Use is subject to license terms.
*
* See the file "LICENSE.txt" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*
*/
package edu.lium.mt;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Logger;
import com.bbn.mt.terp.TERalignment;
import com.bbn.mt.terp.TERalignmentCN;
import com.bbn.mt.terp.TERoutput;
import com.bbn.mt.terp.TERtask;
import com.bbn.mt.terp.TERutilities;
import edu.cmu.sphinx.util.props.Configurable;
import edu.cmu.sphinx.util.props.ConfigurationManager;
import edu.cmu.sphinx.util.props.PropertyException;
import edu.cmu.sphinx.util.props.PropertySheet;
import edu.cmu.sphinx.util.props.S4Component;
import edu.cmu.sphinx.util.props.S4Double;
import edu.cmu.sphinx.util.props.S4Integer;
import edu.cmu.sphinx.util.props.S4String;
import edu.lium.decoder.Graph;
import edu.lium.decoder.MANYcn;
import edu.lium.decoder.TokenPassDecoder;
public class MANY implements Configurable
{
private String name;
private Logger logger;
private TokenPassDecoder decoder = null;
/** The property that defines the decoder component. */
@S4Component(type = TokenPassDecoder.class)
public final static String PROP_DECODER = "decoder";
/** The property that defines the output filename */
@S4String(defaultValue = "many.output")
public final static String PROP_OUTPUT_FILE = "output";
/** The property that defines the TERp parameters filename */
@S4String(defaultValue = "terp.params")
public final static String PROP_TERP_PARAMS_FILE = "terpParams";
/** The property that defines the reference filename */
@S4String(defaultValue = "")
public final static String PROP_REFERENCE_FILE = "reference";
/** The property that defines the hypotheses filenames */
@S4String(defaultValue = "")
public final static String PROP_HYPOTHESES_FILES = "hypotheses";
/** The property that defines the hypotheses scores filenames */
@S4String(defaultValue = "")
public final static String PROP_HYPS_SCORES_FILES = "hyps-scores";
/** The property that defines the TERp costs
@S4String(defaultValue = "1.0 1.0 1.0 1.0 1.0 0.0 1.0")
public final static String PROP_COSTS = "costs";
*/
@S4Double(defaultValue = 1.0)
public final static String PROP_INS_COST = "insertion";
@S4Double(defaultValue = 1.0)
public final static String PROP_DEL_COST = "deletion";
@S4Double(defaultValue = 1.0)
public final static String PROP_SUB_COST = "substitution";
@S4Double(defaultValue = 0.0)
public final static String PROP_MATCH_COST = "match";
@S4Double(defaultValue = 1.0)
public final static String PROP_SHIFT_COST = "shift";
@S4Double(defaultValue = 1.0)
public final static String PROP_STEM_COST = "stem";
@S4Double(defaultValue = 1.0)
public final static String PROP_SYN_COST = "synonym";
/** The property that defines the system priors */
@S4String(defaultValue = "")
public final static String PROP_PRIORS = "priors";
/** The property that defines the shift constraint*/
@S4String(defaultValue = "")
public final static String PROP_SHIFT_CONSTRAINT = "shift-constraint";
/** The property that defines the wordnet database location */
@S4String(defaultValue = "")
public final static String PROP_WORD_NET = "wordnet";
/** The property that defines the stop word list filename */
@S4String(defaultValue = "")
public final static String PROP_STOP_LIST = "shift-word-stop-list";
/** The property that defines the paraphrase-table filename */
@S4String(defaultValue = "")
public final static String PROP_PARAPHRASES = "paraphrases";
/** The property that defines the evaluation method (can be MIN, MEAN or MAX) */
@S4String(defaultValue = "MEAN")
public final static String PROP_METHOD = "method";
/** The property that defines the number of threads used */
@S4Integer(defaultValue = 0)
public final static String PROP_MULTITHREADED = "multithread";
private String outfile;
private String terpParamsFile;
private String hypotheses;
private String hypotheses_scores;
//private String terp_costs;
private float ins, del, sub, match, shift, stem, syn;
private String priors_str;
private boolean mustReWeight = false;
private String shift_constraint;
private String wordnet;
private String shift_word_stop_list;
private String paraphrases;
private int nb_threads;
private boolean allocated;
private String[] hyps = null, hyps_scores = null;
private float[] costs = null;
private float[] priors = null;
public boolean DEBUG = false;
/**
* Main method of this MTSyscomb tool.
*
* @param argv
* argv[0] : config.xml
*/
public static void main(String[] args)
{
if (args.length < 1 || (args.length == 2 && ("--debug".equals(args[1])==false)) || args.length > 2)
{
MANY.usage();
System.exit(0);
}
ConfigurationManager cm;
MANY syscomb;
try
{
URL url = new File(args[0]).toURI().toURL();
cm = new ConfigurationManager(url);
syscomb = (MANY) cm.lookup("MANY");
if(args.length == 2) syscomb.DEBUG = true;
}
catch (IOException ioe)
{
System.err.println("I/O error during initialization: \n " + ioe);
return;
}
catch (PropertyException e)
{
System.err.println("Error during initialization: \n " + e);
return;
}
if (syscomb == null)
{
System.err.println("Can't find MANY" + args[0]);
return;
}
syscomb.allocate();
syscomb.combine();
syscomb.deallocate();
}
private void allocate()
{
if(!allocated)
{
allocated = true;
System.err.println("hypos = "+hypotheses);
hyps = hypotheses.split("\\s+");
hyps_scores = hypotheses_scores.split("\\s+");
//costs = terp_costs.split("\\s+");
costs = new float[7];
costs[0] = del;
costs[1] = stem;
costs[2] = syn;
costs[3] = ins;
costs[4] = sub;
costs[5] = match;
costs[6] = shift;
String[] lst = priors_str.split("\\s+");
priors = new float[lst.length];
// System.err.println("priors : ");
for (int i = 0; i < lst.length; i++)
{
// System.err.print(" >"+lst[i]+"< donne ");
priors[i] = Float.parseFloat(lst[i]);
// System.err.println(" >"+priors_lst[i]+"< ");
}
}
}
private void deallocate()
{
allocated = false;
hyps = hyps_scores = null;
costs = null;
priors = null;
decoder.deallocate();
}
public MANY()
{
}
public void combine()
{
int nbSentences = 0;
ArrayList<String> lst = null;
ArrayList<String> lst_sc = null;
String backbone = null;
String backbone_scores = null;
int[] hyps_idx;
ArrayList<TERoutput> outputs = new ArrayList<TERoutput>();
ArrayList<TERtask> tasks = new ArrayList<TERtask>();
for (int i = 0; i < hyps.length; i++)
{
// 1. Generate CNs with system i as backbone for each sentence
// 1.1 Init variables
lst = new ArrayList<String>();
lst.addAll(Arrays.asList(hyps));
lst.remove(i);
lst_sc = new ArrayList<String>();
lst_sc.addAll(Arrays.asList(hyps_scores));
lst_sc.remove(i);
backbone = hyps[i];
backbone_scores = hyps_scores[i];
logger.info("run : " + backbone + " is the reference ....");
logger.info("run : " + TERutilities.join(" ", lst) + " are the hypotheses ....");
hyps_idx = new int[lst.size()];
for (int idx = 0, pos = 0; idx < hyps.length; idx++)
{
if (idx != i)
hyps_idx[pos++] = idx;
}
// 1.2 Generate terp.params file
String suffix = ".thread" + i;
TERutilities.generateParams(terpParamsFile + suffix, outfile + suffix, backbone, backbone_scores, i, lst, lst_sc, hyps_idx,
costs, priors, shift_constraint, wordnet, shift_word_stop_list, paraphrases);
logger.info("TERp params file generated ...");
tasks.add(new TERtask(i, terpParamsFile + suffix, outfile + ".cn." + i));
}
if (nb_threads > 1)
{
System.err.println("Launching in multithreaded : nb_threads = " + nb_threads);
ExecutorService executor = Executors.newFixedThreadPool(nb_threads);
List<Future<TERoutput>> results = null;
try
{
results = executor.invokeAll(tasks);
}
catch (InterruptedException ie)
{
System.err.println("A task had a problem : " + ie.getMessage());
ie.printStackTrace();
System.exit(-1);
}
executor.shutdown(); // we don't need executor anymore
for (int i = 0; i < results.size(); ++i)
{
try
{
outputs.add(results.get(i).get());
}
catch (InterruptedException ie)
{
System.err.println("The task " + i + " had a problem : " + ie.getMessage());
ie.printStackTrace();
System.exit(-1);
}
catch (ExecutionException ee)
{
System.err.println("The task " + i + " had a problem ... : " + ee.getMessage());
ee.printStackTrace();
System.exit(-1);
}
}
}
else
{
for (int i = 0; i < hyps.length; ++i) // foreach backbone
{
logger.info("run : launching TERp for system " + i + " as backbone ...");
TERoutput output = null;
try
{
output = tasks.get(i).call();
}
catch (Exception e)
{
e.printStackTrace();
}
if (output == null)
{
logger.info("output is null ... exiting !");
System.exit(-1);
}
// else { logger.info("we have an output ...");}
outputs.add(output);
}
}
// Build the lattice and decode
// init output
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
if (outfile != null)
{
try
{
bw = new BufferedWriter(new FileWriter(outfile));
}
catch (IOException ioe)
{
System.err.println("I/O erreur durant creation output file " + String.valueOf(outfile) + " " + ioe);
}
}
// init decoder
try
{
decoder.allocate();
}
catch (IOException e)
{
e.printStackTrace();
}
nbSentences = outputs.get(0).getResults().size();
ArrayList<ArrayList<MANYcn>> all_cns = new ArrayList<ArrayList<MANYcn>>();
for (int i = 0; i < nbSentences; i++) // foreach sentences
{
all_cns.add(new ArrayList<MANYcn>());
// build a lattice with all the results
ArrayList<MANYcn> cns = new ArrayList<MANYcn>();
for (int j = 0; j < outputs.size(); j++)
{
TERalignment al = outputs.get(j).getResults().get(i);
if (al == null)
{
logger.info("combine : empty result for system " + j + "... continuing!");
all_cns.get(i).add(null);
}
else if (al instanceof TERalignmentCN)
{
MANYcn cn = new MANYcn(((TERalignmentCN) al).full_cn, ((TERalignmentCN) al).full_cn_scores, ((TERalignmentCN) al).full_cn_sys);
all_cns.get(i).add(cn);
//if we have to re-weight, then do it !
if(mustReWeight)
{
MANYcn.changeSysWeights(all_cns.get(i), priors);
if(DEBUG) MANYcn.outputFullCNs(all_cns.get(i),"output.fullcn.reweight."+i);
cns = MANYcn.fullCNs2CNs(all_cns.get(i));
if(DEBUG) MANYcn.outputCNs(cns,"output.cn.reweight."+i);
}
}
else
{
logger.info("combine : not a confusion network ... aborting !");
System.exit(0);
}
}
if (all_cns.get(i).isEmpty())
{
logger.info("combine : no result for sentence " + i + "... skipping!");
try
{
bw.newLine();
}
catch (IOException ioe)
{
ioe.printStackTrace();
System.exit(0);
}
continue;
}
if(i%100==0) { logger.info("combine : decoding graph for sentence "+i); }
Graph g = new Graph(cns, priors);
if(DEBUG) g.printHTK("graph.htk_"+i+".txt");
// Then we can decode this graph ...
try
{
decoder.decode(i, g, bw);
}
catch (IOException ioe)
{
ioe.printStackTrace();
System.exit(0);
}
}
try
{
bw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
// @Override
public String getName()
{
return name;
}
@Override
public void newProperties(PropertySheet ps) throws PropertyException
{
logger = ps.getLogger();
// files
outfile = ps.getString(PROP_OUTPUT_FILE);
hypotheses = ps.getString(PROP_HYPOTHESES_FILES);
hypotheses_scores = ps.getString(PROP_HYPS_SCORES_FILES);
// decode
decoder = (TokenPassDecoder) ps.getComponent(PROP_DECODER);
priors_str = ps.getString(PROP_PRIORS);
if(priors_str.equals("") == false)
mustReWeight = true;
// TERp
terpParamsFile = ps.getString(PROP_TERP_PARAMS_FILE);
//terp_costs = ps.getString(PROP_COSTS);
ins = ps.getFloat(PROP_INS_COST);
del = ps.getFloat(PROP_DEL_COST);
sub = ps.getFloat(PROP_SUB_COST);
match = ps.getFloat(PROP_MATCH_COST);
shift = ps.getFloat(PROP_SHIFT_COST);
stem = ps.getFloat(PROP_STEM_COST);
syn = ps.getFloat(PROP_SYN_COST);
shift_constraint = ps.getString(PROP_SHIFT_CONSTRAINT);
if("relax".equals(shift_constraint.toLowerCase()))
{
wordnet = ps.getString(PROP_WORD_NET);
shift_word_stop_list = ps.getString(PROP_STOP_LIST);
paraphrases = ps.getString(PROP_PARAPHRASES);
}
//Others
nb_threads = ps.getInt(PROP_MULTITHREADED);
}
static String[] usage_ar = {"Usage : ", "java -Xmx8G -cp MANY.jar edu.lium.mt.MANY parameters.xml "};
public static void usage()
{
System.err.println(TERutilities.join("\n", usage_ar));
}
}
| true
|
fbe9a573a2757ae5e288a59b5892be19d8f4b7d7
|
Java
|
aashigupta165/Smart-Class
|
/app/src/main/java/com/education/smartclass/modules/Organisation/fragments/OrganisationProfileFragment.java
|
UTF-8
| 2,586
| 2.125
| 2
|
[] |
no_license
|
package com.education.smartclass.modules.Organisation.fragments;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.os.Handler;
import android.os.StrictMode;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.education.smartclass.R;
import com.education.smartclass.storage.SharedPrefManager;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class OrganisationProfileFragment extends Fragment {
private TextView orgCode, orgName, orgAddress;
private ImageView orgLogo;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_organisation_profile, container, false);
orgLogo = view.findViewById(R.id.org_Logo);
orgName = view.findViewById(R.id.org_Name);
orgCode = view.findViewById(R.id.org_Code);
orgAddress = view.findViewById(R.id.org_Address);
orgName.setText(SharedPrefManager.getInstance(getContext()).getUser().getOrgName());
orgCode.setText("Org's id - " + SharedPrefManager.getInstance(getContext()).getUser().getOrgCode());
orgAddress.setText(SharedPrefManager.getInstance(getContext()).getUser().getOrgAddress());
return view;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT > 8) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url = new URL(SharedPrefManager.getInstance(getContext()).getUser().getOrgLogo());
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
orgLogo.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}, 1000);
}
}
| true
|
4f7e75c5b683ba1e9c6ab9a02ae97269fc4b777e
|
Java
|
NoaBoston/JavaProjects
|
/Yahtzee/src/ScoreKeeping.java
|
UTF-8
| 3,225
| 3.0625
| 3
|
[] |
no_license
|
public class ScoreKeeping
{
public static boolean[][] used(String inputChoiceString, boolean[][] inputUsed, int playerNumber, int numberPlayers, int[] inputDice, int[][] inputPrinting)
{
String lastCase;
int inputChoice = Integer.parseInt(inputChoiceString);
boolean[][] outputUsed;
if (inputChoice == 0)
{
lastCase = PrintingScore.printCategoryChoice(inputPrinting, numberPlayers, inputDice, playerNumber, inputUsed);
inputChoice = Integer.parseInt(lastCase);
}
switch(inputChoice)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
inputUsed[playerNumber][inputChoice - 1] = true;
break;
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
inputUsed[playerNumber][inputChoice + 2] = true;
break;
}
outputUsed = inputUsed;
return outputUsed;
}
public static int[][] scores(int[] inputDie, String inputChoiceString, int[][] inputScore, int playerNumber)
{
//Holder values for bonus and totals
int lowerTotal = 0;
int upperTotal = 0;
int bonus = 0;
//Determines how to score the input die set
int inputChoice;
inputChoice = Integer.parseInt(inputChoiceString);
//Each case is modified to fit the array in the order it is displayed either -1 or +2
switch (inputChoice)
{
//Cases 1-6 all have the same code that is contigent upon the input choice
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
inputScore[playerNumber][inputChoice - 1] = 0;
for (int i = 0; i < 5; i++)
{
if (inputDie[i] == inputChoice)
{
inputScore[playerNumber][inputChoice - 1] = inputScore[playerNumber][inputChoice - 1] + inputChoice;
}
}
break;
//Cases 7, 8, 13 all have the same method
case 7:
case 8:
case 13:
for (int i = 0; i < 5; i++)
{
inputScore[playerNumber][inputChoice + 2] = inputScore[playerNumber][inputChoice + 2] + inputDie[i];
}
break;
case 9:
inputScore[playerNumber][inputChoice + 2] = 25;
break;
case 10:
inputScore[playerNumber][inputChoice + 2] = 30;
break;
case 11:
inputScore[playerNumber][inputChoice + 2] = 40;
break;
case 12:
inputScore[playerNumber][inputChoice + 2] = 50;
break;
}
// Choice 6 = Lower Total w/o bonus
for (int i = 0; i < 6; i++)
{
lowerTotal = lowerTotal + inputScore[playerNumber][i];
}
inputScore[playerNumber][6] = lowerTotal;
// Choice 7 = Bonus if Lower Total is greater than 63
if (lowerTotal >= 63)
{
bonus = 35;
}
inputScore[playerNumber][7] = bonus;
// Choice 8 = Lower Total w/ bonus
if (bonus == 35)
{
inputScore[playerNumber][8] = lowerTotal + bonus;
} else
{
inputScore[playerNumber][8] = lowerTotal;
}
// Choice 16 = Lower Total
inputScore[playerNumber][16] = inputScore[playerNumber][8];
// Choice 17 = Upper Total
for (int i = 9; i < 16; i++)
{
upperTotal = upperTotal + inputScore[playerNumber][i];
}
inputScore[playerNumber][17] = upperTotal;
// Choice 18 = Grand Total
inputScore[playerNumber][18] = inputScore[playerNumber][16] + inputScore[playerNumber][17];
//Returns the entire modified scoresheet
int[][] outputScore = inputScore;
return outputScore;
}
}
| true
|
7128732d9dd04981d9c15419e8ea9293821ac772
|
Java
|
cgarchbold/battle-game
|
/src/soldiers/Barbarian.java
|
UTF-8
| 1,724
| 3.578125
| 4
|
[] |
no_license
|
package soldiers;
import java.awt.Color;
public class Barbarian extends Warrior{
private boolean angry;
//constructor
public Barbarian(boolean ev){
super(ev);
//setting armor to half
setArmor(getArmor()/2);
//set block chance to false
setBlockChance(getBlockChance()/2);
//a barbarian is born not angry
angry=false;
}
//overriding Warriors move
public void moveAction(){
//will move once...
super.standardMove();
//If angry will move again
if(angry)
super.standardMove();
}
//overriding Warriors move
public void takeDamage(int dmg, Soldier dudeWhoHitMe){
//when a warrior takes damage that puts him below half health
if(getHealth()<(getMaxHealth()/2)){
//he becomes angry
angry=true;
//his HealthBar becomes orange
setHealthBarColor(Color.ORANGE);
//doubles his AttackPower (MaxAttackPower= AttackPower*2)
setAttackPower(getMaxAttackPower());
//incoming damage is reduced by half
dmg=dmg/2;
}
//barbarian takes damage like a warrior
super.takeDamage(dmg, dudeWhoHitMe);
//if not dead, he faces the direction of the guy he took damage from
if(!isDead()){
setDirection(getBoard().getDirectionFrom(getMySquare(), dudeWhoHitMe.getMySquare()));
}
}
//overriding Warriors attack
public void attackAction(){
// turn to face square diagonal of him
turn();
//attack that square
super.attackAction();
//turn to face square in front of him
turn(-45);
//attack that square
super.attackAction();
//turn to face the other square diagonal of him
turn(-45);
//attack that square
super.attackAction();
//turn to face the starting direction
turn();
}
}
| true
|
505fac3d348a34fdf56258b005f8e990a8d593fc
|
Java
|
drummduck/allMySchoolStuff
|
/CS4150/CS4150 PS3-2/src/PS3_2/Select.java
|
UTF-8
| 761
| 3.28125
| 3
|
[] |
no_license
|
package PS3_2;
import java.lang.reflect.Array;
public class Select {
public static void main(String[] args) {
int[] A = {2, 5, 7, 22};
int[] B = {7, 8, 9, 14};
System.out.println(find(A, 0, A.length-1, B, 0, B.length-1, 4));
}
public static int find(int[] A, int loA, int hiA, int[] B, int loB, int hiB, int k)
{
if(hiA < loA)
{
return B[k-loA];
}
if(hiB < loB)
{
return A[k-loB];
}
int i = (loA + hiA)/2;
int j = (loB + hiB)/2;
if(A[i] > B[j])
{
if(k <= i+j) return find(A, i, hiA-1, B, loB, hiB, k);
else return find(A, loA, hiA, B, j+1, hiB, k);
}
else
{
if(k <= i+j) return find(A, loA, hiA, B, loB, j-1, k);
else return find(A, i+1, hiA, B, loB, hiB, k);
}
}
}
| true
|
19ad329ea0b6929a57339301c9ed4b42c9a93731
|
Java
|
Evincere/mateu-mdd
|
/mdd-core/src/main/java/io/mateu/mdd/core/app/MDDRunnableAction.java
|
UTF-8
| 228
| 2.078125
| 2
|
[
"Beerware"
] |
permissive
|
package io.mateu.mdd.core.app;
public abstract class MDDRunnableAction extends AbstractAction {
public MDDRunnableAction(String caption) {
super(caption);
}
public abstract void run() throws Throwable;
}
| true
|
9c02a871f532724085e10047b56fb7a536c1805c
|
Java
|
kushan22/Startup-Firstcopy
|
/app/src/main/java/com/socialbuy/firstcopy/adapters/MyCustomPagerAdapter.java
|
UTF-8
| 2,418
| 2.390625
| 2
|
[] |
no_license
|
package com.socialbuy.firstcopy.adapters;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.socialbuy.firstcopy.FactoryproductDetails;
import com.socialbuy.firstcopy.R;
import java.util.ArrayList;
/**
* Created by kushansingh on 02/01/18.
*/
public class MyCustomPagerAdapter extends PagerAdapter {
private Context context;
private ArrayList<String> firstNameList,lastNameList;
private ArrayList<Integer> timeInMinutes;
public MyCustomPagerAdapter(Context context, ArrayList<String> firstNameList, ArrayList<String> lastNameList, ArrayList<Integer> timeInMinutes) {
this.context = context;
this.firstNameList = firstNameList;
this.lastNameList = lastNameList;
this.timeInMinutes = timeInMinutes;
}
@Override
public int getCount() {
return firstNameList.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View v = LayoutInflater.from(context).inflate(R.layout.custom_buyer,container,false);
// TextView textView = v.findViewById(R.id.tvBuyerDetail);
// textView.setText(buyerDetails.get(position));
Typeface typeface = Typeface.createFromAsset(context.getAssets(),"fonts/Raleway-Regular.ttf");
assert v != null;
TextView textView = v.findViewById(R.id.tvBuyerDetail);
textView.setTypeface(typeface);
textView.setText(firstNameList.get(position) + " " + lastNameList.get(position) + " purchased this " + timeInMinutes.get(position) + " minutes ago");
container.addView(v,0);
return v;
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
super.restoreState(state, loader);
}
@Override
public Parcelable saveState() {
return null;
}
}
| true
|
86f7177ce4c99d387d9fbd1f2bd3d552b77b356d
|
Java
|
HHIED/MobileSystemsApp
|
/CleanTheStreet/app/src/main/java/dk/sdu/lahan14/cleanthestreet/Util/User.java
|
UTF-8
| 548
| 2.5
| 2
|
[] |
no_license
|
package dk.sdu.lahan14.cleanthestreet.Util;
/**
* Created by Simon-PC on 21-11-2017.
*/
public class User {
public static int userId;
private int id;
private String name;
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public User(int id, String name) {
this.id = id;
this.name = name;
}
public User(){}
}
| true
|
fe8686681da6715645d7a8da3c6c316356983f99
|
Java
|
84EH-FHJ4-2K5L/INT8-CL1N-GT42
|
/main/java/gregtech/api/food/FoodValues.java
|
UTF-8
| 1,504
| 2.8125
| 3
|
[] |
no_license
|
package gregtech.api.food;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
public class FoodValues
{
public final int hunger;
public final float saturationModifier;
public FoodValues(int hunger, float saturationModifier)
{
this.hunger = hunger;
this.saturationModifier = saturationModifier;
}
public FoodValues(FoodValues other)
{
this(other.hunger, other.saturationModifier);
}
/**
* @return The amount of saturation that the food values would provide.
*/
public float getSaturationIncrement()
{
return Math.min(20, hunger * saturationModifier * 2f);
}
/**
* See {@link IAppleCoreAccessor#getUnmodifiedFoodValues}
*/
/**
* See {@link IAppleCoreAccessor#getFoodValues}
*/
public FoodValues getFV(ItemStack itemStack)
{
return getFV(itemStack);
}
/**
* See {@link IAppleCoreAccessor#getFoodValuesForPlayer}
*/
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + hunger;
result = prime * result + Float.floatToIntBits(saturationModifier);
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FoodValues other = (FoodValues) obj;
if (hunger != other.hunger)
return false;
if (Float.floatToIntBits(saturationModifier) != Float.floatToIntBits(other.saturationModifier))
return false;
return true;
}
}
| true
|
e56126891188fb3a9f34c15556527bc1dee04d52
|
Java
|
Softwerke-Java-School-2018/kabanov
|
/src/main/java/com/softwerke/salesregister/menu/browselist/BrowseInvoiceListMenu.java
|
UTF-8
| 2,251
| 2.515625
| 3
|
[] |
no_license
|
package com.softwerke.salesregister.menu.browselist;
import com.softwerke.salesregister.io.Formatter;
import com.softwerke.salesregister.io.StringLiterals;
import com.softwerke.salesregister.menu.base.Menu;
import com.softwerke.salesregister.menu.base.MenuItem;
import com.softwerke.salesregister.menu.filterlist.FilterInvoiceListMenu;
import com.softwerke.salesregister.menu.sortlist.SortInvoiceListMenu;
import com.softwerke.salesregister.tables.invoice.Invoice;
import java.time.format.DateTimeParseException;
import java.util.stream.Collectors;
public class BrowseInvoiceListMenu extends Menu {
public BrowseInvoiceListMenu() {
super("-- Browse and search in sales history menu --",
new MenuItem("Print current list",
() -> Formatter.printFormatInvoice(internalData.invoiceList.stream()
.filter(invoice -> !invoice.isDeleted()), internalData.ioStream)),
new MenuItem("Apply filter to current list", () -> {
internalData.invoices = internalData.invoiceList.stream().filter(invoice -> !invoice.isDeleted());
try {
new FilterInvoiceListMenu().execute();
internalData.invoiceList = internalData.invoices.collect(Collectors.toList());
} catch (IllegalArgumentException | DateTimeParseException e) {
internalData.ioStream.ask(StringLiterals.WRONG_DATA_TEXT);
}
}),
new MenuItem("Reset current list", internalData::resetInvoiceList),
new MenuItem("Sort current list", () -> new SortInvoiceListMenu().execute()),
new MenuItem("Print sale details", () -> {
int saleId = internalData.ioStream.askInt("Enter invoice ID for printing:");
Invoice invoice = internalData.daoInvoice.getInvoice(saleId);
if (invoice.isDeleted()) {
internalData.ioStream.printLine(StringLiterals.ENTRY_IS_DELETED);
} else {
Formatter.printReceipt(invoice, internalData.ioStream);
}
}));
}
}
| true
|
8d1b2ea1163aea8a6d114f111360e82fb027c60a
|
Java
|
Nayeemr45/Project1
|
/Admin_show.java
|
UTF-8
| 1,589
| 2.90625
| 3
|
[] |
no_license
|
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
public class Admin_show extends Frame implements ActionListener{
private TextArea ta;
public Admin_show( ){
super("Show Payment");
Label l=new Label("Data From DB");
ta=new TextArea(6,40);
Button b=new Button("Show Payment Info");
Button b2=new Button("Exit");
add(l);add(ta);add(b);add(b2);
b.addActionListener(this);
b2.addActionListener(this);
setLayout(new FlowLayout());
setSize(400,400);
setLocation(750,250);
}
public void actionPerformed(ActionEvent ae){
String s=ae.getActionCommand();
System.out.println(ta.getText());
ta.setText("");
if(s.equals("Show Payment Info")){
try{
DataAccess da=new DataAccess();ResultSet rs=null;
rs=da.getData("select payment_no,payment_method,payment_date from payment");
while(rs.next()){
String str=rs.getInt("payment_no")+"--Method:"+rs.getString("payment_method")+"--Date:"+rs.getString("payment_date");//get data from Database
ta.append(str+"\n"); //print
}
}catch(Exception ex){ex.printStackTrace();}
}else if(s.equals("Exit")){
System.exit(0); //Exit
}
}
public void paint(Graphics g){
g.setColor(new Color(207,192,58));
g.fillRect(0,0,400,400);
}
}
| true
|
ca3b559ed3afdeae405c87d3a4a325480f65e25b
|
Java
|
neolord0/webserver
|
/src/main/java/kr/dogfoot/webserver/server/resource/performer/NegoFilePerformer.java
|
UTF-8
| 5,496
| 2.140625
| 2
|
[] |
no_license
|
package kr.dogfoot.webserver.server.resource.performer;
import kr.dogfoot.webserver.httpMessage.header.HeaderItem;
import kr.dogfoot.webserver.httpMessage.header.HeaderList;
import kr.dogfoot.webserver.httpMessage.header.HeaderSort;
import kr.dogfoot.webserver.httpMessage.header.valueobj.HeaderValue;
import kr.dogfoot.webserver.httpMessage.request.Request;
import kr.dogfoot.webserver.httpMessage.response.Response;
import kr.dogfoot.webserver.httpMessage.util.ResponseSetter;
import kr.dogfoot.webserver.server.host.HostObjects;
import kr.dogfoot.webserver.server.resource.ResourceNegotiatedFile;
import kr.dogfoot.webserver.server.resource.filter.part.condition.CompareOperator;
import kr.dogfoot.webserver.server.resource.filter.part.condition.HeaderCondition;
import kr.dogfoot.webserver.server.resource.negotiation.NegotiationInfo;
import kr.dogfoot.webserver.server.resource.negotiation.NegotiationVariant;
import java.util.ArrayList;
public class NegoFilePerformer {
public static Response perform(Request request, ResourceNegotiatedFile resource, HostObjects hostObjects) {
NegotiationVariant variant = getBestAvailableVariant(request, resource.negoInfo());
if (variant != null) {
Response response = variant.perform(request, hostObjects);
appendHeader(response, variant, resource.negoInfo());
return response;
} else {
return hostObjects.responseMaker().new_406NotAcceptable(resource);
}
}
private static NegotiationVariant getBestAvailableVariant(Request request, NegotiationInfo negoInfo) {
NegotiationVariant[] variants = negoInfo.variants();
HeaderSort[] compareHeaders = negoInfo.compareHeaders();
for (HeaderSort headerSort : compareHeaders) {
if (variants != null) {
variants = getAvailableVariants(request.headerList(), headerSort, variants);
}
}
if (variants == null || variants.length == 0) {
return null;
} else {
return variants[0];
}
}
private static NegotiationVariant[] getAvailableVariants(HeaderList headerList, HeaderSort sort, NegotiationVariant[] variants) {
ArrayList<NegotiationVariant> result = new ArrayList<NegotiationVariant>();
HeaderItem item = headerList.getHeader(sort);
if (item != null && item.valueObj().hasQvalue()) {
String bestValue = getBestAvailableValue(item.valueObj(), variants);
if (bestValue == null) {
return null;
} else if (bestValue.equals("*") || bestValue.equals("*/*")) {
return variants;
} else {
for (NegotiationVariant variant : variants) {
HeaderCondition condition = variant.getCondition(sort);
if (condition != null && bestValue.equalsIgnoreCase(condition.value())) {
result.add(variant);
}
}
}
} else {
for (NegotiationVariant variant : variants) {
HeaderCondition condition = variant.getCondition(sort);
if (condition != null && headerList.compare(sort, CompareOperator.Include, condition.value())) {
result.add(variant);
}
}
}
return result.toArray(new NegotiationVariant[0]);
}
private static String getBestAvailableValue(HeaderValue headerValue, NegotiationVariant[] variants) {
String result = null;
float max = -1;
float qvalue = -1;
String value;
for (NegotiationVariant variant : variants) {
HeaderCondition condition = variant.getCondition(headerValue.sort());
if (condition != null) {
value = condition.value();
} else {
value = null;
}
qvalue = headerValue.getQvalue(value);
if (qvalue > max) {
max = qvalue;
result = value;
}
}
return result;
}
private static void appendHeader(Response response, NegotiationVariant variant, NegotiationInfo negoInfo) {
ArrayList<HeaderSort> fieldNames = new ArrayList<HeaderSort>();
for (HeaderSort headerSort : negoInfo.compareHeaders()) {
HeaderCondition condition = variant.getCondition(headerSort);
if (condition != null) {
setCorrespondingHeader(response, headerSort, condition.value());
}
fieldNames.add(headerSort);
}
ResponseSetter.addFieldNameOfVaryHeader(response, fieldNames);
ResponseSetter.setContentLocation(response, variant.pathFromRoot());
}
private static void setCorrespondingHeader(Response response, HeaderSort headerSort, String value) {
switch (headerSort) {
case Accept:
ResponseSetter.setContentType(response, value, null);
break;
case Accept_Charset:
ResponseSetter.setCharsetOfContentType(response, value);
break;
case Accept_Encoding:
ResponseSetter.setHeader(response, HeaderSort.Content_Encoding, value.getBytes());
break;
case Accept_Language:
ResponseSetter.setHeader(response, HeaderSort.Content_Language, value.getBytes());
break;
}
}
}
| true
|
5db6d501f66fa9a94cc05b0dfa241c6f9ea0c36f
|
Java
|
Bryanavalos-dev/LabSys
|
/build/web/WEB-INF/lib/src/java/interfaz/CRUD_Horario.java
|
UTF-8
| 276
| 1.820313
| 2
|
[] |
no_license
|
package interfaz;
import modelo.Horario;
import java.util.List;
public interface CRUD_Horario {
public List listar();
public Horario list(int id);
public boolean add(Horario per);
public boolean edit(Horario per);
public boolean eliminar(int id);
}
| true
|
445a32835f8ba586a6f40d4cb493ac14ac820e74
|
Java
|
XinyiYan/Fotag
|
/src/main/java/ImageView.java
|
UTF-8
| 1,212
| 3.0625
| 3
|
[] |
no_license
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class ImageView extends JPanel implements Observer{
private ImageModel imageModel;
private Dimension imageDim = new Dimension(300, 250);
public ImageView(ImageModel imodel) {
this.imageModel = imodel;
this.imageModel.addObserver(this);
this.setPreferredSize(imageDim);
this.setMaximumSize(imageDim);
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
ImageIcon enlarge = new ImageIcon(imageModel.getData().getScaledInstance(600,500,Image.SCALE_SMOOTH));
String name = imodel.getName();
JOptionPane.showMessageDialog(ImageView.this, new JLabel(enlarge), name, JOptionPane.PLAIN_MESSAGE);
}
});
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(imageModel.getData(), 0, 0, getWidth(), getHeight(), this);
this.revalidate();
}
public void update(Object observable) {
// System.out.println("ImageView");
}
}
| true
|
4e5c8b8570de58940b8d1b209745de2ab3ce3ca4
|
Java
|
yuanjinliang1/Scientific-Award-of-CIC
|
/src/main/java/com/dicipulus/app/JDBC/SixthPaperMonographNTJdbc.java
|
UTF-8
| 3,003
| 2.28125
| 2
|
[] |
no_license
|
package com.dicipulus.app.JDBC;
import java.util.List;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.dicipulus.app.applicationModel.SixthPaperMonographNT;
@Repository
public class SixthPaperMonographNTJdbc {
private static final Logger logger=LoggerFactory.getLogger(ThirdProjectBriefIntroductionJdbc.class);
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate=new JdbcTemplate(dataSource);
}
public void createSixthPaperMonographNT(String applierUid){
String sql="insert into paper_monograph(applierUid) values(?)";
jdbcTemplate.update(sql, new Object[] {applierUid});
logger.info( sql+" createSixthPaperMonographNT");
}
public List<SixthPaperMonographNT> getAllSixthPaperMonographNT(String applierUid){
String sql="select * from paper_monograph where applierUid=?";
List<SixthPaperMonographNT> list=jdbcTemplate.query(sql, new Object[] {applierUid},BeanPropertyRowMapper.newInstance(SixthPaperMonographNT.class));
logger.info("getAllSixthPaperMonographNT");
return list;
}
public SixthPaperMonographNT getSixthPaperMonographNT(int idOfPaperMonograph){
String sql="select * from paper_monograph where idOfPaperMonograph=?";
SixthPaperMonographNT sixthPaperMonographNT=jdbcTemplate.queryForObject(sql, new Object[] {idOfPaperMonograph}, BeanPropertyRowMapper.newInstance(SixthPaperMonographNT.class));
logger.info("getSixthPaperMonographNT");
return sixthPaperMonographNT;
}
public void updateSixthPaperMonographNT(SixthPaperMonographNT sixthPaperMonographNT,int idOfPaperMonograph){
String sql="update paper_monograph set name=?,influenceFactor=?,yearPage=?,publishTime=?,correspondenceAuthor=?,"
+ "firstAuthor=?,domesticAuthor=?,referenceBySCI=?,totalReference=?,intellectualRightBelongToNation=? ,representativePaperMonograph=?"
+ "where idOfPaperMonograph=?";
jdbcTemplate.update(sql, new Object[] {sixthPaperMonographNT.getName(),sixthPaperMonographNT.getInfluenceFactor(),sixthPaperMonographNT.getYearPage(),sixthPaperMonographNT.getPublishTime(),sixthPaperMonographNT.getCorrespondenceAuthor(),
sixthPaperMonographNT.getFirstAuthor(),sixthPaperMonographNT.getDomesticAuthor(),sixthPaperMonographNT.getReferenceBySCI(),sixthPaperMonographNT.getTotalReference(),sixthPaperMonographNT.getIntellectualRightBelongToNation(),sixthPaperMonographNT.getRepresentativePaperMonograph(),
idOfPaperMonograph});
logger.info("updateSixthPaperMonographNT");
}
public void deleteSixthPaperMonographNT(int idOfPaperMonograph){
String sql="delete from paper_monograph where idOfPaperMonograph=?";
jdbcTemplate.update(sql, new Object[] {idOfPaperMonograph});
logger.info("deleteSixthPaperMonographNT");
}
}
| true
|
3adf351e2efa0a1aa0d186e4734345cf90bfe102
|
Java
|
AbertLi/testProject
|
/FistTestProject/sample/bundle_two/src/main/java/one/example/com/bundletwo/AdViewOneItem.java
|
UTF-8
| 1,067
| 2.125
| 2
|
[] |
no_license
|
package one.example.com.bundletwo;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.Map;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import one.example.com.myapplication3.R;
import one.example.com.recyclerview.AbstractView;
import one.example.com.data.BaseData;
import one.example.com.recyclerview.BaseViewItem;
/**
* 定制动态下发的样式 1
* 小图 H5跳转样式
*/
public class AdViewOneItem implements BaseViewItem {
private Context mContext;
public AdViewOneItem(Context context){
mContext = context;
}
@Override
public AbstractView inflate(ViewGroup viewGroup) {
View root = LayoutInflater.from(mContext).inflate(R.layout.adview_two_item, viewGroup, false);
return new AbstractView(root);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position,
BaseData info, Map<String, Object> callback) {
}
}
| true
|
3e9885e64cc73df67ca81c249aa389639d1f12a3
|
Java
|
turgot/test
|
/src/main/java/com/icanbuy/utils/ApiTemplates/ResponseContent/LENDER_LOGO_CLICK_URL.java
|
UTF-8
| 872
| 2.53125
| 3
|
[] |
no_license
|
package com.icanbuy.utils.ApiTemplates.ResponseContent;
/**
* <p>«LENDER_LOGO_CLICK_URL» tag (class name is used as tag name so should be like in response)</p>
* <p>From api doc: «Use this path when you want to submit a click to the Informa platform. This click will redirect
* the user to the lenders landing page»</p>
* <p>Can be empty if advertiser not accept clicks.</p>
* <p>Default value exist only {@link #createDefaultClickLeadLink() partially}</p>
* <p>General correct value is {@link #createClickLeadLink() empirical}</p>
*/
public class LENDER_LOGO_CLICK_URL extends ApiTag {
/**
* Regexp which describe any correct value of this tag
*/
@Override
protected void setValue() {
value = createClickLeadLink();
}
@Override
protected void setDefaultValue() {
value = createDefaultClickLeadLink();
}
}
| true
|
bd311c3df7d652b6bb59011208de4238a45b9f68
|
Java
|
caiolarroza/SCS-Medicamentos
|
/SistemaFarmacia/src/DAO/DinheiroDAO.java
|
UTF-8
| 3,528
| 2.71875
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import Model.Dinheiro;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
/**
*
* @author caiol
*/
public class DinheiroDAO implements DAO<Dinheiro>{
//variaveis auxiliares
Banco bd;
ResultSet rs;
public DinheiroDAO(Banco bd) {
this.bd = bd;
}
@Override
public boolean inserir(Dinheiro obj) {
try{
PreparedStatement pst;
bd.conectar(); //abre o banco
pst = bd.getConexao().prepareStatement( //comando SQL
"insert into dinheiro values (?, ?, ?)");
pst.setInt(1, obj.getCodPagamento());
pst.setInt(2, obj.getNotas().getCodNotas());
pst.setInt(3, obj.getMoedas().getCodMoedas());
//verifica se o update foi efetuado e retorna true ou false
return pst.executeUpdate() > 0;
}catch(SQLException ex){
JOptionPane.showMessageDialog(null, "Erro na inserção\n"
+ ex.getMessage());
return false;
}finally{
bd.fechaConexao();
}
}
@Override
public boolean alterar(Dinheiro obj) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public boolean excluir(Dinheiro obj) {
try {
PreparedStatement pst;
bd.conectar(); //abre o banco
pst = bd.getConexao().prepareStatement(
"DELETE FROM dinheiro WHERE codPagamento = ?");
pst.setInt(1, obj.getCodPagamento());
return pst.executeUpdate() > 0;
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro no Delete\n"
+ ex.getMessage());
return false;
} finally {
bd.fechaConexao();
}
}
@Override
public Dinheiro pesquisar(Dinheiro obj) {
try {
PreparedStatement pst;
bd.conectar(); //abre o banco
pst = bd.getConexao().prepareStatement(
"SELECT * FROM dinheiro WHERE codPagamento = ?");
pst.setInt(1, obj.getCodPagamento());
//executa o select
rs = pst.executeQuery();
//verifica se achou alguem
if(rs.next()) { //achou
obj.getNotas().setCodNotas(rs.getInt("codNotas"));
obj.getMoedas().setCodMoedas(rs.getInt("codMoedas"));
return obj;
} else
return null;
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro na Pesquisa\n"
+ ex.getMessage());
return null;
} finally {
bd.fechaConexao();
}
}
/*@Override
public List<Dinheiro> listar(String filtro) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}*/
@Override
public int proxCodigo() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| true
|
55ddd70ec42260a0dc047b4086aef659496e830c
|
Java
|
AthinaZintro/Thesis_AthinaZintro
|
/src/register/FileManagerFactory.java
|
UTF-8
| 132
| 1.8125
| 2
|
[] |
no_license
|
package register;
public class FileManagerFactory {
public IFileManager generateFileManager() {
return new FileManager();
}
}
| true
|
2cf8abf59fbfa5b82383e50bf571279b1e91ce9e
|
Java
|
devindi/robo-meter
|
/robometer/src/main/java/com/devindi/robometer/duration/SimpleTracker.java
|
UTF-8
| 317
| 2.328125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.devindi.robometer.duration;
import com.devindi.robometer.Robometer;
import java.util.concurrent.TimeUnit;
public class SimpleTracker {
public void track(String key, long duration, TimeUnit timeUnit) {
Robometer.getInstance().sendMeasurement(new Duration(key, duration, timeUnit));
}
}
| true
|
b4e4da4a785d9cd3b4a80062d17f9002b006fae5
|
Java
|
eduardodonato/Exercicios_POO_JAVA
|
/ExceptionsPersonalizadas/src/ExceptionsPersonalizadas.java
|
ISO-8859-1
| 1,064
| 4.09375
| 4
|
[] |
no_license
|
/*Objetivo: Criar um programa que apresente uma exception personalizada.
Neste caso, a exception ocorrer no momento da diviso de um nmero impar
por um numero par, informando que o resultado gerar um nmero real
(no inteiro) diferente dos tipos dos dois arrays criados*/
public class ExceptionsPersonalizadas{
public static void main(String[] args) {
int numeros[] = { 4, 8, 5, 16, 32, 21, 64, 128 };
int denominador[] = { 2, 0, 4, 8, 0, 2, 4 };
for (int i = 0; i < numeros.length; i++) {
try {
if(numeros[i] %2 != 0) {
//lana a exception aqui
throw new Exception("Diviso de nmero impar, o resultado no ser inteiro");
}
System.out.println(numeros[i] + "/" + denominador[i] + "=" + (numeros[i] / denominador[i]));
}
catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println("Ocorreu um erro!");
}
catch (Exception e) {
System.out.println("Aconteceu um erro");
System.out.println(e.getMessage()); //Para sabermos o que exatamente ocorreu
}
}
}
}
| true
|
e84d9e69c38bcfdba3651b03e36b2b141568351e
|
Java
|
jpgros/CycabJava
|
/Vanet/Vanet/src/engine/GoalEngine.java
|
UTF-8
| 210
| 2.21875
| 2
|
[] |
no_license
|
package engine;
import individual.Population;
public abstract class GoalEngine
{
public abstract boolean searchShouldStop (GeneticEngine genetic, Population population);
public abstract String getName();
}
| true
|
5b0ad7df848263fb7901c3ecb75ee9b50018761c
|
Java
|
Zjie/704station
|
/src/main/java/cn/edu/ustb/sem/process/web/model/ProcessSearchForm.java
|
UTF-8
| 741
| 2.078125
| 2
|
[] |
no_license
|
package cn.edu.ustb.sem.process.web.model;
import cn.edu.ustb.sem.core.web.model.SearchFormModel;
public class ProcessSearchForm extends SearchFormModel {
private int pid;
private String phase;
private String content;
private int groupName;
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getPhase() {
return phase;
}
public void setPhase(String phase) {
this.phase = phase;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getGroupName() {
return groupName;
}
public void setGroupName(int groupName) {
this.groupName = groupName;
}
}
| true
|
d694b88d4361222f43a49c1d0225ba3671e3272e
|
Java
|
makespace-re-good/backend
|
/后端/src/main/java/com/xmu/makerspace/model/Team/TeamMessage.java
|
UTF-8
| 1,449
| 2.21875
| 2
|
[] |
no_license
|
package com.xmu.makerspace.model.Team;
/*
用来存放团队列表应该展示的数据
*/
import java.sql.Date;
public class TeamMessage {
int teamId;
String team_name;
String project_name;
String belong_field;
String project_type;
Date register_date;
int message;
public void setTeamId(int teamId) {
this.teamId = teamId;
}
public int getTeamId() {
return teamId;
}
public Date getRegister_date() {
return register_date;
}
public String getBelong_field() {
return belong_field;
}
public String getProject_name() {
return project_name;
}
public String getProject_type() {
return project_type;
}
public String getTeam_name() {
return team_name;
}
public void setBelong_field(String belong_field) {
this.belong_field = belong_field;
}
public void setProject_name(String project_name) {
this.project_name = project_name;
}
public void setProject_type(String project_type) {
this.project_type = project_type;
}
public void setRegister_date(Date register_date) {
this.register_date = register_date;
}
public void setTeam_name(String team_name) {
this.team_name = team_name;
}
public void setMessage(int message) {
this.message = message;
}
public int getMessage() {
return message;
}
}
| true
|
2013806a5d6a6f8a12db7909cf276f60fa99b772
|
Java
|
huiGod/jdk8
|
/src/main/java/com/huigod/java8/stream/MapAndFlatMap.java
|
UTF-8
| 2,196
| 3.796875
| 4
|
[] |
no_license
|
package com.huigod.java8.stream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
public class MapAndFlatMap {
public static void main(String[] args) {
Student student1 = new Student("zhangsan", 100, 20);
Student student2 = new Student("lisi", 90, 20);
Student student3 = new Student("wangwu", 90, 30);
Student student4 = new Student("zhangsan", 80, 40);
List<Student> students = Arrays.asList(student1, student2, student3, student4);
List<String> studentNames = students.stream()
.map(Student::getName)
.collect(toList());
//string length
List<String> words1 = Arrays.asList("Java 8", "Lambdas", "In", "Action");
List<Integer> wordLengths = words1.stream()
.map(String::length)
.collect(toList());
//student name length
List<Integer> studentNamesLength = students.stream()
.map(Student::getName)
.map(String::length)
.collect(toList());
//["Hello","World"] //["H","e","l", "o","W","r","d"]
String[] words = new String[]{"Hello", "World"};
List<String[]> list = Stream.of(words)
.map(word -> word.split("")) //Stream<String[]> //Stream<String>
.distinct()
.collect(toList());
//Arrays.stream
String[] arrayOfWords = {"Goodbye", "World"};
Stream<String> streamOfwords = Arrays.stream(arrayOfWords);
Stream.of(words)
.map(word -> word.split(""))
.map(Arrays::stream)
.distinct()
.collect(toList());
//the flatMap method lets you replace each value of a stream with another stream and then concatenates all the generated streams into a single stream
List<String> uniqueCharacters = Stream.of(words)
.map(w -> w.split(""))
.flatMap(Arrays::stream)
.distinct()
.collect(Collectors.toList());
}
}
| true
|
f7cf2d622774b3dae0e62516f895023d18744de5
|
Java
|
hjindal/hackerrank
|
/src/main/java/hackerrank/algorithms/dp/BricksGame.java
|
UTF-8
| 1,295
| 3.34375
| 3
|
[] |
no_license
|
package hackerrank.algorithms.dp;
import java.util.Scanner;
/**
* Created by hjindal on 9/20/2015.
*/
public class BricksGame {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int t = s.nextInt();
while(t > 0) {
t--;
int n = s.nextInt();
long[] a = new long[n];
for(int i=n-1; i>=0; --i) {
a[i] = s.nextInt();
}
long sum = f(a, n);
System.out.println(sum);
}
}
private static long max(long a, long b) {
return a > b ? a : b;
}
private static long f(long a[], int n) {
if(n == 1)
return a[0];
if(n == 2)
return a[0]+a[1];
if(n == 3)
return a[0] + a[1] + a[2];
long[] sum = new long[3];
long[] sol = new long[3];
sum[0] = sol[0] = a[0];
sum[1] = sol[1] = sol[0]+ a[1];
sum[2] = sol[2] = sol[1] + a[2];
long csum=0, csol=0;
for(int i=3; i<n; ++i) {
long sol1 = a[i] + sum[2] - sol[2];
long sol2 = a[i] + a[i-1] + sum[1] - sol[1];
long sol3 = a[i] + a[i-1] + a[i-2] + sum[0] - sol[0];
csum = sum[2] + a[i];
csol = max(sol1, max(sol2, sol3));
sum[0] = sum[1]; sum[1] = sum[2]; sum[2] = csum;
sol[0] = sol[1]; sol[1] = sol[2]; sol[2] = csol;
}
return sol[2];
}
}
| true
|
2a0313542f71356d54bd0c2ecd0509db1986b83f
|
Java
|
RenMingNeng/xultimate-resource
|
/xultimate-toolkit/xultimate-shard/src/main/java/org/danielli/xultimate/shard/po/PartitionedTable.java
|
UTF-8
| 1,201
| 2.1875
| 2
|
[] |
no_license
|
package org.danielli.xultimate.shard.po;
import java.io.Serializable;
import java.util.Date;
/**
* 物理分区表。
*
* @author Daniel Li
* @since 15 Jun 2013
*/
public class PartitionedTable implements Serializable {
private static final long serialVersionUID = 5256793836881573L;
/** 标识 */
private Long id;
/** 虚拟表ID */
private Long virtualTableId;
/** 虚拟Socket ID */
private Long virtualSocketId;
/** 表分区ID */
private Long shardId;
/** 创建时间 */
private Date createTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getShardId() {
return shardId;
}
public void setShardId(Long shardId) {
this.shardId = shardId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Long getVirtualTableId() {
return virtualTableId;
}
public void setVirtualTableId(Long virtualTableId) {
this.virtualTableId = virtualTableId;
}
public Long getVirtualSocketId() {
return virtualSocketId;
}
public void setVirtualSocketId(Long virtualSocketId) {
this.virtualSocketId = virtualSocketId;
}
}
| true
|
6acce3bfaf9fe0155436b91fbd3f6c09d8ee38b7
|
Java
|
rupertwaldron/credential-manager
|
/src/test/java/com/ruppyrup/credentialmanager/controller/CredentialControllerTest.java
|
UTF-8
| 8,848
| 1.914063
| 2
|
[] |
no_license
|
package com.ruppyrup.credentialmanager.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruppyrup.credentialmanager.config.JwtContextManagerTestImpl;
import com.ruppyrup.credentialmanager.dao.CredentialDao;
import com.ruppyrup.credentialmanager.dao.UserDao;
import com.ruppyrup.credentialmanager.encryption.IEncryptionService;
import com.ruppyrup.credentialmanager.exceptions.ExistingUserException;
import com.ruppyrup.credentialmanager.jwt.JwtTokenUtil;
import com.ruppyrup.credentialmanager.model.Credential;
import com.ruppyrup.credentialmanager.model.CredentialDTO;
import com.ruppyrup.credentialmanager.model.DAOUser;
import com.ruppyrup.credentialmanager.model.UserDTO;
import com.ruppyrup.credentialmanager.service.impl.JwtUserDetailsService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.*;
import org.springframework.security.core.userdetails.User;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class CredentialControllerTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
CredentialDao credentialDao;
@Autowired
private UserDao userDao;
@Autowired
JwtContextManagerTestImpl jwtContextManager;
@Autowired
private JwtUserDetailsService userDetailsService;
@Autowired
IEncryptionService<Credential> encryptionService;
private DAOUser user1Dao;
private String username = "test";
private String password = "test";
private String token;
private Credential credential1;
private Credential credential2;
private HttpHeaders headers;
private UserDTO user = new UserDTO();
private ObjectMapper mapper = new ObjectMapper();
private String user1 = "javainuse";
private String user2 = "ruppyrup";
private String user3 = "bob";
private CredentialDTO amazonUser1DTO = new CredentialDTO( "Amazon", "www.amazon.com", "pete", "football");
private CredentialDTO pondUser1DTO = new CredentialDTO("PondPlanet", "www.pondplanet.com", "ruppyrup", "feelsick");
@BeforeEach
public void setup() throws ExistingUserException {
// create user and save
user.setUsername(username);
user.setPassword(password);
userDetailsService.save(user);
user1Dao = userDetailsService.getUser(username);
//creat credential and save
credential1 = new Credential(amazonUser1DTO);
credential1.setUuid("1234");
credential1.setUser(user1Dao);
credential1 = encryptionService.encrypt(credential1);
credentialDao.save(credential1);
credential2 = new Credential(pondUser1DTO);
credential2.setUuid("abcd");
credential2.setUser(user1Dao);
credential2 = encryptionService.encrypt(credential2);
credentialDao.save(credential2);
//set jwtContext user and get token
jwtContextManager.setUser(username);
User savedUser = new User(this.user.getUsername(), this.user.getPassword(), new ArrayList<>());
token = jwtTokenUtil.generateToken(savedUser);
// set headers
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.APPLICATION_JSON);
headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(mediaTypes);
headers.setBearerAuth(token);
}
@AfterEach
public void clearData() {
credentialDao.deleteAll();
userDao.deleteAll();
}
@Test
public void findCredential() {
//given database has two credentials and valid jwt token
HttpEntity<String> entity = new HttpEntity<>(null, headers);
UriComponents uriComponents = UriComponentsBuilder.newInstance()
.scheme("http")
.host("localhost")
.port(port)
.path("credentials/" + credential1.getUuid())
.build();
//when
ResponseEntity<Credential> exchange = restTemplate.exchange(uriComponents.toUriString(), HttpMethod.GET, entity, Credential.class);
//then
assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(exchange.getBody()).isEqualTo(encryptionService.decrypt(credential1));
}
@Test
public void findAllCredentials() {
//given database has two credentials and valid jwt token
HttpEntity<String> entity = new HttpEntity<>(null, headers);
UriComponents uriComponents = UriComponentsBuilder.newInstance()
.scheme("http")
.host("localhost")
.port(port)
.path("credentials")
.build();
//when
ResponseEntity<Credential[]> exchange = restTemplate.exchange(uriComponents.toUriString(), HttpMethod.GET, entity, Credential[].class);
//then
assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(exchange.getBody()).containsExactlyInAnyOrder(encryptionService.decrypt(credential1), encryptionService.decrypt(credential2));
}
@Test
public void createCredential() throws JsonProcessingException {
//given database has two credential and valid jwt token
CredentialDTO credentialDTO = new CredentialDTO("John Lewis", "www.jl.com", "rr", "spoons");
String credentialJson = mapper.writeValueAsString(credentialDTO);
HttpEntity<String> entity = new HttpEntity<>(credentialJson, headers);
UriComponents uriComponents = UriComponentsBuilder.newInstance()
.scheme("http")
.host("localhost")
.port(port)
.path("credentials")
.build();
//when
ResponseEntity<Credential> exchange = restTemplate.exchange(uriComponents.toUriString(), HttpMethod.POST, entity, Credential.class);
//then
assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(new CredentialDTO(exchange.getBody())).isEqualToIgnoringGivenFields(credentialDTO, "login", "password");
}
@Test
public void updateCredential() throws JsonProcessingException {
//given database has two credential and valid jwt token
CredentialDTO credentialDTO = new CredentialDTO("John Lewis", "www.jl.com", "rr", "spoons");
String credentialJson = mapper.writeValueAsString(credentialDTO);
HttpEntity<String> entity = new HttpEntity<>(credentialJson, headers);
UriComponents uriComponents = UriComponentsBuilder.newInstance()
.scheme("http")
.host("localhost")
.port(port)
.path("credentials/" + credential1.getUuid())
.build();
//when
ResponseEntity<Credential> exchange = restTemplate.exchange(uriComponents.toUriString(), HttpMethod.PUT, entity, Credential.class);
//then
assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(new CredentialDTO(exchange.getBody())).isEqualToIgnoringGivenFields(credentialDTO, "login", "password");
}
@Test
public void deleteCredential() throws JsonProcessingException {
//given database has two credential and valid jwt token
HttpEntity<String> entity = new HttpEntity<>(null, headers);
UriComponents uriComponents = UriComponentsBuilder.newInstance()
.scheme("http")
.host("localhost")
.port(port)
.path("credentials/" + credential1.getUuid())
.build();
//when
ResponseEntity<Credential> exchange = restTemplate.exchange(uriComponents.toUriString(), HttpMethod.DELETE, entity, Credential.class);
//then
assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(exchange.getBody()).isEqualTo(credential1);
}
}
| true
|
90c8e67c71d6fb5b4d85c018f46078d733b5c81a
|
Java
|
byz8866/niceapp
|
/app/src/main/java/com/niceapp/service/interfaces/IXlmDepositRecordService.java
|
UTF-8
| 590
| 2.03125
| 2
|
[] |
no_license
|
package com.niceapp.service.interfaces;
import com.niceapp.model.request.EosDepositRecordRequest;
import com.niceapp.model.request.SendMessage;
import com.niceapp.model.result.EosDepositRecordResult;
import com.niceapp.model.result.ResultMessage;
import retrofit2.http.Body;
import retrofit2.http.POST;
import rx.Observable;
public interface IXlmDepositRecordService {
int i = 0;
/**
* xlm 提现记录
*/
@POST("deposit/xlmDepositRecord")
Observable<ResultMessage<EosDepositRecordResult>> register(@Body SendMessage<EosDepositRecordRequest> sendMessage);
}
| true
|
18dca0e8b6f302fda3d8a55786f05c536b7f8dd8
|
Java
|
zsdai/gyl
|
/gyl/src/main/java/com/myself/gyl/business/xsgl/service/impl/XsysServiceImpl.java
|
UTF-8
| 2,849
| 2.03125
| 2
|
[] |
no_license
|
package com.myself.gyl.business.xsgl.service.impl;
import java.util.HashSet;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.myself.gyl.base.dao.BaseDao;
import com.myself.gyl.business.base.service.impl.BaseBusinessServiceImpl;
import com.myself.gyl.business.xsgl.dao.XsddzhibDao;
import com.myself.gyl.business.xsgl.dao.XsddzhubDao;
import com.myself.gyl.business.xsgl.dao.XsyszhibDao;
import com.myself.gyl.business.xsgl.dao.XsyszhubDao;
import com.myself.gyl.business.xsgl.service.XsysService;
import com.myself.gyl.domain.business.Xsddzhib;
import com.myself.gyl.domain.business.Xsddzhub;
import com.myself.gyl.domain.business.Xsysdzhib;
import com.myself.gyl.domain.business.Xsysdzhub;
@Service("xsysService")
public class XsysServiceImpl extends BaseBusinessServiceImpl<Xsysdzhub, Xsysdzhib> implements XsysService{
@Resource(name="xsyszhubDao")
private XsyszhubDao xsyszhubDao;
@Resource(name="xsyszhibDao")
private XsyszhibDao xsyszhibDao;
@Resource(name="xsddzhibDao")
private XsddzhibDao xsddzhibDao;
@Resource(name="xsddzhubDao")
private XsddzhubDao xsddzhubDao;
@Override
public BaseDao<Xsysdzhub> getBaseDao_zhu() {
return this.xsyszhubDao;
}
@Override
public BaseDao<Xsysdzhib> getBaseDao_zi() {
return this.xsyszhibDao;
}
@Override
@Transactional
public void saveXsysd(Xsysdzhub xsysdzhub, List<Xsysdzhib> xsysdzhibs) {
for (Xsysdzhib xsysdzhib : xsysdzhibs) {
String ytdjh = xsysdzhib.getYtdjh();
Long ythh = xsysdzhib.getYthh();
Xsddzhib xsddzhib = this.xsddzhibDao.getXsddzhibByYtdjhAndYthh(ytdjh, ythh);
Long ljyssl_db = xsddzhib.getLjyssl();
xsysdzhib.setLjyssl(ljyssl_db+xsysdzhib.getSl());
xsddzhib.setLjyssl(ljyssl_db+xsysdzhib.getSl());
if(xsysdzhib.getLjyssl().longValue()==xsddzhib.getLjyssl().longValue()){
xsysdzhib.setIsysgb(true);
xsddzhib.setIsskjs(true);
/**
* 因为销售应收是最后一个环节,因此
* 对销售订单子表中的商品进行行关闭,表示该种商品在销售过程流程结束
*/
xsddzhib.setHstatus("1");
//循环遍历xsddzhib中所有的商品,看所有状态是否完毕
List<Xsddzhib> xsddzhibs_db = xsddzhubDao.getXsddzhibsByDDh(ytdjh);
boolean flag=true;
for (Xsddzhib xsddzhib_db : xsddzhibs_db) {
if(!"1".equals(xsddzhib_db.getHstatus())){
flag=false;
break;
}
}
if(flag){
Xsddzhub xsddzhub = this.xsddzhubDao.getXsddzhubByDDH(ytdjh);
xsddzhub.setState("1");//表示订单流程全部走完
}
}
}
xsysdzhub.setXsysdzhibs(new HashSet<Xsysdzhib>(xsysdzhibs));
this.xsyszhubDao.saveEntry(xsysdzhub);
}
}
| true
|
11dbecb14bfa0f9be1183a0b3b1e89730748e8eb
|
Java
|
SophyaTs/VI_semester
|
/OOP/Problem3/src/main/java/server/ServerObject.java
|
UTF-8
| 2,852
| 3.0625
| 3
|
[] |
no_license
|
package server;
import common.MessageObject;
import common.ServerInterface;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
public class ServerObject implements ServerInterface {
AtomicInteger numberOfPlayers = new AtomicInteger(0);
Map<Integer, GameInstance> games = new HashMap<>();
Integer lastGameId = -1;
@Override
public MessageObject registerForGame(MessageObject requestMessage){
Thread thread;
if(games.size() == 2){
return new MessageObject("Server error: too many players, try later");
}
if(numberOfPlayers.compareAndSet(0, 1)){
try {
lastGameId = Math.abs(new Random().nextInt()) / 10 * 10;
int currentGame = lastGameId;
games.put(lastGameId, new GameInstance(lastGameId, lastGameId + 1, lastGameId + 2));
thread = new Thread(new PlayerThread(games.get(currentGame), true, requestMessage.getMyMessage()));
thread.start();
thread.join();
System.out.println("Left user id : " + (lastGameId + 1));
return new MessageObject(requestMessage.getMyMessage(), lastGameId+1, "You play with " + games.get(currentGame).getMessage(1));
}catch(Exception ex){
return new MessageObject("Server error: " + ex.getMessage());
}
}else if(numberOfPlayers.compareAndSet(1, 0)){
try{
int currentGame = lastGameId;
thread = new Thread(new PlayerThread(games.get(currentGame), false, requestMessage.getMyMessage()));
thread.start();
thread.join();
System.out.println("right user id : " + (lastGameId + 2));
return new MessageObject(requestMessage.getMyMessage(), lastGameId+2, "You play with " + games.get(currentGame).getMessage(2));
}catch(Exception ex){
return new MessageObject("Server error: " + ex.getMessage());
}
}
return new MessageObject("Server error: unhandled move");
}
@Override
public MessageObject performMove(MessageObject requestMessage){
Thread thread;
Integer gameId=requestMessage.getClientId() / 10 * 10;
try{
var game = games.get(gameId);
thread = new Thread(new PlayerThread(game, requestMessage.getClientId() % 10 == 1, requestMessage.getMyMessage()));
thread.start();
thread.join();
return new MessageObject(requestMessage.getMyMessage(), requestMessage.getClientId(), game.getMessage(requestMessage.getClientId() % 10));
}catch(Exception ex){
return new MessageObject("Server error: " + ex.getMessage());
}
}
}
| true
|
ec715f0eeea347ed2b7631187775c03e8e9c5b83
|
Java
|
KanadeSong/webserver
|
/smartmining/src/main/java/com/seater/smartmining/service/impl/CarBrandServiceImpl.java
|
UTF-8
| 2,111
| 2.140625
| 2
|
[] |
no_license
|
package com.seater.smartmining.service.impl;
import com.seater.smartmining.dao.CarBrandDaoI;
import com.seater.smartmining.entity.CarBrand;
import com.seater.smartmining.entity.CarType;
import com.seater.smartmining.service.CarBrandServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.List;
@Service
public class CarBrandServiceImpl implements CarBrandServiceI {
@Autowired
ApplicationContext applicationContext;
@Autowired
CarBrandDaoI carBrandDaoI;
@Override
public CarBrand get(Long id) throws IOException{
return carBrandDaoI.get(id);
}
@Override
public CarBrand save(CarBrand log) throws IOException{
return carBrandDaoI.save(log);
}
@Override
public void delete(Long id) {
carBrandDaoI.delete(id);
}
@Override
public void delete(List<Long> ids) {
carBrandDaoI.delete(ids);
}
@Override
public Page<CarBrand> query(Pageable pageable) {
return carBrandDaoI.query(pageable);
}
@Override
public Page<CarBrand> query() {
return carBrandDaoI.query();
}
@Override
public Page<CarBrand> query(Example<CarBrand> example) {
return carBrandDaoI.query(example);
}
@Override
public Page<CarBrand> query(Example<CarBrand> example, Pageable pageable) {
return carBrandDaoI.query(example, pageable);
}
@Override
public List<CarBrand> getAll() {
return carBrandDaoI.getAll();
}
@Override
public List<CarBrand> findAllByOrderById() {
return carBrandDaoI.findAllByOrderById();
}
@Override
public List<CarBrand> queryAllByParams(Specification<CarBrand> spec) {
return carBrandDaoI.queryAllByParams(spec);
}
}
| true
|
3f3d5a6b47bb7269ea75e0af30a1964d179ea9b8
|
Java
|
zapper59/RangerHale---Space-Adventure
|
/src/org/enemies/SmashBlock.java
|
UTF-8
| 2,325
| 2.6875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package org.enemies;
import java.awt.image.BufferedImage;
import org.items.Health;
import org.players.Player;
import org.resources.Collisions;
import org.resources.ImagePack;
import org.rooms.Room;
import org.walls.Wall;
import static java.lang.Math.*;
public class SmashBlock extends Enemy {
static final BufferedImage[] ani = new BufferedImage[]{ImagePack.getImage("Robot/smashblock1.png"),
ImagePack.getImage("Robot/smashblock2.png"), ImagePack.getImage("Robot/smashblock3.png"),
ImagePack.getImage("Robot/smashblock4.png"), ImagePack.getImage("Robot/smashblock5.png"),
ImagePack.getImage("Robot/smashblock6.png"), ImagePack.getImage("Robot/smashblockd1.png"),
ImagePack.getImage("Robot/smashblockd2.png"),};
int counter = (int) round(1000 * random());
int lastHealth;
public boolean smashing = false;
public SmashBlock(int a, int b) {
x = a;
y = b;
w = 15;
h = 25;
lastHealth = life = lifeCapacity = 100;
}
public void run() {
if (life <= 0) {
Health.add(this, 4);
dead = true;
}
counter++;
image = ani[smashing ? 6 + counter / 5 % 2 : counter / 5 % 6];
Player p = Player.player;
if ((x < p.x + p.w && x + w > p.x) && (y < p.y + p.h && y + h > p.y)) {
life = 0;
Player.damage(30);
dead = true;
}
double dx = x - p.x - p.w / 2;
double dy = y - p.y - p.h / 2;
if (counter % 60 == 0) {
vx = (float) (.4 * (dx > 0 ? -1 : 1) * (Math.random() * 5 - 2.5));
}
if (counter % 60 == 0) {
vy = (float) (.4 * (dy > 0 ? -1 : 1) * (Math.random() * 2 - 1));
}
if (!smashing && (Collisions.collides(new Wall(x, y, w, Room.HEIGHT), Player.player) || lastHealth != life)) {
smashing = true;
}
if (smashing) {
lastHealth = life;
h = 40;
vx = 0;
vy = 10;
} else {
h = 25;
}
// vy-=(counter%10)-4.5;
vMult1();
for (Wall wal : Room.walls) {
if (Collisions.willCollide(this, wal, vx, 0)) {
if (vx > 0) {
x = wal.x - w;
} else {
x = wal.x + wal.w;
}
vx = 0;
}
if (Collisions.willCollide(this, wal, vx, vy)) {
if (vy > 0) {
y = wal.y - h;
} else {
y = wal.y + wal.h;
}
vy = 0;
if (smashing) {
smashing = false;
lastHealth = life;
vy = -10;
}
}
}
x += vx;
y += vy;
vMult2();
}
public boolean preventsNextRoom() {
return false;
}
}
| true
|
619cfb9c32c90cf613a0e3fce055b27209563a3a
|
Java
|
wilbertcargeson/ShadowDefend
|
/src/PlaneDirection.java
|
UTF-8
| 110
| 1.929688
| 2
|
[] |
no_license
|
/**
* The direction in which the plane flies with
*/
public enum PlaneDirection {
VERTICAL,HORIZONTAL
}
| true
|
7f61ff006c7f5b1f819bbacdf2451472f44d42fc
|
Java
|
rosylee/Code-Monster
|
/Code-Monster_complete_SW/20180927/app/src/main/java/com/example/dwu/a20180927/Certification/CertificationActivity.java
|
UTF-8
| 1,745
| 2.078125
| 2
|
[] |
no_license
|
package com.example.dwu.a20180927.Certification;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.dwu.management.R;
import java.util.ArrayList;
public class CertificationActivity extends AppCompatActivity {
ArrayList<String> cerList;
ArrayAdapter<String> adapter; // ListView 에 연결할 기본 Adapter
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_certification);
cerList = new ArrayList<String>();
cerList.add("OTP");
cerList.add("공인인증");
cerList.add("바이오인증");
cerList.add("인증서");
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, cerList);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(itemClickListener);
}
AdapterView.OnItemClickListener itemClickListener =
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long ld) {
int pposition = position+1;
Intent intent = new Intent(CertificationActivity.this, CertificationChinese.class);
intent.putExtra(CertificationChinese.ACCOUNT_SOUND_NUMBER, pposition);
CertificationActivity.this.startActivity(intent);
}
};
}
| true
|
0863e95bc7a0873118b8412042bd7795b12eb1f3
|
Java
|
povloid/voyager
|
/voyager/src/main/java/pk/home/voyager/service/HotelServiceImpl.java
|
UTF-8
| 1,129
| 2.453125
| 2
|
[] |
no_license
|
/**
*
*/
package pk.home.voyager.service;
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pk.home.pulibs.basic.intefaces.dao.DAOCRUDFunctional;
import pk.home.pulibs.spring.service.AbstractServiceCRUDFunctionalImpl;
import pk.home.voyager.dao.HotelDAO;
import pk.home.voyager.domain.Hotel;
/**
* @author traveler
*
*/
@Service("HotelService")
@Transactional
public class HotelServiceImpl extends AbstractServiceCRUDFunctionalImpl<Hotel>
implements HotelService, Serializable {
/**
*
*/
public HotelServiceImpl() {
super();
}
/**
*
*/
private static final long serialVersionUID = -1L;
/**
* DAO injected by Spring that manages Testrb entities
*
*/
@Autowired
private HotelDAO HotelDAO;
@Override
@Transactional
public Hotel store(Hotel object) throws Exception {
return store(object, object.getId());
}
@Override
@Transactional
public DAOCRUDFunctional<Hotel> getDAOGRUDFunctional() {
return HotelDAO;
}
}
| true
|
feffc4fb65cee0a256c3b90d1d1acd00a825358c
|
Java
|
harshwall/MNNITDean
|
/app/src/main/java/com/example/mnnit/mnnitdean/user.java
|
UTF-8
| 312
| 2.265625
| 2
|
[] |
no_license
|
package com.example.mnnit.mnnitdean;
public class user {
String name,fathername,regno,email;
public user(String name,String fathername,String regno,String email){
this.name=name;
this.fathername=fathername;
this.regno=regno;
this.email=email;
}
user(){
}
}
| true
|
333ec5e85491417a2959ab52bf16e77da9e4e5bf
|
Java
|
nikitaden03/MyFood
|
/app/src/main/java/com/example/myfood/components/login/ui/TypeAccountDialog.java
|
UTF-8
| 673
| 1.78125
| 2
|
[] |
no_license
|
package com.example.myfood.components.login.ui;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import com.example.myfood.R;
public class TypeAccountDialog extends DialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(getActivity().getLayoutInflater().inflate(R.layout.layout_type_account_dialog, null));
return builder.create();
}
}
| true
|
3e910f430e0fff288154762cf1fc719521b6245f
|
Java
|
WeiChungChang/ExoPlayer
|
/library/src/main/java/com/google/android/exoplayer2/audio/BufferProcessor.java
|
UTF-8
| 2,372
| 2.421875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.audio;
import com.google.android.exoplayer2.C;
import java.nio.ByteBuffer;
/**
* Interface for processors of audio buffers.
*/
public interface BufferProcessor {
/**
* Exception thrown when a processor can't be configured for a given input format.
*/
final class UnhandledFormatException extends Exception {
public UnhandledFormatException(int sampleRateHz, int channelCount, @C.Encoding int encoding) {
super("Unhandled format: " + sampleRateHz + " Hz, " + channelCount + " channels in encoding "
+ encoding);
}
}
/**
* Configures this processor to take input buffers with the specified format.
*
* @param sampleRateHz The sample rate of input audio in Hz.
* @param channelCount The number of interleaved channels in input audio.
* @param encoding The encoding of input audio.
* @throws UnhandledFormatException Thrown if the specified format can't be handled as input.
*/
void configure(int sampleRateHz, int channelCount, @C.Encoding int encoding)
throws UnhandledFormatException;
/**
* Returns the encoding used in buffers output by this processor.
*/
@C.Encoding
int getOutputEncoding();
/**
* Processes the data in the specified input buffer in its entirety.
*
* @param input A buffer containing the input data to process.
* @return A buffer containing the processed output. This may be the same as the input buffer if
* no processing was required.
*/
ByteBuffer handleBuffer(ByteBuffer input);
/**
* Clears any state in preparation for receiving a new stream of buffers.
*/
void flush();
/**
* Releases any resources associated with this instance.
*/
void release();
}
| true
|
7b9372396a4488d357d9dae5f666b0462e51da25
|
Java
|
mtaylor/data-broker
|
/data-ws/src/main/java/com/arjuna/databroker/data/ws/EndpointFactorySetup.java
|
UTF-8
| 910
| 1.8125
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2013-2014, Arjuna Technologies Limited, Newcastle-upon-Tyne, England. All rights reserved.
*/
package com.arjuna.databroker.data.ws;
import java.util.Collections;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import com.arjuna.databroker.data.DataFlowNodeFactoryInventory;
@Startup
@Singleton
public class EndpointFactorySetup
{
@PostConstruct
public void setup()
{
EndpointDataSourceFactory endpointDataSourceFactory = new EndpointDataSourceFactory("Endpoint Data Source Factory", Collections.<String, String>emptyMap());
_dataFlowNodeFactoryInventory.addDataFlowNodeFactory(endpointDataSourceFactory);
}
@EJB(lookup="java:global/server-ear-1.0.0p1m1/control-core-1.0.0p1m1/DataFlowNodeFactoryInventory")
private DataFlowNodeFactoryInventory _dataFlowNodeFactoryInventory;
}
| true
|
41875237c59dad1395ac27b5a21dd49e6c69b79d
|
Java
|
lzd931201/roll_call
|
/attendance /app/src/main/java/com/example/xiao/attendance/export.java
|
UTF-8
| 6,726
| 2.03125
| 2
|
[] |
no_license
|
package com.example.xiao.attendance;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
import java.util.Calendar;
public class export extends AppCompatActivity {
public class Student {
public String mac;
public String name;
public Student(){}
public Student(String m,String n){
mac=m;
name=n;
}
}
public SQLiteDatabase db;
private String m_classnum;
private ArrayList<globalapp.student_state> m_arraylist_state=new ArrayList<globalapp.student_state>();
private Button b_save,b_cancel;
private View.OnClickListener listener1 = new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog_save();
}
};
private View.OnClickListener listener2 = new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog();
}
};
protected void dialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(export.this);
builder.setMessage("确认清空缓存吗?");
builder.setTitle("提示");
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
globalapp appG = ((globalapp)getApplicationContext());
appG.clearall();
Intent intent1 = new Intent();
intent1.setClass(export.this, mytime.class);
startActivity(intent1);
export.this.finish();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setCancelable(true);
AlertDialog dialog=builder.create();
dialog.show();
}
protected void dialog_save(){
AlertDialog.Builder builder = new AlertDialog.Builder(export.this);
builder.setMessage("确认保存记录吗?");
builder.setTitle("提示");
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
m_save(m_getTime());
globalapp appG = ((globalapp)getApplicationContext());
appG.clearall();
dialog_show();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setCancelable(true);
AlertDialog dialog=builder.create();
dialog.show();
}
protected void dialog_show() {
AlertDialog.Builder builder = new AlertDialog.Builder(export.this);
builder.setMessage("已经保存当前点名记录!");
builder.setTitle("提示");
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent intent1 = new Intent();
intent1.setClass(export.this, mytime.class);
startActivity(intent1);
export.this.finish();
}
});
builder.setCancelable(true);
AlertDialog dialog=builder.create();
dialog.show();
}
public void m_save(String name){
db.execSQL("ALTER TABLE" + m_classnum + "ADD COLUMN"+name+"VARCHAR DEFAULT '0'");
globalapp appG = ((globalapp)getApplicationContext());
m_arraylist_state=appG.get_ALS();
ContentValues contentValues = new ContentValues();
for(globalapp.student_state tmp:m_arraylist_state) {
String tmp_state="";
switch (tmp.getState()){
case 0:
tmp_state="×";break;
case 1:
tmp_state="√";break;
case 2:
tmp_state="迟到";break;
case 3:
tmp_state="请假";
}
contentValues.put(name, tmp_state);
String[] selectionArgs = {tmp.getStu_num()};
db.update(m_classnum, contentValues, "xuehao=?", selectionArgs);
}
}
public String m_getTime(){
Calendar x=Calendar.getInstance();
int year = x.get(Calendar.YEAR);
int month = x.get(Calendar.MONTH);
int day = x.get(Calendar.DATE);
int hour=x.get(Calendar.HOUR_OF_DAY);
int minute=x.get(Calendar.MINUTE);
String date = Integer.toString(year) +"/"+Integer.toString(month + 1) + "/"+Integer.toString(day)+ "-"+Integer.toString(hour)+":"+ Integer.toString(minute);
return "'"+date+"'";
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_export);
db = openOrCreateDatabase("students_origin.db", Context.MODE_PRIVATE, null);
globalapp appG = ((globalapp)getApplicationContext());
m_classnum="'"+appG.getClass_num()+"'";
b_save=(Button)findViewById(R.id.m_save);
b_save.setOnClickListener(listener1);
b_cancel=(Button)findViewById(R.id.m_clear);
b_cancel.setOnClickListener(listener2);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.activity_export);
db = openOrCreateDatabase("students_origin.db", Context.MODE_PRIVATE, null);
globalapp appG = ((globalapp)getApplicationContext());
m_classnum="'"+appG.getClass_num()+"'";
b_save=(Button)findViewById(R.id.m_save);
b_save.setOnClickListener(listener1);
b_cancel=(Button)findViewById(R.id.m_clear);
b_cancel.setOnClickListener(listener2);
}
}
| true
|
9e979f454352f84dd763f29aef522b2316033327
|
Java
|
bhasin11/Algorithms-in-Java
|
/BST/size.java
|
UTF-8
| 181
| 2.765625
| 3
|
[] |
no_license
|
/*
Given a BST, find the number of node in the tree.
*/
public int size(Node root){
if(root!=null){
size(root.leftChild);
size++;
size(root.rightChild);
}
return size;
}
| true
|
6aaa628cb7011c964c94728648c557621c0b1b76
|
Java
|
saidmh577/PFE2
|
/app/src/main/java/com/app/pfe2/MainHome.java
|
UTF-8
| 828
| 1.742188
| 2
|
[] |
no_license
|
package com.app.pfe2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainHome extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_home);
}
public void detectionArmature(View view) {
Intent intent = new Intent(this, ArmatureActivity.class);
startActivity(intent);
}
public void quantite(View view) {
Intent intent = new Intent(this, QuantiteArmature.class);
startActivity(intent);
}
public void deformation(View view) {
Intent intent = new Intent(this, VerificationDeformation.class);
startActivity(intent);
}
}
| true
|
3b4fa923a9cf0fe3a3737393c259c9ffd49b415b
|
Java
|
KenHoang16CDTH12/Library-Manager-Project
|
/src/kenhoang/refresh/IDataSet.java
|
UTF-8
| 138
| 1.578125
| 2
|
[] |
no_license
|
package kenhoang.refresh;
/**
* Created by sample on 5/28/17.
*/
public interface IDataSet {
public void refreshDataTableBook();
}
| true
|
bd1384e9c1bb11bf78039fd7ed712ad98394eb35
|
Java
|
trinodb/trino
|
/plugin/trino-accumulo/src/test/java/io/trino/plugin/accumulo/TestingAccumuloServer.java
|
UTF-8
| 3,796
| 1.929688
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* 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 io.trino.plugin.accumulo;
import io.trino.testing.TestingProperties;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.ZooKeeperInstance;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.testcontainers.containers.FixedHostPortGenericContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import java.time.Duration;
import static java.lang.String.format;
import static org.testcontainers.utility.MountableFile.forClasspathResource;
public class TestingAccumuloServer
{
private static final int ACCUMULO_MASTER_PORT = 9999;
private static final int ACCUMULO_TSERVER_PORT = 9997;
private static final int ZOOKEEPER_PORT = 2181;
private static final String ACCUMULO_EXT_PATH = "/usr/local/lib/accumulo/lib/ext";
private static final String ITERATORS_JAR = "trino-accumulo-iterators.jar";
private static final TestingAccumuloServer instance = new TestingAccumuloServer();
private final FixedHostPortGenericContainer<?> accumuloContainer;
public static TestingAccumuloServer getInstance()
{
return instance;
}
private TestingAccumuloServer()
{
accumuloContainer = new FixedHostPortGenericContainer<>("ghcr.io/trinodb/testing/accumulo:" + TestingProperties.getDockerImagesVersion());
accumuloContainer.withFixedExposedPort(ACCUMULO_MASTER_PORT, ACCUMULO_MASTER_PORT);
accumuloContainer.withFixedExposedPort(ACCUMULO_TSERVER_PORT, ACCUMULO_TSERVER_PORT);
accumuloContainer.withExposedPorts(ZOOKEEPER_PORT);
accumuloContainer.withCreateContainerCmdModifier(cmd -> cmd
.withHostName("localhost")
.withEnv("ADDRESS=0.0.0.0")
.withEntrypoint("supervisord", "-c", "/etc/supervisord.conf"));
accumuloContainer.waitingFor(Wait.forHealthcheck().withStartupTimeout(Duration.ofMinutes(10)));
accumuloContainer.withCopyFileToContainer(forClasspathResource(ITERATORS_JAR), ACCUMULO_EXT_PATH + "/" + ITERATORS_JAR);
// No need for an explicit stop since this server is a singleton
// and the container will be stopped by TestContainers on shutdown
// TODO Change this class to not be a singleton
// https://github.com/trinodb/trino/issues/5842
accumuloContainer.start();
}
public String getInstanceName()
{
return "default";
}
public String getZooKeepers()
{
return format("%s:%s", accumuloContainer.getHost(), accumuloContainer.getMappedPort(ZOOKEEPER_PORT));
}
public String getUser()
{
return "root";
}
public String getPassword()
{
return "secret";
}
public Connector getConnector()
{
try {
ZooKeeperInstance instance = new ZooKeeperInstance(getInstanceName(), getZooKeepers());
return instance.getConnector(getUser(), new PasswordToken(getPassword()));
}
catch (AccumuloException | AccumuloSecurityException e) {
throw new RuntimeException(e);
}
}
}
| true
|
12ff687de0a5b2744a9923887eb2801e340da7b6
|
Java
|
kennycaiguo/itheima-base
|
/2017-04-15基础班/day10_作业_陈仲尧/src/com/itheima/Test3.java
|
UTF-8
| 1,378
| 3.265625
| 3
|
[] |
no_license
|
package com.itheima;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
/*
分析以下需求,并用代码实现
项目根路径下有text.txt文件,内容如下:
我爱黑马
123456
利用IO流的知识读取text.txt文件的内容反转后写入text.txt文件中
写入后文件的内容为:
654321
马黑爱我
*/
public class Test3 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ArrayList<String> aList = new ArrayList<>();
BufferedReader bReader = new BufferedReader(new FileReader("text.txt"));
String readLn;
while ((readLn = bReader.readLine()) != null) {
// sBuilder = new StringBuilder(readLn);
// bWriter.write(sBuilder.reverse().toString());
// bWriter.newLine();
// bWriter.flush();
// System.out.println(readLn);
aList.add(readLn);
}
// System.out.println(bReader.readLine());
// System.out.println(bReader.readLine());
// System.out.println(bReader.readLine());
bReader.close();
BufferedWriter bWriter = new BufferedWriter(new FileWriter("text.txt"));
for (int i = 0; i < aList.size(); i++) {
bWriter.write(new StringBuilder(aList.get(i)).reverse().toString());
bWriter.newLine();
bWriter.flush();
}
bWriter.close();
}
}
| true
|
9afa6dca2b41e7edb5135e9314e5e91868e16e57
|
Java
|
brunotarditi/Proyectos-Java-UTN
|
/Programacion-2/Practica_1_arreglos/src/map_list/ejercicio_3.java
|
UTF-8
| 1,792
| 3.875
| 4
|
[] |
no_license
|
package map_list;
import java.util.HashMap;
/*
3.(NumPrimos2.java) Almacenar en un arreglo de 10 posiciones los 10
números primos comprendidos entre 100 y 300. Luego mostrarlos en pantalla.
*/
/**
*
* @author Bruno Tarditi
*/
public class ejercicio_3 {
public static void main(String[] args) {
HashMap<Integer, Integer> mapa = new HashMap<>();
for (int i = 0; i < 10; i++) {
generarAleatorio(mapa);
}
System.out.println(mapa.toString());
burbuja(mapa);
for (int i = 0; i < mapa.size(); i++) {
System.out.println("Posición " + i + " = " + mapa.get(i));
}
}
public static boolean esPrimo(int numero) {
for (int i = 2; i < numero; i++) {
if (numero % i == 0) {
return false;
}
}
return true;
}
public static HashMap<Integer, Integer> generarAleatorio(HashMap<Integer, Integer> mapa) {
int i = 10;
while (i != mapa.size()) {
int clave = (int) (Math.random() * 10) + 0;
int valor = (int) (Math.random() * 200) + 100;
if (esPrimo(valor) == true) {
mapa.put(clave, valor);
}
}
return mapa;
}
private static HashMap burbuja(HashMap<Integer, Integer> A) {
int n = A.size();
boolean intercambiado;
do {
intercambiado = false;
for (int i = 1; i < n; i++) {
if (A.get(i - 1) > A.get(i)) {
int aux = A.get(i - 1);
A.put((i - 1), A.get(i));
A.put(i, aux);
intercambiado = true;
}
}
} while (intercambiado == true);
return A;
}
}
| true
|
c48eace1c53c3fdc370f019a228e032061f88407
|
Java
|
cllkfan/eda-shopping
|
/src/main/java/com/eda/service/impl/VipServiceImpl.java
|
UTF-8
| 436
| 1.648438
| 2
|
[] |
no_license
|
package com.eda.service.impl;
import com.eda.entity.Vip;
import com.eda.service.VipService;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import javax.annotation.Resource;
/**
* (Vip)表服务实现类
*
* @author makejava
* @since 2021-10-23 19:25:26
*/
@Service("vipService")
public class VipServiceImpl implements VipService {
}
| true
|
cb7fed6c70120b456662313de39db0c4de8fbfba
|
Java
|
thisfardi/keibai-api
|
/src/main/java/servlets/user/UserUpdateCredit.java
|
UTF-8
| 2,860
| 2.390625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package main.java.servlets.user;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import main.java.dao.DAOException;
import main.java.dao.UserDAO;
import main.java.dao.sql.UserDAOSQL;
import main.java.gson.BetterGson;
import main.java.models.User;
import main.java.utils.HttpRequest;
import main.java.utils.DefaultHttpSession;
import main.java.utils.HttpResponse;
import main.java.utils.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "UserUpdateCredit", urlPatterns = {"/users/update/credit"})
public class UserUpdateCredit extends HttpServlet {
public static final String INVALID_CREDIT_AMOUNT = "Invalid credit amount";
public static final String USER_NOT_EXIST = "User does not exist";
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpResponse httpResponse = new HttpResponse(response);
DefaultHttpSession session = new DefaultHttpSession(request);
UserDAO userDAO = UserDAOSQL.getInstance();
int userId = session.userId();
if (userId == -1) {
httpResponse.unauthorized();
return;
}
// Retrieve body data
User unsafeUser;
try {
unsafeUser = new HttpRequest(request).extractPostRequestBody(User.class);
} catch (IOException|JsonSyntaxException e) {
httpResponse.invalidRequest();
return;
}
if (unsafeUser == null) {
httpResponse.invalidRequest();
return;
}
double creditDiff = unsafeUser.credit;
User user;
try {
user = userDAO.getById(userId);
} catch (DAOException e) {
Logger.error("Get user by ID in update user credit: UserID " + userId, e.toString());
httpResponse.internalServerError();
return;
}
if (user == null) {
httpResponse.error(USER_NOT_EXIST);
return;
}
if (user.credit + creditDiff < 0) {
httpResponse.error(INVALID_CREDIT_AMOUNT);
return;
}
user.credit += creditDiff;
User dbUser;
try {
dbUser = userDAO.update(user);
} catch(DAOException e) {
Logger.error("Create user in update user credit", user.toString(), e.toString());
httpResponse.internalServerError();
return;
}
// Hide password from output
dbUser.password = null;
httpResponse.response(new BetterGson().newInstance().toJson(dbUser));
}
}
| true
|
908eedd18e28fb15f6684f323bb0d4dc933434e4
|
Java
|
Manifold0/adcom_decompile
|
/sources/com/google/android/gms/games/stats/Stats.java
|
UTF-8
| 617
| 1.789063
| 2
|
[] |
no_license
|
package com.google.android.gms.games.stats;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Releasable;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.util.VisibleForTesting;
@Deprecated
@VisibleForTesting
public interface Stats {
@Deprecated
public interface LoadPlayerStatsResult extends Releasable, Result {
PlayerStats getPlayerStats();
}
PendingResult<LoadPlayerStatsResult> loadPlayerStats(GoogleApiClient googleApiClient, boolean z);
}
| true
|
9f1e227207d55398fe4690e0c445058d4b70ab76
|
Java
|
pointer95/leetcode
|
/algorithms/java/src/permutations/Solution.java
|
UTF-8
| 1,054
| 3.1875
| 3
|
[] |
no_license
|
package permutations;
import java.util.ArrayList;
import java.util.List;
/**
* source: https://leetcode-cn.com/problems/permutations/
* date: 2019/10/29
*/
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums.length == 0) return res;
int[] visit = new int[nums.length];
permuteHelper(nums, visit, res, new ArrayList<>());
return res;
}
private void permuteHelper(int[] nums, int[] visit,
List<List<Integer>> res,
ArrayList<Integer> tempList) {
if (tempList.size() == nums.length) {
res.add(new ArrayList<>(tempList));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visit[i] == 1) continue;
tempList.add(nums[i]);
visit[i] = 1;
permuteHelper(nums, visit, res, tempList);
tempList.remove(tempList.size() - 1);
visit[i] = 0;
}
}
}
| true
|
e5497c2e0261f05d0eed3d96166ecdc1c4e00ab2
|
Java
|
sebastienduche/MyCellar
|
/src/mycellar/search/SearchTableModel.java
|
UTF-8
| 4,016
| 2.25
| 2
|
[] |
no_license
|
package mycellar.search;
import mycellar.MyCellarUtils;
import mycellar.Program;
import mycellar.core.MyCellarObject;
import mycellar.core.text.LabelProperty;
import mycellar.general.ProgramPanels;
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
import java.util.List;
import static mycellar.core.text.MyCellarLabelManagement.getLabel;
/**
* Titre : Cave à vin
* Description : Votre description
* Copyright : Copyright (c) 2003
* Société : Seb Informatique
*
* @author Sébastien Duché
* @version 3.7
* @since 25/05/22
*/
class SearchTableModel extends AbstractTableModel {
static final int ETAT = 0;
static final int SHOW = 7;
private static final long serialVersionUID = -3899189654755476591L;
private final List<String> columnNames = List.of("",
getLabel("Main.Item", LabelProperty.SINGLE.withCapital()), getLabel("Main.Year"), getLabel("Main.Storage"),
getLabel("MyCellarFields.NumPlace"), getLabel("MyCellarFields.Line"), getLabel("MyCellarFields.Column"), "");
private final List<Boolean> listBoolean = new ArrayList<>();
private final List<MyCellarObject> datas = new ArrayList<>();
@Override
public int getRowCount() {
if (datas == null) {
return 0;
}
return datas.size();
}
@Override
public int getColumnCount() {
return columnNames.size();
}
@Override
public Object getValueAt(int row, int column) {
if (row >= datas.size()) {
Program.Debug("SearchTableModel: Error index " + row + " > " + datas.size());
return "";
}
if (row >= listBoolean.size()) {
Program.Debug("SearchTableModel: Error listBoolean index " + row + " > " + datas.size());
return "";
}
final MyCellarObject myCellarObject = datas.get(row);
switch (column) {
case ETAT:
return listBoolean.get(row);
case 1:
return MyCellarUtils.convertStringFromHTMLString(myCellarObject.getNom());
case 2:
return myCellarObject.getAnnee();
case 3:
if (myCellarObject.isInTemporaryStock()) {
return getLabel("Bouteille.TemporaryPlace");
}
return myCellarObject.getEmplacement();
case 4:
return Integer.toString(myCellarObject.getNumLieu());
case 5:
return Integer.toString(myCellarObject.getLigne());
case 6:
return Integer.toString(myCellarObject.getColonne());
case SHOW:
return Boolean.FALSE;
default:
return "";
}
}
@Override
public String getColumnName(int column) {
return columnNames.get(column);
}
@Override
public boolean isCellEditable(int row, int column) {
return (column == ETAT || column == SHOW);
}
@Override
public void setValueAt(Object value, int row, int column) {
switch (column) {
case SHOW:
ProgramPanels.showBottle(datas.get(row), true);
break;
case ETAT:
listBoolean.set(row, (Boolean) value);
break;
}
}
void addObjects(List<MyCellarObject> myCellarObjects) {
if (myCellarObjects != null) {
myCellarObjects.forEach(myCellarObject -> {
datas.add(myCellarObject);
listBoolean.add(Boolean.FALSE);
});
fireTableDataChanged();
}
}
void removeAll() {
datas.clear();
listBoolean.clear();
fireTableDataChanged();
}
void removeObject(MyCellarObject myCellarObject) {
int index = datas.indexOf(myCellarObject);
if (index != -1) {
datas.remove(myCellarObject);
listBoolean.remove(index);
fireTableDataChanged();
}
}
List<MyCellarObject> getDatas() {
return datas;
}
boolean doesNotContain(MyCellarObject b) {
return !datas.contains(b);
}
List<MyCellarObject> getSelectedObjects() {
List<MyCellarObject> selectedObjects = new ArrayList<>();
for (int i = 0; i < listBoolean.size(); i++) {
if (listBoolean.get(i)) {
selectedObjects.add(datas.get(i));
}
}
return selectedObjects;
}
}
| true
|
351a9072e360defaa46611019d1ea2012a8ace60
|
Java
|
CoderNoOne/Hibernate-Project
|
/src/main/java/converters/impl/ProductDtoListJsonConverter.java
|
UTF-8
| 283
| 1.820313
| 2
|
[
"MIT"
] |
permissive
|
package converters.impl;
import converters.JsonConverter;
import dto.ProductDto;
import java.util.List;
public class ProductDtoListJsonConverter extends JsonConverter <List<ProductDto>> {
public ProductDtoListJsonConverter(String jsonFilename) {
super(jsonFilename);
}
}
| true
|
7e0322be204d41079bc46e2d6f54ddc99d6b382a
|
Java
|
hyponet/ayanami
|
/src/main/java/xyz/acmer/service/impl/ContestServiceImpl.java
|
UTF-8
| 14,027
| 2.328125
| 2
|
[
"MIT"
] |
permissive
|
package xyz.acmer.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.acmer.entity.contest.ContestAnnouncement;
import xyz.acmer.entity.contest.ContestInfo;
import xyz.acmer.entity.contest.ContestProblem;
import xyz.acmer.entity.contest.ContestType;
import xyz.acmer.entity.problem.Status;
import xyz.acmer.entity.user.User;
import xyz.acmer.repository.contest.ContestAnnouncementRepository;
import xyz.acmer.repository.contest.ContestInfoRepository;
import xyz.acmer.repository.contest.ContestProblemRepository;
import xyz.acmer.repository.contest.ContestTypeRepository;
import xyz.acmer.repository.problem.StatusRepository;
import xyz.acmer.service.IBalanceService;
import xyz.acmer.service.IContestService;
import xyz.acmer.service.IProblemService;
import xyz.acmer.util.StringHelper;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
/**
* 比赛相关Service
* Created by hypo on 16-2-26.
*/
@Service
public class ContestServiceImpl implements IContestService{
@Autowired
private ContestInfoRepository contestInfoRepository;
@Autowired
private ContestProblemRepository contestProblemRepository;
@Autowired
private ContestTypeRepository contestTypeRepository;
@Autowired
private ContestAnnouncementRepository contestAnnouncementRepository;
@Autowired
private StatusRepository statusRepository;
@Autowired
private IProblemService problemService;
@Autowired
private IBalanceService balanceService;
/**
* 新增比赛
*
* @param title 比赛标题
* @param beginTime 开始时间
* @param length 比赛时间(长度)
* @param password 比赛密码(可为空)
* @param description 描述
* @param contestType 比赛类型(奖罚与类型有关)
* @param problems 添加的题目
* @param user 创建者(对该比赛有绝对权限)
* @return
*/
@Override
public ContestInfo addContest(String title, Date beginTime, Integer length, String password, String description,
ContestType contestType, Set<ContestProblem> problems, User user) {
title = StringHelper.getSafeString(title, 100);
description = StringHelper.getSafeString(description, 255);
if(password != null && password.length() == 0){
password = null;
}
ContestInfo contestInfo = new ContestInfo(user, title, beginTime, length, password, description, contestType);
contestInfo.setProblems(problems);
// 扣取创建该比赛所需积分
balanceService.spend(user, contestType.getCreateSpend(), "创建比赛 [" + title + "]");
contestInfoRepository.save(contestInfo);
return contestInfo;
}
/**
* 更新比赛信息
* #不允许删除比赛#,因为每次用户积分的变动需要有稽可查
*
* @param title 更新的标题
* @param beginTime 更新开始时间,如果比赛已经开始,这不能修改
* @param length 比赛长度,可以延时
* @param password 更新密码,可为空
* @param description 更新描述
* @param contestType 如果比赛开始,类型不能再修改
* @param problems 更新题目, 如果比赛开始,题目不能被修改
* @return
*/
@Override
public ContestInfo updateContest(ContestInfo contestInfo, String title, Date beginTime,
Integer length, String password, String description,
ContestType contestType, Set<ContestProblem> problems) {
Date nowDate = new Date();
Date oldBeginTime = contestInfo.getBeginTime();
title = StringHelper.getSafeString(title, 100);
description = StringHelper.getSafeString(description, 255);
if(password != null && password.length() == 0){
password = null;
}
contestInfo.setTitle(title);
contestInfo.setDescription(description);
contestInfo.setPassword(password);
contestInfo.setLength(length);
if(oldBeginTime.after(nowDate)){
contestInfo.setBeginTime(beginTime);
contestInfo.setContestType(contestType);
contestInfo.setProblems(problems);
}
contestInfoRepository.save(contestInfo);
return contestInfo;
}
/**
* 调用ProblemService的方法提交程序并返回结果
* 结果返回成功后根据比赛类型对用户积分进行更新
*
* @param problem
* @param code
* @param language
* @param user
* @param contestInfo
* @return
*/
@Override
public Status submitProblem(ContestProblem problem, String code, String language,
User user, ContestInfo contestInfo) {
Status status = problemService.submitProblem(problem.getProblem(), code, language, user, contestInfo);
if(status == null){
return null;
}
ContestType contestType = contestInfo.getContestType();
balanceService.spend(user, contestType.getSubmitSpend(),
"在[" + contestInfo.getTitle()+ "]比赛中,向 " + problem.getTitle() + " 提交代码");
if(status.getResult().equals("Accepted")){
balanceService.get(user, contestType.getAcceptedAward(),
"在[" + contestInfo.getTitle()+ "]比赛中,手刃 " + problem.getTitle());
List<Status> statuses = statusRepository.getStatusByContestInfoAndProblem(contestInfo, problem.getProblem());
if(statuses == null || statuses.size() == 1){
// 一血
balanceService.get(user, contestType.getAcceptedAward(),
"在[" + contestInfo.getTitle()+ "]比赛中,获得题目 " + problem.getTitle() + " 一血");
}
}
return status;
}
/**
* 获得比赛列表(根据开始时间排序)
*
* @return
*/
@Override
public List<ContestInfo> getAllContest() {
return contestInfoRepository.getAllContestByBeginTime();
}
/**
* 根据时间(未开始 进行中 已结束)获得比赛列表
*
* @param time scheduled | running | ended
* @return
*/
@Override
public List<ContestInfo> getContestByTime(String time) {
if(time == null){
return new ArrayList<ContestInfo>();
}
if(time.equals("scheduled")){
return contestInfoRepository.getContestScheduled(new Date());
}else if(time.equals("running")){
return contestInfoRepository.getContestRunning(new Date());
}else if(time.equals("ended")){
return contestInfoRepository.getContestEnded(new Date());
}else {
return getAllContest();
}
}
/**
* 根据比赛类型获得比赛列表
*
* @param contestType
* @return
*/
@Override
public List<ContestInfo> getContestByType(ContestType contestType) {
return contestInfoRepository.getContestByContestType(contestType);
}
/**
* 新增比赛类型
*
* @param typeName 类型名称
* @param createSpend 创建该比赛的花费
* @param firstBlood 一血的奖励
* @param champion 冠军奖励
* @param second 亚军奖励
* @param third 季军奖励
* @param submitSpend 每次提交的花费
* @param acceptedAward 每次AC的奖励
* @return
*/
@Override
public ContestType addContestType(String typeName, Integer createSpend, Integer firstBlood,
Integer champion, Integer second, Integer third,
Integer submitSpend, Integer acceptedAward) {
createSpend = createSpend < 0 ? createSpend * -1 : createSpend;
firstBlood = firstBlood < 0 ? firstBlood * -1 : firstBlood;
champion = champion < 0 ? champion * -1 : champion;
second = second < 0 ? second * -1 : second;
third = third < 0 ? third * -1 : third;
submitSpend = submitSpend < 0 ? submitSpend * -1 : submitSpend;
acceptedAward = acceptedAward < 0 ? acceptedAward * -1 : acceptedAward;
ContestType contestType = new ContestType(typeName, createSpend, firstBlood,
champion, second, third, submitSpend, acceptedAward);
contestTypeRepository.save(contestType);
return contestType;
}
/**
* 更新比赛类型
*
* @param typeName 类型名称
* @param createSpend 创建该比赛的花费
* @param firstBlood 一血的奖励
* @param champion 冠军奖励
* @param second 亚军奖励
* @param third 季军奖励
* @param submitSpend 每次提交的花费
* @param acceptedAward 每次AC的奖励
* @return
*/
@Override
public Boolean updateContestType(String typeName, Integer createSpend, Integer firstBlood,
Integer champion, Integer second, Integer third,
Integer submitSpend, Integer acceptedAward, ContestType contestType) {
contestType.setCreateSpend(createSpend < 0 ? createSpend * -1 : createSpend);
contestType.setFirstBlood(firstBlood < 0 ? firstBlood * -1 : firstBlood);
contestType.setChampion(champion < 0 ? champion * -1 : champion);
contestType.setSecond(second < 0 ? second * -1 : second);
contestType.setThird(third < 0 ? third * -1 : third);
contestType.setSubmitSpend(submitSpend < 0 ? submitSpend * -1 : submitSpend);
contestType.setAcceptedAward(acceptedAward < 0 ? acceptedAward * -1 : acceptedAward);
contestTypeRepository.save(contestType);
return true;
}
/**
* 删除比赛类型
* 因为外键的关系,如果该类型已经被添加比赛,则不能删除
* 建议更新比赛类型而不是删除
*
* @param contestTypeId
* @return
*/
@Override
public Boolean deleteContestType(Integer contestTypeId) {
ContestType contestType = contestTypeRepository.findOne(contestTypeId);
if(contestType == null){
return false;
}
List<ContestInfo> contestInfos = contestInfoRepository.getContestByContestType(contestType);
if(contestInfos == null || contestInfos.size() == 0){
contestTypeRepository.delete(contestTypeId);
return true;
}
return false;
}
/**
* 获得所有的比赛类型
*
* @return
*/
@Override
public List<ContestType> getAllContestType() {
return contestTypeRepository.findAll();
}
/**
* 新增比赛公告
*
* @param title 公告标题
* @param content 公告内容
* @param autherName 作者名称
* @param contest 所属比赛
* @return
*/
@Override
public ContestAnnouncement addContestAnnouncement(User user, String title, String content,
String autherName, ContestInfo contest) {
if(contest.getCreater().getUserId() == user.getUserId()){
title = StringHelper.getSafeString(title, 100);
content = StringHelper.getSafeString(content, 255);
autherName = StringHelper.getSafeString(autherName, 50);
ContestAnnouncement contestAnnouncement = new ContestAnnouncement(contest, title, content, autherName);
contestAnnouncementRepository.save(contestAnnouncement);
return contestAnnouncement;
}
return null;
}
/**
* 更新比赛公告内容
*
* @param title 公告标题
* @param content 公告内容
* @param autherName 作者名称
* @param contestAnnouncementId 所需更新的公告
* @return
*/
@Override
public Boolean updateContestAnnouncement(String title, String content, String autherName,
Long contestAnnouncementId, User user) {
if(user == null){
return false;
}
ContestAnnouncement contestAnnouncement = contestAnnouncementRepository.getOne(contestAnnouncementId);
if(contestAnnouncement == null){
return false;
}
if(contestAnnouncement.getContest().getCreater().getUserId() == user.getUserId()){
title = StringHelper.getSafeString(title, 100);
content = StringHelper.getSafeString(content, 255);
autherName = StringHelper.getSafeString(autherName, 50);
contestAnnouncement.setTitle(title);
contestAnnouncement.setContent(content);
contestAnnouncement.setAutherName(autherName);
contestAnnouncementRepository.save(contestAnnouncement);
return true;
}
return false;
}
/**
* 删除公告
*
* @param contestAnnouncementId 要删除的公告ID
* @param user 操作用户(验证权限,只有比赛创建者有权限删除)
* @return
*/
@Override
public Boolean deleteContestAnnouncement(Long contestAnnouncementId, User user) {
if(user == null){
return false;
}
ContestAnnouncement contestAnnouncement = contestAnnouncementRepository.getOne(contestAnnouncementId);
if(contestAnnouncement == null){
return false;
}
if(contestAnnouncement.getContest().getCreater().getUserId() == user.getUserId()){
contestAnnouncementRepository.delete(contestAnnouncementId);
return true;
}
return false;
}
}
| true
|
dfc0a89a6899f3946137969d4820383a0e8a3a2d
|
Java
|
5mm/balsize
|
/Source/DontTouchMe/DontTouchMe/app/src/main/java/com/devroo/donttouchme/FourFragment.java
|
UTF-8
| 3,337
| 2.40625
| 2
|
[] |
no_license
|
package com.devroo.donttouchme;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.devroo.donttouchme.Adapter.AdapterSetting;
import com.devroo.donttouchme.Fragment.FragmentApplication;
import com.devroo.donttouchme.Fragment.FragmentRoom;
import com.devroo.donttouchme.Fragment.FragmentSubject;
import com.devroo.donttouchme.Fragment.FragmentTime;
import java.util.ArrayList;
public class FourFragment extends Fragment implements View.OnClickListener {
//Fragment의 View 작업을 하는 function
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.four_fragment, container, false);
TextView topTitle = (TextView) view.findViewById(R.id.topTitle);
topTitle.setText("설정");
ArrayList image_details = getListData();
final ListView lv1 = (ListView) view.findViewById(R.id.listView);
lv1.setAdapter(new AdapterSetting(getActivity(), image_details));
// InnerClass 방식으로 Listener 호출하는 방식
lv1.setOnItemClickListener( new ListViewItemClickListener() );
return view;
}
// 데이터 가져오기
private ArrayList getListData() {
ArrayList<String> results = new ArrayList<String>();
results.add(new String("과제알림날짜"));
results.add(new String("시간표 시간설정"));
results.add(new String("어플리케이션 차단"));
results.add(new String("강의실 위치관리"));
return results;
}
//ImageButton 클릭 시 fragmentReplace 호출
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_ok:
break;
}
}
// InnerClass Listener방식으로 구현
private class ListViewItemClickListener implements android.widget.AdapterView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fragment newFragment = null;
FragmentManager fragmentManager;
final FragmentTransaction transaction;
switch (position) {
case 0:
//D-Days
newFragment = new FragmentSubject();
break;
case 1:
//Time Schedule
newFragment = new FragmentTime();
break;
case 2:
//Block Application
newFragment = new FragmentApplication();
break;
case 3:
//Room Location
newFragment = new FragmentRoom();
break;
}
fragmentManager = getFragmentManager();
transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.view_fragment, newFragment);
transaction.commit();
}
}
}
| true
|
66d0073c268f62be5d3b9040d47c69559105368b
|
Java
|
mrajput-systango/movies-app-android
|
/app/src/main/java/com/otb/mvvmboilerplate/viewmodel/MoviesViewModel.java
|
UTF-8
| 1,587
| 2.390625
| 2
|
[] |
no_license
|
package com.otb.mvvmboilerplate.viewmodel;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import com.otb.mvvmboilerplate.data.MovieRepository;
import com.otb.mvvmboilerplate.network.response.ApiResponse;
import javax.inject.Inject;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
/**
* Created by Mohit Rajput on 11/2/19.
* Movies data view-model
*/
public class MoviesViewModel extends ViewModel {
private final CompositeDisposable disposables = new CompositeDisposable();
private MovieRepository movieRepository;
private MutableLiveData<ApiResponse> moviesLiveData = new MutableLiveData<>();
@Inject
public MoviesViewModel(MovieRepository movieRepository) {
this.movieRepository = movieRepository;
}
public MutableLiveData<ApiResponse> observeMoviesResponse() {
return moviesLiveData;
}
public void fetchMovies() {
disposables.add(movieRepository.fetchAllMovies()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe((d) -> moviesLiveData.setValue(ApiResponse.loading()))
.subscribe(
result -> moviesLiveData.setValue(ApiResponse.success(result)),
throwable -> moviesLiveData.setValue(ApiResponse.error(throwable))
));
}
@Override
protected void onCleared() {
disposables.clear();
}
}
| true
|
adfd81be130b2695944204507c0ea22361879756
|
Java
|
nikitasah/Library-Management
|
/src/main/java/com/utd/libmgmnt/model/Fine.java
|
UTF-8
| 1,046
| 2.828125
| 3
|
[] |
no_license
|
package com.utd.libmgmnt.model;
/*
* Description : Author is used to get and set the parameters of the fine table in the application.
* @author : nikita
*/
public class Fine {
private int loanId;
private float fineAmt;
private boolean paid;
private Loan loan;
private Borrower borrower;
public Borrower getBorrower() {
return borrower;
}
public void setBorrower(Borrower borrower) {
this.borrower = borrower;
}
public Loan getLoan() {
return loan;
}
public void setLoan(Loan loan) {
this.loan = loan;
}
/* Getters and Setters for fine table */
public int getLoanId() {
return loanId;
}
public void setLoanId(int loanId) {
this.loanId = loanId;
}
public float getFineAmt() {
return fineAmt;
}
public void setFineAmt(float fineAmt) {
this.fineAmt = fineAmt;
}
public boolean isPaid() {
return paid;
}
public void setPaid(boolean paid) {
this.paid = paid;
}
@Override
public String toString() {
return "Fine{" + "loanId=" + loanId + ",paid =" + paid + ", fineAmt=" + fineAmt +'}';
}
}
| true
|
e42bd275a2d5de99ad1aa267e11754f79f565356
|
Java
|
csr88/Java_Codes
|
/TernaryOperators.java
|
UTF-8
| 952
| 4.1875
| 4
|
[] |
no_license
|
package com.company;
public class TernaryOperators {
public static void main(String[] args) {
//know if the number num is even or odd
int num = 10;
String res;
//if remainder of num/2 is true i.e. 0 then it will give even if it is false then print odd
res = (num%2==0)?"even":"odd";
System.out.println(res);
int lam = 121;
String jet = (lam%2==0)?"This is an even number":"This is an odd number";
System.out.println(jet);
//to know if the number is positive or negative
int number = -3;
String you = (number < 0)?"Negative number":"Positive number";
System.out.println(you);
//if the number is + then give its negative and vice versa
int fly = -13;
int me = (fly<0)?-fly:-fly;
System.out.println(me);
int sky = 77;
int they = (sky<0)?-sky:-sky;
System.out.println(they);
}
}
| true
|
a5dc26770a3cf4f42420ff917ff7835a1b256561
|
Java
|
forste/tagaprice
|
/src/main/java/org/tagaprice/client/gwt/shared/logging/LoggerFactory.java
|
UTF-8
| 205
| 1.890625
| 2
|
[] |
no_license
|
package org.tagaprice.client.gwt.shared.logging;
public class LoggerFactory {
@SuppressWarnings("rawtypes")
public static MyLogger getLogger(Class theClass) {
return new MyLoggerImpl(theClass);
}
}
| true
|
12aece8f55c4ce251c621a3dedc781ced914c45f
|
Java
|
mingwei-cheng/spring-cloud-seata-demo
|
/common/src/main/java/ch/cheng/seata/service/AccountService.java
|
UTF-8
| 249
| 1.820313
| 2
|
[] |
no_license
|
package ch.cheng.seata.service;
public interface AccountService {
/**
* 扣减用户余额
*
* @param userId 用户id
* @param price 价格
*/
Boolean reduceBalance(Long userId, Integer price) throws Exception;
}
| true
|
8c4bcababd5691066ae144c20d701c3063f98e33
|
Java
|
wubo19961213/HelloWorld
|
/src/com/Animal/Animal.java
|
GB18030
| 268
| 3.34375
| 3
|
[] |
no_license
|
package com.Animal;
public abstract class Animal {
protected int legs;
protected Animal(int legs) {
this.legs = legs;
}
public abstract void eat();
public void walk(Animal a) {
System.out.println("Ǹ"+a.legs+"·Ķ");
}
}
| true
|
6ca2a98f760599ddfde02447937f9e022a3a62ec
|
Java
|
leetcode-1533/Leetcode_Practice
|
/insertion_sort_list/Solution.java
|
UTF-8
| 1,571
| 3.25
| 3
|
[] |
no_license
|
package insertion_sort_list;
import edu.princeton.cs.algs4.StdOut;
public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head == null) {
return null;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
// ListNode pointer = head;
ListNode in;
ListNode jn;
ListNode inn;
ListNode temp = new ListNode(0);
// ListNode jnn = jn.next;
for(ListNode i = head; i.next != null; ) {
// StdOut.println();
boolean inserted = false;
for(ListNode j = dummy; j.next != i.next; j = j.next) {
if(i.next.val < j.next.val) {
in = i.next;
jn = j.next;
inn = in.next;
// jnn = jn.next;
j.next = in;
in.next = jn;
i.next = inn;
inserted = true;
break;
}
}
// StdOut.println("Dummy" + dummy);
if(!inserted)
i = i.next;
}
return dummy.next;
}
public static void main(String[] args) {
ListNode test = ListNode.randomeNode(10, 3);
StdOut.println(test);
Solution sol = new Solution();
test = sol.insertionSortList(test);
StdOut.println(test);
}
}
| true
|
ddd46e7814a6ad0b585b112de8949bf7782c4631
|
Java
|
anilrewatown/eclipse-workspace
|
/PracticeJava/src/streamapi/Test1.java
|
UTF-8
| 1,194
| 2.796875
| 3
|
[] |
no_license
|
package streamapi;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class Test1 {
public static void main(String[] args) {
String s = "my name is anil and my country name is india";
String[] tokens = s.split(" ");
/* int len = tokens.length;
List<String> notDuplicate = new ArrayList<>();
List<String> duplicate = new ArrayList<>();
for(int i=0; i<len; i++) {
if(!notDuplicate.contains(tokens[i])) {
notDuplicate.add(tokens[i]);
}else {
duplicate.add(tokens[i]);
}
}
notDuplicate.removeAll(duplicate);
System.out.println(duplicate);
System.out.println(notDuplicate);*/
List<String> list = Arrays.asList(tokens);
Set<String> duplicate = new HashSet<String>();
List<String> list1=list.stream().filter(x-> !duplicate.add(x)).collect(Collectors.toList());
System.out.println(list1);
System.out.println(duplicate);
List<String> readOnly = Collections.unmodifiableList(list);
readOnly.add("abc");
}
}
| true
|
d25627b072d65c191ed6579872bef10153c67ea0
|
Java
|
dnoise/IG-6.9.1-decompiled
|
/src/com/instagram/android/directshare/d/o.java
|
UTF-8
| 764
| 1.609375
| 2
|
[] |
no_license
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.instagram.android.directshare.d;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.instagram.feed.d.l;
// Referenced classes of package com.instagram.android.directshare.d:
// c
final class o extends BroadcastReceiver
{
final c a;
o(c c1)
{
a = c1;
super();
}
public final void onReceive(Context context, Intent intent)
{
c.b(a);
if (intent.getAction().equals(l.a(c.c(a))))
{
c.a(a, true);
c.d(a);
}
}
}
| true
|
7bd543c064f968e4bbeca05122bc19c0d9ac7a41
|
Java
|
yaneeves/Interview
|
/src/main/java/com/mobli/interview/broker/MessageBrokerImpl.java
|
UTF-8
| 464
| 2.0625
| 2
|
[] |
no_license
|
package com.mobli.interview.broker;
import com.mobli.interview.consumer.SmsConsumer;
import com.mobli.interview.data.SmsMessage;
public class MessageBrokerImpl implements MessageBroker {
@Override
public void addSubscriber(SmsConsumer consumer) {
}
@Override
public void removeSubscriber(SmsConsumer consumer) {
}
@Override
public void receive(SmsMessage message) {
}
@Override
public void shutdown() {
}
}
| true
|
47992853bd7e6e4488d53b386c317f26848c04cd
|
Java
|
capybarin/DB_Client
|
/src/sample/controllers/AddManufacture.java
|
UTF-8
| 1,242
| 2.53125
| 3
|
[] |
no_license
|
package sample.controllers;
import io.reactivex.Scheduler;
import io.reactivex.rxjavafx.schedulers.JavaFxScheduler;
import io.reactivex.schedulers.Schedulers;
import javafx.event.ActionEvent;
import javafx.scene.Node;
import javafx.scene.control.TextField;
import sample.data.Database;
public class AddManufacture {
public TextField name;
private Database db;
{
try {
db = Database.getInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void save(ActionEvent actionEvent){
if(!name.getText().isBlank()){
db.addManufacture(name.getText())
.subscribeOn(Schedulers.io())
.observeOn(JavaFxScheduler.platform())
.subscribe(result -> {
System.out.println("success");
((Node)(actionEvent.getSource())).getScene().getWindow().hide();
}, throwable -> {
System.out.println(throwable.getLocalizedMessage());
});
}
}
public void close(ActionEvent actionEvent){
((Node)(actionEvent.getSource())).getScene().getWindow().hide();
}
}
| true
|
f49ebac21b7d16d93dc8919759c21acaa199269c
|
Java
|
sunkaiiii/instabtbu
|
/instabtbu/src/main/java/hk/ypw/instabtbu/xiaoyuanka_guashi.java
|
UTF-8
| 1,062
| 1.984375
| 2
|
[] |
no_license
|
package hk.ypw.instabtbu;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.RelativeLayout.LayoutParams;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
public class xiaoyuanka_guashi extends SwipeBackActivity {
Activity thisActivity = this;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xiaoyuanka_guashi);
}
public void dianhua(View v) {
Intent intent = new Intent(Intent.ACTION_DIAL,
Uri.parse("tel:01081353262"));
try {
startActivity(intent);
} catch (Exception e) {
new AlertDialog.Builder(thisActivity).setTitle("提示")
.setMessage("您的设备暂时不支持拨打电话。").setPositiveButton("确定", null)
.show();
}
}
}
| true
|
837170ac39a2a4e1f776063b2a8f5ecb91bb0b2d
|
Java
|
travel-cloud/Cheddar
|
/cheddar/cheddar-integration-aws/src/main/java/com/clicktravel/infrastructure/persistence/aws/elasticache/MemcachedItemCache.java
|
UTF-8
| 2,256
| 2.34375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2014 Click Travel Ltd
*
* 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.clicktravel.infrastructure.persistence.aws.elasticache;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.clicktravel.cheddar.infrastructure.persistence.cache.ItemCache;
import net.spy.memcached.MemcachedClient;
public class MemcachedItemCache implements ItemCache {
private final MemcachedClient memcachedClient;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public MemcachedItemCache(final MemcachedClient memcachedClient) {
this.memcachedClient = memcachedClient;
}
@Override
public Object getItem(final String key, final long timeout) {
Object item = null;
final Future<Object> f = memcachedClient.asyncGet(key);
try {
item = f.get(timeout, TimeUnit.SECONDS);
} catch (final TimeoutException e) {
f.cancel(false);
logger.trace("Unable to get cache item within given time", e);
return null;
} catch (final InterruptedException | ExecutionException e) {
logger.debug("Unable to get cache item", e);
}
return item;
}
@Override
public void putItem(final String key, final Object item, final long expire) {
if (expire < Integer.MIN_VALUE || expire > Integer.MAX_VALUE) {
throw new IllegalArgumentException(expire + " cannot be cast to int without changing its value.");
}
memcachedClient.set(key, (int) expire, item);
}
}
| true
|
fd33517682939bf7f87612e0e494034ac1022197
|
Java
|
ibisTime/xn-forum
|
/src/main/java/com/std/forum/api/impl/XN610025.java
|
UTF-8
| 1,724
| 2.078125
| 2
|
[] |
no_license
|
package com.std.forum.api.impl;
import org.apache.commons.lang3.StringUtils;
import com.std.forum.ao.IBplateAO;
import com.std.forum.ao.IBplateTemplateAO;
import com.std.forum.api.AProcessor;
import com.std.forum.common.JsonUtil;
import com.std.forum.core.StringValidater;
import com.std.forum.domain.Bplate;
import com.std.forum.dto.req.XN610025Req;
import com.std.forum.exception.BizException;
import com.std.forum.exception.ParaException;
import com.std.forum.spring.SpringContextHolder;
/**
* 分页查询大板块
* @author: asus
* @since: 2017年3月20日 下午6:13:58
* @history:
*/
public class XN610025 extends AProcessor {
private IBplateAO bplateAO = SpringContextHolder.getBean(IBplateAO.class);
private XN610025Req req = null;
@Override
public Object doBusiness() throws BizException {
Bplate condition = new Bplate();
condition.setName(req.getName());
condition.setStatus(req.getStatus());
condition.setCompanyCode(req.getCompanyCode());
String orderColumn = req.getOrderColumn();
if (StringUtils.isBlank(orderColumn)) {
orderColumn = IBplateTemplateAO.DEFAULT_ORDER_COLUMN;
}
condition.setOrder(orderColumn, req.getOrderDir());
int start = StringValidater.toInteger(req.getStart());
int limit = StringValidater.toInteger(req.getLimit());
return bplateAO.queryBplatePage(start, limit, condition);
}
@Override
public void doCheck(String inputparams) throws ParaException {
req = JsonUtil.json2Bean(inputparams, XN610025Req.class);
StringValidater.validateNumber(req.getStart(), req.getLimit());
}
}
| true
|
3bb07f0b0e54f9f9d5108c92fdbc76dbd01f22e7
|
Java
|
evtimovi/MemoryManagers
|
/Process.java
|
UTF-8
| 7,370
| 3.609375
| 4
|
[] |
no_license
|
/**
* represents a process and thus holds a page table and allows the Controller to tell it to read or write from a given virtual address.
*
* CS 406 Operating Systems
* Spring 2016, Lafayette College
* Professor Amir Sadovnik
*
* Project 3
*
* Renan Dincer and Ivan Evtimov
*
* @author Renan Dincer
* @author Ivan Evtimov
*
*/
import java.util.*;
public class Process
{
/**
* this might need a more sophisticated implementation than an ArrayList, but
* it represents the page table and is addressed by frame number
* this is essentially the Virtual Address Space of the process so it should always be initialized as follows:
* - exactly as big as the total possible number of pages in the system (need to reference global user-supplied parameters during initialization)
* - at the point of initialization, each Frame object being held in here has its number set to -1 and is assumed to not be loaded in main memory
* as frames are accessed and loaded into main memory, each Frame object is updated accordingly
*/
private ArrayList<Frame> pageTable;
/** this process' unique identifier*/
private int pid;
/**
* default constructs an empty process based on the Controller parameters.
* note that for this constructor to execute properly, these parameters need to have intialized by a call to setup in the Controller
* NO PID ASSIGNED!!!!
*/
public Process() throws ParametersUninitializedException
{
if(! Controller.PARAM_INIT)
{
throw new ParametersUninitializedException("");
}
pageTable = new ArrayList<Frame>(Controller.NUM_OF_PAGES);
for (Frame f : pageTable)
{
f = new Frame();
}
}
/** same as default, but pid is assigned as provided, use this not the default */
public Process(int id) throws ParametersUninitializedException
{
if(! Controller.PARAM_INIT)
{
throw new ParametersUninitializedException("");
}
pid = id;
pageTable = new ArrayList<Frame>(Controller.NUM_OF_PAGES);
for (int i = 0; i < Controller.NUM_OF_PAGES; i++)
{
pageTable.add(new Frame(pid));
}
}
/**
* method to simulate a read.
* will follow this procedural flow:
* 1. strip the offset from the virtual address being passed as a parameter
* (need to reference global parameters about the bits allocated to the offset here)
* 2. use resulting page number to look up a Frame object in its page table
* 3. get the Frame object's number and call the MemoryManager in order to access that frame*
* * note that we need to figure out who owns the memory manager here - is it passed as a parameter or is a reference to it stored in each process object?
* also note that this Frame object being used here should be, if all is implemented as intended,
* the EXACT SAME instance that is also stored in the PhysicalMemory object
* of course, this is a departure from reality, but makes this simulation more efficient
* because we don't have to go back to the process to update its page table when we do page replacement
*
* @return translated address (that is, full physical address)
*/
public void read(int address)
{
int pageNum = whichPage(address);
Frame fr = pageTable.get(pageNum);
MemoryManager mm = Controller.getMemoryManager();
int replacedFrame = mm.reference(fr);
if(replacedFrame < 0) //no page fault
{
printNoPageFaultMsg(fr.getNumber());
System.out.println("\tVirtual address: " + address + "-> Physical address: " + this.whichPhysicalAddress(address, fr.getNumber()) + " ");
}
else
{
printLoadedMsg(pageNum, this.pid, replacedFrame);
System.out.println("\tVirtual address: " + address + "-> Physical address: " + this.whichPhysicalAddress(address, replacedFrame) + " ");
}
}
/**
* method to simulate a read.
* follow steps for read BUT
* add step 4:
* 4. set dirty bit to true
*/
public void write(int address)
{
int pageNum = whichPage(address);
Frame fr = pageTable.get(pageNum);
MemoryManager mm = Controller.getMemoryManager();
int replacedFrame = mm.reference(fr);
fr.setDirtyBit();
if(replacedFrame < 0) //no page fault
{
printNoPageFaultMsg(fr.getNumber());
System.out.println("\tVirtual address: " + address + "-> Physical address: " + this.whichPhysicalAddress(address, fr.getNumber()) + " ");
}
else
{
printLoadedMsg(pageNum, this.pid, replacedFrame);
System.out.println("\tVirtual address: " + address + "-> Physical address: " + this.whichPhysicalAddress(address, replacedFrame) + " ");
}
}
/**
* method used to translate address into VIRTUAL page number, thereby stripping the offset.
* will be useful as helper in read and write, but also in the algorithms that need future knowledge of page accesses
*/
public int whichPage(int address)
{
//convert to bit string and pad with leading 0s to make it 16 bits long
String bitAddress = Integer.toBinaryString(address);
bitAddress = padWithZeroes(bitAddress);
//get just the front - i.e. the page number
String pageNumBinary = bitAddress.substring(0, Controller.PAGE_NUMBER_LENGTH);
//parse that to a real integer and return it
return Integer.parseInt(pageNumBinary, 2);
}
public int whichPhysicalAddress(int address, int frameNum)
{
//convert to bit string and pad with leading 0s to make it 16 bits long
String bitAddress = Integer.toBinaryString(address);
bitAddress = padWithZeroes(bitAddress);
String frameBinary = Integer.toBinaryString(frameNum);
//get just the back - i.e. the offset
String offsetBinary = bitAddress.substring(Controller.PAGE_NUMBER_LENGTH);
String physicalAddressBinary = frameBinary + offsetBinary;
//parse that to a real integer and return it
return Integer.parseInt(physicalAddressBinary, 2);
}
/** helper utility to pad a string with zeroes up to the virtual address size length */
public static String padWithZeroes(String ba)
{
int howMany = Controller.VIRTUAL_ADDRESS_LENGTH - ba.length();
String pad = "";
for(int i = 0; i < howMany; i++)
{
pad += "0";
}
return pad.concat(ba);
}
/** accessors for the PID */
public int getPid(){return pid;}
public int getPID(){return pid;}
/** prints the message describing the result of the operation */
public void printLoadedMsg(int page, int pid, int frame)
{
String out = "";
out += "loaded page #";
out += page;
out += " of process #";
out+= pid;
out += " to frame #";
out += frame;
// out += " with ";
// out += (frame ? "" : " no ");
// out += "replacement.";
System.out.println(out);
}
public void printNoPageFaultMsg(int frame)
{
System.out.println("no page fault. accessed frame #" + frame);
}
}
| true
|
32c06ef2102526da665d88055b9e0733fb04da7f
|
Java
|
CleanstoneMC/Cleanstone
|
/src/main/java/rocks/cleanstone/endpoint/minecraft/vanilla/modern/v1_14/net/protocol/MinecraftProtocolLayer_v1_14_3.java
|
UTF-8
| 848
| 1.90625
| 2
|
[
"MIT",
"CC-BY-4.0"
] |
permissive
|
package rocks.cleanstone.endpoint.minecraft.vanilla.modern.v1_14.net.protocol;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import rocks.cleanstone.endpoint.minecraft.vanilla.net.protocol.MinecraftClientProtocolLayer;
import rocks.cleanstone.net.packet.Packet;
import rocks.cleanstone.net.protocol.PacketCodec;
import java.util.List;
@Component("minecraftProtocolLayer_v1_14_3")
public class MinecraftProtocolLayer_v1_14_3 extends MinecraftProtocolLayer_v1_14_2 {
@Autowired
public MinecraftProtocolLayer_v1_14_3(List<? extends PacketCodec<? extends Packet>> packetCodecs) {
super(packetCodecs);
}
@Override
public MinecraftClientProtocolLayer getCorrespondingClientLayer() {
return MinecraftClientProtocolLayer.MINECRAFT_V1_14_3;
}
}
| true
|