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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
2d0891bc4027bd691b13ec886de040d65668dec8 | Java | CallMeHeda/PDB-parking | /src/dao/IStationnementDAO.java | UTF-8 | 1,085 | 2.515625 | 3 | [] | no_license | package dao;
import java.sql.SQLException;
import model.SortieVoiture;
import model.Stationnement;
public interface IStationnementDAO extends IDAO<Stationnement, String>{
/**
* ARRIVEE_VOIT(String immatr)
* @param immatr de la voiture
* @return un objet de type Stationnement en faisant appel à la même méthode avec 2 param
* @throws ParkingException
* @throws SQLException
*/
public Stationnement arrivee_voit(String immatr) throws ParkingException, SQLException;
/**
* ARRIVEE_VOIT(IMMATR,PLACE)
* @param immatr de la voiture
* @param place de stationnement
* @return un Objet de type Stationnement
* @throws SQLException
* @throws ParkingException
*/
public Stationnement arrivee_voit(String immatr, String place) throws SQLException, ParkingException;
/**
* SORTIE_VOIT(String immatr)
* @param immatr de la voiture
* @return Objet de type sortieVoiture qui contient la place et la durée de stationnement
*/
public SortieVoiture sortie_voit(String immatr) throws SQLException, ParkingException;
}
| true |
64929f8dfafbe62ddbb22b9d333ffae2015ebe9e | Java | rortiz13/solicitudes-sdisc-responsable-portlet | /docroot/WEB-INF/src-liferay/la/netco/solicitudes_sdisc/model/model/impl/ParametrosCacheModel.java | UTF-8 | 2,968 | 1.945313 | 2 | [] | no_license | /**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package la.netco.solicitudes_sdisc.model.model.impl;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.model.CacheModel;
import la.netco.solicitudes_sdisc.model.model.Parametros;
import java.io.Serializable;
/**
* The cache model class for representing Parametros in entity cache.
*
* @author smontanez
* @see Parametros
* @generated
*/
public class ParametrosCacheModel implements CacheModel<Parametros>,
Serializable {
@Override
public String toString() {
StringBundler sb = new StringBundler(19);
sb.append("{tiempo_proximo_caducar=");
sb.append(tiempo_proximo_caducar);
sb.append(", tiempo_caducidad=");
sb.append(tiempo_caducidad);
sb.append(", email_resposable=");
sb.append(email_resposable);
sb.append(", mensaje_email=");
sb.append(mensaje_email);
sb.append(", asunto_email=");
sb.append(asunto_email);
sb.append(", id=");
sb.append(id);
sb.append(", repositoryId=");
sb.append(repositoryId);
sb.append(", folderId=");
sb.append(folderId);
sb.append(", userRepositoryId=");
sb.append(userRepositoryId);
sb.append("}");
return sb.toString();
}
public Parametros toEntityModel() {
ParametrosImpl parametrosImpl = new ParametrosImpl();
parametrosImpl.setTiempo_proximo_caducar(tiempo_proximo_caducar);
parametrosImpl.setTiempo_caducidad(tiempo_caducidad);
if (email_resposable == null) {
parametrosImpl.setEmail_resposable(StringPool.BLANK);
}
else {
parametrosImpl.setEmail_resposable(email_resposable);
}
if (mensaje_email == null) {
parametrosImpl.setMensaje_email(StringPool.BLANK);
}
else {
parametrosImpl.setMensaje_email(mensaje_email);
}
if (asunto_email == null) {
parametrosImpl.setAsunto_email(StringPool.BLANK);
}
else {
parametrosImpl.setAsunto_email(asunto_email);
}
parametrosImpl.setId(id);
parametrosImpl.setRepositoryId(repositoryId);
parametrosImpl.setFolderId(folderId);
parametrosImpl.setUserRepositoryId(userRepositoryId);
parametrosImpl.resetOriginalValues();
return parametrosImpl;
}
public int tiempo_proximo_caducar;
public int tiempo_caducidad;
public String email_resposable;
public String mensaje_email;
public String asunto_email;
public int id;
public long repositoryId;
public long folderId;
public long userRepositoryId;
} | true |
95d908034a00d689f4bab83a22f5641128332b57 | Java | averder/Obligatorio-Programacion2 | /UY.ORT.Ing.Sist.Obligatorio2/src/interfaz/VentanaLista.java | UTF-8 | 2,094 | 2.125 | 2 | [] | no_license | package interfaz;
import dominio.Sistema;
import java.util.Collections;
import javax.swing.JFrame;
public class VentanaLista extends javax.swing.JDialog {
private Sistema modelo;
public Sistema getModelo() {
return modelo;
}
public void setModelo(Sistema modelo) {
this.modelo = modelo;
}
public VentanaLista(Sistema sis, JFrame ventanaPadre) {
super(ventanaPadre, true);
initComponents();
modelo = sis;
jLstJugadores.setListData(modelo.getListaJugadores().toArray());
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPopupMenu1 = new javax.swing.JPopupMenu();
jScrollPane1 = new javax.swing.JScrollPane();
jLstJugadores = new javax.swing.JList();
jLblListaJugadores = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Perfección");
setMinimumSize(new java.awt.Dimension(450, 349));
setPreferredSize(new java.awt.Dimension(450, 349));
setResizable(false);
getContentPane().setLayout(null);
jLstJugadores.setBorder(new javax.swing.border.MatteBorder(null));
jScrollPane1.setViewportView(jLstJugadores);
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(30, 50, 350, 230);
jLblListaJugadores.setFont(new java.awt.Font("Traditional Arabic", 0, 18)); // NOI18N
jLblListaJugadores.setText("Lista Jugadores");
getContentPane().add(jLblListaJugadores);
jLblListaJugadores.setBounds(40, 20, 110, 20);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLblListaJugadores;
private javax.swing.JList jLstJugadores;
private javax.swing.JPopupMenu jPopupMenu1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
}
| true |
496047040e303e97384eaa814a2d0d0f3e12a010 | Java | LearninAndroid/Eat_Out_0.0.2 | /app/src/main/java/dev/brian/com/eatout/Cart.java | UTF-8 | 4,812 | 2.171875 | 2 | [] | no_license | package dev.brian.com.eatout;
import android.content.DialogInterface;
import android.icu.text.NumberFormat;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.annotation.RequiresApi;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SnapHelper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import dev.brian.com.eatout.Common.Common;
import dev.brian.com.eatout.Database.Database;
import dev.brian.com.eatout.Model.Order;
import dev.brian.com.eatout.Model.Request;
import dev.brian.com.eatout.ViewHolder.CartAdapter;
public class Cart extends AppCompatActivity {
CheckOutListener checkOutListener = new CheckOutListener();
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManage;
FirebaseDatabase firebaseDatabase;
DatabaseReference requests;
TextView txtTotalPrice;
Button placeOrder;
List<Order> cart = new ArrayList<>();
CartAdapter adapter;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
firebaseDatabase = FirebaseDatabase.getInstance();
requests = firebaseDatabase.getReference("Requests");
recyclerView = (RecyclerView)findViewById(R.id.listCart);
recyclerView.setHasFixedSize(true);
layoutManage = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManage);
txtTotalPrice = (TextView)findViewById(R.id.total);
placeOrder = (Button)findViewById(R.id.btnPlaceOrder);
// placeOrder.setOnClickListener(checkOutListener);
loadListFood();
placeOrder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showAlertDialog();
}
});
}
@RequiresApi(api = Build.VERSION_CODES.N)
private void loadListFood(){
cart = new Database(this).getCarts();
adapter = new CartAdapter(cart,this);
recyclerView.setAdapter(adapter);
int total = 0;
for(Order order:cart){
total+= (Integer.parseInt(order.getPrice())) * (Integer.parseInt(order.getQuantity()));
}
Locale locale = new Locale("en","US");
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(locale);
txtTotalPrice.setText(numberFormat.format(total));
}
class CheckOutListener implements View.OnClickListener{
@Override
public void onClick(View v) {
showAlertDialog();
}
}
public void showAlertDialog(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Cart.this);
alertDialog.setTitle("One More Step");
alertDialog.setMessage("Enter Your Address");
final EditText editAdress = new EditText(Cart.this);
LinearLayout.LayoutParams ip = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
editAdress.setLayoutParams(ip);
alertDialog.setView(editAdress);
alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Request request = new Request(Common.currentUser.getPhone(),
Common.currentUser.getName(),
editAdress.getText().toString(),
txtTotalPrice.getText().toString(),
cart);
requests.child(String.valueOf(System.currentTimeMillis())).setValue(request);
new Database(getBaseContext()).cleanCart();
Toast.makeText(Cart.this, "Thank You, Order Placed", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
| true |
47f67e24effdfbce25a25e1bcbeaed98c1274121 | Java | captainjspace/dmpro | /src/main/java/dmpro/attributes/Wisdom.java | UTF-8 | 3,438 | 2.84375 | 3 | [] | no_license | package dmpro.attributes;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import dmpro.spells.Spell;
public class Wisdom extends Attribute {
static final int fieldCount = 5;
// beguiling, charmming, fear, hypnosis, illusion,magic jar
// mass charm, phanstasmal force, possession, rulership, suggestion, telepathic attack, etc.
// general mental attack saving throw modifier
int magicalAttackAdjustment;
float percentSpellFailure;
List<Integer> bonusSpells = new ArrayList<Integer>(); //cumulative above 13
List<Spell> spellImmunity=new ArrayList<Spell>();
public Wisdom(){}
public Wisdom(String[] fields) {
attributeName = "Wisdom";
abilityScore=Integer.parseInt(fields[0].trim());
magicalAttackAdjustment = Integer.parseInt(fields[1]);
setBonusSpells(fields[2]);
setPercentSpellFailure(fields[3]);
setSpellImmunity(fields[4]);
}
/**
* @return the magicalAttackAdjustment
*/
public int getMagicalAttackAdjustment() {
return magicalAttackAdjustment;
}
/**
* @param magicalAttackAdjustment the magicalAttackAdjustment to set
*/
public void setMagicalAttackAdjustment(int magicalAttackAdjustment) {
this.magicalAttackAdjustment = magicalAttackAdjustment;
}
/**
* @return the percentSpellFailure
*/
public float getPercentSpellFailure() {
return percentSpellFailure;
}
/**
* @param percentSpellFailure the percentSpellFailure to set
*/
public void setPercentSpellFailure(float percentSpellFailure) {
this.percentSpellFailure = percentSpellFailure;
}
/**
* @return the bonusSpells
*/
public List<Integer> getBonusSpells() {
return bonusSpells;
}
/**
* @param bonusSpells the bonusSpells to set
*/
public void setBonusSpells(List<Integer> bonusSpells) {
this.bonusSpells = bonusSpells;
}
/**
* @return the spellImmunity
*/
public List<Spell> getSpellImmunity() {
return spellImmunity;
}
/**
* @param spellImmunity the spellImmunity to set
*/
public void setSpellImmunity(List<Spell> spellImmunity) {
this.spellImmunity = spellImmunity;
}
/**
* @return the fieldcount
*/
public static int getFieldcount() {
return fieldCount;
}
private void setPercentSpellFailure(String string) {
if (!string.matches(".*\\d+.*") )
return;
percentSpellFailure = Float.parseFloat(string);
}
private void setSpellImmunity(String spells) {
if (spells.matches(".*--.*") )
return;
for (String s : spells.split(",")) {
spellImmunity.add(new Spell(s.trim()));
}
}
private void setBonusSpells(String levels) {
// TODO Auto-generated method stub
if (!levels.matches(".*\\d+.*") )
return;
//System.out.println(levels);
//bonusSpells.add( Arrays.asList(levels.replaceAll("[","").replaceAll("]","").split(",")) );
List<String> l = Pattern.compile(",")
.splitAsStream(levels.replaceAll("\\[","").replace("]","").trim())
.collect(Collectors.toList() );
//System.out.println("done");
bonusSpells.addAll(l.stream().map(Integer::parseInt).collect(Collectors.toList()));
// bonusSpells.stream().forEach(a -> System.out.println(a));
}
@Override
public String toString() {
return "Wisdom [abilityScore=" + abilityScore + ", magicalAttackAdjustment=" + magicalAttackAdjustment
+ ", percentSpellFailure=" + percentSpellFailure + ", bonusSpells=" + bonusSpells + ", spellImmunity="
+ spellImmunity + "]";
}
}
| true |
cb4b031e20aa6ad4f7aae037211e511589a0c0b1 | Java | mageru/softwarereuse | /reuze/gb_IntersectionData.java | UTF-8 | 1,705 | 2.328125 | 2 | [] | no_license | package reuze;
/*
* Copyright (c) 2006-2011 Karsten Schmidt
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* http://creativecommons.org/licenses/LGPL/2.1/
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
public class gb_IntersectionData {
public boolean isIntersection;
public float dist;
public gb_Vector3 pos;
public gb_Vector3 dir;
public gb_Vector3 normal;
public gb_IntersectionData() {
}
public gb_IntersectionData(gb_IntersectionData isec) {
isIntersection = isec.isIntersection;
dist = isec.dist;
pos = isec.pos.cpy();
dir = isec.dir.cpy();
normal = isec.normal.cpy();
}
public void clear() {
isIntersection = false;
dist = 0;
pos = new gb_Vector3();
dir = new gb_Vector3();
normal = new gb_Vector3();
}
public String toString() {
String s = "isec: " + isIntersection;
if (isIntersection) {
s += " at:" + pos + " dist:" + dist + "normal:" + normal;
}
return s;
}
} | true |
8ab0d74e997621f46797161a14f5de0a098a4e13 | Java | ypsliu/serviceplatform | /serviceplatform/commons/validation/StringEnum.java | UTF-8 | 836 | 2 | 2 | [] | no_license | /**
*
*/
package com.ruixue.serviceplatform.commons.validation;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
/**
* the string enum validation constraint
*
* @author shangchunming@rkylin.com.cn
*
*/
@Documented
@Target({ FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = { StringEnumConstraintValidator.class, StringEnumsConstraintValidator.class })
public @interface StringEnum {
String message() default "{com.ruixue.serviceplatform.commons.validation.StringEnum.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String[] value();
}
| true |
3165033615a3ed19e74fe0054cc53310f8c90b0a | Java | cherkavi/java-web | /applet-javascript2/src/gui/EnterPoint/JInternalFrameMain.java | WINDOWS-1251 | 6,217 | 2.625 | 3 | [] | no_license | package gui.EnterPoint;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import BonCard.applet.JavaScriptExchange;
/**
* ,
* @author cherkashinv
*/
public class JInternalFrameMain extends JInternalFrame
implements InternalFrameListener,
JavaScriptExchange{
/** , */
private JDesktopPane field_desktop;
/** JavaScript*/
private JTextField field_textfield_text;
/** , , HTML(JavaScript) */
private JTextArea field_textarea_log;
/** */
private JApplet field_applet;
/**
*
* @param desktop -
* @param caption -
* @param width -
* @param height -
*/
public JInternalFrameMain(JApplet applet,
JDesktopPane desktop,
String caption,
int width,
int height){
super(caption,true,true,true,true);
this.field_applet=applet;
this.field_desktop=desktop;
this.addInternalFrameListener(this);
this.setSize(width,height);
initComponents();
this.setVisible(true);
this.field_desktop.add(this);
Position.set_frame_to_center(this, field_desktop, 20, 20);
}
/** */
private void initComponents(){
//
JButton field_button_go=new JButton(" ");
field_textfield_text=new JTextField();
JLabel field_label_text=new JLabel(" ");
//
field_button_go.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Click:");
onButtonGoClick();
}
});
//
JPanel panel_main=new JPanel(new BorderLayout());
/** JavaScript */
JPanel panel_send_data=new JPanel();
panel_send_data.setBorder(javax.swing.BorderFactory.createTitledBorder(" JavaScript"));
GroupLayout group_layout=new GroupLayout(panel_send_data);
panel_send_data.setLayout(group_layout);
GroupLayout.SequentialGroup group_layout_horizontal=group_layout.createSequentialGroup();
GroupLayout.SequentialGroup group_layout_veritcal=group_layout.createSequentialGroup();
group_layout_horizontal.addGroup(group_layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(field_label_text,GroupLayout.PREFERRED_SIZE,GroupLayout.PREFERRED_SIZE,GroupLayout.PREFERRED_SIZE)
.addComponent(field_textfield_text)
.addComponent(field_button_go,GroupLayout.PREFERRED_SIZE,GroupLayout.PREFERRED_SIZE,GroupLayout.PREFERRED_SIZE)
);
group_layout_veritcal.addComponent(field_label_text,GroupLayout.PREFERRED_SIZE,GroupLayout.PREFERRED_SIZE,GroupLayout.PREFERRED_SIZE);
group_layout_veritcal.addComponent(field_textfield_text,GroupLayout.PREFERRED_SIZE,GroupLayout.PREFERRED_SIZE,GroupLayout.PREFERRED_SIZE);
group_layout_veritcal.addComponent(field_button_go,GroupLayout.PREFERRED_SIZE,GroupLayout.PREFERRED_SIZE,GroupLayout.PREFERRED_SIZE);
group_layout.setHorizontalGroup(group_layout_horizontal);
group_layout.setVerticalGroup(group_layout_veritcal);
/** JavaScript */
JPanel panel_get_data=new JPanel();
panel_get_data.setBorder(javax.swing.BorderFactory.createTitledBorder(" HTML"));
panel_get_data.setLayout(new GridLayout(1,1));
field_textarea_log=new JTextArea();
panel_get_data.add(field_textarea_log);
//
panel_main.add(panel_send_data,BorderLayout.NORTH);
panel_main.add(panel_get_data,BorderLayout.CENTER);
this.getContentPane().add(panel_main);
}
/** reaction on striking button GO */
private void onButtonGoClick(){
try{
System.out.println("javascript:toConsole(\"" + this.field_textfield_text.getText() +"\")");
this.field_applet.getAppletContext().showDocument(new URL("javascript:toConsole(\"" + this.field_textfield_text.getText() +"\")"));
System.out.println("onButtonGoClick:end");
}catch (MalformedURLException me) {
System.out.println("Exception:"+me.getMessage());
}
}
@Override
public void internalFrameActivated(InternalFrameEvent e) {
}
@Override
public void internalFrameClosed(InternalFrameEvent e) {
System.exit(0);
}
@Override
public void internalFrameClosing(InternalFrameEvent e) {
}
@Override
public void internalFrameDeactivated(InternalFrameEvent e) {
}
@Override
public void internalFrameDeiconified(InternalFrameEvent e) {
}
@Override
public void internalFrameIconified(InternalFrameEvent e) {
}
@Override
public void internalFrameOpened(InternalFrameEvent e) {
}
@Override
public String echo(String value) {
this.field_textarea_log.append("echo:>>>"+value);
this.field_textarea_log.append("\n");
return value;
}
@Override
public void method_simple() {
this.field_textarea_log.append("method_simple:>>>");
this.field_textarea_log.append("\n");
}
@Override
public void method_string(String value) {
this.field_textarea_log.append("method_string:>>>"+value);
this.field_textarea_log.append("\n");
}
}
| true |
8be45767795b662a43c838c905b2a2b9f1309066 | Java | cooperay/cop-all | /cop-facade-admin/src/main/java/com/cooperay/facade/admin/service/GroupFacade.java | UTF-8 | 516 | 1.71875 | 2 | [] | no_license | package com.cooperay.facade.admin.service;
import java.util.List;
import com.cooperay.common.exceptions.BizException;
import com.cooperay.common.facade.BaseFacade;
import com.cooperay.facade.admin.entity.Group;
import com.cooperay.facade.admin.entity.GroupResource;
public interface GroupFacade extends BaseFacade<Group>{
public void setResource(GroupResource groupResource);
public void setResources(List<GroupResource> groupResource);
public List<GroupResource> getResourcesByGroupId(Long groupId);
}
| true |
1e2ea5afcf64a4d5259654257ecb33b42b92bb99 | Java | mazeRn/mazeNet | /mazenet-server-master-new/src/clientPackages/client/Player.java | UTF-8 | 676 | 2.109375 | 2 | [] | no_license | package clientPackages.client;
import generated.AwaitMoveMessageType;
import generated.MoveMessageType;
import generated.PositionType;
public class Player implements InterfaceKI {
@Override
public MoveMessageType getMove(AwaitMoveMessageType status) {
MoveMessageType message = new MoveMessageType();
PositionType shiftPosition = new PositionType();
shiftPosition.setCol(1);
shiftPosition.setRow(0);
message.setShiftPosition(shiftPosition);
PositionType pinPosition = new PositionType();
pinPosition.setCol(1);
shiftPosition.setRow(0);
message.setNewPinPos(pinPosition);
message.setShiftCard(status.getBoard().getShiftCard());
return message;
}
}
| true |
a2fc29c3bd73d323890a8bcbe6504bc92474d2a3 | Java | kotoroshinoto/HoNApp | /HoNApp/src/akirashino/honapp/DBAdapter.java | UTF-8 | 6,233 | 2.375 | 2 | [] | no_license | package akirashino.honapp;
import java.lang.reflect.Field;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class DBAdapter{
// ///////////////////////////////////////////////////////////////////
// Constants & Data
// ///////////////////////////////////////////////////////////////////
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_NAME = "name";
public static final String KEY_HERO = "hero";
public static final String KEY_RESID = "resid";
public static final String PRICE = "price";
public static final String IMAGE = "image";
public static final String DESC = "desc";
public static final String COST = "cost";
public static final String PLACE = "place";
public static final int COL_IMAGE = 1;
public static final int COL_NAME = 2;
public static final int COL_DESC = 3;
public static final int COL_PRICE = 4;
public static final int COL_HERO = 5;
public static final int COL_RESID = 6;
public static final int COL_COST = 7;
public static final int COL_PLACE = 9;
public static final String[] HERO_KEYS = new String[] { KEY_ROWID,
KEY_NAME, IMAGE, KEY_RESID};
public static final String[] IMAGE_KEYS = new String[] { KEY_ROWID, IMAGE};
public static final String[] ABILITY_KEYS = new String[] { KEY_ROWID,
KEY_NAME, KEY_HERO, DESC, IMAGE, KEY_RESID, COST, PLACE};
public static final String[] ITEM_KEYS = new String[] { KEY_ROWID, KEY_NAME, PRICE, DESC, IMAGE, KEY_RESID, };
public static final String DATABASE_NAME = "HonData";
public static final String DATABASE_TABLE_HERO = "hero";
public static final String DATABASE_TABLE_ITEM = "item";
public static final String DATABASE_TABLE_ABILITY = "ability";
public static final int DATABASE_VERSION = 2;
private final Context context;
private DataBaseHelper myDbHelper;
private SQLiteDatabase db;
// ///////////////////////////////////////////////////////////////////
// Public methods:
// ///////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDbHelper = new DataBaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDbHelper.getWritableDatabase();
//set hero images
this.setHeroImageIDs();
//set ability images
this.setAbilityImageIDs();
//set item images
this.setItemImageIDs();
return this;
}
// Close the database connection.
public void close() {
myDbHelper.close();
}
public Cursor getAllHero() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE_HERO, HERO_KEYS, where, null,
null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getAllHeroImage() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE_HERO, IMAGE_KEYS, where, null,
null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getAllAbility() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE_ABILITY, ABILITY_KEYS, where,
null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getAllItem() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE_ITEM, ITEM_KEYS, where, null,
null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRowHero(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE_HERO, HERO_KEYS, where, null,
null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getRowAbility(String hero) {
String where = KEY_HERO + "= \"" +hero+"\"";
Cursor c = db.query(true, DATABASE_TABLE_ABILITY, ABILITY_KEYS, where,
null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getRowItem(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE_ITEM, ITEM_KEYS, where, null,
null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public void setHeroImageIDs(){
Cursor c = this.getAllHero();
if (c != null){
while(!c.isAfterLast()){
try {
Class res = R.drawable.class;
String imgname=c.getString(c.getColumnIndex("image"));
Field field = res.getField(imgname);
int drawableId = field.getInt(null);
db.execSQL("update hero set " +
"resid=\""+drawableId+"\" where " +
"image= \""+imgname+"\"");
}
catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
}
c.moveToNext();
}
}
}
public void setAbilityImageIDs(){
Cursor c = this.getAllAbility();
if (c != null){
while(!c.isAfterLast()){
try {
Class res = R.drawable.class;
String imgname=c.getString(c.getColumnIndex("image"));
Field field = res.getField(imgname);
int drawableId = field.getInt(null);
db.execSQL("update ability" +
" set resid=\""+drawableId+"\" where " +
"image= \""+imgname+"\"");
}
catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
}
c.moveToNext();
}
}
}
public void setItemImageIDs(){
Cursor c = this.getAllItem();
if (c != null){
while(!c.isAfterLast()){
try {
Class res = R.drawable.class;
String imgname=c.getString(c.getColumnIndex("image"));
Field field = res.getField(imgname);
int drawableId = field.getInt(null);
db.execSQL("update item set " +
"resid=\""+drawableId+"\" where " +
"image= \""+imgname+"\"");
}
catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
}
c.moveToNext();
}
}
}
} | true |
b7bebf059facfdb951b29e4c3ce5741e143d8ae7 | Java | Witold101/comecofinale | /src/by/vistar/comeco/entity/autor/PackageSoft.java | UTF-8 | 665 | 2.25 | 2 | [] | no_license | package by.vistar.comeco.entity.autor;
public class PackageSoft {
private Long id;
private Integer key;
private String name;
private String info;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getKey() {
return key;
}
public void setKey(Integer key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
| true |
d716d61e1cca7fdeb0b2a667d6151dcc75ca0da1 | Java | xugeiyangguang/test2 | /src/ExperienceOfferTest/ConvertBinarySearchTree.java | UTF-8 | 3,028 | 3.625 | 4 | [] | no_license | package ExperienceOfferTest;
/*?????????????*/
public class ConvertBinarySearchTree {
static TreeNode head = null;
static TreeNode realHead = null;
public static TreeNode Convert(TreeNode pRootOfTree) {
ConvertSub(pRootOfTree);
return realHead;
}
private static void ConvertSub(TreeNode pRootOfTree) {
if(pRootOfTree==null) return;
ConvertSub(pRootOfTree.left);
if (head == null) {
head = pRootOfTree;
realHead = pRootOfTree;
} else {
head.right = pRootOfTree;
pRootOfTree.left = head;
head = pRootOfTree;
}
ConvertSub(pRootOfTree.right);
}
/*static TreeNode lastNodeList = null;*/
/*TreeNode lastNodeList = null;
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null){
return null;
}
*//*TreeNode lastNodeList = null;*//*
ConveretNode(pRootOfTree);
*//*将头结点先指向尾节点*//*
TreeNode headOfList = lastNodeList;
*//*将头节点从最后往前面移动*//*
while (headOfList!=null&&headOfList.left!=null){
headOfList = headOfList.left;
}
return headOfList;
}
*//*lastNodeList只能改变它指向的对象的值,不能改变他指向的对象*//*
public void ConveretNode(TreeNode pRootOfTree) {
TreeNode currentNode = pRootOfTree;
*//*一直找到最右节点*//*
if (currentNode.left != null) {
Convert(currentNode.left);
}
*//*将最右节点看成链表的尾节点*//*
currentNode.left = lastNodeList;
*//*将尾节点和当前中点节点链接*//*
if (lastNodeList != null) {
lastNodeList.right = currentNode;
}
*//*尾节点为当前节点*//*
lastNodeList = currentNode;
*//*对右子树进行同样的操作*//*
if (currentNode.right != null) {
Convert(currentNode.right);
}
}*/
public static void main(String[] args){
TreeNode a1 = new TreeNode(8);
TreeNode a2 = new TreeNode(8);
TreeNode a3 = new TreeNode(7);
TreeNode a4 = new TreeNode(9);
TreeNode a5 = new TreeNode(2);
TreeNode a6 = new TreeNode(4);
TreeNode a7 = new TreeNode(7);
a1.left = a2;
a1.right = a3;
a2.left = a4;
a2.right = a5;
a5.left = a6;
a5.right = a7;
a3.left = null;a3.right = null;
a4.left = null;a4.right = null;
a6.left = null;a6.right = null;
a7.left = null;a7.right = null;
ConvertBinarySearchTree test = new ConvertBinarySearchTree();
TreeNode r = test.Convert(a1);
while(r!=null){
System.out.print(r.val);
r = r.right;
}
/* TreeNode r1 = test.Convert(a2);
while(r1!=null){
System.out.print(" "+r1.val);
r1 = r1.right;
}*/
}
}
| true |
7410424a301d8be9bd8d0c8e38ab212746401465 | Java | yohanwahyudi/mdsreport | /GradleDyReports/src/main/java/com/vdi/batch/mds/repository/dao/impl/StagingAgentDAOImpl.java | UTF-8 | 1,874 | 2.28125 | 2 | [] | no_license | package com.vdi.batch.mds.repository.dao.impl;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaDelete;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.vdi.batch.mds.repository.StagingAgentRepository;
import com.vdi.batch.mds.repository.dao.StagingAgentDAOService;
import com.vdi.model.staging.StagingAgent;
@Transactional
@Repository("stagingAgentDAO")
public class StagingAgentDAOImpl implements StagingAgentDAOService{
@Autowired
private StagingAgentRepository repo;
@PersistenceContext
private EntityManager em;
@Override
public void add(Object obj) {
repo.save((StagingAgent)obj);
}
@Override
public <T> void addAll(Collection<T> col) {
Collection<StagingAgent> agentCol = (Collection<StagingAgent>) col;
for(StagingAgent stAgent : agentCol) {
repo.save(stAgent);
}
}
@Override
public void deleteEntity() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaDelete<StagingAgent> delete = (CriteriaDelete<StagingAgent>) cb.createCriteriaDelete(StagingAgent.class);
delete.from(StagingAgent.class);
em.createQuery(delete).executeUpdate();
}
@Override
public void merge(Object obj) {
}
@Override
public List<StagingAgent> getDataForInsert() {
return repo.getDataForInsert();
}
@Override
public void resetSequenceTo1() {
repo.resetSequenceTo1();
}
@Override
public void disableSafeUpdates() {
repo.disableSafeUpdates();
}
@Override
public void enableSafeUpdates() {
repo.enableSafeUpdates();
}
}
| true |
2baaaf65a89d6cde56c0005e81e09fb33b493723 | Java | boubah/demo | /src/main/java/com/sncf/fusion/demo/patternity/annotation/designpattern/Facade.java | UTF-8 | 544 | 2.328125 | 2 | [] | no_license | package com.sncf.fusion.demo.patternity.annotation.designpattern;
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.CLASS)
@Inherited
@Documented
public @interface Facade {
/**
* Each class this facades shields from
*/
Class<?>[] subFacades() default {};
/**
* The descriptions of each sub-system this facades shields from
*/
Class<?>[] subSystems() default {};
}
| true |
5df4647cbc52963dd38605f41ccbc80bc758687c | Java | mguetlein/TestAmbitSmarts | /src/test/java/org/kramerlab/test/TestAmbit.java | UTF-8 | 9,403 | 1.953125 | 2 | [] | no_license | package org.kramerlab.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.openscience.cdk.CDKConstants;
import org.openscience.cdk.aromaticity.Aromaticity;
import org.openscience.cdk.aromaticity.ElectronDonation;
import org.openscience.cdk.exception.CDKException;
import org.openscience.cdk.graph.Cycles;
import org.openscience.cdk.interfaces.IAtom;
import org.openscience.cdk.interfaces.IAtomContainer;
import org.openscience.cdk.interfaces.IAtomContainerSet;
import org.openscience.cdk.interfaces.IBond;
import org.openscience.cdk.silent.SilentChemObjectBuilder;
import org.openscience.cdk.smiles.SmilesGenerator;
import org.openscience.cdk.smiles.SmilesParser;
import org.openscience.cdk.tools.manipulator.AtomContainerManipulator;
import ambit2.core.data.MoleculeTools;
import ambit2.smarts.SMIRKSManager;
import ambit2.smarts.SMIRKSReaction;
import ambit2.smarts.SmartsConst;
@RunWith(JUnit4.class)
public class TestAmbit
{
public void ringSplit2_rule4287()
{
String smirks = "[#8-:10]-[#6:9](=[O:11])-[#6:1]-1=[CH1]-[#6;H1:5]=[#6;H1:4]-[#6;H1:3]=[#6;H1:2]-1>>O-[#6:5](=O)-[#6;H2:4]\\[#6;H1:3]=[#6;H1:2]/[#6;H2:1]-[#6:9](-[#8-:10])=[O:11]";
String smi = "O=C([O-])C1=CC=CC=C1";
List<String> products = applySmirks(smirks, smi);
Map<String, String> diff = diffProductToReference(products,
new String[] { "OC(=O)C\\C=C/CC([O-])=O" });
Assert.assertTrue("" + diff, null == diff);
}
@Test
public void ringSplit3_rule3743_u50144_u137948()
{
String smirks = "[#6:3]-[#8:15]-[c;R:11]1[c:12](-[#8:2]([H]))[c:7](-[#8:1]([H]))[c;R:8]([#1,#6,#9,#17,#35,#53;A:4])[c;R:9](-[!#16:6])[c;R:10]1-[!#8!#16:5]>>[!#16:6]\\[#6:9](=[#6:10](/[!#8!#16:5])-[#6:11](-[#8:15])=O)-[#6:8]([#1,#6,#9,#17,#35,#53;A:4])-[#6:7](=[O:1])-[#6:12](-[#8-:2])=O.[#6:3]-[#8]";
String smi1 = "COC1=C2C=CC=CC2=CC(=C1O)O";
String smi2 = "C1=CC2=CC(=C(C3=C2C(=C1)CC(=O)O3)O)O";
Assert.assertFalse("Results should not be empty",
applySmirks(smirks, smi1).isEmpty() || applySmirks(smirks, smi2).isEmpty());
}
@Test
public void ringSplit4_rule4298_u140722()
{
String smirks = "[#6:11]@-[c:2]1[c;R1:4][c;R1:5][c:6](-[#8:8]([H]))[c:7](-[#8:1]([H]))[c:3]1@-[#6:12]>>[#6:12]-[#6:3](=O)-[#6:2](\\[#6:11])=[#6:4]/[#6:5]=[#6:6](/[#8:8]([H]))-[#6:7](-[O-])=[O:1]";
String onceAromatic = "Oc1ccc2CCCCc2c1O";
List<String> products = applySmirks(smirks, onceAromatic);
Map<String, String> diff = diffProductToReference(products,
new String[] { "O\\C(=C\\C=C1\\CCCCC1=O)C([O-])=O" });
Assert.assertTrue("" + diff, null == diff);
String twiceAromatic = "Oc1ccc2ccccc2c1O";
products = applySmirks(smirks, twiceAromatic);
diff = diffProductToReference(products,
new String[] { "O\\C(=C\\C=C1\\C=CC=CC1=O)C([O-])=O" });
Assert.assertTrue("" + diff, null == diff);
String smiles_u140722 = "OCc1cc(O)c(O)c2cccc(C([O-])=O)c12";
products = applySmirks(smirks, smiles_u140722);
diff = diffProductToReference(products,
new String[] { "C1=CC(=O)\\C(=C(/C=C(\\C(=O)[O-])/O)\\CO)\\C(=C1)C(=O)[O-]" });
Assert.assertTrue("" + diff, null == diff);
}
@Test
public void ringSplit5_rule4224_missing()
{
String smirks = "[#8:2]([H])-[c:10]1[#6,#7;a:9][c:8][c:7][c:6](-[*,#1:11])[c:5]1-[#8:1]([H])>>[#8-:2]-[#6:10](=O)\\[#6,#7:9]=[#6:8]/[#6:7]=[#6:6](/[*,#1:11])-[#6:5](-[#8-:1])=O";
String u97336 = "Oc1ncc2ccccc2c1O";
List<String> products = applySmirks(smirks, u97336);
Map<String, String> diff = diffProductToReference(products,
new String[] { "C1=CC(=C(C=C1)C(=O)[O-])/C=N\\C(=O)[O-]" });
Assert.assertTrue("" + diff, null == diff);
String u8723 = "CC(C(C)=O)c1cc2c(Cl)nc(O)c(O)c2[nH]1";
products = applySmirks(smirks, u8723);
diff = diffProductToReference(products,
new String[] { "CC(C(C)=O)c1cc(\\C(Cl)=N/C([O-])=O)c([nH]1)C([O-])=O" });
Assert.assertTrue("" + diff, null == diff);
}
@Test
public void ringSplit5_rule4224_toomany()
{
String smirks = "[#8:2]([H])-[c:10]1[#6,#7;a:9][c:8][c:7][c:6](-[*,#1:11])[c:5]1-[#8:1]([H])>>[#8-:2]-[#6:10](=O)\\[#6,#7:9]=[#6:8]/[#6:7]=[#6:6](/[*,#1:11])-[#6:5](-[#8-:1])=O";
String smiles = "Nc1ccc(O)c(O)c1";
List<String> products = applySmirks(smirks, smiles);
Map<String, String> diff = diffProductToReference(products,
new String[] { "N\\C(\\C=C/C([O-])=O)=C\\C([O-])=O" });
Assert.assertTrue("" + diff, null == diff);
}
@Test
// https://sourceforge.net/p/ambit/bugs/104/
public void ringSplit5_rule4224_valenceError()
{
String smirks = "[#8:2]([H])-[c:10]1[#6,#7;a:9][c:8][c:7][c:6](-[*,#1:11])[c:5]1-[#8:1]([H])>>[#8-:2]-[#6:10](=O)\\[#6,#7:9]=[#6:8]/[#6:7]=[#6:6](/[*,#1:11])-[#6:5](-[#8-:1])=O";
String c0707 = "OCc1ccc2ccc(O)c(O)c2c1";
List<String> products = applySmirks(smirks, c0707);
Map<String, String> diff = diffProductToReference(products,
new String[] { "C1=C(C=C(C(=C1)/C=C\\C(=O)[O-])C(=O)[O-])CO" });
Assert.assertTrue("" + diff, null == diff);
}
public static Map<String, String> diffProductToReference(List<String> products,
String[] reference)
{
Set<String> p = new HashSet<String>();
p.addAll(products);
Set<String> r = new HashSet<String>();
r.addAll(Arrays.asList(reference));
diffSmiles(p, r);
if (p.isEmpty() && r.isEmpty())
return null;
Map<String, String> diff = new HashMap<String, String>();
for (String notInReference : p)
{
diff.put(notInReference, "notInReference");
}
for (String notInProducts : r)
{
diff.put(notInProducts, "notInProducts");
}
return diff;
}
public static List<String> applySmirks(String smrk, String smi)
{
try
{
SMIRKSManager smrkMan = new SMIRKSManager(SilentChemObjectBuilder.getInstance());
smrkMan.setFlagSSMode(SmartsConst.SSM_MODE.SSM_NON_IDENTICAL_FIRST);
smrkMan.setFlagProcessResultStructures(true);
smrkMan.setFlagClearHybridizationBeforeResultProcess(true);
smrkMan.setFlagClearImplicitHAtomsBeforeResultProcess(true);
smrkMan.setFlagClearAromaticityBeforeResultProcess(true);
smrkMan.setFlagAddImplicitHAtomsOnResultProcess(true);
smrkMan.setFlagConvertAddedImplicitHToExplicitOnResultProcess(false);
smrkMan.setFlagConvertExplicitHToImplicitOnResultProcess(true);
smrkMan.getSmartsParser().mSupportDoubleBondAromaticityNotSpecified = false;
smrkMan.setFlagApplyStereoTransformation(true);
SMIRKSReaction reaction = smrkMan.parse(smrk);
if (!smrkMan.getErrors().equals(""))
throw new RuntimeException("Invalid SMIRKS: " + smrkMan.getErrors());
IAtomContainer target = new SmilesParser(SilentChemObjectBuilder.getInstance())
.parseSmiles(smi);
for (IAtom atom : target.atoms())
if (atom.getFlag(CDKConstants.ISAROMATIC))
atom.setFlag(CDKConstants.ISAROMATIC, false);
for (IBond bond : target.bonds())
if (bond.getFlag(CDKConstants.ISAROMATIC))
bond.setFlag(CDKConstants.ISAROMATIC, false);
// do not add Hs: https://sourceforge.net/p/cdk/mailman/message/34608714/
// AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(target);
// CDKHydrogenAdder adder = CDKHydrogenAdder.getInstance(SilentChemObjectBuilder.getInstance());
// adder.addImplicitHydrogens(target);
//CDK bug regarding stereo in 1.5.13
//AtomContainerManipulator.convertImplicitToExplicitHydrogens(target);
MoleculeTools.convertImplicitToExplicitHydrogens(target);
// for our project, we want to use daylight aromaticity
// CDKHueckelAromaticityDetector.detectAromaticity(target);
Aromaticity aromaticity = new Aromaticity(ElectronDonation.daylight(),
Cycles.or(Cycles.all(), Cycles.edgeShort()));
aromaticity.apply(target);
IAtomContainerSet resSet2 = smrkMan.applyTransformationWithSingleCopyForEachPos(target,
null, reaction, SmartsConst.SSM_MODE.SSM_ALL);
List<String> result = new ArrayList<String>();
if (resSet2 != null)
for (int i = 0; i < resSet2.getAtomContainerCount(); i++)
{
IAtomContainer mol = resSet2.getAtomContainer(i);
AtomContainerManipulator.suppressHydrogens(mol);
String smiles = SmilesGenerator.absolute().create(mol);
result.add(smiles);
}
return result;
}
catch (Exception e)
{
System.err.println("SMIRKS " + smrk);
System.err.println("SMILES " + smi);
e.printStackTrace();
return null;
}
}
/**
* compares smiles string
* @param smiA
* @param smiB
* @return true if smiA and smiB are equal
*/
public static boolean sameSame(String smiA, String smiB)
{
/*
* TODO: compare standardized smiles
*/
return smiA.equals(smiB);
}
/**
* removes intersection from both sets, based on the {@link #sameSame(String, String)} comparing method
* @param smilesA
* @param smilesB
*/
public static void diffSmiles(Set<String> smilesA, Set<String> smilesB)
{
for (String smiA : smilesA)
{
for (String smiB : smilesB)
{
if (sameSame(smiA, smiB))
{
smilesA.remove(smiA);
smilesB.remove(smiB);
diffSmiles(smilesA, smilesB);
return;
}
}
}
}
public static void main(String[] args) throws CDKException
{
TestAmbit t = new TestAmbit();
// t.chiralityInformationNotAdded_rule2978_c0105();
// t.productToSmilesError_rule3707_u143203();
}
}
| true |
ff2d397df0d0aaf1c9289447715c06f94615a19f | Java | veione/WebFrameByNetty | /src/main/java/com/lianxi/server/StaticRequestHandler.java | UTF-8 | 5,591 | 2.265625 | 2 | [] | no_license | package com.lianxi.server;
import com.lianxi.server.interfs.WebRequestHandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.DefaultFileRegion;
import io.netty.handler.codec.DateFormatter;
import io.netty.handler.codec.http.*;
import org.apache.tika.Tika;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Calendar;
import java.util.Date;
/**
* @Author: developerfengrui
* @Description:
* @Date: Created in 17:41 2018/6/11
*/
public class StaticRequestHandler implements WebRequestHandler{
private String staticRoot;
private boolean classpath;
private final static int DEFAULT_CACHE_EXPIRE = 3600;
private Tika tika = new Tika();
private int cacheDuration = DEFAULT_CACHE_EXPIRE;
public StaticRequestHandler() {
this("/");
}
public StaticRequestHandler(String staticRoot) {
this(staticRoot, true, DEFAULT_CACHE_EXPIRE);
}
public StaticRequestHandler(String staticRoot, boolean classpath) {
this(staticRoot, classpath, DEFAULT_CACHE_EXPIRE);
}
public StaticRequestHandler(String staticRoot, boolean classpath, int cacheDuration) {
this.classpath = classpath;
if (classpath) {
// 使用classpath里面的资源
this.staticRoot = CurrentUtil.normalize(staticRoot);
} else {
// 使用文件系统的资源
this.staticRoot = staticRoot;
if (!Files.isDirectory(Paths.get(staticRoot))) {
throw new IllegalArgumentException("static root must be valid directory");
}
}
this.cacheDuration = cacheDuration;
}
@Override
public void handle(ApplicationContext ctx, Request req) {
String path = req.relativeUri();
path = Paths.get(this.staticRoot, path).toString();
if (classpath) {
sendResource(ctx, path);
} else {
sendFile(ctx, path, req.header(HttpHeaderNames.IF_MODIFIED_SINCE));
}
}
public void sendResource(ApplicationContext ctx, String path) {
InputStream is = null;
byte[] bytes = null;
try {
is = this.getClass().getResourceAsStream(path);
if (is == null) {
throw new AbortException(HttpResponseStatus.NOT_FOUND);
}
//readAllBytes()
is.read(bytes);
} catch (IOException e) {
throw new AbortException(HttpResponseStatus.INTERNAL_SERVER_ERROR, "read file error");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.headers().add(HttpHeaderNames.CONTENT_LENGTH, bytes.length);
String contentType = tika.detect(bytes);
if (contentType.equals("text/plain")) {
contentType = tika.detect(path);
}
response.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType);
ByteBuf buf = ctx.alloc().buffer();
buf.writeBytes(bytes);
ctx.send(response, new DefaultHttpContent(buf), LastHttpContent.EMPTY_LAST_CONTENT);
}
public void sendFile(ApplicationContext ctx, String path, String ifModifiedSince) {
File file = new File(path);
if (!file.exists()) {
throw new AbortException(HttpResponseStatus.NOT_FOUND);
}
if (!file.isFile()) {
throw new AbortException(HttpResponseStatus.FORBIDDEN, "not a valid file");
}
if (!file.canRead()) {
throw new AbortException(HttpResponseStatus.FORBIDDEN, "file not allowed to read");
}
long lastModified = file.lastModified() / 1000;
long ifModifiedSinceTs = 0;
if (ifModifiedSince != null) {
ifModifiedSinceTs = DateFormatter.parseHttpDate(ifModifiedSince).getTime() / 1000;
}
if (ifModifiedSinceTs >= lastModified) {
DefaultFullHttpResponse notModified = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.NOT_MODIFIED);
notModified.headers().add(HttpHeaderNames.DATE, DateFormatter.format(new Date()));
ctx.send(notModified);
return;
}
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.headers().add(HttpHeaderNames.CONTENT_LENGTH, file.length());
try {
String contentType = tika.detect(file);
if (contentType.equals("text/plain")) {
contentType = tika.detect(file.getName());
}
response.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType);
} catch (IOException e) {
throw new AbortException(HttpResponseStatus.INTERNAL_SERVER_ERROR, "detect file type error");
}
Calendar cald = Calendar.getInstance();
cald.add(Calendar.SECOND, cacheDuration);
response.headers().add(HttpHeaderNames.EXPIRES, DateFormatter.format(cald.getTime()));
response.headers().add(HttpHeaderNames.CACHE_CONTROL, "private, max-age=" + cacheDuration);
response.headers().add(HttpHeaderNames.LAST_MODIFIED, DateFormatter.format(new Date(file.lastModified())));
ctx.send(response, new DefaultFileRegion(file, 0, file.length()), LastHttpContent.EMPTY_LAST_CONTENT);
}
}
| true |
67b9f68e47a63a5210a72f661a442f4d17f0f439 | Java | djdwosk97/UIUC | /CS242 - FA16/Poker/src/drawPoker/Deck.java | UTF-8 | 1,081 | 3.4375 | 3 | [] | no_license | package drawPoker;
//SUITS: HEARTS = 0, SPADES = 1, DIAMONDS = 2, CLUBS = 3, joker = 4
//COLORS: RED = 0, BLACK = 1, joker = 2
//Card: Ace (1), 2, 3, 4, 5, 6, 7, 8, 9, 10, jack (11), queen (12), king (13)
//Players: deck = 0, board = 1, players >= 2
public class Deck {
private static Card[] deck;
public static Card[] initializeDeck(boolean jokers, int numSuits){
int numCards = 0;
if(!jokers){
deck = new Card[52];
} else {
deck = new Card[54];
deck[52] = new Card(0, 2, 4, 14);
deck[53] = new Card(0, 2, 4, 14);
}
for(int suit = 0; suit < numSuits; suit++){
for(int card = 0; card < 13; card++){
deck[numCards] = new Card(0, suit%2, suit, card);
numCards++;
}
}
return deck;
}
/**
* Shuffles a deck of cards
* @param deck
* @return
*/
public static Card[] shuffleDeck(Card[] deck){
for(int i=0; i<100000; i++){
for(int j=0; j<deck.length; j++){
int rand = (int)(deck.length *Math.random());
Card tempCard = deck[j];
deck[j] = deck[rand];
deck[rand] = tempCard;
}
}
return deck;
}
}
| true |
bf7b55d1d8f434df9404dde520da2b3a68457a01 | Java | cracken47/ShaktimanApp | /app/src/main/java/com/alabhya/Shaktiman/utils/AgeCalculator.java | UTF-8 | 796 | 3.28125 | 3 | [] | no_license | package com.alabhya.Shaktiman.utils;
import java.util.Calendar;
public class AgeCalculator {
public AgeCalculator() {
}
public String getAge(String DateOfBirth){
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
int year = Integer.parseInt(DateOfBirth.substring(0,4));
int month = Integer.parseInt(DateOfBirth.substring(5,7));
int day = Integer.parseInt(DateOfBirth.substring(8));
dob.set(year, month, day);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)){
age--;
}
Integer ageInt = new Integer(age);
String ageS = ageInt.toString();
return ageS;
}
}
| true |
6c56eb16e23b0102a6ca0fec74df9a307b9aee16 | Java | JenyaKnyazev/coupon-system-part2 | /src/main/java/com/spring/CouponSystempart3/controller/AdminController.java | UTF-8 | 8,985 | 2.28125 | 2 | [] | no_license | package com.spring.CouponSystempart3.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import com.spring.CouponSystempart3.LoginManager;
import com.spring.CouponSystempart3.TokensManager;
import com.spring.CouponSystempart3.beans.ClientType;
import com.spring.CouponSystempart3.beans.Company;
import com.spring.CouponSystempart3.beans.Customer;
import com.spring.CouponSystempart3.beans.LoginResult;
import com.spring.CouponSystempart3.exceptions.ValidationException;
import com.spring.CouponSystempart3.facade.AdminFacade;
import com.spring.CouponSystempart3.facade.ClientFacade;
@RestController
public class AdminController extends ClientController {
@Autowired
private LoginManager loginManager;
@Autowired
private TokensManager tokensManager;
@Override
@GetMapping("api/admin/login/{email}/{password}")
public ResponseEntity<LoginResult> login(@PathVariable("email") String email,
@PathVariable("password") String password) {
ClientFacade facade = loginManager.login(email, password, ClientType.Adminstrator);
boolean isLogged = facade != null;
LoginResult result = new LoginResult();
result.setLogged(isLogged);
if (isLogged) {
result.setToken(tokensManager.generateToken(facade, ClientType.Adminstrator));
}
return ResponseEntity.ok().body(result);
}
@PostMapping("api/admin/company")
public ResponseEntity<Void> addCompany(@RequestBody Company company, @RequestHeader("token") String token)
throws ValidationException {
try {
ClientFacade facade = tokensManager.getFacadeByToken(token);
if (facade == null || !(facade instanceof AdminFacade)) {
return new ResponseEntity<Void>(HttpStatus.UNAUTHORIZED);
}
AdminFacade adminFacade = (AdminFacade) facade;
adminFacade.addCompany(company);
} catch (ValidationException ex) {
throw ex;
} catch (Exception ex) {
System.out.println("Failed to add company " + ex.getMessage());
return new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<Void>(HttpStatus.OK);
}
@PutMapping("api/admin/company")
public ResponseEntity<Void> updateCompany(@RequestBody Company company, @RequestHeader("token") String token) {
try {
ClientFacade facade = tokensManager.getFacadeByToken(token);
if (facade == null || !(facade instanceof AdminFacade)) {
return new ResponseEntity<Void>(HttpStatus.UNAUTHORIZED);
}
AdminFacade adminFacade = (AdminFacade) facade;
adminFacade.updateCompany(company);
} catch (Exception ex) {
return new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<Void>(HttpStatus.OK);
}
@DeleteMapping("api/admin/company/{companyId}")
public ResponseEntity<Void> deleteCompany(@PathVariable("companyId") Integer companyId,
@RequestHeader("token") String token) {
try {
ClientFacade facade = tokensManager.getFacadeByToken(token);
if (facade == null || !(facade instanceof AdminFacade)) {
return new ResponseEntity<Void>(HttpStatus.UNAUTHORIZED);
}
AdminFacade adminFacade = (AdminFacade) facade;
adminFacade.deleteCompany(companyId);
} catch (ValidationException ex) {
return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
} catch (Exception ex) {
return new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<Void>(HttpStatus.OK);
}
@GetMapping("api/admin/company")
public ResponseEntity<List<Company>> getAllCompanies(@RequestHeader("token") String token) {
List<Company> compancies = null;
try {
ClientFacade facade = tokensManager.getFacadeByToken(token);
if (facade == null || !(facade instanceof AdminFacade)) {
return new ResponseEntity<List<Company>>(HttpStatus.UNAUTHORIZED);
}
AdminFacade adminFacade = (AdminFacade) facade;
compancies = adminFacade.getAllCompanies();
} catch (Exception ex) {
return new ResponseEntity<List<Company>>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<List<Company>>(compancies, HttpStatus.OK);
}
@GetMapping("api/admin/company/{companyId}")
public ResponseEntity<Company> getOneCompany(@PathVariable("companyId") int companyId,
@RequestHeader("token") String token) {
Company company = null;
try {
ClientFacade facade = tokensManager.getFacadeByToken(token);
if (facade == null || !(facade instanceof AdminFacade)) {
return new ResponseEntity<Company>(HttpStatus.UNAUTHORIZED);
}
AdminFacade adminFacade = (AdminFacade) facade;
company = adminFacade.getOneCompany(companyId);
} catch (Exception ex) {
return new ResponseEntity<Company>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<Company>(company, HttpStatus.OK);
}
@PostMapping("api/admin/customer")
public ResponseEntity<Void> addCustomer(@RequestBody Customer customer, @RequestHeader("token") String token) {
try {
ClientFacade facade = tokensManager.getFacadeByToken(token);
if (facade == null || !(facade instanceof AdminFacade)) {
return new ResponseEntity<Void>(HttpStatus.UNAUTHORIZED);
}
AdminFacade adminFacade = (AdminFacade) facade;
adminFacade.addCustomer(customer);
} catch (ValidationException ex) {
return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
} catch (Exception ex) {
return new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<Void>(HttpStatus.OK);
}
@PutMapping("api/admin/customer")
public ResponseEntity<Void> updateCustomer(@RequestBody Customer customer, @RequestHeader("token") String token) {
try {
ClientFacade facade = tokensManager.getFacadeByToken(token);
if (facade == null || !(facade instanceof AdminFacade)) {
return new ResponseEntity<Void>(HttpStatus.UNAUTHORIZED);
}
AdminFacade adminFacade = (AdminFacade) facade;
adminFacade.updateCustomer(customer);
} catch (Exception ex) {
return new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<Void>(HttpStatus.OK);
}
@DeleteMapping("api/admin/customer/{customerId}")
public ResponseEntity<Void> deleteCustomer(@PathVariable("customerId") int customerId,
@RequestHeader("token") String token) {
try {
ClientFacade facade = tokensManager.getFacadeByToken(token);
if (facade == null || !(facade instanceof AdminFacade)) {
return new ResponseEntity<Void>(HttpStatus.UNAUTHORIZED);
}
AdminFacade adminFacade = (AdminFacade) facade;
adminFacade.deleteCustomer(customerId);
} catch (Exception ex) {
return new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<Void>(HttpStatus.OK);
}
@GetMapping("api/admin/customer")
public ResponseEntity<List<Customer>> getAllCustomers(@RequestHeader("token") String token) {
List<Customer> customers = null;
try {
ClientFacade facade = tokensManager.getFacadeByToken(token);
if (facade == null || !(facade instanceof AdminFacade)) {
return new ResponseEntity<List<Customer>>(HttpStatus.UNAUTHORIZED);
}
AdminFacade adminFacade = (AdminFacade) facade;
customers = adminFacade.getAllCustomers();
} catch (Exception ex) {
return new ResponseEntity<List<Customer>>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<List<Customer>>(customers, HttpStatus.OK);
}
@GetMapping("api/admin/customer/{customerId}")
public ResponseEntity<Customer> getOneCustomer(@PathVariable("customerId") Integer customerId,
@RequestHeader("token") String token) {
Customer customer = null;
try {
ClientFacade facade = tokensManager.getFacadeByToken(token);
if (facade == null || !(facade instanceof AdminFacade)) {
return new ResponseEntity<Customer>(HttpStatus.UNAUTHORIZED);
}
AdminFacade adminFacade = (AdminFacade) facade;
customer = adminFacade.getOneCustomer(customerId);
} catch (Exception ex) {
return new ResponseEntity<Customer>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<Customer>(customer, HttpStatus.OK);
}
@Override
@GetMapping("api/admin/logout")
public ResponseEntity<Void> logout(@RequestHeader("token") String token) {
boolean isDeleted = tokensManager.deleteToken(token, ClientType.Adminstrator);
if (isDeleted) {
return new ResponseEntity<Void>(HttpStatus.OK);
} else {
return new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
| true |
b14e9e8b03da59d1f2ce0eec692b64561e14ba3a | Java | 2chfl/GeoIP | /src/main/java/com/alexander/geoip/Start.java | UTF-8 | 378 | 1.929688 | 2 | [] | no_license | package com.alexander.geoip;
import com.alexander.geoip.view.MainView;
import javafx.application.Application;
import javafx.stage.Stage;
public class Start extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
new MainView(primaryStage, "GeoIP", 750, 450);
}
} | true |
f2ec730ee3a24be7c462cfbfc1e17b529f3dcbd0 | Java | sriragcs/Misc-1 | /problem2/StreamChecker.java | UTF-8 | 1,910 | 3.59375 | 4 | [] | no_license | // Time Complexity : Query -> O(q), q -> Length of query, O(m*n), m -> Number of words, n -> Average length of word
// Space Complexity : Query -> O(q), q -> Length of query, O(m*n), m -> Number of words, n -> Average length of word
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
package problem2;
public class StreamChecker {
TrieNode root;
StringBuilder sb;
int wordLen;
public StreamChecker(String[] words) {
root = new TrieNode();
sb = new StringBuilder();
for (String word : words) {
insert(word);
wordLen = Math.max(wordLen, word.length());
}
}
public boolean query(char letter) {
sb.append(letter);
if (sb.length() > wordLen) {
sb.delete(0, sb.length() - wordLen);
}
TrieNode curr = root;
for (int i = sb.length() - 1; i >= 0; i--) {
char ch = sb.charAt(i);
if (curr.children[ch - 'a'] == null) {
return false;
}
curr = curr.children[ch - 'a'];
if (curr.isStart) {
return true;
}
}
return false;
}
private void insert(String word) {
TrieNode curr = root;
for (int i = word.length() - 1; i >= 0; i--) {
char ch = word.charAt(i);
if (curr.children[ch - 'a'] == null) {
curr.children[ch - 'a'] = new TrieNode();
}
curr = curr.children[ch - 'a'];
}
curr.isStart = true;
}
public static void main(String[] args) {
StreamChecker obj = new StreamChecker(new String[] { "cd", "f", "kl" });
System.out.println(obj.query('a'));
System.out.println(obj.query('b'));
System.out.println(obj.query('c'));
System.out.println(obj.query('d'));
System.out.println(obj.query('e'));
System.out.println(obj.query('f'));
System.out.println(obj.query('g'));
System.out.println(obj.query('h'));
System.out.println(obj.query('i'));
System.out.println(obj.query('j'));
System.out.println(obj.query('k'));
System.out.println(obj.query('l'));
}
}
| true |
b8eb5182bfbb2bacc41e7466465eab8c90e84aa9 | Java | ahsxsk/tsharding | /tsharding-client/src/test/java/com/mogujie/service/tsharding/annotation/SimpleDaoWithAnotationTest.java | UTF-8 | 2,532 | 2.28125 | 2 | [
"MIT"
] | permissive | package com.mogujie.service.tsharding.annotation;
import com.alibaba.fastjson.JSON;
import com.mogujie.trade.tsharding.annotation.parameter.ShardingBuyerPara;
import org.apache.ibatis.annotations.Param;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @auther qigong on 5/29/15 12:46 PM.
*/
public class SimpleDaoWithAnotationTest {
private static ShardingBuyerPara a;
public static void main(String[] args) {
Class z = SimpleDao.class;
try {
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("proxy method");
System.out.println(JSON.toJSONString(method.getParameterTypes()));
Annotation[][] an = method.getParameterAnnotations();
if (an.length > 0) {
for (int i = 0; i < an.length; i++) {
System.out.print("i::" + i + ";");
System.out.println(JSON.toJSONString(an[i].length));
for (int j = 0; j < an[i].length; j++) {
System.out.println("j::" + j);
if(j==0) {
a = (ShardingBuyerPara) an[i][j];
System.out.println("sharding参数"+args[i]);
}else {
Param b = (Param) an[i][j];
System.out.println(b.value());
}
}
}
}
return method.invoke(SimpleDaoImpl.class.newInstance(), new Object[]{"abc", "cde", 4191574207234L});
}
};
Proxy proxy = (Proxy) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{SimpleDao.class}, handler);
Method m = z.getMethod("abc", new Class[]{String.class, String.class, Long.class});
try {
handler.invoke(proxy, m, new Object[]{"abc", "cde", 4191574207234L});
} catch (Throwable throwable) {
throwable.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
3321f300b266b265a4e07ea3e3289b76595be02e | Java | jessicaplm/projetoFinalVS | /ProjetoAlimentosSuadaveis/src/com/vidasaudavel/service/SugestaoServiceImpl.java | UTF-8 | 1,151 | 1.9375 | 2 | [] | no_license | package com.vidasaudavel.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.vidasaudavel.dao.SugestaoDAO;
import com.vidasaudavel.model.Sugestao;
@Service
@Transactional(readOnly = true)
public class SugestaoServiceImpl implements SugestaoService {
private SugestaoDAO sugestaoDAO;
public void setSugestaoDAO(SugestaoDAO sugestaoDAO) {
this.sugestaoDAO = sugestaoDAO;
}
@Override
@Transactional(readOnly = false)
public void addSugestao(Sugestao c) {
// TODO Auto-generated method stub
this.sugestaoDAO.addSugestao(c);
}
@Override
public List<Sugestao> listSugestao() {
// TODO Auto-generated method stub
return sugestaoDAO.listSugestao();
}
@Override
@Transactional(readOnly = false)
public void updateSugestao(Sugestao c) {
// TODO Auto-generated method stub
sugestaoDAO.updateSugestao(c);
}
@Override
@Transactional(readOnly = false)
public void removeSugestaoById(int id) {
// TODO Auto-generated method stub
sugestaoDAO.removeSugestaoById(id);
}
}
| true |
90c554807f790ba59d5ace7408cb4cce56abaa8b | Java | sanjeevan7/Ass2-RecyclingMachine | /44/Week4/src/com/perisic/beds/ReceiptBasis.java | UTF-8 | 1,076 | 3.34375 | 3 | [] | no_license | package com.perisic.beds;
import java.util.Vector;
/**
* The database of the system.
* @author Jake Scott
*
*/
public class ReceiptBasis {
private Vector<DepositItem> myItems = new Vector<DepositItem>();
/**
* adds the item being added to a list of all items in machine
* @param item
*/
public void addItem(DepositItem item) {
myItems.add(item);
item.number = myItems.indexOf(item); //number is position in list
}
/**
* Calculate the total amount of all items inserted.
* @return The sum total of the items.
*/
public String computeSum() {
String receipt = "";
int sum = 0;
for(int i=0; i < myItems.size(); i++ ) { //for each item
DepositItem item = myItems.get(i);
receipt = receipt + (item.number + 1) +": "+item.value +" - A "+item.getName()+" has been inserted into the machine.";
receipt = receipt + System.getProperty("line.separator"); //new line
sum = sum + item.value; //total value
}
receipt = receipt + "Total: "+sum;
myItems = null;
return receipt;
}
}
| true |
5a62e8943d921d56fcacf29b59bd79619444afcd | Java | alxio/ify | /libs/ifyAPI/src/pl/poznan/put/cs/ify/api/core/ActivityHandler.java | UTF-8 | 2,109 | 2.09375 | 2 | [] | no_license | /*******************************************************************************
* Copyright 2014 if{y} team
*
* 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 pl.poznan.put.cs.ify.api.core;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
/**
* Handler used in communication from Service to Activity.
*
*/
public class ActivityHandler extends Handler {
public ActivityHandler(ActivityCommunication comm) {
mComm = comm;
}
public interface ActivityCommunication {
void onAvailableRecipesListReceived(Bundle data);
void onActiveRecipesListReceiverd(Bundle data);
void onLoginFailure(String string);
void onLoginSuccessful();
void onLogout();
}
private ActivityCommunication mComm;
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d("TEMP", "Message delivered do Activity " + msg.what);
switch (msg.what) {
case ServiceHandler.RESPONSE_AVAILABLE_RECIPES:
mComm.onAvailableRecipesListReceived(msg.getData());
break;
case ServiceHandler.RESPONSE_ACTIVE_RECIPES:
mComm.onActiveRecipesListReceiverd(msg.getData());
break;
case ServiceHandler.RESULT_LOGIN:
if (msg.arg1 == ServiceHandler.SUCCESS) {
mComm.onLoginSuccessful();
} else if (msg.arg1 == ServiceHandler.FAILURE) {
mComm.onLoginFailure(msg.getData().getString(
ServiceHandler.MESSAGE));
}
break;
case ServiceHandler.LOGOUT:
mComm.onLogout();
break;
default:
break;
}
}
}
| true |
1f165d11c41ac237615835c9d49ae5069aba4307 | Java | zhuangYuFeiHelloGit/whj1103 | /Day56_Mybatis02/src/main/java/com/lanou/dao/impl/UserDaoImpl.java | UTF-8 | 857 | 2.09375 | 2 | [] | no_license | package com.lanou.dao.impl;
import com.lanou.dao.UserDao;
import com.lanou.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.util.List;
/**
* Created by zyf on 2018/2/7.
*/
public class UserDaoImpl implements UserDao {
private SqlSessionFactory ssf;
public User findById(int id) throws IOException {
ssf = new SqlSessionFactoryBuilder().build(
Resources.getResourceAsReader(
"SqlMapCfg.xml"
)
);
SqlSession sqlSession =
ssf.openSession();
User user =
sqlSession.selectOne(
"user.findById", id
);
return user;
}
public List<User> findAll() {
return null;
}
public void insertUser(User user) {
}
}
| true |
5c05100feeb795bd75af3b0df234c93f83632f40 | Java | arkilis/pyramid | /java/src/com/pyramidframework/sdi/SDIContext.java | GB18030 | 723 | 2.34375 | 2 | [] | no_license | package com.pyramidframework.sdi;
/**
* Ҫתݵݷװһcontext
*
* @author Mikab Peng
* @version 2008-7-26
*/
public class SDIContext {
SDIDocument parent = null; // ĵ
SDIDocument child = null; // õĵ
SDIDocument rule = null; // ̳жĵ
public SDIDocument getParent() {
return parent;
}
public void setParent(SDIDocument parent) {
this.parent = parent;
}
public SDIDocument getChild() {
return child;
}
public void setChild(SDIDocument child) {
this.child = child;
}
public SDIDocument getRule() {
return rule;
}
public void setRule(SDIDocument rule) {
this.rule = rule;
}
}
| true |
b47eb1d34b3fb5702601aa7bbe1e0ec1d05917d1 | Java | dwaps/navigation-console | /src/fr/dwaps/business/RepListAction.java | UTF-8 | 222 | 1.765625 | 2 | [
"MIT"
] | permissive | package fr.dwaps.business;
import fr.dwaps.main.ScreenDisplayer;
public class RepListAction extends AbstractAction {
@Override
public void executeAction(ScreenDisplayer displayer) {
displayer.repListScreen();
}
}
| true |
9ff3d0be86353f7deb641e23fecd49185391d0d8 | Java | ImanH1/Jax-person | /src/java/util/Converter.java | UTF-8 | 986 | 2.546875 | 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 util;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import entity.Person;
import java.util.List;
/**
*
* @author Iman H
*/
public class Converter {
static Gson gson = new Gson();
public static Person getPersonFromJson(String js) {
Person p = gson.fromJson(js, Person.class);
return p;
}
public static String getJSONFromPerson(Person p) {
return gson.toJson(p);
}
public static String getJSONFromPersonList(List<Person> persons) {
return gson.toJson(persons);
}
public static List<Person> getPersonListFromJson(String js) {
List<Person> list = gson.fromJson(js, new TypeToken<List<Person>>(){}.getType());
return list;
}
}
| true |
23e951e687bfcbedc72a6a7ebb08d3b6684e001e | Java | atlassian/hazelcast | /hazelcast/src/main/java/com/hazelcast/cache/impl/LatencyTrackingCacheWriter.java | UTF-8 | 2,986 | 2.03125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.hazelcast.cache.impl;
import com.hazelcast.internal.diagnostics.StoreLatencyPlugin;
import com.hazelcast.internal.diagnostics.StoreLatencyPlugin.LatencyProbe;
import javax.cache.Cache;
import javax.cache.integration.CacheWriter;
import javax.cache.integration.CacheWriterException;
import java.util.Collection;
public class LatencyTrackingCacheWriter<K, V> implements CacheWriter<K, V> {
static final String KEY = "CacheStoreLatency";
private final CacheWriter<K, V> delegate;
private final LatencyProbe writeProbe;
private final LatencyProbe writeAllProbe;
private final LatencyProbe deleteProbe;
private final LatencyProbe deleteAllProbe;
public LatencyTrackingCacheWriter(CacheWriter<K, V> delegate, StoreLatencyPlugin plugin, String cacheName) {
this.delegate = delegate;
this.writeProbe = plugin.newProbe(KEY, cacheName, "write");
this.writeAllProbe = plugin.newProbe(KEY, cacheName, "writeAll");
this.deleteProbe = plugin.newProbe(KEY, cacheName, "delete");
this.deleteAllProbe = plugin.newProbe(KEY, cacheName, "deleteAll");
}
@Override
public void write(Cache.Entry<? extends K, ? extends V> entry) throws CacheWriterException {
long startNanos = System.nanoTime();
try {
delegate.write(entry);
} finally {
writeProbe.recordValue(System.nanoTime() - startNanos);
}
}
@Override
public void writeAll(Collection<Cache.Entry<? extends K, ? extends V>> collection) throws CacheWriterException {
long startNanos = System.nanoTime();
try {
delegate.writeAll(collection);
} finally {
writeAllProbe.recordValue(System.nanoTime() - startNanos);
}
}
@Override
public void delete(Object o) throws CacheWriterException {
long startNanos = System.nanoTime();
try {
delegate.delete(o);
} finally {
deleteProbe.recordValue(System.nanoTime() - startNanos);
}
}
@Override
public void deleteAll(Collection<?> collection) throws CacheWriterException {
long startNanos = System.nanoTime();
try {
delegate.deleteAll(collection);
} finally {
deleteAllProbe.recordValue(System.nanoTime() - startNanos);
}
}
}
| true |
acd6e41a9825a300e7a02bb88ffd683689170715 | Java | BongHoLee/Modern_Java | /src/main/java/PrettyPrint.java | UTF-8 | 70 | 2.109375 | 2 | [] | no_license | public interface PrettyPrint {
String prettyPrint(Apple apple);
}
| true |
6fbe94a7087b5ee647b10ce45b84f0e200e8a6b1 | Java | yanbigot/NiFiCustomProc | /nifi-Processors-processors/src/main/java/com/socgen/drgh/processors/Processors/mapper/ObjectAttribute.java | UTF-8 | 549 | 2.078125 | 2 | [] | no_license | package com.socgen.drgh.processors.Processors.mapper;
import java.util.Map;
public class ObjectAttribute extends AbstractAttribute {
private Map<String,AbstractAttribute> attributes;
private String objectName ;
public Map<String, AbstractAttribute> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, AbstractAttribute> attributes) {
this.attributes = attributes;
}
public String getObjectName() {
return objectName;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
}
| true |
9270c8b2a0dd80bb49fb26e1c947a480f0c38011 | Java | kaleksandrov/social-media-player | /application/app/src/main/java/com/kaleksandrov/smp/model/Model.java | UTF-8 | 367 | 2.46875 | 2 | [
"MIT"
] | permissive | package com.kaleksandrov.smp.model;
/**
* Created by kaleksandrov on 4/25/15.
*/
public class Model {
private int mId;
private String mTitle;
public Model(int id, String title) {
this.mId = id;
this.mTitle = title;
}
public int getId() {
return mId;
}
public String getName() {
return mTitle;
}
}
| true |
0c07f72c3e0eb126e39bfebae7c03cf5d31a6d60 | Java | Romejanic/jMarch | /src/com/romejanic/jmarch/test/HighDefTest.java | UTF-8 | 1,835 | 2.671875 | 3 | [] | no_license | package com.romejanic.jmarch.test;
import java.awt.Color;
import java.io.File;
import com.romejanic.jmarch.Raymarcher;
import com.romejanic.jmarch.Scene;
import com.romejanic.jmarch.debug.Debug;
import com.romejanic.jmarch.lighting.DirectionalLight;
import com.romejanic.jmarch.lighting.Light;
import com.romejanic.jmarch.lighting.PointLight;
import com.romejanic.jmarch.lighting.materials.PhongMaterial;
import com.romejanic.jmarch.math.Camera;
import com.romejanic.jmarch.math.Mathf;
import com.romejanic.jmarch.math.Vec3;
import com.romejanic.jmarch.primitives.Floor;
import com.romejanic.jmarch.primitives.Sphere;
import com.romejanic.jmarch.render.SceneRenderer;
public class HighDefTest {
public static final int WIDTH = 3840;
public static final int HEIGHT = 2160;
public static final int AA = 4;
public static void main(String[] args) throws Exception {
Raymarcher raymarcher = new Raymarcher(WIDTH, HEIGHT, AA);
Scene scene = new Scene();
Camera camera = new Camera(0f, 0f, -3f);
Sphere sphere = new Sphere(Vec3.ZERO, 1f) {
public float getDistance(Vec3 p) {
float dx = Mathf.sin(p.x * 10f);
float dz = Mathf.cos(p.y * 10f);
return super.getDistance(p) - (dx + dz) * 0.15f;
}
};
sphere.setMaterial(new PhongMaterial(Color.red));
scene.addObject(sphere);
scene.addObject(new Floor(Vec3.UP, 1f));
scene.addLight(new DirectionalLight(new Vec3(45f, 30, -45f)));
Light light = scene.addLight(new PointLight(new Vec3(1f, 0f, -1f), 15f));
light.color = Color.yellow;
Light light1 = scene.addLight(new PointLight(new Vec3(0f, 0f, 2f), 10f));
light1.color = Color.green;
Debug.ENABLED = true;
SceneRenderer.renderScene(scene, camera, raymarcher);
SceneRenderer.savePNGToFile(raymarcher, new File("render/high_def_" + WIDTH + "x" + HEIGHT + ".png"));
}
} | true |
987f6aa66e462fde4b41dab6026f5469c1207a3e | Java | waLLxAck/Sparta-Global-SortManager | /src/main/java/com/sparta/svilen/Main.java | UTF-8 | 307 | 1.757813 | 2 | [] | no_license | package com.sparta.svilen;
import com.sparta.svilen.start.Starter;
import com.sparta.svilen.utility.FileRetriever;
/**
* Main.java - application starts from here.
* @author Svilen Petrov
* @version 1.0
*/
public class Main {
public static void main( String[] args ) {
Starter.start();
}
}
| true |
2866d50a8180461a969008a118b93980c7d2d331 | Java | incoding/api-usage | /src/main/java/com/javaapi/test/spring/spring/pattern/templatev2/factory/base/BaseResponseDTO.java | UTF-8 | 838 | 2.390625 | 2 | [] | no_license | package com.javaapi.test.spring.spring.pattern.templatev2.factory.base;
public class BaseResponseDTO extends BaseResult {
private static final long serialVersionUID = -6141372643933452297L;
private String traceId;
public BaseResponseDTO() {
}
public String getTraceId() {
return this.traceId;
}
public BaseResponseDTO setTraceId(String traceId) {
this.traceId = traceId;
return this;
}
public static BaseResponseDTO success(String traceId) {
BaseResponseDTO baseResponseDTO = new BaseResponseDTO();
baseResponseDTO.setTraceId(traceId);
baseResponseDTO.setSuccess(true);
return baseResponseDTO;
}
public String toString() {
return "BaseResponseDTO(super=" + super.toString() + ", traceId=" + this.getTraceId() + ")";
}
}
| true |
bc95550330bd274dc5022d5ab87284dde275ec7f | Java | nghoang/myPHD | /src/DataStructure/GeneralizedTransactionDataSet.java | UTF-8 | 7,747 | 2.703125 | 3 | [] | no_license | package DataStructure;
import java.util.Collections;
import java.util.Vector;
public class GeneralizedTransactionDataSet {
// Vector<Hashtable<String, Boolean>> itemMatrix = new
// Vector<Hashtable<String, Boolean>>();
Vector<GeneralizedTransaction> records = new Vector<GeneralizedTransaction>();
Vector<TransactionItem> suppressedItem = new Vector<TransactionItem>();
public Vector<GeneralizedTransaction> GetData() {
return records;
}
public GeneralizedTransaction get(int i) {
return records.get(i);
}
public int size() {
return records.size();
}
@Override
public String toString() {
String aStr = "";
for (GeneralizedTransaction a : records) {
aStr += a.toString() + "\n";
}
return aStr;
}
public void AddRecord(GeneralizedTransaction item) {
records.add(item);
// Hashtable<String, Boolean> m = new Hashtable<String, Boolean>();
// for (GeneralizedTransactionItem i : item.GetData()) {
// for (String ii : i.get_rule_data()) {
// m.put(ii, true);
// }
// }
// itemMatrix.add(m);
}
public int GetSupport(String p) {
GeneralizedTransactionItem setItem = new GeneralizedTransactionItem();
Vector<String> ps = new Vector<String>();
ps.add(p);
setItem.AddItemData(ps);
return GetSupport(setItem);
}
public int GetSupport(GeneralizedTransactionItem setItem) {
// int res = 0;
// for (GeneralizedTransaction record : records) {
// if (record.IsContains(setItem))
// res++;
// }
// return res;
// for (Hashtable<String, Boolean> i : itemMatrix)
// {
// boolean HasAll = true;
// for (String d : setItem.get_rule_data())
// {
// if (!i.containsKey(d))
// {
// HasAll = false;
// break;
// }
// }
// if (HasAll)
// {
// res++;
// }
// }
// return res;
Vector<GeneralizedTransactionItem> setItems = new Vector<GeneralizedTransactionItem>();
setItems.add(setItem);
return GetSupport(setItems);
}
public int GetSupport(Vector<GeneralizedTransactionItem> setItems) {
// int res = 0;
// GeneralizedTransactionItem ite = new GeneralizedTransactionItem();
// Vector<String> data = new Vector<String>();
Vector<GeneralizedTransaction> temp = new Vector<GeneralizedTransaction>(
records);
Collections.copy(temp, records);
int pos = 0;
for (GeneralizedTransactionItem setitem : setItems) {
pos = 0;
if (setitem.size() == 0)
continue;
int size = temp.size();
for (int j = 0; j < size; j++) {
if (temp.get(pos).IsContains(setitem))
pos++;
else
temp.remove(pos);
}
}
return temp.size();
// Vector<Integer> ignore = new Vector<Integer>();
// for (GeneralizedTransactionItem setitem : setItems) {
// for (int i = 0; i < records.size(); i++) {
// if (ignore.contains(i))
// continue;
// if (!records.get(i).IsContains(setitem)) {
// ignore.add(i);
// }
// }
// }
// for (GeneralizedTransaction record : records) {
// for (GeneralizedTransactionItem ii : setItems) {
// for (String iii : ii.get_rule_data()) {
// if (!data.contains(iii)) {
// data.add(iii);
// }
// }
// }
// if (record.IsContainsAll(setItems))
// res++;
// boolean isFound = false;
// for (GeneralizedTransactionItem tarItem : setItems) {
// for (GeneralizedTransactionItem comparingItem : record
// .GetData()) {
// for (TransactionItem i : tarItem.get_rule()) {
// for (TransactionItem j : comparingItem.get_rule()) {
// if (i.getItem().equals(j.getItem())) {
// isFound = true;
// break;
// }
// }
// if (isFound)
// break;
// }
// }
// if (isFouFnd)
// res++;
// }
// }
// ite.AddItemData(data);
// return GetSupport(ite);
// res = records.size() - ignore.size();
// return res;// / records.size();
}
// public int GetSupportAnd(Vector<GeneralizedTransactionItem> setItems) {
// int res = 0;
// for (GeneralizedTransaction record : records) {
// boolean isFound = false;
// for (GeneralizedTransactionItem tarItem : setItems) {
// for (GeneralizedTransactionItem comparingItem : record
// .GetData()) {
// if (comparingItem.IsThis(tarItem)) {
// res++;
// }
// }
// }
// }
// return res;// / records.size();
// }
public double GetConfidenceOr(Vector<GeneralizedTransactionItem> anteItems,
Vector<GeneralizedTransactionItem> conItems) {
float support1 = GetSupport(anteItems);
anteItems.addAll(conItems);
float support2 = GetSupport(anteItems);
return support2 / support1;
}
// public double GetConfidenceAnd(
// Vector<GeneralizedTransactionItem> anteItems,
// Vector<GeneralizedTransactionItem> conItems) {
// float support1 = GetSupportAnd(anteItems);
// anteItems.addAll(conItems);
// float support2 = GetSupportAnd(anteItems);
// return support2 / support1;
// }
public static GeneralizedTransactionDataSet FilterDataSet(
GeneralizedTransactionDataSet D, GeneralizedTransactionItem item) {
GeneralizedTransactionDataSet nD = new GeneralizedTransactionDataSet();
for (int i = 0; i < D.GetData().size(); i++) {
if (D.GetData().get(i).IsContains(item)) {
nD.AddRecord(D.GetData().get(i));
}
}
return nD;
}
public void Generalize(GeneralizedTransactionItem item) {
for (int i = 0; i < records.size(); i++) {
records.get(i).Generalize(item);
}
// for (int i = 0; i < itemMatrix.size(); i++) {
// boolean isCon = false;
// for (String ii : item.get_rule_data()) {
// if (itemMatrix.get(i).contains(ii)) {
// isCon = true;
// break;
// }
// }
// if (isCon == true) {
// for (String ii : item.get_rule_data()) {
// itemMatrix.get(i).put(ii, true);
// }
// }
//
// }
}
public void AddSet(GeneralizedTransactionDataSet dr) {
for (GeneralizedTransaction t : dr.GetData()) {
AddRecord(t);
}
}
public int NumberOfItems() {
int total = 0;
for (GeneralizedTransaction gt : records) {
total += gt.NumberOfItems();
}
return total;
}
public int SuppressItem(String im) {
TransactionItem i = new TransactionItem(im);
for (TransactionItem ii : suppressedItem) {
if (ii.getItem().equals(i.getItem())) {
return 0;
}
}
suppressedItem.add(i);
int total = 0;
int total_i = 0;
for (int ic = 0; ic < records.size(); ic++) {
total_i = records.get(ic).SuppressItem(im);
if (total_i > 0) {
if (!suppressed_items.contains(ic))
suppressed_items.add(ic);
}
total += total_i;
}
// for (int j = 0; j < itemMatrix.size(); j++) {
// itemMatrix.get(j).remove(im);
// }
return total;
}
public void RemoveEmpty() {
for (int i = 0; i < GetData().size(); i++) {
GetData().get(i).RemoveEmpty();
if (GetData().get(i).GetData().size() == 0) {
GetData().remove(i);
i--;
}
}
}
public void FilterDuplication() {
for (int i = 0; i < GetData().size() - 1; i++) {
for (int j = i + 1; j < GetData().size(); j++) {
if (GetData().get(i).IsContainsAll(GetData().get(j).GetData())) {
GetData().remove(j);
j--;
}
}
}
}
Vector<Integer> suppressed_items;
public Vector<Integer> GetSuppressedItems() {
return suppressed_items;
}
public int SuppressItem(Vector<String> ims) {
int total = 0;
suppressed_items = new Vector<Integer>();
for (String im : ims) {
total += SuppressItem(im);
}
return total;
}
public Vector<GeneralizedTransactionItem> GetDomain() {
Vector<GeneralizedTransactionItem> res = new Vector<GeneralizedTransactionItem>();
for (GeneralizedTransaction tr : records) {
res.addAll(tr.GetData());
}
return RemoveDumplication(res);
}
public static Vector<GeneralizedTransactionItem> RemoveDumplication(
Vector<GeneralizedTransactionItem> data) {
GeneralizedTransaction tr = new GeneralizedTransaction();
tr.AddItemAll(data);
tr.FilterDuplication();
return tr.GetData();
}
}
| true |
e56e6f42452cf1a89c7741f78a27fe3e4d729016 | Java | mr-yhl/javajybc | /day11/src/cn/com/mryhl/demo08_list/Task.java | UTF-8 | 753 | 3.484375 | 3 | [] | no_license | package cn.com.mryhl.demo08_list;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/*
ArrayList是线程不安全的,多个线程一起对ArrayList进行操作有可能会有安全问题
CopyOnWriteArrayList是线程安全的,可以使用它来解决这个问题
*/
public class Task implements Runnable {
//List<Integer> list=new ArrayList<>();
List<Integer> list=new CopyOnWriteArrayList<>();
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
list.add(i);
}
System.out.println("添加完毕");
}
}
| true |
d56be655de3b774727a403abd7f3914d7bf313f7 | Java | SUDIP2222/Java-practice | /src/main/java/Java8/SOILD/LiskovSubstitution/Violate/Bicycle.java | UTF-8 | 259 | 2.078125 | 2 | [] | no_license | package Java8.SOILD.LiskovSubstitution.Violate;
public class Bicycle extends Trasportation {
//violate Liskov Substitution Principle
public void startEngine() {
//problem
throw new AssertionError("Bicycle don't have Engine");
}
}
| true |
84c57c8386d51a3be259879ae032f4429fb23fcb | Java | ischelsea/test | /MemokeyBlog/src/entity/Pinlun.java | UTF-8 | 319 | 1.953125 | 2 | [] | no_license | package entity;
public class Pinlun {
private int count;
private int articleid;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getArticleid() {
return articleid;
}
public void setArticleid(int articleid) {
this.articleid = articleid;
}
}
| true |
46c982bffcc224cfd47faedbae578c9ceeb00b32 | Java | HIHIroom/getTheJob | /Allen/java/code/rfib/RFIB.java | UTF-8 | 966 | 3.0625 | 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 rfib;
import java.util.Scanner;
/**
*
* @User:Huang Yi
*/
public class RFIB {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("請輸入費氏陣列項數:");
Scanner scanner = new Scanner(System.in);
int number=scanner.nextInt();
int[] fArray=new int[number+1];
for(int i=0;i<fArray.length;i++){
fArray[i]=fib(i);
System.out.print( fArray[i]+",");
}
}
public static int fib(int n){
if(n==0 || n==1)
return n;
else
return fib(n-1)+fib(n-2);
}
}
| true |
48aa6f6c888b575f38cbcf30c9dd349aa9306189 | Java | Rugal/gracker | /src/test/java/ga/rugal/gracker/core/service/impl/DetailTerminalServiceImplIntegrationTest.java | UTF-8 | 1,141 | 2.03125 | 2 | [] | no_license | package ga.rugal.gracker.core.service.impl;
import javax.annotation.Resource;
import config.TestConstant;
import ga.rugal.IntegrationTestBase;
import ga.rugal.gracker.core.entity.Issue;
import ga.rugal.gracker.core.service.TerminalService;
import lombok.SneakyThrows;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* @author Rugal Bernstein
*/
public class DetailTerminalServiceImplIntegrationTest extends IntegrationTestBase {
@Autowired
private Issue issue;
@Autowired
private Repository repository;
@Resource(name = "detail")
private TerminalService detail;
private ObjectId id;
@Before
@SneakyThrows
public void setUp() {
this.id = this.repository.resolve(TestConstant.SAMPLE_ID);
this.issue.getCommit().setId(this.id);
}
@SneakyThrows
@Test
public void print() {
this.detail.print(this.issue);
}
@SneakyThrows
@Test
public void print_no_label() {
this.issue.getContent().setLabel(null);
this.detail.print(this.issue);
}
}
| true |
348d96eec06079d6eee556b57110ddd5ff052f82 | Java | elithz/leetcode_questions | /src/LeetCodeQuestions/Medium/TopKFrequentElements_m.java | UTF-8 | 1,051 | 3.34375 | 3 | [] | no_license | package LeetCodeQuestions.Medium;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
public class TopKFrequentElements_m {
class Solution {
public int[] topKFrequent(int[] nums, int k) {
// counter, entry map
int[] ans = new int[k];
Map<Integer, Integer> map = new HashMap<>();
PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>(
(a, b) -> b.getValue() - a.getValue()
);
for (int i = 0; i < nums.length; i++) {
if (!map.containsKey(nums[i])) {
map.put(nums[i], 1);
} else {
map.replace(nums[i], map.get(nums[i]), map.get(nums[i]) + 1);
}
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
pq.add(entry);
}
for (int i = 0; i < k; i++) {
ans[i] = pq.poll().getKey();
}
return ans;
}
}
}
| true |
f40c9379546b37d46ad2ed1a29282508dec41b5b | Java | CustomROMs/android_vendor | /st-ericsson/tools/platform/RefMan/test/com/stericsson/RefMan/Toc/TestElementFactory.java | WINDOWS-1250 | 13,141 | 1.859375 | 2 | [] | no_license | /**
* Copyright ST-Ericsson 2010. All rights reserved.
*/
package com.stericsson.RefMan.Toc;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Vector;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author emarttr <a
* href="mailto:martin.trulsson@stericsson.com?subject=ElementFactory"
* >Email</a>
*
*/
public class TestElementFactory {
/** The root element of the tree with correct structure for b2r2.xml */
Element rootOneFile;
/**
* The root element of the tree with correct structure for all files in
* IM_Tocs folder
*/
Element rootFull;
/**
* The root element of the tree with correct structure for
* stdapi-correct.xml
*/
Element stdApi;
/**
* The root element of the tree with correct structure for standardAPI file
* with values for required arguments and tags only.
*/
Element stdApiOnlyRequired;
/** The logger */
final static Logger logger = LoggerFactory
.getLogger(TestElementFactory.class);
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
Element bar = new TopicElement("1", "bar.html", new Vector<Element>());
Element foo = new TopicElement("2", "foo.html", new Vector<Element>());
Element mySection = new TopicElement("3", "mySection.html",
new Vector<Element>());
Vector<Element> topics = new Vector<Element>();
topics.add(bar);
topics.add(foo);
topics.add(mySection);
Element b2r2 = new TopicElement("b2r2", null, topics);
Vector<Element> b2r2_vector = new Vector<Element>();
b2r2_vector.add(b2r2);
Element userSpace = new TopicElement("User space", null, b2r2_vector);
Vector<Element> userSpace_vector = new Vector<Element>();
userSpace_vector.add(userSpace);
Element multimedia = new TopicElement("Multimedia", null,
userSpace_vector);
Vector<Element> multimedia_vector = new Vector<Element>();
multimedia_vector.add(multimedia);
rootOneFile = new TocElement("API", null, multimedia_vector);
Element b3r3 = new TopicElement("b3r3", null, topics);
Element p2r2 = new TopicElement("p2r2", null, topics);
Element k2r2 = new TopicElement("k2r2", null, topics);
Element k3r3 = new TopicElement("k3r3", null, topics);
Vector<IncludeDoc> includeDirs = new Vector<IncludeDoc>();
includeDirs.add(new IncludeDoc("includedir/", "includes", true));
Vector<IncludeDoc> includeFiles = new Vector<IncludeDoc>();
includeFiles.add(new IncludeDoc("es_full_spec.1.1.10.pdf", "docs",
false));
Vector<Script> scripts = new Vector<Script>();
scripts.add(new Script("testScript", "directory/to/start/in"));
Element stdApiElm = new StdAPIElement("Open GL ES",
"ste-meta-data/opengl-index.xml", "opengl", "opengl", "opengl",
includeDirs, includeFiles, scripts);
Vector<Element> mmUserSpace_vector = new Vector<Element>();
mmUserSpace_vector.add(b2r2);
mmUserSpace_vector.add(b3r3);
mmUserSpace_vector.add(stdApiElm);
Vector<Element> mmKernelSpace_vector = new Vector<Element>();
mmKernelSpace_vector.add(k2r2);
mmKernelSpace_vector.add(k3r3);
Vector<Element> baseKernelSpace_vector = new Vector<Element>();
baseKernelSpace_vector.add(p2r2);
Element baseKernelSpace = new TopicElement("Kernel space", null,
baseKernelSpace_vector);
Element mmUserSpace = new TopicElement("User space", null,
mmUserSpace_vector);
Element mmKernelSpace = new TopicElement("Kernel space", null,
mmKernelSpace_vector);
Vector<Element> base_vector = new Vector<Element>();
base_vector.add(baseKernelSpace);
Vector<Element> mm_vector = new Vector<Element>();
mm_vector.add(mmUserSpace);
mm_vector.add(mmKernelSpace);
Element baseUtilities = new TopicElement("Base utilities", null,
base_vector);
Element multimedia_full = new TopicElement("Multimedia", null,
mm_vector);
Vector<Element> toc_vector = new Vector<Element>();
toc_vector.add(baseUtilities);
toc_vector.add(multimedia_full);
rootFull = new TocElement("API", null, toc_vector);
rootFull.setHref("");
setupStdAPI();
}
/**
* Help method to set up correct standard api element structure.
*/
private void setupStdAPI() {
Vector<IncludeDoc> includeDirs = new Vector<IncludeDoc>();
includeDirs.add(new IncludeDoc("includedir/", "includes", true));
Vector<IncludeDoc> includeFiles = new Vector<IncludeDoc>();
includeFiles.add(new IncludeDoc("es_full_spec.1.1.10.pdf", "docs",
false));
Vector<Script> scripts = new Vector<Script>();
scripts.add(new Script("testScript", "directory/to/start/in"));
Element stdApiElm = new StdAPIElement("Open GL ES",
"ste-meta-data/opengl-index.xml", "opengl", "opengl", "opengl",
includeDirs, includeFiles, scripts);
Vector<Element> userSpace_vector = new Vector<Element>();
userSpace_vector.add(stdApiElm);
Element userSpace = new TopicElement("User space", null,
userSpace_vector);
Vector<Element> mm_vector = new Vector<Element>();
mm_vector.add(userSpace);
Element multimedia = new TopicElement("Multimedia", null, mm_vector);
Vector<Element> toc_vector = new Vector<Element>();
toc_vector.add(multimedia);
stdApi = new TocElement("API", null, toc_vector);
Element stdAPIElmReq = new StdAPIElement("Open GL ES",
"ste-meta-data/opengl-index.xml", "opengl", null, null,
new Vector<IncludeDoc>(), new Vector<IncludeDoc>(),
new Vector<Script>());
Vector<Element> vUs = new Vector<Element>();
vUs.add(stdAPIElmReq);
Element us = new TopicElement("User space", null, vUs);
Vector<Element> vMm = new Vector<Element>();
vMm.add(us);
Element mm = new TopicElement("Multimedia", null, vMm);
Vector<Element> vToc = new Vector<Element>();
vToc.add(mm);
stdApiOnlyRequired = new TocElement("API", null, vToc);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}
/**
* Test method for {@link ElementFactory#getElementArray(File ImTocFiles)}.
*/
@Test
public void testGetElementArray() {
String inputFilePath = "test//com//stericsson//RefMan//Toc//IM_Tocs";
boolean passed = true;
try {
List<Element> tocs = ElementFactory.getElementArray(new File(
inputFilePath));
if (tocs.size() > 0) {
passed = checkElements(tocs.get(0), rootOneFile);
}
} catch (Exception e) {
logger.error("Could not get the toc files. ", e.getMessage());
}
assertTrue(passed);
}
/**
* Test method for {@link ElementFactory#getElementArray(File ImTocFiles)}.
*
* Test getElementArray with two toc files that have the same name.
*/
@Test
public void testGetElementArrayDuplicatedModule() {
String inputFilePath = "test//com//stericsson//RefMan//Toc//DuplicatedModules";
try {
InputStream in = new FileInputStream(new File(inputFilePath
+ "//toc-location2.xml"));
OutputStream out = new FileOutputStream(new File(inputFilePath
+ "//toc-location.xml"));
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (FileNotFoundException e1) {
logger.info("File could not be found " + e1);
} catch (IOException e) {
logger.info("Failed to copy file " + e);
}
try {
List<Element> tocs = ElementFactory.getElementArray(new File(
inputFilePath));
assertTrue(tocs.size() == 1);
} catch (IOException e) {
logger.error("Could not get the toc files. ", e.getMessage());
}
}
/**
* Test method for
* {@link ElementFactory#getElement(File imTocFile, int depth)} .
*/
@Test
public void testGetElement() {
boolean passed = true;
Element elm = ElementFactory.getElement(new File(
"test//com//stericsson//RefMan//Toc//IM_Tocs//b2r2.xml"), 0);
passed = checkElements(elm, rootOneFile);
assertTrue(passed);
}
/**
* Test method for
* {@link ElementFactory#getElement(File imTocFile, int depth)} . Test to
* handle a toc-location file for a standard api.
*/
@Test
public void testGetElementStdAPIElement() {
Element elm = ElementFactory.getElement(new File(
"test//com//stericsson//RefMan//Toc//stdapi-correct.xml"), 0);
assertTrue(checkElements(elm, stdApi));
}
/**
* Test method for
* {@link ElementFactory#getElement(File imTocFile, int depth)} . Test to
* handle a toc-location file for a standard api with values for required
* arguments and tags only.
*/
@Test
public void testGetElementStdAPIElementRequiredOnly() {
Element elm = ElementFactory
.getElement(
new File(
"test//com//stericsson//RefMan//Toc//stdapi-required-only.xml"),
0);
assertTrue(checkElements(elm, stdApiOnlyRequired));
}
/**
* Help method that compares two <code>Element's</code> to see if they are equal.
*
* @return <code>True</code> if the <code>Element's</code> are equal, otherwise
* <code>False</code>.
*/
private boolean checkElements(Element e1, Element e2) {
boolean passed = true;
List<Element> children_e1;
List<Element> children_e2;
if (!e1.toString().equals(e2.toString())) {
logger.error(e1.toString() + " doesnt match " + e2.toString());
passed = false;
}
if (passed) {
children_e1 = e1.getTopics();
children_e2 = e2.getTopics();
if (children_e1.size() != children_e2.size()) {
passed = false;
} else {
for (int i = 0; i < children_e1.size(); i++) {
passed = checkElements(children_e1.get(i), children_e2
.get(i));
if (!passed) {
break;
}
}
}
}
return passed;
}
/**
* Test method for
* {@link ElementFactory#getAssembledElement(File ImTocFiles)} .
*/
@Test
public void testGetAssembledElement() {
boolean passed = true;
Element elm = ElementFactory.getAssembledElement(new File(
"test//com//stericsson//RefMan//Toc//IM_Tocs"));
passed = checkElements(elm, rootFull);
assertTrue(passed);
}
/**
* Test method for {@link ElementFactory#sort(Element tocElm)} .
*/
@Test
public void testSort() {
Element bar = new TopicElement("1", "bar.html", new Vector<Element>());
Element foo = new TopicElement("2", "foo.html", new Vector<Element>());
Element mySection = new TopicElement("3", "mySection.html",
new Vector<Element>());
Vector<Element> topics = new Vector<Element>();
topics.add(mySection);
topics.add(bar);
topics.add(foo);
Element elm = new TopicElement("name", null, topics);
List<Element> correct = new Vector<Element>();
correct.add(bar);
correct.add(foo);
correct.add(mySection);
ElementFactory.sort(elm);
Vector<Element> sorted = (Vector<Element>) elm.getTopics();
for (int i = 0; i < sorted.size(); i++) {
assertTrue(sorted.get(i).equals(correct.get(i)));
}
}
}
| true |
f3a58a02878cbd45afd9fef96b4f303c32f94e55 | Java | wooui/JavaBattleField | /src/com/wooui/mail/SendMailTest.java | UTF-8 | 840 | 2.640625 | 3 | [] | no_license | package com.wooui.mail;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
public class SendMailTest {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.163.com");
Session session = Session.getInstance(props, null);
try{
MimeMessage msg = new MimeMessage(session);
msg.setFrom("jasonyifei@163.com");
msg.setRecipients(Message.RecipientType.TO, "37978634@qq.com");
msg.setSubject("Test java mail");
msg.setSentDate(new Date());
msg.setText("Hello Java Mail");
Transport.send(msg, "jasonyifei@163.com","111111");
}catch (MessagingException e){
System.out.println("send failed, excepton:" + e);
}
}
}
| true |
1732fa05d210f2e7f7eb87cc10242b6e4da2917a | Java | XuCpeng/LeetCode_PTA | /JavaCodeSpace/src/cn/medemede/leecode/MinOperations.java | UTF-8 | 1,374 | 3.5625 | 4 | [] | no_license | package cn.medemede.leecode;
import java.util.ArrayList;
import java.util.HashMap;
/**
* 得到子序列的最少操作次数
* <p>
* 转换为最长单调子序列问题,贪心+二分查找
*/
public class MinOperations {
public int minOperations(int[] target, int[] arr) {
HashMap<Integer, Integer> numToIndex = new HashMap<>();
for (int i = 0; i < target.length; i++) {
numToIndex.put(target[i], i);
}
ArrayList<Integer> arrIndex = new ArrayList<>();
for (int x : arr) {
if (numToIndex.containsKey(x)) {
arrIndex.add(numToIndex.get(x));
}
}
ArrayList<Integer> d = new ArrayList<>();
if (arrIndex.isEmpty()) {
return target.length;
}
d.add(arrIndex.get(0));
for (int x : arrIndex) {
int n = d.size();
if (x > d.get(n - 1)) {
d.add(x);
} else {
int p = 0;
int q = n;
while (p < q) {
int mid = (p + q) / 2;
if (d.get(mid) < x) {
p = mid + 1;
} else {
q = mid;
}
}
d.set(p, x);
}
}
return target.length - d.size();
}
}
| true |
4d78446754816dbf316bde8143d7acd06b14eed8 | Java | pinky07/EmployeeAppraisal | /src/test/java/com/gft/employeeappraisal/helper/builder/model/EmployeeEvaluationFormAnswerBuilder.java | UTF-8 | 3,353 | 2.546875 | 3 | [] | no_license | package com.gft.employeeappraisal.helper.builder.model;
import com.gft.employeeappraisal.helper.builder.ObjectBuilder;
import com.gft.employeeappraisal.model.EmployeeEvaluationForm;
import com.gft.employeeappraisal.model.EmployeeEvaluationFormAnswer;
import com.gft.employeeappraisal.model.EvaluationFormTemplateXSectionXQuestion;
import com.gft.employeeappraisal.model.ScoreValue;
/**
* Builder object for the {@link EmployeeEvaluationFormAnswer} class.
*
* @author Manuel Yépez
*/
public class EmployeeEvaluationFormAnswerBuilder implements ObjectBuilder<EmployeeEvaluationFormAnswer> {
private int id;
private EmployeeEvaluationForm employeeEvaluationForm;
private EvaluationFormTemplateXSectionXQuestion evaluationFormTemplateXSectionXQuestion;
private ScoreValue scoreValue;
private String comment;
private boolean idSet;
private boolean evaluationFormTemplateSet;
private boolean scoreValueSet;
private boolean commentSet;
// This was made to avoid a cyclic redundance error. On a business level, it's impossible to have no
// EmployeeEvaluationForm nor EvaluationFormTemplate here.
public EmployeeEvaluationFormAnswerBuilder(EmployeeEvaluationForm employeeEvaluationForm) {
this.employeeEvaluationForm = employeeEvaluationForm;
}
public EmployeeEvaluationFormAnswerBuilder id(int id) {
this.id = id;
this.idSet = true;
return this;
}
public EmployeeEvaluationFormAnswerBuilder evaluationFormTemplateXSectionXQuestion(
EvaluationFormTemplateXSectionXQuestion evaluationFormTemplateXSectionXQuestion) {
this.evaluationFormTemplateXSectionXQuestion = evaluationFormTemplateXSectionXQuestion;
this.evaluationFormTemplateSet = true;
return this;
}
public EmployeeEvaluationFormAnswerBuilder scoreValue(ScoreValue scoreValue) {
this.scoreValue = scoreValue;
this.scoreValueSet = true;
return this;
}
public EmployeeEvaluationFormAnswerBuilder comment(String comment) {
this.comment = comment;
this.commentSet = true;
return this;
}
@Override
public EmployeeEvaluationFormAnswer build() {
EmployeeEvaluationFormAnswer obj = new EmployeeEvaluationFormAnswer();
obj.setId(this.id);
obj.setEmployeeEvaluationForm(this.employeeEvaluationForm);
obj.setEvaluationFormTemplateXSectionXQuestion(this.evaluationFormTemplateXSectionXQuestion);
obj.setScoreValue(this.scoreValue);
obj.setComment(this.comment);
return obj;
}
@Override
public EmployeeEvaluationFormAnswer buildWithDefaults() {
EmployeeEvaluationFormAnswer obj = new EmployeeEvaluationFormAnswer();
if (this.idSet) obj.setId(this.id);
obj.setEmployeeEvaluationForm(this.employeeEvaluationForm);
obj.setEvaluationFormTemplateXSectionXQuestion(this.evaluationFormTemplateSet ?
this.evaluationFormTemplateXSectionXQuestion :
new EvaluationFormTemplateXSectionXQuestionBuilder(obj.getEmployeeEvaluationForm()
.getEvaluationFormTemplate()).buildWithDefaults());
if (this.scoreValueSet) obj.setScoreValue(this.scoreValue);
obj.setComment(this.commentSet ? this.comment : "Test Comment");
return obj;
}
}
| true |
0e32351a9e096a5e5dfcd0069d36e47881081489 | Java | chdryra/Startouch | /src/main/java/com/chdryra/android/startouch/ApplicationPlugins/PlugIns/PersistencePlugin/SQLiteFirebase/LocalReviewerDb/SqLiteDb/Implementation/FactoryTransactorSqLite.java | UTF-8 | 1,174 | 2.078125 | 2 | [] | no_license | /*
* Copyright (c) Rizwan Choudrey 2016 - All Rights Reserved
* Unauthorized copying of this file via any medium is strictly prohibited
* Proprietary and confidential
* rizwan.choudrey@gmail.com
*
*/
package com.chdryra.android.startouch.ApplicationPlugins.PlugIns.PersistencePlugin.SQLiteFirebase
.LocalReviewerDb.SqLiteDb.Implementation;
import android.database.sqlite.SQLiteDatabase;
import com.chdryra.android.startouch.ApplicationPlugins.PlugIns.PersistencePlugin.Implementation
.RelationalDb.Api.TableTransactor;
/**
* Created by: Rizwan Choudrey
* On: 12/01/2016
* Email: rizwan.choudrey@gmail.com
*/
public class FactoryTransactorSqLite {
private final RowToValuesConverter mRowConverter;
private final EntryToStringConverter mEntryConverter;
public FactoryTransactorSqLite(RowToValuesConverter rowConverter,
EntryToStringConverter entryConverter) {
mRowConverter = rowConverter;
mEntryConverter = entryConverter;
}
public TableTransactor newTransactor(SQLiteDatabase db, TablesSql sql) {
return new TableTransactorSqLite(new AndroidSqLiteDb(db), sql, mRowConverter,
mEntryConverter);
}
}
| true |
768c20e376336e8a9a445d5e6513321dfedbfc9f | Java | IlknurAslan/KayipBulMobil | /Kanpaylasmaproje/app/src/main/java/com/example/asus/kanpaylasmaproje/InsanKayipListe.java | UTF-8 | 3,652 | 2.015625 | 2 | [] | no_license | package com.example.asus.kanpaylasmaproje;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class InsanKayipListe extends AppCompatActivity {
// List<String> arrList = new ArrayList<String>();
// KayipListeAdapter adapter;
// KayipListeAdapter adapter1;
String kategori="insan";
private FirebaseAuth firebaseKullanicilar;
private DatabaseReference veritabaniReferans;
private ListView list;
private KayipListeAdapter insankayipListeAdapter;
private List<KayipPaylasModel> insanpaylasilanList;
private ProgressDialog yüklemeDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insan_kayip_liste);
setTitle("İNSAN KAYIP LİSTESİ");
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
list = (ListView) findViewById(R.id.insanlistkayip);
insanpaylasilanList = new ArrayList<>();
firebaseKullanicilar = FirebaseAuth.getInstance();
veritabaniReferans = FirebaseDatabase.getInstance().getReference("kayipara");
yüklemeDialog = new ProgressDialog(InsanKayipListe.this);
yüklemeDialog.setMessage("Yükleniyor...");
yüklemeDialog.setCancelable(false);
yüklemeDialog.show();
DatabaseReference ddRef= FirebaseDatabase.getInstance().getReference().child("kayipara");
DatabaseReference ddRef1= FirebaseDatabase.getInstance().getReference().child("users");
veritabaniReferans.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
yüklemeDialog.dismiss();
insanpaylasilanList.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
if (kategori.equals(postSnapshot.child("kategori").getValue().toString())) {
KayipPaylasModel userObj = postSnapshot.getValue(KayipPaylasModel.class);
insanpaylasilanList.add(userObj);
}
}
insankayipListeAdapter = new KayipListeAdapter(getApplicationContext(),insanpaylasilanList);
list.setAdapter(insankayipListeAdapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
yüklemeDialog.dismiss();
Toast.makeText(InsanKayipListe.this, "DATABASE error", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onResume() {
super.onResume();
if(insankayipListeAdapter!=null){
insankayipListeAdapter.notifyDataSetChanged();
}
}
}
| true |
0764d7779a6351f391de6fcea6223b3513f381b3 | Java | SunWen991/pc | /web/src/main/java/com/heidian/reptile/WeiBoArticleProcessor.java | UTF-8 | 2,661 | 1.648438 | 2 | [] | no_license | package com.heidian.reptile;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;
import java.util.List;
/**
* @author :SunWen
* @date :Created in 2019/12/19 18:25
* @description:微博文章
* @modified By:
* @version: 1.0.0$
*/
public class WeiBoArticleProcessor implements PageProcessor {
// 抓取网站的相关配置,包括编码、抓取间隔、重试次数等
private Site site = Site.me().setRetryTimes(3).setSleepTime(100).addCookie("Cookie",
"Ugrow - G0 = 140 ad66ad7317901fc818d7fd7743564;" +
"login_sid_t = 4 cf727ad071b41296f443d951221b401;" +
"cross_origin_proto = SSL;" +
"TC - V5 - G0 = 595 b7637c272b28fccec3e9d529f251a;" +
"_s_tentry = passport.weibo.com;" +
"Apache = 6563767398768.017 .1576732291495;" +
"SINAGLOBAL = 6563767398768.017 .1576732291495;" +
"ULV = 1576732291507: 1: 1: 1: 6563767398768.017 .1576732291495: ;" +
"WBtopGlobal_register_version = 307744 aa77dd5677;" +
"UOR = , , login.sina.com.cn;" +
"appkey = ;" +
"YF - V5 - G0 = 9903 d059c95dd34f9204f222e5a596b8;" +
"wb_view_log = 1366 * 7681 % 261920 * 10801;" +
"SUB = _2A25w - AcxDeRhGeFO6lYX8SrMzDyIHXVTjH_5rDV8PUNbmtANLRjekW9NQZME_5EUPahiL9og1DDjyL9FnBoNPqsc;" +
"SUBP = 0033 WrSXqPxfM725Ws9jqgMF55529P9D9W5Eo9jDMJ0cuHTxChY.axgf5JpX5KzhUgL.FoM7eKBceKB7S052dJLoI0qLxK - L1K5LB - qLxKqL1KnL12 - LxKqL1KnL1 - qLxKML1 - 2 L1hBLxK - LBKBL1 - eLxKqL1K.L1 - 2 t;" +
"SUHB = 0x nCEMUlFtJQFc;" +
"ALF = 1608362721;" +
"SSOLoginState = 1576826721;" +
"wb_view_log_7014614070 = 1366 * 7681 % 261920 * 10801;" +
"wvr = 6;" +
"TC - Page - G0 = b993e9b6e353749ed3459e1837a0ae89 | 1576832955 | 1576832884;" +
"webim_unReadCount = % 7 B % 22 time % 22 % 3 A1576833201705 % 2 C % 22 dm_pub_total % 22 % 3 A1 % 2 C % 22 chat_group_client % 22 % 3 A1019 % 2 C % 22 allcountNum % 22 % 3 A1020 % 2 C % 22 msgbox % 22 % 3 A0 % 7 D"
);
@Override
public void process(Page page) {
//List<String> stringList = page.getHtml().xpath("//*[@id=\"pl_top_realtimehot\"]/table/tbody/tr/td[2]/a/text()").all();
System.out.println("数据:"+page.getRawText());
}
@Override
public Site getSite() {
return site;
}
}
| true |
51abf95a3aa36b3ce2d536b7b3f962fa472d3e1a | Java | YezenRashid/Coding-Problems | /Knights Tour (Java)/Optimized with a Chess Board/HorseVisit.java | UTF-8 | 2,971 | 3.53125 | 4 | [] | no_license | import java.util.*;
public class HorseVisit {
public static final int SIZE = 5;
private Tile[][] chessBoard = new Tile[SIZE][SIZE];
public class Tile {
boolean visited;
int col;
int row;
Tile() {
col = 0;
row = 0;
visited = false;
}
Tile(int col, int row, boolean visited) {
this.col = col;
this.row = row;
this.visited = visited;
}
}
HorseVisit(int initialCol, int initialRow) {
//Intialize chessBoard
for(int row = 0; row < chessBoard.length; row++) {
for(int col = 0; col < chessBoard[0].length; col++) {
chessBoard[col][row] = new Tile(col, row, false);
}
}
Stack<Tile> path = new Stack<Tile>();
chessBoard[initialCol][initialRow].visited = true;
path.push(chessBoard[initialCol][initialRow]);
if(horsePath(chessBoard[initialCol][initialRow], path)) {
System.out.println(path.size());
printPath(path);
} else {
System.out.println("Could not find a possible path");
}
}
public boolean horsePath(Tile t, Stack<Tile> path) {
if(path.size() >= SIZE*SIZE) {
return true;
} else {
ArrayList<Tile> availableMoves = possibleMoves(t, path);
if(availableMoves.isEmpty()) {
return false;
}
for(int i = 0; i < availableMoves.size(); i++) {
path.push(availableMoves.get(i));
chessBoard[availableMoves.get(i).col][availableMoves.get(i).row].visited = true;
if(horsePath(availableMoves.get(i), path)) {
return true;
}
path.pop();
chessBoard[availableMoves.get(i).col][availableMoves.get(i).row].visited = false;
}
}
return false;
}
public ArrayList<Tile> possibleMoves(Tile t, Stack<Tile> path) {
ArrayList<Tile> tiles = new ArrayList<Tile>();
if(t.col + 1 < SIZE && t.row + 2 < SIZE) {
tiles.add(chessBoard[t.col + 1][t.row + 2]);
}
if(t.col + 1 < SIZE && t.row - 2 >= 0) {
tiles.add(chessBoard[t.col + 1][t.row - 2]);
}
if(t.col + 2 < SIZE && t.row + 1 < SIZE) {
tiles.add(chessBoard[t.col + 2][t.row + 1]);
}
if(t.col + 2 < SIZE && t.row - 1 >= 0) {
tiles.add(chessBoard[t.col + 2][t.row - 1]);
}
if(t.col - 1 >= 0 && t.row + 2 < SIZE) {
tiles.add(chessBoard[t.col - 1][t.row + 2]);
}
if(t.col - 1 >= 0 && t.row - 2 >= 0) {
tiles.add(chessBoard[t.col - 1][t.row - 2]);
}
if(t.col - 2 >= 0 && t.row + 1 < SIZE) {
tiles.add(chessBoard[t.col - 2][t.row + 1]);
}
if(t.col - 2 >= 0 && t.row - 1 >= 0) {
tiles.add(chessBoard[t.col - 2][t.row - 1]);
}
for(int i = 0; i < tiles.size(); i++) {
if(chessBoard[tiles.get(i).col][tiles.get(i).row].visited) {
tiles.remove(i);
i--;
}
}
return tiles;
}
public void printPath(Stack<Tile> path) {
Queue<Tile> q = new LinkedList<Tile>();
while(!path.isEmpty()) {
q.add(path.pop());
}
while(!q.isEmpty()) {
path.push(q.remove());
}
while(!path.isEmpty()) {
Tile t = path.pop();
System.out.print("(" + t.col + ", " + t.row + ") ->");
}
}
}
| true |
5379b9bb6be0b723fbcadd4477b5e06d0a1916cb | Java | developeratdaguanyuan/ikkyu | /utils/nlp/src/main/java/nlp/tokenizer/EnglishTokenizer.java | UTF-8 | 1,059 | 3.0625 | 3 | [] | no_license | package nlp.tokenizer;
import java.io.IOException;
import java.io.StringReader;
import java.util.LinkedList;
import java.util.List;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.process.CoreLabelTokenFactory;
import edu.stanford.nlp.process.PTBTokenizer;
public class EnglishTokenizer {
public static List<String> tokenizer(String text) {
PTBTokenizer<CoreLabel> ptbt =
new PTBTokenizer<CoreLabel>(new StringReader(text), new CoreLabelTokenFactory(), "normalizeParentheses=false,normalizeOtherBrackets=false,latexQuotes=false,asciiQuotes=true,escapeForwardSlashAsterisk=false");
List<String> tokens = new LinkedList<String>();
while (ptbt.hasNext()) {
CoreLabel label = ptbt.next();
tokens.add(label.value());
}
return tokens;
}
public static void main(String[] args) throws IOException {
List<String> tokens = EnglishTokenizer.tokenizer("Who created la bohème, act iv: in un coupé??".toLowerCase());
for (String token : tokens) {
System.out.println(token);
}
}
}
| true |
90e45dafbbad988cb1c6308902d3457c232cad77 | Java | sergeylukichev/JavaCourse | /Drafts/project-tracker/src/main/java/com/telran/project/tracker/repository/UserSessionRepository.java | UTF-8 | 321 | 1.890625 | 2 | [] | no_license | package com.telran.project.tracker.repository;
import com.telran.project.tracker.model.entity.UserSession;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserSessionRepository extends JpaRepository<UserSession, Long> {
UserSession findBySessionIdAndIsValidTrue(String sessionId);
}
| true |
32618ae19efd8758827e6760afb113780dce3f0e | Java | stefanjcollier/ThirdYearProject | /test/sjc/dissertation/retailer/state/quality/QualityTest.java | UTF-8 | 7,990 | 3.234375 | 3 | [] | no_license | package sjc.dissertation.retailer.state.quality;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Set;
import org.junit.Test;
public class QualityTest {
final double HIGH_QUALITY_COST = 100;
final double MEDIUM_QUALITY_COST = 66;
final double LOW_QUALITY_COST = 44.44;
/**
* A test to ensure that the equals works.
* High = High, Low = Low, High != Low, etc
*/
@Test
public void testEqualsMethodWorks(){
//GIVEN each Quality instance
final Quality hq = Quality.HighQuality;
final Quality mq = Quality.MediumQuality;
final Quality lq = Quality.LowQuality;
//THEN They are equal to themselves
assertEquals("High should equal itself", hq, hq);
assertEquals("Medium should equal itself", mq, mq);
assertEquals("Low should equal itself", lq, lq);
//AND High != Medium != Low != High
assertNotEquals("High should not equal Medium", hq, mq);
assertNotEquals("Medium should not equal Low", mq, lq);
assertNotEquals("Low should not equal High", lq, hq);
//GIVEN one more of each quality instance
final Quality hq2 = Quality.HighQuality;
final Quality mq2 = Quality.MediumQuality;
final Quality lq2 = Quality.LowQuality;
//THEN the new instances should equal their origonal counterparts
assertEquals("The new High instance should equal the first High instance", hq, hq2);
assertEquals("The new Medium instance should equal the first Medium instance", mq, mq2);
assertEquals("The new Low instance should equal the first Low instance", lq, lq2);
}
/**
* A test to ensure the cost of each level is correct.
*
* Methods Under Test: Constructor, getCost()
*/
@Test
public void testThatTheValuesAreCorrect(){
//GIVEN each Quality instance
final Quality hq = Quality.HighQuality;
final Quality mq = Quality.MediumQuality;
final Quality lq = Quality.LowQuality;
//WHEN getting their costs
final double hC = hq.getCost();
final double mC = mq.getCost();
final double lC = lq.getCost();
//THEN their costs are the intended value
assertEquals("High cost not correct", this.HIGH_QUALITY_COST, hC, 0);
assertEquals("Medium cost not correct", this.MEDIUM_QUALITY_COST, mC, 0);
assertEquals("Low cost not correct", this.LOW_QUALITY_COST, lC, 0);
}
/**
* A test to see that HighQuality behaves correctly under all quality change commands.
*
* Methods Under Test: Constructor, changeQuality()
* @throws InvalidQualityException -- The unexpected error caused from changing the quality level
*/
@Test
public void testHighQualityChangeCommands() throws InvalidQualityException {
//GIVEN a HighQuality instance
final Quality q = Quality.HighQuality;
//AND all quality changes
final QualityChange plusQ= QualityChange.IncreaseQuality;
final QualityChange mainQ= QualityChange.MaintainQuality;
final QualityChange minusQ= QualityChange.DecreaseQuality;
//WHEN changing the quality using each change level
final Quality q_mainQ = q.changeQuality(mainQ);
final Quality q_minusQ = q.changeQuality(minusQ);
//THEN High + Increase = throws an exception
try {
q.changeQuality(plusQ);
fail("Commanding HighQuality to IncreaseQuality should throw an Exception");
} catch (final InvalidQualityException e) {
//We expect an exception to be thrown
}
//AND High + Maintain = High
assertEquals("'High + Maintain = High' is not true", Quality.HighQuality, q_mainQ);
//AND High + Decrease = Medium
assertEquals("'High + Decrease = Medium' is not true", Quality.MediumQuality, q_minusQ);
}
/**
* A test to see that MediumQuality behaves correctly under all quality change commands.
*
* Methods Under Test: Constructor, changeQuality()
* @throws InvalidQualityException -- The unexpected error caused from changing the quality level
*/
@Test
public void testMediumQualityChangeCommands() throws InvalidQualityException {
//GIVEN a HighQuality instance
final Quality q = Quality.MediumQuality;
//AND all quality changes
final QualityChange plusQ= QualityChange.IncreaseQuality;
final QualityChange mainQ= QualityChange.MaintainQuality;
final QualityChange minusQ= QualityChange.DecreaseQuality;
//WHEN changing the quality using each change level
final Quality q_plusQ = q.changeQuality(plusQ);
final Quality q_mainQ = q.changeQuality(mainQ);
final Quality q_minusQ = q.changeQuality(minusQ);
//THEN Medium + Increase = High
assertEquals("'Medium + Increase = High' is not true", Quality.HighQuality, q_plusQ);
//AND Medium + Maintain = Medium
assertEquals("'Medium + Maintain = Medium' is not true", Quality.MediumQuality, q_mainQ);
//AND Medium + Decrease = Low
assertEquals("'Medium + Decrease = Low' is not true", Quality.LowQuality, q_minusQ);
}
/**
* A test to see that LowQuality behaves correctly under all quality change commands.
*
* Methods Under Test: Constructor, changeQuality()
* @throws InvalidQualityException -- The unexpected error caused from changing the quality level
*/
@Test
public void testLowQualityChangeCommands() throws InvalidQualityException {
//GIVEN a HighQuality instance
final Quality q = Quality.LowQuality;
//AND all quality changes
final QualityChange plusQ= QualityChange.IncreaseQuality;
final QualityChange mainQ= QualityChange.MaintainQuality;
final QualityChange minusQ= QualityChange.DecreaseQuality;
//WHEN changing the quality using each change level
final Quality q_plusQ = q.changeQuality(plusQ);
final Quality q_mainQ = q.changeQuality(mainQ);
//THEN Low + Increase = Medium
assertEquals("'Low + Increase = Medium' is not true", Quality.MediumQuality, q_plusQ);
//AND Low + Maintain = Low
assertEquals("'Low + Maintain = Low' is not true", Quality.LowQuality, q_mainQ);
//AND Low + Decrease = throw exception
try {
q.changeQuality(minusQ);
fail("Commanding HighQuality to IncreaseQuality should throw an Exception");
} catch (final InvalidQualityException e) {
//We expect an exception to be thrown
}
}
@Test
public void testHighQualityProducesCorrectActions(){
//GIVEN a Quality level
final Quality q = Quality.HighQuality;
//WHEN getting all actions
final Set<QualityChange> actions = q.getActions();
//THEN there are only 2 actions
assertEquals("High should only have 2 actions", 2, actions.size());
//AND those actions are the correct actions
assertTrue("High Quality should be able to Maintain.", actions.contains(QualityChange.MaintainQuality));
assertTrue("High Quality should be able to Decrease.", actions.contains(QualityChange.DecreaseQuality));
}
@Test
public void testMediumQualityProducesCorrectActions(){
//GIVEN a Quality level
final Quality q = Quality.MediumQuality;
//WHEN getting all actions
final Set<QualityChange> actions = q.getActions();
//THEN there are only 3 actions
assertEquals("Medium should only have 3 actions", 3, actions.size());
//AND those actions are the correct actions
assertTrue("Medium Quality should be able to Increase.", actions.contains(QualityChange.IncreaseQuality));
assertTrue("Medium Quality should be able to Maintain.", actions.contains(QualityChange.MaintainQuality));
assertTrue("Medium Quality should be able to Decrease.", actions.contains(QualityChange.DecreaseQuality));
}
@Test
public void testLowQualityProducesCorrectActions(){
//GIVEN a Quality level
final Quality q = Quality.LowQuality;
//WHEN getting all actions
final Set<QualityChange> actions = q.getActions();
//THEN there are only 2 actions
assertEquals("Medium should only have 2 actions", 2, actions.size());
//AND those actions are the correct actions
assertTrue("Low Quality should be able to Increase.", actions.contains(QualityChange.IncreaseQuality));
assertTrue("Low Quality should be able to Maintain.", actions.contains(QualityChange.MaintainQuality));
}
}
| true |
cbbbc7975cb883e277dbe3400960c455909c57f7 | Java | brunoSS07/aula-2-JAVA | /aula09/exemplos/Exemplo02.java | UTF-8 | 581 | 3.390625 | 3 | [] | no_license | package exemplos;
import java.util.ArrayList;
public class Exemplo02 {
//public boolean ativar(int p){
// return p > 1;
//}
public static void main(String[] args) {
ArrayList<Integer> lista = new ArrayList<>();
lista.add(1);
lista.add(2);
lista.add(3);
lista.add(4);
//System.out.println(lista);
for (int i = 0; i < lista.size(); i++) {
System.out.println(lista.get(i));
}
//Exemplo02 e = new Exemplo02();
//System.out.println(e.ativar( 1));
}
}
| true |
1907d8b91b089e0d3e69b3ec51c373466b6f3659 | Java | qiu2421653/AndroidProject | /MyApplication/app/src/main/java/com/qiu/retrofit/view/activity/WallPaperActivity.java | UTF-8 | 1,422 | 1.859375 | 2 | [] | no_license | package com.qiu.retrofit.view.activity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.CompoundButton;
import com.qiu.retrofit.R;
import com.qiu.retrofit.core.service.VideoLiveWallpaper;
import com.qiu.retrofit.presenter.BasePresenter;
import com.qiu.retrofit.view.activity.base.BaseActivity;
import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
/**
* @author @Qiu
* @version V1.0
* @Description:屏保
* @date 2017/5/31 10:37
*/
public class WallPaperActivity extends BaseActivity {
@BindView(R.id.toolbar)
Toolbar toolbar;
@Override
public void onCreateMyView() {
setContentView(R.layout.activity_animator);
}
@Override
public void initView() {
}
@Override
public void initData() {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public BasePresenter initPresenter() {
return null;
}
@OnClick({R.id.tv_first})
public void onClick(View view) {
int Id = view.getId();
switch (Id) {
case R.id.tv_first:
VideoLiveWallpaper.setToWallPaper(this);
break;
}
}
@OnCheckedChanged(R.id.cb_voice)
public void onCheck(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// 静音
VideoLiveWallpaper.voiceSilence(getApplicationContext());
} else {
VideoLiveWallpaper.voiceNormal(getApplicationContext());
}
}
}
| true |
9730e5fd51d496387d448242fd4c41afd1d7cb8e | Java | Xzhou556/amhs | /src/main/java/amhs/amhs/dao/RoleMenuDao.java | UTF-8 | 1,374 | 2.21875 | 2 | [] | no_license | package amhs.amhs.dao;
import amhs.amhs.entity.Role;
import amhs.amhs.entity.RoleMenu;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import javax.transaction.Transactional;
import java.util.List;
public interface RoleMenuDao extends JpaRepository<RoleMenu,Integer>, JpaSpecificationExecutor<RoleMenu> {
@Query(value="select * from t_role_menu where id = ?1",nativeQuery = true)
public RoleMenu findId(Integer id);
/**
* 设置权限 时需要 清空 之前的权限 。
* @param roleId
*/
@Modifying
@Transactional
@Query(value="delete from t_role_menu where role_id = ?1",nativeQuery = true)
public Integer deleteByRoleId(Integer roleId);
@Query(value="select * from t_role_menu where role_id = ?1",nativeQuery = true)
List<RoleMenu> findByRoleId(Integer roleId);
/**
* 根据 roleId menuId 查询 是否有内容
* @return
*/
@Query(value="select * from t_role_menu where role_id = ?1 and menu_id =?2",nativeQuery = true)
public RoleMenu findByRoleIdAndMenuId(Integer roleId,Integer menuId);
//根据role 拿 对应 的菜单
public List<RoleMenu> findByRole(Role role);
}
| true |
a773e566746d2b457f68edb455d5ed65f9f8af1f | Java | mcfloonyloo/EInvVatOutcoming | /src/by/gomelagro/outcoming/gui/frames/count/ILoadCount.java | UTF-8 | 283 | 1.640625 | 2 | [] | no_license | package by.gomelagro.outcoming.gui.frames.count;
public interface ILoadCount extends ICount {
public void addBaseCount();
public void addMissCount();
public void addErrorCount();
public int getBaseCount();
public int getMissCount();
public int getErrorCount();
}
| true |
4469f9e0a21c924c57e72987cef4887a5b947bcd | Java | Franklin2412/Laminin | /apkToolexipiry/working/libs/classes-dex2jar/com/payu/india/Model/StoredCard.java | UTF-8 | 5,360 | 2.09375 | 2 | [] | no_license | package com.payu.india.Model;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
public class StoredCard implements Parcelable {
public static final Creator<StoredCard> CREATOR;
private String cardBin;
private String cardBrand;
private String cardMode;
private String cardName;
private String cardToken;
private String cardType;
private String cvv;
private int enableOneClickPayment;
private String expiryMonth;
private String expiryYear;
private String isDomestic;
private Boolean isExpired;
private String issuingBank;
private String maskedCardNumber;
private String merchantHash;
private String nameOnCard;
private int oneTapCard;
static {
CREATOR = new Creator<StoredCard>() {
public StoredCard createFromParcel(Parcel parcel) {
return new StoredCard(parcel);
}
public StoredCard[] newArray(int i) {
return new StoredCard[i];
}
};
}
protected StoredCard(Parcel parcel) {
this.nameOnCard = parcel.readString();
this.cardName = parcel.readString();
this.expiryYear = parcel.readString();
this.expiryMonth = parcel.readString();
this.cardType = parcel.readString();
this.cardToken = parcel.readString();
this.cardMode = parcel.readString();
this.maskedCardNumber = parcel.readString();
this.cardBrand = parcel.readString();
this.cardBin = parcel.readString();
this.isDomestic = parcel.readString();
this.cvv = parcel.readString();
this.issuingBank = parcel.readString();
this.enableOneClickPayment = parcel.readInt();
this.oneTapCard = parcel.readInt();
this.merchantHash = parcel.readString();
}
public int describeContents() {
return 0;
}
public String getCardBin() {
return this.cardBin;
}
public String getCardBrand() {
return this.cardBrand;
}
public String getCardMode() {
return this.cardMode;
}
public String getCardName() {
return this.cardName;
}
public String getCardToken() {
return this.cardToken;
}
public String getCardType() {
return this.cardType;
}
public String getCvv() {
return this.cvv;
}
public int getEnableOneClickPayment() {
return this.enableOneClickPayment;
}
public String getExpiryMonth() {
return this.expiryMonth;
}
public String getExpiryYear() {
return this.expiryYear;
}
public String getIsDomestic() {
return this.isDomestic;
}
public Boolean getIsExpired() {
return this.isExpired;
}
public String getIssuingBank() {
return this.issuingBank;
}
public String getMaskedCardNumber() {
return this.maskedCardNumber;
}
public String getMerchantHash() {
return this.merchantHash;
}
public String getNameOnCard() {
return this.nameOnCard;
}
public int getOneTapCard() {
return this.oneTapCard;
}
public void setCardBin(String str) {
this.cardBin = str;
}
public void setCardBrand(String str) {
this.cardBrand = str;
}
public void setCardMode(String str) {
this.cardMode = str;
}
public void setCardName(String str) {
this.cardName = str;
}
public void setCardToken(String str) {
this.cardToken = str;
}
public void setCardType(String str) {
this.cardType = str;
}
public void setCvv(String str) {
this.cvv = str;
}
public void setEnableOneClickPayment(int i) {
this.enableOneClickPayment = i;
}
public void setExpiryMonth(String str) {
this.expiryMonth = str;
}
public void setExpiryYear(String str) {
this.expiryYear = str;
}
public void setIsDomestic(String str) {
this.isDomestic = str;
}
public void setIsExpired(Boolean bool) {
this.isExpired = bool;
}
public void setIssuingBank(String str) {
this.issuingBank = str;
}
public void setMaskedCardNumber(String str) {
this.maskedCardNumber = str;
}
public void setMerchantHash(String str) {
this.merchantHash = str;
}
public void setNameOnCard(String str) {
this.nameOnCard = str;
}
public void setOneTapCard(int i) {
this.oneTapCard = i;
}
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(this.nameOnCard);
parcel.writeString(this.cardName);
parcel.writeString(this.expiryYear);
parcel.writeString(this.expiryMonth);
parcel.writeString(this.cardType);
parcel.writeString(this.cardToken);
parcel.writeString(this.cardMode);
parcel.writeString(this.maskedCardNumber);
parcel.writeString(this.cardBrand);
parcel.writeString(this.cardBin);
parcel.writeString(this.isDomestic);
parcel.writeString(this.cvv);
parcel.writeString(this.issuingBank);
parcel.writeInt(this.enableOneClickPayment);
parcel.writeInt(this.oneTapCard);
parcel.writeString(this.merchantHash);
}
}
| true |
77787837e53d44d03731bdb819ee5f2e3a307796 | Java | KnnethKong/BaseMvp | /app/src/main/java/com/base/welcome/WelcomeActivity.java | UTF-8 | 1,804 | 2.140625 | 2 | [] | no_license | package com.base.welcome;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import com.base.mvp.R;
/**
* Created by KXF on 2018/5/20.
*/
public class WelcomeActivity extends FragmentActivity {
private ViewPager vp;
private int[] layouts = {
R.layout.vp_one,
R.layout.vp_two,
R.layout.vp_three};
private WelcomePagerTransformer transformer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome_layout);
vp = (ViewPager) findViewById(R.id.welcome_vp);
WelcomePagerAdapter adapter = new WelcomePagerAdapter(getSupportFragmentManager());
System.out.println("offset:" + vp.getOffscreenPageLimit());
vp.setOffscreenPageLimit(3);
vp.setAdapter(adapter);
transformer = new WelcomePagerTransformer();
vp.setPageTransformer(true, transformer);
vp.setOnPageChangeListener(transformer);
}
class WelcomePagerAdapter extends FragmentPagerAdapter {
public WelcomePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment f = new TranslateFragment();
Bundle bundle = new Bundle();
bundle.putInt("layoutId", layouts[position]);
bundle.putInt("pageIndex", position);
f.setArguments(bundle);
return f;
}
@Override
public int getCount() {
return layouts.length;
}
}
}
| true |
c6f73cd37d87a38957398d7518c0a071c310a330 | Java | favorit72/appium-androidTests | /src/test/java/javaTests/pageObjects/DemoPage.java | UTF-8 | 634 | 1.84375 | 2 | [] | no_license | package javaTests.pageObjects;
import helpers.DriverWait;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.pagefactory.AndroidFindBy;
public class DemoPage extends DriverWait {
public DemoPage(AndroidDriver androidDriver) {
super(androidDriver);
}
@AndroidFindBy(id = "com.XXX.client:id/btn_demo")
public MobileElement demoModeBtn;
@AndroidFindBy(id = "com.XXX.client:id/demo_close")
public MobileElement closeDemoHouseBtn;
@AndroidFindBy(id = "com.XXX.client:id/demo_header")
public MobileElement demoHouseName;
}
| true |
a829e6bc1b024c1c50e02baf8c503de2e6fd9dc3 | Java | fanok1/AudioBooks | /app/src/main/java/com/fanok/audiobooks/interface_pacatge/books/GenreModel.java | UTF-8 | 263 | 1.898438 | 2 | [] | no_license | package com.fanok.audiobooks.interface_pacatge.books;
import com.fanok.audiobooks.pojo.GenrePOJO;
import java.util.ArrayList;
import io.reactivex.Observable;
public interface GenreModel {
Observable<ArrayList<GenrePOJO>> getBooks(String url, int page);
}
| true |
0947112cd810a8cc61ec33e3073ae1a2cac794a8 | Java | Yahayawebmaster/StatusSaver-1 | /app/src/main/java/com/collabcreation/statussaver/Activity/InstaStory.java | UTF-8 | 1,412 | 2.078125 | 2 | [] | no_license | package com.collabcreation.statussaver.Activity;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.collabcreation.statussaver.Adapter.FollowersAdapter;
import com.collabcreation.statussaver.R;
import java.util.concurrent.ExecutionException;
public class InstaStory extends AppCompatActivity {
Toolbar toolbar;
RecyclerView accounts;
FollowersAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insta_story);
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Instagram Story");
setSupportActionBar(toolbar);
accounts = findViewById(R.id.accounts);
try {
adapter = new FollowersAdapter(getApplicationContext());
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
accounts.setHasFixedSize(true);
accounts.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
accounts.setAdapter(adapter);
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
}
| true |
1c3c8708d713bf10e66215046f5b85af823d99b0 | Java | brunoarakaki/mensageiro-p2p | /app/src/main/java/com/poli/usp/whatsp2p/data/local/Contact.java | UTF-8 | 2,628 | 2.265625 | 2 | [
"MIT"
] | permissive | package com.poli.usp.whatsp2p.data.local;
import android.content.Context;
import com.poli.usp.whatsp2p.utils.exceptions.ContactNotFoundException;
import com.poli.tcc.dht.DHT;
import java.io.IOException;
import java.io.Serializable;
import java.security.PublicKey;
/**
* Created by Bruno on 14-Aug-17.
*/
public class Contact implements Serializable {
static final long serialVersionUID = 504;
private String id;
private String name;
private String ip;
private int port;
private byte[] signPublicKeyEncoded;
private byte[] chatPublicKeyRingEncoded;
private boolean trust;
public Contact(String id) {
super();
this.id = id;
}
public Contact(String id, String name) {
super();
this.id = id;
this.name = name;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getIp() { return ip; }
public void setIp(String ip) { this.ip = ip; }
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public byte[] getSignPublicKeyEncoded() {
return signPublicKeyEncoded;
}
public void setSignPublicKeyEncoded(byte[] signPublicKeyEncoded) {
this.signPublicKeyEncoded = signPublicKeyEncoded;
}
public byte[] getChatPublicKeyRingEncoded() {
return chatPublicKeyRingEncoded;
}
public void setChatPublicKeyRingEncoded(byte[] chatPublicKeyRingEncoded) {
this.chatPublicKeyRingEncoded = chatPublicKeyRingEncoded;
}
public boolean isTrusted() {
return trust;
}
public void setTrust(boolean trust) {
this.trust = trust;
}
public void save(Context context) {
ContactDatabaseHelper dbHelper = new ContactDatabaseHelper(context);
dbHelper.update(this);
}
public void updateChatPublicKey(Context context) throws ContactNotFoundException {
try {
final PublicKey signPublicKey = (PublicKey) DHT.get(this.getId());
if (signPublicKey == null) throw new ContactNotFoundException();
final byte[] chatPublicKeyRingEncoded = (byte[]) DHT.getProtected("chatPublicKey", signPublicKey);
this.setChatPublicKeyRingEncoded(chatPublicKeyRingEncoded);
this.save(context);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
| true |
cee45d5145b2cf5b262fc6ab7d0182fc96cd8d62 | Java | livinglh/leetcode_record | /src/笔试题/网易8_8/Main3.java | UTF-8 | 2,225 | 3.640625 | 4 | [] | no_license | package 笔试题.网易8_8;
import java.util.Scanner;
/*
给了 n 个物品和它对应的价值。可以舍弃一部分物品,要两个人平分这些物品(数量可以不一样,价值总和要一样),问最少舍弃多少价值。
*/
public class Main3 {
static int min = Integer.MAX_VALUE;
static int sum = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
int n = sc.nextInt();
int[] nums = new int[n];
for (int j = 0; j < n; j++) {
nums[j] = sc.nextInt();
sum += nums[j];
}
dfs(nums, 0, 0, 0);
System.out.println(min);
}
}
public static void dfs(int[] nums, int index, int ans1, int ans2){
if(index == nums.length){
if(ans1 == ans2){
min = Math.min(min, sum - 2 * ans1);
}
return;
}
int val = nums[index];
// 丢弃
dfs(nums, index+1, ans1, ans2);
// 给第一位
dfs(nums, index+1, ans1+val, ans2);
// 给第二位
dfs(nums, index+1, ans1, ans2+val);
}
// 背包解法
public static void main2(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T -- > 0) {
sum = 0;
int n = sc.nextInt();
int[] nums = new int[n];
for (int j = 0; j < n; j++) {
nums[j] = sc.nextInt();
sum += nums[j];
}
boolean[] dp = new boolean[sum+1];
dp[0] = true;
for (int i = 0; i < n; i++) {
for (int j = sum; j >= nums[i] ; j--) {
dp[j] = dp[j] || dp[j-nums[i]];
}
}
int ans = sum;
for (int i = sum; i >= 0; i--) {
if(i % 2 != 0){
continue;
}
if(dp[i] && dp[i/2]){
ans = sum - i;
break;
}
}
System.out.println(ans);
}
}
}
| true |
0f751ed3e816640898dfa201f9e1006fb1752071 | Java | spartan2015/jpajsf | /proiectCap2/src/proiectCap2/Main.java | UTF-8 | 495 | 2.640625 | 3 | [] | no_license | package proiectCap2;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//1 catalog
Catalog catalog = new Catalog(1, "Catalog 2011");
//2produse
Categorie categorie1 = new Categorie(1, "Software", null);
Categorie categorie2 =new Categorie(2, "Hardware", null);
catalog.adaugaCategorie(categorie1);
catalog.adaugaCategorie(categorie2);
//4subcategorii
Categorie categorie11 = new Categorie(11, "Office", categorie1);
}
}
| true |
62fb0cc2216b0beaa963b148926c39664754bd04 | Java | tss0823/mnote | /mnote-service/src/main/java/com/loong/mnote/service/SubPubMessageConsumeService.java | UTF-8 | 1,087 | 1.984375 | 2 | [] | no_license | package com.loong.mnote.service;
import com.loong.mnote.common.constants.SubPubConstants;
import com.loong.mnote.service.component.AuthComponent;
import com.loong.mnote.service.component.SystemConfigComponent;
import com.loong.mnote.service.component.redis.SubPubMessage;
import com.loong.mnote.service.component.redis.SubPubMessageConsume;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author: sam
* @date: 2019-02-01 20:05
*/
@Service
public class SubPubMessageConsumeService implements SubPubMessageConsume {
@Autowired
private SystemConfigComponent systemConfigComponent;
@Autowired
private AuthComponent authComponent;
@Override
public void consume(SubPubMessage subPubMessage) {
if(!systemConfigComponent.getAppName().equals(subPubMessage.getAppName())){
return;
}
if(StringUtils.equals(SubPubConstants.AUTH_DATA,subPubMessage.getKey())){
authComponent.initData();
}
}
}
| true |
7649b54b893e84c9748d7290540686faae033b07 | Java | luoxiao5566/basic-api-implementation | /src/test/java/com/thoughtworks/rslist/UserControllerTest.java | UTF-8 | 6,223 | 2.171875 | 2 | [] | no_license | package com.thoughtworks.rslist;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.thoughtworks.rslist.domain.User;
import com.thoughtworks.rslist.po.UserPo;
import com.thoughtworks.rslist.repository.UserRepository;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import javax.persistence.OrderBy;
import java.util.List;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@SpringBootTest
@AutoConfigureMockMvc
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class UserControllerTest {
@Autowired
MockMvc mockMvc;
@Autowired
UserRepository userRepository;
@Test
@Order(1)
public void should_register_user() throws Exception {
User user = new User("idolice", "male", 19, "a@b.com", "18888888888");
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(user);
mockMvc.perform(post("/user").content(jsonString).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
List<UserPo> all = userRepository.findAll();
assertEquals(1, all.size());
assertEquals("idolice", all.get(0).getName());
assertEquals("a@b.com", all.get(0).getEmail());
/*mockMvc.perform(get("/user"))
.andExpect(jsonPath("$",hasSize(1)))
.andExpect(jsonPath("$[0].name",is("xyxia")))
.andExpect(jsonPath("$[0].gender",is("male")))
.andExpect(jsonPath("$[0].age",is(19)))
.andExpect(jsonPath("$[0].email",is("a@b.com")))
.andExpect(jsonPath("$[0].phone",is("18888888888")))
.andExpect(status().isOk());*/
}
@Test
@Order(2)
public void name_should_less_than_8() throws Exception {
User user = new User("xyxiaxxxx", "male", 19, "a@b.com", "18888888888");
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(user);
mockMvc.perform(post("/user").content(jsonString).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
}
@Test
@Order(3)
public void age_should_between_18_and_100() throws Exception {
User user = new User("xyxia", "male", 15, "a@b.com", "18888888888");
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(user);
mockMvc.perform(post("/user").content(jsonString).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
}
@Test
@Order(5)
public void email_should_suit_format() throws Exception {
User user = new User("xyxia", "male", 19, "ab.com", "18888888888");
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(user);
mockMvc.perform(post("/user").content(jsonString).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
}
@Test
@Order(5)
public void phone_should_suit_format() throws Exception {
User user = new User("xyxia", "male", 19, "a@b.com", "188888888881");
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(user);
mockMvc.perform(post("/user").content(jsonString).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
}
@Test
public void should_throw_user_method_argument_not_valid_exception() throws Exception {
User user = new User("xyxiaxxxxxx", "male", 19, "a@b.com", "18888888888");
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(user);
mockMvc.perform(post("/user").content(jsonString).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.error", is("invalid user")));
}
@Test
public void should_register_user_by_id() throws Exception {
User user = new User("idolice", "male", 19, "a@b.com", "18888888888");
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(user);
mockMvc.perform(post("/user").content(jsonString).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
mockMvc.perform(get("/user?id=1"))
.andExpect(jsonPath("$.name",is("idolice")))
.andExpect(jsonPath("$.age",is(19)))
.andExpect(jsonPath("$.email",is("a@b.com")))
.andExpect(status().isOk());
}
@Test
public void should_delete_user_by_id() throws Exception {
User user = new User("idolice", "male", 19, "a@b.com", "18888888888");
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(user);
mockMvc.perform(post("/user").content(jsonString).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
mockMvc.perform(delete("/user/delete?id=1"))
.andExpect(status().isOk());
mockMvc.perform(get("/user?id=1"))
.andExpect(status().isBadRequest());
}
}
| true |
5a46179042dddd0c5c17aa977b04deb5cfa5fbd5 | Java | NamanAgg/pep_foundation | /src/LEVEL_UP/advanceLinkedList/mergeSort.java | UTF-8 | 2,545 | 3.984375 | 4 | [] | no_license | //*******Mergesort Linkedlist
// Given the head of a linked list, return the list after sorting it in increasing order.
// Time Complexity : O(nlogn)
// Space Complexity : constant space
// Input Format
// 1->7->2->6->3->5->4->null
// Output Format
// 1->2->3->4->5->6->7->null
// Constraints
// 0 <= N <= 10^6
// Sample Input
// 4
// 0
// 6
// 7
// 5
// Sample Output
// 0 5 6 7
package LEVEL_UP.advanceLinkedList;
import java.util.*;
public class mergeSort {
public static Scanner scn = new Scanner(System.in);
public static class ListNode {
int val = 0;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public static ListNode midNode(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode slow = head, fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null || l2 == null)
return l1 != null ? l1 : l2;
ListNode dummy = new ListNode(-1);
ListNode prev = dummy, c1 = l1, c2 = l2;
while (c1 != null && c2 != null) {
if (c1.val <= c2.val) {
prev.next = c1;
c1 = c1.next;
} else {
prev.next = c2;
c2 = c2.next;
}
prev = prev.next;
}
prev.next = c1 != null ? c1 : c2;
return dummy.next;
}
public static ListNode mergeSort(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode mid = midNode(head);
ListNode nHead = mid.next;
mid.next = null;
return mergeTwoLists(mergeSort(head), mergeSort(nHead));
}
public static void printList(ListNode node) {
while (node != null) {
System.out.print(node.val + " ");
node = node.next;
}
}
public static ListNode createList(int n) {
ListNode dummy = new ListNode(-1);
ListNode prev = dummy;
while (n-- > 0) {
prev.next = new ListNode(scn.nextInt());
prev = prev.next;
}
return dummy.next;
}
public static void main(String[] args) {
int n = scn.nextInt();
ListNode h1 = createList(n);
ListNode head = mergeSort(h1);
printList(head);
}
}
| true |
847e32295ab6937b02d0e7b2b1365004710aad62 | Java | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/arc085/A/1765519.java | UTF-8 | 471 | 3.03125 | 3 | [] | no_license | import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
double x = 0;
int y = 0;
if(n-m>0){
y = (n-m)*100;
}
double k = Math.pow(2, m);
double p,q;
p=1-1/k;
for(int i=1; i<3500000; i++){
q=Math.pow(p, i-1);
x += (y + 1900*m)*i*q/(double)k;
}
System.out.println(Math.round(x));
sc.close();
}
} | true |
08e627561d533a470e6a03205edf9f5f53fe6ef8 | Java | BGCX261/zpi-4-svn-to-git | /trunk/rozpoznawanie_wzorca/src/uslugi/AuthorizationService.java | UTF-8 | 2,525 | 2.71875 | 3 | [] | no_license | package uslugi;
import java.util.ArrayList;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import autoryzacja.AuthorizationMethod;
import baza_danych.model.Uzytkownik;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import czytnik.DaneCzytnika;
/**
* Serwis dokonujacy autoryzacji
*
* @author elistan
*
*/
public class AuthorizationService {
ArrayList<AuthorizationMethod> methods = new ArrayList<AuthorizationMethod>();
private final Logger LOGGER;
private String ostatniKomunikat;
/**
* Inicjuje metodami autoryzacji
*
* @param methods
* Rozne metody autoryzacji
*/
@Inject
public AuthorizationService(Set<AuthorizationMethod> methods,
@Named("SystemAccessLogger") Logger systemAccessLogger) {
for (AuthorizationMethod am : methods) {
this.methods.add(am);
}
this.LOGGER = systemAccessLogger;
}
/**
* Przekazuje dane do metod autoryzacji
*
* @param czytnik
* dane czytnika
* @param hash
* Hash uzytkownika
* @return Wynik autoryzacji - negatywny gdy chociaz jedna metoda nie dopusci
* autoryzacji.
*/
public boolean autoryzuj(DaneCzytnika czytnik, Uzytkownik hash) {
boolean result = true;
AuthorizationMethod failingMethod = null;
for (AuthorizationMethod method : methods) {
boolean before = result;
result = result && method.verify(hash, czytnik);
if (before != result) {
failingMethod = method;
}
}
logAccess(czytnik, hash, failingMethod);
return result;
}
private void logAccess(DaneCzytnika czytnik, Uzytkownik uzytkownik,
AuthorizationMethod failingMethod) {
Object[] params = new Object[2];
LogRecord logRec = przygotujKomunikat(failingMethod);
params[0] = uzytkownik.getId();
params[1] = czytnik.getId();
logRec.setParameters(params);
LOGGER.log(logRec);
}
private LogRecord przygotujKomunikat(AuthorizationMethod failingMethod) {
LogRecord logRec;
Level logLevel;
if (failingMethod != null) {
ostatniKomunikat = "ACCESS DENIED; CAUSE: "
+ failingMethod.getErrorMessage();
logLevel = Level.WARNING;
} else {
ostatniKomunikat = "ACCESS GRANTED;";
logLevel = Level.INFO;
}
logRec = new LogRecord(logLevel, ostatniKomunikat);
return logRec;
}
public String pobierzOstatniKomunikat() {
return ostatniKomunikat;
}
}
| true |
e12d664f6e5bbf9ebd0573d328b13b95e59eb907 | Java | kyungsubbb/Coding-Test | /Baekjoon/Java/1759.java | UTF-8 | 1,509 | 2.9375 | 3 | [] | no_license | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class BOJ_1759 {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static int L, C;
static String[] output, arr;
static boolean[] isSelected;
public static void main(String[] args) throws Exception{
st = new StringTokenizer(in.readLine(), " ");
L = Integer.parseInt(st.nextToken());
C = Integer.parseInt(st.nextToken());
output = new String[L];
arr = new String[C];
isSelected = new boolean[C];
st = new StringTokenizer(in.readLine(), " ");
for (int i = 0; i < arr.length; i++) {
arr[i] = st.nextToken();
}
Arrays.sort(arr);
subSet(0, 0);
}
private static void subSet(int idx, int start) {
if(idx == L) {
boolean flag = false;
int mo = 0;
int ja = 0;
for (int i = 0; i < output.length; i++) {
if(output[i].equals("a") || output[i].equals("e") || output[i].equals("i") || output[i].equals("o") || output[i].equals("u")) {
mo ++;
}else {
ja ++;
}
}
if(mo >= 1 && ja >= 2) {
flag = true;
}
if(flag) {
String res = "";
for (int i = 0; i < output.length; i++) {
res += output[i];
}
System.out.println(res);
}
return;
}
for (int i = start; i < arr.length; i++) {
if(!isSelected[i]) {
output[idx] = arr[i];
isSelected[i] = true;
subSet(idx+1, i+1);
isSelected[i] = false;
}
}
}
}
| true |
84d1cf28b67cfc12b6023c8d2e628347b3327c7c | Java | przsul/Reflections-Java | /src/main/java/pl/edu/utp/wtie/ControlCreator.java | UTF-8 | 3,084 | 2.625 | 3 | [] | no_license | package pl.edu.utp.wtie;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javafx.scene.Node;
import javafx.scene.control.Control;
import pl.edu.utp.wtie.validation.Validator;
public class ControlCreator {
private Class<?> reflectClass;
private Object object;
private List<Field> classFields;
private VFieldControl vFieldControl;
private FieldControl fieldControl;
private Map<VFieldControl, List<Validator>> controlsValidators = new LinkedHashMap<>();
private List<Node> nodes = new ArrayList<>();
private Map<Control, Field> map = new LinkedHashMap<>();
public ControlCreator(Class<?> reflectClass, Object object, List<Field> classFields) {
this.reflectClass = reflectClass;
this.object = object;
this.classFields = classFields;
}
public List<Node> getNodes() {
return nodes;
}
public Map<VFieldControl, List<Validator>> getControlsValidators() {
return controlsValidators;
}
public Map<Control, Field> getMap() {
return map;
}
private List<Validator> reflectValidator(Field classField, Annotation[] annotations) {
List<Object> objects = new ArrayList<>();
List<Validator> validators = new ArrayList<>();
for(Annotation annotation : annotations) {
try {
Class<?> reflectValidator = Class.forName("pl.edu.utp.wtie.validation."
+ annotation.annotationType().getSimpleName() + "Validator");
Constructor<?> reflectConstructor = reflectValidator.getConstructor(Field.class);
objects.add(reflectConstructor.newInstance(classField));
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException
| IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
objects.forEach(object -> validators.add((Validator)object));
return validators;
}
public void createControls() {
classFields.forEach(classField -> {
// PropertyDescriptor for access to getters and setters
PropertyDescriptor pd = null;
try {
pd = new PropertyDescriptor(classField.getName(), reflectClass);
} catch (IntrospectionException e) {
e.printStackTrace();
}
Annotation[] annotations = classField.getAnnotations();
// Create text input without validation
if (annotations.length == 0) {
fieldControl = new FieldControl(5, classField, object, pd);
nodes.add(fieldControl);
map.putAll(fieldControl.getMap());
// Create text input with validation
} else {
vFieldControl = new VFieldControl(5, classField, object, pd);
List<Validator> v = reflectValidator(classField, annotations);
controlsValidators.put(vFieldControl, v);
vFieldControl.registerValidator(v);
nodes.add(vFieldControl);
map.putAll(vFieldControl.getMap());
}
});
}
}
| true |
c4de3a35c8b8c492afcae8f93a8d9d34b29bdb6e | Java | Corginator4000/FleshCraft | /src/main/java/com/Corginator4000/fleshcraft/library/registration/ItemDeferredRegister.java | UTF-8 | 1,689 | 2.328125 | 2 | [] | no_license | package com.Corginator4000.fleshcraft.library.registration;
import com.Corginator4000.fleshcraft.library.mantle.registration.object.ItemObject;
import net.minecraft.item.Item;
import net.minecraft.util.IStringSerializable;
import net.minecraftforge.registries.ForgeRegistries;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
public class ItemDeferredRegister extends DeferredRegisterWrapper<Item> {
public ItemDeferredRegister(String modID) {
super(ForgeRegistries.ITEMS, modID);
}
public <I extends Item> ItemObject<I> register(String name, Supplier<? extends I> sup) {
return new ItemObject(this.register.register(name, sup));
}
public ItemObject<Item> register(String name, Item.Properties props) {
return this.register(name, () -> {
return new Item(props);
});
}
/*public <T extends Enum<T> & IStringSerializable, I extends Item> EnumObject<T, I> registerEnum(T[] values, String name, Function<T, ? extends I> mapper) {
return registerEnum((Enum[])values, (String)name, (BiFunction)((fullName, type) -> {
return this.register(fullName, () -> {
return (Item)mapper.apply(type);
});
}));
}*/
/*public <T extends Enum<T> & IStringSerializable, I extends Item> EnumObject<T, I> registerEnum(String name, T[] values, Function<T, ? extends I> mapper) {
return registerEnum((String)name, (Enum[])values, (BiFunction)((fullName, type) -> {
return this.register(fullName, () -> {
return (Item)mapper.apply(type);
});
}));
}*/
}
| true |
164bea3a51f4b9f1555db2520a97e02e5b188b1f | Java | Krelix/spring_file_injector | /src/main/java/com/github/krelix/storage/StorageService.java | UTF-8 | 3,407 | 2.40625 | 2 | [] | no_license | package com.github.krelix.storage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
* Created by brizarda on 21/01/2017.
*/
public class StorageService {
private static final String STORAGE_URL = "http://127.0.0.1:8080/upload";
private static final Logger LOGGER = LoggerFactory.getLogger(StorageService.class);
public void uploadFile(File fileToUpload, RestTemplate restTemplate) {
HttpHeaders mainHeader = new HttpHeaders();
mainHeader.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpHeaders fileHeaders = new HttpHeaders();
fileHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
HttpEntity<FileSystemResource> fileEntity = new HttpEntity<>(new FileSystemResource(fileToUpload), fileHeaders);
MultiValueMap<String, Object> multiPartRequest = new LinkedMultiValueMap<>();
multiPartRequest.add("file", fileEntity);
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(multiPartRequest, mainHeader);
LOGGER.info("Obtained result from rest call : {}",
restTemplate.postForEntity(STORAGE_URL, entity, FileURL.class).toString());
}
// TODO : async upload to separate them in multiple threads ?
public void uploadFiles(Flux<File> files, RestTemplate restTemplate) {
final Scheduler myScheduler = Schedulers.newParallel(4, Executors.defaultThreadFactory());
CountDownLatch latch = new CountDownLatch(200);
files.subscribeOn(myScheduler)
.parallel()
.doAfterTerminate(myScheduler::dispose)
.subscribe((f) -> {
RestTemplate myRestTemplate = new RestTemplate();
HttpHeaders mainHeader = new HttpHeaders();
mainHeader.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpHeaders fileHeaders = new HttpHeaders();
fileHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
HttpEntity<FileSystemResource> fileEntity = new HttpEntity<>(new FileSystemResource(f), fileHeaders);
MultiValueMap<String, Object> multiPartRequest = new LinkedMultiValueMap<>();
multiPartRequest.add("file", fileEntity);
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(multiPartRequest, mainHeader);
LOGGER.info("Obtained result from rest call : {}",
myRestTemplate.postForEntity(STORAGE_URL, entity, FileURL.class).toString());
latch.countDown();
});
}
}
| true |
12c9207e9d5cf1741eee577791ddb56a81777898 | Java | katejay/Selenium-Exercise | /EndToEnd/EndToEnd + Cucumber/EndToEnd/src/test/java/stepDefinations/StepDefination.java | UTF-8 | 1,532 | 2.390625 | 2 | [] | no_license | package stepDefinations;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
import endtoend.pageobject.HomePage;
import endtoend.pageobject.LoginPage;
import endtoend.resources.Browser;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.And;
public class StepDefination extends Browser {
@Given("^Initialize the browser with chrome$")
public void initialize_the_browser_with_chrome() throws Throwable {
driver = initializeDriver();
}
@When("^User login into site with (.+) and (.+)$")
public void user_login_into_site_with_and(String username, String password) throws Throwable {
LoginPage lp = new LoginPage(driver);
lp.getUsername().sendKeys(username);
lp.getPassword().sendKeys(password);
lp.submit().click();
}
@Then("^Validate login$")
public void validate_login() throws Throwable {
LoginPage lp = new LoginPage(driver);
//System.out.println(lp.getProfile().isDisplayed()); //Provide valid details and uncomment this line
System.out.println("Provide valid info");
}
@And("^Navigate to \"([^\"]*)\" site$")
public void navigate_to_something_site(String strArg1) throws Throwable {
driver.get(strArg1);
}
@And("^Click on Sign In button$")
public void click_on_sign_in_button() throws Throwable {
HomePage hp = new HomePage(driver);
hp.signIn().click();
}
@And("^Close browser$")
public void close_browser() throws Throwable {
driver.close();
}
} | true |
0c32863e5822adbc6238a08b992d6a169902c4d0 | Java | bhumikamarolia/Algo_dsa_cc | /BitManipulation/HammingDistance.java | UTF-8 | 630 | 3.75 | 4 | [] | no_license | package demo;
/*
* The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, return the Hamming distance between them.
Example 1:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
*/
public class HammingDistance {
public int hammingDistance(int x, int y) {
int a=x^y;
int count=0;
while(a>0)
{
count+=a&1;
a>>=1;
}
return count;
}
}
| true |
d7c4858e3f5b8821d8a99df35d89efddf9fe4053 | Java | yuanchengprojectteam/mailMgr | /mailMgr/src/main/java/com/yc/mailMgr/dao/OrderBy.java | UTF-8 | 955 | 1.757813 | 2 | [] | no_license | package com.yc.mailMgr.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.yc.mailMgr.bean.Goods;
import com.yc.mailMgr.bean.OrderdetailsOderBy;
public interface OrderBy {
@Select("select count(gid)as gnum , gid from orderdetail , goods where orderdetail.gid = goods.id and goods.tid = ${val} GROUP BY gid ORDER BY gnum DESC")
List<OrderdetailsOderBy> selectOrderBy(@Param("val")int val);
//
@Select("select * from goods where tid=${val} ORDER BY price")
List<Goods> selectPriceOrderBy(@Param("val")int val);
@Select("select * from goods where tid=${val} ORDER BY commnum DESC")
List<Goods> selectcommentOrderBy(@Param("val")int val);
@Select("select * from goods where tid=${tid} and price > ${low} and price < ${top} ORDER BY price")
List<Goods> selectScopeOrderBy(@Param("tid")int tid,@Param("low")int low,@Param("top")int top);
}
| true |
4b2b2a29452747c9e172a67183fc2c73fad09a11 | Java | nOy39/Address-Book-v2.0 | /src/main/java/dao/ConnectDB.java | UTF-8 | 513 | 2.5 | 2 | [] | no_license | package dao;
import helpers.Constant;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectDB {
public Connection connect() {
Connection connection = null;
try {
connection = DriverManager.getConnection(Constant.getURL(),
Constant.getUSER(),
Constant.getPASSWORD());
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
| true |
3edc2ef44cd5c359f27e492dc45d3ebf3017f9d9 | Java | LemonTea387/Chat-Client | /src/client/network/ClientConnection.java | UTF-8 | 4,100 | 2.734375 | 3 | [] | no_license | package client.network;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import client.gui.GuiClient;
import client.listeners.MessageListener;
import client.listeners.OnlineListener;
import client.network.state.ConnectionState;
/**
*
* @author LemonTea387
*
*/
public class ClientConnection {
private String url;
int port;
private Socket connectionSocket;
private InputStream input;
private OutputStream output;
private BufferedReader br;
private BufferedWriter bw;
private List<MessageListener> msgListeners = new ArrayList<MessageListener>();
private List<OnlineListener> onListeners = new ArrayList<OnlineListener>();
ConnectionState state;
GuiClient guiClient;
public ClientConnection(String url, int port) {
this.url = url;
this.port = port;
}
/**
* Specialize method to login with supplied credentials
*
* @param username Supply username credential
* @param password Supply password credential
*/
// Login with credentials provided
public boolean login(String username, String password) {
String response = "";
try {
send("login " + username + " " + password);
String input = br.readLine();
if (input != null) {
response += input;
}
System.out.println("response : " + response);
} catch (IOException e) {
e.printStackTrace();
}
if ("Success".equalsIgnoreCase(response)) {
return true;
}
return false;
}
/**
* Called when program is about to exit, closes the client connection
*
* @throws IOException When streams and socket failed to close()
*
*/
// Handler for when connection should be closed
public void handleExit() throws IOException {
send("quit");
input.close();
output.close();
connectionSocket.close();
}
/**
*
* @return Socket
*/
public Socket getSocket() {
return connectionSocket;
}
// Handles all the communication of client and server
private void handleCommunication() {
String input;
String[] tokens;
String cmd, attribute, content;
try {
while (!connectionSocket.isClosed() && (input = br.readLine().trim()) != null) {
tokens = input.split(" ", 3);
if (tokens.length == 3) {
cmd = tokens[0];
attribute = tokens[1];
content = tokens[2];
if ("message".equalsIgnoreCase(cmd))
handleReceiveMessage(attribute, content);
} else if ("Online".equalsIgnoreCase(tokens[0]) || "Offline".equalsIgnoreCase(tokens[0]))
handleOnlineStatus(tokens[1]);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void handleOnlineStatus(String username) {
}
// Handles every message received
private void handleReceiveMessage(String sender, String content) {
for (MessageListener listener : msgListeners) {
listener.onMessage(sender, content);
}
}
// Handles the initial connection to the server
public boolean handleConnection() {
try {
connectionSocket = new Socket(url, port);
input = connectionSocket.getInputStream();
output = connectionSocket.getOutputStream();
br = new BufferedReader(new InputStreamReader(input));
bw = new BufferedWriter(new OutputStreamWriter(output));
this.addMessageListener((sender, content) -> {
System.out.println(sender + content);
});
this.addOnlineListener(() -> {
});
return true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
// Writes a string to the output stream of clientSocket
private void send(String command) {
try {
bw.write((command + "\n").toCharArray());
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void addMessageListener(MessageListener listener) {
msgListeners.add(listener);
}
private void addOnlineListener(OnlineListener listener) {
onListeners.add(listener);
}
}
| true |
367a067f56bf7ae98e26e6ff630fb8ba330cc558 | Java | SchweitzerGAO/OlympicGames | /src/test/moduletest/StrategyTest.java | UTF-8 | 1,333 | 3.40625 | 3 | [] | no_license | package test.moduletest;
import com.team.olympics.athlete.Athlete;
import com.team.olympics.athlete.AmericanAthleteFactory;
import com.team.olympics.athlete.Sleep;
/**
* @author Wu Fei
* @description the test class for strategy pattern
* @date 2021/11/2
*/
public class StrategyTest {
public static void strategyTest(){
AmericanAthleteFactory americanAthleteFactory=new AmericanAthleteFactory();
Athlete americanAthlete= americanAthleteFactory.produce();
//use the strategy
americanAthlete.play();
//change the strategy
americanAthlete.setSkill(new Sleep());
//should output a different result
americanAthlete.play();
System.out.println("------------------------Strategy ends------------------------");
}
public static void main(String[] args) {
System.out.println("------------------------- Strategy ---------------------------");
System.out.println("AmericanAthleteFactory():A class extending AbstractAthleteFactory");
System.out.println("produce():Producing an athlete");
System.out.println("play():use the strategy");
System.out.println("setSkill():change the strategy");
System.out.println("-------------------------------------------------------------");
strategyTest();
}
}
| true |
4a0e1ab5c7595b83f0caa3ec54e891a2ce43cf86 | Java | BhavsarMeet/studentmanagingapp | /src/main/java/com/controller/student/AddStudentController.java | UTF-8 | 2,575 | 2.4375 | 2 | [] | no_license | package com.controller.student;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
import com.bean.student.StudentBean;
import com.dao.student.StudentDao;
import com.util.Validation;
/**
* Servlet implementation class AddStudentController
*/
public class AddStudentController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//info from jsp-->start
String sName=request.getParameter("txtStudentName");
String age=request.getParameter("txtStudentAge");
int sAge=0;
if(age.trim().length()>0 && age!=null)
sAge=Integer.parseInt(age);
String sMob=request.getParameter("txtStudentMob");
String sEmail=request.getParameter("txtStudentEmail");
String fid=request.getParameter("txtFacultyId");
int fId=0;
if(fid.trim().length()>0 && fid!=null)
fId=Integer.parseInt(fid);
//info from jsp-->end
boolean flag=true;
StudentBean sb=new StudentBean();
//validation to set student bean--->start
if(!new Validation().checkEmail(sEmail))
{
flag=false;
request.setAttribute("email","*Valid email Required");
}
else
{
sb.setsEmail(sEmail);
}
if(!(sAge>18))
{
flag=false;
request.setAttribute("age","*age must be greater than 18");
}
else
{
sb.setsAge(sAge);
}
if(!new Validation().checkMobile(sMob))
{
flag=false;
request.setAttribute("mobile","*Valid mobile number Required");
}
else
{
sb.setsMob(sMob);
}
if(!new Validation().checkName(sName))
{
flag=false;
request.setAttribute("name","*valid Name Required");
}
else
{
sb.setsName(sName);
}
if(!(fId>0))
{
flag=false;
request.setAttribute("faculty","*please select faculty name");
}
else
{
sb.setfId(fId);
}
//validation to set student bean--->end
//insertion in database
if(flag==true)
{
sb.setsMob("+91"+sMob);
boolean setStudent=new StudentDao().addStudent(sb);
if(setStudent)
{
response.sendRedirect("StudentListController");
}
}
else
{
request.setAttribute("sb", sb);
request.getRequestDispatcher("./student/StudentAdd.jsp").forward(request, response);
}
}
}
| true |
772fa21982fc3580145821c1342f93846419a888 | Java | Darshitkuwadia/CloudAPM | /apm/src/main/java/edu/sjsu/cmpe295/dto/ApplicationMetrics.java | UTF-8 | 15,812 | 2.203125 | 2 | [] | no_license | package edu.sjsu.cmpe295.dto;
import java.io.StringReader;
import javax.ws.rs.core.MultivaluedMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.codehaus.jettison.Node;
import org.json.JSONObject;
import org.json.XML;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;
public class ApplicationMetrics {
Client client = Client.create();
WebResource webResource;
ClientResponse response ;
String output = null ;
static String applicationID = "6087294";
static String xApiKey= "f09a3be01866a3be3c78e13f1cd5d172c1cb465a78c4b2e";
public String getApplicationIDs()
{
try {
webResource = client
.resource("https://api.newrelic.com/v2/applications.json");
response = webResource.accept("application/json")
.header("X-Api-Key", xApiKey)
.get(ClientResponse.class)
;
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
return output;
}
/*
*
* curl -X GET 'https://api.newrelic.com/v2/applications/${APPID}/metrics/data.xml' \
-H "X-Api-Key:${APIKEY}" -i \
-d 'names[]=Apdex&names[]=EndUser/Apdex&values[]=score&from=2014-01-01T00:00:00+00:00&to=2014-01-02T00:00:00+00:00&summarize=true'
*/
// summarize : false --> to get all the data
public String getApdexScore() {
try {
webResource = client
.resource("https://api.newrelic.com/v2/applications/"+ applicationID +"/metrics/data.xml");
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("names[]", "Apdex");
queryParams.add("names[]", "EndUser/Apdex");
// optional
/* queryParams.add("values[]", "score");
queryParams.add("from", "2015-01-01T00:00:00+00:00");
queryParams.add("to", "2016-01-02T00:00:00+00:00");
queryParams.add("summarize", "true");*/
response = webResource.queryParams(queryParams)
.accept("application/json","application/xml" )
.header("X-Api-Key", xApiKey)
.get(ClientResponse.class)
;
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
String jsonOutput= convertXmlToJson(output);
return jsonOutput;
}
public static int PRETTY_PRINT_INDENT_FACTOR = 4;
public String convertXmlToJson(String xmlString)
{
JSONObject xmlJSONObj = XML.toJSONObject(xmlString);
String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
System.out.println(jsonPrettyPrintString);
return jsonPrettyPrintString;
}
public String getAverageThroughputApp() {
try {
webResource = client
.resource("https://api.newrelic.com/v2/applications/"+applicationID+"/metrics/data.json");
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("names[]", "HttpDispatcher");
queryParams.add("values[]", "requests_per_minute");
// optional
/*
queryParams.add("from", "2015-01-01T00:00:00+00:00");
queryParams.add("to", "2016-01-02T00:00:00+00:00");
queryParams.add("summarize", "true");*/
response = webResource.queryParams(queryParams)
.accept("application/json","application/xml" )
.header("X-Api-Key", xApiKey)
.get(ClientResponse.class)
;
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
return output;
}
/**
*
* query params to be passed as parameters from and to
* @return
*
* The default time range for an API call is the last 30 minutes.
* To modify the time range, include both from= and to= values. For example:
*
*
*
*curl -X GET "https://api.newrelic.com/v2/applications/${APPID}/metrics/data.json" \
-H "X-Api-Key:${APIKEY}" -i \
-d 'names[]=Agent/MetricsReported/count&from=2014-08-11T14:42:00+00:00&to=2014-08-11T15:12:00+00:00'
*
*/
public String getTimeRange() {
try {
webResource = client
.resource("https://api.newrelic.com/v2/applications/"+applicationID+"/metrics/data.json");
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("names[]", "Agent/MetricsReported/count");
queryParams.add("from", "2015-04-01T00:00:00+00:00");
queryParams.add("to", "2015-04-13T00:00:00+00:00");
response = webResource.queryParams(queryParams)
.accept("application/json")
.header("X-Api-Key", xApiKey)
.get(ClientResponse.class)
;
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
return output;
}
/**
* Calculating average metric values (summarize)
*
*
* To prevent summarizing data, omit summarize in your API call.
* You do not need to specify &summarize=false.
* @return
*/
public String summarize() {
try {
webResource = client
.resource("https://api.newrelic.com/v2/applications/"+applicationID+"/metrics/data.json");
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("names[]", "Agent/MetricsReported/count");
queryParams.add("from", "2015-04-01T00:00:00+00:00");
queryParams.add("to", "2015-04-13T00:00:00+00:00");
queryParams.add("summarize","true");
response = webResource.queryParams(queryParams)
.accept("application/json")
.header("X-Api-Key", xApiKey)
.get(ClientResponse.class)
;
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
return output;
}
/**
*
* Application error rate
*
*
* Application Error Rate = 100 * Errors/all:error_count / (HttpDispatcher:call_count + OtherTransaction/all:call_count)
* @return
*/
public String getErrorRate() {
JSONObject json = new JSONObject(getCallCount());
System.out.println("-----------------------------");
int callCount =json.getJSONObject("metric_data_response").getJSONObject("metric_data").getJSONObject("metrics").getJSONObject("metric")
.getJSONObject("timeslices").getJSONObject("timeslice").getJSONObject("values").getInt("call_count")
;
JSONObject json1 = new JSONObject(getErrorCount());
System.out.println("-----------------------------");
int errorCount =json1.getJSONObject("metric_data_response").getJSONObject("metric_data").getJSONObject("metrics").getJSONObject("metric")
.getJSONObject("timeslices").getJSONObject("timeslice").getJSONObject("values").getInt("error_count")
;
JSONObject json2 = new JSONObject(getAverage());
System.out.println("-----------------------------");
int otherTrans =json2.getJSONObject("metric_data_response").getJSONObject("metric_data").getJSONObject("metrics").getJSONObject("metric")
.getJSONObject("timeslices").getJSONObject("timeslice").getJSONObject("values").getInt("call_count")
;
int applicationErrorRate = 100* errorCount/(callCount+otherTrans);
System.out.println(applicationErrorRate);
//String applicationErrorRate = 100*
JSONObject j = new JSONObject();
j.put("errorRate",applicationErrorRate);
return j.toString();
}
/**
*
* Error Count
*
* curl -X GET "https://api.newrelic.com/v2/applications/${APPID}/metrics/data.xml" \
-H "X-Api-Key:${APIKEY}" -i \
-d 'names[]=Errors/all&values[]=error_count&from=2014-04-01T00:00:00+00:00&to=2014-04-01T23:35:00+00:00&summarize=true'
*
*
* @return
*/
public String getErrorCount()
{
try {
webResource = client
.resource("https://api.newrelic.com/v2/applications/"+applicationID+"/metrics/data.xml");
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("names[]", "Errors/all");
queryParams.add("values[]", "error_count");
queryParams.add("from", "2015-01-01T00:00:00+00:00");
queryParams.add("to", "2015-04-13T00:00:00+00:00");
queryParams.add("summarize", "true");
response = webResource.queryParams(queryParams)
.accept("application/json","application/xml" )
.header("X-Api-Key", xApiKey)
.get(ClientResponse.class)
;
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
String jsonOutput= convertXmlToJson(output);
return jsonOutput;
}
/**
* Call Count
*
* curl -X GET "https://api.newrelic.com/v2/applications/${APPID}/metrics/data.xml" \
-H "X-Api-Key:${APIKEY}" -i \
-d 'names[]=HttpDispatcher&values[]=call_count&from=2014-04-01T00:00:00+00:00&to=2014-04-01T23:35:00+00:00&summarize=true'
*
*
* @return
*/
public String getCallCount()
{
try {
webResource = client
.resource("https://api.newrelic.com/v2/applications/"+applicationID+"/metrics/data.xml");
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("names[]", "HttpDispatcher");
queryParams.add("values[]", "call_count");
queryParams.add("from", "2015-01-01T00:00:00+00:00");
queryParams.add("to", "2015-04-13T00:00:00+00:00");
queryParams.add("summarize", "true");
response = webResource.queryParams(queryParams)
.accept("application/json","application/xml" )
.header("X-Api-Key", xApiKey)
.get(ClientResponse.class)
;
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
output = response.getEntity(String.class);
} catch (Exception e) {
e.printStackTrace();
}
String jsonOutput= convertXmlToJson(output);
return jsonOutput;
}
/**
* Average Value
*
* curl -X GET "https://api.newrelic.com/v2/applications/${APPID}/metrics/data.xml" \
-H "X-Api-Key:${APIKEY}" -i \
-d 'names[]=OtherTransaction/all&values[]=call_count&from=2014-04-01T00:00:00+00:00&to=2014-04-01T23:35:00+00:00&summarize=true'
*
* @return
*/
public String getAverage()
{
try {
webResource = client
.resource("https://api.newrelic.com/v2/applications/"+ applicationID+"/metrics/data.xml");
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("names[]", "OtherTransaction/all");
queryParams.add("values[]", "call_count");
queryParams.add("from", "2015-01-01T00:00:00+00:00");
queryParams.add("to", "2015-04-13T00:00:00+00:00");
queryParams.add("summarize", "true");
response = webResource.queryParams(queryParams)
.accept("application/json","application/xml" )
.header("X-Api-Key", xApiKey)
.get(ClientResponse.class)
;
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
String jsonOutput= convertXmlToJson(output);
return jsonOutput;
}
/**
* Average response time
*
* Application Average response time = HttpDispatcher:average_call_time
* + ((WebFrontend/Queue:call_count * WebFrontend/Queue:average_response_time)/ HttpDispatcher:call_count)
*
*
*/
public String getAverageResponseTime() {
return null;
}
public String gethttpDisp() {
try {
webResource = client
.resource("https://api.newrelic.com/v2/applications/"+applicationID+"/metrics/data.xml");
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("names[]", "HttpDispatcher");
queryParams.add("values[]", "average_call_time");
queryParams.add("values[]", "call_count");
queryParams.add("from", "2015-01-01T00:00:00+00:00");
queryParams.add("to", "2015-04-13T00:00:00+00:00");
queryParams.add("summarize", "true");
response = webResource.queryParams(queryParams)
.accept("application/json","application/xml" )
.header("X-Api-Key", xApiKey)
.get(ClientResponse.class)
;
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
String jsonOutput= convertXmlToJson(output);
return jsonOutput;
}
public String getWebFront() {
try {
webResource = client
.resource("https://api.newrelic.com/v2/applications/"+applicationID+"/metrics/data.xml");
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("names[]", "WebFrontend/QueueTime");
queryParams.add("values[]", "call_count");
queryParams.add("values[]", "average_response_time");
queryParams.add("from", "2015-01-01T00:00:00+00:00");
queryParams.add("to", "2015-04-13T00:00:00+00:00");
queryParams.add("summarize", "true");
response = webResource.queryParams(queryParams)
.accept("application/json","application/xml" )
.header("X-Api-Key", xApiKey)
.get(ClientResponse.class)
;
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
String jsonOutput= convertXmlToJson(output);
return jsonOutput;
}
public static void main(String[] args)
{
ApplicationMetrics am = new ApplicationMetrics();
// am.getApplicationIDs();
// am.getApdexScore();
//am.getAverageThroughputApp();
}
}
| true |
7ff9013521e07c008b6e83d42b616654f2c7f81a | Java | artvinicius/EstruturaDeDados | /src/com/arthur/estruturadados/vetor/teste/curso/Aula12.java | ISO-8859-1 | 1,041 | 3.8125 | 4 | [] | no_license | package com.arthur.estruturadados.vetor.teste.curso;
import java.util.ArrayList;
public class Aula12 {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList();
arrayList.add("A");
arrayList.add("C");
System.out.println(arrayList);
arrayList.add(1, "B");
System.out.println(arrayList);
boolean existe = arrayList.contains("A");
if (existe) {
System.out.println("Elemento existe no Array");
} else {
System.out.println("Elemento no existe no Array");
//Resultado
//[A, C]
//[A, B, C]
//Elemento existe no Array
}
//Mtodo para exibir mais a posio
int pos = arrayList.indexOf("B");
if (pos > -1) {
System.out.println("Elemento existe " + pos);
} else {
System.out.println("Elemento no existe");
}
//Busca por posio
System.out.println(arrayList.get(2));
//Mtodo para remove
arrayList.remove(0);
arrayList.remove("B");
System.out.println(arrayList);
//Tamanho
System.out.println(arrayList.size());
}
}
| true |
7dbe40deace44bba0ff4418e9cfa2473e85608fd | Java | AnuKrithiga/EmployeeAttendance | /getDataFroomDB/src/getDataFroomDB/check.java | UTF-8 | 679 | 2.5 | 2 | [] | no_license | package getDataFroomDB;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class check {
public static boolean verify(String n)
{
boolean status=false;
System.out.println(n);
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3307/employee","root","aaaa");
PreparedStatement ps=con.prepareStatement("select * from empName where name=?");
ps.setString(1,n);
ResultSet rs=ps.executeQuery();
status = rs.next();
System.out.println(status);
}
catch(Exception e){System.out.println(e);}
return status;
}
}
| true |
a718cd9346beab12574ef1a35d7623ca6f3aea2a | Java | coderjia0618/basic-study | /src/main/java/cn/coderjia/netty/action/Client.java | UTF-8 | 1,655 | 2.421875 | 2 | [] | no_license | package cn.coderjia.netty.action;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import java.util.stream.IntStream;
import static cn.coderjia.netty.action.Consts.PORT;
import static cn.coderjia.netty.action.Consts.SERVER_IP;
/**
* @Author CoderJiA
* @Description Client
* @Date 14/6/2019 7:38 AM
**/
public class Client {
public static void main(String[] args) {
new Client().start();
}
private void start(){
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
final Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_REUSEADDR, true)
.handler(new ChannelInitializer<SocketChannel>(){
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new FixedLengthFrameDecoder(Long.BYTES));
ch.pipeline().addLast(ClientBusinessHandler.INSTANCE);
}
});
IntStream.range(0, 1000).forEach(i -> {
try {
bootstrap.connect(SERVER_IP, PORT).get();
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
| true |
ee5deb50b70c4821a64ed62165140c6cd2e82464 | Java | netty/netty | /transport/src/main/java/io/netty/channel/socket/nio/NioDatagramChannel.java | UTF-8 | 22,122 | 1.6875 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"CC-PDDC",
"BSD-3-Clause",
"APSL-2.0",
"MIT"
] | permissive | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://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.netty.channel.socket.nio;
import io.netty.buffer.ByteBuf;
import io.netty.channel.AddressedEnvelope;
import io.netty.channel.Channel;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelMetadata;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelOutboundBuffer;
import io.netty.channel.ChannelPromise;
import io.netty.channel.DefaultAddressedEnvelope;
import io.netty.channel.RecvByteBufAllocator;
import io.netty.channel.nio.AbstractNioMessageChannel;
import io.netty.channel.socket.DatagramChannelConfig;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.InternetProtocolFamily;
import io.netty.util.UncheckedBooleanSupplier;
import io.netty.util.internal.ObjectUtil;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.SuppressJava6Requirement;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.MembershipKey;
import java.nio.channels.SelectionKey;
import java.nio.channels.UnresolvedAddressException;
import java.nio.channels.spi.SelectorProvider;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* An NIO datagram {@link Channel} that sends and receives an
* {@link AddressedEnvelope AddressedEnvelope<ByteBuf, SocketAddress>}.
*
* @see AddressedEnvelope
* @see DatagramPacket
*/
public final class NioDatagramChannel
extends AbstractNioMessageChannel implements io.netty.channel.socket.DatagramChannel {
private static final ChannelMetadata METADATA = new ChannelMetadata(true);
private static final SelectorProvider DEFAULT_SELECTOR_PROVIDER = SelectorProvider.provider();
private static final String EXPECTED_TYPES =
" (expected: " + StringUtil.simpleClassName(DatagramPacket.class) + ", " +
StringUtil.simpleClassName(AddressedEnvelope.class) + '<' +
StringUtil.simpleClassName(ByteBuf.class) + ", " +
StringUtil.simpleClassName(SocketAddress.class) + ">, " +
StringUtil.simpleClassName(ByteBuf.class) + ')';
private final DatagramChannelConfig config;
private Map<InetAddress, List<MembershipKey>> memberships;
private static DatagramChannel newSocket(SelectorProvider provider) {
try {
/**
* Use the {@link SelectorProvider} to open {@link SocketChannel} and so remove condition in
* {@link SelectorProvider#provider()} which is called by each DatagramChannel.open() otherwise.
*
* See <a href="https://github.com/netty/netty/issues/2308">#2308</a>.
*/
return provider.openDatagramChannel();
} catch (IOException e) {
throw new ChannelException("Failed to open a socket.", e);
}
}
@SuppressJava6Requirement(reason = "Usage guarded by java version check")
private static DatagramChannel newSocket(SelectorProvider provider, InternetProtocolFamily ipFamily) {
if (ipFamily == null) {
return newSocket(provider);
}
checkJavaVersion();
try {
return provider.openDatagramChannel(ProtocolFamilyConverter.convert(ipFamily));
} catch (IOException e) {
throw new ChannelException("Failed to open a socket.", e);
}
}
private static void checkJavaVersion() {
if (PlatformDependent.javaVersion() < 7) {
throw new UnsupportedOperationException("Only supported on java 7+.");
}
}
/**
* Create a new instance which will use the Operation Systems default {@link InternetProtocolFamily}.
*/
public NioDatagramChannel() {
this(newSocket(DEFAULT_SELECTOR_PROVIDER));
}
/**
* Create a new instance using the given {@link SelectorProvider}
* which will use the Operation Systems default {@link InternetProtocolFamily}.
*/
public NioDatagramChannel(SelectorProvider provider) {
this(newSocket(provider));
}
/**
* Create a new instance using the given {@link InternetProtocolFamily}. If {@code null} is used it will depend
* on the Operation Systems default which will be chosen.
*/
public NioDatagramChannel(InternetProtocolFamily ipFamily) {
this(newSocket(DEFAULT_SELECTOR_PROVIDER, ipFamily));
}
/**
* Create a new instance using the given {@link SelectorProvider} and {@link InternetProtocolFamily}.
* If {@link InternetProtocolFamily} is {@code null} it will depend on the Operation Systems default
* which will be chosen.
*/
public NioDatagramChannel(SelectorProvider provider, InternetProtocolFamily ipFamily) {
this(newSocket(provider, ipFamily));
}
/**
* Create a new instance from the given {@link DatagramChannel}.
*/
public NioDatagramChannel(DatagramChannel socket) {
super(null, socket, SelectionKey.OP_READ);
config = new NioDatagramChannelConfig(this, socket);
}
@Override
public ChannelMetadata metadata() {
return METADATA;
}
@Override
public DatagramChannelConfig config() {
return config;
}
@Override
@SuppressWarnings("deprecation")
public boolean isActive() {
DatagramChannel ch = javaChannel();
return ch.isOpen() && (
config.getOption(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION) && isRegistered()
|| ch.socket().isBound());
}
@Override
public boolean isConnected() {
return javaChannel().isConnected();
}
@Override
protected DatagramChannel javaChannel() {
return (DatagramChannel) super.javaChannel();
}
@Override
protected SocketAddress localAddress0() {
return javaChannel().socket().getLocalSocketAddress();
}
@Override
protected SocketAddress remoteAddress0() {
return javaChannel().socket().getRemoteSocketAddress();
}
@Override
protected void doBind(SocketAddress localAddress) throws Exception {
doBind0(localAddress);
}
private void doBind0(SocketAddress localAddress) throws Exception {
if (PlatformDependent.javaVersion() >= 7) {
SocketUtils.bind(javaChannel(), localAddress);
} else {
javaChannel().socket().bind(localAddress);
}
}
@Override
protected boolean doConnect(SocketAddress remoteAddress,
SocketAddress localAddress) throws Exception {
if (localAddress != null) {
doBind0(localAddress);
}
boolean success = false;
try {
javaChannel().connect(remoteAddress);
success = true;
return true;
} finally {
if (!success) {
doClose();
}
}
}
@Override
protected void doFinishConnect() throws Exception {
throw new Error();
}
@Override
protected void doDisconnect() throws Exception {
javaChannel().disconnect();
}
@Override
protected void doClose() throws Exception {
javaChannel().close();
}
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
DatagramChannel ch = javaChannel();
DatagramChannelConfig config = config();
RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle();
ByteBuf data = allocHandle.allocate(config.getAllocator());
allocHandle.attemptedBytesRead(data.writableBytes());
boolean free = true;
try {
ByteBuffer nioData = data.internalNioBuffer(data.writerIndex(), data.writableBytes());
int pos = nioData.position();
InetSocketAddress remoteAddress = (InetSocketAddress) ch.receive(nioData);
if (remoteAddress == null) {
return 0;
}
allocHandle.lastBytesRead(nioData.position() - pos);
buf.add(new DatagramPacket(data.writerIndex(data.writerIndex() + allocHandle.lastBytesRead()),
localAddress(), remoteAddress));
free = false;
return 1;
} catch (Throwable cause) {
PlatformDependent.throwException(cause);
return -1;
} finally {
if (free) {
data.release();
}
}
}
@Override
protected boolean doWriteMessage(Object msg, ChannelOutboundBuffer in) throws Exception {
final SocketAddress remoteAddress;
final ByteBuf data;
if (msg instanceof AddressedEnvelope) {
@SuppressWarnings("unchecked")
AddressedEnvelope<ByteBuf, SocketAddress> envelope = (AddressedEnvelope<ByteBuf, SocketAddress>) msg;
remoteAddress = envelope.recipient();
data = envelope.content();
} else {
data = (ByteBuf) msg;
remoteAddress = null;
}
final int dataLen = data.readableBytes();
if (dataLen == 0) {
return true;
}
final ByteBuffer nioData = data.nioBufferCount() == 1 ? data.internalNioBuffer(data.readerIndex(), dataLen)
: data.nioBuffer(data.readerIndex(), dataLen);
final int writtenBytes;
if (remoteAddress != null) {
writtenBytes = javaChannel().send(nioData, remoteAddress);
} else {
writtenBytes = javaChannel().write(nioData);
}
return writtenBytes > 0;
}
private static void checkUnresolved(AddressedEnvelope<?, ?> envelope) {
if (envelope.recipient() instanceof InetSocketAddress
&& (((InetSocketAddress) envelope.recipient()).isUnresolved())) {
throw new UnresolvedAddressException();
}
}
@Override
protected Object filterOutboundMessage(Object msg) {
if (msg instanceof DatagramPacket) {
DatagramPacket p = (DatagramPacket) msg;
checkUnresolved(p);
ByteBuf content = p.content();
if (isSingleDirectBuffer(content)) {
return p;
}
return new DatagramPacket(newDirectBuffer(p, content), p.recipient());
}
if (msg instanceof ByteBuf) {
ByteBuf buf = (ByteBuf) msg;
if (isSingleDirectBuffer(buf)) {
return buf;
}
return newDirectBuffer(buf);
}
if (msg instanceof AddressedEnvelope) {
@SuppressWarnings("unchecked")
AddressedEnvelope<Object, SocketAddress> e = (AddressedEnvelope<Object, SocketAddress>) msg;
checkUnresolved(e);
if (e.content() instanceof ByteBuf) {
ByteBuf content = (ByteBuf) e.content();
if (isSingleDirectBuffer(content)) {
return e;
}
return new DefaultAddressedEnvelope<ByteBuf, SocketAddress>(newDirectBuffer(e, content), e.recipient());
}
}
throw new UnsupportedOperationException(
"unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES);
}
/**
* Checks if the specified buffer is a direct buffer and is composed of a single NIO buffer.
* (We check this because otherwise we need to make it a non-composite buffer.)
*/
private static boolean isSingleDirectBuffer(ByteBuf buf) {
return buf.isDirect() && buf.nioBufferCount() == 1;
}
@Override
protected boolean continueOnWriteError() {
// Continue on write error as a DatagramChannel can write to multiple remote peers
//
// See https://github.com/netty/netty/issues/2665
return true;
}
@Override
public InetSocketAddress localAddress() {
return (InetSocketAddress) super.localAddress();
}
@Override
public InetSocketAddress remoteAddress() {
return (InetSocketAddress) super.remoteAddress();
}
@Override
public ChannelFuture joinGroup(InetAddress multicastAddress) {
return joinGroup(multicastAddress, newPromise());
}
@Override
public ChannelFuture joinGroup(InetAddress multicastAddress, ChannelPromise promise) {
try {
NetworkInterface iface = config.getNetworkInterface();
if (iface == null) {
iface = NetworkInterface.getByInetAddress(localAddress().getAddress());
}
return joinGroup(
multicastAddress, iface, null, promise);
} catch (SocketException e) {
promise.setFailure(e);
}
return promise;
}
@Override
public ChannelFuture joinGroup(
InetSocketAddress multicastAddress, NetworkInterface networkInterface) {
return joinGroup(multicastAddress, networkInterface, newPromise());
}
@Override
public ChannelFuture joinGroup(
InetSocketAddress multicastAddress, NetworkInterface networkInterface,
ChannelPromise promise) {
return joinGroup(multicastAddress.getAddress(), networkInterface, null, promise);
}
@Override
public ChannelFuture joinGroup(
InetAddress multicastAddress, NetworkInterface networkInterface, InetAddress source) {
return joinGroup(multicastAddress, networkInterface, source, newPromise());
}
@SuppressJava6Requirement(reason = "Usage guarded by java version check")
@Override
public ChannelFuture joinGroup(
InetAddress multicastAddress, NetworkInterface networkInterface,
InetAddress source, ChannelPromise promise) {
checkJavaVersion();
ObjectUtil.checkNotNull(multicastAddress, "multicastAddress");
ObjectUtil.checkNotNull(networkInterface, "networkInterface");
try {
MembershipKey key;
if (source == null) {
key = javaChannel().join(multicastAddress, networkInterface);
} else {
key = javaChannel().join(multicastAddress, networkInterface, source);
}
synchronized (this) {
List<MembershipKey> keys = null;
if (memberships == null) {
memberships = new HashMap<InetAddress, List<MembershipKey>>();
} else {
keys = memberships.get(multicastAddress);
}
if (keys == null) {
keys = new ArrayList<MembershipKey>();
memberships.put(multicastAddress, keys);
}
keys.add(key);
}
promise.setSuccess();
} catch (Throwable e) {
promise.setFailure(e);
}
return promise;
}
@Override
public ChannelFuture leaveGroup(InetAddress multicastAddress) {
return leaveGroup(multicastAddress, newPromise());
}
@Override
public ChannelFuture leaveGroup(InetAddress multicastAddress, ChannelPromise promise) {
try {
return leaveGroup(
multicastAddress, NetworkInterface.getByInetAddress(localAddress().getAddress()), null, promise);
} catch (SocketException e) {
promise.setFailure(e);
}
return promise;
}
@Override
public ChannelFuture leaveGroup(
InetSocketAddress multicastAddress, NetworkInterface networkInterface) {
return leaveGroup(multicastAddress, networkInterface, newPromise());
}
@Override
public ChannelFuture leaveGroup(
InetSocketAddress multicastAddress,
NetworkInterface networkInterface, ChannelPromise promise) {
return leaveGroup(multicastAddress.getAddress(), networkInterface, null, promise);
}
@Override
public ChannelFuture leaveGroup(
InetAddress multicastAddress, NetworkInterface networkInterface, InetAddress source) {
return leaveGroup(multicastAddress, networkInterface, source, newPromise());
}
@SuppressJava6Requirement(reason = "Usage guarded by java version check")
@Override
public ChannelFuture leaveGroup(
InetAddress multicastAddress, NetworkInterface networkInterface, InetAddress source,
ChannelPromise promise) {
checkJavaVersion();
ObjectUtil.checkNotNull(multicastAddress, "multicastAddress");
ObjectUtil.checkNotNull(networkInterface, "networkInterface");
synchronized (this) {
if (memberships != null) {
List<MembershipKey> keys = memberships.get(multicastAddress);
if (keys != null) {
Iterator<MembershipKey> keyIt = keys.iterator();
while (keyIt.hasNext()) {
MembershipKey key = keyIt.next();
if (networkInterface.equals(key.networkInterface())) {
if (source == null && key.sourceAddress() == null ||
source != null && source.equals(key.sourceAddress())) {
key.drop();
keyIt.remove();
}
}
}
if (keys.isEmpty()) {
memberships.remove(multicastAddress);
}
}
}
}
promise.setSuccess();
return promise;
}
/**
* Block the given sourceToBlock address for the given multicastAddress on the given networkInterface
*/
@Override
public ChannelFuture block(
InetAddress multicastAddress, NetworkInterface networkInterface,
InetAddress sourceToBlock) {
return block(multicastAddress, networkInterface, sourceToBlock, newPromise());
}
/**
* Block the given sourceToBlock address for the given multicastAddress on the given networkInterface
*/
@SuppressJava6Requirement(reason = "Usage guarded by java version check")
@Override
public ChannelFuture block(
InetAddress multicastAddress, NetworkInterface networkInterface,
InetAddress sourceToBlock, ChannelPromise promise) {
checkJavaVersion();
ObjectUtil.checkNotNull(multicastAddress, "multicastAddress");
ObjectUtil.checkNotNull(sourceToBlock, "sourceToBlock");
ObjectUtil.checkNotNull(networkInterface, "networkInterface");
synchronized (this) {
if (memberships != null) {
List<MembershipKey> keys = memberships.get(multicastAddress);
for (MembershipKey key: keys) {
if (networkInterface.equals(key.networkInterface())) {
try {
key.block(sourceToBlock);
} catch (IOException e) {
promise.setFailure(e);
}
}
}
}
}
promise.setSuccess();
return promise;
}
/**
* Block the given sourceToBlock address for the given multicastAddress
*
*/
@Override
public ChannelFuture block(InetAddress multicastAddress, InetAddress sourceToBlock) {
return block(multicastAddress, sourceToBlock, newPromise());
}
/**
* Block the given sourceToBlock address for the given multicastAddress
*
*/
@Override
public ChannelFuture block(
InetAddress multicastAddress, InetAddress sourceToBlock, ChannelPromise promise) {
try {
return block(
multicastAddress,
NetworkInterface.getByInetAddress(localAddress().getAddress()),
sourceToBlock, promise);
} catch (SocketException e) {
promise.setFailure(e);
}
return promise;
}
@Override
@Deprecated
protected void setReadPending(boolean readPending) {
super.setReadPending(readPending);
}
void clearReadPending0() {
clearReadPending();
}
@Override
protected boolean closeOnReadError(Throwable cause) {
// We do not want to close on SocketException when using DatagramChannel as we usually can continue receiving.
// See https://github.com/netty/netty/issues/5893
if (cause instanceof SocketException) {
return false;
}
return super.closeOnReadError(cause);
}
@Override
protected boolean continueReading(RecvByteBufAllocator.Handle allocHandle) {
if (allocHandle instanceof RecvByteBufAllocator.ExtendedHandle) {
// We use the TRUE_SUPPLIER as it is also ok to read less then what we did try to read (as long
// as we read anything).
return ((RecvByteBufAllocator.ExtendedHandle) allocHandle)
.continueReading(UncheckedBooleanSupplier.TRUE_SUPPLIER);
}
return allocHandle.continueReading();
}
}
| true |
fbb2c2a8b59e2f763beb060b0df24d3a3ff58f3e | Java | dikshya321/Emenu | /emenu/src/main/java/com/ncit/emenu/repository/OrderItemRepo.java | UTF-8 | 433 | 1.9375 | 2 | [] | no_license | package com.ncit.emenu.repository;
import java.util.List;
import com.ncit.emenu.model.Item;
import com.ncit.emenu.model.OrderItem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface OrderItemRepo extends JpaRepository<OrderItem,Integer> {
List<OrderItem> findAllByItem(Item item);
void deleteAllByItem(Item item);
}
| true |
0649fd24f7cdbdaae69c0285d0801ef7d863411f | Java | ncontrerasn/AFD | /AFD/src/CadenaAFD.java | UTF-8 | 2,298 | 3.3125 | 3 | [] | no_license | import java.util.ArrayList;
public class CadenaAFD {
/*
clase que calcula el camino que debe cruzar una cadena de prueba en el AFD.
calcula el tiempo que tarda en procesar la cadena en la variable tiempo.
llena el array orden que guarda las posciones de los estados que tiene que atravesar.
*/
ArrayList<String> estados;
ArrayList<Character> alfabeto;
String[][] matriz;
long tiempo;
ArrayList<Integer> orden = new ArrayList<>();
public CadenaAFD(ArrayList<String> estados, ArrayList<Character> alfabeto, String[][] matriz){
this.estados = estados;
this.alfabeto = alfabeto;
this.matriz = matriz;
}
public String probarAutomata(String prueba) {
orden.add(0);
String res = "";
String estadoFinal = estados.get(estados.size() - 1);
String estadoActual;
int fila, columna;
res += "[ " + estados.get(0);
fila = 0;
char lambda = 955;
long TInicio, TFin; //Variables para determinar el tiempo de ejecución
TInicio = System.currentTimeMillis();
for(int i = 0; i < prueba.length(); i++){
columna = alfabeto.indexOf(prueba.charAt(i));
estadoActual = matriz[fila][columna];
if(estadoActual == null || (i == prueba.length() - 1 && !estadoActual.equals(estadoFinal))){
res += ", " + prueba.substring(i) + " ]";
res += "\n\nNo hay un camino para que la cadena sea aceptada.";
res += "\nLa cadena ingresada no hace parte del lenguaje aceptado por el autómata.";
break;
}
fila = estados.indexOf(estadoActual);
orden.add(estados.indexOf(estadoActual));
res += ", " + prueba.substring(i) + " ] |-- [ " + estadoActual;
if(i == prueba.length() - 1 && estadoActual.equals(estadoFinal)){
res += ", " + lambda + " ]";
res += "\n\nLa cadena ingresada es parte del lenguaje aceptado por el autómata.";
}
}
TFin = System.currentTimeMillis(); //Tomamos la hora en que finalizó el algoritmo y la almacenamos en la variable T
tiempo = 1 + TFin - TInicio; //Calculamos los milisegundos de diferencia
return res;
}
} | true |
4f1864867baae191a03f3926a0592f7e9160225f | Java | visautomates/seleniummavenframework | /src/test/java/utilities/BaseClass.java | UTF-8 | 2,343 | 2.09375 | 2 | [] | no_license | package utilities;
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.io.FileHandler;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
import com.pageFactory.Demobuttons;
public class BaseClass {
public static WebDriver driver;
protected static ExtentReports extentreport;
protected static ExtentTest testcase;
static ExtentSparkReporter htmlreporter ;
static String path = System.getProperty("user.dir") ;
public static void driverintiateWeb() {
ConfigurationReade ConfigurationReade = new ConfigurationReade();
System.setProperty("webdriver.chrome.driver", ConfigurationReade.getdriverpath());
extentreport = new ExtentReports();
htmlreporter = new ExtentSparkReporter(path+"\\target\\"+"ExtentReport.html");
extentreport.attachReporter(htmlreporter);
driver = new ChromeDriver();
driver.manage().window().maximize();
}
public static void Dobleclick() {
Actions action = new Actions(driver);
Demobuttons button = PageFactory.initElements(driver, Demobuttons.class);
// need more look into tis
}
public static void WaituntilDisplay(WebElement Locator) {
WebDriverWait w = new WebDriverWait(driver,5);
w.until(ExpectedConditions.visibilityOf(Locator));
}
public static void takeScreenshot(String Methodname) {
try {
TakesScreenshot screenshot = (TakesScreenshot)driver;
File sourcefile = screenshot.getScreenshotAs(OutputType.FILE);
File destinationfile = new File(path+"\\target\\"+Methodname+".png");
FileHandler.copy(sourcefile, destinationfile);
testcase.addScreenCaptureFromPath(Methodname+".png");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Unable to capture thr screenshot check the issue");
}
}
}
| true |
25141c8764d6007deb8c298772555c485a791f37 | Java | vmj/skew-consumer | /skew-consumer-app/src/main/java/fi/linuxbox/skew/consumer/app/Boot.java | UTF-8 | 1,159 | 2.234375 | 2 | [] | no_license | package fi.linuxbox.skew.consumer.app;
import org.apache.webbeans.config.*;
import org.apache.webbeans.spi.*;
import org.slf4j.*;
/**
*
*/
public class Boot
{
public static void main(final String[] args) throws InterruptedException
{
final ContainerLifecycle containerLifecycle = WebBeansContext.currentInstance()
.getService(ContainerLifecycle.class);
containerLifecycle.startApplication(null);
Runtime.getRuntime().addShutdownHook(new Cleanup(containerLifecycle));
final Object o = new Object();
synchronized (o) { o.wait(); }
}
private static class Cleanup extends Thread {
private final Logger log = LoggerFactory.getLogger(Cleanup.class);
final ContainerLifecycle containerLifecycle;
public Cleanup(final ContainerLifecycle containerLifecycle)
{
this.containerLifecycle = containerLifecycle;
}
@Override
public void run()
{
log.debug("stopping application");
containerLifecycle.stopApplication(null);
}
}
}
| true |
44f3ec51c9f10abcdc93084e396fef52ee380059 | Java | guilherme-dev/tap-trabalho-ru | /src/model/entity/Ingredient.java | UTF-8 | 1,095 | 2.953125 | 3 | [] | no_license | /**
*
*/
package model.entity;
import java.io.Serializable;
import model.dao.*;
/**
* @author ana araujo, guilherme santos
*
*/
public class Ingredient implements Serializable {
private String name;
private int calories;
private int quantity;
public Ingredient() {
this.name = "";
this.calories = 0;
this.quantity = 0;
}
public Ingredient(String name, int calories, int quantity) {
this.name = name;
this.calories = calories;
this.quantity = quantity;
}
@Override
public String toString() {
return name + " - " + calories + " calorias, " + quantity + " gramas em estoque.";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCalories() {
return calories;
}
public void setCalories(int calories) {
this.calories = calories;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public void save() {
Dao.save("ingredient", this);
}
public static Ingredient load(){
return (Ingredient) Dao.load("ingredient");
}
}
| true |
1dabe9624bc2f6d12a92b59354fad94b539df553 | Java | trebaud/FunkBaz | /src/baz/TreeVisualizer.java | UTF-8 | 1,485 | 3.046875 | 3 | [] | no_license |
package baz;
import java.util.*;
import baz.syntax.analysis.*;
import baz.syntax.node.*;
public class TreeVisualizer
extends DepthFirstAdapter {
private HashMap<Node, Integer> ids = new HashMap<Node, Integer>();
int nextID = 1;
@Override
public void inStart(
Start node) {
System.out.println("graph G {");
defaultIn(node);
}
@Override
public void outStart(
Start node) {
defaultOut(node);
System.out.println("}");
}
@Override
public void defaultIn(
Node node) {
int id = this.nextID++;
this.ids.put(node, id);
System.out.println(" " + id + " [label=\""
+ node.getClass().getSimpleName() + "\"];");
Node parent = node.parent();
if (parent != null) {
System.out.println(" " + this.ids.get(parent) + " -- " + id + ";");
}
}
@Override
public void defaultCase(
Node node) {
if (node instanceof Token) {
Token token = (Token) node;
int id = this.nextID++;
this.ids.put(token, id);
System.out.println(" " + id + " [label=\""
+ token.getClass().getSimpleName() + ": "
+ token.getText().replaceAll("\"", "\\\\\"") + "\"];");
Node parent = node.parent();
System.out.println(" " + this.ids.get(parent) + " -- " + id + ";");
}
}
}
| true |
de1d601d6e9fad9b13c046a89dafa88504327bda | Java | swings134man/java_project | /day12/src/배열/이차원배열2.java | UTF-8 | 719 | 3.703125 | 4 | [] | no_license | package 배열;
public class 이차원배열2 {
public static void main(String[] args) {
int[] arr1 = new int[3];
int[] arr2 = new int[5];
int[] arr3 = new int[4];
int[][] arrList = new int[3][]; //정방형이 아니라 열을 지정해줄수 없음.
arrList[0] = arr1 ; //열의 갯수가 다르다면 1차원으로 만들어서 대입.
arrList[1] = arr2 ;
arrList[2] = arr3 ;
// 0 1 2 3 4
//0 0 0 0
//1 0 0 0 0 0
//2 0 0 0 0
// arrList[1][1] = 1;
// arrList[1][3] = 1;
// arrList[2][4] = 1;
System.out.println(arrList.length);
System.out.println(arrList[0].length);
System.out.println(arrList[1].length);
System.out.println(arrList[2].length);
}
}
| true |
a056e3fa2cc94a3e72d482a0c8505e93f90ae47e | Java | hartmga/java-exercises | /src/main/java/com/hcl/accounts2/SavingsAccount.java | UTF-8 | 1,303 | 3.015625 | 3 | [
"Apache-2.0"
] | permissive | package com.hcl.accounts2;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter(AccessLevel.PROTECTED)
public class SavingsAccount extends BankAccount {
public static final Logger logger = LogManager.getLogger(SavingsAccount.class);
private double annualInterestRate;
public SavingsAccount(String owner, double balance, double annualInterestRate) {
super(owner, balance);
setAnnualInterestRate(annualInterestRate);
}
@Override
public int withdrawal(double amount) {
if (amount >= 0) {
setBalance(getBalance() - amount);
logger.trace("Withdrew ${} from account #{}, new balance is {}", amount, this.getAccountNo());
return SUCCESS;
} else {
logger.debug("Invalid withdrawal amount ${} in account #{}", amount, this.getAccountNo());
return INVALID_AMOUNT;
}
}
public void depositMonthlyInterest() {
// this assumes the annual rate is nominal and does not account for compounding
setBalance(getBalance() * (1 + getAnnualInterestRate() / 12));
logger.info("Deposited monthly interest for account #{}", getAccountNo());
}
@Override
public String toString() {
return super.toString() + ", annualInterestRate=" + annualInterestRate;
}
}
| true |
c7bc1a182730ac226c98dcf773993cb2fd2518e4 | Java | alexace013/test_items | /tasks/src/hw2/university/Student.java | UTF-8 | 1,547 | 3.9375 | 4 | [] | no_license | package hw2.university;
/**
* Студент
поля:
Имя
Адрес
Предметы
методы:
учиться
добавить предмет
удалить предмет из списка последний
показать всю информацию о предметах
получить средний бал за все предметы
*/
public class Student {
private String name;
private String address;
private Subject[] subjects;
private int index;
public Student() {
subjects = new Subject[0];
}
public Student(String name, String address, int sizeSubjects) {
this.name = name;
this.address = address;
subjects = new Subject[sizeSubjects];
}
public void learn(int hours, int subIdx) {
Subject tempSubject = subjects[subIdx];
tempSubject.addHours(hours);
}
public void addSubject(Subject subject) {
subjects[index] = subject;
index++;
}
public void removeLastSubject() {
subjects[index] = null;
index--;
}
public String getSubjectsInfo() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < index; i++) {
builder.append(subjects[i].getSubjectInfo() + "\n");
}
return builder.toString();
}
public double getAverageSubjects() {
double result = 0;
for (Subject subject : subjects) {
result += subject.getRank();
}
return result / subjects.length;
}
}
| true |
4a27f1d5830ead0cedbbb1d56c5aa34d012bc9b1 | Java | ernestpascual/progap3 | /PostMidtermActivity/src/LoginCategoryServlet.java | UTF-8 | 1,318 | 2.296875 | 2 | [] | no_license |
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginCategoryServlet
*/
@WebServlet("/login.action")
public class LoginCategoryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public LoginCategoryServlet() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user = request.getParameter("user");
String pass = request.getParameter("pass");
if (user.equals("ernest") && pass.equals("euge")) {
response.sendRedirect("validateUser.jsp");
} else {
response.sendRedirect("errorLogin.jsp");
}
}
}
| true |
e354c2de62f79eb53d67cb1ac71a818f792c1460 | Java | Dxita/Booze | /app/src/main/java/com/sky21/liquor_app/Login/LoginActivity.java | UTF-8 | 5,181 | 1.992188 | 2 | [] | no_license | package com.sky21.liquor_app.Login;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.sky21.liquor_app.Home.MainActivity;
import com.sky21.liquor_app.Home.ProductsActivity;
import com.sky21.liquor_app.R;
import com.sky21.liquor_app.SharedHelper;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class LoginActivity extends AppCompatActivity {
Button signin;
ImageView backspace;
EditText phone, password;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
phone = findViewById(R.id.mobile);
password = findViewById(R.id.password);
progressBar = findViewById(R.id.progressbar);
signin = findViewById(R.id.signin);
backspace = findViewById(R.id.backspace);
phone.setText("8290638499");
password.setText("1234567");
backspace.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
signin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String m = phone.getText().toString();
String p = password.getText().toString();
if (m.isEmpty()) {
phone.requestFocus();
phone.setError("Enter Mobile number");
} else if (p.isEmpty()) {
password.requestFocus();
password.setError("Enter password");
} else {
api();
}
}
});
}
private void api() {
progressBar.setVisibility(View.VISIBLE);
RequestQueue requestQueue = Volley.newRequestQueue(this);
String url = "https://boozeapp.co/Booze-App-Api/api/login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("res", response);
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("success").equalsIgnoreCase("true")) {
SharedHelper.putKey(LoginActivity.this, "loggedin", "true");
JSONObject object = jsonObject.getJSONObject("data");
String token;
token = object.getString("token");
Intent signup = new Intent(getApplicationContext(), MainActivity.class);
startActivity(signup);
Toast.makeText(LoginActivity.this, "Welcome back!", Toast.LENGTH_SHORT).show();
String phonenumber = phone.getText().toString();
SharedHelper.putKey(LoginActivity.this, "number", phonenumber);
SharedHelper.putKey(LoginActivity.this, "token", token);
} else {
Toast.makeText(LoginActivity.this, "We cant find an account with this credentials.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("mobile_no", phone.getText().toString());
map.put("password", password.getText().toString());
return map;
}
};
requestQueue.add(stringRequest);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
}
| true |
9630affd40dd897f7fd641ca62cad899ad010199 | Java | kuanglongwokong/UserManagementSystem | /src/main/java/com/qubo/learning/rest/controller/BBSController.java | UTF-8 | 5,341 | 2.171875 | 2 | [] | no_license | package com.qubo.learning.rest.controller;
import com.qubo.learning.common.model.SysPost;
import com.qubo.learning.common.model.SysReply;
import com.qubo.learning.common.model.SysUser;
import com.qubo.learning.common.service.PostDao;
import com.qubo.learning.common.service.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.sql.Timestamp;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Qubo_Song on 3/14/14.
*/
@Controller
@RequestMapping(value = "/bbs")
public class BBSController {
/* the number of posts to display on each page should
* be configurable in a per-session manner, here we just
* set it temporarily for convenience.
*/
final int MAX_POSTS_PER_PAGE = 10;
@Autowired
private UserDao userDao;
@Autowired
private PostDao postDao;
@ModelAttribute("numOnline")
int getOnlineUserCount() {
return userDao.getOnlineUserCount();
}
@RequestMapping(value = "", method = RequestMethod.GET)
public String getBBSMainPage(Model model) {
model.asMap().clear();
return "redirect:bbs/page/1";
}
@RequestMapping(value = "/page/{page}", method = RequestMethod.GET)
public String getBBSPage(@PathVariable int page, Model model) {
int postsCount = postDao.getTotalPostsCount();
int totalPage = (int) Math.ceil((double) postsCount / MAX_POSTS_PER_PAGE);
if(page < 1) {
model.asMap().clear();
return "redirect:1";
} else if(page > totalPage) {
model.asMap().clear();
return "redirect:" + totalPage;
}
model.addAttribute("totalPage", totalPage);
model.addAttribute("currentPage", page);
model.addAttribute("posts",
postDao.getAllPosts().subList(
(page - 1) * MAX_POSTS_PER_PAGE,
(page * MAX_POSTS_PER_PAGE > postsCount) ? postsCount : (page * MAX_POSTS_PER_PAGE)));
return "bbs";
}
@RequestMapping(value = "/post/{postId}", method = RequestMethod.GET)
public String getPost(@PathVariable int postId, Model model) {
int currentPage = (int) Math.ceil((double) postId / MAX_POSTS_PER_PAGE);
SysPost post = postDao.getPostById(postId);
if(post == null) {
model.asMap().clear();
return "redirect:../page/1";
}
model.addAttribute("currentPage", currentPage);
model.addAttribute("post", post);
model.addAttribute("replies", postDao.getAllRepliesByPostId(postId));
return "post";
}
@RequestMapping(value = "/new", method = RequestMethod.GET)
public String getNewPostForm(Model model) {
model.addAttribute("newPostForm", new SysPost());
return "post_new";
}
@RequestMapping(value = "/new", method = RequestMethod.POST)
public String postNewPostForm(@ModelAttribute("newPostForm") @Valid SysPost newPostForm, BindingResult result, Model model) {
int postsCount;
int totalPage;
Timestamp timeStamp;
User user;
if(result.hasErrors()) {
return "post_new";
}
timeStamp = new Timestamp(new Date().getTime());
user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
postDao.newPost(newPostForm.getPost_title(), newPostForm.getPost_content(), userDao.getUserByName(user.getUsername()).getUser_id(), timeStamp);
postsCount = postDao.getTotalPostsCount();
totalPage = (int) Math.ceil((double) postsCount / MAX_POSTS_PER_PAGE);
model.asMap().remove("numOnline");
return "redirect:page/" + totalPage;
}
@RequestMapping(value = "/post/reply/{postId}", method = RequestMethod.GET)
public String getReplyForm(@PathVariable int postId, Model model) {
SysPost post = postDao.getPostById(postId);
if(post == null) {
model.asMap().clear();
return "redirect:../../page/1";
}
SysReply newReplyForm = new SysReply();
newReplyForm.setPost(post);
model.addAttribute("newReplyForm", newReplyForm);
return "post_reply";
}
@RequestMapping(value = "/post/reply/{postId}", method = RequestMethod.POST)
public String postReplyForm(@ModelAttribute("newReplyForm") @Valid SysReply newReplyForm, BindingResult result, @PathVariable int postId, Model model) {
Timestamp timeStamp;
User user;
if(result.hasErrors()) {
return "post_reply";
}
timeStamp = new Timestamp(new Date().getTime());
user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
postDao.newReply(postId, newReplyForm.getReply_content(), userDao.getUserByName(user.getUsername()).getUser_id(), timeStamp);
model.asMap().remove("numOnline");
return "redirect:../" + postId;
}
}
| true |